Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

feat(cli): add structured output and define durable runtime UX

kashorin1bb0acb4aaf3
diff --git a/docs/README.md b/docs/README.md
index a3edcab5..5cbfe888 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -26,6 +26,10 @@ the working tree contains only documents that should inform current implementati
locking, contributions and Host-selected facet activation.
- [`local-developer-runtime.md`](./local-developer-runtime.md) — local SQLite/filesystem
Runtime, recovery and environment replacement.
+- [`runtime-execution-control.md`](./runtime-execution-control.md) — target durable Build dispatch,
+ Worker lifecycle, transparent queue inspection and unambiguous Build/Operation cancellation.
+- [`cli-experience.md`](./cli-experience.md) — complete human/CI/machine terminal design,
+ command hierarchy, visual language and decentralized Endpoint authentication.
- [`runtime-adapter-loading.md`](./runtime-adapter-loading.md) — separately locked Provider
and Store activation, physical-code identity, diagnostics and explicit Artifact maintenance.
- [`build-archive-and-egress.md`](./build-archive-and-egress.md) — Targets, durable Records,
diff --git a/docs/guide/services.md b/docs/guide/services.md
index dc270ef4..465f2792 100644
--- a/docs/guide/services.md
+++ b/docs/guide/services.md
@@ -5,9 +5,13 @@ description: Setting up the WhisperX and OpenCV services.
# Local Services
-Local Builds may depend on managed sidecars, managed tool assets or operator-owned executables.
+Local Builds may depend on managed daemons, prepared tool assets or operator-owned executables.
They are Runtime deployment concerns, not part of Core or the author language.
+This page describes the current pre-Worker command surface. The domain-neutral target separates
+prepared tools, managed daemons, remote dependency probes and the Build Worker beneath one
+`runtime` lifecycle; see [`../runtime-execution-control.md`](../runtime-execution-control.md).
+
For an installed Runtime Profile, prefer the profile-scoped lifecycle:
```bash
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 5e2a926f..a2219ce7 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -25,3 +25,9 @@ Another domain can reuse this command engine without installing any video packag
`check` accepts any self-described Author or Run Source whose Header names a trusted Frontend.
`plan` and `build` require a Run Source. Targets, Candidate selections and substitute fidelity may
not be synthesized by CLI flags; they are visible Run Graph meaning.
+
+The command engine has one structured presentation seam. `check`, `plan` and `doctor` currently
+render compact human output by default; `--verbose` reveals closure identities and complete lists,
+while explicit `--json` preserves full machine-readable data without ANSI or progress prose.
+TTY capability is supplied only by the executable Distribution entrypoint. Providers, components
+and Frontends return structured facts and never print directly to the terminal.
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index a5914a6f..55bff8c7 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,5 +1,13 @@
export { materializeArtifact, materializeRecord } from "./archive.js";
export { runCli } from "./main.js";
+export { renderCliError, writeCliHelp, writeCliOutput } from "./output.js";
+export type {
+ CliColorMode,
+ CliIo,
+ CliOutputOptions,
+ CliPresentation,
+ CliTerminal,
+} from "./output.js";
export type {
CliCompilerOptions,
CliDistribution,
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 1abed1d7..516e970e 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -22,10 +22,8 @@ import {
} from "./archive.js";
import { collectRunFrontends, loadRunFile } from "./run-file.js";
import type { CliDistribution } from "./distribution.js";
-
-type CliIo = {
- readonly write: (text: string) => void;
-};
+import { writeCliHelp, writeCliOutput } from "./output.js";
+import type { CliColorMode, CliIo } from "./output.js";
type ParsedArgs = {
readonly command: string | undefined;
@@ -53,6 +51,9 @@ type ParsedArgs = {
readonly apply: boolean;
/** Leave the declared external programs alone; build against what is running. */
readonly noServices: boolean;
+ readonly json: boolean;
+ readonly color: CliColorMode;
+ readonly verbose: boolean;
};
function parseArgs(argv: readonly string[]): ParsedArgs {
@@ -79,8 +80,35 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
const pins: { output: string; build: string }[] = [];
let apply = false;
let noServices = false;
+ let json = false;
+ let color: CliColorMode = "auto";
+ let verbose = false;
for (let index = 0; index < rest.length; index += 1) {
const item = rest[index];
+ if (item === "--json") {
+ json = true;
+ continue;
+ }
+ if (item === "--verbose") {
+ verbose = true;
+ continue;
+ }
+ if (item === "--debug") {
+ continue;
+ }
+ if (item === "--no-color") {
+ color = "never";
+ continue;
+ }
+ if (item === "--color") {
+ const value = rest[index + 1];
+ if (value !== "auto" && value !== "always" && value !== "never") {
+ throw new Error("--color requires auto, always or never");
+ }
+ color = value;
+ index += 1;
+ continue;
+ }
if (item === "--target") {
const target = rest[index + 1];
if (target === undefined || target.startsWith("--")) throw new Error("--target requires an export name");
@@ -227,6 +255,9 @@ function parseArgs(argv: readonly string[]): ParsedArgs {
pins,
apply,
noServices,
+ json,
+ color,
+ verbose,
};
}
@@ -245,6 +276,9 @@ function usage(): string {
" narratage inspect <build-id> --runtime profile.json|./svml.runtime.ts",
" narratage get <build-id> --runtime profile.json|./svml.runtime.ts [--name source-name|--record record-id|--output logical-output-id|--artifact digest] [--to path]",
" narratage cancel <build-id> --runtime profile.json|./svml.runtime.ts",
+ "",
+ "output:",
+ " --json --verbose --color auto|always|never --no-color --debug",
].join("\n");
}
@@ -345,6 +379,10 @@ export async function runCli(
io: CliIo,
distribution: CliDistribution,
): Promise<void> {
+ if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {
+ writeCliHelp(io);
+ return;
+ }
const args = parseArgs(argv);
const known = args.command === "lock-packages" || args.command === "check" || args.command === "plan"
|| args.command === "build" || args.command === "status" || args.command === "builds"
@@ -371,12 +409,15 @@ export async function runCli(
|| args.packages.length > 0 || args.apply) {
throw new Error("doctor reads all deployment selection from the Runtime Profile itself");
}
- const result = await distribution.doctorRuntimeConfig(resolve(args.file!));
- io.write(`${JSON.stringify({
+ const profile = resolve(args.file!);
+ const result = await distribution.doctorRuntimeConfig(profile);
+ const machine = {
+ format: "narratage.cli-doctor@1" as const,
ok: !result.diagnostics.some((item) => item.severity === "error"),
root: result.root,
diagnostics: result.diagnostics,
- }, null, 2)}\n`);
+ };
+ writeCliOutput(io, args, { kind: "doctor", machine, profile });
return;
}
if (args.command === "services") {
@@ -602,7 +643,9 @@ export async function runCli(
loadedPackageSet?.lock.digest,
);
const selected = loaded.run.graph.targetSets.find((item) => item.id === loaded.run.graph.selectedTargets)!;
- io.write(`${JSON.stringify({
+ const machine = {
+ format: "narratage.cli-check@1" as const,
+ sourceKind: "run" as const,
ok: true,
run: loaded.path,
source: loaded.authorSource,
@@ -618,11 +661,18 @@ export async function runCli(
candidates: loaded.run.candidates,
satisfactions: loaded.run.graph.satisfactions,
steps: planned.plan.steps.length,
- }, null, 2)}\n`);
+ } as const;
+ writeCliOutput(io, args, {
+ kind: "check-run",
+ machine,
+ frontend: sourceHeader.using,
+ });
return;
}
const result = await compiler.compileSource(workspace.entry, workspace);
- io.write(`${JSON.stringify({
+ const machine = {
+ format: "narratage.cli-check@1" as const,
+ sourceKind: "author" as const,
ok: true,
sourceClosure: result.closure.id,
moduleClosure: result.program.closure.digest,
@@ -631,7 +681,13 @@ export async function runCli(
sourceAssets: result.attachments.map((item) => item.artifact),
modules: result.program.closure.modules.map((item) => `${item.ref.name}@${item.ref.version}`),
exports: result.exports.map((item) => ({ name: item.name, type: item.type, kind: item.ref.kind })),
- }, null, 2)}\n`);
+ } as const;
+ writeCliOutput(io, args, {
+ kind: "check-author",
+ machine,
+ source: workspace.entry.name,
+ frontend: sourceHeader.using,
+ });
return;
} finally {
await runtime?.close();
@@ -702,7 +758,12 @@ export async function runCli(
...(runtime === undefined ? {} : { runtime }),
});
const result = loaded.compiler.planCompilation(loaded, loadedPackageSet?.lock.digest);
- io.write(`${JSON.stringify(result.plan, null, 2)}\n`);
+ writeCliOutput(io, args, {
+ kind: "plan",
+ machine: result.plan,
+ run: loaded.path,
+ targetSet: loaded.run.graph.selectedTargets,
+ });
} finally {
await runtime?.close();
}
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
new file mode 100644
index 00000000..725d6f62
--- /dev/null
+++ b/packages/cli/src/output.ts
@@ -0,0 +1,413 @@
+import { relative, resolve } from "node:path";
+
+import type { BuildPlan, TypeRef } from "@narratage/protocol";
+
+export type CliTerminal = {
+ readonly isTTY: boolean;
+ readonly color: boolean;
+ readonly unicode: boolean;
+ readonly columns: number;
+};
+
+export type CliIo = {
+ readonly write: (text: string) => void;
+ readonly terminal?: CliTerminal;
+};
+
+export type CliColorMode = "auto" | "always" | "never";
+
+export type CliOutputOptions = {
+ readonly json: boolean;
+ readonly color: CliColorMode;
+ readonly verbose: boolean;
+};
+
+export type CliDiagnostic = {
+ readonly severity: "error" | "warning" | "info";
+ readonly code: string;
+ readonly message: string;
+ readonly subject?: string;
+};
+
+export type DoctorOutput = {
+ readonly format: "narratage.cli-doctor@1";
+ readonly ok: boolean;
+ readonly root: string;
+ readonly diagnostics: readonly CliDiagnostic[];
+};
+
+export type AuthorCheckOutput = {
+ readonly format: "narratage.cli-check@1";
+ readonly sourceKind: "author";
+ readonly ok: true;
+ readonly sourceClosure: string;
+ readonly moduleClosure: string;
+ readonly graph: string;
+ readonly units: number;
+ readonly sourceAssets: readonly unknown[];
+ readonly modules: readonly string[];
+ readonly exports: readonly {
+ readonly name: string;
+ readonly type: TypeRef;
+ readonly kind: string;
+ }[];
+};
+
+export type RunCheckOutput = {
+ readonly format: "narratage.cli-check@1";
+ readonly sourceKind: "run";
+ readonly ok: true;
+ readonly run: string;
+ readonly source: string;
+ readonly authorSourceClosure: string;
+ readonly runSourceClosure: string;
+ readonly authorModuleClosure: string;
+ readonly executionModuleClosure: string;
+ readonly authorGraph: string;
+ readonly runGraph: string;
+ readonly graph: string;
+ readonly targetSet: string;
+ readonly targets: readonly unknown[];
+ readonly candidates: Readonly<Record<string, string>>;
+ readonly satisfactions: readonly unknown[];
+ readonly steps: number;
+};
+
+export type CliPresentation =
+ | {
+ readonly kind: "doctor";
+ readonly machine: DoctorOutput;
+ readonly profile: string;
+ }
+ | {
+ readonly kind: "check-author";
+ readonly machine: AuthorCheckOutput;
+ readonly source: string;
+ readonly frontend: string;
+ }
+ | {
+ readonly kind: "check-run";
+ readonly machine: RunCheckOutput;
+ readonly frontend: string;
+ }
+ | {
+ readonly kind: "plan";
+ readonly machine: BuildPlan;
+ readonly run: string;
+ readonly targetSet: string;
+ };
+
+type Palette = {
+ readonly accent: (value: string) => string;
+ readonly success: (value: string) => string;
+ readonly warning: (value: string) => string;
+ readonly error: (value: string) => string;
+ readonly dim: (value: string) => string;
+ readonly strong: (value: string) => string;
+};
+
+const ansi = (open: number, close: number) => (enabled: boolean) => (value: string): string =>
+ enabled ? `\u001b[${open}m${value}\u001b[${close}m` : value;
+
+function palette(enabled: boolean): Palette {
+ return {
+ accent: ansi(36, 39)(enabled),
+ success: ansi(32, 39)(enabled),
+ warning: ansi(33, 39)(enabled),
+ error: ansi(31, 39)(enabled),
+ dim: ansi(2, 22)(enabled),
+ strong: ansi(1, 22)(enabled),
+ };
+}
+
+function colorEnabled(io: CliIo, mode: CliColorMode): boolean {
+ if (mode === "never") return false;
+ if (mode === "always") return true;
+ return io.terminal?.isTTY === true && io.terminal.color;
+}
+
+function glyph(io: CliIo, unicode: string, ascii: string): string {
+ return io.terminal?.unicode === false ? ascii : unicode;
+}
+
+function shortPath(path: string): string {
+ const absolute = resolve(path);
+ const local = relative(process.cwd(), absolute);
+ return local.length > 0 && !local.startsWith("..") ? local : absolute;
+}
+
+function shortIdentity(value: string): string {
+ if (!value.startsWith("sha256:") || value.length <= 22) return value;
+ return `${value.slice(0, 15)}…${value.slice(-6)}`;
+}
+
+function shortOpaque(value: string): string {
+ if (value.length <= 38) return value;
+ return `${value.slice(0, 24)}…${value.slice(-8)}`;
+}
+
+function typeName(type: TypeRef): string {
+ return `${type.module.name}@${type.module.version}/${type.name}`;
+}
+
+function facts(rows: readonly (readonly [string, string])[], colors: Palette): string[] {
+ const width = Math.max(...rows.map(([name]) => name.length), 0);
+ return rows.map(([name, value]) => ` ${colors.dim(name.padEnd(width))} ${value}`);
+}
+
+function heading(status: "success" | "warning" | "error" | "info", text: string, io: CliIo, colors: Palette): string {
+ const mark = status === "success"
+ ? colors.success(glyph(io, "✓", "+"))
+ : status === "warning"
+ ? colors.warning("!")
+ : status === "error"
+ ? colors.error(glyph(io, "×", "x"))
+ : colors.accent(glyph(io, "•", "i"));
+ return `${mark} ${colors.strong(text)}`;
+}
+
+function renderDoctor(view: Extract<CliPresentation, { kind: "doctor" }>, io: CliIo, colors: Palette): string {
+ const errors = view.machine.diagnostics.filter((item) => item.severity === "error");
+ const warnings = view.machine.diagnostics.filter((item) => item.severity === "warning");
+ const lines = [colors.accent(colors.strong("Narratage Doctor")), ""];
+ lines.push(...facts([
+ ["Profile", shortPath(view.profile)],
+ ["Root", shortPath(view.machine.root)],
+ ], colors));
+ lines.push("");
+ if (view.machine.diagnostics.length === 0) {
+ lines.push(heading("success", "No problems found", io, colors));
+ } else {
+ for (const item of view.machine.diagnostics) {
+ const status = item.severity === "error" ? "error" : item.severity === "warning" ? "warning" : "info";
+ lines.push(heading(status, item.code, io, colors));
+ lines.push(` ${item.message}`);
+ if (item.subject !== undefined) lines.push(` ${colors.dim("Subject")} ${item.subject}`);
+ }
+ }
+ lines.push("");
+ const summary = `${errors.length} error${errors.length === 1 ? "" : "s"}`
+ + ` · ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
+ lines.push(view.machine.ok ? colors.success(summary) : colors.error(summary));
+ return `${lines.join("\n")}\n`;
+}
+
+function renderAuthorCheck(
+ view: Extract<CliPresentation, { kind: "check-author" }>,
+ io: CliIo,
+ colors: Palette,
+ verbose: boolean,
+): string {
+ const lines = [heading("success", "Source is valid", io, colors), ""];
+ lines.push(...facts([
+ ["Source", shortPath(view.source)],
+ ["Frontend", view.frontend],
+ ["Modules", String(view.machine.modules.length)],
+ ["Units", String(view.machine.units)],
+ ["Exports", String(view.machine.exports.length)],
+ ["Assets", String(view.machine.sourceAssets.length)],
+ ], colors));
+ if (view.machine.exports.length > 0) {
+ lines.push("", colors.strong("Exports"));
+ const ordered = [...view.machine.exports].sort((left, right) => {
+ const leftRank = left.kind === "logical-output" ? 0 : 1;
+ const rightRank = right.kind === "logical-output" ? 0 : 1;
+ return leftRank - rightRank || left.name.localeCompare(right.name);
+ });
+ const shown = verbose ? ordered : ordered.slice(0, 12);
+ const width = Math.max(...shown.map((item) => item.name.length));
+ for (const item of shown) {
+ lines.push(` ${colors.accent(item.name.padEnd(width))} ${typeName(item.type)} ${colors.dim(item.kind)}`);
+ }
+ if (shown.length < ordered.length) {
+ lines.push(` ${colors.dim(`${ordered.length - shown.length} more · use --verbose for the complete list`)}`);
+ }
+ }
+ if (verbose) {
+ lines.push("", colors.strong("Identity"));
+ lines.push(...facts([
+ ["Source closure", shortIdentity(view.machine.sourceClosure)],
+ ["Module closure", shortIdentity(view.machine.moduleClosure)],
+ ["Graph", shortIdentity(view.machine.graph)],
+ ], colors));
+ }
+ return `${lines.join("\n")}\n`;
+}
+
+function renderRunCheck(
+ view: Extract<CliPresentation, { kind: "check-run" }>,
+ io: CliIo,
+ colors: Palette,
+ verbose: boolean,
+): string {
+ const lines = [heading("success", "Run source is valid", io, colors), ""];
+ lines.push(...facts([
+ ["Run", shortPath(view.machine.run)],
+ ["Author", shortPath(view.machine.source)],
+ ["Frontend", view.frontend],
+ ["Target set", view.machine.targetSet],
+ ["Targets", String(view.machine.targets.length)],
+ ["Candidates", String(Object.keys(view.machine.candidates).length)],
+ ["Satisfactions", String(view.machine.satisfactions.length)],
+ ["Steps", String(view.machine.steps)],
+ ], colors));
+ if (verbose) {
+ lines.push("", colors.strong("Identity"));
+ lines.push(...facts([
+ ["Author graph", shortIdentity(view.machine.authorGraph)],
+ ["Run graph", shortIdentity(view.machine.runGraph)],
+ ["Build graph", shortIdentity(view.machine.graph)],
+ ["Author closure", shortIdentity(view.machine.authorSourceClosure)],
+ ["Run closure", shortIdentity(view.machine.runSourceClosure)],
+ ], colors));
+ }
+ return `${lines.join("\n")}\n`;
+}
+
+function renderPlan(
+ view: Extract<CliPresentation, { kind: "plan" }>,
+ io: CliIo,
+ colors: Palette,
+ verbose: boolean,
+): string {
+ const exact = view.machine.steps.filter((item) => item.fidelity === "exact").length;
+ const substitute = view.machine.steps.length - exact;
+ const grouped = new Map<string, number>();
+ for (const step of view.machine.steps) {
+ const name = `${step.producer.module.name}@${step.producer.module.version}`;
+ grouped.set(name, (grouped.get(name) ?? 0) + 1);
+ }
+ const lines = [heading("success", "Build plan is valid", io, colors), ""];
+ lines.push(...facts([
+ ["Run", shortPath(view.run)],
+ ["Target set", view.targetSet],
+ ["Goals", String(view.machine.goals.length)],
+ ["Steps", String(view.machine.steps.length)],
+ ["Exact", String(exact)],
+ ["Substitute", String(substitute)],
+ ], colors));
+ if (grouped.size > 0) {
+ lines.push("", colors.strong("Operations"));
+ const entries = [...grouped.entries()].sort(([left], [right]) => left.localeCompare(right));
+ const countWidth = Math.max(...entries.map(([, count]) => String(count).length));
+ for (const [name, count] of entries) {
+ lines.push(` ${colors.accent(String(count).padStart(countWidth))} ${name}`);
+ }
+ }
+ const visibleSelections = verbose
+ ? view.machine.selections
+ : view.machine.selections.filter((selection) => selection.fidelity === "substitute");
+ if (visibleSelections.length > 0) {
+ lines.push("", colors.strong("Selections"));
+ for (const selection of visibleSelections) {
+ const status = selection.fidelity === "exact"
+ ? colors.success(glyph(io, "✓", "+"))
+ : colors.warning("!");
+ lines.push(` ${status} ${shortOpaque(selection.output)} ${colors.dim(selection.fidelity)}`);
+ }
+ }
+ if (verbose) {
+ lines.push("", colors.strong("Identity"));
+ lines.push(...facts([
+ ["Plan", shortIdentity(view.machine.id)],
+ ["Graph", shortIdentity(view.machine.graph)],
+ ["Request", shortIdentity(view.machine.request)],
+ ], colors));
+ }
+ lines.push("", colors.dim("No external work was started."));
+ return `${lines.join("\n")}\n`;
+}
+
+export function writeCliOutput(
+ io: CliIo,
+ options: CliOutputOptions,
+ presentation: CliPresentation,
+): void {
+ if (options.json) {
+ io.write(`${JSON.stringify(presentation.machine, null, 2)}\n`);
+ return;
+ }
+ const colors = palette(colorEnabled(io, options.color));
+ const output = presentation.kind === "doctor"
+ ? renderDoctor(presentation, io, colors)
+ : presentation.kind === "check-author"
+ ? renderAuthorCheck(presentation, io, colors, options.verbose)
+ : presentation.kind === "check-run"
+ ? renderRunCheck(presentation, io, colors, options.verbose)
+ : renderPlan(presentation, io, colors, options.verbose);
+ io.write(output);
+}
+
+export function writeCliHelp(io: CliIo): void {
+ const colors = palette(io.terminal?.isTTY === true && io.terminal.color);
+ io.write([
+ colors.accent(colors.strong("Narratage")),
+ colors.dim("Write the story. Compile the result."),
+ "",
+ colors.strong("Authoring"),
+ " check <source> verify one self-described Author or Run source",
+ " plan <run-source> freeze and inspect a Build plan",
+ " build <run-source> execute a Build through a Runtime Profile",
+ "",
+ colors.strong("Archive"),
+ " builds list known Builds",
+ " status <build-id> show Build and Operation status",
+ " inspect <build-id> inspect accepted Records and demanded outputs",
+ " get <build-id> read or materialize one archived result",
+ " cancel <build-id> request cancellation (transitional command)",
+ "",
+ colors.strong("Runtime"),
+ " doctor <profile> validate deployment without executing",
+ " services up|status|down manage current local dependencies",
+ " gc <profile> report unreachable Artifacts; --apply deletes",
+ "",
+ colors.strong("Packages"),
+ " lock-packages <file> lock explicitly installed packages",
+ "",
+ colors.strong("Output"),
+ " --json complete machine-readable result",
+ " --verbose reveal identities and complete lists",
+ " --color auto|always|never control ANSI color",
+ " --debug include internal trace frames on failure",
+ "",
+ ].join("\n"));
+}
+
+export function renderCliError(error: unknown, options: {
+ readonly json: boolean;
+ readonly color: boolean;
+ readonly unicode: boolean;
+ readonly debug: boolean;
+}): string {
+ const source = error instanceof Error ? error : new Error(String(error));
+ const trace = source.stack?.split("\n").slice(1).join("\n").trim();
+ const candidateCode = (source as Error & { readonly code?: unknown }).code;
+ const code = typeof candidateCode === "string" && candidateCode.trim().length > 0
+ ? candidateCode
+ : "CLI_ERROR";
+ if (options.json) {
+ return `${JSON.stringify({
+ format: "narratage.cli-error@1",
+ ok: false,
+ error: {
+ code,
+ message: source.message,
+ ...(options.debug && trace !== undefined && trace.length > 0 ? { trace } : {}),
+ },
+ }, null, 2)}\n`;
+ }
+ const colors = palette(options.color);
+ const mark = options.unicode ? "×" : "x";
+ const lines = [
+ `${colors.error(mark)} ${colors.strong("Command failed")}`,
+ "",
+ ` ${colors.error(code)}`,
+ ...source.message.split("\n").map((line) => ` ${line}`),
+ ];
+ if (options.debug && trace !== undefined && trace.length > 0) {
+ lines.push("", colors.dim(trace));
+ } else {
+ lines.push("", colors.dim("Run with --debug to include the internal stack trace."));
+ }
+ return `${lines.join("\n")}\n`;
+}
diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.ts
new file mode 100644
index 00000000..9a47bb4c
--- /dev/null
+++ b/packages/cli/test/output.test.ts
@@ -0,0 +1,176 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { BuildPlan } from "@narratage/protocol";
+
+import { renderCliError, writeCliHelp, writeCliOutput } from "../src/output.js";
+
+const digest = `sha256:${"1".repeat(64)}` as const;
+
+function capture(
+ options: Parameters<typeof writeCliOutput>[1],
+ presentation: Parameters<typeof writeCliOutput>[2],
+ terminal?: Parameters<typeof writeCliOutput>[0]["terminal"],
+): string {
+ let output = "";
+ writeCliOutput({
+ write(text) { output += text; },
+ ...(terminal === undefined ? {} : { terminal }),
+ }, options, presentation);
+ return output;
+}
+
+const human = { json: false, color: "auto", verbose: false } as const;
+
+test("author check renders a compact human summary without dumping identity", () => {
+ const output = capture(human, {
+ kind: "check-author",
+ source: "/project/main.svml",
+ frontend: "@narratage/markup@1",
+ machine: {
+ format: "narratage.cli-check@1",
+ sourceKind: "author",
+ ok: true,
+ sourceClosure: digest,
+ moduleClosure: digest,
+ graph: digest,
+ units: 2,
+ sourceAssets: [{ digest }],
+ modules: ["@narratage/script@1"],
+ exports: [{
+ name: "story",
+ type: { module: { name: "@narratage/narrative", version: "1" }, name: "Narrative" },
+ kind: "record",
+ }],
+ },
+ });
+ assert.match(output, /✓ Source is valid/u);
+ assert.match(output, /Frontend\s+@narratage\/markup@1/u);
+ assert.match(output, /story\s+@narratage\/narrative@1\/Narrative/u);
+ assert.doesNotMatch(output, /sha256:/u);
+ assert.doesNotMatch(output, /\u001b\[/u);
+});
+
+test("large author exports are bounded until verbose output is requested", () => {
+ const exports = Array.from({ length: 15 }, (_, index) => ({
+ name: `output-${String(index).padStart(2, "0")}`,
+ type: { module: { name: "example", version: "1" }, name: "Value" },
+ kind: "logical-output",
+ }));
+ const presentation = {
+ kind: "check-author" as const,
+ source: "/project/main.svml",
+ frontend: "example@1",
+ machine: {
+ format: "narratage.cli-check@1" as const,
+ sourceKind: "author" as const,
+ ok: true as const,
+ sourceClosure: digest,
+ moduleClosure: digest,
+ graph: digest,
+ units: 1,
+ sourceAssets: [],
+ modules: [],
+ exports,
+ },
+ };
+ const compact = capture(human, presentation);
+ assert.match(compact, /3 more · use --verbose/u);
+ assert.doesNotMatch(compact, /output-14/u);
+ assert.match(capture({ ...human, verbose: true }, presentation), /output-14/u);
+});
+
+test("verbose human output reveals shortened identities", () => {
+ const output = capture({ ...human, verbose: true }, {
+ kind: "check-author",
+ source: "/project/main.svml",
+ frontend: "@narratage/markup@1",
+ machine: {
+ format: "narratage.cli-check@1",
+ sourceKind: "author",
+ ok: true,
+ sourceClosure: digest,
+ moduleClosure: digest,
+ graph: digest,
+ units: 1,
+ sourceAssets: [],
+ modules: [],
+ exports: [],
+ },
+ });
+ assert.match(output, /Identity/u);
+ assert.match(output, /sha256:11111111…111111/u);
+});
+
+test("JSON mode is exact machine data with no terminal decoration", () => {
+ const machine = {
+ format: "narratage.cli-doctor@1" as const,
+ ok: false,
+ root: "/project",
+ diagnostics: [{ severity: "error" as const, code: "MISSING", message: "not found" }],
+ };
+ const output = capture({ json: true, color: "always", verbose: true }, {
+ kind: "doctor",
+ profile: "/project/svml.runtime.json",
+ machine,
+ }, { isTTY: true, color: true, unicode: true, columns: 100 });
+ assert.deepEqual(JSON.parse(output), machine);
+ assert.doesNotMatch(output, /Narratage Doctor/u);
+ assert.doesNotMatch(output, /\u001b\[/u);
+});
+
+test("plan groups operations by their declaring module", () => {
+ const plan: BuildPlan = {
+ format: "svml.plan@1",
+ id: digest,
+ graph: digest,
+ request: digest,
+ initialValues: [],
+ steps: [{
+ id: "step-1",
+ producer: { module: { name: "@narratage/media", version: "1" }, name: "inspect" },
+ fidelity: "exact",
+ inputs: {},
+ outputs: {},
+ needs: {},
+ }, {
+ id: "step-2",
+ producer: { module: { name: "@narratage/media", version: "1" }, name: "normalize" },
+ fidelity: "substitute",
+ inputs: {},
+ outputs: {},
+ needs: {},
+ }],
+ goals: [],
+ selections: [],
+ };
+ const output = capture(human, { kind: "plan", machine: plan, run: "/project/build.svrun", targetSet: "film" });
+ assert.match(output, /2\s+@narratage\/media@1/u);
+ assert.match(output, /Exact\s+1/u);
+ assert.match(output, /Substitute\s+1/u);
+ assert.match(output, /No external work was started\./u);
+});
+
+test("human errors expose stable codes while JSON errors remain parseable", () => {
+ const error = Object.assign(new Error("credential is absent"), { code: "RUNTIME_CREDENTIAL_MISSING" });
+ const humanError = renderCliError(error, { json: false, color: false, unicode: true, debug: false });
+ assert.match(humanError, /× Command failed/u);
+ assert.match(humanError, /RUNTIME_CREDENTIAL_MISSING/u);
+ const machine = JSON.parse(renderCliError(error, {
+ json: true,
+ color: true,
+ unicode: true,
+ debug: false,
+ })) as { readonly format: string; readonly error: { readonly code: string } };
+ assert.equal(machine.format, "narratage.cli-error@1");
+ assert.equal(machine.error.code, "RUNTIME_CREDENTIAL_MISSING");
+});
+
+test("help is a successful product surface rather than a usage error", () => {
+ let output = "";
+ writeCliHelp({ write(text) { output += text; } });
+ assert.match(output, /^Narratage\n/u);
+ assert.match(output, /Authoring/u);
+ assert.match(output, /--json/u);
+ assert.doesNotMatch(output, /CLI_ERROR/u);
+});
diff --git a/packages/local/package.json b/packages/local/package.json
index 7f6e1490..16401079 100644
--- a/packages/local/package.json
+++ b/packages/local/package.json
@@ -4,7 +4,9 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./config": "./src/config.ts",
+ "./external-services": "./src/external-services.ts"
},
"dependencies": {
"@narratage/artifact-store-fs": "workspace:*",
diff --git a/packages/local/src/config.ts b/packages/local/src/config.ts
index 4729692e..f4cf08db 100644
--- a/packages/local/src/config.ts
+++ b/packages/local/src/config.ts
@@ -15,7 +15,6 @@ import type {
RuntimeServiceState,
} from "@narratage/runtime-adapter";
-import { createProjectLocalRuntime } from "./runtime.js";
import type { LocalRuntime } from "./types.js";
export type RuntimeConfigEntry = {
@@ -357,6 +356,9 @@ export async function createRuntimeFromConfig(
path: string,
options: LoadRuntimeConfigOptions = {},
): Promise<LocalRuntime> {
+ // Diagnostics and lifecycle discovery must not initialize SQLite, Drivers or Endpoints.
+ // Load the executable Runtime assembly only on the command that actually constructs it.
+ const { createProjectLocalRuntime } = await import("./runtime.js");
const absolute = resolve(path);
const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));
const root = resolve(dirname(absolute), document.root ?? ".");
diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.ts
index 11eb3ae5..f9697bfa 100644
--- a/packages/video-cli/src/cli.ts
+++ b/packages/video-cli/src/cli.ts
@@ -1,8 +1,45 @@
#!/usr/bin/env node
-import { runVideoCli } from "./index.js";
+import { renderCliError, writeCliHelp } from "@narratage/cli";
+import type { CliIo } from "@narratage/cli";
-runVideoCli(process.argv.slice(2), { write: (text) => process.stdout.write(text) }).catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
- process.stderr.write(`${message}\n`);
+const argv = process.argv.slice(2);
+const json = argv.includes("--json");
+const debug = argv.includes("--debug");
+const colorIndex = argv.indexOf("--color");
+const colorMode = argv.includes("--no-color")
+ ? "never"
+ : colorIndex >= 0 ? argv[colorIndex + 1] : "auto";
+const color = !json && colorMode !== "never" && process.env.TERM !== "dumb"
+ && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stdout.isTTY === true));
+const unicode = process.env.TERM !== "dumb";
+
+const io: CliIo = {
+ write: (text) => process.stdout.write(text),
+ terminal: {
+ isTTY: process.stdout.isTTY === true,
+ color,
+ unicode,
+ columns: process.stdout.columns ?? 100,
+ },
+};
+
+async function main(): Promise<void> {
+ if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {
+ writeCliHelp(io);
+ return;
+ }
+ const { runVideoCli } = await import("./index.js");
+ await runVideoCli(argv, io);
+}
+
+main().catch((error: unknown) => {
+ const rendered = renderCliError(error, {
+ json,
+ color: !json && colorMode !== "never" && process.env.TERM !== "dumb"
+ && (colorMode === "always" || (process.env.NO_COLOR === undefined && process.stderr.isTTY === true)),
+ unicode,
+ debug,
+ });
+ (json ? process.stdout : process.stderr).write(rendered);
process.exitCode = 1;
});
diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.ts
index bb2acf8c..09cd84e2 100644
--- a/packages/video-cli/src/distribution.ts
+++ b/packages/video-cli/src/distribution.ts
@@ -3,13 +3,6 @@ import {
createVideoCompiler,
videoBuiltInPackageContributions,
} from "./compiler.js";
-import {
- bringExternalServicesUp,
- doctorRuntimeConfig,
- reportExternalServices,
- takeExternalServicesDown,
-} from "@narratage/local";
-import { createVideoRuntimeFromConfig } from "./runtime-config.js";
const packageRoot = import.meta.dirname;
@@ -20,11 +13,26 @@ export const videoCliDistribution: CliDistribution = {
builtInPackageContributions: videoBuiltInPackageContributions,
runFrontends: [],
createCompiler: createVideoCompiler,
- createRuntimeFromConfig: createVideoRuntimeFromConfig,
- doctorRuntimeConfig: async (path) => await doctorRuntimeConfig(path, { packageRoot }),
+ createRuntimeFromConfig: async (path) => {
+ const { createVideoRuntimeFromConfig } = await import("./runtime-config.js");
+ return await createVideoRuntimeFromConfig(path);
+ },
+ doctorRuntimeConfig: async (path) => {
+ const { doctorRuntimeConfig } = await import("@narratage/local/config");
+ return await doctorRuntimeConfig(path, { packageRoot });
+ },
externalServices: {
- up: async (path, options) => await bringExternalServicesUp(path, { ...options, packageRoot }),
- down: async (path) => await takeExternalServicesDown(path, { packageRoot }),
- report: async (path) => await reportExternalServices(path, { packageRoot }),
+ up: async (path, options) => {
+ const { bringExternalServicesUp } = await import("@narratage/local/external-services");
+ return await bringExternalServicesUp(path, { ...options, packageRoot });
+ },
+ down: async (path) => {
+ const { takeExternalServicesDown } = await import("@narratage/local/external-services");
+ return await takeExternalServicesDown(path, { packageRoot });
+ },
+ report: async (path) => {
+ const { reportExternalServices } = await import("@narratage/local/external-services");
+ return await reportExternalServices(path, { packageRoot });
+ },
},
};
diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.ts
index 3d8e4fe1..816ffe88 100644
--- a/packages/video-cli/src/index.ts
+++ b/packages/video-cli/src/index.ts
@@ -3,6 +3,7 @@ import {
materializeRecord,
runCli,
} from "@narratage/cli";
+import type { CliIo } from "@narratage/cli";
import type { NodePackageContribution } from "@narratage/package-loader-node";
import { videoCliDistribution } from "./distribution.js";
@@ -12,14 +13,16 @@ export {
createVideoCompiler,
videoBuiltInPackageContributions,
} from "./compiler.js";
-export {
- createVideoRuntimeFromConfig,
-} from "./runtime-config.js";
export { videoCliDistribution } from "./distribution.js";
+export async function createVideoRuntimeFromConfig(path: string) {
+ const implementation = await import("./runtime-config.js");
+ return await implementation.createVideoRuntimeFromConfig(path);
+}
+
export function runVideoCli(
argv: readonly string[],
- io: { readonly write: (text: string) => void },
+ io: CliIo,
packageContributions: readonly NodePackageContribution[] = [],
): Promise<void> {
return runCli(argv, io, {
diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.ts
index d5114c98..aec64881 100644
--- a/packages/video-cli/test/cli.test.ts
+++ b/packages/video-cli/test/cli.test.ts
@@ -13,7 +13,7 @@ import { videoTestPackages } from "./packages.js";
const runCli = (
argv: readonly string[],
io: { readonly write: (text: string) => void },
-) => runVideoCli(argv, io, videoTestPackages);
+) => runVideoCli([...argv, "--json"], io, videoTestPackages);
test("production video CLI has no implicit author or Run packages", async () => {
const root = await mkdtemp(join(tmpdir(), "svml-cli-empty-distribution-"));
diff --git a/tsconfig.json b/tsconfig.json
index 7966f520..227e9b4b 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -151,6 +151,12 @@
"@narratage/local": [
"packages/local/src/index.ts"
],
+ "@narratage/local/config": [
+ "packages/local/src/config.ts"
+ ],
+ "@narratage/local/external-services": [
+ "packages/local/src/external-services.ts"
+ ],
"@narratage/generation": [
"packages/generation/src/index.ts"
],