@staix/agent-research 0.1.0 → 0.3.0

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 (78) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +356 -31
  3. package/package.json +4 -2
  4. package/src/autonomy.ts +50 -0
  5. package/src/cli.ts +134 -14
  6. package/src/commands-table.ts +43 -9
  7. package/src/commands.ts +244 -43
  8. package/src/copilot.ts +91 -0
  9. package/src/exp/attempts.ts +512 -69
  10. package/src/exp/executor.ts +235 -12
  11. package/src/exp/final.ts +1 -1
  12. package/src/exp/investigate.ts +7 -2
  13. package/src/exp/logs.ts +25 -12
  14. package/src/exp/metrics.ts +6 -5
  15. package/src/exp/pipeline.ts +92 -0
  16. package/src/exp/protocol.ts +88 -18
  17. package/src/exp/retention-script.ts +649 -0
  18. package/src/exp/retention.ts +70 -0
  19. package/src/exp/reuse-admission.ts +63 -0
  20. package/src/exp/reuse-contract.ts +48 -0
  21. package/src/exp/reuse-runtime.ts +87 -0
  22. package/src/exp/reuse.ts +87 -0
  23. package/src/exp/selection.ts +1 -1
  24. package/src/exp/snapshot.ts +3 -3
  25. package/src/exp/stages.ts +117 -0
  26. package/src/harness/experience-source.ts +34 -0
  27. package/src/harness/experience.ts +206 -0
  28. package/src/harness/hub-guidance.ts +140 -0
  29. package/src/harness/hub-reference.ts +18 -0
  30. package/src/harness/lesson-candidates.ts +162 -0
  31. package/src/harness/limits.ts +2 -0
  32. package/src/harness/privacy.ts +4 -0
  33. package/src/harness/receipts.ts +84 -0
  34. package/src/harness/rounds.ts +198 -0
  35. package/src/harness/transitions.ts +152 -0
  36. package/src/http.ts +46 -2
  37. package/src/lit/candidates.ts +13 -5
  38. package/src/lit/cards.ts +55 -4
  39. package/src/lit/flow.ts +82 -0
  40. package/src/lit/queries.ts +62 -0
  41. package/src/lit/watch.ts +14 -1
  42. package/src/manifest.ts +15 -7
  43. package/src/mcp-tools.ts +140 -32
  44. package/src/mcp.ts +6 -0
  45. package/src/memory/amem-show.ts +135 -0
  46. package/src/memory/amem.ts +3 -0
  47. package/src/memory/archive.ts +20 -8
  48. package/src/memory/evidence-local.ts +77 -0
  49. package/src/memory/evidence.ts +39 -0
  50. package/src/memory/lessons.ts +4 -2
  51. package/src/memory/skill-check.ts +56 -0
  52. package/src/memory/skill-format.ts +77 -0
  53. package/src/memory/skills.ts +72 -26
  54. package/src/memory/source-budget.ts +11 -0
  55. package/src/memory/vault-cards.ts +226 -0
  56. package/src/paper/build.ts +20 -8
  57. package/src/paper/check.ts +40 -12
  58. package/src/paper/headings.ts +39 -0
  59. package/src/paper/hygiene.ts +153 -0
  60. package/src/paper/placeholders.ts +21 -4
  61. package/src/paper/plan.ts +170 -0
  62. package/src/paper/point-evidence.ts +63 -0
  63. package/src/paper/points.ts +83 -0
  64. package/src/paper/review.ts +116 -11
  65. package/src/paper/scopes.ts +51 -0
  66. package/src/plan/controller.ts +42 -12
  67. package/src/plan/definition.ts +22 -6
  68. package/src/plan/hub.ts +6 -0
  69. package/src/plan/state.ts +58 -17
  70. package/src/playbook.ts +47 -20
  71. package/src/privacy.ts +9 -0
  72. package/src/provenance.ts +679 -0
  73. package/src/scope.ts +24 -3
  74. package/src/study-export.ts +282 -0
  75. package/src/study.ts +94 -26
  76. package/src/ui/panel.css +4 -0
  77. package/src/ui/panel.js +271 -9
  78. package/src/ui/plugin.ts +89 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-research",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Research engine for the agent family: literature with verified references, study ledger and gates (ares)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,7 +30,9 @@
30
30
  "LICENSE"
31
31
  ],
32
32
  "scripts": {
33
- "check": "bun x tsc --noEmit && bun scripts/check-boundary.ts && bun test && bun pm pack --dry-run",
33
+ "check": "bun x tsc --noEmit && bun scripts/check-boundary.ts && bun scripts/readme-facts.ts && bun scripts/check-docs.mjs && bun test --timeout 30000 && bun pm pack --dry-run",
34
+ "release:prepare": "bun scripts/release-tag.ts prepare",
35
+ "release:tag": "bun scripts/check-docs.mjs --require-fresh && bun scripts/release-tag.ts tag",
34
36
  "release:stage": "bun scripts/release.ts stage",
35
37
  "release:smoke": "bun scripts/release-smoke.ts"
36
38
  }
@@ -0,0 +1,50 @@
1
+ export const AUTONOMY_MODES = ["auto", "gates", "copilot", "step"] as const;
2
+ export const PHASES = ["scope", "literature", "hypotheses", "design", "investigate", "ablate", "final", "posthoc", "write", "review", "archive"] as const;
3
+ export type AutonomyMode = typeof AUTONOMY_MODES[number];
4
+ export type Phase = typeof PHASES[number];
5
+ export const ACCEPT_ARTIFACTS = ["hypotheses", "paper", "reviews"] as const;
6
+ export type AcceptArtifact = typeof ACCEPT_ARTIFACTS[number];
7
+ export type Autonomy = AutonomyMode | { default: AutonomyMode; phases: Partial<Record<Phase, AutonomyMode>> };
8
+
9
+ /** Direct gate mappings are explicit; plan gates receive their declared guarded phase. */
10
+ export const GATE_PHASES = { scope: "scope", screen: "literature", design: "design", final: "final", review: "review", "accept:hypotheses": "hypotheses", "accept:paper": "write", "accept:reviews": "review" } as const satisfies Record<string, Phase>;
11
+
12
+ function refuse(field: string, reason: string): never {
13
+ throw new Error(`${field}: ${reason}; correct the policy and retry ares autonomy set with a supported mode and phase`);
14
+ }
15
+ function object(raw: unknown): raw is Record<string, unknown> {
16
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw) && (Object.getPrototypeOf(raw) === Object.prototype || Object.getPrototypeOf(raw) === null);
17
+ }
18
+ export function validateAutonomyMode(raw: unknown): AutonomyMode {
19
+ if (typeof raw !== "string" || !AUTONOMY_MODES.includes(raw as AutonomyMode)) refuse("autonomy.mode", "expected auto, gates, copilot or step");
20
+ return raw as AutonomyMode;
21
+ }
22
+ export function validatePhase(raw: unknown): Phase {
23
+ if (typeof raw !== "string" || !PHASES.includes(raw as Phase)) refuse("autonomy.phase", `expected one of ${PHASES.join(", ")}`);
24
+ return raw as Phase;
25
+ }
26
+ /** Validate strictly and return a detached policy, leaving the input unchanged. */
27
+ export function validateAutonomy(raw: unknown): Autonomy {
28
+ if (typeof raw === "string") return validateAutonomyMode(raw);
29
+ if (!object(raw)) refuse("autonomy", "mode string or policy object required");
30
+ for (const key of Reflect.ownKeys(raw)) if (key !== "default" && key !== "phases") refuse("autonomy", "unknown policy field");
31
+ const mode = validateAutonomyMode(raw.default);
32
+ if (!object(raw.phases)) refuse("autonomy.phases", "phase-to-mode object required");
33
+ const phases: Partial<Record<Phase, AutonomyMode>> = {};
34
+ for (const key of Reflect.ownKeys(raw.phases)) {
35
+ const phase = validatePhase(key);
36
+ phases[phase] = validateAutonomyMode(raw.phases[phase]);
37
+ }
38
+ return { default: mode, phases };
39
+ }
40
+
41
+ export function resolvePhaseAutonomy(policy: Autonomy, phase?: Phase): AutonomyMode {
42
+ if (typeof policy === "string") return policy;
43
+ return phase === undefined ? policy.default : policy.phases[phase] ?? policy.default;
44
+ }
45
+
46
+ /** Unknown gate kinds and phase-ambiguous plan gates use the study default. */
47
+ export function resolveAutonomy(policy: Autonomy, gate: string, guardedPhase?: Phase): AutonomyMode {
48
+ const phase = gate.startsWith("plan:") ? guardedPhase : Object.hasOwn(GATE_PHASES, gate) ? GATE_PHASES[gate as keyof typeof GATE_PHASES] : undefined;
49
+ return resolvePhaseAutonomy(policy, phase);
50
+ }
package/src/cli.ts CHANGED
@@ -3,7 +3,8 @@ import { findCommand, help, type CommandSpec } from "./commands-table.ts";
3
3
  import * as ops from "./commands.ts";
4
4
  import { createHttp, type Http } from "./http.ts";
5
5
  import { PLAYBOOK } from "./playbook.ts";
6
- import { detectActor, readTextBounded } from "./study.ts";
6
+ import { validateExecutionReference } from "./provenance.ts";
7
+ import { detectActor, openStudy, readTextBounded, releaseStudyLocksForExit } from "./study.ts";
7
8
 
8
9
  const INPUT_BYTES = 65_536;
9
10
  export interface Io extends ops.ExperimentRuntime { readStdin?: () => Promise<string>; http?: Http; signal?: AbortSignal }
@@ -56,6 +57,31 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
56
57
  const str = (flag: string) => (typeof flags[flag] === "string" ? flags[flag] as string : undefined);
57
58
  let result: unknown, code = 0;
58
59
  switch (spec.name) {
60
+ case "lineage show": {
61
+ count(spec, positional, 1);
62
+ const kind = str("--root"), id = str("--id"), revision = str("--revision"), hash = str("--sha256"), cursor = str("--cursor");
63
+ 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");
65
+ let root = hasRoot ? validateExecutionReference({ v: 1, tool: "ares", projectKey: "pending-study-identity", kind, id, ...(revision === undefined ? {} : { revision }), ...(hash === undefined ? {} : { sha256: hash }) }) : undefined;
66
+ if (root) {
67
+ let projectKey: string;
68
+ try { projectKey = openStudy(positional[0]!).study.id; }
69
+ catch { result = ops.lineageShow(positional[0]!, cursor === undefined ? {} : {cursor}); break; }
70
+ root = {...root, projectKey};
71
+ }
72
+ result = ops.lineageShow(positional[0]!, { ...(root === undefined ? {} : { root }), ...(cursor === undefined ? {} : { cursor }) }); break;
73
+ }
74
+ case "lineage compare": {
75
+ count(spec, positional, 1);
76
+ 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,...");
78
+ const list = (value: string) => {
79
+ 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");
81
+ return values;
82
+ };
83
+ result = ops.lineageCompare(positional[0]!, { ...(attempts === undefined ? {} : { attempts: list(attempts) }), ...(candidates === undefined ? {} : { candidates: list(candidates) }) }); break;
84
+ }
59
85
  case "console add": count(spec, positional, 1); result = ops.consoleAdd(positional[0]!, env); break;
60
86
  case "console remove": count(spec, positional, 1); result = ops.consoleRemove(positional[0]!, env); break;
61
87
  case "console list": count(spec, positional, 0); result = ops.consoleList(env); break;
@@ -76,15 +102,25 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
76
102
  if ((result as ReturnType<typeof ops.setup>).actions.some(action => action.change === "refused")) code = 1;
77
103
  break;
78
104
  }
105
+ case "lesson list": count(spec, positional, 1); result = ops.lessonList(positional[0]!); break;
106
+ case "lesson check": count(spec, positional, 2); result = await ops.lessonCheck(positional[0]!, positional[1]!, ctx, env); break;
107
+ case "lesson propose":
108
+ case "lesson decide": {
109
+ 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`);
111
+ const raw = await readInput(file, io);
112
+ 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
+ }
114
+ case "skill check": count(spec, positional, 2); result = await ops.skillCheck(positional[0]!, positional[1]!, ctx, env); break;
79
115
  case "skill propose": {
80
116
  count(spec, positional, 1); const file = str("--file");
81
117
  if (file === undefined) throw new Error("skill propose: input missing; pass --file PATH or --file - for proposal JSON");
82
- result = await ops.skillPropose(positional[0]!, await readInput(file, io), ctx); break;
118
+ result = await ops.skillPropose(positional[0]!, await readInput(file, io), ctx, env); break;
83
119
  }
84
120
  case "skill decide": {
85
121
  count(spec, positional, 3); const reason = str("--reason");
86
122
  if (reason === undefined) throw new Error("skill decide: reason missing; pass --reason TEXT and --pr URL for accept");
87
- result = await ops.skillDecide(positional[0]!, positional[1]!, positional[2]!, reason, str("--pr"), ctx); break;
123
+ result = await ops.skillDecide(positional[0]!, positional[1]!, positional[2]!, reason, str("--pr"), ctx, undefined, env); break;
88
124
  }
89
125
  case "skill list": count(spec, positional, 1); result = ops.skillList(positional[0]!); break;
90
126
  case "lessons": {
@@ -97,11 +133,14 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
97
133
  }
98
134
  case "run": {
99
135
  count(spec, positional, 1); const parallel = integer(flags["--parallel"], "--parallel");
100
- result = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}) }, ctx); break;
136
+ const completed = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}) }, ctx);
137
+ result = completed; if (completed.state === "failed") code = 1; break;
101
138
  }
102
139
  case "manifest": count(spec, positional, 0); result = ops.manifest(); break;
103
140
  case "playbook": count(spec, positional, 0); return { text: PLAYBOOK.trimEnd(), code: 0 };
104
141
  case "mcp": throw new Error("mcp: run `ares mcp` with no other arguments");
142
+ case "autonomy show": count(spec, positional, 1); result = ops.autonomyShow(positional[0]!); break;
143
+ case "autonomy set": count(spec, positional, 2); result = await ops.autonomySet(positional[0]!, positional[1]!, str("--phase"), ctx); break;
105
144
  case "init": {
106
145
  count(spec, positional, 1);
107
146
  const question = str("--question");
@@ -123,6 +162,11 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
123
162
  }
124
163
  case "plan show": count(spec, positional, 1); result = ops.planShow(positional[0]!); break;
125
164
  case "status": count(spec, positional, 1); result = ops.status(positional[0]!); break;
165
+ case "study export": {
166
+ 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");
168
+ result = await ops.studyExport(positional[0]!, { bundle, ...(flags["--list"] ? { list: true } : {}) }); break;
169
+ }
126
170
  case "scope": {
127
171
  count(spec, positional, 1);
128
172
  const file = str("--file");
@@ -162,25 +206,69 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
162
206
  if (file === undefined) throw new Error("selection: input missing; pass --file PATH or --file - for a JSON rule");
163
207
  result = await ops.selection(positional[0]!, await readInput(file, io), ctx); break;
164
208
  }
209
+ case "retention inspect": {
210
+ 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");
212
+ result = await ops.retentionInspect(positional[0]!, ctx, { ...(offset === undefined ? {} : { offset: Number(offset) }), ...(limit === undefined ? {} : { limit }) }); break;
213
+ }
214
+ case "retention prune": {
215
+ 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");
217
+ const refs = await readInput(file, io);
218
+ result = await ops.retentionPrune(positional[0]!, { refs: refs as Parameters<typeof ops.retentionPrune>[1]["refs"], ...(fingerprint === undefined ? {} : { fingerprint }) }, ctx); break;
219
+ }
165
220
  case "protocol": {
166
221
  count(spec, positional, 1);
167
222
  const file = str("--file");
168
223
  if (file === undefined) throw new Error("protocol: input file missing; use --file PATH or --file - for JSON standard input");
169
224
  result = await ops.protocol(positional[0]!, await readInput(file, io), ctx); break;
170
225
  }
226
+ 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}`);
228
+ const raw = await readInput(file, io);
229
+ 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
+ }
231
+ case "harness stream show": count(spec, positional, 1); result = ops.harnessStreamShow(positional[0]!); break;
232
+ 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}`);
234
+ result = await ops.experienceCheck(positional[0]!, positional[1]!, {model, runtime, ...(toolsetSha256 !== undefined ? {toolsetSha256} : {})}, ctx, env); break;
235
+ }
236
+ 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}`);
238
+ const form = await readInput(file, io);
239
+ 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
+ }
241
+ case "harness set": {
242
+ count(spec, positional, 1); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
243
+ result = await ops.harnessSet(positional[0]!, await readInput(file, io), ctx); break;
244
+ }
245
+ case "harness show": count(spec, positional, 1); result = ops.harnessShow(positional[0]!, str("--round")); break;
246
+ case "harness import": {
247
+ count(spec, positional, 2); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
248
+ result = await ops.harnessImport(positional[0]!, positional[1]!, await readInput(file, io), ctx); break;
249
+ }
171
250
  case "executor set": {
172
251
  count(spec, positional, 1);
173
252
  const kind = str("--kind"), workdir = str("--workdir");
174
253
  if (!kind || !workdir) throw new Error("executor set: kind/workdir missing; use --kind local|ssh --workdir PATH and --host ALIAS for ssh");
175
- result = await ops.executorSet(positional[0]!, { v: 1, kind, workdir, ...(str("--host") !== undefined ? { host: str("--host") } : {}) }, ctx); break;
254
+ const gpuValues = [str("--gpu-devices"), str("--gpu-min-free-memory-mb"), str("--gpu-max-load-ratio")];
255
+ 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");
257
+ 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");
259
+ 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");
261
+ 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;
176
262
  }
263
+ case "executor inputs hash": count(spec, positional, 2); result = await ops.executorInputsHash(positional[0]!, positional[1]!, ctx); break;
177
264
  case "executor check": count(spec, positional, 1); result = await ops.executorCheck(positional[0]!, ctx); break;
178
265
  case "attempt run": {
179
266
  count(spec, positional, 1);
180
267
  const repo = str("--repo"), commit = str("--commit"), chosenSeed = seed(str("--seed"));
181
268
  if (!repo || !commit) throw new Error("attempt run: repo/commit missing; use --repo PATH --commit FULL_40_HEX_SHA");
182
- 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") } : {}), detach: !!flags["--detach"] }, ctx);
183
- if (attempt.status !== "running" && attempt.status !== "succeeded") code = 1;
269
+ 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
+ if (attempt.status === "deferred") code = 75;
271
+ else if (attempt.status !== "running" && attempt.status !== "succeeded") code = 1;
184
272
  result = attempt; break;
185
273
  }
186
274
  case "attempt list": {
@@ -192,8 +280,8 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
192
280
  case "attempt reconcile": count(spec, positional, 1); result = await ops.attemptReconcile(positional[0]!, ctx); break;
193
281
  case "attempt logs": {
194
282
  count(spec, positional, 2); const tailBytes = integer(flags["--tail"], "--tail");
195
- const logs = await ops.attemptLogs(positional[0]!, positional[1]!, { ...(str("--stage") !== undefined ? { stage: str("--stage") } : {}), ...(str("--stream") !== undefined ? { stream: str("--stream") } : {}), ...(tailBytes !== undefined ? { tailBytes } : {}) }, ctx);
196
- if (!flags["--json"]) return { text: logs.logs.map(log => `[${log.stage} ${log.stream}${log.truncated ? ", truncated copy" : ""}]\n${log.text}`).join("\n"), code: 0 };
283
+ 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 };
197
285
  result = logs; break;
198
286
  }
199
287
  case "gate list": count(spec, positional, 1); result = ops.gateList(positional[0]!); break;
@@ -204,11 +292,17 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
204
292
  case "lit search": {
205
293
  count(spec, positional, 2);
206
294
  const limit = integer(flags["--limit"], "--limit"), yearFrom = integer(flags["--year-from"], "--year-from");
207
- const out = await ops.search(positional[0]!, positional[1]!, { ...(str("--source") ? { source: str("--source")! } : {}), ...(limit !== undefined ? { limit } : {}), ...(yearFrom !== undefined ? { yearFrom } : {}) }, ctx);
295
+ const out = await ops.search(positional[0]!, positional[1]!, { ...(str("--source") ? { source: str("--source")! } : {}), ...(limit !== undefined ? { limit } : {}), ...(yearFrom !== undefined ? { yearFrom } : {}), ...(str("--intent") !== undefined ? { intent: str("--intent")! } : {}) }, ctx);
208
296
  if (!out.sources.some(s => s.ok)) code = 1;
209
297
  result = out;
210
298
  break;
211
299
  }
300
+ case "lit queries": count(spec, positional, 1); result = ops.queries(positional[0]!); break;
301
+ case "lit flow": {
302
+ 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 }; }
304
+ result = ops.flow(positional[0]!); break;
305
+ }
212
306
  case "lit list": {
213
307
  count(spec, positional, 1);
214
308
  const limit = integer(flags["--limit"], "--limit");
@@ -218,9 +312,20 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
218
312
  case "lit screen": {
219
313
  if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
220
314
  if (!!flags["--include"] === !!flags["--exclude"]) throw new Error("lit screen: exactly one of --include or --exclude");
221
- result = await ops.screen(positional[0]!, positional.slice(1), flags["--include"] ? "include" : "exclude", str("--reason"), ctx);
315
+ result = await ops.screen(positional[0]!, positional.slice(1), flags["--include"] ? "include" : "exclude", str("--reason"), ctx, undefined, str("--code"));
222
316
  break;
223
317
  }
318
+ case "lit card export": case "lit card import": {
319
+ if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
320
+ const vault = str("--vault");
321
+ if (vault === undefined) throw new Error(`${spec.name}: --vault is required; pass the registered vault id (vmem vaults list)`);
322
+ const confirm = str("--confirm"), family = str("--model-family");
323
+ result = spec.name === "lit card export"
324
+ ? await ops.cardExport(positional[0]!, positional.slice(1), { vault, ...(confirm !== undefined ? { confirm } : {}), ...(family !== undefined ? { modelFamily: family } : {}) }, ctx, env)
325
+ : await ops.cardImport(positional[0]!, positional.slice(1), { vault }, ctx, env);
326
+ break;
327
+ }
328
+ case "lit card list": count(spec, positional, 1); result = ops.cardList(positional[0]!); break;
224
329
  case "lit card": {
225
330
  count(spec, positional, 2);
226
331
  const file = str("--file");
@@ -241,7 +346,17 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
241
346
  result = await ops.reviewResolve(positional[0]!, positional[1]!, reason, ctx); break;
242
347
  }
243
348
  case "review show": count(spec, positional, 1); result = ops.reviewShow(positional[0]!); break;
349
+ case "review checklist": count(spec, positional, 0); result = ops.reviewChecklistShow(); break;
244
350
  case "paper build": count(spec, positional, 1); result = await ops.paperBuild(positional[0]!, ctx); break;
351
+ case "paper plan set": {
352
+ 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");
354
+ let plan: unknown;
355
+ try { plan = await readInput(file, io); }
356
+ 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|-"); }
357
+ result = await ops.paperPlanSet(positional[0]!, plan, ctx); break;
358
+ }
359
+ case "paper plan show": count(spec, positional, 1); result = ops.paperPlanShow(positional[0]!); break;
245
360
  case "paper check": {
246
361
  count(spec, positional, 1); const report = ops.paperCheck(positional[0]!);
247
362
  if (!report.ok) code = 1;
@@ -260,11 +375,16 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
260
375
  }
261
376
 
262
377
  /** `ares mcp`: stdout carries protocol frames only. */
263
- export async function runMcp(env: NodeJS.ProcessEnv = process.env): Promise<void> {
378
+ export async function runMcp(env: NodeJS.ProcessEnv = process.env, http?: Http): Promise<void> {
264
379
  const [{ serveMcp }, { createAresMcp }] = await Promise.all([import("./mcp.ts"), import("./mcp-tools.ts")]);
265
- const server = createAresMcp(env);
380
+ const server = createAresMcp(env, http);
381
+ const terminate = () => {
382
+ try { server.terminate(); }
383
+ finally { releaseStudyLocksForExit(); process.exit(143); }
384
+ };
385
+ process.once("SIGTERM", terminate);
266
386
  try { await serveMcp({ tools: server.tools, handlers: server.handlers, name: "ares", version }); }
267
- finally { await server.waitForIdle(); }
387
+ finally { try { await server.waitForIdle(); } finally { process.off("SIGTERM", terminate); } }
268
388
  }
269
389
 
270
390
  /** Standard input stops at the input bound instead of buffering everything first. */
@@ -2,6 +2,29 @@
2
2
  export interface CommandSpec { name: string; usage: string; mutates: boolean | "network"; options: Record<string, "flag" | "value"> }
3
3
  const json = { "--json": "flag" } as const;
4
4
  export const COMMANDS: readonly CommandSpec[] = [
5
+ { name: "retention inspect", usage: "retention inspect <dir> [--offset N] [--limit N] [--json]", mutates: "network", options: { "--offset": "value", "--limit": "value", ...json } },
6
+ { name: "retention prune", usage: "retention prune <dir> --file PATH|- [--confirm FINGERPRINT] [--json]", mutates: "network", options: { "--file": "value", "--confirm": "value", ...json } },
7
+ { name: "skill check", usage: "skill check <dir> <name> [--json]", mutates: "network", options: json },
8
+ { name: "harness close", usage: "harness close <dir> <round> --file PATH|- [--confirm FINGERPRINT] [--json]", mutates: true, options: { "--file": "value", "--confirm": "value", ...json } },
9
+ { name: "harness contrast", usage: "harness contrast <dir> <round> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
10
+ { name: "harness compose", usage: "harness compose <dir> <round> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
11
+ { name: "harness adopt", usage: "harness adopt <dir> <round> --file PATH|- [--confirm FINGERPRINT] [--json]", mutates: true, options: { "--file": "value", "--confirm": "value", ...json } },
12
+ { name: "harness stream set", usage: "harness stream set <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
13
+ { name: "harness stream show", usage: "harness stream show <dir> [--json]", mutates: false, options: json },
14
+ { name: "experience select", usage: "experience select <dir> --file PATH|- [--json]", mutates: "network", options: { "--file": "value", ...json } },
15
+ { name: "experience freeze", usage: "experience freeze <dir> --file PATH|- [--json]", mutates: "network", options: { "--file": "value", ...json } },
16
+ { name: "experience check", usage: "experience check <dir> <round> --model MODEL --runtime VERSION [--toolset-sha256 HASH] [--json]", mutates: "network", options: { "--model": "value", "--runtime": "value", "--toolset-sha256": "value", ...json } },
17
+ { name: "harness set", usage: "harness set <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
18
+ { name: "harness show", usage: "harness show <dir> [--round ID] [--json]", mutates: false, options: { "--round": "value", ...json } },
19
+ { name: "harness import", usage: "harness import <dir> <round> --file FIXTURE_PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
20
+ { name: "lineage show", usage: "lineage show <dir> [--root KIND --id ID --revision REV --sha256 HASH] [--cursor CURSOR] [--json]", mutates: false, options: { "--root": "value", "--id": "value", "--revision": "value", "--sha256": "value", "--cursor": "value", ...json } },
21
+ { name: "lineage compare", usage: "lineage compare <dir> (--attempts ID,... | --candidates COMMIT,...) [--json]", mutates: false, options: { "--attempts": "value", "--candidates": "value", ...json } },
22
+ { name: "autonomy show", usage: "autonomy show <dir> [--json]", mutates: false, options: json },
23
+ { name: "autonomy set", usage: "autonomy set <dir> <auto|gates|copilot|step> [--phase PHASE] [--json]", mutates: true, options: { "--phase": "value", ...json } },
24
+ {name: "lesson propose", usage: "lesson propose <dir> --file PATH|- [--json]", mutates: "network", options: {"--file": "value", ...json}},
25
+ {name: "lesson list", usage: "lesson list <dir> [--json]", mutates: false, options: {...json}},
26
+ {name: "lesson check", usage: "lesson check <dir> <name> [--json]", mutates: "network", options: {...json}},
27
+ {name: "lesson decide", usage: "lesson decide <dir> <name> --file PATH|- [--json]", mutates: "network", options: {"--file": "value", ...json}},
5
28
  { name: "skill propose", usage: "skill propose <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
6
29
  { name: "skill decide", usage: "skill decide <dir> <name> <accept|reject|withdraw> --reason TEXT [--pr URL] [--json]", mutates: true, options: { "--reason": "value", "--pr": "value", ...json } },
7
30
  { name: "skill list", usage: "skill list <dir> [--json]", mutates: false, options: json },
@@ -15,12 +38,13 @@ export const COMMANDS: readonly CommandSpec[] = [
15
38
  { name: "console remove", usage: "console remove <dir> [--json]", mutates: true, options: json },
16
39
  { name: "console list", usage: "console list [--json]", mutates: false, options: json },
17
40
  { name: "manifest", usage: "manifest [--json]", mutates: false, options: json },
18
- { name: "init", usage: "init <dir> --question TEXT [--mode survey|experiment] [--autonomy auto|gates] [--json]", mutates: true, options: { "--question": "value", "--mode": "value", "--autonomy": "value", ...json } },
41
+ { name: "init", usage: "init <dir> --question TEXT [--mode survey|experiment] [--autonomy auto|gates|copilot|step] [--json]", mutates: true, options: { "--question": "value", "--mode": "value", "--autonomy": "value", ...json } },
19
42
  { name: "run", usage: "run <dir> [--parallel 1..8] [--json]", mutates: "network", options: { "--parallel": "value", ...json } },
20
43
  { name: "plan set", usage: "plan set <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
21
44
  { name: "plan control", usage: "plan control <dir> <pause|resume|retry|cancel|skip> [node] --command-id ID --expected-revision N [--json]", mutates: "network", options: { "--command-id": "value", "--expected-revision": "value", ...json } },
22
45
  { name: "plan show", usage: "plan show <dir> [--json]", mutates: false, options: json },
23
46
  { name: "status", usage: "status <dir> [--json]", mutates: false, options: json },
47
+ { name: "study export", usage: "study export <dir> --bundle DIR [--list] [--json]", mutates: true, options: { "--bundle": "value", "--list": "flag", ...json } },
24
48
  { name: "scope", usage: "scope <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
25
49
  { name: "idea add", usage: "idea add <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
26
50
  { name: "idea decide", usage: "idea decide <dir> <id> <refine|pivot> --reason TEXT [--attempts ID[,ID...]] [--commit SHA] [--cause TEXT] [--retry-when TEXT] [--json]", mutates: true, options: { "--cause": "value", "--retry-when": "value", "--reason": "value", "--attempts": "value", "--commit": "value", ...json } },
@@ -34,34 +58,44 @@ export const COMMANDS: readonly CommandSpec[] = [
34
58
  { name: "final seeds", usage: "final seeds <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
35
59
  { name: "selection", usage: "selection <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
36
60
  { name: "protocol", usage: "protocol <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
37
- { name: "executor set", usage: "executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH [--json]", mutates: true, options: { "--kind": "value", "--host": "value", "--workdir": "value", ...json } },
61
+ { name: "executor set", usage: "executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH [--retention-cap-bytes BYTES] [--gpu-devices IDS --gpu-min-free-memory-mb MB --gpu-max-load-ratio RATIO] [--json]", mutates: true, options: { "--kind": "value", "--host": "value", "--workdir": "value", "--retention-cap-bytes": "value", "--gpu-devices": "value", "--gpu-min-free-memory-mb": "value", "--gpu-max-load-ratio": "value", ...json } },
62
+ { name: "executor inputs hash", usage: "executor inputs hash <dir> <path> [--json]", mutates: "network", options: json },
38
63
  { name: "executor check", usage: "executor check <dir> [--json]", mutates: "network", options: json },
39
64
  { name: "gate list", usage: "gate list <dir> [--json]", mutates: false, options: json },
40
- { name: "gate approve", usage: "gate approve <dir> <scope|screen|design|final|review|plan:node-id> [--reason TEXT] [--json]", mutates: true, options: { "--reason": "value", ...json } },
41
- { name: "gate reject", usage: "gate reject <dir> <scope|screen|design|final|review|plan:node-id> --reason TEXT [--json]", mutates: true, options: { "--reason": "value", ...json } },
42
- { name: "attempt run", usage: "attempt run <dir> --repo PATH --commit SHA [--seed N] [--run NAME] [--label TEXT] [--retry ID] [--detach] [--json]", mutates: "network", options: { "--repo": "value", "--commit": "value", "--seed": "value", "--run": "value", "--label": "value", "--retry": "value", "--detach": "flag", ...json } },
65
+ { name: "gate approve", usage: "gate approve <dir> <scope|screen|design|final|review|plan:node-id|accept:artifact|harness:round-id> [--reason TEXT] [--json]", mutates: true, options: { "--reason": "value", ...json } },
66
+ { name: "gate reject", usage: "gate reject <dir> <scope|screen|design|final|review|plan:node-id|accept:artifact|harness:round-id> --reason TEXT [--json]", mutates: true, options: { "--reason": "value", ...json } },
67
+ { name: "attempt run", usage: "attempt run <dir> --repo PATH --commit SHA [--seed N] [--run NAME] [--label TEXT] [--retry ID] [--reuse off|eligible] [--force-fresh] [--detach] [--json]", mutates: "network", options: { "--repo": "value", "--commit": "value", "--seed": "value", "--run": "value", "--label": "value", "--retry": "value", "--reuse": "value", "--force-fresh": "flag", "--detach": "flag", ...json } },
43
68
  { name: "attempt list", usage: "attempt list <dir> [--run NAME] [--status running|succeeded|failed|cancelled|unknown] [--limit N] [--offset N] [--json]", mutates: false, options: { "--run": "value", "--status": "value", "--limit": "value", "--offset": "value", ...json } },
44
69
  { name: "attempt show", usage: "attempt show <dir> <id> [--json]", mutates: false, options: json },
45
70
  { name: "attempt cancel", usage: "attempt cancel <dir> <id> [--reason TEXT] [--json]", mutates: "network", options: { "--reason": "value", ...json } },
46
71
  { name: "attempt reconcile", usage: "attempt reconcile <dir> [--json]", mutates: "network", options: json },
47
- { name: "attempt logs", usage: "attempt logs <dir> <id> [--stage candidate|evaluator] [--stream stdout|stderr] [--tail BYTES] [--json]", mutates: false, options: { "--stage": "value", "--stream": "value", "--tail": "value", ...json } },
48
- { name: "lit search", usage: "lit search <dir> <query> [--source openalex|s2|arxiv|all] [--limit 1..50] [--year-from YYYY] [--json]", mutates: "network", options: { "--source": "value", "--limit": "value", "--year-from": "value", ...json } },
72
+ { name: "attempt logs", usage: "attempt logs <dir> <id> [--stage candidate|evaluator] [--candidate-stage NAME] [--stream stdout|stderr] [--tail BYTES] [--json]", mutates: false, options: { "--stage": "value", "--candidate-stage": "value", "--stream": "value", "--tail": "value", ...json } },
73
+ { name: "lit search", usage: "lit search <dir> <query> [--source openalex|s2|arxiv|all] [--limit 1..50] [--year-from YYYY] [--intent lexical|semantic|background] [--json]", mutates: "network", options: { "--source": "value", "--limit": "value", "--year-from": "value", "--intent": "value", ...json } },
74
+ { name: "lit queries", usage: "lit queries <dir> [--json]", mutates: false, options: json },
75
+ { name: "lit flow", usage: "lit flow <dir> [--markdown] [--json]", mutates: false, options: { "--markdown": "flag", ...json } },
49
76
  { name: "lit list", usage: "lit list <dir> [--status new|included|excluded] [--limit 1..500] [--json]", mutates: false, options: { "--status": "value", "--limit": "value", ...json } },
50
- { name: "lit screen", usage: "lit screen <dir> <id>... --include|--exclude [--reason TEXT] [--json]", mutates: true, options: { "--include": "flag", "--exclude": "flag", "--reason": "value", ...json } },
77
+ { name: "lit screen", usage: "lit screen <dir> <id>... --include|--exclude [--code CODE] [--reason TEXT] [--json]", mutates: true, options: { "--include": "flag", "--exclude": "flag", "--code": "value", "--reason": "value", ...json } },
51
78
  { name: "lit card", usage: "lit card <dir> <id> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
79
+ { name: "lit card export", usage: "lit card export <dir> <id>... --vault ID [--model-family NAME] [--confirm FINGERPRINT] [--json]", mutates: "network", options: { "--vault": "value", "--model-family": "value", "--confirm": "value", ...json } },
80
+ { name: "lit card import", usage: "lit card import <dir> <id>... --vault ID [--json]", mutates: "network", options: { "--vault": "value", ...json } },
81
+ { name: "lit card list", usage: "lit card list <dir> [--json]", mutates: false, options: json },
52
82
  { name: "lit verify", usage: "lit verify <dir> [<id>...] [--json]", mutates: "network", options: json },
53
83
  { name: "lit bib", usage: "lit bib <dir> [--json]", mutates: true, options: json },
54
84
  { name: "review add", usage: "review add <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
55
85
  { name: "review resolve", usage: "review resolve <dir> <review-id>/<finding-id> --reason TEXT [--json]", mutates: true, options: { "--reason": "value", ...json } },
56
86
  { name: "review show", usage: "review show <dir> [--json]", mutates: false, options: json },
87
+ { name: "review checklist", usage: "review checklist [--json]", mutates: false, options: json },
57
88
  { name: "paper build", usage: "paper build <dir> [--json]", mutates: true, options: json },
89
+ { name: "paper plan set", usage: "paper plan set <dir> --file PATH|- [--json]", mutates: true, options: { "--file": "value", ...json } },
90
+ { name: "paper plan show", usage: "paper plan show <dir> [--json]", mutates: false, options: json },
58
91
  { name: "paper check", usage: "paper check <dir> [--json]", mutates: false, options: json },
59
92
  { name: "cite check", usage: "cite check <dir> <draft> [--json]", mutates: false, options: json },
60
93
  { name: "playbook", usage: "playbook", mutates: false, options: {} },
61
94
  { name: "mcp", usage: "mcp", mutates: false, options: {} },
62
95
  ];
63
96
  export function findCommand(args: string[]): { spec: CommandSpec; rest: string[] } | undefined {
64
- for (const words of [2, 1]) {
97
+ const longest = Math.max(...COMMANDS.map(command => command.name.split(" ").length));
98
+ for (let words = longest; words >= 1; words--) {
65
99
  const name = args.slice(0, words).join(" "), spec = COMMANDS.find(c => c.name === name);
66
100
  if (spec) return { spec, rest: args.slice(words) };
67
101
  }