// The verb registry (lib/cli/verbs.mjs) names every verb umtool dispatches, // each row is a form or says why it is not, and `umtool help` and // docs/cli.md are what it generates. import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { VERBS, formVerbs, verbRow, commandOf, BLOCK_KINDS, BLOCK_FIELDS, BLOCK_NAVS, blockVerbs, fromBlockValues, templateFields } from "./verbs.mjs"; import { GROUPS } from "./groups.mjs"; import { CLI_MD, DOCS_BEGIN, DOCS_END, usageText, withVerbsSection } from "./docs.mjs"; import { buildArgv, cliLine, confirmOf, pathArgsOf, shellQuote, synopsis } from "./argv.mjs"; import { confineToProject } from "./confine.mjs"; const UMTOOL = fileURLToPath(new URL("../../", import.meta.url)); const read = (rel) => readFileSync(`${UMTOOL}${rel}`, "utf8"); const ADD = "add a row to umtool/lib/cli/verbs.mjs: form(verb, target, summary, args) with its args, or none(verb, target, summary, reason) with why it has no form"; /** The top-level commands bin/umtool.mjs dispatches: its COMMANDS table's keys. */ function dispatched() { const src = read("bin/umtool.mjs"); const a = src.indexOf("const COMMANDS = {"); const b = src.indexOf("\n};", a); assert.ok(a >= 0 && b > a, "bin/umtool.mjs has its COMMANDS table"); return [...src.slice(a, b).matchAll(/^ {2}("?)([a-z][a-z-]*)\1:/gm)].map((m) => m[2]); } // Where each command's sub-verbs are dispatched, and the pattern that names one. A sub-verb added to one of // these files without a row fails "every sub-verb …" below, naming it. const SUBVERBS = [ { cmd: "takes", file: "lib/report/takeCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "timeline", file: "lib/report/timelineCli.mjs", re: /\bverb === "([a-z][a-z-]*)"|case "([a-z][a-z -]*)":/g }, { cmd: "posts", file: "lib/report/postsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g }, { cmd: "trailer-beats", file: "lib/report/trailerBeatsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"|case "([a-z][a-z-]*)":/g }, { cmd: "cast", file: "lib/report/castCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help", "remove"] }, { cmd: "reads", file: "lib/report/readsCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "queue", file: "lib/queue/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "notes", file: "lib/annotations/cli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g, ignore: ["help"] }, { cmd: "rulings", file: "lib/report/rulingsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g }, { cmd: "ledger", file: "lib/report/ledgerCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g }, { cmd: "candidates", file: "lib/report/candidatesCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g }, { cmd: "clips", file: "lib/report/reactions.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help"] }, { cmd: "pool", file: "lib/report/poolCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "library", file: "lib/library/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "render-mode", file: "lib/report/renderMode.mjs", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "schedule", file: "bin/schedule.ts", re: /\bsub === "([a-z][a-z-]*)"/g }, { cmd: "storage", file: "bin/umtool.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, within: ["async function cmdStorage()", "async function cmdStorageDeliverables"] }, ]; /** The sub-verbs a file dispatches for a command. */ function subverbsOf({ file, re, ignore = [], within }) { let src = read(file); if (within) src = src.slice(src.indexOf(within[0]), src.indexOf(within[1])); const names = new Set(); for (const m of src.matchAll(re)) names.add((m[1] ?? m[2]).trim()); return [...names].filter((n) => !ignore.includes(n)); } test("every command bin/umtool.mjs dispatches has a row (and its help lines in groups.mjs)", () => { const verbs = new Set(VERBS.map((r) => commandOf(r.verb))); const groups = new Set(GROUPS.map((g) => g.cmd)); for (const cmd of dispatched()) { assert.ok(verbs.has(cmd), `\`umtool ${cmd}\` is dispatched (bin/umtool.mjs COMMANDS) but has no row -- ${ADD}`); if (cmd !== "help") assert.ok(groups.has(cmd), `\`umtool ${cmd}\` has no help lines -- add a group to umtool/lib/cli/groups.mjs`); } const all = new Set(dispatched()); for (const r of VERBS) assert.ok(all.has(commandOf(r.verb)), `the row \`${r.verb}\` names a command bin/umtool.mjs does not dispatch`); for (const g of GROUPS) assert.ok(all.has(g.cmd), `groups.mjs's \`${g.cmd}\` is not a command bin/umtool.mjs dispatches`); }); test("every sub-verb the CLI modules dispatch has a row", () => { const have = new Set(VERBS.map((r) => r.verb)); for (const s of SUBVERBS) { const subs = subverbsOf(s); assert.ok(subs.length, `${s.file} still dispatches ${s.cmd}'s sub-verbs the way verbs.test.mjs reads them`); for (const sub of subs) { const verb = `${s.cmd} ${sub}`; // A group's bare name ("timeline groups") is its listing. assert.ok(have.has(verb), `\`umtool ${verb}\` is dispatched (${s.file}) but has no row -- ${ADD}`); } } for (const v of ["modules list", "modules apply", "preset list", "preset show", "preset save", "preset apply", "render-mode off", "take status", "takes save", "takes open", "takes freeze"]) { assert.ok(have.has(v), `\`umtool ${v}\` has no row -- ${ADD}`); } }); test("every row is a form or says why it is not, and its args make sense", () => { const TYPES = new Set(["project", "string", "text", "number", "boolean", "choice", "json", "pairs", "flagpairs", "list", "name", "path", "ref"]); const seen = new Set(); for (const r of VERBS) { assert.ok(!seen.has(r.verb), `\`${r.verb}\` has two rows`); seen.add(r.verb); assert.ok(r.summary?.trim(), `\`${r.verb}\` has a summary`); assert.ok(["draft", "project", "corpus"].includes(r.target), `\`${r.verb}\`'s target is draft, project or corpus`); assert.ok(r.ui === "form" || r.ui === "none", `\`${r.verb}\`'s ui is "form" or "none"`); if (r.ui === "none") { assert.ok(r.reason?.trim(), `\`${r.verb}\` has no form: say why (reason)`); continue; } const names = new Set(); for (const a of r.args) { assert.ok(!names.has(a.name), `\`${r.verb}\`: ${a.name} twice`); names.add(a.name); assert.ok(TYPES.has(a.type), `\`${r.verb}\`: ${a.name}'s type ${a.type}`); if (a.type === "choice") assert.ok(a.choices?.length, `\`${r.verb}\`: ${a.name} names its choices`); if (a.type === "boolean" || a.type === "flagpairs") assert.ok(a.name.startsWith("--") || a.type === "flagpairs", `\`${r.verb}\`: a boolean is a flag`); } for (const t of (r.shape ?? r.verb).split(" ")) { const m = /^<(.+)>$/.exec(t); if (m) assert.ok(r.args.some((a) => a.name === m[1] && !a.name.startsWith("--")), `\`${r.verb}\`'s shape names <${m[1]}>, a positional it has`); } // The shape's words are the verb's own, in order. const words = (r.shape ?? r.verb).split(" ").filter((t) => !t.startsWith("<")); assert.deepEqual(words, r.verb.split(" "), `\`${r.verb}\`'s shape keeps its words in order`); } assert.ok(formVerbs().every((r) => !("usage" in r) && !("reason" in r)), "the page's list carries no prose"); assert.equal(formVerbs().length, VERBS.filter((r) => r.ui === "form").length); // The page builds its Copy as CLI line from these rows: the same argv the server builds from the registry's. const sample = { project: "reports/p", id: "c01", "--to": "2", "--after": "c01", item: "p-5", op: "ls", settings: "a=1", ruling: "keep", clip: "c01", marker: "m1", gid: "g1", n: "1", span: "1-2", second: "3" }; for (const r of formVerbs()) { // What the page builds the line from IS the registry's: its shape and its args, whole. assert.deepEqual(r.shape, verbRow(r.verb).shape, `\`${r.verb}\`: the page's row has the registry's shape`); assert.deepEqual(r.args, verbRow(r.verb).args, `\`${r.verb}\`: the page's row has the registry's args`); const vals = Object.fromEntries(r.args.filter((a) => a.name in sample).map((a) => [a.name, sample[a.name]])); assert.deepEqual(buildArgv(r, vals), buildArgv(verbRow(r.verb), vals), `\`${r.verb}\`: the page's line is the command that runs`); } }); test("cli.md's generated section is current (node umtool/lib/cli/docs.mjs rewrites it)", () => { const text = readFileSync(CLI_MD, "utf8"); assert.ok(text.includes(DOCS_BEGIN) && text.includes(DOCS_END), "the markers are in cli.md"); assert.equal(withVerbsSection(text), text, "umtool/docs/cli.md is stale: run `node umtool/lib/cli/docs.mjs`"); // Every row is in it, and the hand-written sections around it stay. for (const r of VERBS) assert.ok(text.includes(r.ui === "form" ? synopsis(r).replace(/\|/g, "\\|") : `\`${r.verb}\``), `cli.md lists \`${r.verb}\``); assert.ok(text.includes("## Environment") && text.includes("## `check` is the one to run before every build")); }); test("umtool help is generated from the groups, with its fills", () => { const help = usageText({ reportsRoot: "/r", chainSteps: "current, windows", draftAllSteps: "a, b" }); assert.match(help, /^umtool — the project tree, from a terminal\n\n {2}umtool ls /); assert.match(help, /one step a process: current, windows/); assert.match(help, /\(Draft everything\): a, b —/); assert.match(help, /reading \/r {2}\(set REPORTS_DIR to move it\)/); assert.ok(!help.includes("{chainSteps}")); for (const g of GROUPS) for (const l of g.usage) assert.ok(/^ {2}umtool [a-z-]+ |^ {19}/.test(l), `${g.cmd}: "${l.slice(0, 40)}…" is a usage line`); }); test("buildArgv: a row and a form's values to the words umtool is run with", () => { const look = verbRow("look"); assert.deepEqual(buildArgv(look, { project: "reports/basic-fixture", settings: "mode=basic\n\n deck.markerLayout=stagger " }), { ok: true, argv: ["look", "reports/basic-fixture", "mode=basic", "deck.markerLayout=stagger"], }); // The shape puts the project before the sub-verb; flags after the positionals. const insert = verbRow("timeline insert"); assert.deepEqual(buildArgv(insert, { project: "p", spec: "yt/abc@1-5", "--after": "-", "--lock": true, "--section": 2 }).argv, [ "timeline", "p", "insert", "yt/abc@1-5", "--after", "-", "--section", "2", "--lock", ]); // A repeated flag, flag pairs. assert.deepEqual(buildArgv(verbRow("look"), { project: "p", settings: ["a=1"], "--unset": ["render.rail", "render.title"] }).argv, [ "look", "p", "a=1", "--unset", "render.rail", "--unset", "render.title", ]); assert.deepEqual(buildArgv(verbRow("ledger set"), { project: "p", id: "r1", keys: "value=12\nflags=a|b" }).argv, ["ledger", "p", "set", "r1", "--value", "12", "--flags", "a|b"]); // A false boolean and an empty string are left out. assert.deepEqual(buildArgv(verbRow("show"), { project: "p" }).argv, ["show", "p"]); assert.deepEqual(buildArgv(verbRow("check"), { project: "", "--all-severities": false }).argv, ["check"]); }); test("buildArgv refuses what a form may not send", () => { const look = verbRow("look"); const no = (values, re, row = look) => { const r = buildArgv(row, values); assert.equal(r.ok, false, JSON.stringify(values)); assert.match(r.error, re); }; no({ project: "p" }, /settings is required/); no({ project: "p", settings: "mode=basic", argv: ["rm", "-rf"] }, /takes no "argv"/); no({ project: "--all", settings: "mode=basic" }, /may not start with "-"/); no({ project: "p", settings: "--json" }, /not key=value/); no({ project: "p", settings: "mode" }, /not key=value/); no({ project: "p", settings: "a=\0" }, /NUL/); no({ project: "p", settings: { a: 1 } }, /a string, a number/); no({ project: "p", clip: "c1", "--start": "soon" }, /a number/, verbRow("window")); no({ project: "p", clip: "c1", "--verdict": "maybe" }, /one of confirmed, incorrect/, verbRow("window")); no({ project: "p", "--patch-json": "{nope", "--id": "t" }, /not JSON/, verbRow("take")); }); test("an empty optional positional before a given one is refused (it would shift the words)", () => { const row = { verb: "x", args: [{ name: "a", type: "string" }, { name: "b", type: "string" }] }; const r = buildArgv(row, { b: "2" }); assert.equal(r.ok, false); assert.match(r.error, /a is needed before b/); // Negative numbers are values, not flags. assert.deepEqual(buildArgv(verbRow("window"), { project: "p", clip: "c1", "--start": "-0.5" }).argv, ["window", "p", "c1", "--start", "-0.5"]); }); test("cliLine: the exact line to paste, quoted for a shell", () => { assert.equal(cliLine(["look", "reports/basic-fixture", "mode=basic"]), "node umtool/bin/umtool.mjs look reports/basic-fixture mode=basic"); assert.equal(shellQuote("it's here"), `'it'\\''s here'`); assert.equal(shellQuote(""), "''"); assert.equal(shellQuote('deck.markers=[{"after":"c01"}]'), `'deck.markers=[{"after":"c01"}]'`); assert.equal(synopsis(verbRow("timeline move")), "timeline move --to N [--take TAKE]"); }); test("a form's flags are flags the CLI still parses (a renamed flag fails here)", () => { // Best effort: every `--flag` of a form row is a string literal somewhere in the CLI's parsers. A `--no-x` is // the negation idiom of `--x` (bin/umtool.mjs window); ledger takes any `--` of its schema. const files = [ ...readdirSync(`${UMTOOL}lib/report`).filter((f) => f.endsWith(".mjs") && !f.includes(".test.")).map((f) => `lib/report/${f}`), "bin/umtool.mjs", "bin/schedule.ts", "bin/refresh.ts", "bin/inbox.ts", "bin/model-log.ts", "lib/queue/cli.mjs", "lib/annotations/cli.mjs", "lib/phrase-finder/cli.mjs", "lib/ingredients/cli.mjs", ]; const src = files.map(read).join("\n"); const GENERIC = new Set(["ledger"]); const lost = []; for (const r of VERBS) { if (GENERIC.has(commandOf(r.verb))) continue; for (const a of r.args) { if (!a.name.startsWith("--")) continue; const lit = (n) => src.includes(`"${n}"`) || src.includes(`'${n}'`); const neg = a.name.startsWith("--no-") && lit(`--${a.name.slice(5)}`) && src.includes("`--no-${"); if (!lit(a.name) && !neg) lost.push(`${r.verb} ${a.name}`); } } assert.deepEqual(lost, [], "a form names a flag no CLI parser does: rename it in umtool/lib/cli/verbs.mjs"); }); test("no form writes or reads a file a page names freely: outputs are bare names, inputs are project files", () => { for (const r of VERBS.filter((x) => x.ui === "form")) { for (const a of r.args) { if (["--out", "--name", "--id", "--from", "--by", "--reel", "--folder", "--site"].includes(a.name) && a.type !== "project") { assert.ok(["name", "ref", "string", "number"].includes(a.type), `${r.verb} ${a.name}: ${a.type}`); } if (a.name === "--out") assert.equal(a.type, "name", `${r.verb} --out is a bare name, never a path`); if (a.type === "path") assert.ok(r.args.some((x) => x.name === "project" && x.type === "project"), `${r.verb}: a path arg needs the project it is inside`); if (/@file/.test(a.help ?? "")) assert.ok(a.atFile, `${r.verb} ${a.name} names @file: it refuses it from a form`); } } for (const v of ["vertical", "voice-match"]) assert.ok(!verbRow(v).args.some((a) => a.name === "--out"), `${v}: --out (a path) is a terminal's`); for (const [v, n] of [["take", "--patch"], ["trailer", "--beats"], ["modules apply", "--config"], ["candidates import", "file"], ["timeline groups import", "file"], ["posts narrate", "--recording"], ["takes make", "--recipe"]]) { assert.equal(verbRow(v).args.find((a) => a.name === n)?.type, "path", `${v} ${n} is a project file`); } }); test("names, paths, refs and @file: what a page may not send", () => { const no = (row, values, re) => { const r = buildArgv(row, values); assert.equal(r.ok, false, JSON.stringify(values)); assert.match(r.error, re); }; const trailer = verbRow("trailer"); for (const out of ["../x.mp4", "a/b.mp4", ".hidden", "/etc/x", "..", "x\\y"]) no(trailer, { project: "p", "--out": out }, /bare name|start with "-"/); assert.deepEqual(buildArgv(trailer, { project: "p", "--out": "teaser-2.mp4" }).argv, ["trailer", "p", "--out", "teaser-2.mp4"]); no(verbRow("take"), { project: "p", "--id": "../../evil" }, /bare name/); no(verbRow("take"), { project: "p", "--id": "t", "--patch": "@/etc/passwd" }, /no @/); no(verbRow("candidates add"), { project: "p", proposal: "@/etc/passwd" }, /terminal only/); no(verbRow("timeline teaser"), { project: "p", id: "t1", patch: "@x.json" }, /terminal only/); for (const o of ["/etc/passwd", "package.json", "@ids.txt", "../x"]) no(verbRow("timeline order"), { project: "p", order: o }, /not an entry's id|start with "-"|terminal only/); assert.deepEqual(buildArgv(verbRow("timeline order"), { project: "p", order: "c01\nx-1987\nt:2" }).argv, ["timeline", "p", "order", "c01", "x-1987", "t:2"]); // An @file reference anywhere a CLI splits a value (review): post-json:@…, a=@…, a,@…. for (const spec of ["post-json:@/etc/passwd", "post-json: @x.json", "@x", "post:@x"]) no(verbRow("timeline insert"), { project: "p", spec, "--after": "-" }, /terminal only/); for (const settings of ["a=b,@/etc/passwd", "deck.markers=@m.json", "x=1;@y", "chat='@f'"]) no(verbRow("look"), { project: "p", settings }, /terminal only/); no(verbRow("posts set-item"), { project: "p", item: "i1", settings: 'link.add= @/etc/passwd' }, /terminal only/); no(verbRow("timeline set-video"), { project: "p", id: "v1", settings: "src=@x" }, /terminal only/); // A person's words keep their @: a flag's value, free prose, a handle, a lexicon word, a pause at a take second. assert.ok(buildArgv(verbRow("timeline insert"), { project: "p", spec: "yt/abc@1-5", "--quote": "@grok said, @x", "--title": "@sam" }).ok, "/