Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
fix(cli): clarify usage errors and preserve query context
kashorinb4389a3af742
diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 6bb05699..871bce04 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -14,6 +14,11 @@ invent targets, candidates or Provider choices.Human and JSON output answer the same command-specific question. `--json` changes encoding;`--verbose` expands scope. Compiler, Runtime and Repository objects are not default reports.+Argument errors use `CLI_USAGE` and point to the relevant `hypit help <command>`; JSON retains that+command in `error.help`. Unknown help topics fail explicitly. Runtime and execution failures retain+their own diagnostics and optional `--debug` trace. Result pagination changes only the `--before`+cursor on the current query, preserving its project, Source filter and other options.+| Command | Default scope | Explicit detail || --- | --- | --- || `check` | Validation, targets and counts | `--verbose`: exported names/types and historical references |@@ -113,6 +118,9 @@ flow.execution phases and Provider diagnostics. It reads a finished Result directly, without opening theRuntime; an active Build is read through Runtime control. The selected Repository handles file access.`--lines` limits the tail and the report states the omitted count; JSON carries records plus that count.+An unavailable log reports `source: "unavailable"` and exits unsuccessfully; a readable log with zero+records is a successful empty result. The human report distinguishes a finished Result with no log+from a lookup that still needs the Build's Runtime or correct project selection.`inspect` exposes an available log separately from authored Outputs. `hypit runtime logs` reads theWorker process log instead, for Runtime startup or process-level failures.diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.tsindex 9ecf86f6..91644d62 100644--- a/packages/cli/src/arguments.ts+++ b/packages/cli/src/arguments.ts@@ -13,6 +13,7 @@ import type {RuntimeSelectionCommand,} from "./command.js";import type { CliColorMode, CliOutputOptions } from "./output.js";+import { CliUsageError } from "./usage-error.js";type RawOptions = {readonly presentation: CliOutputOptions;@@ -48,6 +49,15 @@ type RawOptions = {const commonOptions = ["--json", "--color", "--no-color", "--verbose", "--debug"] as const;export function parseCommand(argv: readonly string[]): CliCommand {+ try { return parseArguments(argv); }+ catch (error) {+ if (error instanceof CliUsageError) throw error;+ throw new CliUsageError(error instanceof Error ? error.message : String(error),+ argv[0] === undefined ? "hypit help" : `hypit help ${argv[0]}`, { cause: error });+ }+}++function parseArguments(argv: readonly string[]): CliCommand {const [command, ...tail] = argv;switch (command) {case "check": {@@ -246,7 +256,8 @@ export function parseCommand(argv: readonly string[]): CliCommand {...optionalPackageRoot(options),};}- default: throw new Error(usage());+ default: throw new CliUsageError(command === undefined ? "A command is required"+ : `Unknown command ${JSON.stringify(command)}`, "hypit help");}}diff --git a/packages/cli/src/commands/execution.ts b/packages/cli/src/commands/execution.tsindex 13e17146..48d2fb69 100644--- a/packages/cli/src/commands/execution.ts+++ b/packages/cli/src/commands/execution.ts@@ -83,13 +83,19 @@ export async function runExecutionCommand(input: {const records = view?.records ?? [];const omitted = (view?.total ?? 0) - records.length;write({ format: "hypit.cli-logs@1", build: args.build, source, records, omittedRecords: omitted },- view === undefined ? "No execution log recorded" : "Build execution log", "info",+ view === undefined ? "Execution log unavailable" : "Build execution log", view === undefined ? "warning" : "info",[["Build", args.build], ["Source", source]], [+ ...(view !== undefined ? [] : [finished+ ? "This Result has no saved execution log."+ : activeProfile === undefined+ ? "No saved log found in this project. Select the Build's Runtime with --runtime <profile> to check active execution."+ : "No log found in this project's Results or the selected Runtime. Check the Build id and project selection."]),...(omitted > 0 ? [`Showing last ${records.length} records; ${omitted} earlier records omitted. Use --lines to read more.`] : []),...records.map((record) => `${new Date(record.time).toISOString()} ${record.endpoint} ${record.command} ${record.kind === "phase" ? record.phase : record.kind === "diagnostic" || record.kind === "failed"? `${record.kind}: ${record.message}` : record.kind}`),]);+ if (view === undefined) io.setExitCode?.(1);return;}diff --git a/packages/cli/src/commands/results.ts b/packages/cli/src/commands/results.tsindex 52cd60d0..46e3cd9a 100644--- a/packages/cli/src/commands/results.ts+++ b/packages/cli/src/commands/results.ts@@ -54,7 +54,9 @@ export async function runProjectResultCommand(input: {const label = item.title === undefined ? item.id : `${item.title} · ${item.id}`;const run = item.run === undefined ? "" : ` · ${item.run}`;return `${label}: ${item.outcome} · ${new Date(item.createdAt).toLocaleString()}${run} · ${item.targetCount} target${item.targetCount === 1 ? "" : "s"}`;- }).concat(page.next === undefined ? [] : [`Older hypit builds --before ${page.next}`]));+ }).concat(page.next === undefined ? [] : [+ `Older Repeat this command with --before ${page.next}, keeping the other options.`,+ ]));return;}@@ -89,7 +91,9 @@ export async function runProjectResultCommand(input: {const label = item.title === undefined ? item.build : `${item.title} · ${item.build}`;return `${label}: ${item.outcome} · ${new Date(item.createdAt).toLocaleString()}`+ (args.presentation.verbose ? ` · ${item.output.kind} · ${item.output.type}` : "");- }).concat(page.next === undefined ? [] : [`Older hypit history ${args.outputName} --before ${page.next}`]));+ }).concat(page.next === undefined ? [] : [+ `Older Repeat this command with --before ${page.next}, keeping the other options.`,+ ]));return;}diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex 28b1abd5..cce5a6a9 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -62,7 +62,8 @@ export async function runCli(distribution: CliDistribution,): Promise<void> {if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {- const topic = argv[0] === "help" ? argv[1] : argv.includes("--help") ? argv[0] : undefined;+ const topic = argv[0] === "help" ? argv[1] : argv[0] === "--help" ? undefined+ : argv.includes("--help") ? argv[0] : undefined;writeCliHelp(io, topic);return;}diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex 09fa52d4..351fe46b 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -3,6 +3,7 @@ import { relative, resolve } from "node:path";import type { CanonicalValue } from "@hypit/protocol";import type { OperationalMachineView } from "./machine-view.js";+import { CliUsageError } from "./usage-error.js";export type CliTerminal = {readonly isTTY: boolean;@@ -986,6 +987,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {io.write(`${selected.join("\n")}\n`);return;}+ throw new CliUsageError(`Unknown help topic ${JSON.stringify(topic)}`, "hypit help");}io.write([colors.accent(colors.strong("Hypit")),@@ -1044,6 +1046,7 @@ export function renderCliError(error: unknown, options: {error: {code,message: source.message,+ ...(source instanceof CliUsageError ? { help: source.help } : {}),...(options.debug && trace !== undefined && trace.length > 0 ? { trace } : {}),},}, null, 2)}\n`;@@ -1058,6 +1061,8 @@ export function renderCliError(error: unknown, options: {];if (options.debug && trace !== undefined && trace.length > 0) {lines.push("", colors.dim(trace));+ } else if (source instanceof CliUsageError) {+ lines.push("", `Usage ${source.help}`);} else {lines.push("", colors.dim("Run with --debug to include the internal stack trace."));}diff --git a/packages/cli/src/usage-error.ts b/packages/cli/src/usage-error.tsnew file mode 100644index 00000000..d5ddbc5c--- /dev/null+++ b/packages/cli/src/usage-error.ts@@ -0,0 +1,8 @@+/** Argument errors point to public usage rather than an internal stack trace. */+export class CliUsageError extends Error {+ readonly code = "CLI_USAGE";+ constructor(message: string, readonly help: string, options?: ErrorOptions) {+ super(message, options);+ this.name = "CliUsageError";+ }+}diff --git a/packages/cli/test/build-results.test.ts b/packages/cli/test/build-results.test.tsindex 0dcfd678..d6ca3f7c 100644--- a/packages/cli/test/build-results.test.ts+++ b/packages/cli/test/build-results.test.ts@@ -33,11 +33,11 @@ function completedState(): BuildState {} as unknown as BuildState;}-async function fixture(root: string): Promise<void> {+async function fixture(root: string, id = "bld_20260902T110000000Z_0000000001", source = "main.svml"): Promise<void> {const result = await FileBuildResult.create(join(root, ".hypit", "results"), {- id: "bld_20260902T110000000Z_0000000001",+ id,title: "episode-stage",- source: { path: "main.svml" },+ source: { path: source },run: { path: "build.svrun" },targets: ["stage.value"],publishedOutputs: [{ name: "stage.value", output: "logical:stage" }],@@ -647,3 +647,43 @@ test("logs reads finished evidence without a Runtime and clearly limits the tailassert.match(await humanCommand(["logs", id, "--lines", "1"], root), /earlier records omitted/u);} finally { await rm(root, { recursive: true, force: true }); }});++test("history continuation keeps the same project and Source query", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit cli pagination "));+ try {+ const older = "bld_20260902T110000000Z_0000000001";+ const newer = "bld_20260902T110000002Z_0000000001";+ await fixture(root, older, "selected source.svml");+ await fixture(root, "bld_20260902T110000001Z_0000000001", "unrelated.svml");+ await fixture(root, newer, "selected source.svml");+ const args = ["history", "stage.value", "--source", join(root, "selected source.svml"), "--limit", "1"];+ const human = await humanCommand(args, root);+ assert.match(human, /Repeat this command with --before (\S+), keeping the other options/u);+ const cursor = /--before (\S+),/u.exec(human)![1]!;+ const next = await jsonCommand([...args, "--before", cursor], root) as { entries: { build: string }[] };+ assert.deepEqual(next.entries.map((item) => item.build), [older]);+ } finally { await rm(root, { recursive: true, force: true }); }+});++test("logs reports unavailable evidence as unsuccessful, while an existing empty log is valid", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-cli-missing-log-"));+ try {+ const id = "bld_20260902T110000000Z_0000000001";+ for (const state of ["missing", "no-log", "empty-log"] as const) {+ if (state === "no-log") await fixture(root);+ if (state === "empty-log") {+ const result = await FileBuildResult.create(join(root, ".hypit/results"), {+ id: "bld_20260902T110000001Z_0000000001", source: { path: "main.svml" }, targets: [], publishedOutputs: [],+ });+ await result.finish({ outcome: "complete", executionLog: (async function* () {})() });+ }+ let exit = 0;+ let output = "";+ await runCli(["logs", state === "empty-log" ? "bld_20260902T110000001Z_0000000001" : id, "--workspace", root, "--json"], {+ write: (text) => { output += text; }, setExitCode: (code) => { exit = code; },+ }, resultDistribution());+ assert.equal(exit, state === "empty-log" ? 0 : 1);+ assert.equal(JSON.parse(output).source, state === "empty-log" ? "result" : "unavailable");+ }+ } finally { await rm(root, { recursive: true, force: true }); }+});diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex a5bd3769..d9a3575e 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -381,3 +381,27 @@ test("Result help makes exact Output addressing explicit", () => {assert.match(output, /--output <name> --to <path>/u);assert.match(output, /Composite Output becomes a directory/u);});++test("argument errors give command help in text and JSON without suggesting a stack trace", () => {+ for (const [args, help] of [+ [["plan"], "hypit help plan"],+ [["status", "a-build", "--typo"], "hypit help status"],+ [["plna"], "hypit help"],+ ] as const) {+ let failure: unknown;+ try { parseCommand(args); } catch (error) { failure = error; }+ assert.ok(failure instanceof Error);+ const text = renderCliError(failure, { json: false, color: false, unicode: false, debug: false });+ assert.ok(text.includes(help));+ assert.doesNotMatch(text, /--debug|stack trace/u);+ const json = JSON.parse(renderCliError(failure, { json: true, color: false, unicode: false, debug: false }));+ assert.equal(json.error.code, "CLI_USAGE");+ assert.equal(json.error.help, help);+ }+});++test("an unknown help topic reports the typo without dumping unrelated commands", () => {+ let output = "";+ assert.throws(() => writeCliHelp({ write(text) { output += text; } }, "plna"), /Unknown help topic "plna"/u);+ assert.equal(output, "");+});