@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/src/commands.ts CHANGED
@@ -1,14 +1,22 @@
1
+ import {proposeLesson, decideLesson, checkLesson, listLessonCandidates} from "./harness/lesson-candidates.ts";
2
+ import type {SkillCheckOptions} from "./memory/skill-check.ts";
3
+ import {setHarnessStream, readHarnessStream, selectExperience, freezeExperience, checkExperience} from "./harness/experience.ts";
4
+ import {harnessRoundBinding, readHarnessRounds, type HarnessRound, setHarnessRound, showHarness, importHarnessFixture, recordHarnessTransition} from "./harness/rounds.ts";
5
+ import { readProvenance, compareLineage, attemptReuseView, type ProvenanceOptions, type ProvenancePage, type LineageComparison } from "./provenance.ts";
6
+ import { validateAutonomyMode, validatePhase, PHASES, ACCEPT_ARTIFACTS, resolveAutonomy, type AcceptArtifact, type Autonomy } from "./autonomy.ts";
7
+ import { copilotBinding, requireCopilotAccept } from "./copilot.ts";
1
8
  import { homedir } from "node:os";
2
9
  import { addStudy, removeStudy, readRegistry } from "./console/registry.ts";
3
- import { readWatchSnapshot, setWatch, runWatch, showWatch, type WatchSnapshot } from "./lit/watch.ts";
10
+ import { readWatchSnapshot, setWatch, runWatch, showWatch, recordWatchFailure, watchFailureClass, type WatchSnapshot } from "./lit/watch.ts";
4
11
  import { runSetup, type SetupMode } from "./setup.ts";
5
- import { proposeSkill, decideSkill, listSkills } from "./memory/skills.ts";
12
+ import { proposeSkill, decideSkill, listSkills, checkSkill } from "./memory/skills.ts";
6
13
  import { rankLessons, type LessonRankOptions } from "./memory/lessons.ts";
7
14
  import { createAmemClient } from "./memory/amem.ts";
8
15
  import { previewArchive, exportArchive, type ArchivePreview, type ArchiveResult } from "./memory/archive.ts";
9
- import { addReview, resolveReview, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
16
+ import { addReview, resolveReview, reviewChecklist, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
10
17
  import { buildPaper } from "./paper/build.ts";
11
18
  import { checkPaper } from "./paper/check.ts";
19
+ import { setPaperPlan, showPaperPlan } from "./paper/plan.ts";
12
20
  import { addAblation, showAblate, closeAblate } from "./exp/ablate.ts";
13
21
  import { setFinalSeeds, finalGateBinding, requireFinalInputs, closeFinal, showPosthoc } from "./exp/final.ts";
14
22
  import { addIdea, decideIdea } from "./exp/ideas.ts";
@@ -17,36 +25,47 @@ import { setSelection } from "./exp/selection.ts";
17
25
  import { createHubClient } from "./plan/hub.ts";
18
26
  import { runPlan, type ControllerRuntime, type Observation, type StepNode } from "./plan/controller.ts";
19
27
  import { resolveSnapshot } from "./exp/snapshot.ts";
20
- import { spawnRunner } from "./exp/executor.ts";
28
+ import { GpuAdmissionDeferred, spawnRunner } from "./exp/executor.ts";
21
29
  import { foldPlan, readPlanState, planGateBinding, prepareControl, type ControlRequest, type ControlResult } from "./plan/state.ts";
22
30
  import { setPlan } from "./plan/definition.ts";
23
31
  export { manifest } from "./manifest.ts";
32
+ import { exportBundle } from "./study-export.ts";
24
33
  import { existsSync, readdirSync, utimesSync } from "node:fs";
25
34
  import { join, resolve } from "node:path";
26
35
  import type { Http } from "./http.ts";
27
36
  import { readScope, scopeHash, setScope } from "./scope.ts";
28
- import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study } from "./study.ts";
37
+ import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, isHarnessGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } from "./study.ts";
29
38
  import { candidatesFile, includedHash, isVerified, loadCandidates, mergeCandidates, sameWork, verifySubject, type Candidate } from "./lit/candidates.ts";
39
+ import { litQueries, nextSearchId, validateIntent } from "./lit/queries.ts";
40
+ import { flowMarkdown, litFlow } from "./lit/flow.ts";
30
41
  import { searchSource, SOURCES, type SourceName } from "./lit/sources.ts";
31
42
  import { verifyCandidates } from "./lit/verify.ts";
32
43
  import { assignCitekeys, renderBib } from "./lit/bibtex.ts";
33
44
  import { checkCitations } from "./lit/cite.ts";
34
45
  import { cardPath, validateCard } from "./lit/cards.ts";
46
+ import { createVaultClient, exportCards, importCards, listCards, previewCardExport } from "./memory/vault-cards.ts";
35
47
  import { designBinding, protocolHash, readDesign, setProtocol } from "./exp/protocol.ts";
36
48
  import { requireExperiment } from "./study.ts";
37
- import { checkExecutor, setExecutor } from "./exp/executor.ts";
49
+ import { checkExecutor, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
38
50
  import { cancelAttempt, listAttempts, listAttemptSummaries, reconcileAttempts, runAttempt, showAttempt, type AttemptContext, type AttemptListOptions, type AttemptOptions } from "./exp/attempts.ts";
39
51
  import { readAttemptLogs, type LogOptions } from "./exp/logs.ts";
52
+ import { retainedOperation, type RetainedRef, type RetentionResult } from "./exp/retention.ts";
53
+ import { assertStudyReadLock, onlyKeys, plain, prepareCommit, type PendingEvent } from "./study.ts";
40
54
 
41
55
  export type ExperimentRuntime = Omit<AttemptContext, "actor">;
42
56
  export interface Ctx extends ExperimentRuntime { actor: Actor; http: Http; signal?: AbortSignal }
43
57
  const MAX_IDS = 200, DRAFT_BYTES = 2 * 1024 * 1024, BIB_BYTES = 16 * 1024 * 1024, CARD_BYTES = 65_536;
44
58
 
45
- export function binder(dir: string): Binder {
46
- return gate => gate === "review" ? reviewBinding(dir) : gate === "final" ? finalGateBinding(dir) : gate.startsWith("plan:") ? planGateBinding(readPlanState(dir, readLedger(dir)), gate) : gate === "scope" ? scopeHash(dir) : gate === "design" ? designBinding(dir) : includedHash(loadCandidates(dir));
59
+ export function binder(dir: string, rounds?: readonly HarnessRound[]): Binder {
60
+ let harness = rounds === undefined ? undefined : new Map(rounds.map(round => [round.id, harnessRoundBinding(round)]));
61
+ const harnessHash = (id: string) => {
62
+ harness ??= new Map(readHarnessRounds(dir).map(round => [round.id, harnessRoundBinding(round)]));
63
+ return harness.get(id);
64
+ };
65
+ return gate => isHarnessGate(gate) ? harnessHash(gate.slice(8)) : gate.startsWith("accept:") ? copilotBinding(dir, gate.slice(7) as AcceptArtifact) : gate === "review" ? reviewBinding(dir) : gate === "final" ? finalGateBinding(dir) : gate.startsWith("plan:") ? planGateBinding(readPlanState(dir, readLedger(dir)), gate) : gate === "scope" ? scopeHash(dir) : gate === "design" ? designBinding(dir) : includedHash(loadCandidates(dir));
47
66
  }
48
67
  function gateName(value: string): GateName {
49
- if (!GATES.includes(value as GateName) && !value.startsWith("plan:")) throw new Error(`unknown gate: ${value} (${GATES.join(", ")})`);
68
+ if (!GATES.includes(value as GateName) && !ACCEPT_ARTIFACTS.some(artifact => value === `accept:${artifact}`) && !value.startsWith("plan:") && !isHarnessGate(value)) throw new Error("unknown gate: unsupported name; run ares gate list <dir> and choose a listed gate before approval or rejection");
50
69
  return value as GateName;
51
70
  }
52
71
  function ids(values: string[]): string[] {
@@ -65,6 +84,24 @@ export function init(dir: string, options: { question: string; mode?: string; au
65
84
  return { created: resolve(dir), study };
66
85
  }
67
86
 
87
+ export function autonomyShow(dirArg: string) {
88
+ const { study } = openStudy(dirArg), policy = study.autonomy;
89
+ const effective = Object.fromEntries(PHASES.map(phase => [phase, typeof policy === "string" ? policy : policy.phases[phase] ?? policy.default]));
90
+ return { autonomy: policy, effective };
91
+ }
92
+ export async function autonomySet(dirArg: string, rawMode: string, rawPhase: string | undefined, ctx: Pick<Ctx, "actor">) {
93
+ const mode = validateAutonomyMode(rawMode), phase = rawPhase === undefined ? undefined : validatePhase(rawPhase);
94
+ const { dir } = openStudy(dirArg);
95
+ return withLock(dir, () => {
96
+ const { study } = openStudy(dir), from = study.autonomy;
97
+ const to: Autonomy = phase !== undefined ? { default: typeof from === "string" ? from : from.default, phases: { ...(typeof from === "string" ? {} : from.phases), [phase]: mode } }
98
+ : typeof from === "string" ? mode : { default: mode, phases: { ...from.phases } };
99
+ const v = study.v === 2 || typeof to !== "string" || to === "copilot" || to === "step" ? 2 : 1;
100
+ commit(dir, [[join(dir, "study.json"), JSON.stringify({ ...study, v, autonomy: to }, null, 2) + "\n", STUDY_BYTES]], [{ actor: ctx.actor, type: "autonomy.set", data: { from, to, phase: phase ?? null } }]);
101
+ return autonomyShow(dir);
102
+ });
103
+ }
104
+
68
105
  export async function protocol(dirArg: string, raw: unknown, ctx: Ctx) {
69
106
  const { dir } = openStudy(dirArg);
70
107
  return withLock(dir, () => {
@@ -76,10 +113,97 @@ export async function executorSet(dirArg: string, raw: unknown, ctx: Ctx) {
76
113
  const { dir } = openStudy(dirArg);
77
114
  return withLock(dir, () => setExecutor(dir, raw, ctx.actor));
78
115
  }
116
+ /** Read only configured executor-host inputs; no paths or bodies are recorded in the study. */
117
+ export async function executorInputsHash(dirArg: string, path: string, ctx: Ctx): Promise<InputManifest> {
118
+ const { dir, study } = openStudy(dirArg); requireExperiment(study);
119
+ const executor = readExecutor(dir);
120
+ if (!executor) throw new Error("executor: not configured; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH");
121
+ return hashExecutorInput(executor, path, ctx.runner);
122
+ }
79
123
  export const executorCheck = (dir: string, ctx: Ctx) => checkExecutor(dir, ctx.runner);
80
- export const attemptRun = (dir: string, options: AttemptOptions, ctx: Ctx) => runAttempt(dir, options, ctx);
124
+
125
+ function retentionRefs(raw: unknown): RetainedRef[] {
126
+ if (!Array.isArray(raw) || !raw.length || raw.length > 500) throw new Error("retention refs: select 1..500 explicit retained references");
127
+ const seen = new Set<string>();
128
+ return raw.map(value => {
129
+ if (!plain(value)) throw new Error("retention refs: each reference must be an object");
130
+ onlyKeys(value, ["attemptId", "stage", "sha256"], "retention reference");
131
+ if (typeof value.attemptId !== "string" || !/^[a-f0-9]{16}$/.test(value.attemptId) || typeof value.stage !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(value.stage) || ["constructor", "prototype", "__proto__"].includes(value.stage) || typeof value.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.sha256)) throw new Error("retention reference: invalid attempt, stage or manifest digest; use identities from retention inspect");
132
+ const key = `${value.attemptId}/${value.stage}`;
133
+ if (seen.has(key)) throw new Error("retention refs: duplicate source; select each attempt/stage once");
134
+ seen.add(key);
135
+ return { attemptId: value.attemptId, stage: value.stage, sha256: value.sha256 };
136
+ });
137
+ }
138
+ function retentionExecutor(dirArg: string) {
139
+ const { dir, study } = openStudy(dirArg); requireExperiment(study);
140
+ const executor = readExecutor(dir);
141
+ if (!executor) throw new Error("executor: not configured; configure an executor before retention inspect or prune");
142
+ return { dir, study, executor };
143
+ }
144
+ /** Read-only study operation; the executor serializes inventory with producer/consumer/prune state. */
145
+ export async function retentionInspect(dirArg: string, ctx: Pick<Ctx, "runner">, options: { offset?: number; limit?: number } = {}): Promise<RetentionResult> {
146
+ if (!plain(options)) throw new Error("retention inspect: options object required");
147
+ onlyKeys(options, ["offset", "limit"], "retention inspect");
148
+ if (options.offset !== undefined && (!Number.isSafeInteger(options.offset) || options.offset < 0 || options.offset > 16_000_000) || options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 500)) throw new Error("retention inspect: use offset 0..16000000 and limit 1..500");
149
+ const { study, executor } = retentionExecutor(dirArg);
150
+ return retainedOperation(executor, { op: "inspect", studyId: study.id, ...options }, ctx.runner ?? spawnRunner);
151
+ }
152
+ /** Preview has no local receipt. Confirmation checks current policy and records only a validated disposal. */
153
+ export async function retentionPrune(dirArg: string, options: { refs: RetainedRef[]; fingerprint?: string }, ctx: Ctx): Promise<RetentionResult> {
154
+ if (!plain(options)) throw new Error("retention prune: options object required");
155
+ onlyKeys(options, ["refs", "fingerprint"], "retention prune");
156
+ const refs = retentionRefs(options.refs), fingerprint = options.fingerprint;
157
+ if (fingerprint !== undefined && (typeof fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(fingerprint))) throw new Error("retention prune: invalid fingerprint; preview the exact references before confirming");
158
+ const initial = retentionExecutor(dirArg);
159
+ const request = { op: "prune" as const, studyId: initial.study.id, refs, ...(fingerprint === undefined ? {} : { fingerprint }) };
160
+ const checked = async (executor: typeof initial.executor) => {
161
+ const result = await retainedOperation(executor, request, ctx.runner ?? spawnRunner);
162
+ if (typeof result.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(result.fingerprint) || result.pruned !== (fingerprint === undefined ? 0 : refs.length) || (fingerprint !== undefined && result.fingerprint !== fingerprint)) throw new Error("retention prune: invalid executor receipt; inspect authoritative tombstones before retrying");
163
+ return { op: "prune" as const, fingerprint: result.fingerprint, pruned: result.pruned };
164
+ };
165
+ if (fingerprint === undefined) return checked(initial.executor);
166
+ return withLock(initial.dir, async lock => {
167
+ const { dir, study, executor } = retentionExecutor(initial.dir);
168
+ requireCopilotAccept(dir, "hypotheses");
169
+ const binding = designBinding(dir), approval = requireGate(dir, study, "design", binder(dir));
170
+ const event: PendingEvent = { actor: ctx.actor, type: "retention.pruned", data: { fingerprint, refsSha256: sha256(JSON.stringify(refs)), count: refs.length, refs: refs.map(ref => [ref.attemptId, ref.stage, ref.sha256]) } };
171
+ prepareCommit(dir, [], [...approval, event]);
172
+ assertStudyReadLock(dir, lock);
173
+ const result = await checked(executor);
174
+ // Executor tombstones are authoritative across a crash before this local audit receipt.
175
+ assertStudyReadLock(dir, lock);
176
+ if (designBinding(dir) !== binding) throw new Error("retention prune: design changed during disposal; inspect authoritative tombstones before retrying");
177
+ commit(dir, [], [...approval, event]);
178
+ return result;
179
+ });
180
+ }
181
+
182
+ export const harnessStreamSet = (dir: string, raw: unknown, ctx: Ctx) => withLock(dir, () => setHarnessStream(dir, raw, ctx.actor));
183
+ export const harnessStreamShow = (dir: string) => readHarnessStream(dir);
184
+ export const experienceSelect = (dir: string, raw: unknown, ctx: Pick<Ctx, "runner" | "now">, env: NodeJS.ProcessEnv = process.env) => selectExperience(dir, raw, {...ctx, env});
185
+ export const experienceFreeze = (dir: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => freezeExperience(dir, raw, ctx.actor, {...ctx, env, lock}));
186
+ export const experienceCheck = (dir: string, round: string, identity: {model: string; runtime: string; toolsetSha256?: string}, ctx: Pick<Ctx, "runner" | "now">, env: NodeJS.ProcessEnv = process.env) => checkExperience(dir, round, identity, {...ctx, env});
187
+ export const harnessSet = (dir: string, raw: unknown, ctx: Ctx) => withLock(dir, () => setHarnessRound(dir, raw, ctx.actor));
188
+ export const harnessContrast = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "contrast", raw, ctx.actor));
189
+ export const harnessCompose = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "composition", raw, ctx.actor));
190
+ export const harnessClose = (dir: string, round: string, raw: unknown, confirm: string | undefined, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "closure", raw, ctx.actor, confirm));
191
+ export const harnessAdopt = (dir: string, round: string, raw: unknown, confirm: string | undefined, ctx: Ctx) => withLock(dir, () => recordHarnessTransition(dir, round, "adoption", raw, ctx.actor, confirm));
192
+ export const harnessShow = (dir: string, round?: string) => showHarness(dir, round);
193
+ export const harnessImport = (dir: string, round: string, raw: unknown, ctx: Ctx) => withLock(dir, () => importHarnessFixture(dir, round, raw, ctx.actor));
194
+ export async function attemptRun(dir: string, options: AttemptOptions, ctx: Ctx) {
195
+ if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("attempt reuse: off or eligible required; select --reuse off|eligible (MCP reuse) and retry");
196
+ if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("attempt forceFresh: boolean required; set forceFresh to true/false or use --force-fresh, then retry");
197
+ try { return await runAttempt(dir, options, ctx); }
198
+ catch (error) { if (error instanceof GpuAdmissionDeferred) return error.result; throw error; }
199
+ }
81
200
  export const attemptList = (dir: string, options: AttemptListOptions = {}) => listAttemptSummaries(dir, options);
82
- export const attemptShow = (dir: string, id: string) => showAttempt(dir, id);
201
+ export const attemptShow = (dir: string, id: string) => {
202
+ const attempt = showAttempt(dir, id);
203
+ if (attempt.v !== 3) return attempt;
204
+ const reuseView = attemptReuseView(attempt, readLedger(dir));
205
+ return reuseView === undefined ? attempt : {...attempt, reuseView};
206
+ };
83
207
  export const attemptCancel = (dir: string, id: string, reason: string | undefined, ctx: Ctx) => cancelAttempt(dir, id, reason, ctx);
84
208
  export const attemptReconcile = (dir: string, ctx: Ctx) => reconcileAttempts(dir, ctx);
85
209
  export const attemptLogs = (dir: string, id: string, options: LogOptions, ctx: Ctx) => readAttemptLogs(dir, id, options, ctx.runner);
@@ -103,6 +227,8 @@ export function status(dirArg: string) {
103
227
  };
104
228
  }
105
229
 
230
+ export const studyExport = (dir: string, options: { bundle: string; list?: boolean }) => exportBundle(dir, options);
231
+
106
232
  export async function scope(dirArg: string, raw: unknown, ctx: Ctx) {
107
233
  const { dir } = openStudy(dirArg);
108
234
  return withLock(dir, () => {
@@ -112,15 +238,17 @@ export async function scope(dirArg: string, raw: unknown, ctx: Ctx) {
112
238
  }
113
239
 
114
240
  export function gateList(dirArg: string) {
115
- const { dir, study } = openStudy(dirArg), events = readLedger(dir), bind = binder(dir);
241
+ const { dir, study } = openStudy(dirArg), events = readLedger(dir);
242
+ const harness = study.mode === "experiment" ? readHarnessRounds(dir, events) : [], bind = binder(dir, harness);
116
243
  const plan = foldPlan(events);
117
- const gates: GateName[] = [...GATES.filter(g => (g !== "design" && g !== "final") || study.mode === "experiment"), ...(plan?.nodes.filter(n => n.kind === "gate").map(n => `plan:${n.id}` as GateName) ?? [])];
244
+ const accepts = ACCEPT_ARTIFACTS.filter(artifact => resolveAutonomy(study.autonomy, `accept:${artifact}`) === "copilot").map(artifact => `accept:${artifact}` as GateName);
245
+ const gates: GateName[] = [...accepts, ...GATES.filter(g => (g !== "design" && g !== "final") || study.mode === "experiment"), ...(plan?.nodes.filter(n => n.kind === "gate").map(n => `plan:${n.id}` as GateName) ?? []), ...harness.map(round => `harness:${round.id}` as GateName)];
118
246
  return gates.map(g => gateState(g, events, bind));
119
247
  }
120
248
 
121
249
  export async function gateDecide(dirArg: string, gate: string, decision: "approve" | "reject", reason: string | undefined, ctx: Ctx, guard?: () => void) {
122
250
  const { dir, study } = openStudy(dirArg), name = gateName(gate), why = reason === undefined ? undefined : boundedText(reason, "--reason", 500);
123
- if (name === "design" || name === "final") requireExperiment(study);
251
+ if (name === "design" || name === "final" || isHarnessGate(name)) requireExperiment(study);
124
252
  return withLock(dir, () => {
125
253
  guard?.();
126
254
  if (name === "final") requireFinalInputs(dir);
@@ -130,11 +258,12 @@ export async function gateDecide(dirArg: string, gate: string, decision: "approv
130
258
  });
131
259
  }
132
260
 
133
- export async function search(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number }, ctx: Ctx) {
261
+ export async function search(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number; intent?: string }, ctx: Ctx) {
134
262
  const { dir } = openStudy(dirArg); return withLock(dir, () => searchLocked(dir, query, options, ctx));
135
263
  }
136
- async function searchLocked(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number }, ctx: Ctx) {
264
+ async function searchLocked(dirArg: string, query: string, options: { source?: string; limit?: number; yearFrom?: number; intent?: string }, ctx: Ctx) {
137
265
  const { dir, study } = openStudy(dirArg), q = boundedText(query, "query", 500);
266
+ const intent = options.intent === undefined ? undefined : validateIntent(options.intent);
138
267
  const source = options.source ?? "all";
139
268
  if (source !== "all" && !SOURCES.includes(source as SourceName)) throw new Error("--source: openalex, s2, arxiv or all");
140
269
  const limit = options.limit ?? 20;
@@ -148,15 +277,20 @@ async function searchLocked(dirArg: string, query: string, options: { source?: s
148
277
  const names = source === "all" ? SOURCES : [source as SourceName];
149
278
  const results = [];
150
279
  for (const name of names) results.push(await searchSource(ctx.http, name, q, { limit, ...(yearFrom !== undefined ? { yearFrom } : {}), ...(sc.yearTo !== undefined ? { yearTo: sc.yearTo } : {}) }));
151
- const list = loadCandidates(dir), counts = mergeCandidates(list, results.flatMap(r => r.records), sc.maxCandidates);
280
+ const list = loadCandidates(dir), counts = mergeCandidates(list, results.flatMap(r => r.records), sc.maxCandidates, undefined, nextSearchId(readLedger(dir)));
152
281
  const sources = results.map(r => ({ source: r.source, ok: r.ok, returned: r.records.length, ...(r.error ? { error: r.error } : {}) }));
153
282
  // A search where every source failed is recorded but is not a success, so it approves nothing.
154
283
  const answered = sources.some(r => r.ok);
155
- commit(dir, [candidatesFile(dir, list)], [...(answered ? approval : []), { actor: ctx.actor, type: "lit.search", data: { query: q, sources, ...counts } }]);
156
- return { query: q, sources, ...counts, candidates: list.length };
284
+ // Intent and year-from are added only when given, so a search without them keeps the earlier event shape.
285
+ commit(dir, [candidatesFile(dir, list)], [...(answered ? approval : []), { actor: ctx.actor, type: "lit.search", data: { query: q, ...(intent ? { intent } : {}), ...(options.yearFrom !== undefined ? { yearFrom: options.yearFrom } : {}), sources, ...counts } }]);
286
+ return { query: q, ...(intent ? { intent } : {}), sources, ...counts, candidates: list.length };
157
287
 
158
288
  }
159
289
 
290
+ export const queries = (dir: string) => litQueries(dir);
291
+ export const flowMarkdownView = (dir: string) => ({ markdown: flowMarkdown(dir) });
292
+ export const litFlowView = (dir: string) => litFlow(dir);
293
+ export function flow(dir: string, format: "json" | "markdown" = "json") { return format === "markdown" ? flowMarkdownView(dir) : litFlow(dir); }
160
294
  export function list(dirArg: string, options: { status?: string; limit?: number }) {
161
295
  const { dir } = openStudy(dirArg), limit = options.limit ?? 50;
162
296
  if (options.status !== undefined && !["new", "included", "excluded"].includes(options.status)) throw new Error("--status: new, included or excluded");
@@ -173,10 +307,15 @@ export function list(dirArg: string, options: { status?: string; limit?: number
173
307
  };
174
308
  }
175
309
 
176
- export async function screen(dirArg: string, values: string[], decision: "include" | "exclude", reason: string | undefined, ctx: Ctx, guard?: () => void) {
310
+ export async function screen(dirArg: string, values: string[], decision: "include" | "exclude", reason: string | undefined, ctx: Ctx, guard?: () => void, code?: string) {
177
311
  const { dir, study } = openStudy(dirArg), wanted = ids(values), why = reason === undefined ? undefined : boundedText(reason, "--reason", 500);
312
+ if (code !== undefined && decision !== "exclude") throw new Error("lit screen: --code applies only with --exclude; drop --code or exclude instead");
178
313
  return withLock(dir, () => {
179
314
  guard?.();
315
+ if (code !== undefined) {
316
+ const declared = readScope(dir)?.exclusionCodes ?? [];
317
+ if (!declared.some(item => item.code === code)) throw new Error(`lit screen: unknown exclusion code ${JSON.stringify(code).slice(0, 40)}; declare it in scope.json exclusionCodes (${declared.length ? declared.map(item => item.code).join(", ") : "none declared"}) and rerun ares scope, or omit --code`);
318
+ }
180
319
  const all = loadCandidates(dir), at = new Date().toISOString(), status = decision === "include" ? "included" : "excluded";
181
320
  for (const id of wanted) find(all, id);
182
321
  const approval = requireGate(dir, study, "scope", binder(dir));
@@ -184,8 +323,9 @@ export async function screen(dirArg: string, values: string[], decision: "includ
184
323
  const c = find(all, id);
185
324
  c.status = status; c.decidedBy = ctx.actor; c.decidedAt = at;
186
325
  if (why) c.reason = why; else delete c.reason;
326
+ if (code !== undefined) c.exclusionCode = code; else delete c.exclusionCode;
187
327
  }
188
- commit(dir, [candidatesFile(dir, all)], [...approval, { actor: ctx.actor, type: "lit.screen", data: { ids: wanted, decision, ...(why ? { reason: why } : {}) } }]);
328
+ commit(dir, [candidatesFile(dir, all)], [...approval, { actor: ctx.actor, type: "lit.screen", data: { ids: wanted, decision, ...(why ? { reason: why } : {}), ...(code !== undefined ? { code } : {}) } }]);
189
329
  return { decision, ids: wanted, gate: gateState("screen", readLedger(dir), binder(dir)) };
190
330
  });
191
331
  }
@@ -202,6 +342,20 @@ export async function card(dirArg: string, id: string, raw: unknown, ctx: Ctx) {
202
342
  });
203
343
  }
204
344
 
345
+ /** Read-only without --confirm; with the current fingerprint, writes each card to its vault reference note. Needs the scope gate. */
346
+ export async function cardExport(dirArg: string, ids: string[], options: { vault: string; confirm?: string; modelFamily?: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env) {
347
+ const { dir, study } = openStudy(dirArg);
348
+ if (options.confirm === undefined) { const { payloads: _p, ...preview } = previewCardExport(dir, options.vault, ids, options.modelFamily); return { ...preview, wouldWrite: true }; }
349
+ const client = createVaultClient(options.vault, dir, ctx.runner, env);
350
+ return exportCards(dir, options.vault, ids, options.confirm, ctx.actor, client, () => requireGate(dir, study, "scope", binder(dir)), options.modelFamily);
351
+ }
352
+ /** Copies cards from vault reference notes for included, identifier-verified candidates; needs the scope gate and never changes verification, screening or other gates. */
353
+ export async function cardImport(dirArg: string, ids: string[], options: { vault: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env) {
354
+ const { dir, study } = openStudy(dirArg), client = createVaultClient(options.vault, dir, ctx.runner, env);
355
+ return importCards(dir, options.vault, ids, ctx.actor, client, () => requireGate(dir, study, "scope", binder(dir)));
356
+ }
357
+ export const cardList = (dir: string) => listCards(dir);
358
+
205
359
  /**
206
360
  * Without ids: included candidates never checked, checked against other identifiers, or left unknown, up to 200.
207
361
  * Final results (no identifier, not found, title or year mismatch) are skipped so the batch always advances;
@@ -262,23 +416,26 @@ export async function planControl(dirArg: string, request: ControlRequest, ctx:
262
416
  const { dir } = openStudy(dirArg);
263
417
  const prepared = await withLock(dir, () => {
264
418
  const events = readLedger(dir), state = readPlanState(dir, events);
265
- const prepared = prepareControl(state, events, request, ctx.actor);
419
+ const prepared = prepareControl(state, events, request, ctx.actor, openStudy(dir).study.autonomy);
266
420
  if (!prepared.event) return { result: prepared.result };
267
421
  const node = state.nodes.find(n => n.id === request.node);
268
422
  const attempt = node?.attemptId ? listAttempts(dir).attempts.find(a => a.id === node.attemptId) : undefined;
269
- if (request.action === "cancel" && attempt) return { attemptId: attempt.id };
423
+ if (request.action === "cancel" && attempt) return { attemptId: attempt.id, dispatchId: node?.dispatchId };
270
424
  // A missing record after a crash is uncertain, and explicit retry/cancel may release it.
271
425
  if ((request.action === "retry" || request.action === "skip") && attempt?.status === "running") throw new Error(`plan node ${node!.id}: attempt is still running; cancel it or run ares attempt reconcile before retry`);
272
- commit(dir, [], [prepared.event]);
426
+ commit(dir, [], [prepared.event, ...(prepared.pause ? [prepared.pause] : [])]);
273
427
  return { result: prepared.result };
274
428
  });
275
429
  if (prepared.result) return prepared.result;
276
430
  let result: ControlResult | undefined;
277
431
  await cancelAttempt(dir, prepared.attemptId!, "plan cancellation", ctx, () => {
278
432
  const events = readLedger(dir), state = readPlanState(dir, events);
279
- const prepared = prepareControl(state, events, request, ctx.actor);
280
- result = prepared.result;
281
- return prepared.event ? [prepared.event] : [];
433
+ // An identical cancel may have committed while this request waited for the attempt control lock.
434
+ const current = prepareControl(state, events, request, ctx.actor, openStudy(dir).study.autonomy);
435
+ if (!current.event) { result = current.result; return []; }
436
+ if (state.nodes.find(node => node.id === request.node)?.dispatchId !== prepared.dispatchId) throw new Error("plan cancel: dispatch changed while cancelling the attempt; inspect ares plan show and retry with a new command-id");
437
+ result = current.result;
438
+ return current.event ? [current.event, ...(current.pause ? [current.pause] : [])] : [];
282
439
  });
283
440
  return result!;
284
441
  }
@@ -295,15 +452,19 @@ function stepNumber(node: StepNode, key: string): number | undefined {
295
452
  }
296
453
  export async function planRun(dirArg: string, options: { parallel?: number }, ctx: Ctx) {
297
454
  const { dir } = openStudy(dirArg);
298
- const attemptOptions = (node: StepNode, retryOf?: string) => {
455
+ const attemptOptions = (node: StepNode, retryOf?: string): AttemptOptions => {
299
456
  const parent = retryOf ?? (node.args.retry !== undefined ? stepText(node, "retry") : undefined);
300
457
  const retry = parent && listAttempts(dir).attempts.some(a => a.id === parent) ? parent : undefined;
458
+ const reuse = node.args.reuse;
459
+ if (reuse !== undefined && reuse !== "off" && reuse !== "eligible") throw new Error("plan attempt reuse: off or eligible required; correct args.reuse with ares plan set <dir>, then retry the node explicitly");
460
+ const forceFresh = node.args["force-fresh"];
461
+ if (forceFresh !== undefined && typeof forceFresh !== "boolean") throw new Error("plan attempt force-fresh: boolean required; correct args.force-fresh with ares plan set <dir>, then retry the node explicitly");
301
462
  return {
302
463
  repo: resolve(dir, stepText(node, "repo")), commit: stepText(node, "commit"),
303
464
  ...(stepNumber(node, "seed") !== undefined ? { seed: stepNumber(node, "seed")! } : {}),
304
465
  ...(node.args.run !== undefined ? { run: stepText(node, "run") } : {}),
305
466
  ...(node.args.label !== undefined ? { label: stepText(node, "label") } : {}),
306
- ...(retry ? { retry } : {}), detach: true,
467
+ ...(retry ? { retry } : {}), ...(reuse === undefined ? {} : { reuse }), ...(forceFresh === undefined ? {} : { forceFresh }), detach: true,
307
468
  };
308
469
  };
309
470
  const observed = (attempt: ReturnType<typeof showAttempt>): Observation => ({
@@ -317,6 +478,7 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
317
478
  actor: ctx.actor, ...(ctx.signal ? { signal: ctx.signal } : {}), ...(ctx.sleep ? { sleep: ctx.sleep } : {}),
318
479
  prepare: async (node, state) => {
319
480
  if (node.command !== "attempt.run") return {};
481
+ requireCopilotAccept(dir, "hypotheses");
320
482
  const design = readDesign(dir);
321
483
  if (!design) throw new Error("plan attempt: protocol missing; run ares protocol before resume");
322
484
  const options = attemptOptions(node, state.retryOf), snapshot = await resolveSnapshot(options.repo, options.commit, ctx.runner ?? spawnRunner);
@@ -324,7 +486,13 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
324
486
  return { attemptId: attemptId(protocolHash(design.protocol), snapshot.commit, snapshot.treeId, options.seed ?? design.protocol.seeds[0]!, options.run ?? "main", options.retry) };
325
487
  },
326
488
  execute: async (node, state) => {
327
- if (node.command === "attempt.run") return observed(await runAttempt(dir, { ...attemptOptions(node, state.retryOf), expectedId: state.attemptId! }, ctx));
489
+ if (node.command === "attempt.run") {
490
+ try { return observed(await runAttempt(dir, { ...attemptOptions(node, state.retryOf), expectedId: state.attemptId! }, ctx)); }
491
+ catch (error) {
492
+ if (error instanceof GpuAdmissionDeferred) return { status: "failed", reason: `deferred:${error.result.reason}; ${error.result.message}; run ares plan control <dir> retry ${node.id} --command-id ID --expected-revision N` };
493
+ throw error;
494
+ }
495
+ }
328
496
  let result: unknown, ok = true;
329
497
  switch (node.command) {
330
498
  case "watch.run": {
@@ -332,7 +500,7 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
332
500
  return result.ok ? { status: "done", output: { added: result.added } } : { status: "failed", reason: "watch: every source failed; inspect ares watch show and retry the plan node" };
333
501
  }
334
502
  case "lit.search": {
335
- const value = await search(dir, stepText(node, "query"), { ...(node.args.source !== undefined ? { source: stepText(node, "source") } : {}), ...(stepNumber(node, "limit") !== undefined ? { limit: stepNumber(node, "limit")! } : {}), ...(stepNumber(node, "year-from") !== undefined ? { yearFrom: stepNumber(node, "year-from")! } : {}) }, ctx);
503
+ const value = await search(dir, stepText(node, "query"), { ...(node.args.source !== undefined ? { source: stepText(node, "source") } : {}), ...(stepNumber(node, "limit") !== undefined ? { limit: stepNumber(node, "limit")! } : {}), ...(stepNumber(node, "year-from") !== undefined ? { yearFrom: stepNumber(node, "year-from")! } : {}), ...(node.args.intent !== undefined ? { intent: stepText(node, "intent") } : {}) }, ctx);
336
504
  ok = value.sources.some(s => s.ok); result = value; break;
337
505
  }
338
506
  case "lit.verify": result = await verify(dir, (node.args.ids as string[] | undefined) ?? [], ctx); break;
@@ -357,9 +525,11 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
357
525
  }
358
526
  return { status: ok ? "done" : "failed", ...(ok ? { output: { sha256: sha256(JSON.stringify(result)) } } : { reason: "step reported failure; inspect its command result and inputs before retry" }) };
359
527
  },
360
- reconcile: async (_node, state) => {
528
+ reconcile: async (node, state) => {
361
529
  if (!state.attemptId || !listAttempts(dir).attempts.some(a => a.id === state.attemptId)) return { status: "uncertain", reason: "expected attempt record missing; explicitly retry or skip this node" };
362
- const before = showAttempt(dir, state.attemptId);
530
+ const before = showAttempt(dir, state.attemptId), requested = attemptOptions(node, state.retryOf);
531
+ const recordedMode = before.v === 3 ? before.reuse!.mode : before.freshRequest?.reuse ?? "off", recordedForce = before.v === 3 ? before.reuse!.forceFresh : before.freshRequest?.forceFresh ?? false;
532
+ if ((requested.reuse ?? "off") !== recordedMode || (requested.forceFresh ?? false) !== recordedForce) return { status: "uncertain", reason: `attempt recorded reuse=${recordedMode}, forceFresh=${recordedForce}; inspect ares attempt show, then retry this plan node explicitly` };
363
533
  if (before.status === "running") await reconcileAttempts(dir, ctx);
364
534
  return observed(showAttempt(dir, state.attemptId));
365
535
  },
@@ -430,6 +600,10 @@ export async function finalClose(dirArg: string, ctx: Pick<Ctx, "actor">) {
430
600
  export const posthocShow = (dir: string) => showPosthoc(dir);
431
601
 
432
602
  export const paperCheck = (dir: string) => checkPaper(dir);
603
+ export async function paperPlanSet(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
604
+ const { dir } = openStudy(dirArg); return withLock(dir, () => setPaperPlan(dir, raw, ctx.actor));
605
+ }
606
+ export const paperPlanShow = (dir: string) => showPaperPlan(dir);
433
607
 
434
608
  export async function paperBuild(dirArg: string, ctx: Pick<Ctx, "actor">) {
435
609
  const { dir } = openStudy(dirArg); return withLock(dir, () => buildPaper(dir, ctx.actor));
@@ -442,12 +616,13 @@ export async function reviewResolve(dirArg: string, target: string, reason: stri
442
616
  const { dir } = openStudy(dirArg); return withLock(dir, () => resolveReview(dir, target, reason, ctx.actor));
443
617
  }
444
618
  export const reviewShow = (dir: string) => reviewReadiness(dir);
619
+ export const reviewChecklistShow = () => reviewChecklist();
445
620
 
446
621
  /** Preview is read-only; confirmed outward writes and receipts share the study lock. */
447
- export async function archive(dirArg: string, options: { confirm?: string }, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv = process.env, guard?: () => void): Promise<ArchivePreview | ArchiveResult> {
622
+ export async function archive(dirArg: string, options: { confirm?: string }, ctx: Pick<Ctx, "actor" | "runner" | "now">, env: NodeJS.ProcessEnv = process.env, guard?: () => void, sourceOptions?: SkillCheckOptions): Promise<ArchivePreview | ArchiveResult> {
448
623
  const { dir } = openStudy(dirArg);
449
624
  if (options.confirm === undefined) return previewArchive(dir);
450
- return withLock(dir, () => { guard?.(); return exportArchive(dir, options.confirm!, ctx.actor, ctx.runner, env); });
625
+ return withLock(dir, lock => {guard?.(); return exportArchive(dir, options.confirm!, ctx.actor, ctx.runner, env, {...(sourceOptions ?? ctx), env: sourceOptions?.env ?? env, lock});});
451
626
  }
452
627
 
453
628
  /** The study cwd binds amem's project; search and optional intent brief never write study files. */
@@ -461,12 +636,17 @@ export async function lessons(dirArg: string, options: LessonRankOptions & { for
461
636
  return { lessons: ranked, ...(brief === undefined ? {} : { brief }) };
462
637
  }
463
638
 
464
- export async function skillPropose(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
465
- const { dir } = openStudy(dirArg); return withLock(dir, () => proposeSkill(dir, raw, ctx.actor));
639
+ export const lessonPropose = (dir: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => proposeLesson(dir, raw, ctx.actor, {...ctx, env, lock}));
640
+ export const lessonList = (dir: string) => listLessonCandidates(dir);
641
+ export const lessonCheck = (dir: string, name: string, ctx: Pick<Ctx, "runner" | "now"> = {}, env: NodeJS.ProcessEnv = process.env) => checkLesson(dir, name, {...ctx, env});
642
+ export const lessonDecide = (dir: string, name: string, raw: unknown, ctx: Ctx, env: NodeJS.ProcessEnv = process.env) => withLock(dir, lock => decideLesson(dir, name, raw, ctx.actor, {...ctx, env, lock}));
643
+ export async function skillPropose(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor" | "runner" | "now">, env: NodeJS.ProcessEnv = process.env) {
644
+ const { dir } = openStudy(dirArg); return withLock(dir, lock => proposeSkill(dir, raw, ctx.actor, {...ctx, env, lock}));
466
645
  }
467
- export async function skillDecide(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, ctx: Pick<Ctx, "actor">, guard?: () => void) {
468
- const { dir } = openStudy(dirArg); return withLock(dir, () => { guard?.(); return decideSkill(dir, name, decision, reason, pr, ctx.actor); });
646
+ export async function skillDecide(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, ctx: Pick<Ctx, "actor" | "runner" | "now">, guard?: () => void, env: NodeJS.ProcessEnv = process.env) {
647
+ const { dir } = openStudy(dirArg); return withLock(dir, lock => { guard?.(); return decideSkill(dir, name, decision, reason, pr, ctx.actor, {...ctx, env, lock}); });
469
648
  }
649
+ export const skillCheck = (dir: string, name: string, ctx: Pick<Ctx, "runner" | "now"> = {}, env: NodeJS.ProcessEnv = process.env) => checkSkill(dir, name, {...ctx, env});
470
650
  export const skillList = (dir: string) => listSkills(dir);
471
651
 
472
652
  export const setup = (target: string, mode: SetupMode, env: NodeJS.ProcessEnv, options: { cwd?: string; root?: string } = {}) => runSetup(target, mode, { ...options, env });
@@ -495,19 +675,32 @@ export async function watchRun(dirArg: string, ctx: Ctx) {
495
675
  }
496
676
  export interface WatchStarted { started: true; configSha256: string }
497
677
  /** Acknowledge only validated admission; the finite pass keeps the same lock until its receipt is written. */
498
- export function watchRunDetached(dirArg: string, ctx: Ctx, track?: (completion: Promise<void>) => void): Promise<WatchStarted> {
678
+ export function watchRunDetached(dirArg: string, ctx: Ctx, track?: (completion: Promise<void>, terminate: () => void) => void): Promise<WatchStarted> {
499
679
  const { dir, study } = openStudy(dirArg);
500
680
  let accept!: (value: WatchStarted) => void, reject!: (cause: unknown) => void, started = false;
681
+ let terminate = () => {};
501
682
  const admission = new Promise<WatchStarted>((resolve, refuse) => { accept = resolve; reject = refuse; });
502
683
  const completion = withLock(dir, async () => {
503
684
  const snapshot = watchPreflight(dir, study);
685
+ let settled = false;
686
+ terminate = () => {
687
+ if (settled) return; settled = true;
688
+ recordWatchFailure(dir, snapshot, ctx.actor, "terminated");
689
+ console.error("ares watch: terminated; inspect ares watch show and lit list before retrying");
690
+ };
504
691
  started = true; accept({ started: true, configSha256: snapshot.sha256 });
505
- await watchRunLocked(dir, snapshot, ctx);
692
+ try { await watchRunLocked(dir, snapshot, ctx); settled = true; }
693
+ catch (cause) {
694
+ if (settled) return; settled = true;
695
+ const kind = watchFailureClass(cause);
696
+ recordWatchFailure(dir, snapshot, ctx.actor, kind);
697
+ console.error(`ares watch: background pass failed (${kind}); inspect ares watch show and lit list before retrying`);
698
+ }
506
699
  }).then(() => {}, cause => {
507
700
  if (!started) reject(cause);
508
- else console.error("ares watch: background pass failed; inspect ares watch show and lit list before retrying");
701
+ else console.error(`ares watch: failure receipt could not be written (${watchFailureClass(cause)}); restore study storage, inspect ares watch show and lit list, then retry`);
509
702
  });
510
- track?.(completion);
703
+ track?.(completion, () => terminate());
511
704
  return admission;
512
705
  }
513
706
  export const watchShow = (dir: string) => ({ ...showWatch(dir), newCandidates: list(dir, { status: "new", limit: 500 }) });
@@ -518,3 +711,11 @@ function consoleHome(env: NodeJS.ProcessEnv): string {
518
711
  export const consoleAdd = (dir: string, env: NodeJS.ProcessEnv) => addStudy(consoleHome(env), dir);
519
712
  export const consoleRemove = (dir: string, env: NodeJS.ProcessEnv) => removeStudy(consoleHome(env), dir);
520
713
  export const consoleList = (env: NodeJS.ProcessEnv) => readRegistry(consoleHome(env));
714
+
715
+ /** Local source-derived reads; comparison adds no verdict, winner or result authority. */
716
+ export function lineageShow(dir: string, options: ProvenanceOptions = {}): ProvenancePage {
717
+ return readProvenance(dir, options);
718
+ }
719
+ export function lineageCompare(dir: string, options: Parameters<typeof compareLineage>[1] = {}): LineageComparison {
720
+ return compareLineage(dir, options);
721
+ }
package/src/copilot.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { lstatSync, opendirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ACCEPT_ARTIFACTS, resolveAutonomy, type AcceptArtifact } from "./autonomy.ts";
4
+ import { canonical } from "./plan/state.ts";
5
+ import { gateState, openStudy, readBytesBounded, readLedger, readTextBounded, sha256 } from "./study.ts";
6
+
7
+ export const COPILOT_HYPOTHESES_BYTES = 2 * 1024 * 1024;
8
+ export const COPILOT_PAPER_BYTES = 64 * 1024 * 1024;
9
+ export const COPILOT_PAPER_FILES = 500, COPILOT_PAPER_DIRECTORIES = 1000, COPILOT_PAPER_DEPTH = 64;
10
+ export class CopilotAcceptError extends Error {}
11
+ class DraftReadError extends CopilotAcceptError {}
12
+ function refuse(artifact: AcceptArtifact, reason: string): never {
13
+ throw new DraftReadError(`copilot draft ${artifact}: ${reason}; restore the last valid bounded regular draft files and ledger, then run ares gate list and ares gate approve <dir> accept:${artifact} before retrying`);
14
+ }
15
+ function draftLedger(dir: string, artifact: AcceptArtifact) {
16
+ try { return readLedger(dir); }
17
+ catch (error) {
18
+ if (error instanceof Error && /^ledger\.jsonl line [0-9]+: unsupported schema version/.test(error.message)) throw new DraftReadError(`copilot draft ${artifact}: unsupported ledger version; keep its bytes unchanged and use a compatible ares version before ares gate approve <dir> accept:${artifact}`);
19
+ refuse(artifact, "acceptance ledger is unreadable, malformed or over-bound");
20
+ }
21
+ }
22
+ function metadata(file: string) {
23
+ try { return lstatSync(file); }
24
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
25
+ }
26
+ function paperTree(dir: string): [string, string][] {
27
+ const root = join(dir, "paper"), entries: [string, string][] = [];
28
+ const rootStat = metadata(root);
29
+ if (rootStat === undefined) return entries;
30
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) refuse("paper", "paper source root must be a directory without symbolic links");
31
+ const derived = metadata(join(root, "build"));
32
+ let bytes = 0, directories = 0;
33
+ function walk(relative: string, depth: number): void {
34
+ // paper/build is derived output; manuscript sources include all other notes and assets.
35
+ if (relative === "build") return;
36
+ const file = relative ? join(root, relative) : root, stat = lstatSync(file);
37
+ // Respect the filesystem's case aliases without excluding a distinct source directory on case-sensitive hosts.
38
+ if (depth === 1 && relative.toLowerCase() === "build" && derived && derived.dev === stat.dev && derived.ino === stat.ino) return;
39
+ if (stat.isSymbolicLink()) refuse("paper", "symbolic links refused");
40
+ if (stat.isDirectory()) {
41
+ if (depth > COPILOT_PAPER_DEPTH || ++directories > COPILOT_PAPER_DIRECTORIES) refuse("paper", `source tree exceeds ${COPILOT_PAPER_DIRECTORIES} directories or ${COPILOT_PAPER_DEPTH} levels`);
42
+ const directory = opendirSync(file);
43
+ try { for (let entry = directory.readSync(); entry; entry = directory.readSync()) walk(relative ? `${relative}/${entry.name}` : entry.name, depth + 1); }
44
+ finally { directory.closeSync(); }
45
+ } else {
46
+ if (!relative || !stat.isFile()) refuse("paper", "regular files within the paper directory required");
47
+ if (entries.length >= COPILOT_PAPER_FILES) refuse("paper", `file count exceeds ${COPILOT_PAPER_FILES}`);
48
+ if (stat.size > COPILOT_PAPER_BYTES - bytes) refuse("paper", `aggregate bytes exceed ${COPILOT_PAPER_BYTES}`);
49
+ const content = readBytesBounded(file, COPILOT_PAPER_BYTES - bytes, { noFollow: true });
50
+ bytes += content.byteLength; entries.push([relative, sha256(content)]);
51
+ }
52
+ }
53
+ walk("", 0);
54
+ return entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
55
+ }
56
+
57
+ /** Only active, present drafts have accept bindings. Irrelevant and acceptance events are excluded. */
58
+ export function copilotBinding(dirArg: string, artifact: AcceptArtifact): string | undefined {
59
+ if (!ACCEPT_ARTIFACTS.includes(artifact)) throw new Error("copilot draft: unknown artifact; select hypotheses, paper or reviews and retry ares gate list");
60
+ const { dir, study } = openStudy(dirArg);
61
+ if (resolveAutonomy(study.autonomy, `accept:${artifact}`) !== "copilot") return undefined;
62
+ try {
63
+ if (artifact === "paper") {
64
+ const files = paperTree(dir);
65
+ return files.length ? sha256(canonical(files)) : undefined;
66
+ }
67
+ const events = draftLedger(dir, artifact).filter(event => artifact === "hypotheses" ? event.type === "idea.added" || event.type === "idea.decided" : event.type === "review.added" || event.type === "review.resolved");
68
+ if (artifact === "reviews") return events.length ? sha256(canonical(events)) : undefined;
69
+ const file = join(dir, "hypotheses.md"), stat = metadata(file);
70
+ let hypotheses: string | undefined;
71
+ if (stat !== undefined) {
72
+ if (stat.isSymbolicLink() || !stat.isFile()) refuse(artifact, "regular hypotheses file required; symbolic links refused");
73
+ if (stat.size > COPILOT_HYPOTHESES_BYTES) refuse(artifact, `hypotheses source exceeds ${COPILOT_HYPOTHESES_BYTES} bytes`);
74
+ hypotheses = readTextBounded(file, COPILOT_HYPOTHESES_BYTES, { noFollow: true });
75
+ }
76
+ return hypotheses !== undefined || events.length ? sha256(canonical([hypotheses === undefined ? null : sha256(hypotheses), events])) : undefined;
77
+ } catch (error) {
78
+ if (error instanceof DraftReadError) throw error;
79
+ refuse(artifact, "artifact or ledger is unreadable, non-regular, invalid UTF-8 or over-bound");
80
+ }
81
+ }
82
+
83
+ /** Acceptance records the existing gate actor; neither agents nor people receive an implicit approval. */
84
+ export function requireCopilotAccept(dir: string, artifact: AcceptArtifact): void {
85
+ const binding = copilotBinding(dir, artifact);
86
+ if (binding === undefined) return;
87
+ const events = draftLedger(dir, artifact);
88
+ const gate = `accept:${artifact}` as const, state = gateState(gate, events, () => binding);
89
+ if (state.state === "approved") return;
90
+ throw new CopilotAcceptError(`copilot draft ${artifact}: ${state.state} acceptance; run ares gate approve <dir> ${gate} for the current draft before retrying`);
91
+ }