commit 337a345ac315783e91d6793340c7ce091e744f1a
parent d4ae246ea06497f240c7daec7ba109787c47a3a2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 20:06:32 -0500
umtool: ⌘K forms name no file outside the project; no-undo verbs want confirm (L8a review)
An output is a bare name (arg type name: trailer --out, take ids, reels, --name); vertical and voice-match --out are terminal-only. An input file (type path: take --patch, trailer/vertical --beats, modules --config, takes make --recipe, voice-match --instances, clips --words, candidates import, timeline groups import, posts narrate --recording, posts avatar, add-video src) runs only when its realpath is inside the project's (lib/cli/confine.mjs), as that absolute path. @file is refused where a CLI reads it, a key=value value that is @..., /..., ~/... or climbs with .. is refused, new --from takes a URL or <channel>/<id> (type ref), timeline order takes ids only. A row's confirm ({what, when, unless}: prune --yes, pool prune, index --prune, takes freeze --apply, takes make/take --force, queue cancel, takes cancel, render-mode off --force, notes resolve/wontfix/reply --resolve, ledger rm, fetch --refetch, refresh --yes, speaker-check --remove, preset save --force) makes POST /api/cli answer 409 until confirm: true. A queued step asked again within 5 s is the one there; row.timeoutMin reaches the queue; a form's "false" is off. verbs.test.mjs also checks every form flag is one a CLI parser names.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 357 insertions(+), 82 deletions(-)
diff --git a/umtool/app/api/cli/route.ts b/umtool/app/api/cli/route.ts
@@ -1,10 +1,11 @@
import path from "node:path";
import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
-import { buildArgv, cliLine } from "@/lib/cli/argv.mjs";
+import { buildArgv, cliLine, confirmOf, pathArgsOf } from "@/lib/cli/argv.mjs";
+import { confineToProject } from "@/lib/cli/confine.mjs";
import { formVerbs, verbRow } from "@/lib/cli/verbs.mjs";
import { resolveProject } from "@/lib/projects/core.mjs";
import { resolveProjectPath } from "@/lib/projects";
-import { addStep, getStep, isQid, logFileOf, logTail } from "@/lib/queue/store.mjs";
+import { addStep, getStep, isQid, listSteps, logFileOf, logTail } from "@/lib/queue/store.mjs";
import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner";
import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
@@ -19,19 +20,25 @@ export const dynamic = "force-dynamic";
// pathname + search>, what the page is about -- { project, clip, post, take }
// GET ?job=<id>[&since=N] { job }: the app job a form started (lib/jobs.ts jobView, its log from N)
// GET ?qid=<qid> { step, log }: a queued form's step and its log's last lines
-// POST { verb, values } -> 202 { job, line } | 202 { queued: { qid }, line }
+// POST { verb, values, confirm? } -> 202 { job, line } | 202 { queued: { qid }, line }
// the row's args validated and built into argv HERE (lib/cli/argv.mjs);
// a row with `queue` (it renders, or holds the heavy slot) is added to the
// durable queue, any other runs as one job on the app's runner
-// | 400 not a form verb, a value its schema refuses, a raw argv
-// | 403 not this app's own page | 409 another job is running
+// | 400 not a form verb, a value its schema refuses, a raw argv, a path
+// outside the project | 409 a row with `confirm` sent without confirm: true
+// | 403 not this app's own page, or a host that is not this machine (DNS
+// rebinding: lib/report/sameOrigin.mjs, UMTOOL_ALLOWED_HOSTS) | 409 another job runs
+// The same queued command asked again within 5 s is the step already there.
//
// The page never sends argv: a body that carries one is refused, and app/api/queue/route.ts
// still refuses to add a step from a page. What runs is a registry row's argv, nothing else.
const headers = { "cache-control": "no-store" };
const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
-type Row = { verb: string; summary: string; ui: string; reason?: string; queue?: boolean; timeoutMin?: number; args: Array<{ name: string; type: string; context?: string }> };
+type Row = { verb: string; summary: string; ui: string; reason?: string; queue?: boolean; timeoutMin?: number; confirm?: { what: string } | null; args: Array<{ name: string; type: string; context?: string; pass?: string }> };
+
+/** A double Enter: the same command queued again this soon is the step already there. */
+const DEDUPE_MS = 5000;
/** The project, and the selection, a page's address is about. */
async function contextOf(raw: string | null) {
@@ -107,33 +114,64 @@ export async function POST(request: Request) {
if ("argv" in body || "args" in body || "cmd" in body || "command" in body) {
return Response.json({ error: "a raw command line is refused: name a verb of the registry and its values ({ verb, values })" }, { status: 400, headers });
}
- const extra = Object.keys(body).filter((k) => k !== "verb" && k !== "values");
- if (extra.length) return Response.json({ error: `unexpected ${extra.join(", ")}: the body is { verb, values }` }, { status: 400, headers });
+ const extra = Object.keys(body).filter((k) => k !== "verb" && k !== "values" && k !== "confirm");
+ if (extra.length) return Response.json({ error: `unexpected ${extra.join(", ")}: the body is { verb, values, confirm? }` }, { status: 400, headers });
const verb = typeof body.verb === "string" ? body.verb.trim() : "";
const row = verbRow(verb) as Row | null;
if (!row) return Response.json({ error: `no verb "${verb}" in the registry (umtool/lib/cli/verbs.mjs)` }, { status: 400, headers });
if (row.ui !== "form") return Response.json({ error: `umtool ${verb} has no form: ${row.reason}` }, { status: 400, headers });
const values = (body.values ?? {}) as Record<string, unknown>;
- const built = buildArgv(row, values);
- if (!built.ok) return Response.json({ error: built.error, field: built.field ?? null }, { status: 400, headers });
+ const pre = buildArgv(row, values);
+ if (!pre.ok) return Response.json({ error: pre.error, field: pre.field ?? null }, { status: 400, headers });
+ const confirmWhat = confirmOf(row, values);
+ if (confirmWhat && body.confirm !== true) {
+ return Response.json({ error: `this would ${confirmWhat}, with no undo: send it again with confirm: true`, confirm: confirmWhat }, { status: 409, headers });
+ }
// A project arg is one the CLI will find: said here, not as the job's first line.
let project: string | null = null;
+ let projectDir: string | null = null;
for (const a of row.args) {
const v = values[a.name];
if (a.type !== "project" || typeof v !== "string" || !v.trim()) continue;
- const r = (await resolveProject(v.trim())) as { project?: { id: string }; ambiguous?: unknown[] };
+ const r = (await resolveProject(v.trim())) as { project?: { id: string; dir: string }; ambiguous?: unknown[] };
if (r.ambiguous) return Response.json({ error: `"${v}" is the name of ${r.ambiguous.length} projects — give its id`, field: a.name }, { status: 400, headers });
if (!r.project) return Response.json({ error: `no project matches "${v}"`, field: a.name }, { status: 400, headers });
- if (a.name === "project") project = r.project.id;
+ if (a.name === "project") {
+ project = r.project.id;
+ projectDir = r.project.dir;
+ }
+ }
+ // A file a form names is a file of THE project, by its realpath; it runs as that absolute path
+ // (a row whose CLI joins it to the project itself: as typed).
+ const run: Record<string, unknown> = { ...values };
+ for (const a of pathArgsOf(row, values) as Row["args"]) {
+ if (!projectDir) return Response.json({ error: `${a.name}: a file names a project's file -- name the project`, field: a.name }, { status: 400, headers });
+ const c = await confineToProject(projectDir, String(values[a.name]));
+ if (!c.ok) return Response.json({ error: `${a.name}: ${c.error}`, field: a.name }, { status: 400, headers });
+ if (a.pass !== "relative") run[a.name] = c.abs;
}
+ const built = buildArgv(row, run);
+ if (!built.ok) return Response.json({ error: built.error, field: built.field ?? null }, { status: 400, headers });
const take = row.args.filter((a) => a.context === "take").map((a) => values[a.name]).find((v): v is string => typeof v === "string" && !!v.trim()) ?? null;
const line = cliLine(built.argv);
const label = `⌘K: umtool ${built.argv.join(" ")}`.slice(0, 160);
if (row.queue) {
try {
- const step = (await addStep(queueDir(), { argv: built.argv, label, by: "the umtool app (⌘K)", cwd: UMTOOL_DIR, target: project ? { project, take } : null })) as { qid: string };
+ const same = JSON.stringify(built.argv);
+ const recent = ((await listSteps(queueDir())) as Array<{ qid: string; argv: string[]; state: string; createdAt: string; by?: string }>).find(
+ (s) => (s.state === "queued" || s.state === "running") && JSON.stringify(s.argv) === same && Date.now() - Date.parse(s.createdAt) < DEDUPE_MS,
+ );
+ if (recent) return Response.json({ ok: true, queued: { qid: recent.qid }, deduped: true, line, queue: queueRunnerStatus() }, { status: 200, headers });
+ const step = (await addStep(queueDir(), {
+ argv: built.argv,
+ label,
+ by: "the umtool app (⌘K)",
+ cwd: UMTOOL_DIR,
+ target: project ? { project, take } : null,
+ ...(row.timeoutMin ? { timeoutMin: row.timeoutMin } : {}),
+ })) as { qid: string };
kickQueue();
return Response.json({ ok: true, queued: { qid: step.qid }, line, queue: queueRunnerStatus() }, { status: 202, headers });
} catch (e) {
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -156,8 +156,8 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `check [<project>] [--all-severities]` | what blocks a build (exit 1 on anything blocking) | form · *project* |
| `links <project> [--fix]` | do the clip QRs open on their sites (out/links.json) | form · *project* |
| `cast ls` | the characters' voices across projects | form · *corpus* |
-| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--avatar AVATAR] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
-| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--avatar AVATAR] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
+| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
+| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
| `cast rm <id>` | a character out of the cast (an undo point) | form · *corpus* |
| `cast undo` | the cast as it was before its last write | form · *corpus* |
| `cast project <project>` | the project's characters, their voices and drift | form · *project* |
@@ -242,7 +242,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* |
| `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* |
| `trailer <project> [--take TAKE] [--reel REEL] [--beats BEATS] [--beats-json JSON] [--intro] [--finale N] [--xfade N] [--no-snap] [--out OUT] [--dry-run] [--candidates] [--vertical] [--layout reframe]` | a trailer or beat reel cut from a take's master | form · queued · *project* |
-| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--out OUT] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro]` | a vertical short (1080x1920) of a take's items | form · queued · *project* |
+| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro]` | a vertical short (1080x1920) of a take's items | form · queued · *project* |
| `trailer-beats <project> ls [--reel REEL]` | a reel's beats against its limit | form · *project* |
| `trailer-beats <project> add <clip> [<span>] [--at N] [--label LABEL] [--take TAKE] [--reel REEL]` | a clip beat | form · *project* |
| `trailer-beats <project> add-raw <at> <dur> [--at N] [--label LABEL] [--reel REEL]` | a beat of master seconds | form · *project* |
@@ -282,7 +282,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `prune [<project>] [--all] [--take TAKE] [--anyway] [--keep N] [--older-than OLDER-THAN] [--idle-work IDLE-WORK] [--versions] [--idle IDLE] [--grace GRACE] [--yes]` | takes' work files freed by policy (a dry run unless --yes) | form · *project* |
| `fallback <project> [--dry-run] [--clip CLIP…] [--restore RESTORE]` | stand-ins for refused montage windows | form · *draft* |
| `phrases <phrases>… --channels CHANNELS [--prefer PREFER] [--exclude EXCLUDE] [--words] [--regex] [--samples N] [--no-cache] [--full]` | how often each phrase was said, by year | form · *corpus* |
-| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video REFERENCE-VIDEO…] [--reference-channel REFERENCE-CHANNEL…] [--instances INSTANCES] [--span phrase\|cut] [--pad N] [--likely N] [--unlikely N] [--out OUT] [--dry]` | a speaker-similarity score per montage clip | form · queued · *project* |
+| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video REFERENCE-VIDEO…] [--reference-channel REFERENCE-CHANNEL…] [--instances INSTANCES] [--span phrase\|cut] [--pad N] [--likely N] [--unlikely N] [--dry]` | a speaker-similarity score per montage clip | form · queued · *project* |
| `clips analyze <project> [--from FROM] [--rescan] [--no-laughs] [--no-voices] [--target N] [--laugh-min N] [--merge-gap N] [--setup-max N] [--clip-max N] [--words WORDS] [--keep-cut] [--scope SCOPE] [--segment SEGMENT]` | the clip finder's scans on a long recording, then proposals | form · queued · *draft* |
| `clips propose <project> [--from FROM] [--host N] [--target N] [--laugh-min N] [--merge-gap N] [--setup-max N] [--clip-max N] [--words WORDS] [--keep-cut] [--dry]` | the clip finder's proposals again, from what is there | form · *draft* |
| `clips show <project>` | the speakers, the laughs, what is in the cut | form · *project* |
diff --git a/umtool/lib/cli/argv.mjs b/umtool/lib/cli/argv.mjs
@@ -15,6 +15,12 @@ const LIST_MAX = 200;
const PAIR_KEY = /^[A-Za-z_*][\w.*[\]<>-]*$/;
const FLAG_KEY = /^[A-Za-z][\w-]*$/;
const NUMBER = /^-?(\d+\.?\d*|\.\d+)$/;
+/** A bare file or id name: no directory, no `..`, no leading dot (`--out`, a take's id, a reel's name). */
+const BARE = /^[A-Za-z0-9_][\w.+-]*$/;
+/** A `..` segment, a home or an absolute path inside a value: a page may not name a path outside the project. */
+const ESCAPES = /(^|[\\/])\.\.([\\/]|$)|^~[\\/]|^[\\/]/;
+/** A share URL or a <channel>/<id> (`new --from` from a page: never a file). */
+const REF = /^(https?:\/\/\S+|[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9_-]+)$/;
const isFlag = (a) => a.name.startsWith("--");
const isRun = (a) => a.type === "list" || a.type === "pairs" || a.type === "flagpairs";
@@ -29,6 +35,7 @@ function linesOf(v) {
/** Whether a form value is empty (left out of argv). */
function absent(a, v) {
if (v === undefined || v === null || v === false) return true;
+ if (a.type === "boolean" && (v === "false" || v === "off" || v === "")) return true;
if (typeof v === "string") return a.type === "text" ? v.trim() === "" : v.trim() === "";
if (Array.isArray(v)) return v.length === 0 || (isRun(a) && linesOf(v).length === 0);
return false;
@@ -49,6 +56,38 @@ function word(a, raw, { what = a.name, max = STRING_MAX } = {}) {
// `-` alone is a value (`--after -`); a negative number is a value; anything else that starts with a
// dash would be read as a flag by umtool's parsers.
if (/^-./.test(s) && !NUMBER.test(s.trim())) throw new FormError(`${what}: a value may not start with "-" (it would be read as a flag)`, a.name);
+ // `@file` reads a file wherever it is: a terminal's, never a form's (paste what the file holds).
+ if (a.atFile && s.startsWith("@")) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name);
+ return s;
+}
+
+/** A bare name: one word, no directory. */
+function bare(a, raw, what = a.name) {
+ const s = word(a, String(raw).trim(), { what });
+ if (!BARE.test(s) || s.includes("..")) throw new FormError(`${what}: a bare name (letters, digits, . _ - +; no directory, no leading dot)`, a.name);
+ return s;
+}
+
+/** A key=value value from a page: never `@file`, never a path out of the project. */
+function pairValue(a, value, what) {
+ const v = value.trim().replace(/^['"]/, "");
+ if (v.startsWith("@")) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name);
+ if (ESCAPES.test(v)) throw new FormError(`${what}: a path outside the project (.., ~ or /) -- from a terminal only`, a.name);
+ return value;
+}
+
+/** One key=value word. */
+function pairWord(a, line) {
+ const at = line.indexOf("=");
+ const key = at > 0 ? line.slice(0, at).trim() : "";
+ if (!PAIR_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name);
+ return word(a, `${key}=${pairValue(a, line.slice(at + 1), key)}`, { max: TEXT_MAX });
+}
+
+/** A share URL or a <channel>/<id>: never a file. */
+function refWord(a, raw) {
+ const s = word(a, raw);
+ if (!REF.test(s)) throw new FormError(`${a.name}: a share URL or <channel>/<id> (a file only from a terminal)`, a.name);
return s;
}
@@ -84,6 +123,19 @@ function wordsOf(a, v) {
case "project":
case "string":
return [...flag, word(a, String(v).trim())];
+ case "name":
+ if (a.literals?.includes(String(v).trim())) return [...flag, String(v).trim()];
+ return [...flag, bare(a, v)];
+ case "path": {
+ // A file of the project, relative to its directory. The SERVER confines it (realpath inside the
+ // project: app/api/cli/route.ts) and runs it as the absolute path it found; here it is one word.
+ const s = word(a, String(v).trim());
+ if (a.literals?.includes(s)) return [...flag, s];
+ if (s.startsWith("@")) throw new FormError(`${a.name}: a file of the project, by its path (no @)`, a.name);
+ return [...flag, s];
+ }
+ case "ref":
+ return [...flag, refWord(a, String(v).trim())];
case "list":
case "pairs":
case "flagpairs": {
@@ -93,18 +145,17 @@ function wordsOf(a, v) {
const out = [];
for (const line of lines) {
if (a.type === "list") {
- const w = word(a, line);
+ const w = a.item === "name" ? bare(a, line) : a.item === "pair" ? pairWord(a, line) : a.item === "ref" ? refWord(a, line) : word(a, line);
out.push(...(isFlag(a) ? [a.name, w] : [w]));
continue;
}
const at = line.indexOf("=");
const key = at > 0 ? line.slice(0, at).trim() : "";
if (a.type === "pairs") {
- if (!PAIR_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name);
- out.push(word(a, `${key}=${line.slice(at + 1)}`, { max: TEXT_MAX }));
+ out.push(pairWord(a, line));
} else {
if (!FLAG_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name);
- out.push(`--${key}`, word(a, line.slice(at + 1).trim(), { what: `--${key}`, max: TEXT_MAX }));
+ out.push(`--${key}`, word(a, pairValue(a, line.slice(at + 1).trim(), `--${key}`), { what: `--${key}`, max: TEXT_MAX }));
}
}
return out;
@@ -204,3 +255,27 @@ export function synopsis(row) {
});
return [...head, ...positionals.filter((a) => !placed.has(a.name)).map(one), ...args.filter(isFlag).map(one)].join(" ");
}
+
+/**
+ * Whether these values make the row do something with no undo (a row's `confirm`): the sentence to
+ * confirm with, or null. `confirm: { what, when?: [arg names, any of them given], unless?: [arg names] }`;
+ * no `when`: always.
+ * @returns {string | null}
+ */
+export function confirmOf(row, values = {}) {
+ const c = row.confirm;
+ if (!c) return null;
+ const args = row.args ?? [];
+ const given = (name) => {
+ const a = args.find((x) => x.name === name);
+ return !!a && !absent(a, values?.[name]);
+ };
+ if (c.unless?.some(given)) return null;
+ if (c.when && !c.when.some(given)) return null;
+ return c.what;
+}
+
+/** The row's path args a page gave: the server confines each. */
+export function pathArgsOf(row, values = {}) {
+ return (row.args ?? []).filter((a) => a.type === "path" && !absent(a, values?.[a.name]) && !a.literals?.includes(String(values[a.name]).trim()));
+}
diff --git a/umtool/lib/cli/confine.mjs b/umtool/lib/cli/confine.mjs
@@ -0,0 +1,40 @@
+// A PATH A PAGE NAMED, KEPT INSIDE THE PROJECT (lane palette L8a, review):
+// POST /api/cli runs a registry row's `path` arg (lib/cli/verbs.mjs) only
+// when it is a file of the project the form names -- relative to the
+// project's directory, its REALPATH (every symlink followed, the project's
+// own too) inside the project's realpath. What runs is that absolute path, so
+// the CLI's own resolution (most of them path.resolve() from their cwd) cannot
+// put it anywhere else; a row whose CLI takes it relative to the project
+// (`pass: "relative"`) gets the path as typed, checked the same way.
+//
+// The refusal names the arg and never what the file holds.
+import { realpath, stat } from "node:fs/promises";
+import path from "node:path";
+
+/**
+ * @param {string} projectDir
+ * @param {string} value what the form gave
+ * @returns {Promise<{ ok: true, abs: string } | { ok: false, error: string }>}
+ */
+export async function confineToProject(projectDir, value) {
+ const v = String(value ?? "").trim();
+ if (!v) return { ok: false, error: "no file named" };
+ if (v.includes("\0")) return { ok: false, error: "a NUL byte" };
+ let root;
+ try {
+ root = await realpath(/* turbopackIgnore: true */ projectDir);
+ } catch {
+ return { ok: false, error: "the project's directory is not there" };
+ }
+ const wanted = path.resolve(/* turbopackIgnore: true */ projectDir, v);
+ let real;
+ try {
+ real = await realpath(/* turbopackIgnore: true */ wanted);
+ } catch {
+ return { ok: false, error: `${v}: no such file in the project` };
+ }
+ if (real !== root && !real.startsWith(root + path.sep)) return { ok: false, error: `${v}: not a file of the project (a form may only name files inside it)` };
+ const st = await stat(/* turbopackIgnore: true */ real).catch(() => null);
+ if (!st?.isFile()) return { ok: false, error: `${v}: not a file` };
+ return { ok: true, abs: real };
+}
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -21,7 +21,10 @@
// words, then every positional in order. Positionals the shape leaves out follow it.
// queue true: it renders (or holds the heavy slot) -- POST /api/cli adds it to the durable
// queue (lib/queue/store.mjs), never the app's one-job runner
-// timeoutMin a job's time limit (default 15; lib/jobs.ts)
+// timeoutMin a job's (or a queued step's) time limit, minutes (default 15 for a job, the queue's 12 h)
+// confirm { what, when?, unless? }: it does something with no undo point (deletes, evicts, kills):
+// the form asks a second press ("Yes, <what>") and POST /api/cli wants `confirm: true`;
+// `when` the arg names that make it so (any given), `unless` those that make it a dry run
//
// An arg: { name, type, required?, choices?, default?, help?, repeat?, context? }
// name "--flag" is a flag; anything else is a positional
@@ -32,6 +35,13 @@
// pairs key=value lines, each one argv word (a positional run)
// flagpairs key=value lines, each `--key value`
// list several values: a positional run, or (`repeat`) the flag once per value
+// (`item: "name"` each a bare name; `item: "pair"` each key=value; `item: "ref"` each a ref)
+// name a bare name: no directory, no `..`, no leading dot (`--out`, a take's id, a reel)
+// path a file of the project, relative to its directory: POST /api/cli runs it only when
+// its realpath is inside the project's, as that absolute path (`pass: "relative"`: as typed)
+// ref a share URL or <channel>/<id>, never a file (`new --from`)
+// literals values a name or path arg also takes as words ("none", "off")
+// atFile the CLI reads `@file` here: a form may not (the file could be anywhere)
// context "clip" | "post" | "take": filled from the page's selection (its URL: /clip/<id>,
// /post/<id>, /takes/<id>, ?clip=, ?take=)
//
@@ -55,11 +65,13 @@ const pairs = (o = {}) => ({ name: "settings", type: "pairs", required: true, he
const many = (name, o = {}) => ({ name, type: "list", ...o });
const clip = (o = {}) => arg("clip", { context: "clip", help: "the clip's id", ...o });
const item = (o = {}) => arg("item", { context: "post", help: "the post item's id (or its post's)", ...o });
-const takeOpt = (o = {}) => opt("--take", { context: "take", help: "a take of the project: the edit lands in its patch", ...o });
-const takeArg = (o = {}) => arg("take", { context: "take", help: "the take's id", ...o });
-const inTake = () => opt("--in-take", { context: "take", help: "a take of the project: the edit lands in its patch" });
+const takeOpt = (o = {}) => opt("--take", { type: "name", context: "take", help: "a take of the project: the edit lands in its patch", ...o });
+const takeArg = (o = {}) => arg("take", { type: "name", context: "take", help: "the take's id", ...o });
+const inTake = () => opt("--in-take", { type: "name", context: "take", help: "a take of the project: the edit lands in its patch" });
+const name = (n, o = {}) => ({ name: n, type: "name", ...(n.startsWith("--") ? {} : { required: true }), ...o });
+const file = (n, o = {}) => ({ name: n, type: "path", ...(n.startsWith("--") ? {} : { required: true }), help: "a file of the project, relative to its directory", ...o });
const dry = () => bool("--dry-run", "say what it would do; change nothing");
-const reel = () => opt("--reel", { help: "that beat reel (promo/<name>-beats.json); default the trailer" });
+const reel = () => opt("--reel", { type: "name", help: "that beat reel (promo/<name>-beats.json); default the trailer" });
const window_ = () => [num("--at", { help: "the window's start, s" }), num("--dur", { help: "the window's length, s" }), bool("--full", "the whole cut")];
// ---- the rows -------------------------------------------------------------------
@@ -87,11 +99,11 @@ export const VERBS = Object.freeze([
form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
form("cast add", "corpus", "a character: name, stock voice, handles", [
arg("id"), opt("--name", { required: true }), opt("--voice", { required: true, help: "engine:voice" }), opt("--handles", { help: "a,b" }), opt("--speakers", { help: "Name,…" }),
- pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--avatar"), opt("--note"), bool("--narrator", "the recordings' default character"),
+ pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--note"), bool("--narrator", "the recordings' default character"),
]),
form("cast set", "corpus", "change a character", [
arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice"),
- opt("--avatar"), opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
+ opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
]),
form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]),
form("cast undo", "corpus", "the cast as it was before its last write", []),
@@ -106,7 +118,7 @@ export const VERBS = Object.freeze([
form("speaker-check", "project", "which named voice each clip is (speaker-check.json)", [
project(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every clip)" }), bool("--list", "list the named voices"),
opt("--set", { help: "Name=<clip>,<channel>/<id>,channel:<slug>" }), opt("--remove", { help: "a voice's name" }),
- ], Q),
+ ], { ...Q, confirm: { what: "remove that named voice from speakers.json", when: ["--remove"] } }),
form("quote-check", "project", "is each clip's quote in the seconds it plays", [project(), opt("--clips", { help: "a,b (none: every clip)" }), num("--pad"), bool("--status", "the rows as they stand")], Q),
form("check-joins", "project", "do a rendered take's post joins carry on", [project(), takeOpt({ required: true, help: "the rendered take" }), bool("--all", "every post-to-post boundary"), num("--limit")], Q),
form("link-policy", "draft", "cite via site X, these channels direct", [
@@ -146,11 +158,11 @@ export const VERBS = Object.freeze([
arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"),
opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"),
], Q),
- form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })]),
+ form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })], { confirm: { what: "prune the index's rows of projects no longer on disk", when: ["--prune"] } }),
form("new", "corpus", "a new project (scaffold)", [
- arg("slug", { help: "<slug> or <folder>/<slug>" }), opt("--folder"), opt("--from", { help: "a report.md, a share URL or <channel>/<id>" }), opt("--site-origin"),
+ arg("slug", { help: "<slug> or <folder>/<slug>" }), opt("--folder"), opt("--from", { type: "ref", help: "a share URL or <channel>/<id> (a report.md: from a terminal)" }), opt("--site-origin"),
pick("--seed", ["chapters", "frames", "phrase", "reactions"]), num("--target", { help: "s" }), opt("--phrase", { help: "a regex (--seed phrase)" }), opt("--channels", { help: "a,b" }),
- opt("--prefer"), opt("--exclude"), num("--max"), opt("--from-posts", { help: "a posts channel: a posts reel" }), opt("--brand"),
+ opt("--prefer"), opt("--exclude"), num("--max"), opt("--from-posts", { type: "name", help: "a posts channel: a posts reel" }), name("--brand"),
], { timeoutMin: 30 }),
form("doctor", "corpus", "the tools and the roots on this machine", []),
form("storage status", "corpus", "where each project's out/ lives", [project({ required: false })]),
@@ -167,71 +179,71 @@ export const VERBS = Object.freeze([
// ---- notes ----
form("notes", "corpus", "the operator's notes, as markdown", [arg("target", { required: false, help: "<site>/<report> or a project" }), bool("--all"), bool("--resolved"), bool("--all-status")]),
- form("notes reply", "corpus", "answer a note", [arg("id"), arg("text", { type: "text" }), bool("--resolve")]),
- form("notes resolve", "corpus", "a note resolved", [arg("id")]),
- form("notes wontfix", "corpus", "a note closed as won't fix", [arg("id")]),
+ form("notes reply", "corpus", "answer a note", [arg("id"), arg("text", { type: "text" }), bool("--resolve")], { confirm: { what: "answer the note and resolve it", when: ["--resolve"] } }),
+ form("notes resolve", "corpus", "a note resolved", [arg("id")], { confirm: { what: "resolve the operator's note" } }),
+ form("notes wontfix", "corpus", "a note closed as won't fix", [arg("id")], { confirm: { what: "close the operator's note as won't fix" } }),
form("notes reopen", "corpus", "a note open again", [arg("id")]),
form("notes source", "corpus", "the source a target's notes name (the draft to edit)", [arg("target", { help: "<site>/<report>" }), opt("--draft"), opt("--generator"), opt("--how")]),
// ---- modules, presets ----
form("modules list", "corpus", "the video modules", []),
form("modules apply", "draft", "a module-config.json onto the cut, or as a take's patch", [
- project(), opt("--config"), dry(), takeOpt({ help: "made as that take (rendered) instead" }), opt("--label"), ...window_(), bool("--quick"), bool("--force"), opt("--from"),
+ project(), file("--config"), dry(), takeOpt({ help: "made as that take (rendered) instead" }), opt("--label"), ...window_(), bool("--quick"), bool("--force"), name("--from"),
], Q),
form("preset list", "corpus", "the look presets", []),
- form("preset show", "corpus", "one look preset", [arg("name")]),
- form("preset save", "corpus", "a project's look as a preset", [arg("name"), project({ name: "--from" }), opt("--description"), bool("--force")]),
- form("preset apply", "draft", "a preset under the cut (none: off it)", [arg("name", { help: "a preset, or none" }), project(), bool("--replace", "clear the manifest's own values of its keys")]),
+ form("preset show", "corpus", "one look preset", [name("name")]),
+ form("preset save", "corpus", "a project's look as a preset", [name("name"), project({ name: "--from" }), opt("--description"), bool("--force")], { confirm: { what: "overwrite the preset of that name", when: ["--force"] } }),
+ form("preset apply", "draft", "a preset under the cut (none: off it)", [name("name", { help: "a preset, or none" }), project(), bool("--replace", "clear the manifest's own values of its keys")]),
// ---- takes ----
form("take", "project", "one take: rendered, drafted, previewed or promoted", [
- project(), opt("--id", { required: true, context: "take", help: "the take's id" }), opt("--label"), opt("--group"), pick("--kind", ["similar", "different"]), opt("--summary"),
- opt("--style"), opt("--patch", { help: "a patch file" }), opt("--patch-json", { type: "json" }), many("--set", { repeat: true, help: "path=value, one per line" }), opt("--effect"),
- ...window_(), bool("--quick"), bool("--force"), opt("--from", { help: "a take whose built parts it reuses" }), bool("--keep-frames"), bool("--priority", "render mode for its lifetime"), bool("--uncensored"),
+ project(), name("--id", { required: true, context: "take", help: "the take's id" }), opt("--label"), opt("--group"), pick("--kind", ["similar", "different"]), opt("--summary"),
+ opt("--style"), file("--patch", { help: "a patch file of the project" }), opt("--patch-json", { type: "json" }), many("--set", { repeat: true, item: "pair", help: "path=value, one per line" }), opt("--effect"),
+ ...window_(), bool("--quick"), bool("--force", "make it again over the take there"), name("--from", { help: "a take whose built parts it reuses" }), bool("--keep-frames"), bool("--priority", "render mode for its lifetime"), bool("--uncensored"),
bool("--draft", "record it, render nothing"), bool("--rebuild"), bool("--preview"), bool("--changes"), num("--pad"), bool("--no-preview"),
bool("--promote", "make this take the cut"), bool("--anyway"),
many("--import-item", { repeat: true, help: "<project>:<item>[,<item>…], one per line" }), opt("--after"), opt("--before"), opt("--as"), dry(),
- ], Q),
+ ], { ...Q, confirm: { what: "make the take again over the one there", when: ["--force"] } }),
form("lint", "project", "the manifest lint a build runs first", [project(), takeOpt({ help: "a take's manifest" }), pick("--variant", ["sourced", "full"]), bool("--final")]),
- form("take status", "project", "a take's render record", [project(), opt("--id", { context: "take" }), bool("--log"), num("--tail")]),
+ form("take status", "project", "a take's render record", [project(), name("--id", { context: "take" }), bool("--log"), num("--tail")]),
none("queue add", "corpus", "a step of the durable queue: a umtool command's argv", "takes a raw argv -- a page never sends one (app/api/queue/route.ts); a form's Run on a heavy verb queues the step itself"),
form("queue ls", "corpus", "the queue's steps and its runner", [bool("--all")]),
form("queue status", "corpus", "one step: state, exit code, error, log", [arg("qid")]),
none("queue wait", "corpus", "wait for a step to finish", "blocks a terminal until a step ends: a form's Run follows its own step"),
form("queue log", "corpus", "a step's full log", [arg("qid"), num("--tail")]),
- form("queue cancel", "corpus", "a step cancelled (a running one stopped)", [arg("qid")]),
+ form("queue cancel", "corpus", "a step cancelled (a running one stopped)", [arg("qid")], { confirm: { what: "cancel the step (a running one is killed)" } }),
form("queue retry", "corpus", "a failed or cancelled step back in the queue", [arg("qid")]),
form("jobs", "corpus", "every running and recent render, step and app job", []),
form("takes make", "project", "a recipe's takes, or one per montage style", [
- project(), opt("--recipe"), opt("--only", { help: "ID,ID" }), bool("--force"), bool("--all-styles"), opt("--group"), ...window_(), bool("--quick"), bool("--priority"),
- ], Q),
+ project(), file("--recipe"), opt("--only", { help: "ID,ID" }), bool("--force", "make again the takes that exist"), bool("--all-styles"), opt("--group"), ...window_(), bool("--quick"), bool("--priority"),
+ ], { ...Q, confirm: { what: "render again over the takes that exist", when: ["--force"] } }),
form("takes styles", "corpus", "the montage styles", []),
form("takes pick", "project", "use this take: its manifest over the project's", [project(), takeArg(), bool("--anyway"), bool("--pin"), bool("--unpin")]),
form("takes effects", "project", "the overlay effects this cut offers", [project()]),
form("takes ls", "project", "the working cut, then each take", [project()]),
form("takes relabel", "project", "a take's label", [project(), takeArg(), arg("label")]),
- form("takes supersede", "project", "a take folded away in the list (or back)", [project(), takeArg(), opt("--by"), bool("--clear")]),
+ form("takes supersede", "project", "a take folded away in the list (or back)", [project(), takeArg(), name("--by"), bool("--clear")]),
form("takes save", "project", "the working draft frozen as the next version (v<N>)", [project(), opt("--label"), bool("--force", "save even with no edits since its parent")]),
form("takes open", "draft", "a saved version into the draft (the draft saved first)", [project(), takeArg({ help: "the version (or take) to open" })]),
- form("takes freeze", "project", "legacy takes given a frozen base (a dry run unless --apply)", [project(), many("takes", { help: "take ids, one per line (none: --all)" }), bool("--all"), bool("--apply", "write them (else a dry run)")]),
+ form("takes freeze", "project", "legacy takes given a frozen base (a dry run unless --apply)", [project(), many("takes", { item: "name", help: "take ids, one per line (none: --all)" }), bool("--all"), bool("--apply", "write them (else a dry run)")], { confirm: { what: "write each legacy take's frozen base (how it resolves can change)", when: ["--apply"] } }),
none("takes delete", "project", "a take's directory, whole", "deletes a take's directory whole, past undo: the Takes panel's Delete asks first; a terminal's --dry-run shows what goes"),
- form("takes cancel", "project", "stop a take's render", [project(), takeArg()]),
- form("takes fork", "project", "the take as a variant project beside this one", [project(), takeArg(), opt("--name")]),
+ form("takes cancel", "project", "stop a take's render", [project(), takeArg()], { confirm: { what: "stop the take's render (killed, marked cancelled)" } }),
+ form("takes fork", "project", "the take as a variant project beside this one", [project(), takeArg(), name("--name")]),
form("takes compare", "project", "two takes side by side", [project(), arg("a", { help: "<take> or <project>:<take>" }), arg("b")]),
form("render-mode on", "corpus", "render mode: a render gets the machine, for a window", [opt("--for", { help: "90m, 2h (default 2h)" }), opt("--note")]),
- form("render-mode off", "corpus", "render mode off", [bool("--force")]),
+ form("render-mode off", "corpus", "render mode off", [bool("--force", "even while a render holds it")], { confirm: { what: "take render mode from the render that holds it", when: ["--force"] } }),
form("render-mode status", "corpus", "is render mode on, for what, until when", []),
form("pool stats", "corpus", "the render pool: what it holds", [opt("--since", { help: "7d" })], { shape: "pool stats" }),
- form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()]),
+ form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()], { confirm: { what: "delete render pool files past the cap", unless: ["--dry-run"] } }),
form("pool verify", "corpus", "the render pool's files checked", [num("--sample"), bool("--all")], Q),
form("trailer", "project", "a trailer or beat reel cut from a take's master", [
- project(), takeOpt({ help: "the take whose master it is cut from" }), reel(), opt("--beats", { help: "a beats file" }), opt("--beats-json", { type: "json" }),
- bool("--intro"), num("--finale", { help: "s" }), num("--xfade"), bool("--no-snap"), opt("--out"), dry(), bool("--candidates", "the walk's ★ clips as beats (prints)"), bool("--vertical"), pick("--layout", ["reframe"]),
+ project(), takeOpt({ help: "the take whose master it is cut from" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--beats-json", { type: "json" }),
+ bool("--intro"), num("--finale", { help: "s" }), num("--xfade"), bool("--no-snap"), name("--out", { help: "a file name, written in the take's out/" }), dry(), bool("--candidates", "the walk's ★ clips as beats (prints)"), bool("--vertical"), pick("--layout", ["reframe"]),
], Q),
form("vertical", "project", "a vertical short (1080x1920) of a take's items", [
- project(), takeOpt({ required: true, help: "the take" }), reel(), opt("--beats"), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]),
+ project(), takeOpt({ required: true, help: "the take" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]),
pick("--side", ["split", "overlay"]), opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), num("--max"),
- opt("--name"), opt("--out"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"),
+ name("--name"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"),
], Q),
// ---- the trailer's beats ----
@@ -244,7 +256,7 @@ export const VERBS = Object.freeze([
{ name: "more", type: "flagpairs", help: "any other key=value, one per line (each --key value)" },
], { shape: "ledger <project> add <id>" }),
form("ledger set", "draft", "a ledger row's keys", [project(), arg("id"), { name: "keys", type: "flagpairs", required: true, help: "key=value, one per line (each --key value; null clears)" }, opt("--unset", { help: "k,k" })], { shape: "ledger <project> set <id>" }),
- form("ledger rm", "draft", "a ledger row removed (refused while something names it)", [project(), arg("id")], { shape: "ledger <project> rm <id>" }),
+ form("ledger rm", "draft", "a ledger row removed (refused while something names it)", [project(), arg("id")], { shape: "ledger <project> rm <id>", confirm: { what: "remove the ledger row" } }),
form("measure", "project", "the measure slice the instruments draw from", [project(), takeOpt({ help: "that take's built seconds" }), opt("--scopes", { help: "a,b" }), opt("--scale", { help: "MIN-MAX" }), opt("--as-of", { help: "YYYY-MM-DD" })]),
form("rulings show", "project", "each montage clip and its ruling", [project()], { shape: "rulings <project> show" }),
form("rulings import", "draft", "the earlier rulings in the seed's edits.json", [project(), dry()], { shape: "rulings <project> import" }),
@@ -253,28 +265,28 @@ export const VERBS = Object.freeze([
form("fetch", "project", "the clip windows, asked of the editor", [
project(), dry(), bool("--wait", "follow the editor's jobs"), bool("--status", "the last run's jobs"), bool("--body", "print the request body"), opt("--reason"),
opt("--refetch", { help: "clipId,clipId: evict those windows first" }), opt("--refetch-video", { help: "<slug>/<id>" }), takeOpt({ help: "a take's clips" }),
- ], { timeoutMin: 60 }),
+ ], { timeoutMin: 60, confirm: { what: "evict those cached windows, then fetch them again", when: ["--refetch", "--refetch-video"], unless: ["--dry-run"] } }),
form("prep", "project", "the bench's excerpts and waveforms, before the walk", [project(), opt("--clips", { help: "a,b" }), bool("--wait", "here, until done"), bool("--status"), takeOpt()], Q),
form("prune", "project", "takes' work files freed by policy (a dry run unless --yes)", [
project({ required: false, help: "one project (none: --all)" }), bool("--all"), opt("--take", { help: "X[,Y]" }), bool("--anyway"), num("--keep"), opt("--older-than", { help: "3d" }), opt("--idle-work", { help: "3d" }),
bool("--versions", "whole superseded takes"), opt("--idle"), opt("--grace"), bool("--yes", "free them (else a dry run)"),
- ]),
+ ], { confirm: { what: "delete those work files (--versions: whole superseded takes)", when: ["--yes"] } }),
form("fallback", "draft", "stand-ins for refused montage windows", [project(), dry(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every candidate)" }), opt("--restore", { help: "a switched clip's id" })]),
form("phrases", "corpus", "how often each phrase was said, by year", [
many("phrases", { required: true, help: "one phrase per line" }), opt("--channels", { required: true, help: "a,b" }), opt("--prefer"), opt("--exclude", { help: "a regex" }),
bool("--words"), bool("--regex"), num("--samples"), bool("--no-cache"), bool("--full"),
], { timeoutMin: 30 }),
form("voice-match", "project", "a speaker-similarity score per montage clip", [
- project(), pick("--reference", ["auto", "rulings", "recordings"]), many("--reference-video", { repeat: true, help: "<channel>/<id>, one per line" }), many("--reference-channel", { repeat: true }),
- opt("--instances"), pick("--span", ["phrase", "cut"]), num("--pad"), num("--likely"), num("--unlikely"), opt("--out"), bool("--dry"),
+ project(), pick("--reference", ["auto", "rulings", "recordings"]), many("--reference-video", { repeat: true, item: "ref", help: "<channel>/<id>, one per line" }), many("--reference-channel", { repeat: true, item: "name" }),
+ file("--instances"), pick("--span", ["phrase", "cut"]), num("--pad"), num("--likely"), num("--unlikely"), bool("--dry"),
], Q),
- form("clips analyze", "draft", "the clip finder's scans on a long recording, then proposals", [project(), opt("--from", { help: "<channel>/<id>" }), bool("--rescan"), bool("--no-laughs"), bool("--no-voices"), ...clipParams(), opt("--words"), bool("--keep-cut"), opt("--scope"), opt("--segment")], Q),
- form("clips propose", "draft", "the clip finder's proposals again, from what is there", [project(), opt("--from"), num("--host"), ...clipParams(), opt("--words"), bool("--keep-cut"), bool("--dry")]),
+ form("clips analyze", "draft", "the clip finder's scans on a long recording, then proposals", [project(), opt("--from", { type: "ref", help: "<channel>/<id>" }), bool("--rescan"), bool("--no-laughs"), bool("--no-voices"), ...clipParams(), file("--words"), bool("--keep-cut"), opt("--scope"), opt("--segment")], Q),
+ form("clips propose", "draft", "the clip finder's proposals again, from what is there", [project(), opt("--from", { type: "ref", help: "<channel>/<id>" }), num("--host"), ...clipParams(), file("--words"), bool("--keep-cut"), bool("--dry")]),
form("clips show", "project", "the speakers, the laughs, what is in the cut", [project()]),
form("clips segments", "project", "the narrated-video spans auto-scope finds", [project()]),
- form("refresh", "corpus", "re-fetch an article's scope: the plan, and --yes starts it", [arg("article", { required: false }), num("--iteration"), bool("--no-fetch"), bool("--yes", "start it"), bool("--check", "the daily suggestion check, now"), bool("--force")]),
- form("clip", "corpus", "quick clip: one moment to a basic-mode mp4 and its share line", [arg("spec", { help: "<channel>/<video>@<start>-<end>" }), pick("--snap", ["words"]), opt("--title"), opt("--site"), opt("--folder")], Q),
- form("share", "project", "a clip's share line", [project(), clip({ required: false, help: "the clip (none: the first)" }), takeOpt({ help: "the take's cut" }), opt("--site")]),
+ form("refresh", "corpus", "re-fetch an article's scope: the plan, and --yes starts it", [arg("article", { required: false }), num("--iteration"), bool("--no-fetch"), bool("--yes", "start it"), bool("--check", "the daily suggestion check, now"), bool("--force")], { confirm: { what: "start the refresh: an editor job that fetches the article's scope again", when: ["--yes"] } }),
+ form("clip", "corpus", "quick clip: one moment to a basic-mode mp4 and its share line", [arg("spec", { help: "<channel>/<video>@<start>-<end>" }), pick("--snap", ["words"]), opt("--title"), name("--site"), name("--folder")], Q),
+ form("share", "project", "a clip's share line", [project(), clip({ required: false, help: "the clip (none: the first)" }), takeOpt({ help: "the take's cut" }), name("--site")]),
// ---- the cut's structure ----
...timeline(),
@@ -285,8 +297,8 @@ export const VERBS = Object.freeze([
...posts(),
form("candidates ls", "project", "the proposed clips waiting on the Candidates panel", [project(), bool("--all", "the inserted and set aside too")], { shape: "candidates <project> ls" }),
- form("candidates import", "project", "a sweep's bullets as candidates", [project(), arg("file", { help: "<sweep.md>" }), dry()], { shape: "candidates <project> import <file>" }),
- form("candidates add", "project", "an agent's proposal(s) as candidates", [project(), arg("proposal", { type: "text", help: "JSON, or @file" })], { shape: "candidates <project> add <proposal>" }),
+ form("candidates import", "project", "a sweep's bullets as candidates", [project(), file("file", { help: "a sweep's markdown, a file of the project" }), dry()], { shape: "candidates <project> import <file>" }),
+ form("candidates add", "project", "an agent's proposal(s) as candidates", [project(), arg("proposal", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })], { shape: "candidates <project> add <proposal>" }),
none("help", "corpus", "every command", "prints the command list: the palette's Commands are the same list"),
]);
@@ -314,7 +326,7 @@ function trailerBeats() {
tb("candidates", "the walk's ★ clips not yet beats", [bool("--add", "add them all")]),
tb("verdict", "the walk's word on beat n", [n(), pick("verdict", ["confirmed", "note", "clear"], { required: true })]),
tb("title", "the reel's name", [arg("text", { help: "a title, or none" })]),
- tb("take", "the take the reel is cut from", [arg("take", { context: "take", help: "a take, or none" })]),
+ tb("take", "the take the reel is cut from", [name("take", { context: "take", help: "a take, or none" })]),
tb("undo", "the reel as it was before its last write", []),
tb("status", "each beat against the take the reel plays now", [takeOpt({ help: "against that take" })]),
tb("anchor", "beats anchored to a take's master", [many("beats", { help: "beat numbers, one per line (none: all)" }), takeOpt({ required: true })]),
@@ -322,7 +334,7 @@ function trailerBeats() {
tb("repoint", "an orphan beat's seconds on another clip", [n(), clip(), takeOpt()]),
tb("history", "every write to the reel", []),
tb("reels", "the project's reels", []),
- tb("new-reel", "a new reel, empty or a copy", [arg("name"), opt("--from", { help: "a reel to copy" }), opt("--title")]),
+ tb("new-reel", "a new reel, empty or a copy", [name("name"), name("--from", { help: "a reel to copy" }), opt("--title")]),
];
}
@@ -346,9 +358,9 @@ function timeline() {
tl("duplicate", "draft", "an entry twice", [id(), num("--at")]),
tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })]),
tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })]),
- tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", help: "JSON, or @file" })]),
+ tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]),
tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]),
- tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", help: "a JSON patch, or @file" })]),
+ tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]),
tl("undo", "draft", "the newest automatic snapshot back", [takeOpt({ help: "a take's own undo" })]),
tl("sections", "project", "the deck's sections and their clips", []),
tl("section-move", "draft", "clips to the end (or start) of section N", [ids(), num("--to-section", { required: true }), bool("--start")]),
@@ -358,17 +370,17 @@ function timeline() {
tl("section-set", "draft", "a section's label, colour or level", [marker(), opt("--label"), opt("--color"), pick("--level", ["1", "2"])]),
tl("split", "draft", "a clip in two at a source second", [id(), num("second", { required: true })]),
tl("flash-forward", "draft", "a tight copy of a span elsewhere, as a repeat", [id(), arg("span", { help: "<from>-<to>" }), opt("--after"), num("--to-section"), bool("--start"), bool("--move", "the span leaves the clip"), opt("--quote"), opt("--id")]),
- tl("order", "draft", "the cut's order in one write", [many("order", { required: true, help: "entry ids in order, one per line (or @file)" })]),
+ tl("order", "draft", "the cut's order in one write", [many("order", { required: true, item: "name", help: "entry ids in order, one per line" })]),
tl("threads", "draft", "the cut's conversations (and --write gathers them)", [bool("--write"), opt("--conversation")]),
tl("groups", "project", "the claim groups, by section", []),
- tl("groups import", "draft", "a claim-groups file in one write", [arg("file"), bool("--skip-missing"), bool("--drop-empty")]),
+ tl("groups import", "draft", "a claim-groups file in one write", [file("file", { help: "a claim-groups file of the project" }), bool("--skip-missing"), bool("--drop-empty")]),
tl("groups set", "draft", "a group is these clips", [arg("gid", { help: "a group id, or - (a new one)" }), ids(), opt("--claim")]),
tl("groups label", "draft", "a group's claim", [gid(), arg("claim", { type: "text" })]),
tl("groups remove", "draft", "a group dissolved (its clips stay)", [gid()]),
tl("groups move", "draft", "a whole group to another place", [gid(), opt("--to", { required: true, help: "<index>, or after <gid>" })]),
tl("groups promote", "draft", "a group opens a subsection", [gid(), opt("--label")]),
tl("add-video", "draft", "a video entry: a project file full frame", [
- arg("src", { help: "a file of the project" }), num("--from"), num("--to"), pick("--fit", ["contain", "cover"]), num("--bass"), num("--gain"), opt("--enter", { help: "cut | <out>,<in>" }),
+ file("src", { pass: "relative", help: "a video file of the project, relative to its directory" }), num("--from"), num("--to"), pick("--fit", ["contain", "cover"]), num("--bass"), num("--gain"), opt("--enter", { help: "cut | <out>,<in>" }),
num("--hold"), opt("--title"), opt("--id"), opt("--after"), dry(), takeOpt(),
]),
tl("set-video", "draft", "a video entry's knobs", [id(), pairs({ help: "from= to= fit= audio.gain= …, one per line" }), takeOpt()]),
@@ -382,7 +394,7 @@ function posts() {
p("add", "draft", "a post card from the posts archive", [arg("post", { help: "<archive-channel>/<postId>" }), opt("--attach", { help: "a clip id" }), opt("--flag"), opt("--author"), opt("--id"), bool("--thread"), num("--crop"), dry()]),
p("set", "draft", "the Posts table's writer: thread, hide, attach, crop", [arg("post", { context: "post", help: "x-<postId> or the bare id" }), pairs({ help: "thread=on, hide=off, attach=<clip>|auto, crop=<px>|off" })]),
p("reel", "draft", "post items from posts channels, in one write", [
- many("--channel", { repeat: true, required: true, help: "posts channels, one per line" }), opt("--since"), opt("--until"), bool("--own"), bool("--with-media"),
+ many("--channel", { repeat: true, required: true, item: "name", help: "posts channels, one per line" }), opt("--since"), opt("--until"), bool("--own"), bool("--with-media"),
pick("--replies", ["include", "only", "exclude"]), pick("--order", ["chrono", "reverse"]), num("--limit"), opt("--after"), dry(),
]),
p("set-item", "draft", "a post item's knobs", [item(), pairs({ help: "hold=4, layout=grid, media.0.start=2 …" }), inTake()]),
@@ -390,7 +402,7 @@ function posts() {
item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
- num("--limit"), bool("--force"), opt("--recording", { help: "a person's recording made the read" }), opt("--as"), dry(),
+ num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(),
pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(),
], Q),
p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
@@ -402,7 +414,7 @@ function posts() {
], { shape: "posts fx <project> <item> <op>" }),
p("clock", "draft", "the cut's clock default", [pick("mode", ["on", "off", "default"]), opt("--zone", { help: "an IANA zone" })]),
p("progress", "draft", "the cut's progress bar default", [pick("mode", ["auto", "on", "off", "default"])]),
- p("avatar", "draft", "an author's picture on the cards", [arg("handle", { required: false }), arg("image", { required: false, help: "a file, or off" })]),
+ p("avatar", "draft", "an author's picture on the cards", [arg("handle", { required: false }), file("image", { required: false, literals: ["off"], help: "a picture file of the project, or off" })]),
p("avatars", "draft", "the authors' pictures from the archive", [dry()]),
p("redact", "draft", "words blanked from what is published", [pick("op", ["ls", "add", "remove"], { required: true }), arg("value", { required: false, help: "the term (add), its n (remove)" }), bool("--substring"), opt("--note")], { shape: "posts redact <project> <op>" }),
p("slurs", "draft", "the slur filter", [pick("op", ["ls", "on", "off", "level", "visual", "voice", "add", "except", "remove", "edges"], { required: true }), arg("value", { required: false }), bool("--off")], { shape: "posts slurs <project> <op>" }),
@@ -433,6 +445,7 @@ export function formVerbs() {
summary: r.summary,
target: r.target,
queue: !!r.queue,
+ confirm: r.confirm ?? null,
args: r.args,
}));
}
diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs
@@ -3,13 +3,16 @@
// docs/cli.md are what it generates.
import { test } from "node:test";
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
+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 } from "./verbs.mjs";
import { GROUPS } from "./groups.mjs";
import { CLI_MD, DOCS_BEGIN, DOCS_END, usageText, withVerbsSection } from "./docs.mjs";
-import { buildArgv, cliLine, shellQuote, synopsis } from "./argv.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");
@@ -82,7 +85,7 @@ test("every sub-verb the CLI modules dispatch has a row", () => {
});
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"]);
+ 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`);
@@ -189,3 +192,109 @@ test("cliLine: the exact line to paste, quoted for a shell", () => {
assert.equal(shellQuote('deck.markers=[{"after":"c01"}]'), `'deck.markers=[{"after":"c01"}]'`);
assert.equal(synopsis(verbRow("timeline move")), "timeline <project> move <id> --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 `--<key>` 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", "lib/queue/cli.mjs", "lib/annotations/cli.mjs", "lib/phrase-finder/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/);
+ no(verbRow("timeline order"), { project: "p", order: "/etc/passwd" }, /bare name/);
+ for (const v of ["@/etc/passwd", "/etc/passwd", "../../x", "~/x", "a/../../b", "'@x'"]) no(verbRow("posts set-item"), { project: "p", item: "i1", settings: `parent.0=${v}` }, /terminal only|outside the project/);
+ no(verbRow("take"), { project: "p", "--id": "t", "--set": "render.x=@f" }, /terminal only/);
+ no(verbRow("ledger add"), { project: "p", id: "r", more: "src=../../etc" }, /outside the project/);
+ for (const from of ["./report.md", "/home/x/report.md", "../r.md", "report.md"]) no(verbRow("new"), { slug: "s", "--from": from }, /share URL or <channel>\/<id>/);
+ assert.deepEqual(buildArgv(verbRow("new"), { slug: "s", "--from": "https://example.com/s/abc" }).argv.slice(-2), ["--from", "https://example.com/s/abc"]);
+ assert.deepEqual(buildArgv(verbRow("new"), { slug: "s", "--from": "thequartering/abc_123" }).argv.slice(-2), ["--from", "thequartering/abc_123"]);
+ // A handle is not a file: cast's <character|@handle> stays a value.
+ assert.ok(buildArgv(verbRow("cast use"), { project: "p", character: "@grok", voice: "kokoro:am_michael" }).ok);
+ // "false" from a form is off.
+ assert.deepEqual(buildArgv(verbRow("check"), { "--all-severities": "false" }).argv, ["check"]);
+ // The path args the server confines, literals aside.
+ assert.deepEqual(pathArgsOf(verbRow("posts avatar"), { project: "p", handle: "h", image: "off" }), []);
+ assert.deepEqual(pathArgsOf(verbRow("posts avatar"), { project: "p", handle: "h", image: "pics/a.png" }).map((a) => a.name), ["image"]);
+});
+
+test("confirm: a row that deletes, evicts or kills asks, when its args make it so", () => {
+ assert.match(String(confirmOf(verbRow("prune"), { project: "p", "--yes": true })), /delete/);
+ assert.equal(confirmOf(verbRow("prune"), { project: "p" }), null, "a dry run");
+ assert.match(String(confirmOf(verbRow("pool prune"), {})), /delete/);
+ assert.equal(confirmOf(verbRow("pool prune"), { "--dry-run": true }), null);
+ assert.match(String(confirmOf(verbRow("fetch"), { project: "p", "--refetch": "c1" })), /evict/);
+ assert.equal(confirmOf(verbRow("fetch"), { project: "p", "--refetch": "c1", "--dry-run": true }), null);
+ assert.equal(confirmOf(verbRow("fetch"), { project: "p" }), null);
+ for (const v of ["queue cancel", "notes resolve", "notes wontfix", "takes cancel", "ledger rm"]) assert.ok(confirmOf(verbRow(v), {}), v);
+ for (const [v, a] of [["index", "--prune"], ["takes freeze", "--apply"], ["render-mode off", "--force"], ["refresh", "--yes"], ["takes make", "--force"]]) {
+ assert.equal(confirmOf(verbRow(v), {}), null, `${v} bare`);
+ assert.ok(confirmOf(verbRow(v), { [a]: true }), `${v} ${a}`);
+ }
+ assert.ok(formVerbs().find((r) => r.verb === "prune")?.confirm, "the page knows to ask");
+});
+
+test("confineToProject: a file of the project by its realpath, symlinks followed", async () => {
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-confine-"));
+ try {
+ const proj = path.join(tmp, "proj");
+ mkdirSync(path.join(proj, "promo"), { recursive: true });
+ writeFileSync(path.join(proj, "promo", "beats.json"), "[]");
+ writeFileSync(path.join(tmp, "secret.txt"), "the secret");
+ symlinkSync(path.join(tmp, "secret.txt"), path.join(proj, "leak.txt"));
+ symlinkSync(proj, path.join(tmp, "alias"));
+ const ok = await confineToProject(proj, "promo/beats.json");
+ assert.deepEqual(ok, { ok: true, abs: path.join(proj, "promo", "beats.json") });
+ assert.equal((await confineToProject(path.join(tmp, "alias"), "promo/beats.json")).ok, true, "a project reached through a link");
+ for (const bad of ["../secret.txt", path.join(tmp, "secret.txt"), "leak.txt", "promo", "nope.json", "promo/../../secret.txt"]) {
+ const r = await confineToProject(proj, bad);
+ assert.equal(r.ok, false, bad);
+ assert.ok(!String(r.error).includes("the secret"), "never what the file holds");
+ }
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});