@staix/agent-research 0.2.1 → 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 (72) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +255 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +192 -32
  7. package/src/exp/attempts.ts +500 -65
  8. package/src/exp/executor.ts +235 -12
  9. package/src/exp/final.ts +1 -1
  10. package/src/exp/logs.ts +25 -12
  11. package/src/exp/metrics.ts +6 -5
  12. package/src/exp/pipeline.ts +92 -0
  13. package/src/exp/protocol.ts +85 -18
  14. package/src/exp/retention-script.ts +649 -0
  15. package/src/exp/retention.ts +70 -0
  16. package/src/exp/reuse-admission.ts +63 -0
  17. package/src/exp/reuse-contract.ts +48 -0
  18. package/src/exp/reuse-runtime.ts +87 -0
  19. package/src/exp/reuse.ts +87 -0
  20. package/src/exp/selection.ts +1 -1
  21. package/src/exp/snapshot.ts +3 -3
  22. package/src/exp/stages.ts +117 -0
  23. package/src/harness/experience-source.ts +34 -0
  24. package/src/harness/experience.ts +206 -0
  25. package/src/harness/hub-guidance.ts +140 -0
  26. package/src/harness/hub-reference.ts +18 -0
  27. package/src/harness/lesson-candidates.ts +162 -0
  28. package/src/harness/limits.ts +2 -0
  29. package/src/harness/privacy.ts +4 -0
  30. package/src/harness/receipts.ts +84 -0
  31. package/src/harness/rounds.ts +198 -0
  32. package/src/harness/transitions.ts +152 -0
  33. package/src/lit/candidates.ts +13 -5
  34. package/src/lit/cards.ts +55 -4
  35. package/src/lit/flow.ts +82 -0
  36. package/src/lit/queries.ts +62 -0
  37. package/src/manifest.ts +13 -6
  38. package/src/mcp-tools.ts +123 -25
  39. package/src/mcp.ts +4 -0
  40. package/src/memory/amem-show.ts +135 -0
  41. package/src/memory/amem.ts +3 -0
  42. package/src/memory/archive.ts +17 -8
  43. package/src/memory/evidence-local.ts +77 -0
  44. package/src/memory/evidence.ts +39 -0
  45. package/src/memory/lessons.ts +4 -2
  46. package/src/memory/skill-check.ts +56 -0
  47. package/src/memory/skill-format.ts +77 -0
  48. package/src/memory/skills.ts +72 -26
  49. package/src/memory/source-budget.ts +11 -0
  50. package/src/memory/vault-cards.ts +226 -0
  51. package/src/paper/build.ts +16 -7
  52. package/src/paper/check.ts +37 -10
  53. package/src/paper/headings.ts +39 -0
  54. package/src/paper/hygiene.ts +153 -0
  55. package/src/paper/placeholders.ts +16 -1
  56. package/src/paper/plan.ts +170 -0
  57. package/src/paper/point-evidence.ts +63 -0
  58. package/src/paper/points.ts +83 -0
  59. package/src/paper/review.ts +102 -9
  60. package/src/paper/scopes.ts +51 -0
  61. package/src/plan/definition.ts +5 -1
  62. package/src/plan/hub.ts +6 -0
  63. package/src/plan/state.ts +5 -0
  64. package/src/playbook.ts +35 -20
  65. package/src/privacy.ts +9 -0
  66. package/src/provenance.ts +679 -0
  67. package/src/scope.ts +24 -3
  68. package/src/study-export.ts +55 -27
  69. package/src/study.ts +54 -14
  70. package/src/ui/panel.css +4 -0
  71. package/src/ui/panel.js +263 -6
  72. package/src/ui/plugin.ts +68 -10
package/src/commands.ts CHANGED
@@ -1,16 +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";
1
6
  import { validateAutonomyMode, validatePhase, PHASES, ACCEPT_ARTIFACTS, resolveAutonomy, type AcceptArtifact, type Autonomy } from "./autonomy.ts";
2
7
  import { copilotBinding, requireCopilotAccept } from "./copilot.ts";
3
8
  import { homedir } from "node:os";
4
9
  import { addStudy, removeStudy, readRegistry } from "./console/registry.ts";
5
10
  import { readWatchSnapshot, setWatch, runWatch, showWatch, recordWatchFailure, watchFailureClass, type WatchSnapshot } from "./lit/watch.ts";
6
11
  import { runSetup, type SetupMode } from "./setup.ts";
7
- import { proposeSkill, decideSkill, listSkills } from "./memory/skills.ts";
12
+ import { proposeSkill, decideSkill, listSkills, checkSkill } from "./memory/skills.ts";
8
13
  import { rankLessons, type LessonRankOptions } from "./memory/lessons.ts";
9
14
  import { createAmemClient } from "./memory/amem.ts";
10
15
  import { previewArchive, exportArchive, type ArchivePreview, type ArchiveResult } from "./memory/archive.ts";
11
- import { addReview, resolveReview, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
16
+ import { addReview, resolveReview, reviewChecklist, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
12
17
  import { buildPaper } from "./paper/build.ts";
13
18
  import { checkPaper } from "./paper/check.ts";
19
+ import { setPaperPlan, showPaperPlan } from "./paper/plan.ts";
14
20
  import { addAblation, showAblate, closeAblate } from "./exp/ablate.ts";
15
21
  import { setFinalSeeds, finalGateBinding, requireFinalInputs, closeFinal, showPosthoc } from "./exp/final.ts";
16
22
  import { addIdea, decideIdea } from "./exp/ideas.ts";
@@ -19,7 +25,7 @@ import { setSelection } from "./exp/selection.ts";
19
25
  import { createHubClient } from "./plan/hub.ts";
20
26
  import { runPlan, type ControllerRuntime, type Observation, type StepNode } from "./plan/controller.ts";
21
27
  import { resolveSnapshot } from "./exp/snapshot.ts";
22
- import { spawnRunner } from "./exp/executor.ts";
28
+ import { GpuAdmissionDeferred, spawnRunner } from "./exp/executor.ts";
23
29
  import { foldPlan, readPlanState, planGateBinding, prepareControl, type ControlRequest, type ControlResult } from "./plan/state.ts";
24
30
  import { setPlan } from "./plan/definition.ts";
25
31
  export { manifest } from "./manifest.ts";
@@ -28,28 +34,38 @@ import { existsSync, readdirSync, utimesSync } from "node:fs";
28
34
  import { join, resolve } from "node:path";
29
35
  import type { Http } from "./http.ts";
30
36
  import { readScope, scopeHash, setScope } from "./scope.ts";
31
- import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } 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";
32
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";
33
41
  import { searchSource, SOURCES, type SourceName } from "./lit/sources.ts";
34
42
  import { verifyCandidates } from "./lit/verify.ts";
35
43
  import { assignCitekeys, renderBib } from "./lit/bibtex.ts";
36
44
  import { checkCitations } from "./lit/cite.ts";
37
45
  import { cardPath, validateCard } from "./lit/cards.ts";
46
+ import { createVaultClient, exportCards, importCards, listCards, previewCardExport } from "./memory/vault-cards.ts";
38
47
  import { designBinding, protocolHash, readDesign, setProtocol } from "./exp/protocol.ts";
39
48
  import { requireExperiment } from "./study.ts";
40
- import { checkExecutor, setExecutor } from "./exp/executor.ts";
49
+ import { checkExecutor, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
41
50
  import { cancelAttempt, listAttempts, listAttemptSummaries, reconcileAttempts, runAttempt, showAttempt, type AttemptContext, type AttemptListOptions, type AttemptOptions } from "./exp/attempts.ts";
42
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";
43
54
 
44
55
  export type ExperimentRuntime = Omit<AttemptContext, "actor">;
45
56
  export interface Ctx extends ExperimentRuntime { actor: Actor; http: Http; signal?: AbortSignal }
46
57
  const MAX_IDS = 200, DRAFT_BYTES = 2 * 1024 * 1024, BIB_BYTES = 16 * 1024 * 1024, CARD_BYTES = 65_536;
47
58
 
48
- export function binder(dir: string): Binder {
49
- return gate => 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));
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));
50
66
  }
51
67
  function gateName(value: string): GateName {
52
- if (!GATES.includes(value as GateName) && !ACCEPT_ARTIFACTS.some(artifact => value === `accept:${artifact}`) && !value.startsWith("plan:")) throw new Error("unknown gate: unsupported name; run ares gate list <dir> and choose a listed gate before approval or rejection");
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");
53
69
  return value as GateName;
54
70
  }
55
71
  function ids(values: string[]): string[] {
@@ -97,10 +113,97 @@ export async function executorSet(dirArg: string, raw: unknown, ctx: Ctx) {
97
113
  const { dir } = openStudy(dirArg);
98
114
  return withLock(dir, () => setExecutor(dir, raw, ctx.actor));
99
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
+ }
100
123
  export const executorCheck = (dir: string, ctx: Ctx) => checkExecutor(dir, ctx.runner);
101
- 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
+ }
102
200
  export const attemptList = (dir: string, options: AttemptListOptions = {}) => listAttemptSummaries(dir, options);
103
- 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
+ };
104
207
  export const attemptCancel = (dir: string, id: string, reason: string | undefined, ctx: Ctx) => cancelAttempt(dir, id, reason, ctx);
105
208
  export const attemptReconcile = (dir: string, ctx: Ctx) => reconcileAttempts(dir, ctx);
106
209
  export const attemptLogs = (dir: string, id: string, options: LogOptions, ctx: Ctx) => readAttemptLogs(dir, id, options, ctx.runner);
@@ -135,16 +238,17 @@ export async function scope(dirArg: string, raw: unknown, ctx: Ctx) {
135
238
  }
136
239
 
137
240
  export function gateList(dirArg: string) {
138
- 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);
139
243
  const plan = foldPlan(events);
140
244
  const accepts = ACCEPT_ARTIFACTS.filter(artifact => resolveAutonomy(study.autonomy, `accept:${artifact}`) === "copilot").map(artifact => `accept:${artifact}` as GateName);
141
- 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) ?? [])];
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)];
142
246
  return gates.map(g => gateState(g, events, bind));
143
247
  }
144
248
 
145
249
  export async function gateDecide(dirArg: string, gate: string, decision: "approve" | "reject", reason: string | undefined, ctx: Ctx, guard?: () => void) {
146
250
  const { dir, study } = openStudy(dirArg), name = gateName(gate), why = reason === undefined ? undefined : boundedText(reason, "--reason", 500);
147
- if (name === "design" || name === "final") requireExperiment(study);
251
+ if (name === "design" || name === "final" || isHarnessGate(name)) requireExperiment(study);
148
252
  return withLock(dir, () => {
149
253
  guard?.();
150
254
  if (name === "final") requireFinalInputs(dir);
@@ -154,11 +258,12 @@ export async function gateDecide(dirArg: string, gate: string, decision: "approv
154
258
  });
155
259
  }
156
260
 
157
- 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) {
158
262
  const { dir } = openStudy(dirArg); return withLock(dir, () => searchLocked(dir, query, options, ctx));
159
263
  }
160
- 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) {
161
265
  const { dir, study } = openStudy(dirArg), q = boundedText(query, "query", 500);
266
+ const intent = options.intent === undefined ? undefined : validateIntent(options.intent);
162
267
  const source = options.source ?? "all";
163
268
  if (source !== "all" && !SOURCES.includes(source as SourceName)) throw new Error("--source: openalex, s2, arxiv or all");
164
269
  const limit = options.limit ?? 20;
@@ -172,15 +277,20 @@ async function searchLocked(dirArg: string, query: string, options: { source?: s
172
277
  const names = source === "all" ? SOURCES : [source as SourceName];
173
278
  const results = [];
174
279
  for (const name of names) results.push(await searchSource(ctx.http, name, q, { limit, ...(yearFrom !== undefined ? { yearFrom } : {}), ...(sc.yearTo !== undefined ? { yearTo: sc.yearTo } : {}) }));
175
- 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)));
176
281
  const sources = results.map(r => ({ source: r.source, ok: r.ok, returned: r.records.length, ...(r.error ? { error: r.error } : {}) }));
177
282
  // A search where every source failed is recorded but is not a success, so it approves nothing.
178
283
  const answered = sources.some(r => r.ok);
179
- commit(dir, [candidatesFile(dir, list)], [...(answered ? approval : []), { actor: ctx.actor, type: "lit.search", data: { query: q, sources, ...counts } }]);
180
- 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 };
181
287
 
182
288
  }
183
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); }
184
294
  export function list(dirArg: string, options: { status?: string; limit?: number }) {
185
295
  const { dir } = openStudy(dirArg), limit = options.limit ?? 50;
186
296
  if (options.status !== undefined && !["new", "included", "excluded"].includes(options.status)) throw new Error("--status: new, included or excluded");
@@ -197,10 +307,15 @@ export function list(dirArg: string, options: { status?: string; limit?: number
197
307
  };
198
308
  }
199
309
 
200
- 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) {
201
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");
202
313
  return withLock(dir, () => {
203
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
+ }
204
319
  const all = loadCandidates(dir), at = new Date().toISOString(), status = decision === "include" ? "included" : "excluded";
205
320
  for (const id of wanted) find(all, id);
206
321
  const approval = requireGate(dir, study, "scope", binder(dir));
@@ -208,8 +323,9 @@ export async function screen(dirArg: string, values: string[], decision: "includ
208
323
  const c = find(all, id);
209
324
  c.status = status; c.decidedBy = ctx.actor; c.decidedAt = at;
210
325
  if (why) c.reason = why; else delete c.reason;
326
+ if (code !== undefined) c.exclusionCode = code; else delete c.exclusionCode;
211
327
  }
212
- 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 } : {}) } }]);
213
329
  return { decision, ids: wanted, gate: gateState("screen", readLedger(dir), binder(dir)) };
214
330
  });
215
331
  }
@@ -226,6 +342,20 @@ export async function card(dirArg: string, id: string, raw: unknown, ctx: Ctx) {
226
342
  });
227
343
  }
228
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
+
229
359
  /**
230
360
  * Without ids: included candidates never checked, checked against other identifiers, or left unknown, up to 200.
231
361
  * Final results (no identifier, not found, title or year mismatch) are skipped so the batch always advances;
@@ -322,15 +452,19 @@ function stepNumber(node: StepNode, key: string): number | undefined {
322
452
  }
323
453
  export async function planRun(dirArg: string, options: { parallel?: number }, ctx: Ctx) {
324
454
  const { dir } = openStudy(dirArg);
325
- const attemptOptions = (node: StepNode, retryOf?: string) => {
455
+ const attemptOptions = (node: StepNode, retryOf?: string): AttemptOptions => {
326
456
  const parent = retryOf ?? (node.args.retry !== undefined ? stepText(node, "retry") : undefined);
327
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");
328
462
  return {
329
463
  repo: resolve(dir, stepText(node, "repo")), commit: stepText(node, "commit"),
330
464
  ...(stepNumber(node, "seed") !== undefined ? { seed: stepNumber(node, "seed")! } : {}),
331
465
  ...(node.args.run !== undefined ? { run: stepText(node, "run") } : {}),
332
466
  ...(node.args.label !== undefined ? { label: stepText(node, "label") } : {}),
333
- ...(retry ? { retry } : {}), detach: true,
467
+ ...(retry ? { retry } : {}), ...(reuse === undefined ? {} : { reuse }), ...(forceFresh === undefined ? {} : { forceFresh }), detach: true,
334
468
  };
335
469
  };
336
470
  const observed = (attempt: ReturnType<typeof showAttempt>): Observation => ({
@@ -352,7 +486,13 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
352
486
  return { attemptId: attemptId(protocolHash(design.protocol), snapshot.commit, snapshot.treeId, options.seed ?? design.protocol.seeds[0]!, options.run ?? "main", options.retry) };
353
487
  },
354
488
  execute: async (node, state) => {
355
- 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
+ }
356
496
  let result: unknown, ok = true;
357
497
  switch (node.command) {
358
498
  case "watch.run": {
@@ -360,7 +500,7 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
360
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" };
361
501
  }
362
502
  case "lit.search": {
363
- 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);
364
504
  ok = value.sources.some(s => s.ok); result = value; break;
365
505
  }
366
506
  case "lit.verify": result = await verify(dir, (node.args.ids as string[] | undefined) ?? [], ctx); break;
@@ -385,9 +525,11 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
385
525
  }
386
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" }) };
387
527
  },
388
- reconcile: async (_node, state) => {
528
+ reconcile: async (node, state) => {
389
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" };
390
- 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` };
391
533
  if (before.status === "running") await reconcileAttempts(dir, ctx);
392
534
  return observed(showAttempt(dir, state.attemptId));
393
535
  },
@@ -458,6 +600,10 @@ export async function finalClose(dirArg: string, ctx: Pick<Ctx, "actor">) {
458
600
  export const posthocShow = (dir: string) => showPosthoc(dir);
459
601
 
460
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);
461
607
 
462
608
  export async function paperBuild(dirArg: string, ctx: Pick<Ctx, "actor">) {
463
609
  const { dir } = openStudy(dirArg); return withLock(dir, () => buildPaper(dir, ctx.actor));
@@ -470,12 +616,13 @@ export async function reviewResolve(dirArg: string, target: string, reason: stri
470
616
  const { dir } = openStudy(dirArg); return withLock(dir, () => resolveReview(dir, target, reason, ctx.actor));
471
617
  }
472
618
  export const reviewShow = (dir: string) => reviewReadiness(dir);
619
+ export const reviewChecklistShow = () => reviewChecklist();
473
620
 
474
621
  /** Preview is read-only; confirmed outward writes and receipts share the study lock. */
475
- 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> {
476
623
  const { dir } = openStudy(dirArg);
477
624
  if (options.confirm === undefined) return previewArchive(dir);
478
- 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});});
479
626
  }
480
627
 
481
628
  /** The study cwd binds amem's project; search and optional intent brief never write study files. */
@@ -489,12 +636,17 @@ export async function lessons(dirArg: string, options: LessonRankOptions & { for
489
636
  return { lessons: ranked, ...(brief === undefined ? {} : { brief }) };
490
637
  }
491
638
 
492
- export async function skillPropose(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
493
- 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}));
494
645
  }
495
- export async function skillDecide(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, ctx: Pick<Ctx, "actor">, guard?: () => void) {
496
- 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}); });
497
648
  }
649
+ export const skillCheck = (dir: string, name: string, ctx: Pick<Ctx, "runner" | "now"> = {}, env: NodeJS.ProcessEnv = process.env) => checkSkill(dir, name, {...ctx, env});
498
650
  export const skillList = (dir: string) => listSkills(dir);
499
651
 
500
652
  export const setup = (target: string, mode: SetupMode, env: NodeJS.ProcessEnv, options: { cwd?: string; root?: string } = {}) => runSetup(target, mode, { ...options, env });
@@ -559,3 +711,11 @@ function consoleHome(env: NodeJS.ProcessEnv): string {
559
711
  export const consoleAdd = (dir: string, env: NodeJS.ProcessEnv) => addStudy(consoleHome(env), dir);
560
712
  export const consoleRemove = (dir: string, env: NodeJS.ProcessEnv) => removeStudy(consoleHome(env), dir);
561
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
+ }