@staix/agent-research 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +93 -22
  3. package/package.json +4 -1
  4. package/src/cli-output.ts +446 -0
  5. package/src/cli.ts +208 -66
  6. package/src/commands-table.ts +213 -93
  7. package/src/commands.ts +86 -17
  8. package/src/exp/artifacts.ts +20 -2
  9. package/src/exp/attempts.ts +26 -9
  10. package/src/exp/calibrate.ts +125 -0
  11. package/src/exp/executor.ts +130 -21
  12. package/src/exp/final.ts +12 -3
  13. package/src/exp/idea-report.ts +97 -0
  14. package/src/exp/ideas.ts +90 -6
  15. package/src/exp/investigate.ts +25 -22
  16. package/src/exp/metrics.ts +3 -5
  17. package/src/exp/protocol.ts +28 -3
  18. package/src/exp/reuse-admission.ts +3 -1
  19. package/src/exp/reuse-runtime.ts +5 -1
  20. package/src/exp/screen.ts +83 -0
  21. package/src/exp/selection.ts +110 -4
  22. package/src/exp/snapshot.ts +28 -8
  23. package/src/exp/stages.ts +3 -1
  24. package/src/harness/transitions.ts +37 -5
  25. package/src/manifest.ts +13 -5
  26. package/src/mcp-tools.ts +67 -14
  27. package/src/memory/archive.ts +8 -3
  28. package/src/paper/build.ts +39 -25
  29. package/src/paper/check.ts +46 -15
  30. package/src/paper/dependencies.ts +47 -0
  31. package/src/paper/document.ts +19 -0
  32. package/src/paper/figures.ts +152 -0
  33. package/src/paper/hygiene.ts +16 -5
  34. package/src/paper/plan.ts +71 -29
  35. package/src/paper/point-evidence.ts +27 -12
  36. package/src/paper/render.ts +113 -0
  37. package/src/paper/renderer.ts +128 -0
  38. package/src/paper/review.ts +41 -5
  39. package/src/plan/definition.ts +6 -1
  40. package/src/playbook.ts +21 -11
  41. package/src/provenance.ts +4 -3
  42. package/src/study-export.ts +7 -4
  43. package/src/study.ts +9 -4
  44. package/src/ui/plugin.ts +3 -1
package/src/cli.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { paperDocument } from "./paper/document.ts";
1
2
  import { version } from "../package.json";
2
- import { findCommand, help, type CommandSpec } from "./commands-table.ts";
3
+ import { findCommand, helpUsage, type CommandSpec } from "./commands-table.ts";
4
+ import { fillMessage, colorFor, outputAscii, renderError, renderHelp, renderResult, streamWidth, usageHint, type OutputContext, type OutputOptions } from "./cli-output.ts";
3
5
  import * as ops from "./commands.ts";
6
+ import { validateCalibrationOptions, type CalibrationOptions } from "./exp/calibrate.ts";
4
7
  import { createHttp, type Http } from "./http.ts";
5
8
  import { PLAYBOOK } from "./playbook.ts";
6
9
  import { validateExecutionReference } from "./provenance.ts";
@@ -9,32 +12,57 @@ import { detectActor, openStudy, readTextBounded, releaseStudyLocksForExit } fro
9
12
  const INPUT_BYTES = 65_536;
10
13
  export interface Io extends ops.ExperimentRuntime { readStdin?: () => Promise<string>; http?: Http; signal?: AbortSignal }
11
14
 
12
- function parse(spec: CommandSpec, args: string[]): { flags: Record<string, string | true>; positional: string[] } {
15
+ class UsageError extends Error {}
16
+
17
+ interface CliOutput {
18
+ options: OutputOptions;
19
+ context?: OutputContext;
20
+ spec?: CommandSpec;
21
+ tty?: boolean;
22
+ columns?: number;
23
+ }
24
+
25
+ export function parse(spec: CommandSpec, args: string[], output: OutputOptions = {}): { flags: Record<string, string | true>; positional: string[] } {
13
26
  const flags: Record<string, string | true> = {}, positional: string[] = [];
14
27
  for (let i = 0; i < args.length; i++) {
15
- const word = args[i]!;
28
+ const arg = args[i]!;
29
+ const word = arg.startsWith("--color=") ? "--color" : arg;
30
+ if (word === "--ascii" || word === "--color") {
31
+ if (word in flags) throw new UsageError(`${spec.name}: repeated option ${word}`);
32
+ if (word === "--ascii") {
33
+ flags[word] = output.ascii = true;
34
+ } else {
35
+ const value = arg === word ? args[++i] : arg.slice("--color=".length);
36
+ if (value === undefined || value.startsWith("--")) throw new UsageError("--color: expected auto, always or never");
37
+ flags[word] = output.color = value;
38
+ }
39
+ continue;
40
+ }
16
41
  if (word === "-" || !word.startsWith("-")) { positional.push(word); continue; }
17
42
  const kind = spec.options[word];
18
- if (!kind || word in flags) throw new Error(`${spec.name}: unknown or repeated option ${word}; use ares --help and pass each supported option once`);
43
+ if (!kind || word in flags) throw new UsageError(`${spec.name}: unknown or repeated option ${word}; use ares --help and pass each supported option once`);
19
44
  if (kind === "value") {
20
45
  const value = args[++i];
21
- if (value === undefined || (value.startsWith("--") && value !== "-")) throw new Error(`${spec.name}: ${word} needs a value; use ares --help for its accepted values`);
46
+ if (value === undefined || (value.startsWith("--") && value !== "-")) throw new UsageError(`${spec.name}: ${word} needs a value; use ares --help for its accepted values`);
22
47
  flags[word] = value;
23
- } else flags[word] = true;
48
+ } else {
49
+ flags[word] = true;
50
+ if (word === "--json") output.json = true;
51
+ }
24
52
  }
25
53
  return { flags, positional };
26
54
  }
27
55
  function count(spec: CommandSpec, positional: string[], min: number, max = min): void {
28
- if (positional.length < min || positional.length > max) throw new Error(`usage: ares ${spec.usage}`);
56
+ if (positional.length < min || positional.length > max) throw new UsageError(`usage: ares ${spec.usage}`);
29
57
  }
30
58
  function integer(value: string | true | undefined, what: string): number | undefined {
31
59
  if (value === undefined) return undefined;
32
- if (typeof value !== "string" || !/^\d{1,7}$/.test(value)) throw new Error(`${what}: integer required; pass a nonnegative decimal integer`);
60
+ if (typeof value !== "string" || !/^\d{1,7}$/.test(value)) throw new UsageError(`${what}: integer required; pass a nonnegative decimal integer`);
33
61
  return Number(value);
34
62
  }
35
63
  function seed(value: string | undefined): number | undefined {
36
64
  if (value === undefined) return undefined;
37
- if (!/^-?\d{1,10}$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < -2_147_483_648 || Number(value) > 2_147_483_647) throw new Error("--seed: invalid integer; use a declared protocol seed in -2147483648..2147483647");
65
+ if (!/^-?\d{1,10}$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < -2_147_483_648 || Number(value) > 2_147_483_647) throw new UsageError("--seed: invalid integer; use a declared protocol seed in -2147483648..2147483647");
38
66
  return Number(value);
39
67
  }
40
68
  async function readInput(path: string, io: Io): Promise<unknown> {
@@ -48,20 +76,61 @@ async function readInput(path: string, io: Io): Promise<unknown> {
48
76
  }
49
77
 
50
78
  export async function run(args: string[], env: NodeJS.ProcessEnv = process.env, io: Io = {}): Promise<{ text: string; code: number }> {
51
- if (!args.length || (args.length === 1 && ["--help", "-h", "help"].includes(args[0]!))) return { text: help(), code: 0 };
79
+ return execute(args, env, io, { options: {} });
80
+ }
81
+
82
+ async function execute(args: string[], env: NodeJS.ProcessEnv, io: Io, output: CliOutput): Promise<{ text: string; code: number }> {
83
+ const leadingHelp = args[0] === "help" || args[0] === "--help" || args[0] === "-h";
84
+ const helpArgs = leadingHelp ? args.slice(1) : args;
85
+ const helpCommand = args[0] === "help" || !leadingHelp ? findCommand(helpArgs) : undefined;
86
+ const trailingHelp = !leadingHelp && helpCommand?.rest[0] === "--help";
87
+ if (!args.length || leadingHelp || trailingHelp) {
88
+ const formatting = trailingHelp ? helpCommand.rest.slice(1) : helpCommand?.rest ?? helpArgs;
89
+ const spec = helpCommand?.spec;
90
+ if (spec) output.spec = spec;
91
+ const { positional } = parse({ name: spec?.name ?? "help", usage: "", mutates: false, options: {}, summary: "" }, formatting, output.options);
92
+ if (positional.length) {
93
+ throw new UsageError(spec ? `${spec.name}: unexpected help argument ${positional[0]}` : `unknown help command: ${positional.join(" ")}`);
94
+ }
95
+ const color = colorFor(output.options, output.tty ?? false, env);
96
+ if (color instanceof Error) throw new UsageError(color.message);
97
+ return { text: renderHelp(spec, color, outputAscii(output.options, env)), code: 0 };
98
+ }
52
99
  if (args.length === 1 && args[0] === "--version") return { text: version, code: 0 };
53
- const found = findCommand(args);
54
- if (!found) throw new Error(`unknown command: ${args.slice(0, 2).join(" ")}; use --help`);
55
- const { spec, rest } = found, { flags, positional } = parse(spec, rest);
100
+ const found = helpCommand;
101
+ if (!found) throw new UsageError(`unknown command: ${args.slice(0, 2).join(" ")}; use --help`);
102
+ const { spec, rest } = found;
103
+ output.spec = spec;
104
+ const { flags, positional } = parse(spec, rest, output.options);
105
+ const values: Record<string, string> = {};
106
+ const declaration = helpUsage(spec).slice(spec.name.length).trim().split(/\s+(?=\[?--)/)[0] ?? "";
107
+ for (const [index, token] of declaration.split(/\s+/).entries()) {
108
+ const key = /<([a-z][a-z0-9-]*)>/.exec(token)?.[1];
109
+ if (key && positional[index] !== undefined) values[key] = positional[index]!;
110
+ }
111
+ const commandArgs = [...spec.name.split(" "), ...positional];
112
+ for (const [flag, value] of Object.entries(flags)) {
113
+ if (typeof value === "string") values[flag] = value;
114
+ if (["--json", "--ascii", "--color"].includes(flag)) continue;
115
+ commandArgs.push(flag);
116
+ if (typeof value === "string") commandArgs.push(value);
117
+ }
118
+ output.context = { args: commandArgs, values, now: io.now?.() ?? Date.now() };
119
+ const color = colorFor(output.options, output.tty ?? false, env);
120
+ if (color instanceof Error) throw new UsageError(color.message);
56
121
  const ctx: ops.Ctx = { actor: detectActor(env), http: io.http ?? createHttp(env), ...(io.signal ? { signal: io.signal } : {}), ...(io.sleep ? { sleep: io.sleep } : {}), ...(io.runner ? { runner: io.runner } : {}), ...(io.now ? { now: io.now } : {}), ...(io.collectEvaluation ? { collectEvaluation: io.collectEvaluation } : {}), ...(io.collectStageEvidence ? { collectStageEvidence: io.collectStageEvidence } : {}) };
57
122
  const str = (flag: string) => (typeof flags[flag] === "string" ? flags[flag] as string : undefined);
123
+ const selectDocument = () => {
124
+ try { return paperDocument(str("--doc")); }
125
+ catch (error) { throw new UsageError(error instanceof Error ? error.message : "paper document: invalid --doc"); }
126
+ };
58
127
  let result: unknown, code = 0;
59
128
  switch (spec.name) {
60
129
  case "lineage show": {
61
130
  count(spec, positional, 1);
62
131
  const kind = str("--root"), id = str("--id"), revision = str("--revision"), hash = str("--sha256"), cursor = str("--cursor");
63
132
  const hasRoot = [kind, id, revision, hash].some(value => value !== undefined);
64
- if (hasRoot && (kind === undefined || id === undefined)) throw new Error("lineage show: partial root reference; pass --root KIND and --id ID together, with optional --revision/--sha256");
133
+ if (hasRoot && (kind === undefined || id === undefined)) throw new UsageError("lineage show: partial root reference; pass --root KIND and --id ID together, with optional --revision/--sha256");
65
134
  let root = hasRoot ? validateExecutionReference({ v: 1, tool: "ares", projectKey: "pending-study-identity", kind, id, ...(revision === undefined ? {} : { revision }), ...(hash === undefined ? {} : { sha256: hash }) }) : undefined;
66
135
  if (root) {
67
136
  let projectKey: string;
@@ -74,10 +143,10 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
74
143
  case "lineage compare": {
75
144
  count(spec, positional, 1);
76
145
  const attempts = str("--attempts"), candidates = str("--candidates");
77
- if (attempts !== undefined && candidates !== undefined) throw new Error("lineage compare: selection flags conflict; pass either --attempts ID,... or --candidates COMMIT,...");
146
+ if (attempts !== undefined && candidates !== undefined) throw new UsageError("lineage compare: selection flags conflict; pass either --attempts ID,... or --candidates COMMIT,...");
78
147
  const list = (value: string) => {
79
148
  const values = value.split(",");
80
- if (values.length < 1 || values.length > 8 || values.some(item => !item.trim())) throw new Error("lineage compare: selection needs 1..8 nonblank ids; pass a comma-separated --attempts or --candidates list");
149
+ if (values.length < 1 || values.length > 8 || values.some(item => !item.trim())) throw new UsageError("lineage compare: selection needs 1..8 nonblank ids; pass a comma-separated --attempts or --candidates list");
81
150
  return values;
82
151
  };
83
152
  result = ops.lineageCompare(positional[0]!, { ...(attempts === undefined ? {} : { attempts: list(attempts) }), ...(candidates === undefined ? {} : { candidates: list(candidates) }) }); break;
@@ -87,7 +156,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
87
156
  case "console list": count(spec, positional, 0); result = ops.consoleList(env); break;
88
157
  case "watch set": {
89
158
  count(spec, positional, 1); const file = str("--file");
90
- if (file === undefined) throw new Error("watch set: input missing; pass --file PATH or --file - for watch JSON");
159
+ if (file === undefined) throw new UsageError("watch set: input missing; pass --file PATH or --file - for watch JSON");
91
160
  result = await ops.watchSet(positional[0]!, await readInput(file, io), ctx); break;
92
161
  }
93
162
  case "watch run": {
@@ -97,7 +166,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
97
166
  case "watch show": count(spec, positional, 1); result = ops.watchShow(positional[0]!); break;
98
167
  case "setup": {
99
168
  count(spec, positional, 1);
100
- if (flags["--apply"] && flags["--undo"]) throw new Error("setup: --apply and --undo conflict; choose one or omit both for preview");
169
+ if (flags["--apply"] && flags["--undo"]) throw new UsageError("setup: --apply and --undo conflict; choose one or omit both for preview");
101
170
  const root = str("--root"); result = ops.setup(positional[0]!, flags["--apply"] ? "apply" : flags["--undo"] ? "undo" : "dry-run", env, { ...(root === undefined ? {} : { root }) });
102
171
  if ((result as ReturnType<typeof ops.setup>).actions.some(action => action.change === "refused")) code = 1;
103
172
  break;
@@ -107,19 +176,19 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
107
176
  case "lesson propose":
108
177
  case "lesson decide": {
109
178
  count(spec, positional, spec.name === "lesson propose" ? 1 : 2); const file = str("--file");
110
- if (file === undefined) throw new Error(`${spec.name}: input missing; pass --file PATH or --file - for bounded JSON`);
179
+ if (file === undefined) throw new UsageError(`${spec.name}: input missing; pass --file PATH or --file - for bounded JSON`);
111
180
  const raw = await readInput(file, io);
112
181
  result = spec.name === "lesson propose" ? await ops.lessonPropose(positional[0]!, raw, ctx, env) : await ops.lessonDecide(positional[0]!, positional[1]!, raw, ctx, env); break;
113
182
  }
114
183
  case "skill check": count(spec, positional, 2); result = await ops.skillCheck(positional[0]!, positional[1]!, ctx, env); break;
115
184
  case "skill propose": {
116
185
  count(spec, positional, 1); const file = str("--file");
117
- if (file === undefined) throw new Error("skill propose: input missing; pass --file PATH or --file - for proposal JSON");
186
+ if (file === undefined) throw new UsageError("skill propose: input missing; pass --file PATH or --file - for proposal JSON");
118
187
  result = await ops.skillPropose(positional[0]!, await readInput(file, io), ctx, env); break;
119
188
  }
120
189
  case "skill decide": {
121
190
  count(spec, positional, 3); const reason = str("--reason");
122
- if (reason === undefined) throw new Error("skill decide: reason missing; pass --reason TEXT and --pr URL for accept");
191
+ if (reason === undefined) throw new UsageError("skill decide: reason missing; pass --reason TEXT and --pr URL for accept");
123
192
  result = await ops.skillDecide(positional[0]!, positional[1]!, positional[2]!, reason, str("--pr"), ctx, undefined, env); break;
124
193
  }
125
194
  case "skill list": count(spec, positional, 1); result = ops.skillList(positional[0]!); break;
@@ -133,62 +202,72 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
133
202
  }
134
203
  case "run": {
135
204
  count(spec, positional, 1); const parallel = integer(flags["--parallel"], "--parallel");
136
- const completed = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}) }, ctx);
205
+ const completed = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}), env }, ctx);
137
206
  result = completed; if (completed.state === "failed") code = 1; break;
138
207
  }
139
208
  case "manifest": count(spec, positional, 0); result = ops.manifest(); break;
140
209
  case "playbook": count(spec, positional, 0); return { text: PLAYBOOK.trimEnd(), code: 0 };
141
- case "mcp": throw new Error("mcp: run `ares mcp` with no other arguments");
210
+ case "mcp": throw new UsageError("mcp: run `ares mcp` with no other arguments");
142
211
  case "autonomy show": count(spec, positional, 1); result = ops.autonomyShow(positional[0]!); break;
143
212
  case "autonomy set": count(spec, positional, 2); result = await ops.autonomySet(positional[0]!, positional[1]!, str("--phase"), ctx); break;
144
213
  case "init": {
145
214
  count(spec, positional, 1);
146
215
  const question = str("--question");
147
- if (question === undefined) throw new Error("init: --question is required");
216
+ if (question === undefined) throw new UsageError("init: --question is required");
148
217
  result = ops.init(positional[0]!, { question, ...(str("--mode") ? { mode: str("--mode")! } : {}), ...(str("--autonomy") ? { autonomy: str("--autonomy")! } : {}) }, ctx);
149
218
  break;
150
219
  }
151
220
  case "plan set": {
152
221
  count(spec, positional, 1);
153
222
  const file = str("--file");
154
- if (file === undefined) throw new Error("plan set: --file is required");
223
+ if (file === undefined) throw new UsageError("plan set: --file is required");
155
224
  result = await ops.planSet(positional[0]!, await readInput(file, io), ctx); break;
156
225
  }
157
226
  case "plan control": {
158
227
  count(spec, positional, 2, 3);
159
228
  const commandId = str("--command-id"), expectedRevision = integer(flags["--expected-revision"], "--expected-revision");
160
- if (!commandId || expectedRevision === undefined) throw new Error("plan control: command id and revision required; pass --command-id ID --expected-revision N from ares plan show");
229
+ if (!commandId || expectedRevision === undefined) throw new UsageError("plan control: command id and revision required; pass --command-id ID --expected-revision N from ares plan show");
161
230
  result = await ops.planControl(positional[0]!, { action: positional[1]! as Parameters<typeof ops.planControl>[1]["action"], ...(positional[2] !== undefined ? { node: positional[2] } : {}), commandId, expectedRevision }, ctx); break;
162
231
  }
163
232
  case "plan show": count(spec, positional, 1); result = ops.planShow(positional[0]!); break;
164
233
  case "status": count(spec, positional, 1); result = ops.status(positional[0]!); break;
165
234
  case "study export": {
166
235
  count(spec, positional, 1); const bundle = str("--bundle");
167
- if (bundle === undefined) throw new Error("study export: --bundle DIR is required; pass a new or empty output directory");
236
+ if (bundle === undefined) throw new UsageError("study export: --bundle DIR is required; pass a new or empty output directory");
168
237
  result = await ops.studyExport(positional[0]!, { bundle, ...(flags["--list"] ? { list: true } : {}) }); break;
169
238
  }
170
239
  case "scope": {
171
240
  count(spec, positional, 1);
172
241
  const file = str("--file");
173
- if (file === undefined) throw new Error("scope: --file is required");
242
+ if (file === undefined) throw new UsageError("scope: --file is required");
174
243
  result = await ops.scope(positional[0]!, await readInput(file, io), ctx);
175
244
  break;
176
245
  }
177
246
  case "idea add": {
178
247
  count(spec, positional, 1); const file = str("--file");
179
- if (file === undefined) throw new Error("idea add: input missing; pass --file PATH or --file - for JSON");
248
+ if (file === undefined) throw new UsageError("idea add: input missing; pass --file PATH or --file - for JSON");
180
249
  result = await ops.ideaAdd(positional[0]!, await readInput(file, io), ctx); break;
181
250
  }
182
251
  case "idea decide": {
183
252
  count(spec, positional, 3); const reason = str("--reason"), attempts = str("--attempts");
184
- if (reason === undefined) throw new Error("idea decide: reason missing; pass --reason TEXT and --commit SHA for refine, plus --attempts for an idea with commits");
253
+ if (reason === undefined) throw new UsageError("idea decide: reason missing; pass --reason TEXT and --commit SHA for refine, plus --attempts for an idea with commits");
185
254
  result = await ops.ideaDecide(positional[0]!, positional[1]!, { decision: positional[2], reason, ...(str("--cause") !== undefined ? { cause: str("--cause") } : {}), ...(str("--retry-when") !== undefined ? { retryWhen: str("--retry-when") } : {}), ...(attempts !== undefined ? { attempts: attempts.split(",") } : {}), ...(str("--commit") !== undefined ? { commit: str("--commit") } : {}) }, ctx); break;
186
255
  }
256
+ case "idea categories": {
257
+ count(spec, positional, 1); const file = str("--file");
258
+ if (file === undefined) throw new UsageError("idea categories: input missing; pass --file PATH or --file - for JSON");
259
+ result = await ops.ideaCategories(positional[0]!, await readInput(file, io), ctx); break;
260
+ }
261
+ case "idea report": {
262
+ count(spec, positional, 1); const window = integer(flags["--window"], "--window"), runArg = str("--run");
263
+ if (window !== undefined && (window < 1 || window > 1000)) throw new UsageError("--window: integer in 1..1000 required");
264
+ result = ops.ideaReport(positional[0]!, { ...(runArg !== undefined ? { run: runArg } : {}), ...(window !== undefined ? { window } : {}) }); break;
265
+ }
187
266
  case "investigate show": count(spec, positional, 1); result = ops.investigateShow(positional[0]!); break;
188
267
  case "investigate close": count(spec, positional, 1); result = await ops.investigateClose(positional[0]!, ctx); break;
189
268
  case "ablate add": {
190
269
  count(spec, positional, 1); const file = str("--file");
191
- if (file === undefined) throw new Error("ablate add: input missing; pass --file PATH or --file - for JSON");
270
+ if (file === undefined) throw new UsageError("ablate add: input missing; pass --file PATH or --file - for JSON");
192
271
  result = await ops.ablateAdd(positional[0]!, await readInput(file, io), ctx); break;
193
272
  }
194
273
  case "ablate show": count(spec, positional, 1); result = ops.ablateShow(positional[0]!); break;
@@ -197,75 +276,100 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
197
276
  case "final close": count(spec, positional, 1); result = await ops.finalClose(positional[0]!, ctx); break;
198
277
  case "final seeds": {
199
278
  count(spec, positional, 1); const file = str("--file");
200
- if (file === undefined) throw new Error("final seeds: input missing; pass --file PATH or --file - for JSON");
279
+ if (file === undefined) throw new UsageError("final seeds: input missing; pass --file PATH or --file - for JSON");
201
280
  result = await ops.finalSeeds(positional[0]!, await readInput(file, io), ctx); break;
202
281
  }
203
282
  case "selection": {
204
283
  count(spec, positional, 1);
205
284
  const file = str("--file");
206
- if (file === undefined) throw new Error("selection: input missing; pass --file PATH or --file - for a JSON rule");
285
+ if (file === undefined) throw new UsageError("selection: input missing; pass --file PATH or --file - for a JSON rule");
207
286
  result = await ops.selection(positional[0]!, await readInput(file, io), ctx); break;
208
287
  }
288
+ case "selection calibrate": {
289
+ count(spec, positional, 1);
290
+ const fromRun = str("--from-run"), nullCommit = str("--null"), z = str("--z");
291
+ if (!fromRun) throw new UsageError("selection calibrate: --from-run RUN is required");
292
+ let options: CalibrationOptions;
293
+ try {
294
+ options = validateCalibrationOptions({
295
+ fromRun, ...(nullCommit === undefined ? {} : { nullCommit }), ...(z === undefined ? {} : { z: Number(z) }),
296
+ });
297
+ } catch (error) {
298
+ throw new UsageError(error instanceof Error ? error.message : "selection calibrate: invalid options");
299
+ }
300
+ result = await ops.selectionCalibrate(positional[0]!, options, ctx);
301
+ break;
302
+ }
209
303
  case "retention inspect": {
210
304
  count(spec, positional, 1); const offset = str("--offset"), limit = integer(flags["--limit"], "--limit");
211
- if (offset !== undefined && !/^[0-9]{1,8}$/.test(offset)) throw new Error("retention inspect: offset must be in 0..16000000");
305
+ if (offset !== undefined && !/^[0-9]{1,8}$/.test(offset)) throw new UsageError("retention inspect: offset must be in 0..16000000");
212
306
  result = await ops.retentionInspect(positional[0]!, ctx, { ...(offset === undefined ? {} : { offset: Number(offset) }), ...(limit === undefined ? {} : { limit }) }); break;
213
307
  }
214
308
  case "retention prune": {
215
309
  count(spec, positional, 1); const file = str("--file"), fingerprint = str("--confirm");
216
- if (file === undefined) throw new Error("retention prune: --file PATH|- is required for explicit retained references");
310
+ if (file === undefined) throw new UsageError("retention prune: --file PATH|- is required for explicit retained references");
217
311
  const refs = await readInput(file, io);
312
+ if (!flags["--json"] && Array.isArray(refs)) output.context.previewCount = refs.length;
218
313
  result = await ops.retentionPrune(positional[0]!, { refs: refs as Parameters<typeof ops.retentionPrune>[1]["refs"], ...(fingerprint === undefined ? {} : { fingerprint }) }, ctx); break;
219
314
  }
220
315
  case "protocol": {
221
316
  count(spec, positional, 1);
222
317
  const file = str("--file");
223
- if (file === undefined) throw new Error("protocol: input file missing; use --file PATH or --file - for JSON standard input");
318
+ if (file === undefined) throw new UsageError("protocol: input file missing; use --file PATH or --file - for JSON standard input");
224
319
  result = await ops.protocol(positional[0]!, await readInput(file, io), ctx); break;
225
320
  }
226
321
  case "harness stream set": case "experience freeze": case "experience select": {
227
- count(spec, positional, 1); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
322
+ count(spec, positional, 1); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
228
323
  const raw = await readInput(file, io);
229
324
  result = spec.name === "harness stream set" ? await ops.harnessStreamSet(positional[0]!, raw, ctx) : spec.name === "experience freeze" ? await ops.experienceFreeze(positional[0]!, raw, ctx, env) : await ops.experienceSelect(positional[0]!, raw, ctx, env); break;
230
325
  }
231
326
  case "harness stream show": count(spec, positional, 1); result = ops.harnessStreamShow(positional[0]!); break;
232
327
  case "experience check": {
233
- count(spec, positional, 2); const model = str("--model"), runtime = str("--runtime"), toolsetSha256 = str("--toolset-sha256"); if (!model || !runtime) throw new Error(`usage: ares ${spec.usage}`);
328
+ count(spec, positional, 2); const model = str("--model"), runtime = str("--runtime"), toolsetSha256 = str("--toolset-sha256"); if (!model || !runtime) throw new UsageError(`usage: ares ${spec.usage}`);
234
329
  result = await ops.experienceCheck(positional[0]!, positional[1]!, {model, runtime, ...(toolsetSha256 !== undefined ? {toolsetSha256} : {})}, ctx, env); break;
235
330
  }
236
331
  case "harness contrast": case "harness compose": case "harness adopt": case "harness close": {
237
- count(spec, positional, 2); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
332
+ count(spec, positional, 2); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
238
333
  const form = await readInput(file, io);
239
334
  result = spec.name === "harness contrast" ? await ops.harnessContrast(positional[0]!, positional[1]!, form, ctx) : spec.name === "harness compose" ? await ops.harnessCompose(positional[0]!, positional[1]!, form, ctx) : spec.name === "harness close" ? await ops.harnessClose(positional[0]!, positional[1]!, form, str("--confirm"), ctx) : await ops.harnessAdopt(positional[0]!, positional[1]!, form, str("--confirm"), ctx); break;
240
335
  }
241
336
  case "harness set": {
242
- count(spec, positional, 1); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
337
+ count(spec, positional, 1); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
243
338
  result = await ops.harnessSet(positional[0]!, await readInput(file, io), ctx); break;
244
339
  }
245
340
  case "harness show": count(spec, positional, 1); result = ops.harnessShow(positional[0]!, str("--round")); break;
246
341
  case "harness import": {
247
- count(spec, positional, 2); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
342
+ count(spec, positional, 2); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
248
343
  result = await ops.harnessImport(positional[0]!, positional[1]!, await readInput(file, io), ctx); break;
249
344
  }
250
345
  case "executor set": {
251
346
  count(spec, positional, 1);
252
347
  const kind = str("--kind"), workdir = str("--workdir");
253
- if (!kind || !workdir) throw new Error("executor set: kind/workdir missing; use --kind local|ssh --workdir PATH and --host ALIAS for ssh");
348
+ if (!kind || !workdir) throw new UsageError("executor set: kind/workdir missing; use --kind local|ssh --workdir PATH and --host ALIAS for ssh");
254
349
  const gpuValues = [str("--gpu-devices"), str("--gpu-min-free-memory-mb"), str("--gpu-max-load-ratio")];
255
350
  const gpuRequested = gpuValues.some(value => value !== undefined);
256
- if (gpuRequested && gpuValues.some(value => value === undefined)) throw new Error("executor GPU: incomplete settings; pass --gpu-devices, --gpu-min-free-memory-mb and --gpu-max-load-ratio together");
351
+ if (gpuRequested && gpuValues.some(value => value === undefined)) throw new UsageError("executor GPU: incomplete settings; pass --gpu-devices, --gpu-min-free-memory-mb and --gpu-max-load-ratio together");
257
352
  const gpu = gpuRequested ? { devices: gpuValues[0]!.split(",").map(value => value.trim()), minFreeMemoryMb: Number(gpuValues[1]), maxLoadRatio: Number(gpuValues[2]) } : undefined;
258
- if (gpu && (!/^[0-9]{1,10}$/.test(gpuValues[1]!) || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(gpuValues[2]!))) throw new Error("executor GPU: invalid thresholds; use decimal memory MB and a positive decimal load ratio");
353
+ if (gpu && (!/^[0-9]{1,10}$/.test(gpuValues[1]!) || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(gpuValues[2]!))) throw new UsageError("executor GPU: invalid thresholds; use decimal memory MB and a positive decimal load ratio");
259
354
  const cap = str("--retention-cap-bytes");
260
- if (cap !== undefined && !/^[0-9]{1,13}$/.test(cap)) throw new Error("--retention-cap-bytes: expected an integer byte count in 1..1099511627776");
355
+ if (cap !== undefined && !/^[0-9]{1,13}$/.test(cap)) throw new UsageError("--retention-cap-bytes: expected an integer byte count in 1..1099511627776");
261
356
  result = await ops.executorSet(positional[0]!, { v: 1, kind, workdir, ...(cap !== undefined ? { retentionCapBytes: Number(cap) } : {}), ...(str("--host") !== undefined ? { host: str("--host") } : {}), ...(gpu ? { gpu } : {}) }, ctx); break;
262
357
  }
263
358
  case "executor inputs hash": count(spec, positional, 2); result = await ops.executorInputsHash(positional[0]!, positional[1]!, ctx); break;
264
- case "executor check": count(spec, positional, 1); result = await ops.executorCheck(positional[0]!, ctx); break;
359
+ case "executor check": {
360
+ count(spec, positional, 1);
361
+ if (flags["--json"]) result = await ops.executorCheck(positional[0]!, ctx);
362
+ else {
363
+ const report = await ops.executorCheckReport(positional[0]!, ctx);
364
+ result = report;
365
+ if (report.checks.some(row => row.state === "failed")) code = 1;
366
+ }
367
+ break;
368
+ }
265
369
  case "attempt run": {
266
370
  count(spec, positional, 1);
267
371
  const repo = str("--repo"), commit = str("--commit"), chosenSeed = seed(str("--seed"));
268
- if (!repo || !commit) throw new Error("attempt run: repo/commit missing; use --repo PATH --commit FULL_40_HEX_SHA");
372
+ if (!repo || !commit) throw new UsageError("attempt run: repo/commit missing; use --repo PATH --commit FULL_40_HEX_SHA");
269
373
  const attempt = await ops.attemptRun(positional[0]!, { repo, commit, ...(chosenSeed !== undefined ? { seed: chosenSeed } : {}), ...(str("--run") !== undefined ? { run: str("--run") } : {}), ...(str("--label") !== undefined ? { label: str("--label") } : {}), ...(str("--retry") !== undefined ? { retry: str("--retry") } : {}), ...(str("--reuse") !== undefined ? { reuse: str("--reuse") as "off" | "eligible" } : {}), ...(flags["--force-fresh"] ? { forceFresh: true } : {}), detach: !!flags["--detach"] }, ctx);
270
374
  if (attempt.status === "deferred") code = 75;
271
375
  else if (attempt.status !== "running" && attempt.status !== "succeeded") code = 1;
@@ -281,7 +385,6 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
281
385
  case "attempt logs": {
282
386
  count(spec, positional, 2); const tailBytes = integer(flags["--tail"], "--tail");
283
387
  const logs = await ops.attemptLogs(positional[0]!, positional[1]!, { ...(str("--stage") !== undefined ? { stage: str("--stage") } : {}), ...(str("--candidate-stage") !== undefined ? { candidateStage: str("--candidate-stage") } : {}), ...(str("--stream") !== undefined ? { stream: str("--stream") } : {}), ...(tailBytes !== undefined ? { tailBytes } : {}) }, ctx);
284
- if (!flags["--json"]) return { text: logs.logs.map(log => `[${log.candidateStage === undefined ? log.stage : `candidate:${log.candidateStage}`} ${log.stream}${log.truncated ? ", truncated copy" : ""}]\n${log.text}`).join("\n"), code: 0 };
285
388
  result = logs; break;
286
389
  }
287
390
  case "gate list": count(spec, positional, 1); result = ops.gateList(positional[0]!); break;
@@ -300,7 +403,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
300
403
  case "lit queries": count(spec, positional, 1); result = ops.queries(positional[0]!); break;
301
404
  case "lit flow": {
302
405
  count(spec, positional, 1);
303
- if (flags["--markdown"]) { if (flags["--json"]) throw new Error("lit flow: choose one of --markdown or --json"); return { text: ops.flowMarkdownView(positional[0]!).markdown.trimEnd(), code: 0 }; }
406
+ if (flags["--markdown"]) { if (flags["--json"]) throw new UsageError("lit flow: choose one of --markdown or --json"); return { text: ops.flowMarkdownView(positional[0]!).markdown.trimEnd(), code: 0 }; }
304
407
  result = ops.flow(positional[0]!); break;
305
408
  }
306
409
  case "lit list": {
@@ -310,15 +413,15 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
310
413
  break;
311
414
  }
312
415
  case "lit screen": {
313
- if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
314
- if (!!flags["--include"] === !!flags["--exclude"]) throw new Error("lit screen: exactly one of --include or --exclude");
416
+ if (positional.length < 2) throw new UsageError(`usage: ares ${spec.usage}`);
417
+ if (!!flags["--include"] === !!flags["--exclude"]) throw new UsageError("lit screen: exactly one of --include or --exclude");
315
418
  result = await ops.screen(positional[0]!, positional.slice(1), flags["--include"] ? "include" : "exclude", str("--reason"), ctx, undefined, str("--code"));
316
419
  break;
317
420
  }
318
421
  case "lit card export": case "lit card import": {
319
- if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
422
+ if (positional.length < 2) throw new UsageError(`usage: ares ${spec.usage}`);
320
423
  const vault = str("--vault");
321
- if (vault === undefined) throw new Error(`${spec.name}: --vault is required; pass the registered vault id (vmem vaults list)`);
424
+ if (vault === undefined) throw new UsageError(`${spec.name}: --vault is required; pass the registered vault id (vmem vaults list)`);
322
425
  const confirm = str("--confirm"), family = str("--model-family");
323
426
  result = spec.name === "lit card export"
324
427
  ? await ops.cardExport(positional[0]!, positional.slice(1), { vault, ...(confirm !== undefined ? { confirm } : {}), ...(family !== undefined ? { modelFamily: family } : {}) }, ctx, env)
@@ -329,28 +432,48 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
329
432
  case "lit card": {
330
433
  count(spec, positional, 2);
331
434
  const file = str("--file");
332
- if (file === undefined) throw new Error("lit card: --file is required");
435
+ if (file === undefined) throw new UsageError("lit card: --file is required");
333
436
  result = await ops.card(positional[0]!, positional[1]!, await readInput(file, io), ctx);
334
437
  break;
335
438
  }
336
- case "lit verify": if (!positional.length) throw new Error(`usage: ares ${spec.usage}`); result = await ops.verify(positional[0]!, positional.slice(1), ctx); break;
439
+ case "lit verify": if (!positional.length) throw new UsageError(`usage: ares ${spec.usage}`); result = await ops.verify(positional[0]!, positional.slice(1), ctx); break;
337
440
  case "lit bib": count(spec, positional, 1); result = await ops.bib(positional[0]!, ctx); break;
338
441
  case "review add": {
339
442
  count(spec, positional, 1); const file = str("--file");
340
- if (file === undefined) throw new Error("review add: --file is required; pass --file PATH|- with a current-build report");
443
+ if (file === undefined) throw new UsageError("review add: --file is required; pass --file PATH|- with a current-build report");
341
444
  result = await ops.reviewAdd(positional[0]!, await readInput(file, io), ctx); break;
342
445
  }
343
446
  case "review resolve": {
344
447
  count(spec, positional, 2); const reason = str("--reason");
345
- if (reason === undefined) throw new Error("review resolve: --reason is required; explain how the finding was resolved");
448
+ if (reason === undefined) throw new UsageError("review resolve: --reason is required; explain how the finding was resolved");
346
449
  result = await ops.reviewResolve(positional[0]!, positional[1]!, reason, ctx); break;
347
450
  }
348
451
  case "review show": count(spec, positional, 1); result = ops.reviewShow(positional[0]!); break;
349
452
  case "review checklist": count(spec, positional, 0); result = ops.reviewChecklistShow(); break;
350
- case "paper build": count(spec, positional, 1); result = await ops.paperBuild(positional[0]!, ctx); break;
453
+ case "paper build": count(spec, positional, 1); result = await ops.paperBuild(positional[0]!, ctx, selectDocument()); break;
454
+ case "paper render record": {
455
+ count(spec, positional, 1); const file = str("--file"), receipt = str("--receipt");
456
+ if (file === undefined || receipt === undefined) throw new UsageError("paper render record: --file and --receipt are required; pass the rendered document and the renderer's receipt JSON");
457
+ result = await ops.paperRenderRecord(positional[0]!, file, receipt, ctx, selectDocument()); break;
458
+ }
459
+ case "paper render show": count(spec, positional, 1); result = ops.paperRenderShow(positional[0]!, selectDocument()); break;
460
+ case "renderer set": {
461
+ count(spec, positional, 1); const command = str("--command"), timeout = str("--timeout-s");
462
+ if (command === undefined) throw new UsageError("renderer set: --command is required; pass the renderer argv as a JSON array using {study} and {out}");
463
+ let argv: unknown;
464
+ try { argv = JSON.parse(command); } catch { throw new UsageError("renderer set: --command must be a JSON array of strings"); }
465
+ if (timeout !== undefined && !/^[0-9]{1,6}$/.test(timeout)) throw new UsageError("--timeout-s: expected an integer number of seconds");
466
+ result = ops.rendererSet(positional[0]!, { command: argv, ...(timeout !== undefined ? { timeoutS: Number(timeout) } : {}) }, env); break;
467
+ }
468
+ case "renderer show": count(spec, positional, 1); result = ops.rendererShow(positional[0]!, env); break;
469
+ case "renderer check": {
470
+ count(spec, positional, 1); const report = ops.rendererCheck(positional[0]!, env);
471
+ if (!report.ok) code = 1;
472
+ result = report; break;
473
+ }
351
474
  case "paper plan set": {
352
475
  count(spec, positional, 1); const file = str("--file");
353
- if (file === undefined) throw new Error("paper plan set: input missing; pass --file PATH or --file - with a bounded version-1 paper-plan JSON");
476
+ if (file === undefined) throw new UsageError("paper plan set: input missing; pass --file PATH or --file - with a bounded version-1 paper-plan JSON");
354
477
  let plan: unknown;
355
478
  try { plan = await readInput(file, io); }
356
479
  catch { throw new Error("paper plan set: input is unreadable, non-regular, invalid UTF-8/JSON or larger than 64 KiB; restore a bounded JSON file or stdin, then retry ares paper plan set <dir> --file PATH|-"); }
@@ -358,20 +481,23 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
358
481
  }
359
482
  case "paper plan show": count(spec, positional, 1); result = ops.paperPlanShow(positional[0]!); break;
360
483
  case "paper check": {
361
- count(spec, positional, 1); const report = ops.paperCheck(positional[0]!);
484
+ count(spec, positional, 1); const report = ops.paperCheck(positional[0]!, selectDocument());
362
485
  if (!report.ok) code = 1;
363
486
  result = report; break;
364
487
  }
365
488
  case "cite check": {
366
489
  count(spec, positional, 2);
367
- const report = ops.cite(positional[0]!, positional[1]!);
490
+ const report = (flags["--json"] ? ops.cite : ops.citeHuman)(positional[0]!, positional[1]!);
368
491
  if (!report.ok) code = 1;
369
492
  result = report;
370
493
  break;
371
494
  }
372
- default: throw new Error(`unknown command: ${spec.name}`);
495
+ default: throw new UsageError(`unknown command: ${spec.name}`);
373
496
  }
374
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code };
497
+ const text = output.options.json
498
+ ? JSON.stringify(result)
499
+ : renderResult(spec.name, result, code, color, outputAscii(output.options, env), streamWidth(output.tty ?? false, output.columns, env), output.context);
500
+ return { text, code };
375
501
  }
376
502
 
377
503
  /** `ares mcp`: stdout carries protocol frames only. */
@@ -402,13 +528,29 @@ async function readStdinBounded(): Promise<string> {
402
528
  export async function main(args: string[]): Promise<number> {
403
529
  const stop = new AbortController(), interrupt = () => stop.abort();
404
530
  if (args[0] === "run") { process.on("SIGINT", interrupt); process.on("SIGTERM", interrupt); }
531
+ const env = process.env;
532
+ const cli: CliOutput = {
533
+ options: {},
534
+ tty: Boolean(process.stdout.isTTY),
535
+ ...(process.stdout.isTTY ? { columns: process.stdout.columns } : {}),
536
+ };
405
537
  try {
406
- const output = await run(args, process.env, { readStdin: readStdinBounded, signal: stop.signal });
538
+ const output = await execute(args, env, { readStdin: readStdinBounded, signal: stop.signal }, cli);
407
539
  console.log(output.text);
408
540
  return output.code;
409
541
  } catch (error) {
410
- console.error(`ares: ${error instanceof Error ? error.message : "operation failed"}`);
411
- return 1;
542
+ const tty = Boolean(process.stderr.isTTY);
543
+ const columns = streamWidth(tty, process.stderr.columns, env);
544
+ const color = colorFor(cli.options, tty, env) === true;
545
+ const usage = error instanceof UsageError;
546
+ let message = error instanceof Error ? error.message : "operation failed";
547
+ if (message.startsWith("usage: ares ")) message = `${cli.spec?.name ?? "command"}: missing or invalid arguments`;
548
+ const diagnostic = renderError(fillMessage(message, cli.context?.values ?? {}), tty, color, outputAscii(cli.options, env), Math.min(columns ?? 80, 80));
549
+ console.error(diagnostic);
550
+ if (usage) {
551
+ console.error(usageHint(cli.spec, columns));
552
+ }
553
+ return usage ? 2 : 1;
412
554
  } finally {
413
555
  if (args[0] === "run") { process.off("SIGINT", interrupt); process.off("SIGTERM", interrupt); }
414
556
  }