diff --git a/.changeset/cli-090-swap.md b/.changeset/cli-090-swap.md new file mode 100644 index 0000000..6853679 --- /dev/null +++ b/.changeset/cli-090-swap.md @@ -0,0 +1,9 @@ +--- +"coordinate": minor +--- + +Move the whole CLI surface onto @cutils/cli 0.9.0: the argv parser, the help screens and the did-you-mean block all live in the library now. + +`enqueue` and `run` capture the command with the library's remainder args, so a dash-leading command works without `--`. The group verbs (`lease`, `agent`, `cap`, `dead`, `service`) are nested command trees with a help screen per sub-verb, and `daemon` answers `--help` without touching the running daemon. A verb that does not exist exits 1 with a did-you-mean block, so `coordinate statu` points at `status` and `stats`. + +The local sectioned help renderer and the argparse-style remainder pre-split are gone, along with roughly 750 lines of hand-rolled argv parsing. diff --git a/docs/cli.md b/docs/cli.md index 8e47df1..bc8795e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -47,7 +47,9 @@ coordinate [args] Every verb has its own help screen. `coordinate --help` lists the verbs, `coordinate --help` documents one verb, and `coordinate help ` prints the same screen. A group verb (`lease`, `agent`, `cap`, `dead`, `service`) has one screen per sub-verb, so `coordinate lease acquire --help` documents the acquire call and `coordinate lease --help` lists the sub-verbs. -The screens are plain text with no escape sequences when the output is piped, so an agent can read them without a terminal. Each screen has the same sections: a one-line summary, `USAGE`, `ARGUMENTS`, `OPTIONS`, `SUBCOMMANDS` for a group verb, `EXAMPLES` where they help, and a `LEARN MORE` pointer to this page. +The screens are plain text with no escape sequences when the output is piped, so an agent can read them without a terminal. Each screen has the same sections: a one-line summary, `USAGE`, `ARGUMENTS`, `OPTIONS`, `COMMANDS` for a group verb, `EXAMPLES` where they help, and a `LEARN MORE` pointer to this page. + +A verb that does not exist exits 1 and prints a did-you-mean block with the closest matches, so `coordinate statu` points at `status` and `stats`. `coordinate --help` with no other argument exits 1 (the CLI is waiting for a verb), while `coordinate --help` exits 0. An unknown verb exits 1 and names the command. diff --git a/package.json b/package.json index 0eae235..1572bb6 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@cutils/cli": "0.8.1", + "@cutils/cli": "0.9.0", "@cutils/sqlite": "0.8.0", "effect": "4.1.5" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index aeb38ac..52b92c7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -171,8 +171,8 @@ importers: .: dependencies: '@cutils/cli': - specifier: 0.8.1 - version: 0.8.1 + specifier: 0.9.0 + version: 0.9.0 '@cutils/sqlite': specifier: 0.8.0 version: 0.8.0(patch_hash=11a322e94e0a294208b09d78ab5df8016a3f11e61ffb90038dc910bf8418ce38)(koffi@2.14.1) @@ -282,8 +282,8 @@ packages: resolution: {integrity: sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==} engines: {node: '>= 20.12.0'} - '@cutils/cli@0.8.1': - resolution: {integrity: sha512-GABESsBXxE2PtI1FiFNIwfOjniHaUNOZustIhffv8Jf4gb8Y6aJx9H3sANP+88s8F2vBVbrq+N78NyHp3pwbyw==} + '@cutils/cli@0.9.0': + resolution: {integrity: sha512-Z24as1SmflCmQqAJvpfrXC7xbACrqF4qBflG/8OOVfSt1S/g4oRvo9ldbcnFQt4MSvqXvem298s+2ACcXBYBvQ==} engines: {node: '>=22'} '@cutils/sqlite@0.8.0': @@ -1325,7 +1325,7 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 2.0.0 - '@cutils/cli@0.8.1': {} + '@cutils/cli@0.9.0': {} '@cutils/sqlite@0.8.0(patch_hash=11a322e94e0a294208b09d78ab5df8016a3f11e61ffb90038dc910bf8418ce38)(koffi@2.14.1)': optionalDependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 16b442d..3bf9f7d 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -5,6 +5,8 @@ allowBuilds: koffi: true esbuild: true "@docmd/engine-rust": false +minimumReleaseAgeExclude: + - "@cutils/cli@0.9.0" patchedDependencies: effect@4.1.5: patches/effect@4.1.5.patch "@cutils/sqlite@0.8.0": patches/@cutils+sqlite@0.8.0.patch diff --git a/src/cli-spec.ts b/src/cli-spec.ts deleted file mode 100644 index fc2743e..0000000 --- a/src/cli-spec.ts +++ /dev/null @@ -1,324 +0,0 @@ -// Pure-data declaration of the coordinate CLI surface: every verb, its -// one-line summary, args and options. src/help.ts renders this into the -// help screens and src/main.ts dispatches on it. No imports, no logic: -// the module must stay compilable by scriptc and tree-shakeable. - -// API-SWAP: when @cutils/cli 0.9.0 lands these records feed ProgramSpec/ -// CommandSpec directly (help{sections,showGlobalOptions,theme}, examples and -// learnMore fields become native; the parity strings below move into -// per-option error text or disappear with the library's own messages). - -export interface VerbOption { - // long option name without the leading dashes - name: string; - // value placeholder, or null for a boolean flag - metavar: string | null; - description: string; - // set when the error text for this option must keep its argparse-style - // wording; the 0.9.0 swap re-checks these against library-generated errors - parity?: string; -} - -export interface VerbArg { - name: string; - description: string; - optional?: boolean; - variadic?: boolean; -} - -export interface Verb { - name: string; - summary: string; - args?: VerbArg[]; - options?: VerbOption[]; - usage?: string; - examples?: string[]; - // sub-verbs, when the verb is a group node - subs?: Verb[]; -} - -export const ROOT_SUMMARY = "a durable job queue for agents and tools on one machine"; - -export const LEARN_MORE = "Full reference and guides: https://coordinated.pages.dev/docs/cli"; - -const enqueueOptions: VerbOption[] = [ - { name: "cwd", metavar: "DIR", description: "working directory for the job" }, - { name: "repo", metavar: "KEY", description: "per-repo cap key (default: cwd; an empty value skips the key)" }, - { name: "priority", metavar: "N", description: "higher numbers claim first (default 0)", parity: 'enqueue --priority: invalid int value: "x"' }, - { name: "max-attempts", metavar: "N", description: "starts allowed after lease expiries (default 3)", parity: 'enqueue --max-attempts: invalid int value: "x"' }, - { name: "max-runtime", metavar: "DUR", description: "execution-time cap, e.g. 15m, 2h, 90s (0 = unbounded; default comes from [defaults] max_runtime in config.toml)", parity: 'enqueue --max-runtime: bad duration "x" (use e.g. 90s, 15m, 2h)' }, - { name: "run-at", metavar: "WHEN", description: "earliest start, as a delay (30s, 15m, 2h) or an ISO timestamp (2026-11-23T18:00:00Z); the job stays queued until then" }, - { name: "wait-on", metavar: "EVENT", description: "park the job immediately on this event id" }, - { name: "slot", metavar: "KEY", description: "extra tool-level slot key (repeatable), e.g. --slot tool:vitest" }, - { name: "lane", metavar: "NAME", description: "budget lane to claim ([lanes] config); defaults to the job kind when a lane of that name exists" }, - { name: "registry", metavar: "NAME", description: "agent registry to resolve --acp against" }, - { name: "acp", metavar: "AGENT", description: "enqueue an acp agent-session job instead of a command", parity: "enqueue --acp: --cwd and --prompt are required" }, - { name: "prompt", metavar: "TEXT", description: "the agent prompt, for --acp jobs" }, - { name: "shell", metavar: null, description: "cmd is ONE string, stored and run verbatim via sh -c", parity: "enqueue --shell: pass the command as ONE quoted string, e.g. --shell -- 'sh -c \"echo hi\"'" }, -]; - -export const VERBS: Verb[] = [ - { - name: "enqueue", - summary: "adds a job and prints its id", - usage: "coordinate enqueue [options] -- ", - args: [{ name: "command", description: "the command to run, after --", variadic: true }], - options: enqueueOptions, - examples: [ - "coordinate enqueue --cwd /tmp -- ls -la", - 'coordinate enqueue --shell -- \'sh -c "echo hi"\'', - "coordinate enqueue --acp codex --cwd ~/prj --prompt 'review the diff'", - ], - }, - { - name: "status", - summary: "shows one job as JSON, or every job as tab-separated rows", - usage: "coordinate status [ | --self]", - args: [{ name: "id", description: "job id", optional: true }], - options: [{ name: "self", metavar: null, description: "the job whose id is in COORDINATE_JOB_ID" }], - }, - { - name: "jobs", - summary: "lists jobs as a human table, or v1 machine records with --json", - usage: "coordinate jobs [--status a,b] [--kind a,b] [--search TEXT] [--sort id|created|priority|status|runtime] [--asc|--desc] [--limit N] [--json] [--watch]", - options: [ - { name: "status", metavar: "a,b", description: "filter by status list" }, - { name: "kind", metavar: "a,b", description: "filter by job kind list" }, - { name: "search", metavar: "TEXT", description: "substring search over metadata" }, - { name: "sort", metavar: "KEY", description: "one of id, created, priority, status, runtime (default id, descending)", parity: "jobs --sort: must be one of id, created, priority, status, runtime" }, - { name: "asc", metavar: null, description: "ascending sort" }, - { name: "desc", metavar: null, description: "descending sort (default)" }, - { name: "limit", metavar: "N", description: "cap the number of rows", parity: "jobs --limit: must be a non-negative integer" }, - { name: "json", metavar: null, description: "one v1 job JSON object per line (see docs/machine-schema.md)" }, - { name: "watch", metavar: null, description: "repaint the human table every second" }, - ], - }, - { - name: "wait-on", - summary: "parks a job until an event is released", - usage: "coordinate wait-on ", - args: [ - { name: "id", description: "job id" }, - { name: "event", description: "event id to wait on" }, - ], - }, - { - name: "release", - summary: "queues every job parked on an event", - usage: "coordinate release ", - args: [{ name: "event", description: "event id to release" }], - }, - { - name: "cancel", - summary: "cancels a job", - usage: "coordinate cancel ", - args: [{ name: "id", description: "job id" }], - }, - { - name: "run", - summary: "runs a command under a tool lease", - usage: "coordinate run [--wait DUR] [--key KEY] [--cost N] [--fail-fast] [--label TEXT] [--shell STR] -- ", - options: [ - { name: "wait", metavar: "DUR", description: "max time to wait for the slot" }, - { name: "key", metavar: "KEY", description: "force the lease key" }, - { name: "cost", metavar: "N", description: "lease cost (default: the tool class cost or 1)" }, - { name: "fail-fast", metavar: null, description: "exit 4 when the slot is full instead of waiting" }, - { name: "label", metavar: "TEXT", description: "seat label for audit output" }, - { name: "shell", metavar: "STR", description: "run ONE string via sh -c" }, - ], - examples: ["coordinate run --fail-fast -- cargo test"], - }, - { - name: "lease", - summary: "weighted semaphore leases with FIFO waits (no daemon needed)", - subs: [ - { - name: "acquire", - summary: "acquire units of a key, or queue for them", - usage: "coordinate lease acquire [--cost N] [--wait DUR] [--owner ID]", - args: [{ name: "key", description: "lease key, e.g. tool:vitest" }], - options: [ - { name: "cost", metavar: "N", description: "units to acquire (default 1)" }, - { name: "wait", metavar: "DUR", description: "max time to wait; exit 3 on timeout" }, - { name: "owner", metavar: "ID", description: "owner id (default pid:)" }, - ], - }, - { name: "release", summary: "release a grant early", usage: "coordinate lease release ", args: [{ name: "grant-id", description: "grant id" }] }, - { name: "refresh", summary: "extend a grant's TTL", usage: "coordinate lease refresh ", args: [{ name: "grant-id", description: "grant id" }] }, - { name: "cancel", summary: "cancel a queued wait", usage: "coordinate lease cancel ", args: [{ name: "wait-id", description: "wait id" }] }, - { name: "list", summary: "print live leases as NDJSON", usage: "coordinate lease list" }, - { name: "waits", summary: "print queued waits as NDJSON", usage: "coordinate lease waits" }, - ], - }, - { - name: "send", - summary: "delivers a message to an owner's inbox", - usage: "coordinate send [--kind K] [--dedupe K] [--at WHEN] [--from F]", - args: [ - { name: "owner", description: "agent:, job: or pid:" }, - { name: "message", description: "message text" }, - ], - options: [ - { name: "kind", metavar: "K", description: "message kind (default message)" }, - { name: "dedupe", metavar: "K", description: "drop repeats of this key" }, - { name: "at", metavar: "WHEN", description: "deliver after a delay or ISO timestamp" }, - { name: "from", metavar: "F", description: "sender id" }, - ], - }, - { - name: "inbox", - summary: "prints an owner's inbox as NDJSON", - usage: "coordinate inbox [] [--self] [--peek] [--all] [--follow]", - args: [{ name: "owner", description: "agent:, job: or pid:", optional: true }], - options: [ - { name: "self", metavar: null, description: "this job or process" }, - { name: "peek", metavar: null, description: "do not mark messages as read" }, - { name: "all", metavar: null, description: "include future deliveries" }, - { name: "follow", metavar: null, description: "keep polling for new messages" }, - ], - }, - { - name: "agent", - summary: "resident agent registry", - subs: [ - { name: "register", summary: "register an agent", usage: "coordinate agent register [--ttl S]", args: [{ name: "name", description: "agent name" }], options: [{ name: "ttl", metavar: "S", description: "seconds before the registration lapses (default 60)" }] }, - { name: "heartbeat", summary: "refresh an agent's registration", usage: "coordinate agent heartbeat ", args: [{ name: "name", description: "agent name" }] }, - { name: "list", summary: "print registered entities as NDJSON", usage: "coordinate agent list" }, - { name: "unregister", summary: "remove an agent", usage: "coordinate agent unregister ", args: [{ name: "name", description: "agent name" }] }, - ], - }, - { - name: "logs", - summary: "prints the captured stdout and stderr of a job's attempts", - usage: "coordinate logs [--attempt N] [--json] [--follow]", - args: [{ name: "id", description: "job id" }], - options: [ - { name: "attempt", metavar: "N", description: "read that attempt instead of the newest", parity: "logs --attempt: must be an integer" }, - { name: "json", metavar: null, description: "one machine record per attempt (paths and byte counts)" }, - { name: "follow", metavar: null, description: "tail new output" }, - ], - }, - { - name: "why", - summary: "explains a job's live state: blockers, next step, log pointers", - usage: "coordinate why [--json]", - args: [{ name: "id", description: "job id" }], - options: [{ name: "json", metavar: null, description: "the machine record" }], - }, - { - name: "health", - summary: "prints a fixed queue summary for scripts and panels", - usage: "coordinate health [--json]", - options: [{ name: "json", metavar: null, description: "one JSON object" }], - }, - { - name: "stats", - summary: "prints the job count per state as JSON", - usage: "coordinate stats", - }, - { - name: "cap", - summary: "runtime cap control", - subs: [ - { name: "show", summary: "print caps, running count and machine as JSON (the default action)", usage: "coordinate cap show" }, - { - name: "set", - summary: "write the machine or repo cap", - usage: "coordinate cap set [--machine-cap N] [--repo-cap N] [--force]", - options: [ - { name: "machine-cap", metavar: "N", description: "max running jobs on this machine", parity: 'cap set --machine-cap: invalid int value: "x"' }, - { name: "repo-cap", metavar: "N", description: "max running jobs per repo key", parity: 'cap set --repo-cap: invalid int value: "x"' }, - { name: "force", metavar: null, description: "accept lowering below the running count" }, - ], - }, - ], - }, - { - name: "events", - summary: "prints the event log as JSONL, or follows it", - usage: "coordinate events [--follow] [--since ID] [--job ID] [--kind a,b] [--search TEXT]", - options: [ - { name: "follow", metavar: null, description: "keep polling" }, - { name: "since", metavar: "ID", description: "start after this event id" }, - { name: "job", metavar: "ID", description: "only this job's events" }, - { name: "kind", metavar: "a,b", description: "filter by kind list" }, - { name: "search", metavar: "TEXT", description: "substring search over metadata" }, - ], - }, - { - name: "forward", - summary: "runs a command for each event", - usage: "coordinate forward --exec CMD [--machine NAME] [--interval N] [--cursor FILE] [--since ID] [--kinds a,b] [--once] [-v]", - options: [ - { name: "exec", metavar: "CMD", description: "command to run per event (required)", parity: "forward: --exec is required" }, - { name: "machine", metavar: "NAME", description: "only events from this machine" }, - { name: "interval", metavar: "N", description: "poll interval in seconds" }, - { name: "cursor", metavar: "FILE", description: "cursor file path" }, - { name: "since", metavar: "ID", description: "start after this event id" }, - { name: "kinds", metavar: "a,b", description: "filter by kind list" }, - { name: "once", metavar: null, description: "drain once and exit" }, - { name: "verbose", metavar: null, description: "log what is forwarded (alias -v)" }, - ], - }, - { - name: "dead", - summary: "requeues failed and dead jobs", - subs: [ - { - name: "retry", - summary: "requeue one job, or all of them with --all", - usage: "coordinate dead retry | --all", - args: [{ name: "id", description: "job id", optional: true }], - options: [{ name: "all", metavar: null, description: "requeue every failed and dead job, cancelled included" }], - }, - ], - }, - { - name: "audit", - summary: "classifies resident agent sessions; report-only", - usage: "coordinate audit [--json] [--drift-only]", - options: [ - { name: "json", metavar: null, description: "one record per row plus a summary object" }, - { name: "drift-only", metavar: null, description: "only the unseated rows" }, - ], - }, - { - name: "tui", - summary: "the interactive triage screen (needs a TTY on stdout)", - usage: "coordinate tui", - }, - { - name: "doctor", - summary: "prints a health report for this CLI install", - usage: "coordinate doctor", - }, - { - name: "daemon", - summary: "runs the claim loop on this machine", - usage: "coordinate daemon [restart]", - args: [{ name: "action", description: "restart: hand off to the current binary", optional: true }], - }, - { - name: "service", - summary: "installs or inspects the daemon as a user service", - subs: [ - { name: "install", summary: "install the user service unit", usage: "coordinate service install [--force]", options: [{ name: "force", metavar: null, description: "overwrite a differing unit" }] }, - { name: "uninstall", summary: "stop and remove the unit", usage: "coordinate service uninstall" }, - { name: "status", summary: "report installed, enabled and running state", usage: "coordinate service status" }, - ], - }, - { - name: "version", - summary: "prints the CLI version", - usage: "coordinate version", - }, -]; - -export function findVerb(name: string): Verb | null { - for (let i = 0; i < VERBS.length; i++) { - if (VERBS[i].name === name) { - return VERBS[i]; - } - } - return null; -} diff --git a/src/help.ts b/src/help.ts deleted file mode 100644 index 067e6d4..0000000 --- a/src/help.ts +++ /dev/null @@ -1,220 +0,0 @@ -// API-SWAP: delete this file when @cutils/cli 0.9.0 lands; the library's -// sectioned renderer replaces it (ProgramSpec.help{color,width,sections, -// showGlobalOptions,theme,tty}, examples/learnMore fields, exported -// shouldColor()/suggestCommands()). -// -// Local sectioned plain-text help renderer over the cli-spec.ts data. -// Rules enforced here and asserted in test/help.test.mjs: -// - zero ANSI escapes anywhere (piped output is byte-clean) -// - no line exceeds 90 characters (long descriptions wrap at 90) - -import { LEARN_MORE, ROOT_SUMMARY, VERBS, type Verb, type VerbOption } from "./cli-spec.ts"; -import { CLI_VERSION } from "./version.ts"; - -const WIDTH = 90; -const INDENT = " "; - -// Wrap one paragraph into lines no longer than WIDTH, with a hanging indent. -function wrap(text: string, width: number, indent: string): string[] { - const words = text.split(" "); - const lines: string[] = []; - let cur = ""; - for (let i = 0; i < words.length; i++) { - const w = words[i]; - if (cur === "") { - cur = w; - } else if (cur.length + 1 + w.length <= width) { - cur = cur + " " + w; - } else { - lines.push(cur); - cur = indent + w; - } - } - if (cur !== "") { - lines.push(cur); - } - return lines.length === 0 ? [""] : lines; -} - -function section(out: string[], title: string): void { - out.push(""); - out.push(title + ":"); -} - -function twoColumn(out: string[], rows: [string, string][]): void { - let w = 0; - for (let i = 0; i < rows.length; i++) { - if (rows[i][0].length > w) { - w = rows[i][0].length; - } - } - for (let i = 0; i < rows.length; i++) { - const desc = rows[i][1]; - if (desc === "") { - out.push(rows[i][0]); - continue; - } - const label = rows[i][0] + " ".repeat(w - rows[i][0].length); - // a two-column row keeps the description on the same line when it fits, - // otherwise the description hangs at the description column - const col = 2 + w + 2; - if (desc.length <= WIDTH - col) { - out.push(INDENT + label + " " + desc); - } else { - const wrapped = wrap(desc, WIDTH - col, " ".repeat(col)); - out.push(INDENT + label + " " + wrapped[0]); - for (let j = 1; j < wrapped.length; j++) { - out.push(wrapped[j]); - } - } - } -} - -function optionLabel(o: VerbOption): string { - return o.metavar === null ? "--" + o.name : "--" + o.name + " " + o.metavar; -} - -function argLabel(name: string, optional?: boolean, variadic?: boolean): string { - let inner = name; - if (variadic === true) { - inner = inner + "..."; - } - return optional === true ? "[" + inner + "]" : "<" + inner + ">"; -} - -// The usage tail for a verb, relative to "coordinate". The declared usage -// string already carries the full command path ("coordinate lease acquire -// "), so it is used as is. -function usageTail(v: Verb, path: string): string { - if (v.usage !== undefined) { - return v.usage.slice("coordinate ".length); - } - if (v.subs !== undefined) { - const names: string[] = []; - for (let i = 0; i < v.subs.length; i++) { - names.push(v.subs[i].name); - } - return path + " <" + names.join("|") + ">"; - } - return path; -} - -function pushExamples(out: string[], v: Verb): void { - if (v.examples === undefined) { - return; - } - section(out, "EXAMPLES"); - for (let i = 0; i < v.examples.length; i++) { - out.push(INDENT + v.examples[i]); - } -} - -// Per-verb screen: verb + summary, USAGE, ARGUMENTS, OPTIONS, SUBCOMMANDS, -// EXAMPLES, LEARN MORE. `path` is the full command path ("enqueue", -// "lease acquire"), so a sub-verb screen reads "coordinate lease acquire". -export function verbHelp(path: string, v: Verb): string { - const out: string[] = []; - out.push("coordinate " + path + " - " + v.summary); - section(out, "USAGE"); - const tail = usageTail(v, path); - // A long usage line wraps with a hanging indent, so no line is wider - // than the screen. - const usageLines = wrap("coordinate " + tail, WIDTH, INDENT + " "); - for (let i = 0; i < usageLines.length; i++) { - out.push(INDENT + usageLines[i]); - } - if (v.args !== undefined && v.args.length > 0) { - section(out, "ARGUMENTS"); - const rows: [string, string][] = []; - for (let i = 0; i < v.args.length; i++) { - const a = v.args[i]; - rows.push([argLabel(a.name, a.optional, a.variadic), a.description]); - } - twoColumn(out, rows); - } - if (v.options !== undefined && v.options.length > 0) { - section(out, "OPTIONS"); - const rows: [string, string][] = []; - for (let i = 0; i < v.options.length; i++) { - const o = v.options[i]; - rows.push([optionLabel(o), o.description]); - } - twoColumn(out, rows); - } - if (v.subs !== undefined) { - section(out, "SUBCOMMANDS"); - const rows: [string, string][] = []; - for (let i = 0; i < v.subs.length; i++) { - rows.push([v.subs[i].name, v.subs[i].summary]); - } - twoColumn(out, rows); - } - pushExamples(out, v); - section(out, "LEARN MORE"); - out.push(INDENT + LEARN_MORE); - return out.join("\n"); -} - -// Root screen: name + version + summary, USAGE, COMMANDS, LEARN MORE. -export function rootHelp(): string { - const out: string[] = []; - out.push("coordinate " + CLI_VERSION + " - " + ROOT_SUMMARY); - section(out, "USAGE"); - out.push(INDENT + "coordinate [args]"); - section(out, "COMMANDS"); - const rows: [string, string][] = []; - for (let i = 0; i < VERBS.length; i++) { - const v = VERBS[i]; - if (v.subs !== undefined) { - const names: string[] = []; - for (let j = 0; j < v.subs.length; j++) { - names.push(v.subs[j].name); - } - rows.push([v.name, v.summary + " (" + names.join(", ") + ")"]); - } else { - rows.push([v.name, v.summary]); - } - } - twoColumn(out, rows); - section(out, "LEARN MORE"); - out.push(INDENT + LEARN_MORE); - return out.join("\n"); -} - -export function printRootHelp(): void { - process.stdout.write(rootHelp() + "\n"); -} - -// Print the screen for a verb path ("enqueue" or "lease acquire"). -// Returns false when the path names no verb. -export function printVerbHelp(path: string): boolean { - const parts = path.split(" "); - let found: Verb | null = null; - let label = ""; - for (let i = 0; i < VERBS.length; i++) { - const v = VERBS[i]; - if (v.name === parts[0]) { - if (parts.length === 1) { - found = v; - label = v.name; - break; - } - const subs = v.subs; - if (subs !== undefined) { - for (let j = 0; j < subs.length; j++) { - if (subs[j].name === parts[1]) { - found = subs[j]; - label = v.name + " " + subs[j].name; - break; - } - } - } - break; - } - } - if (found === null) { - return false; - } - process.stdout.write(verbHelp(label, found) + "\n"); - return true; -} diff --git a/src/main.ts b/src/main.ts index fb8a0c0..61bd215 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,24 +1,25 @@ // coordinate CLI: enqueue, status, jobs, wait-on, release, cancel, lease, run, // send, inbox, agent, logs, why, health, stats, cap, events, forward, dead, // audit, tui, doctor, daemon, service, version, help. -// Port of src/coordinate/cli.py (cmd lane only). Argv parsing runs on -// @cutils/cli 0.8.1 (`runAsync` + `command()`); the verbs whose argparse-style -// error text or REMAINDER shape the 0.8.1 seam cannot express keep a -// hand-rolled branch, marked with an API-SWAP comment (the 0.9.0 swap makes -// them library-dispatched and deletes the local help renderer). +// Port of src/coordinate/cli.py (cmd lane only). Argv parsing, the help +// screens and the did-you-mean block all run on @cutils/cli 0.9.0 +// (`runAsync` + `command()`), so the CLI surface is one nested command tree +// and no local argv parser remains. import * as fs from "node:fs"; import * as path from "node:path"; -import { bool, command, runAsync, str, type CommandDef, type ProgramSpec } from "@cutils/cli"; +import { bool, command, run, runAsync, str, type CommandDef, type ProgramSpec } from "@cutils/cli"; import { env } from "./env.ts"; import { Database } from "@cutils/sqlite"; import * as q from "./queue.ts"; import { jobRecord, queryJobs, queryEvents, whyJob, health, jobLogs, fmtCost, type JobQuery, type SortKey } from "./readmodel.ts"; import { renderJobsTable } from "./format-table.ts"; import { ConfigError, defaultMaxRuntimeS, observabilityMode, parseCost, parseDurationSecs, slotLimit, validateConfig as cfgValidate } from "./config.ts"; -import { printRootHelp, printVerbHelp } from "./help.ts"; -import { VERBS } from "./cli-spec.ts"; -import { splitRemainder, type FlagSpec } from "./remainder.ts"; +import { CLI_VERSION } from "./version.ts"; + +// The one-line summary on the root screen and the pointer to the docs. +const ROOT_SUMMARY = "a durable job queue for agents and tools on one machine"; +const LEARN_MORE = "Full reference and guides: https://coordinated.pages.dev/docs/cli"; function cfgMode(): string { try { @@ -835,8 +836,10 @@ function buildCommands(): Record { const cmds: Record = {}; cmds["enqueue"] = command("adds a job and prints its id", { - // optional: an --acp job carries no command; the handler validates. - args: [{ name: "command", optional: true, variadic: true, description: "the command to run, after --" }], + // The remainder arg captures the command verbatim: the option parsing + // stops at the first non-option token (or at `--`), so `enqueue ls -la` + // and `enqueue -- -odd-binary` both work. + args: [{ name: "command", optional: true, remainder: true, description: "the command to run, after --" }], options: { cwd: str({ description: "working directory for the job", metavar: "DIR" }), repo: str({ description: "per-repo cap key", metavar: "KEY" }), @@ -858,10 +861,8 @@ function buildCommands(): Record { }, handler: (o: unknown, a: unknown[]) => { const opts = asRecord(o); - // The command tokens were split off before the library saw the argv. - // API-SWAP (0.9: ArgSpec.remainder): the library's remainder spec - // hands them over as the args slot and this lookup disappears. - const cmd = remainderCmds["enqueue"] ?? []; + // The remainder arg hands the command tokens over as one array slot. + const cmd = a.length > 0 && Array.isArray(a[0]) ? (a[0] as string[]) : []; cfgValidate(); cmdEnqueue(q.connect(), opts, cmd); }, @@ -932,8 +933,9 @@ function buildCommands(): Record { }) as unknown as CommandDef; cmds["run"] = command("runs a command under a tool lease", { - // optional: --shell 'cmd' replaces the command; the handler validates. - args: [{ name: "command", optional: true, variadic: true, description: "the command to run, after --" }], + // The remainder arg captures the command verbatim; --shell replaces it + // and the handler validates. + args: [{ name: "command", optional: true, remainder: true, description: "the command to run, after --" }], options: { wait: str({ description: "how long to queue for the lease before giving up", metavar: "DUR" }), key: str({ description: "force the lease key instead of classifying the command", metavar: "KEY" }), @@ -943,10 +945,8 @@ function buildCommands(): Record { shell: str({ description: "run ONE string via sh -c", metavar: "CMD" }), }, handler: (o: unknown, a: unknown[]) => { - // The command tokens were split off before the library saw the argv. - // API-SWAP (0.9: ArgSpec.remainder): the library's remainder spec - // hands them over as the args slot and this lookup disappears. - const cmd = remainderCmds["run"] ?? []; + // The remainder arg hands the command tokens over as one array slot. + const cmd = a.length > 0 && Array.isArray(a[0]) ? (a[0] as string[]) : []; return cmdRun(q.connect(), asRecord(o), cmd); }, }) as unknown as CommandDef; @@ -1112,6 +1112,22 @@ function buildCommands(): Record { }, }) as unknown as CommandDef; + // The daemon runs the claim loop, so it cannot have a handler on this + // process; `restart` is a real sub-verb and the bare verb runs the loop. + cmds["daemon"] = command("runs the claim loop on this machine", { + args: [{ name: "action", description: "restart: hand off to the current binary", optional: true }], + handler: (o: unknown, a: unknown[]) => { + return cmdDaemon(a as string[]); + }, + }) as unknown as CommandDef; + + // The group verbs (lease, agent, cap, dead, service) are nested command + // trees, so the library renders their per-sub-verb screens. + const groups = buildGroupCommands(); + for (const name of Object.keys(groups)) { + cmds[name] = groups[name]; + } + return cmds; } @@ -1202,269 +1218,218 @@ async function cmdLeaseAcquire(db: Database, o: Record, args: s } // --- group verbs ---------------------------------------------------------- -// The group verbs (lease, agent, cap, dead, service, daemon) keep their own -// sub-verb dispatch: @cutils/cli 0.8.1 has no per-node custom error text, -// and these verbs' historical messages are per-sub-verb strings that tests -// assert on. They are reached through the same argv seam as the library -// commands, so `coordinate lease acquire ...` still works exactly as before. -// API-SWAP: 0.9.0 turns these into real nested `commands:` trees; the -// messages below move into per-node schemas. - -async function cmdLease(db: Database, rest: string[]): Promise { - const sub = rest[0]; - if (sub === "acquire") { - let key: string | null = null; - let cost = 1; - let waitDur: string | null = null; - let owner: string | null = null; - for (let i = 1; i < rest.length; i++) { - const t = rest[i]; - if (t === "--cost") { - cost = parseCostFlag(rest[++i]); - } else if (t === "--wait") { - waitDur = rest[++i]; - } else if (t === "--owner") { - owner = rest[++i]; - } else if (t.startsWith("--cost=")) { - cost = parseCostFlag(t.slice(7)); - } else if (t.startsWith("--wait=")) { - waitDur = t.slice(7); - } else if (t.startsWith("--owner=")) { - owner = t.slice(8); - } else if (!t.startsWith("--") && key === null) { - key = t; - } else { - fail("lease acquire: unknown argument " + t); - } - } - if (key === null) { - fail("lease acquire: give a lease key, e.g. coordinate lease acquire tool:vitest --cost 2 --wait 60s"); - } - if (cost <= 0) { - fail("lease acquire --cost: must be a positive multiple of 0.25"); - } - const limit = slotLimit(key); - if (cost > limit) { - process.stderr.write( - JSON.stringify({ error: "ungrantable", key, cost, limit, detail: "cost exceeds the key limit; raise it in [slots] config" }) + "\n", - ); - process.exit(4); - } - if (owner === null) { - owner = "pid:" + process.ppid; - } - const kind = owner.startsWith("pid:") ? "process" : owner.startsWith("job:") ? "job" : "agent"; - q.registerEntity(db, owner, kind, null); - const immediate = q.acquireLease(db, key, owner, cost); - if (immediate !== null) { - const lease = q.qOne(db, "SELECT * FROM leases WHERE grant_id=?", [immediate]) as q.Lease; - process.stdout.write(JSON.stringify({ ...lease, wait_id: null }) + "\n"); - return; - } - let deadlineAt: number | null = null; - if (waitDur !== null) { - const secs = parseDurationSecs(waitDur); - if (secs === null || secs <= 0) { - fail("lease acquire --wait: bad duration " + JSON.stringify(waitDur) + " (use e.g. 30s, 15m)"); - } - deadlineAt = Date.now() / 1000 + secs; - } - const waitId = q.enqueueWait(db, key, owner, cost, deadlineAt); - // Poll loop: every iteration runs the shared maintenance (expire TTLs, - // reap dead owners, drain the FIFO), so any active waiter is its own - // granter and no daemon is required for fairness. - for (;;) { - await new Promise((res) => setTimeout(res, 150)); - { - using _tx = q.writeTx(db); - q.maintainLeases(db, [key]); - } - const w = q.getWait(db, waitId); - if (w === null) { - process.exit(4); - } - if (w.state === "granted" && w.grant_id !== null) { - const lease = q.qOne(db, "SELECT * FROM leases WHERE grant_id=?", [w.grant_id]) as q.Lease | null; - if (lease !== null) { - process.stdout.write(JSON.stringify({ ...lease, wait_id: waitId }) + "\n"); - process.exit(0); - } - } - if (w.state === "expired") { - process.stderr.write(JSON.stringify({ error: "timeout", key, wait_id: waitId }) + "\n"); - process.exit(3); - } - if (w.state === "cancelled") { - process.stderr.write(JSON.stringify({ error: "cancelled", key, wait_id: waitId }) + "\n"); - process.exit(4); - } - } - } else if (sub === "release") { - if (rest.length !== 2) { - fail("lease release: give one grant id"); - } - if (!q.releaseLease(db, rest[1])) { - fail("lease release: no such grant " + rest[1]); - } - } else if (sub === "cancel") { - if (rest.length !== 2) { - fail("lease cancel: give one wait id"); - } - if (!q.cancelWait(db, Number(rest[1]))) { - fail("lease cancel: no queued wait " + rest[1]); - } - } else if (sub === "refresh") { - if (rest.length !== 2) { - fail("lease refresh: give one grant id"); - } - if (!q.refreshLease(db, rest[1])) { - fail("lease refresh: no such grant " + rest[1]); - } - } else if (sub === "list" || sub === "waits") { - const rows = sub === "list" ? q.listLeases(db) : q.listWaits(db); - for (const r of rows) { - process.stdout.write(JSON.stringify(r) + "\n"); - } - } else { - fail("lease: action must be acquire, release, cancel, refresh, list or waits"); - } -} +// The group verbs (lease, agent, cap, dead, service) are nested command trees +// in the library: each sub-verb is a node with its own args, options and +// handler, so the library renders the per-sub-verb help screens and parses +// the flags. The handler bodies keep the historical behavior and exit codes. -function cmdAgent(db: Database, rest: string[]): void { - // coordinate agent register [--ttl S] / heartbeat / list / unregister - const sub = rest[0]; - if (sub === "register") { - if (rest.length < 2) { - fail("agent register: give a name"); - } - const name = rest[1].startsWith("agent:") ? rest[1] : "agent:" + rest[1]; - let ttl: number | null = 60; - for (let i = 2; i < rest.length; i++) { - if (rest[i] === "--ttl") { - ttl = Number(rest[++i]); - } else { - fail("agent register: unknown argument " + rest[i]); - } - } - q.registerEntity(db, name, "agent", ttl); - process.stdout.write(name + "\n"); - } else if (sub === "heartbeat") { - if (rest.length < 2) { - fail("agent heartbeat: give a name"); - } - const name = rest[1].startsWith("agent:") ? rest[1] : "agent:" + rest[1]; - if (!q.heartbeatEntity(db, name, 60)) { - fail("agent heartbeat: no such agent " + name); - } - } else if (sub === "list") { - const rows = q.qAll(db, "SELECT * FROM entities ORDER BY kind, id", []) as q.Entity[]; - for (const r of rows) { - process.stdout.write(JSON.stringify(r) + "\n"); - } - } else if (sub === "unregister") { - if (rest.length < 2) { - fail("agent unregister: give a name"); - } - const name = rest[1].startsWith("agent:") ? rest[1] : "agent:" + rest[1]; - q.qRun(db, "DELETE FROM entities WHERE id=?", [name]); - } else { - fail("agent: action must be register, heartbeat, list or unregister"); - } -} +function buildGroupCommands(): Record { + const cmds: Record = {}; -function cmdCap(db: Database, rest: string[]): void { - // Runtime cap control. The values live in the queue DB, so the daemon - // picks them up on its next claim: raising the cap frees queued jobs - // immediately, lowering it never interrupts the jobs already running. - const action = rest[0] === undefined ? "show" : rest[0]; - if (action === "show") { - if (rest.length > 1) { - fail("cap show: takes no arguments"); - } - process.stdout.write(JSON.stringify(capSnapshot(db)) + "\n"); - } else if (action === "set") { - let machineCapValue: number | null = null; - let repoCapValue: number | null = null; - let force = false; - for (let i = 1; i < rest.length; i++) { - const t = rest[i]; - if (t === "--repo-cap") { - repoCapValue = parseIntArg(rest[++i], "--repo-cap"); - } else if (t === "--machine-cap") { - machineCapValue = parseIntArg(rest[++i], "--machine-cap"); - } else if (t === "--force") { - force = true; - } else { - fail("cap set: unknown argument " + t); - } - } - if (machineCapValue === null && repoCapValue === null) { - fail("cap set: give --machine-cap N and/or --repo-cap N"); - } - for (const [flag, v] of [ - ["--machine-cap", machineCapValue], - ["--repo-cap", repoCapValue], - ] as [string, number | null][]) { - if (v !== null && v <= 0) { - fail("cap set " + flag + ": must be a positive integer"); - } - } - const running = (q.qAll(db, "SELECT COUNT(*) AS c FROM jobs WHERE status='running'", []) as { c: number }[])[0].c; - if (machineCapValue !== null && machineCapValue < running && !force) { - fail( - "cap set --machine-cap " + - machineCapValue + - ": " + - running + - " job(s) are running; lowering below that waits for them to drain. Pass --force to accept the overshoot.", - ); - } - if (machineCapValue !== null) { - q.setCap(db, "machine", machineCapValue); - } - if (repoCapValue !== null) { - q.setCap(db, "repo", repoCapValue); - } - process.stdout.write(JSON.stringify(capSnapshot(db)) + "\n"); - } else { - fail("cap: action must be show or set"); - } -} + cmds["lease"] = command("weighted semaphore leases with FIFO waits (no daemon needed)", { + commands: { + acquire: command("acquire units of a key, or queue for them", { + args: [{ name: "key", description: "lease key, e.g. tool:vitest" }], + options: { + cost: str({ description: "units to acquire (default 1)", metavar: "N" }), + wait: str({ description: "max time to wait; exit 3 on timeout", metavar: "DUR" }), + owner: str({ description: "owner id (default pid:)", metavar: "ID" }), + }, + handler: (o: unknown, a: unknown[]) => { + return cmdLeaseAcquire(q.connect(), asRecord(o), a as string[]); + }, + }) as unknown as CommandDef, + release: command("release a grant early", { + args: [{ name: "grant-id", description: "grant id" }], + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + if (!q.releaseLease(q.connect(), args[0])) { + fail("lease release: no such grant " + args[0]); + } + }, + }) as unknown as CommandDef, + refresh: command("extend a grant's TTL", { + args: [{ name: "grant-id", description: "grant id" }], + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + if (!q.refreshLease(q.connect(), args[0])) { + fail("lease refresh: no such grant " + args[0]); + } + }, + }) as unknown as CommandDef, + cancel: command("cancel a queued wait", { + args: [{ name: "wait-id", description: "wait id" }], + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + if (!q.cancelWait(q.connect(), Number(args[0]))) { + fail("lease cancel: no queued wait " + args[0]); + } + }, + }) as unknown as CommandDef, + list: command("print live leases as NDJSON", { + handler: () => { + for (const r of q.listLeases(q.connect())) { + process.stdout.write(JSON.stringify(r) + "\n"); + } + }, + }) as unknown as CommandDef, + waits: command("print queued waits as NDJSON", { + handler: () => { + for (const r of q.listWaits(q.connect())) { + process.stdout.write(JSON.stringify(r) + "\n"); + } + }, + }) as unknown as CommandDef, + }, + }) as unknown as CommandDef; -function cmdDead(db: Database, rest: string[]): void { - const action = rest[0]; - if (action !== "retry") { - fail("dead: action must be retry"); - } - // A bulk retry revives every failed job, cancelled ones included, so it has - // to be asked for by name: a bare `dead retry` refuses. - if (rest.length !== 2) { - fail("dead retry: give one job id, or --all to requeue every failed and dead job"); - } - const ids = q.retryDead(db, rest[1] === "--all" ? null : parseIntArg(rest[1], "dead retry")); - if (ids.length > 0) { - process.stdout.write(ids.join("\n") + "\n"); - } -} + cmds["agent"] = command("resident agent registry", { + commands: { + register: command("register an agent", { + args: [{ name: "name", description: "agent name" }], + options: { ttl: str({ description: "seconds before the registration lapses (default 60)", metavar: "S" }) }, + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + const name = args[0].startsWith("agent:") ? args[0] : "agent:" + args[0]; + const ttl = optNum(asRecord(o), "ttl") ?? 60; + q.registerEntity(q.connect(), name, "agent", ttl); + process.stdout.write(name + "\n"); + }, + }) as unknown as CommandDef, + heartbeat: command("refresh an agent's registration", { + args: [{ name: "name", description: "agent name" }], + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + const name = args[0].startsWith("agent:") ? args[0] : "agent:" + args[0]; + if (!q.heartbeatEntity(q.connect(), name, 60)) { + fail("agent heartbeat: no such agent " + name); + } + }, + }) as unknown as CommandDef, + list: command("print registered entities as NDJSON", { + handler: () => { + const rows = q.qAll(q.connect(), "SELECT * FROM entities ORDER BY kind, id", []) as q.Entity[]; + for (const r of rows) { + process.stdout.write(JSON.stringify(r) + "\n"); + } + }, + }) as unknown as CommandDef, + unregister: command("remove an agent", { + args: [{ name: "name", description: "agent name" }], + handler: (o: unknown, a: unknown[]) => { + const args = a as string[]; + const name = args[0].startsWith("agent:") ? args[0] : "agent:" + args[0]; + q.qRun(q.connect(), "DELETE FROM entities WHERE id=?", [name]); + }, + }) as unknown as CommandDef, + }, + }) as unknown as CommandDef; -async function cmdService(rest: string[]): Promise { - const svc = await import("./service.ts"); - const action = rest[0]; - if (action === "install") { - svc.cmdInstall(rest.slice(1)); - } else if (action === "uninstall") { - if (rest.length > 1) { - fail("service uninstall: takes no arguments"); - } - svc.cmdUninstall(); - } else if (action === "status") { - if (rest.length > 1) { - fail("service status: takes no arguments"); - } - svc.cmdStatus(); - } else { - fail("service: action must be install, uninstall or status"); - } + cmds["cap"] = command("runtime cap control", { + commands: { + show: command("print caps, running count and machine as JSON", { + handler: () => { + process.stdout.write(JSON.stringify(capSnapshot(q.connect())) + "\n"); + }, + }) as unknown as CommandDef, + set: command("write the machine or repo cap", { + options: { + "machine-cap": str({ description: "max running jobs on this machine", metavar: "N" }), + "repo-cap": str({ description: "max running jobs per repo key", metavar: "N" }), + force: bool({ description: "accept lowering below the running count" }), + }, + handler: (o: unknown) => { + const opts = asRecord(o); + const machineCap = optInt(opts, "machineCap", (raw) => "cap set --machine-cap: invalid int value: " + JSON.stringify(raw)); + const repoCap = optInt(opts, "repoCap", (raw) => "cap set --repo-cap: invalid int value: " + JSON.stringify(raw)); + if (machineCap === null && repoCap === null) { + fail("cap set: give --machine-cap N and/or --repo-cap N"); + } + const db = q.connect(); + for (const [flag, v] of [ + ["--machine-cap", machineCap], + ["--repo-cap", repoCap], + ] as [string, number | null][]) { + if (v !== null && v <= 0) { + fail("cap set " + flag + ": must be a positive integer"); + } + } + const running = (q.qAll(db, "SELECT COUNT(*) AS c FROM jobs WHERE status='running'", []) as { c: number }[])[0].c; + if (machineCap !== null && machineCap < running && opts["force"] !== true) { + fail( + "cap set --machine-cap " + + machineCap + + ": " + + running + + " job(s) are running; lowering below that waits for them to drain. Pass --force to accept the overshoot.", + ); + } + if (machineCap !== null) { + q.setCap(db, "machine", machineCap); + } + if (repoCap !== null) { + q.setCap(db, "repo", repoCap); + } + process.stdout.write(JSON.stringify(capSnapshot(db)) + "\n"); + }, + }) as unknown as CommandDef, + }, + }) as unknown as CommandDef; + + cmds["dead"] = command("requeues failed and dead jobs", { + commands: { + retry: command("requeue one job, or all of them with --all", { + args: [{ name: "id", description: "job id", optional: true }], + options: { all: bool({ description: "requeue every failed and dead job, cancelled included" }) }, + handler: (o: unknown, a: unknown[]) => { + const opts = asRecord(o); + const args = a as (string | null)[]; + const db = q.connect(); + // A bulk retry revives every failed job, cancelled ones included, so + // it has to be asked for by name: a bare `dead retry` refuses. + if (opts["all"] === true) { + const ids = q.retryDead(db, null); + if (ids.length > 0) { + process.stdout.write(ids.join("\n") + "\n"); + } + return; + } + const idText = args[0] ?? null; + if (idText === null) { + fail("dead retry: give one job id, or --all to requeue every failed and dead job"); + } + const ids = q.retryDead(db, parseIntArg(idText, "dead retry")); + if (ids.length > 0) { + process.stdout.write(ids.join("\n") + "\n"); + } + }, + }) as unknown as CommandDef, + }, + }) as unknown as CommandDef; + + cmds["service"] = command("installs or inspects the daemon as a user service", { + commands: { + install: command("install the user service unit", { + options: { force: bool({ description: "overwrite a differing unit" }) }, + handler: (o: unknown) => { + const svc = import("./service.ts"); + return svc.then((s) => s.cmdInstall(asRecord(o)["force"] === true ? ["--force"] : [])); + }, + }) as unknown as CommandDef, + uninstall: command("stop and remove the unit", { + handler: () => { + return import("./service.ts").then((s) => s.cmdUninstall()); + }, + }) as unknown as CommandDef, + status: command("report installed, enabled and running state", { + handler: () => { + return import("./service.ts").then((s) => s.cmdStatus()); + }, + }) as unknown as CommandDef, + }, + }) as unknown as CommandDef; + + return cmds; } async function cmdDaemon(rest: string[]): Promise { @@ -1486,141 +1451,52 @@ async function cmdDaemon(rest: string[]): Promise { // ---------------------------------------------------------------- entrypoint -// The verbs the library dispatches. The group verbs (lease, agent, cap, -// dead, service, daemon) are handled before the library sees the argv, so -// their per-sub-verb error text stays byte-identical. -const GROUP_VERBS: string[] = ["lease", "agent", "cap", "dead", "service", "daemon"]; - -// The verbs whose command tokens follow the flags (argparse REMAINDER). -// The flags listed here are the ones the verb accepts before the command -// starts; anything else ends the flag section. -const REMAINDER_VERBS: Record = { - enqueue: { - names: ["--cwd", "--repo", "--priority", "--max-attempts", "--max-runtime", "--run-at", "--wait-on", "--shell", "--slot", "--acp", "--prompt", "--registry", "--lane"], - valued: ["--cwd", "--repo", "--priority", "--max-attempts", "--max-runtime", "--run-at", "--wait-on", "--slot", "--acp", "--prompt", "--registry", "--lane"], - }, - run: { - names: ["--wait", "--key", "--cost", "--fail-fast", "--label", "--shell"], - valued: ["--wait", "--key", "--cost", "--label", "--shell"], - // --shell takes one string and then the command is done. - stopAfter: ["--shell"], - // `run pytest -x` passes -x to the tool, not to coordinate. - singleDashIsCommand: true, - }, -}; - -// The command tokens the remainder split captured, per verb. The handlers -// read them from here instead of from the positional args. -const remainderCmds: Record = {}; - async function main(): Promise { - let argv = process.argv.slice(2); - let rest = argv.slice(1); + const argv = process.argv.slice(2); - // Help and version come first: they must work without a queue file and - // without opening the DB. + // Version comes first: it must work without a queue file. if (argv.length === 0) { - printRootHelp(); + // The library's root screen; exit 1 because the CLI is waiting for a verb. + runHelpOnly(); process.exit(1); } if (argv[0] === "--version" || argv[0] === "-V" || argv[0] === "version") { - const { CLI_VERSION } = await import("./version.ts"); process.stdout.write("coordinate " + CLI_VERSION + "\n"); return; } - if (argv[0] === "-h" || argv[0] === "--help") { - printRootHelp(); - return; - } - if (argv[0] === "help") { - if (argv.length === 1) { - printRootHelp(); - return; - } - const path = argv.slice(1).join(" "); - if (!printVerbHelp(path)) { - process.stderr.write("unknown command: " + path + " (run coordinate --help)\n"); - process.exit(1); - } - return; - } - - const verb = argv[0]; - - // A verb's own help request. The library would print its own screen for - // the library-dispatched verbs, so the request is intercepted here and - // every verb gets the same local screen. - // API-SWAP (0.9): the library's sectioned renderer replaces the local one - // and this branch disappears. - if (rest.indexOf("--help") >= 0 || rest.indexOf("-h") >= 0) { - if (!printVerbHelp(verb)) { - printRootHelp(); - } - return; - } - - // A group verb's help request: `lease --help` lists the sub-verbs and - // `lease acquire --help` documents one sub-verb. - if (GROUP_VERBS.indexOf(verb) >= 0 && (rest.indexOf("--help") >= 0 || rest.indexOf("-h") >= 0)) { - const path = rest[0] !== undefined && !rest[0].startsWith("-") ? verb + " " + rest[0] : verb; - if (!printVerbHelp(path)) { - printVerbHelp(verb); - } - return; - } - - // The REMAINDER verbs: the command tokens are split off before the - // library sees the argv, so a dash-leading command (`enqueue -- -odd`) - // and a command without `--` (`enqueue ls -la`) both work. - // API-SWAP (0.9: ArgSpec.remainder): the library's remainder spec does - // this split itself and this branch disappears. - if (verb === "enqueue" || verb === "run") { - const spec = REMAINDER_VERBS[verb]; - // A help request on a remainder verb prints the verb's own screen; the - // split would otherwise call --help an unknown option. - if (rest.indexOf("--help") >= 0 || rest.indexOf("-h") >= 0) { - if (!printVerbHelp(verb)) { - printRootHelp(); - } - return; - } - const split = splitRemainder(rest, spec); - if (!split.ok) { - fail(verb + ": unknown option " + split.badOption + " (put -- before a command that starts with a dash)"); - } - remainderCmds[verb] = split.cmd; - rest = split.flags; - argv = [verb].concat(split.flags); - } - - if (GROUP_VERBS.indexOf(verb) >= 0) { - const db = q.connect(); - if (verb === "lease") { - await cmdLease(db, rest); - } else if (verb === "agent") { - cmdAgent(db, rest); - } else if (verb === "cap") { - cmdCap(db, rest); - } else if (verb === "dead") { - cmdDead(db, rest); - } else if (verb === "service") { - await cmdService(rest); - } else { - await cmdDaemon(rest); - } - return; - } // Everything else goes through the library's seam: it picks the command - // node, parses the flags and dispatches to the handler. + // node, parses the flags, renders the help screens (`--help`, `help `, + // group-verb sub-screens), prints the did-you-mean block on an unknown verb + // and dispatches to the handler. const prog: ProgramSpec, readonly never[]> = { name: "coordinate", + version: CLI_VERSION, + description: ROOT_SUMMARY, + help: { width: 90 }, + learnMore: LEARN_MORE, commands: buildCommands(), }; const code = await runAsync(prog as unknown as ProgramSpec, readonly never[]>, argv); process.exit(code); } +// The library's root help screen, printed without a DB connection. +function runHelpOnly(): void { + const prog: ProgramSpec, readonly never[]> = { + name: "coordinate", + version: CLI_VERSION, + description: ROOT_SUMMARY, + help: { width: 90 }, + learnMore: LEARN_MORE, + commands: buildCommands(), + }; + // The library prints the screen and returns 0; the CLI with no arguments + // is waiting for a verb, so the exit stays 1. + run(prog as unknown as ProgramSpec, readonly never[]>, []); + process.exit(1); +} + main().catch((e) => { if (e instanceof ConfigError) { fail("coordinate: " + e.message); diff --git a/src/remainder.ts b/src/remainder.ts deleted file mode 100644 index b88e2eb..0000000 --- a/src/remainder.ts +++ /dev/null @@ -1,92 +0,0 @@ -// The argparse REMAINDER shape of `enqueue` and `run`: the flags come first, -// then the command, and everything from the first non-option token (or from -// an explicit `--`) belongs to the command. -// -// @cutils/cli 0.8.1 has no remainder arg spec, so the split happens here -// before the library sees the argv: the library only ever sees the flags, -// and the command tokens are handed to the handler verbatim. The 0.9.0 swap -// replaces this with the library's `ArgSpec.remainder` and deletes the file -// (see the API-SWAP markers in src/main.ts). - -// The flags a verb accepts before the command starts. A token that is not in -// the list ends the flag section: it is the start of the command, so a -// dash-leading token there is a command, not a mistyped option. -export interface FlagSpec { - // long flag names without the leading dashes - names: string[]; - // the flags that take a value (the value is the next token) - valued: string[]; - // flags that end the flag section (the tokens after them are the command) - stopAfter?: string[]; - // When true a single-dash token starts the command (a tool's own flag, - // e.g. `run pytest -x`). When false it is a mistyped option, because the - // verb's own flags are all long-form. - singleDashIsCommand?: boolean; -} - -// Split argv into the flag section and the command tokens. -export interface RemainderSplit { - ok: boolean; - // the flag tokens, minus the command part - flags: string[]; - // the command tokens, verbatim - cmd: string[]; - // the token that made the split invalid (a dash-leading unknown flag) - badOption: string; -} - -// Split argv at the first `--` or at the first token that is not a flag. -export function splitRemainder(argv: string[], spec: FlagSpec): RemainderSplit { - const flags: string[] = []; - const cmd: string[] = []; - const dashed = argv.indexOf("--"); - if (dashed >= 0) { - for (let i = 0; i < dashed; i++) { - flags.push(argv[i]); - } - for (let i = dashed + 1; i < argv.length; i++) { - cmd.push(argv[i]); - } - return { ok: true, flags, cmd, badOption: "" }; - } - let i = 0; - while (i < argv.length) { - const t = argv[i]; - const eq = t.indexOf("="); - const name = eq === -1 ? t : t.slice(0, eq); - if (spec.names.indexOf(name) === -1) { - // Not a flag of this verb: the command starts here. A dash-leading - // token is a mistyped option, unless the verb accepts single-dash - // command flags. - if (name.startsWith("--")) { - return { ok: false, flags: [], cmd: [], badOption: t }; - } - if (name.startsWith("-") && spec.singleDashIsCommand !== true) { - return { ok: false, flags: [], cmd: [], badOption: t }; - } - break; - } - flags.push(t); - // A valued flag takes the next token as its value. - if (eq === -1 && spec.valued.indexOf(name) >= 0) { - i = i + 1; - if (i >= argv.length) { - // The value is missing: hand the flag over alone and let the - // library report the missing value. - break; - } - flags.push(argv[i]); - } - i = i + 1; - // A stop-after flag ends the flag section: the tokens after it are the - // command (`run --shell 'cmd'` keeps 'cmd' as the shell value and ends - // the flag section). - if (eq === -1 && spec.stopAfter !== undefined && spec.stopAfter.indexOf(name) >= 0) { - break; - } - } - for (let j = i; j < argv.length; j++) { - cmd.push(argv[j]); - } - return { ok: true, flags, cmd, badOption: "" }; -} diff --git a/test/help.test.mjs b/test/help.test.mjs index f324632..8c12f32 100644 --- a/test/help.test.mjs +++ b/test/help.test.mjs @@ -68,24 +68,29 @@ test("every verb answers --help with its own screen and exit 0", () => { } }); -test("help matches --help for the group verbs", () => { +test("help matches --help", () => { const r = rig(); - // Library-dispatched verbs render through the library's screen, group - // verbs through the local renderer; both paths agree for group verbs. - // API-SWAP (0.9): the assertion extends to every verb. - for (const verb of ["lease", "cap", "dead", "agent"]) { + for (const verb of ["lease", "cap", "dead", "agent", "enqueue", "jobs"]) { const a = cli(r, verb, "--help"); const b = cli(r, "help", verb); assert.equal(a.stdout, b.stdout, verb + " help screens differ between --help and help"); } }); -test("help for an unknown verb fails with a pointer to the root screen", () => { +test("help for an unknown verb fails with the usage line", () => { const r = rig(); const out = cli(r, "help", "definitely-not-a-verb"); assert.equal(out.status, 1); assert.match(out.stderr, /unknown command/); - assert.match(out.stderr, /--help/); + assert.match(out.stderr, /Usage:/); +}); + +test("a typo of a verb gets a did-you-mean block", () => { + const r = rig(); + const out = cli(r, "statu"); + assert.equal(out.status, 1); + assert.match(out.stderr, /Did you mean this\?/); + assert.match(out.stderr, /status/); }); test("an unknown verb exits 1 with an error naming the command", () => {