Public: anyone can read this; the crew can change it.

The cloud tree's filter line is read by one language that every list can share #17735

opened this

Merged 18h 12m ago, live in production

sold/leaf-table-1 → main 0 commits

  • Merged. sold/leaf-table-1 was merged into main as 3a50184.

Review

Sign in to review this change.
9 files changed +482 −130
docs/features/infra.md +3 −1
@@ -102,7 +102,9 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
102102
103103 - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. One resource says "About $12.00 a month at list price", or "No list price is known for it" and which bill any cost is inside, with no region's total beside it. An ECS service says "Its tasks, about $9.02 a month at list price", and only the tasks are added. A bill's Tax line says it is included in the AWS total. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added.
104104 - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`.
105 - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost. `!` negates, a comma means any of, `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. It is in the URL as `?q=`.
105 - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost, created. `!` negates a term or a word (`!web`), a comma means any of, and the sign carries on over it (`cost:>10,20`) until a value has its own (`cost:>10,=20`). `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. Quotes are literal: `name:"old web"` holds a space, and `region:"none"` is the word and not the empty value. `created:` takes an age (`<7d` is younger, `>7d` older, `s m h d w`) or a date (`>2026-12-01` is after that day, UTC unless it has an offset). `machine:i-111` is an id, read as text. It is in the URL as `?q=`.
106 - **A line that cannot be read whole** still draws rows, and the page and the terminal say what was made of it. An unknown property is text and the near one is named; a sign on a property without an order is left out; `sort:` and `group:` are words this list cannot do yet. A bad `cost:` or `created:`, and what is past 12 words or 200 characters, narrow nothing. The `infra` tool names the first sort in `problems` and refuses the second (`invalid_filter`, with the place). The language is `src/list/line.ts`, for every list to share.
107 - **Changed with the shared language:** `!web` and `!machine:i-111` negate and a leading `"` quotes (both were part of the word); `sort:`, `group:` and `created:` were text; `cost:=10`, `cost:>10,=20` and `cost:>10,<5` were refused; a sign left out and a long line's rest are now said; over MCP `cost:abc` and `cost:none` listed everything and are refused. `test/cloud-filter-lines.test.ts` holds each, and every line that kept its rows.
106108 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was read, and Ask about this (a talk with those facts, fenced as data).
107109 - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. "not known" is said of a limit (the agent does not send one), of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker.
108110 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
src/cloud/tree.ts +56 −98
@@ -15,6 +15,7 @@ import { dollars } from "./prices.ts";
1515 import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts";
1616 import { agoWords } from "../kernel/ago.ts";
1717 import { LABEL, isProvider } from "./providers.ts";
18 import { holds, parseLine, wordsOf, type Line, type List } from "../list/line.ts";
1819
1920 /** What some resources cost a month, and how much of that is known. */
2021 export interface Money {
@@ -286,7 +287,7 @@ const kindsOf = (unread: AccountRead["unread"]): number => new Set(listGaps(unre
286287 * was never read shows as that and not as nothing; with one, only branches that hold a match.
287288 */
288289 export function cloudTree(projects: readonly ProjectView[], reads: readonly AccountRead[], held: readonly HeldAccount[], q: CloudQuery, now: number, containers: ReadonlyMap<string, readonly Container[]> = new Map()): CloudNode {
289 const filtering = q.terms.length > 0 || q.words.length > 0;
290 const filtering = q.line.terms.length > 0;
290291 const own = groupBy(projects, (p) => `${p.provider}/${p.account}`);
291292 const all = new Map<string, readonly [string, string]>([...projects.map((p) => [p.provider, p.account] as const), ...held.map((h) => [h.provider, h.name] as const)].map((a) => [a.join("/"), a]));
292293 const accounts = [...all].map(([key, [provider, account]]): CloudNode => {
@@ -297,7 +298,7 @@ export function cloudTree(projects: readonly ProjectView[], reads: readonly Acco
297298 const kids = kept.map((p): CloudNode => {
298299 const path = [provider, account, p.id];
299300 const things = p.resources
300 .filter((r) => matches(q, r, p.name))
301 .filter((r) => holds(LIST, q.line, { r, project: p.name }, now))
301302 .map((r): CloudNode => {
302303 const tasks = tasksOf(r, p.resources);
303304 const at = [...path, r.id];
@@ -387,110 +388,65 @@ export const cutSays = (shown: number, more: number, how: string): string => (mo
387388
388389 // ---- the filter line ----
389390
390 /** What a filter may name, and what each reads of a resource. */
391 const PROPS = {
392 kind: (r) => r.kind,
393 cloud: (r) => r.provider,
394 account: (r) => r.account,
395 project: (r, project) => `${project} ${r.project}`,
396 region: (r) => r.region,
397 size: (r) => r.size,
398 name: (r) => r.name || idOf(r),
399 state: (r) => r.state,
400 // A snapshot attaches to nothing: no image on it does not make it waste, it may be the only
401 // backup.
402 attached: (r) => (r.attachedTo === null || r.kind === "snapshot" ? "unknown" : r.attachedTo.length === 0 ? "no" : "yes"),
403 made: (r) => r.madeBy,
404 for: (r) => r.label,
405 app: (r) => r.partOf?.app ?? "",
406 } as const satisfies Record<string, (r: CloudResource, project: string) => string>;
391 /** A resource and its project's name, which the resource does not hold. */
392 interface Placed {
393 readonly r: CloudResource;
394 readonly project: string;
395 }
407396
408 type Prop = keyof typeof PROPS;
397 /**
398 * A snapshot attaches to nothing: no image on it does not make it waste, it may be the only backup.
399 */
400 const attachedWord = (r: CloudResource): string => (r.attachedTo === null || r.kind === "snapshot" ? "unknown" : r.attachedTo.length === 0 ? "no" : "yes");
401
402 /**
403 * What a filter may name, and what each reads of a resource. No field has the name of an id's
404 * prefix (`machine`), so a pasted id stays text.
405 */
406 const LIST: List<Placed> = {
407 text: ({ r, project }) => [r.id, r.name, r.kind, r.provider, r.account, project, r.region, r.size, r.label, r.state, r.partOf?.app ?? ""].join("\n"),
408 fields: [
409 { name: "kind", type: "word", of: ({ r }) => r.kind },
410 { name: "cloud", type: "word", of: ({ r }) => r.provider },
411 { name: "account", type: "text", of: ({ r }) => r.account, blank: "none" },
412 { name: "project", type: "text", of: ({ r, project }) => `${project} ${r.project}`, blank: "none" },
413 { name: "region", type: "text", of: ({ r }) => r.region, blank: "none" },
414 { name: "size", type: "text", of: ({ r }) => r.size, blank: "none" },
415 { name: "name", type: "text", of: ({ r }) => r.name || idOf(r), blank: "none" },
416 { name: "state", type: "start", of: ({ r }) => r.state, blank: "none" },
417 { name: "attached", type: "word", of: ({ r }) => attachedWord(r) },
418 { name: "made", type: "word", of: ({ r }) => r.madeBy },
419 { name: "for", type: "text", of: ({ r }) => r.label, blank: "none" },
420 { name: "app", type: "text", of: ({ r }) => r.partOf?.app ?? "", blank: "unknown" },
421 { name: "cost", type: "number", of: ({ r }) => r.cents, blank: "unknown", takes: "dollars a month, like cost:>10" },
422 { name: "created", type: "time", of: ({ r }) => r.createdAt, blank: "unknown", takes: "an age or a date, like created:<7d or created:>2026-12-01" },
423 ],
424 };
409425
410426 /** The properties a filter line takes, as every door lists them. */
411 export const CLOUD_PROPS: readonly string[] = [...Object.keys(PROPS), "cost"];
412
413 /** These are one word of a short list, so a value is the whole of it; the rest match a part. */
414 const EXACT: ReadonlySet<string> = new Set(["kind", "cloud", "made", "attached"]);
415
416 export interface CloudTerm {
417 readonly field: string;
418 readonly negate: boolean;
419 readonly op: string;
420 readonly values: readonly string[];
421 }
427 export const CLOUD_PROPS: readonly string[] = LIST.fields.map((f) => f.name);
422428
423429 export interface CloudQuery {
424430 /** The line as typed, bounded. */
425431 readonly text: string;
426 readonly terms: readonly CloudTerm[];
427 /** Free text: each word is somewhere in the resource. */
428 readonly words: readonly string[];
429 /** What the line asks that no property answers, in a sentence each. */
432 readonly line: Line;
433 /** What is wrong with the line, a sentence each: not what is half typed, nor a pasted id. */
430434 readonly problems: readonly string[];
431435 }
432436
433 const MAX_TEXT = 200;
434 const MAX_WORDS = 12;
437 /** A filter line for the cloud tree, in the language every list shares (`list/line.ts`). */
438 export function parseCloudQuery(typed: string): CloudQuery {
439 const line = parseLine(typed, LIST.fields, { chars: 200, words: 12 });
440 return { text: line.text, line, problems: line.problems.filter((p) => p.level === "slip" || p.level === "wide").map((p) => p.says) };
441 }
435442
436443 /**
437 * A filter line: `kind:volume cloud:aws cost:>10 web`, every part of which must hold. The grammar
438 * is the fleet's (`fleet/selection.ts`): `!` negates (before the property too), a comma means any
439 * of, `cost` compares. Nothing is refused: a property that is not one is said, and read as text.
444 * What every door says beside the rows: the line's problems, how its marks, quotes and dates were
445 * read, and, with nothing found, what is half typed in it.
440446 */
441 export function parseCloudQuery(line: string): CloudQuery {
442 // Cut inside an emoji, half of it is left, and no link can encode that.
443 const text = line.trim().slice(0, MAX_TEXT).toWellFormed();
444 const terms: CloudTerm[] = [];
445 const words: string[] = [];
446 const problems: string[] = [];
447 for (const word of text.split(/\s+/).filter((w) => w !== "").slice(0, MAX_WORDS)) {
448 const m = /^([!-]?)([a-z]+):(!?)([<>]=?)?(.*)$/i.exec(word);
449 const field = m?.[2]!.toLowerCase() ?? "";
450 const value = m?.[5]!.toLowerCase() ?? "";
451 if (m === null || (value === "" && !CLOUD_PROPS.includes(field))) {
452 words.push(word.toLowerCase());
453 continue;
454 }
455 // Half typed: `kind:` narrows nothing yet.
456 if (value === "") continue;
457 if (!CLOUD_PROPS.includes(field)) {
458 // A provider's id may hold a colon (`machine:i-111`): text, and only a plain word is a slip.
459 words.push(word.toLowerCase());
460 if (!/\d/.test(value)) problems.push(`"${field}" is not a property: use ${CLOUD_PROPS.join(", ")}.`);
461 continue;
462 }
463 const values = value.split(",").filter((v) => v !== "");
464 if (field === "cost" && !values.every((v) => v === "unknown" || /^\$?\d+(\.\d+)?$/.test(v))) {
465 problems.push("cost takes dollars a month, like cost:>10, or cost:unknown.");
466 continue;
467 }
468 terms.push({ field, negate: (m[1] !== "") !== (m[3] !== ""), op: m[4] ?? "=", values });
469 }
470 return { text, terms, words, problems };
471 }
472
473 function costHolds(r: CloudResource, t: CloudTerm): boolean {
474 return t.values.some((v) => {
475 if (v === "unknown") return r.cents === null;
476 if (r.cents === null) return false;
477 const want = Math.round(Number(v.replace("$", "")) * 100);
478 return t.op === ">" ? r.cents > want : t.op === ">=" ? r.cents >= want : t.op === "<" ? r.cents < want : t.op === "<=" ? r.cents <= want : r.cents === want;
479 });
480 }
481
482 function termHolds(t: CloudTerm, r: CloudResource, project: string): boolean {
483 if (t.field === "cost") return costHolds(r, t) !== t.negate;
484 const have = PROPS[t.field as Prop](r, project).toLowerCase();
485 const hit = t.values.some((v) => (EXACT.has(t.field) ? have === v : v === (t.field === "app" ? "unknown" : "none") ? have === "" : t.field === "state" ? have.startsWith(v) : have.includes(v)));
486 return hit !== t.negate;
487 }
488
489 function matches(q: CloudQuery, r: CloudResource, project: string): boolean {
490 if (!q.terms.every((t) => termHolds(t, r, project))) return false;
491 if (q.words.length === 0) return true;
492 const hay = [r.id, r.name, r.kind, r.provider, r.account, project, r.region, r.size, r.label, r.state, r.partOf?.app ?? ""].join(" ").toLowerCase();
493 return q.words.every((w) => hay.includes(w));
447 export function readingOf(v: CloudView): string[] {
448 const half = v.root.count > 0 ? [] : v.q.line.problems.filter((p) => p.level === "half" && p.says !== "").map((p) => p.says);
449 return [...v.q.problems, ...half, ...wordsOf(v.q.line, LIST.fields)];
494450 }
495451
496452 /** One offered narrowing: the term it adds, its words, and how many resources it would leave. */
@@ -504,11 +460,13 @@ export interface Facet {
504460 * looking for waste asks. One already in the line is left out.
505461 */
506462 export function facetsOf(root: CloudNode, q: CloudQuery): Facet[] {
463 // After a quote that is not closed, a term would be inside it.
464 if (q.line.open) return [];
507465 const all = resourcesOf(root).map((n) => n.resource!);
508466 const kinds = [...groupBy(all, (r) => r.kind)].map(([k, own]): Facet => ({ term: `kind:${k}`, count: own.length })).sort((a, b) => b.count - a.count);
509467 const still = [...groupBy(all.filter((r) => /^(stopped|off|failed|deallocated)$/i.test(r.state)), (r) => r.state.toLowerCase())];
510468 const more: Facet[] = [
511 { term: "attached:no", count: all.filter((r) => PROPS.attached(r) === "no").length },
469 { term: "attached:no", count: all.filter((r) => attachedWord(r) === "no").length },
512470 ...still.map(([state, own]): Facet => ({ term: `state:${state}`, count: own.length })),
513471 { term: "made:found", count: all.filter((r) => r.madeBy === "found").length },
514472 { term: "cost:unknown", count: all.filter((r) => r.cents === null).length },
@@ -697,17 +655,17 @@ const SINGULAR = new Map([["logs", "log group"], ["nat", "NAT gateway"], ["balan
697655 export function findingOf(v: CloudView): { readonly found: string; readonly cost: string; readonly caveat: string } {
698656 const { root, q } = v;
699657 const only = (field: string): string => {
700 const own = q.terms.filter((t) => t.field === field);
701 return own.length === 1 && !own[0]!.negate && own[0]!.values.length === 1 ? own[0]!.values[0]! : "";
658 const own = q.line.terms.filter((t) => t.field === field);
659 return own.length === 1 && !own[0]!.not && own[0]!.any.length === 1 ? own[0]!.any[0]!.value : "";
702660 };
703661 const kind = only("kind");
704662 const idle = only("attached") === "no";
705663 const said = [...(kind === "" ? [] : ["kind"]), ...(idle ? ["attached"] : []), ...(only("state") === "" ? [] : ["state"]), ...(only("cloud") === "" ? [] : ["cloud"]), ...(only("region") === "" ? [] : ["region"])];
706664 const noun = kind === "" ? (root.count === 1 ? "resource" : "resources") : root.count === 1 ? (SINGULAR.get(kind) ?? kind) : (PLURAL.get(kind) ?? `${kind}s`);
707 const rest = q.words.length > 0 || q.terms.some((t) => !said.includes(t.field));
665 const rest = q.line.terms.some((t) => t.field === null || !said.includes(t.field));
708666 const found = [root.count === 0 ? "No" : root.count.toLocaleString("en-US"), idle ? "unattached" : "", only("state"), only("cloud") === "" ? "" : cloudName(only("cloud")), noun, only("region") === "" ? "" : `in ${only("region")}`, rest ? "matching" : ""].filter((x) => x !== "").join(" ");
709667 if (root.count === 0) return { found, cost: "", caveat: "" };
710 const caveat = q.terms.some((t) => t.field === "app" && !t.negate && t.values.every((x) => x === "unknown")) ? "No app found for these. That does not mean nothing uses them." : "";
668 const caveat = q.line.terms.some((t) => t.field === "app" && !t.not && t.any.every((c) => c.value === "unknown" && !c.literal)) ? "No app found for these. That does not mean nothing uses them." : "";
711669 const m = root.money;
712670 if (m.list + m.billed > 0) return { found, cost: costLine(root), caveat };
713671 // With no price of their own, they may still be inside a bill that was read.
src/http/mcp/tools/infra.ts +6 −3
@@ -1,7 +1,7 @@
11 import { cloudLinesFresh } from "../../../actions/cloud_says.ts";
22 import { infraCode } from "../../../cloud/infra_read.ts";
33 import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts";
4 import { CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, moneyWords, nodeAt, pathIn, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
4 import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, moneyWords, nodeAt, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts";
55 import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
66 import { machineView } from "../../../actions/machine_view.ts";
77 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
@@ -11,6 +11,7 @@ import { planMinecraft } from "../../../actions/minecraft.ts";
1111 import { dnsWantOf } from "../../../cloud/plan.ts";
1212 import { dollars } from "../../../cloud/prices.ts";
1313 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
14 import { refusalOf } from "../../../list/line.ts";
1415 import { pageRows } from "../page.ts";
1516 import { good, bad, type Answer, type Args, type Tool, str } from "../shared.ts";
1617
@@ -82,10 +83,12 @@ export const tool: Tool = {
8283 // A filter line, /infra's own: every cloud resource it leaves, the costliest first.
8384 const v = cloudResources(ctx.app, user, id);
8485 if (!v.ok) return bad("not_found", "no such tool here");
86 const wide = refusalOf(v.value.q.line);
87 if (wide !== undefined) return bad("invalid_filter", `${wide.says} (at character ${wide.at + 1}) Nothing was listed, because without that part the line finds more than was asked. The fields are ${CLOUD_PROPS.join(", ")}.`);
8588 const all = costliestOf(v.value.root);
8689 const f = findingOf(v.value);
87 const says = [f.found, f.cost, f.caveat, ...v.value.q.problems].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". ");
88 return named(v.value.whole, all, args, says, {});
90 const says = [f.found, f.cost, f.caveat, ...readingOf(v.value)].filter((x) => x !== "").map((x, i, all) => (i < all.length - 1 ? x.replace(/\.$/, "") : x)).join(". ");
91 return named(v.value.whole, all, args, says, { problems: v.value.q.problems });
8992 }
9093 if (action === "list") {
9194 const v = infraOf(ctx.app, user);
src/list/line.ts added +262
@@ -0,0 +1,262 @@
1 /**
2 * The one filter line for every list (#17532): `kind:volume,snapshot !region:us cost:>10 "web one"`.
3 * Terms are apart by spaces and all must hold; a comma is any of; `!` is the exact opposite; a sign
4 * carries on to the bare values after it; quotes are literal, with `\"` and `\\` inside them.
5 * A list declares its fields and what its plain words look in. Pure, and no regex comes from a
6 * person. `docs/features/infra.md` says what a person may type.
7 */
8
9 import { editDistance } from "../text/edit_distance.ts";
10
11 type Op = ">" | ">=" | "<" | "<=" | "=";
12
13 /**
14 * `word` is the whole value, `start` its beginning, `text` a part of it, each in any case. `number`
15 * is dollars in the line and whole cents in the row. `time` is an ISO string in the row, and an age
16 * (`<7d`, younger) or a date in the line.
17 */
18 type Type = "word" | "start" | "text" | "number" | "time";
19
20 export interface Field<R> {
21 readonly name: string;
22 readonly type: Type;
23 readonly of: (r: R) => string | number | null;
24 /**
25 * What an empty value is called: `none` when it is known to be empty, `unknown` when it is not
26 * known. The other one is an ordinary word.
27 */
28 readonly blank?: "none" | "unknown";
29 /** For a field with an order: what it takes, as the sentence about a bad value says it. */
30 readonly takes?: string;
31 }
32
33 export interface List<R> {
34 /** What plain words look in, its parts apart by line breaks. */
35 readonly text: (r: R) => string;
36 readonly fields: readonly Field<R>[];
37 }
38
39 interface Choice {
40 readonly op: Op;
41 /** In small letters. */
42 readonly value: string;
43 /** It was in quotes, so it is never the blank word. */
44 readonly literal: boolean;
45 }
46
47 interface Term {
48 /** Null is plain text, somewhere in the row. */
49 readonly field: string | null;
50 readonly not: boolean;
51 /** Any of these; with none at all (`kind:,`) no row holds. */
52 readonly any: readonly Choice[];
53 }
54
55 /**
56 * `half` is typed halfway, `id` is a provider's id read as text (`machine:i-111`): neither is a
57 * person's mistake. A `slip` still narrows or keeps the order. A `wide` one narrows nothing, so a
58 * program that asked is refused and a person is told.
59 */
60 interface Problem {
61 readonly at: number;
62 readonly says: string;
63 readonly level: "half" | "id" | "slip" | "wide";
64 }
65
66 export interface Line {
67 /** As typed, within the list's limit. */
68 readonly text: string;
69 readonly terms: readonly Term[];
70 readonly problems: readonly Problem[];
71 /** Its last quote is not closed, so nothing can be added after it. */
72 readonly open: boolean;
73 }
74
75 type Named = Pick<Field<never>, "name" | "type" | "blank" | "takes">;
76
77 const HEAD = /([!-]?)(?:"((?:[^"\\]|\\.)*)"|([^\s":,]+)):/y;
78 const SIGN = /[<>]=?|=/y;
79 const AGE = /^(\d+(?:\.\d+)?)([smhdw])$/;
80 const DATE = /^\d{4}-\d\d-\d\d(?:t\d\d:\d\d(?::\d\d)?(?:z|[+-]\d\d:\d\d)?)?$/;
81 const SPAN = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 } as const;
82
83 const fieldOf = <F extends { readonly name: string }>(fields: readonly F[], name: string): F | undefined => fields.find((f) => f.name.toLowerCase() === name.toLowerCase());
84 const ordered = (f: Pick<Named, "type">): boolean => f.type === "number" || f.type === "time";
85
86 const cents = (value: string): number | undefined => (/^\$?\d+(\.\d+)?$/.test(value) ? Math.round(Number(value.replace("$", "")) * 100) : undefined);
87
88 /** The moments a date names, from its first to the one after its last; UTC unless it says. */
89 function daySpan(value: string): { readonly from: number; readonly to: number } | undefined {
90 if (!DATE.test(value)) return undefined;
91 const [day, clock] = value.split("t");
92 // A day a month does not have rolls over in some engines, and is refused in others.
93 const start = Date.parse(`${day}T00:00:00Z`);
94 if (Number.isNaN(start) || new Date(start).toISOString().slice(0, 10) !== day) return undefined;
95 if (clock === undefined) return { from: start, to: start + SPAN.d };
96 const from = Date.parse(`${day}T${clock.toUpperCase()}${/z|[+-]/.test(clock) ? "" : "Z"}`);
97 return Number.isNaN(from) ? undefined : { from, to: from + (/^\d\d:\d\d:/.test(clock) ? SPAN.s : SPAN.m) };
98 }
99
100 const takesIt = (f: Named, c: Choice): boolean => (!c.literal && c.value === f.blank) || (f.type === "number" ? cents(c.value) !== undefined : AGE.test(c.value) || daySpan(c.value) !== undefined);
101
102 /** Text to show in a sentence, cut where it is long. */
103 const short = (text: string): string => (text.length > 60 ? `${text.slice(0, 59).toWellFormed()}…` : text);
104
105 function unknownField(name: string, fields: readonly Named[]): string {
106 const near = fields.map((f) => ({ name: f.name, far: editDistance(name.toLowerCase(), f.name.toLowerCase(), 2) })).sort((a, b) => a.far - b.far)[0];
107 const next = near !== undefined && near.far <= (name.length > 4 ? 2 : 1) ? `Did you mean ${near.name}?` : `The fields are ${fields.map((f) => f.name).join(", ")}.`;
108 return `"${short(name)}" is not a field here, so it is read as text. ${next}`;
109 }
110
111 /** A line's terms and what is wrong with it. It never fails: what cannot be read is a problem. */
112 export function parseLine(line: string, fields: readonly Named[], most: { readonly chars: number; readonly words: number } = { chars: 500, words: 20 }): Line {
113 const whole = line.trim();
114 // Cut inside an emoji, half of it is left, and no link can encode that.
115 const text = whole.slice(0, most.chars).toWellFormed();
116 const terms: Term[] = [];
117 const problems: Problem[] = [];
118 let i = 0;
119 let open = false;
120 const space = (at: number): boolean => at >= text.length || /\s/.test(text[at]!);
121 const problem = (at: number, level: Problem["level"], says: string): void => void problems.push({ at, says, level });
122 /** A word up to a space, or a comma inside a field; in quotes at its start, what they hold. */
123 const word = (comma: boolean): { readonly value: string; readonly literal: boolean } => {
124 let value = "";
125 const literal = text[i] === '"';
126 if (literal) {
127 for (i++; i < text.length && text[i] !== '"'; i++) {
128 if (text[i] === "\\" && (text[i + 1] === '"' || text[i + 1] === "\\")) i++;
129 value += text[i];
130 }
131 if (i >= text.length) open = true;
132 i++;
133 }
134 const from = i;
135 while (!space(i) && !(comma && text[i] === ",")) i++;
136 return { value: (value + text.slice(from, i)).toLowerCase(), literal };
137 };
138
139 for (let count = 0; ; count++) {
140 while (i < text.length && space(i)) i++;
141 if (i >= text.length) break;
142 const at = i;
143 if (count === most.words) {
144 problem(at, "wide", `A line here is at most ${most.words} words, so this is left out: ${short(text.slice(at))}`);
145 break;
146 }
147 HEAD.lastIndex = i;
148 const m = HEAD.exec(text);
149 const quoted = m?.[2]?.replace(/\\(["\\])/g, "$1");
150 const name = quoted ?? m?.[3] ?? "";
151 const f = m === null ? undefined : fieldOf(fields, name);
152 const view = /^(sort|group)$/i.exec(m?.[3] ?? "")?.[1]!.toLowerCase();
153
154 if (m !== null && (f !== undefined || view !== undefined)) {
155 i += m[0].length;
156 let not = m[1] !== "";
157 if (text[i] === "!") {
158 not = !not;
159 i++;
160 }
161 const any: Choice[] = [];
162 let op: Op = "=";
163 let signed = false;
164 let commas = false;
165 for (; ; i++) {
166 SIGN.lastIndex = i;
167 const sign = SIGN.exec(text)?.[0];
168 if (sign !== undefined) {
169 i += sign.length;
170 op = sign as Op;
171 signed = true;
172 }
173 const v = word(true);
174 if (v.value !== "") any.push({ op, ...v });
175 if (text[i] !== ",") break;
176 commas = true;
177 }
178 if (any.length === 0 && !commas) problem(at, "half", "");
179 else if (f === undefined) problem(at, any.length === 0 ? "half" : "slip", any.length === 0 ? "" : `This list cannot ${view}.`);
180 else if (ordered(f) && !any.every((c) => takesIt(f, c))) problem(at, "wide", `${f.name} takes ${f.takes ?? `a ${f.type}`}${f.blank === undefined ? "" : `, or ${f.name}:${f.blank}`}.`);
181 else {
182 if (any.length === 0) problem(at, "half", `${f.name}: has only commas and no value, so it holds for nothing.`);
183 if (signed && !ordered(f)) problem(at, "slip", `${f.name} takes no comparison, so the sign is left out.`);
184 terms.push({ field: f.name, not, any: ordered(f) ? any : any.map((c) => ({ ...c, op: "=" as const })) });
185 }
186 continue;
187 }
188
189 const not = text[i] === "!";
190 if (not) i++;
191 const from = i;
192 const strange = m !== null && (quoted !== undefined || /^[a-z]+$/i.test(name));
193 // `label:"P0 Trust"` on a list with no such field is still one piece of text.
194 const before = strange ? text.slice(from, at + m[0].length) + (/^!?(?:[<>]=?|=)?/.exec(text.slice(at + m[0].length, at + m[0].length + 3))?.[0] ?? "") : "";
195 if (strange) i = from + before.length;
196 const v = word(false);
197 const value = quoted !== undefined && strange ? `${name.toLowerCase()}:${v.value}` : before.toLowerCase() + v.value;
198 if (value === "") {
199 problem(at, "half", "");
200 continue;
201 }
202 // A provider's id may hold a colon (`machine:i-111`): only a plain word is a slip.
203 if (strange && v.value !== "") problem(at, !v.literal && /\d/.test(v.value) ? "id" : "slip", unknownField(name, fields));
204 terms.push({ field: null, not, any: [{ op: "=", value, literal: v.literal && before === "" }] });
205 }
206 if (open) problem(text.lastIndexOf('"'), "half", "The quote is not closed, so all after it is in it.");
207 if (whole.length > most.chars) problem(most.chars, "wide", `A line here is at most ${most.chars} characters, so this is left out: ${short(whole.slice(most.chars).toWellFormed().trim())}`);
208 return { text, terms, problems, open };
209 }
210
211 /**
212 * Why a program that asked is refused: the first problem that would hand it rows it meant to leave
213 * out. A slip is answered, and named.
214 */
215 export const refusalOf = (line: Line): Problem | undefined => line.problems.find((p) => p.level === "wide");
216
217 const compared = (have: number, op: Op, want: number): boolean => (op === ">" ? have > want : op === ">=" ? have >= want : op === "<" ? have < want : op === "<=" ? have <= want : have === want);
218
219 function timeHolds(have: number, c: Choice, now: number): boolean {
220 const age = AGE.exec(c.value);
221 if (age !== null) return compared(now - have, c.op === "=" ? "<=" : c.op, Number(age[1]) * SPAN[age[2] as keyof typeof SPAN]);
222 const { from, to } = daySpan(c.value)!;
223 return c.op === "<" ? have < from : c.op === "<=" ? have < to : c.op === ">" ? have >= to : c.op === ">=" ? have >= from : have >= from && have < to;
224 }
225
226 function choiceHolds<R>(f: Field<R>, c: Choice, r: R, now: number): boolean {
227 const have = f.of(r);
228 const at = f.type === "time" ? Date.parse(String(have)) : 0;
229 const empty = have === null || have === "" || Number.isNaN(at);
230 if (!c.literal && c.value === f.blank) return empty;
231 // A comparison never holds for what is not known.
232 if (empty) return false;
233 if (f.type === "number") return compared(Number(have), c.op, cents(c.value)!);
234 if (f.type === "time") return timeHolds(at, c, now);
235 const value = String(have).toLowerCase();
236 return f.type === "word" ? value === c.value : f.type === "start" ? value.startsWith(c.value) : value.includes(c.value);
237 }
238
239 /** Whether every term holds for one row. */
240 export function holds<R>(list: List<R>, line: Line, r: R, now: number): boolean {
241 return line.terms.every((t) => {
242 const f = t.field === null ? undefined : fieldOf(list.fields, t.field)!;
243 const text = f === undefined ? list.text(r).toLowerCase() : "";
244 return t.any.some((c) => (f === undefined ? text.includes(c.value) : choiceHolds(f, c, r, now))) !== t.not;
245 });
246 }
247
248 /** How the parts that can be read two ways were read: a mark, quotes, an age and a date. */
249 export function wordsOf(line: Line, fields: readonly Named[]): string[] {
250 return line.terms.flatMap((t): string[] => {
251 const value = t.any[0]?.value ?? "";
252 if (t.field === null) return t.not ? [`!${short(value)} is read as: without the text "${short(value)}".`] : t.any[0]!.literal ? [`The quotes are read as marks around the text: ${short(value)}.`] : [];
253 const own = t.any.filter((c) => c.literal || c.value !== "unknown");
254 if (fieldOf(fields, t.field)?.type !== "time" || own.length === 0) return [];
255 const said = t.any.map((c) => {
256 if (AGE.test(c.value)) return `${{ ">": "older than", ">=": "at least", "<": "younger than", "<=": "at most", "=": "at most" }[c.op]} ${c.value}${/=/.test(c.op) ? " old" : ""}`;
257 if (daySpan(c.value) === undefined) return "not known";
258 return `${{ ">": "after", ">=": "from", "<": "before", "<=": "up to the end of", "=": "in" }[c.op]} ${c.value.toUpperCase()}${/t.*[z+-]/.test(c.value) ? "" : " (UTC)"}`;
259 });
260 return [`${t.field}: ${t.not ? "not " : ""}${said.join(", or ")}.`];
261 });
262 }
src/tui/screens/cloudtree.ts +3 −2
@@ -6,7 +6,7 @@
66 */
77
88 import { cloudResources, readProjectsNow } from "../../actions/infra.ts";
9 import { cloudName, CONTAINER_COST, containersSay, costLine, costliestOf, cutSays, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
9 import { cloudName, CONTAINER_COST, containersSay, costLine, costliestOf, cutSays, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, readingOf, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts";
1010 import { dollars } from "../../cloud/prices.ts";
1111 import { keyOf } from "../../web/keymap.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -130,7 +130,8 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen {
130130 const f = findingOf(v);
131131 const total = v.q.text === "" ? costLine(v.root) || (v.root.count === 0 ? "" : [`${v.root.count} resources, no price known`, unreadLine(v.root)].filter((x) => x !== "").join(", ")) : [f.found, f.caveat, f.cost].filter((x) => x !== "").join(" · ");
132132 const says = note !== "" ? note : v.held === 0 ? "No cloud account is attached: press I on Cloud accounts, or open /settings/cloud." : total === "" ? "Nothing read yet: press P to read every account now." : total;
133 const said = wrap(v.q.problems[0] ?? says, area.w).slice(0, f.caveat === "" ? 2 : 3);
133 const reading = readingOf(v);
134 const said = wrap([...reading, ...(v.q.problems.length > 0 ? [] : [says])].join(" "), area.w).slice(0, f.caveat === "" && reading.length === 0 ? 2 : 3);
134135 const [head, box, body] = split(area, "v", [len(said.length), len(1), fill(1)]);
135136 said.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.fg, c.bg), head!.x + head!.w));
136137 const caret = filter.render(s, box!, c, "/ kind:volume cloud:aws cost:>10");
src/web/pages/cloud_tree.ts +2 −1
@@ -15,6 +15,7 @@ import {
1515 cloudName,
1616 costliestOf,
1717 facetsOf,
18 readingOf,
1819 isStale,
1920 largestCosts,
2021 lastMonth,
@@ -119,7 +120,7 @@ export function cloudList(v: CloudView, current: readonly string[]): Html {
119120 const filtering = q.text !== "";
120121 const openAll = root.count <= (filtering ? OPEN_ALL : OPEN_SMALL);
121122 return html`<div id="cloud-list" data-q="${q.text}">
122 ${q.problems.map((p) => html`<p class="small" role="status">${p}</p>`)}
123 ${readingOf(v).map((p) => html`<p class="small" role="status">${p}</p>`)}
123124 <p class="ex-facets small">${facetsOf(root, q).map(
124125 (f) => html`<a href="${withQuery("/infra", { ...q, text: `${q.text} ${f.term}`.trim() })}" data-term="${f.term}">${f.term} <span class="num muted">${f.count}</span></a> `,
125126 )}</p>
test/cloud-filter-lines.test.ts +37 −23
@@ -1,11 +1,12 @@
11 /**
22 * The cloud tree's filter lines and the rows each finds (#17532), written on the parser that drew
3 * the links people have saved. A new language runs this table unchanged: a saved line keeps its
4 * rows. `DELIBERATE` holds the lines whose meaning it may change, and says to what.
3 * the links people have saved. The shared language (`src/list/line.ts`) runs this table unchanged: a
4 * saved line keeps its rows. `DELIBERATE` holds the lines whose meaning it changed, and says from what.
55 */
66 import { expect, test } from "bun:test";
7 import { readFileSync } from "node:fs";
78 import type { CloudResource, ProjectView } from "../src/cloud/projects.ts";
8 import { cloudTree, costliestOf, parseCloudQuery } from "../src/cloud/tree.ts";
9 import { CLOUD_PROPS, cloudTree, costliestOf, parseCloudQuery } from "../src/cloud/tree.ts";
910
1011 const AT = "2026-12-02T12:00:00.000Z";
1112 const NOW = Date.parse(AT);
@@ -63,33 +64,37 @@ const KEEPS: readonly (readonly [string, string])[] = [
6364 ["machine:", "AE"], ["machine:i-111", "A"], ["machine:77", "E"], ["-machine:i-111", ""], ["lables:bug", " !"], ["http://x", " !"],
6465 ];
6566
66 /** What the next language may change. The rows are today's; the words say what is meant instead. */
67 /** Lines that meant something else on the parser before `src/list/line.ts`: what each finds now, and what it found then. */
6768 const DELIBERATE: readonly (readonly [string, string, string])[] = [
68 ["!web", "", "negates: the rows without the word"],
69 ["!machine:i-111", "", "negates, as !web"],
70 ["name:>web", "A", "the same rows, and the sign is said"],
71 ["region:>us", "ABCD", "the same rows, and the sign is said"],
72 ["kind:>volume", "BC", "the same rows, and the sign is said"],
73 ['"vol-1"', "", "a quoted word is the word"],
74 ['name:"web"', "", "a quoted value is the value"],
75 ['state:"running"', "", "a quoted value is the value"],
76 ["sort:-cost", " !", "the order"],
77 ["group:region", " !", "headings"],
78 ["created:>7d", "", "a field, once there is one"],
69 ["!web", "BCDEF", "nothing: the mark was part of the word"],
70 ["!machine:i-111", "BCDEF", "nothing, as !web"],
71 ["!", "ABCDEF", "nothing: a mark with no word yet"],
72 ["name:>web", "A !", "the same rows, and the sign was not said"],
73 ["name:=web", "A !", "nothing: = was part of the word"],
74 ["region:>us", "ABCD !", "the same rows, and the sign was not said"],
75 ["kind:>volume", "BC !", "the same rows, and the sign was not said"],
76 ['"vol-1"', "B", "nothing: the quotes were part of the word"],
77 ['name:"web"', "A", "nothing: the quotes were part of the word"],
78 ['state:"running"', "AE", "nothing: the quotes were part of the word"],
79 ["sort:-cost", "ABCDEF !", "nothing: it was text, and is a word of the language this list does not have yet"],
80 ["sort:", "ABCDEF", "nothing: it was text"],
81 ["group:region", "ABCDEF !", "nothing: it was text, as sort:"],
82 ["created:>7d", "", "nothing: it was text, and is a field"],
83 ["created:<7d", "ABCDEF", "nothing: it was text, and is a field"],
7984 ["file:no", " !", "a field, once there is one"],
80 ["cost:>10,=20", "ABCDEF !", "= ends the sign's reach"],
81 ["cost:=10", "ABCDEF !", "exactly 10"],
82 ["cost:>10,<5", "ABCDEF !", "each value has its own sign"],
83 ["cost:none", "ABCDEF !", "over MCP a 422; a page still narrows nothing"],
84 ["cost:abc", "ABCDEF !", "over MCP a 422; a page still narrows nothing"],
85 ["cost:>abc", "ABCDEF !", "over MCP a 422; a page still narrows nothing"],
85 ["cost:>10,=20", "AEF", "everything, and a problem"],
86 ["cost:=10", "C", "everything, and a problem"],
87 ["cost:>10,<5", "AEF", "everything, and a problem: now each value has its own sign"],
88 ["cost:none", "ABCDEF !", "the same; over MCP it is refused now"],
89 ["cost:abc", "ABCDEF !", "the same; over MCP it is refused now"],
90 ["cost:>abc", "ABCDEF !", "the same; over MCP it is refused now"],
8691 ];
8792
8893 test.each(KEEPS.map(([line, rows]) => [line, rows] as const))("%p finds %p", (line, rows) => {
8994 expect(sorted(line)).toBe(rows);
9095 });
9196
92 test.each(DELIBERATE.map(([line, rows, next]) => [line, rows, next] as const))("%p finds %p today; next: %s", (line, rows) => {
97 test.each(DELIBERATE.map(([line, rows, before]) => [line, rows, before] as const))("%p finds %p; before: %s", (line, rows) => {
9398 expect(sorted(line)).toBe(rows);
9499 });
95100
@@ -97,8 +102,17 @@ test("the costliest first, and one with no known cost last", () => {
97102 expect(found("").join("")).toBe("EAFCBD");
98103 });
99104
100 test("past 12 words or 200 characters a page ignores the rest (the next language says so, and over MCP answers 422)", () => {
105 test("past 12 words or 200 characters a page ignores the rest and says so; the `infra` tool refuses it", () => {
101106 expect(found(`vol-1 ${"vol ".repeat(11)}nothing`)).toEqual(["B"]);
102107 expect(found(`vol-1 ${"vol ".repeat(10)}nothing`)).toEqual([]);
103108 expect(found(`vol-1${" ".repeat(195)}nothing`)).toEqual(["B"]);
109 for (const line of [`vol-1 ${"vol ".repeat(11)}nothing`, `vol-1${" ".repeat(195)}nothing`]) expect(parseCloudQuery(line).problems.join()).toContain("so this is left out: nothing");
110 });
111
112 test("no field has the name of an id's prefix, so a pasted id stays text (project has been both since before)", () => {
113 // The prefixes as `inventory.ts` types them.
114 const typed = readFileSync(new URL("../src/cloud/inventory.ts", import.meta.url), "utf8");
115 const prefixes = [...typed.matchAll(/^ {2}\| "([a-z-]+)"/gm)].map((m) => m[1]!).concat("stack", "target-group", "interface");
116 expect(prefixes).toContain("machine");
117 expect(CLOUD_PROPS.filter((p) => prefixes.includes(p))).toEqual([]);
104118 });
test/cloud-tree.test.ts +20 −2
@@ -147,7 +147,7 @@ describe("with accounts", () => {
147147 for (const line of ["kind:machine !cloud:aws", "kind:machine cloud:!aws", "kind:machine -cloud:aws"]) expect(left(line)).toEqual(["machine:1", "machine:9"]);
148148 expect(left("cost:>10")).toEqual(["machine:1"]);
149149 expect(left("vol-2")).toEqual(["volume:vol-2"]);
150 expect(view("colour:red").q.problems[0]).toContain('"colour" is not a property');
150 expect(view("colour:red").q.problems[0]).toContain('"colour" is not a field here');
151151 });
152152
153153 test("honest states: never read, a failed read, a kind not read with its reason, an old reading", () => {
@@ -186,6 +186,13 @@ describe("with accounts", () => {
186186 expect(pane).toContain("nothing: it still bills");
187187 });
188188
189 test("a page says how it read a mark and a quote, and why it has no rows", async () => {
190 for (const [line, says] of [["!vol-1", "without the text"], ['"vol-1"', "marks around the text"], ["kind:,", "only commas"], ['"vol-1 kind:volume', "The quote is not closed"], ["lables:bug", "is not a field here"], ["cost:abc", "cost takes dollars a month"], ["created:<7d", "younger than 7d"]] as const) {
191 const html = await (await get(`/infra?q=${encodeURIComponent(line)}`)).text();
192 expect(html.slice(html.indexOf('id="cloud-list"'))).toContain(says);
193 }
194 });
195
189196 test("under a filter a resource still says its ties and the bill it is in", async () => {
190197 const pane = await (await get("/infra/-/aws/main/us-east-1/volume:vol-1?fragment=1&q=kind%3Avolume")).text();
191198 expect(pane).toContain('<a href="/infra/-/aws/main/us-east-1/machine:i-1?q=kind%3Avolume">api</a>');
@@ -288,6 +295,15 @@ describe("with accounts", () => {
288295 const token = createToken(app.db, alice.id, "admin", "admin").token;
289296 const listed = await mcpTool(servers.url, token, "infra", { action: "list", id: "kind:volume attached:no" });
290297 expect(listed.value.resources.map((r: { id: string }) => r.id)).toEqual(["aws/main/us-east-1/volume:vol-2"]);
298 // What would hand an agent every row is refused; what only narrows oddly is answered and named.
299 for (const [line, why] of [["kind:volume cost:abc", "(at character 13)"], ["cost:none", "cost:unknown"], ["vol ".repeat(13), "at most 12 words"], [`vol${"l".repeat(250)}`, "at most 200 characters"]] as const) {
300 const refused = await mcpTool(servers.url, token, "infra", { action: "list", id: line });
301 expect(refused.error).toContain("invalid_filter");
302 expect(refused.error).toContain(why);
303 }
304 const slip = await mcpTool(servers.url, token, "infra", { action: "list", id: "kind:>volume attached:no" });
305 expect([slip.value.resources.length, slip.value.problems]).toEqual([1, ["kind takes no comparison, so the sign is left out."]]);
306 expect((await mcpTool(servers.url, token, "infra", { action: "list", id: "volume:vol-2" })).value.problems).toEqual([]);
291307 const one = await mcpTool(servers.url, token, "infra", { action: "cloud", id: "aws/main/us-east-1/volume:vol-1" });
292308 expect(one.value.facts).toContainEqual({ label: "Attached to", value: "api" });
293309 expect((await mcpTool(servers.url, token, "infra", { action: "cloud", id: "aws/main/us-east-1/volume:gone" })).error).toContain("No such cloud resource");
@@ -305,7 +321,9 @@ describe("with accounts", () => {
305321 await settleApp(tui);
306322 return tui.screen.toText();
307323 };
308 expect(await press("/vol-1\r")).toContain("vol-1");
324 expect(await press("/!zzz\r")).toContain("without the text");
325 expect(await press(`/${"\x7f".repeat(4)}kind:,\r`)).toContain("only commas");
326 expect(await press(`/${"\x7f".repeat(6)}vol-1\r`)).toContain("vol-1");
309327 const open = await press("jjj\r");
310328 tui.stop?.();
311329 expect(open).toContain("Attached to");
test/list-line.test.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The one filter line (`src/list/line.ts`): how a line is read, what each problem is, and what an
3 * age and a date mean. The cloud tree's own rows are in `test/cloud-filter-lines.test.ts`.
4 */
5 import { expect, test } from "bun:test";
6 import { holds, parseLine, refusalOf, wordsOf, type Field, type List } from "../src/list/line.ts";
7
8 interface Row {
9 readonly name: string;
10 readonly kind: string;
11 readonly cents: number | null;
12 readonly made: string;
13 }
14 const NOW = Date.parse("2026-12-02T12:00:00Z");
15 const FIELDS: readonly Field<Row>[] = [
16 { name: "name", type: "text", of: (r) => r.name, blank: "none" },
17 { name: "label", type: "word", of: (r) => r.kind },
18 { name: "Unit Price", type: "number", of: (r) => r.cents, blank: "unknown", takes: "dollars, like 10" },
19 { name: "created", type: "time", of: (r) => r.made, blank: "unknown", takes: "an age or a date" },
20 ];
21 const LIST: List<Row> = { text: (r) => `${r.name}\n${r.kind}`, fields: FIELDS };
22 const ROWS: readonly Row[] = [
23 { name: "web one", kind: "P0 Trust", cents: 1000, made: "2026-12-02T11:30:00Z" },
24 { name: "none", kind: "a,b", cents: 2000, made: "2026-11-25T12:00:00Z" },
25 { name: "", kind: 'say "hi"', cents: null, made: "" },
26 { name: "unit:7", kind: "c\\d", cents: 500, made: "2026-12-01T23:59:59Z" },
27 ];
28 const read = (line: string) => parseLine(line, FIELDS);
29 /** The rows a line holds for, by number. */
30 const rows = (line: string): string => ROWS.flatMap((r, i) => (holds(LIST, read(line), r, NOW) ? [i] : [])).join("");
31 const levels = (line: string): string => read(line).problems.map((p) => p.level).join(" ");
32
33 test.each([
34 ['label:"P0 Trust"', "0"], ['label:"a,b"', "1"], ["label:a,b", ""], ['label:"say \\"hi\\""', "2"], ['label:"c\\\\d"', "3"],
35 ["name:none", "2"], ['name:"none"', "1"], ['"web one"', "0"], ['!"web one"', "123"], ['"one P0"', ""], ['"unit:7"', "3"], ["unit:7", "3"], ['"Unit Price":>7', "01"], ['!"unit price":>7', "23"], ['-"unit price":>7', "23"],
36 ['"unit price":>15,=10', "01"], ['"unit price":>15,<6', "13"], ['"unit price":unknown,5', "23"], ['""', "0123"], ['name:""', "0123"], ["!", "0123"],
37 ] as const)("quotes and signs: %p holds for %p", (line, want) => {
38 expect(rows(line)).toBe(want);
39 });
40
41 test.each([
42 // Younger, older, and bare: at most that old.
43 ["created:<1h", "0"], ["created:30m", "0"], ["created:29m", ""], ["created:>1d", "1"], ["created:>=7d", "1"], ["created:>1w", ""], ["created:1.5d", "03"], ["created:unknown", "2"], ["!created:<1h", "123"],
44 // A date is its whole day, a minute its whole minute; UTC unless it says otherwise.
45 ["created:2026-12-01", "3"], ["created:<2026-12-01", "1"], ["created:<=2026-12-01", "13"], ["created:>2026-12-01", "0"], ["created:>=2026-12-01", "03"],
46 ["created:2026-12-02T11:30", "0"], ["created:2026-12-01T23:59:58", ""], ["created:2026-12-01T23:59:59Z", "3"], ["created:2026-12-02T13:30+02:00", "0"],
47 ] as const)("times: %p holds for %p", (line, want) => {
48 expect(rows(line)).toBe(want);
49 });
50
51 test.each([
52 // Half typed, and an id, are quiet.
53 ["name:", "half"], ["!name:", "half"], ["created:>", "half"], ["name:,", "half"], ['"web', "half"], ['name:"web', "half"], ["!", "half"], ["sort:", "half"], ["machine:i-111", "id"], ["!machine:77", "id"], ["machine:", ""],
54 // These still narrow, or keep the order.
55 ["lables:bug", "slip"], ['machine:"i 1"', "slip"], ["name:>a", "slip"], ["name:=a", "slip"], ["sort:-name", "slip"], ["group:label", "slip"],
56 // These narrow nothing.
57 ["created:abc", "wide"], ["created:2026-02-30", "wide"], ["created:2026-13-01", "wide"], ['"unit price":none', "wide"], ["created:none", "wide"], ['created:"unknown"', "wide"],
58 // Plain.
59 ["web one -x web-1:a name:web", ""], ['5"disk', ""],
60 ] as const)("%p has the problems %p", (line, want) => {
61 expect(levels(line)).toBe(want);
62 });
63
64 test("a problem says what it is, and only a wide one is refused", () => {
65 expect(read("lables:bug").problems[0]!.says).toBe('"lables" is not a field here, so it is read as text. Did you mean label?');
66 expect(read("zzzzzzz:bug").problems[0]!.says).toContain("The fields are name, label, Unit Price, created.");
67 expect(read("name:>a").problems[0]!.says).toBe("name takes no comparison, so the sign is left out.");
68 expect(refusalOf(read("lables:bug name:>a machine:77 name:"))).toBeUndefined();
69 expect(refusalOf(read("web created:abc"))).toEqual({ at: 4, says: "created takes an age or a date, or created:unknown.", level: "wide" });
70 });
71
72 test("past the list's limit the rest is left out, named, and wide", () => {
73 const most = { chars: 20, words: 2 };
74 const words = parseLine("a b c d", FIELDS, most);
75 expect([words.terms.length, words.problems[0]]).toEqual([2, { at: 4, says: "A line here is at most 2 words, so this is left out: c d", level: "wide" }]);
76 const chars = parseLine(`${"a".repeat(20)} kind:x`, FIELDS, most);
77 expect([chars.text, refusalOf(chars)?.says]).toEqual(["a".repeat(20), "A line here is at most 20 characters, so this is left out: kind:x"]);
78 });
79
80 test("the words beside a line say how a mark, a quote, an age and a date were read", () => {
81 expect(wordsOf(read("!web"), FIELDS)).toEqual(['!web is read as: without the text "web".']);
82 expect(wordsOf(read('"web one"'), FIELDS)).toEqual(['The quotes are read as marks around the text: web one.']);
83 expect(wordsOf(read("created:<7d,>1h"), FIELDS)).toEqual(["created: younger than 7d, or older than 1h."]);
84 expect(wordsOf(read("!created:>2026-12-01"), FIELDS)).toEqual(["created: not after 2026-12-01 (UTC)."]);
85 expect(wordsOf(read("created:2026-12-02t13:30+02:00"), FIELDS)).toEqual(["created: in 2026-12-02T13:30+02:00."]);
86 expect(wordsOf(read("web name:web created:unknown"), FIELDS)).toEqual([]);
87 });
88
89 test("a long hostile line is read in a bounded time", () => {
90 const started = performance.now();
91 for (const line of ['"'.repeat(50_000), "\\".repeat(50_000), `"${"\\".repeat(50_000)}`, "a:,".repeat(20_000), "!-".repeat(30_000), `${'"a":'.repeat(20_000)}`]) read(line);
92 expect(performance.now() - started).toBeLessThan(1_000);
93 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs