@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
@@ -0,0 +1,679 @@
1
+ import { types } from "node:util";
2
+ import {parseHubExecutionReference, type HubExecutionReferenceV1} from "./harness/hub-reference.ts";
3
+ import { existsSync, lstatSync, opendirSync, realpathSync } from "node:fs";
4
+ import { isAbsolute, join, relative, resolve, sep, posix } from "node:path";
5
+ import { parseLedger, plain, readBytesBounded, hashFileBounded, sha256, validateStudy, type LedgerEvent, type Study, assertStudyReadLock, type StudyReadLock } from "./study.ts";
6
+ import { validateAttemptRecord, type Attempt } from "./exp/attempts.ts";
7
+ import { TASK_BYTES, TASK_FILES, METRIC_LIMIT, validateStoredProtocol, validateProtocolDefinition, protocolHash } from "./exp/protocol.ts";
8
+ import { validateExecutor } from "./exp/executor.ts";
9
+ import { foldIdeas } from "./exp/ideas.ts";
10
+ import { readClosedInvestigation, type CommitResult } from "./exp/investigate.ts";
11
+ import { readClosedFinal } from "./exp/final.ts";
12
+ import { readClosedAblate } from "./exp/ablate.ts";
13
+ import { validatePlan } from "./plan/definition.ts";
14
+ import { canonical, foldPlan } from "./plan/state.ts";
15
+ import { paperEvidenceVersion, readCurrentBuild } from "./paper/build.ts";
16
+ import { PAPER_PLAN_BYTES } from "./paper/plan.ts";
17
+ import { foldReviews } from "./paper/review.ts";
18
+ import {readHarnessViews} from "./harness/rounds.ts";
19
+ import { foldSkills } from "./memory/skills.ts";
20
+
21
+ export const PROVENANCE_NODE_LIMIT = 100, PROVENANCE_EDGE_LIMIT = 200, PROVENANCE_PAGE_BYTES = 256 * 1024;
22
+ export const PROVENANCE_SOURCE_FILES = 512, PROVENANCE_SOURCE_BYTES = 16 * 1024 * 1024, PROVENANCE_EVENTS = 5000, PROVENANCE_TRAVERSAL = 1000;
23
+ const KINDS = ["study", "plan-revision", "dispatch", "idea", "attempt", "artifact", "closed-result", "paper-evidence", "skill-proposal", "harness-closure"] as const;
24
+ export const PROVENANCE_KINDS = KINDS;
25
+ export type ProvenanceKind = typeof KINDS[number];
26
+ export interface ExecutionReferenceV1 { v: 1; tool: "ares"; projectKey: string; kind: ProvenanceKind; id: string; revision?: string; sha256?: string }
27
+ export type SupportedExecutionReferenceV1 = ExecutionReferenceV1 | HubExecutionReferenceV1;
28
+ export type ProvenanceState = "current" | "historical" | "corrupt" | "unavailable" | "declared-unresolved";
29
+ export interface ProvenanceProof { file: string; sha256: string; ledgerIndex?: number; recordSha256?: string; sourceBindingSha256?: string; recordType?: string; nativeId?: string }
30
+ export interface ProvenanceNode { ref: ExecutionReferenceV1; state: ProvenanceState; availability: "available" | "receipt-only" | "missing" | "not-read"; proof: ProvenanceProof; data?: Record<string, string | number | boolean | null> }
31
+ export type ProvenanceRelation = "contains" | "retryOf" | "parent" | "cites-attempt" | "produced" | "dispatched" | "observed-in" | "expected-attempt" | "observed-attempt" | "observed-output" | "closed" | "reviewed" | "uses-attempt" | "names-idea" | "uses-closed-result" | "uses-source" | "reused-from" | "reused-artifact";
32
+ export interface ProvenanceEdge { reuseSource?: {ref: {attemptId: string; stage: string; sha256: string}; retention: RetentionDisposalView}; from: ExecutionReferenceV1; to: ExecutionReferenceV1; relation: ProvenanceRelation; proof: ProvenanceProof }
33
+ export interface ProvenanceIssue { code: string; message: string; ref?: ExecutionReferenceV1 }
34
+ export interface ProvenancePage {
35
+ v: 1; status: "ok" | "changed" | "unavailable" | "capped"; sourceSha256: string | null; ledgerPosition: number | null;
36
+ nodes: ProvenanceNode[]; edges: ProvenanceEdge[]; issues: ProvenanceIssue[]; totals: { nodes: number; edges: number } | null; truncated: boolean; nextCursor?: string;
37
+ }
38
+ export interface ProvenanceOptions { root?: SupportedExecutionReferenceV1; cursor?: string; nodeLimit?: number; edgeLimit?: number; traversalLimit?: number }
39
+ const HASH = /^[a-f0-9]{64}$/, ATTEMPT = /^[a-f0-9]{16}$/, RUN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
40
+ class SourceFailure extends Error { constructor(readonly code: string, readonly capped = false) { super(code); } }
41
+ function fail(code: string, capped = false): never { throw new SourceFailure(code, capped); }
42
+ function text(value: unknown, bound: number): value is string { return typeof value === "string" && value.trim().length > 0 && !value.includes("\0") && Buffer.byteLength(value) <= bound; }
43
+ /** An address is never a path, URL, subprocess or hub resolver instruction. Native ids are preserved verbatim. */
44
+ export function validateExecutionReference<T extends {tool: "ares"}>(raw: T): ExecutionReferenceV1;
45
+ export function validateExecutionReference(raw: unknown): SupportedExecutionReferenceV1;
46
+ export function validateExecutionReference(raw: unknown): SupportedExecutionReferenceV1 {
47
+ if (raw && typeof raw === "object" && !types.isProxy(raw) && [Object.prototype, null].includes(Object.getPrototypeOf(raw)) && !Object.getOwnPropertySymbols(raw).length) {
48
+ const fields = Object.getOwnPropertyDescriptors(raw);
49
+ if (Object.values(fields).some(field => !("value" in field))) throw new Error("provenance reference: accessor fields are unsupported; supply a plain execution address before retrying");
50
+ if (fields.tool?.value === "ahub") return parseHubExecutionReference(raw);
51
+ } else throw new Error("provenance reference: unsupported object shape; supply a plain execution address before retrying");
52
+ if (!plain(raw) || Object.keys(raw).some(key => !["v", "tool", "projectKey", "kind", "id", "revision", "sha256"].includes(key)) || raw.v !== 1 || raw.tool !== "ares" || !KINDS.includes(raw.kind as ProvenanceKind) || !text(raw.projectKey, 256) || !text(raw.id, 256) || raw.revision !== undefined && !text(raw.revision, 128) || raw.sha256 !== undefined && (typeof raw.sha256 !== "string" || !HASH.test(raw.sha256))) throw new Error("provenance reference: unsupported shape or identifier bound; use an ares ExecutionReferenceV1 with native ids <=256 bytes, revision <=128 bytes and a lowercase 64-hex sha256");
53
+ return { v: 1, tool: "ares", projectKey: raw.projectKey, kind: raw.kind as ProvenanceKind, id: raw.id, ...(raw.revision !== undefined ? { revision: raw.revision as string } : {}), ...(raw.sha256 !== undefined ? { sha256: raw.sha256 as string } : {}) };
54
+ }
55
+ interface SourceFile { bytes: Buffer; sha256: string }
56
+ interface Snapshot { files: Map<string, SourceFile>; study: Study; events: LedgerEvent[]; hash: string; ledgerPosition: number }
57
+ function decode(bytes: Uint8Array): string { try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { return fail("malformed-source"); } }
58
+ function parsed(file: SourceFile): unknown { try { return JSON.parse(decode(file.bytes)); } catch (error) { if (error instanceof SourceFailure) throw error; return fail("malformed-source"); } }
59
+ function capture(dir: string, permit?: StudyReadLock): Snapshot {
60
+ if (permit) assertStudyReadLock(dir, permit);
61
+ else if (existsSync(join(dir, ".ares.lock"))) fail("write-in-progress");
62
+ const files = new Map<string, SourceFile>(), directories: string[] = []; let total = 0, entries = 0;
63
+ const forbidden: string[] = [];
64
+ const safe = (name: string) => { if (forbidden.some(prefix => !prefix || name === prefix || name.startsWith(prefix + "/"))) fail("executor-overlaps-source"); };
65
+ const exclude = (name: string, file: SourceFile) => {
66
+ if (name !== "executor.json" && !/\/attempts\//.test(name)) return;
67
+ const raw = parsed(file); if (!plain(raw)) return;
68
+ if (name === "executor.json" && raw.v !== 1) fail("unsupported-version");
69
+ if (name !== "executor.json" && (Object.hasOwn(raw, "executor") && !plain(raw.executor) || Object.hasOwn(raw, "paths") && !plain(raw.paths))) fail("malformed-execution-path");
70
+ const executor = name === "executor.json" ? raw : plain(raw.executor) ? raw.executor : {}, paths = name !== "executor.json" && plain(raw.paths) ? raw.paths : {};
71
+ const evidencePaths: unknown[] = [];
72
+ const outputPaths = (rows: unknown) => { if (Array.isArray(rows)) for (const row of rows) if (plain(row) && Object.hasOwn(row, "path")) evidencePaths.push(row.path); };
73
+ outputPaths(raw.outputs);
74
+ if (plain(raw.stages)) for (const stage of Object.values(raw.stages)) if (plain(stage) && plain(stage.evidence)) {
75
+ outputPaths(stage.evidence.outputs);
76
+ if (plain(stage.evidence.logs)) for (const log of Object.values(stage.evidence.logs)) if (plain(log) && Object.hasOwn(log, "path")) evidencePaths.push(log.path);
77
+ }
78
+ if (plain(raw.pipeline) && Array.isArray(raw.pipeline.completed)) for (const parent of raw.pipeline.completed) if (plain(parent) && plain(parent.record) && plain(parent.record.evidence)) {
79
+ outputPaths(parent.record.evidence.outputs);
80
+ if (plain(parent.record.evidence.logs)) for (const log of Object.values(parent.record.evidence.logs)) if (plain(log) && Object.hasOwn(log, "path")) evidencePaths.push(log.path);
81
+ }
82
+ // Validate host paths, including evaluator inputs; container mount targets/argv are not host locations.
83
+ for (const location of [...(Object.hasOwn(executor, "workdir") ? [executor.workdir] : []), ...Object.values(paths), ...evidencePaths]) if (typeof location !== "string" || !isAbsolute(location) || location.includes("\0")) fail("malformed-execution-path");
84
+ if (name === "executor.json") { try { validateExecutor(raw); } catch { fail("malformed-executor"); } }
85
+ for (const location of [executor.workdir, paths.snapshot, paths.output, paths.result, ...evidencePaths]) if (typeof location === "string") {
86
+ let address = resolve(location); try { address = realpathSync(address); } catch { /* An absent output location has no readable tree. */ }
87
+ const inside = relative(dir, address); if (inside === "" || inside !== ".." && !inside.startsWith(".." + sep)) forbidden.push(inside.split(sep).join("/"));
88
+ }
89
+ // Reject overlapping metadata too, including locations learned from a later record.
90
+ for (const captured of files.keys()) safe(captured);
91
+ };
92
+ const get = (name: string, bound: number): SourceFile | undefined => {
93
+ safe(name);
94
+ const parts = name.split("/"); let absolute = dir;
95
+ for (const [index, part] of parts.entries()) {
96
+ absolute = join(absolute, part); let stat;
97
+ try { stat = lstatSync(absolute); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; return fail("unreadable-source"); }
98
+ if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory()) || (index === parts.length - 1 && !stat.isFile())) fail("non-regular-source");
99
+ if (index === parts.length - 1 && (stat.size > bound || stat.size > PROVENANCE_SOURCE_BYTES - total || files.size >= PROVENANCE_SOURCE_FILES)) fail("source-traversal-capped", true);
100
+ }
101
+ let bytes: Buffer; try { bytes = readBytesBounded(absolute, Math.min(bound, PROVENANCE_SOURCE_BYTES - total), { noFollow: true }); } catch { return fail("unreadable-source"); }
102
+ total += bytes.length; const file = { bytes, sha256: sha256(bytes) }; files.set(name, file); exclude(name, file); return file;
103
+ };
104
+ const names = (name: string): string[] => {
105
+ safe(name);
106
+ let stat; try { stat = lstatSync(join(dir, name)); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; return fail("unreadable-source"); }
107
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail("non-regular-source");
108
+ directories.push(name); const directory = opendirSync(join(dir, name)), result: string[] = [];
109
+ try { for (let entry = directory.readSync(); entry; entry = directory.readSync()) { if (++entries > PROVENANCE_SOURCE_FILES * 4) fail("source-traversal-capped", true); result.push(entry.name); } }
110
+ finally { directory.closeSync(); }
111
+ return result.sort();
112
+ };
113
+ // Learn output exclusions from native metadata before opening any other source content.
114
+ get("executor.json", 65_536);
115
+ const runs = names("runs");
116
+ for (const run of runs) {
117
+ if (!RUN.test(run)) fail("malformed-attempt-store");
118
+ for (const entry of names(`runs/${run}/attempts`)) { if (!/^[a-f0-9]{16}\.json$/.test(entry)) fail("malformed-attempt-store"); get(`runs/${run}/attempts/${entry}`, 1_048_576); }
119
+ }
120
+ const studyFile = get("study.json", 65_536); if (!studyFile) fail("missing-study");
121
+ let study: Study; try { study = validateStudy(parsed(studyFile)); } catch (error) { if (error instanceof Error && error.message.includes("unsupported")) return fail("unsupported-version"); return fail("malformed-study"); }
122
+ const ledger = get("ledger.jsonl", 64 * 1024 * 1024); if (!ledger) fail("missing-ledger");
123
+ let events: LedgerEvent[]; try { events = parseLedger(decode(ledger.bytes)); } catch (error) { if (error instanceof Error && error.message.includes("unsupported")) return fail("unsupported-ledger"); return fail("malformed-ledger"); }
124
+ if (events.length > PROVENANCE_EVENTS || events.filter(event => event.type === "plan.set").length > 64) fail("ledger-traversal-capped", true);
125
+ for (const name of ["plan.json", "hypotheses.md", "design/protocol.json", "design/selection.json", "design/final.json", "literature/candidates.json"]) get(name, name === "hypotheses.md" ? 2 * 1024 * 1024 : name.startsWith("literature/") ? 8 * 1024 * 1024 : 65_536);
126
+ for (const name of ["plan.json", "design/protocol.json", "design/selection.json", "design/final.json"]) {
127
+ const file = files.get(name); if (file) { const raw = parsed(file); if (!plain(raw)) fail("malformed-source"); if (raw.v !== 1 && !(name === "design/protocol.json" && raw.v === 2)) fail("unsupported-version"); }
128
+ }
129
+ for (const [name, bound] of [["design/harness.json", 1_048_576], ["design/harness-stream.json", 16_384], ["design/harness-experience.json", 1_048_576], ["proposals/lessons.json", 1_048_576]] as const) {
130
+ const file = get(name, bound); if (file) {const raw = parsed(file); if (!plain(raw)) fail("malformed-source"); if (raw.v !== 1) fail("unsupported-version");}
131
+ }
132
+ for (const run of runs) for (const name of ["investigate.json", ...(run === "ablate" ? ["ablate.json"] : []), ...(run === "final" ? ["final.json"] : [])]) get(`runs/${run}/${name}`, 1_048_576);
133
+ const taskHashes: [string, string][] = []; let taskBytes = 0, taskDirectories = 0;
134
+ const task = (name: string, depth: number) => {
135
+ safe(name); if (depth > 64 || ++taskDirectories > 1000) fail("task-traversal-capped", true);
136
+ const stat = lstatSync(join(dir, name)); if (stat.isSymbolicLink() || !stat.isDirectory()) fail("non-regular-source");
137
+ directories.push(name); const directory = opendirSync(join(dir, name));
138
+ try {
139
+ for (let entry = directory.readSync(); entry; entry = directory.readSync()) {
140
+ const child = `${name}/${entry.name}`; safe(child); const stat = lstatSync(join(dir, child));
141
+ if (stat.isSymbolicLink()) fail("non-regular-source");
142
+ if (stat.isDirectory()) task(child, depth + 1);
143
+ else {
144
+ if (!stat.isFile()) fail("non-regular-source");
145
+ if (taskHashes.length >= TASK_FILES || stat.size > TASK_BYTES - taskBytes) fail("task-traversal-capped", true);
146
+ let result; try { result = hashFileBounded(join(dir, child), TASK_BYTES - taskBytes, { noFollow: true }); } catch { return fail("unreadable-source"); }
147
+ taskBytes += result.bytes; taskHashes.push([child, result.sha256]);
148
+ }
149
+ }
150
+ } finally { directory.closeSync(); }
151
+ };
152
+ if (existsSync(join(dir, "task"))) task("task", 0);
153
+ get("paper/plan.json", PAPER_PLAN_BYTES);
154
+ for (const name of ["paper/manuscript.md", "paper/build/manuscript.md", "paper/build/evidence.json"]) { safe(name); get(name, name.endsWith("evidence.json") ? 8 * 1024 * 1024 : 2 * 1024 * 1024); }
155
+ for (const event of events) if (event.type === "skill.proposed" && plain(event.data.proposal) && typeof event.data.proposal.name === "string" && RUN.test(event.data.proposal.name)) get(`proposals/skills/${event.data.proposal.name}.md`, 16_384);
156
+ if (permit) assertStudyReadLock(dir, permit);
157
+ else if (existsSync(join(dir, ".ares.lock"))) fail("write-in-progress");
158
+ return { files, study, events, ledgerPosition: ledger.bytes.length, hash: sha256(canonical({ directories: directories.sort(), files: [...taskHashes, ...[...files].map(([name, file]) => [name, file.sha256])].sort(([a], [b]) => (String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0)) })) };
159
+ }
160
+ class TraversalCap extends Error {}
161
+ const key = (ref: ExecutionReferenceV1) => canonical(ref);
162
+ class Graph {
163
+ nodes = new Map<string, ProvenanceNode>(); edges = new Map<string, ProvenanceEdge>(); issues: ProvenanceIssue[] = []; capped = false; work = 0;
164
+ constructor(readonly source: Snapshot, readonly limit: number) {}
165
+ touch() { if (++this.work > this.limit * 16) throw new TraversalCap(); }
166
+ ref(kind: ProvenanceKind, id: string, extra: { revision?: string; sha256?: string } = {}) { this.touch(); return validateExecutionReference({ v: 1, tool: "ares", projectKey: this.source.study.id, kind, id, ...extra }); }
167
+ proof(file: string, index?: number, nativeId?: string): ProvenanceProof { const source = this.source.files.get(file); if (!source) fail("missing-source-proof"); return { file, sha256: source.sha256, ...(index !== undefined ? { ledgerIndex: index, recordSha256: sha256(canonical(this.source.events[index]!)), recordType: this.source.events[index]!.type } : {}), ...(nativeId !== undefined ? { nativeId } : {}) }; }
168
+ issue(code: string, ref?: ExecutionReferenceV1) {
169
+ const next = code.startsWith("unsupported") ? "use a compatible ares version, keeping all original bytes unchanged, then retry" : code === "historical-not-current" ? "inspect the historical receipt; use its existing close/build producer only if a current artifact is needed, then retry" : "restore the corresponding valid original record, then retry the read";
170
+ if (this.issues.length < 64) this.issues.push({ code, message: `provenance ${code}; ${next}`, ...(ref ? { ref } : {}) });
171
+ }
172
+ put(node: ProvenanceNode) { const id = key(node.ref); if (!this.nodes.has(id)) { if (this.nodes.size >= this.limit) throw new TraversalCap(); } this.nodes.set(id, node); return node.ref; }
173
+ edge(from: ExecutionReferenceV1, to: ExecutionReferenceV1, relation: ProvenanceRelation, proof: ProvenanceProof, reuseSource?: ProvenanceEdge["reuseSource"]) { this.touch(); if (this.edges.size >= this.limit * 4) throw new TraversalCap(); const edge = { from, to, relation, proof, ...(reuseSource === undefined ? {} : {reuseSource}) }; this.edges.set(canonical(edge), edge); }
174
+ target(kind: ProvenanceKind, id: string, proof: ProvenanceProof, extra: { revision?: string; sha256?: string } = {}) {
175
+ const ref = this.ref(kind, id, extra); if (!this.nodes.has(key(ref))) { this.put({ ref, state: "unavailable", availability: "missing", proof }); this.issue("missing-referenced-record", ref); } return ref;
176
+ }
177
+ }
178
+ function fileJson(source: Snapshot, file: string): Record<string, unknown> | undefined { const value = source.files.get(file); if (!value) return undefined; const raw = parsed(value); if (!plain(raw)) fail("malformed-source"); return raw; }
179
+ /** Attribute each inventory row from its recorded stage/path relationship, never from a shared hash alone. */
180
+ function attemptOutputAttributions(value: Attempt, file: string, graph: Graph, reuseReceipts: Map<string, number>, ledger: string, disposals: RetentionDisposalIndex) {
181
+ const proof = graph.proof(file), result = new Map<string, {relation: "produced" | "reused-artifact"; proof: ProvenanceProof; reuseSource?: ProvenanceEdge["reuseSource"]}>();
182
+ const outputKey = (output: {path: string; sha256: string; bytes: number}) => canonical([output.path, output.sha256, output.bytes]);
183
+ if (!value.pipeline) { for (const output of value.outputs) result.set(outputKey(output), {relation: "produced", proof}); return result; }
184
+ const root = posix.join(value.executor.workdir, value.studyId, value.id);
185
+ const under = (path: string, base: string): string | undefined => {
186
+ const local = posix.relative(base, path);
187
+ return local && local !== ".." && !local.startsWith("../") && !posix.isAbsolute(local) && posix.join(base, local) === path ? local : undefined;
188
+ };
189
+ const fresh = (record: Attempt["stages"]["candidate"], outputRoot: string) => {
190
+ if (!record?.containerId || !HASH.test(record.containerId)) return;
191
+ for (const output of record.evidence?.outputs ?? []) { graph.touch(); if (under(output.path, outputRoot)) result.set(outputKey(output), {relation: "produced", proof}); }
192
+ };
193
+ for (const parent of value.pipeline.completed) {
194
+ const receipt = parent.reuse;
195
+ if (!receipt) { fresh(parent.record, posix.join(root, "stages", parent.name, "output")); continue; }
196
+ const index = reuseReceipts.get(canonical([value.id, parent.name, receipt.key, receipt.source.attemptId, receipt.source.stage, receipt.source.sha256]));
197
+ if (index === undefined) { graph.issue("missing-stage-reuse-receipt", graph.ref("attempt", value.id)); continue; }
198
+ const reuseProof = graph.proof(ledger, index), source = graph.target("attempt", receipt.source.attemptId, reuseProof);
199
+ const reuseSource = {ref: {...receipt.source}, retention: retentionDisposalView(receipt.source, disposals)};
200
+ graph.edge(graph.ref("attempt", value.id), source, "reused-from", reuseProof, reuseSource);
201
+ const definition = value.pipeline.definition.candidate.stages.find(stage => stage.name === parent.name);
202
+ if (!definition) continue;
203
+ const originalRoot = posix.join(value.executor.workdir, value.studyId, receipt.source.attemptId, "stages", receipt.source.stage, "output");
204
+ const retainedRoot = posix.join(value.executor.workdir, value.studyId, ".retained", "objects", receipt.source.attemptId, receipt.source.stage, "data");
205
+ for (const original of parent.record.evidence?.outputs ?? []) {
206
+ graph.touch(); const local = under(original.path, originalRoot);
207
+ if (!local || !Object.values(definition.outputs).some(declared => local === declared || local.startsWith(`${declared}/`))) continue;
208
+ result.set(outputKey({...original, path: posix.join(retainedRoot, local)}), {relation: "reused-artifact", proof: reuseProof, reuseSource});
209
+ }
210
+ }
211
+ if (value.stage === "candidate") fresh(value.stages.candidate, posix.join(root, "stages", value.pipeline.definition.candidate.stages[value.pipeline.index]!.name, "output"));
212
+ const evaluator = value.stages.evaluator, resultRoot = posix.join(root, "result");
213
+ if (evaluator?.containerId && HASH.test(evaluator.containerId) && value.paths.result === resultRoot) for (const output of value.outputs) {
214
+ graph.touch(); if (under(output.path, resultRoot)) result.set(outputKey(output), {relation: "produced", proof});
215
+ }
216
+ return result;
217
+ }
218
+ function build(dir: string, source: Snapshot, limit: number): Graph {
219
+ const graph = new Graph(source, limit), study = graph.ref("study", source.study.id), ledger = "ledger.jsonl";
220
+ graph.put({ ref: study, state: "current", availability: "available", proof: graph.proof("study.json"), data: { mode: source.study.mode } });
221
+ const owned = (ref: ExecutionReferenceV1, proof: ProvenanceProof) => graph.edge(study, ref, "contains", proof);
222
+ const events = source.events, disposals = retentionDisposalIndex(source.events);
223
+ const stageReuseReceipts = new Map<string, number>();
224
+ const addedIdeas = new Map<string, number>(), decisions = new Map<string, number[]>(), latestAttempts = new Map<string, LedgerEvent>(), attemptReceipts = new Map<string, { index: number; event: LedgerEvent }>(), starts = new Map<string, LedgerEvent[]>(), reviewIndexes = new Map<string, number>(), skillIndexes = new Map<string, number>();
225
+ for (const [index, event] of events.entries()) {
226
+ if (event.type === "attempt.stage.reused") stageReuseReceipts.set(canonical([event.data.id, event.data.candidateStage, event.data.key, event.data.sourceAttemptId, event.data.sourceStage, event.data.sourceSha256]), index);
227
+ if (event.type.startsWith("attempt.")) {
228
+ if (typeof event.data.id !== "string" || !ATTEMPT.test(event.data.id)) graph.issue("malformed-attempt-receipt");
229
+ else if (!attemptReceipts.has(event.data.id)) attemptReceipts.set(event.data.id, { index, event });
230
+ }
231
+ if (event.type === "attempt.started" && typeof event.data.id === "string") starts.set(event.data.id, [...(starts.get(event.data.id) ?? []), event]);
232
+ if (event.type.startsWith("attempt.") && typeof event.data.id === "string" && typeof event.data.status === "string") latestAttempts.set(event.data.id, event);
233
+ if (event.type === "idea.added" && plain(event.data.idea) && typeof event.data.idea.id === "string") addedIdeas.set(event.data.idea.id, index);
234
+ if (event.type === "idea.decided" && typeof event.data.id === "string") decisions.set(event.data.id, [...(decisions.get(event.data.id) ?? []), index]);
235
+ if (event.type === "review.added" && typeof event.data.id === "string") reviewIndexes.set(event.data.id, index);
236
+ if (event.type === "skill.proposed" && plain(event.data.proposal) && typeof event.data.proposal.name === "string") skillIndexes.set(event.data.proposal.name, index);
237
+ }
238
+ const attempts = new Map<string, { value: Attempt; file: string; ref: ExecutionReferenceV1 }>(), attemptCounts = new Map<string, number>();
239
+ for (const file of source.files.keys()) { const id = /^runs\/[^/]+\/attempts\/([a-f0-9]{16})\.json$/.exec(file)?.[1]; if (id) attemptCounts.set(id, (attemptCounts.get(id) ?? 0) + 1); }
240
+ try {
241
+ for (const [file, bytes] of source.files) {
242
+ const path = /^runs\/([A-Za-z0-9][A-Za-z0-9_-]{0,63})\/attempts\/([a-f0-9]{16})\.json$/.exec(file); if (!path) continue;
243
+ const raw = parsed(bytes); let value: Attempt;
244
+ try { value = validateAttemptRecord(raw, path[1]!, path[2]!); } catch (error) { graph.issue(error instanceof Error && error.message.includes("unsupported") ? "unsupported-attempt" : "corrupt-attempt"); continue; }
245
+ const ref = graph.ref("attempt", value.id), proof = graph.proof(file);
246
+ if (!attempts.has(value.id)) attempts.set(value.id, { value, file, ref });
247
+ const latest = latestAttempts.get(value.id);
248
+ const start = starts.get(value.id) ?? [];
249
+ const identity = value.studyId !== source.study.id || typeof value.commit !== "string" || !/^[a-f0-9]{40}$/.test(value.commit) || !Number.isSafeInteger(value.seed);
250
+ const retryInvalid = value.retryOf !== undefined && (typeof value.retryOf !== "string" || !ATTEMPT.test(value.retryOf) || value.retryOf === value.id);
251
+ const outputsInvalid = !Array.isArray(value.outputs) || value.outputs.length > 500 || new Set(value.outputs.map(output => plain(output) ? output.path : undefined)).size !== value.outputs.length || value.outputs.some(output => !plain(output) || typeof output.sha256 !== "string" || !HASH.test(output.sha256) || !Number.isSafeInteger(output.bytes) || output.bytes < 0);
252
+ const issue = (attemptCounts.get(value.id) ?? 0) > 1 ? "duplicate-attempt-id" : retryInvalid ? "corrupt-retry-reference" : outputsInvalid ? "corrupt-output-inventory" : identity ? "attempt-study-identity-mismatch" : start.length === 0 ? "missing-attempt-start-receipt" : start.length > 1 ? "duplicate-attempt-start-receipt" : start[0]!.data.run !== value.run || start[0]!.data.commit !== value.commit || start[0]!.data.seed !== value.seed ? "attempt-start-identity-mismatch" : latest?.data.status !== undefined && latest.data.status !== value.status ? "attempt-receipt-mismatch" : undefined;
253
+ const reuse = issue ? undefined : attemptReuseView(value, disposals);
254
+ graph.put({ ref, state: issue ? "corrupt" : "current", availability: "available", proof, data: { status: value.status, stage: value.stage, seed: Number.isSafeInteger(value.seed) ? value.seed : null, ...(reuse ? {executedStages: reuse.executedStages, reusedStages: reuse.reusedStages, independentSamples: reuse.independentSamples, freshEvaluations: reuse.freshEvaluations, disposedReuseSources: reuse.sources.filter(source => source.retention.state === "disposed").length} : {}) } });
255
+ if (value.studyId === source.study.id) owned(ref, proof);
256
+ if (issue) graph.issue(issue, ref);
257
+ }
258
+ for (const [id, receipt] of attemptReceipts) if (!attemptCounts.has(id)) {
259
+ const ref = graph.ref("attempt", id), proof = graph.proof(ledger, receipt.index, id);
260
+ graph.put({ ref, state: "unavailable", availability: "missing", proof }); owned(ref, proof); graph.issue("missing-attempt-record", ref);
261
+ }
262
+ for (const { value, file, ref } of attempts.values()) {
263
+ if (graph.nodes.get(key(ref))?.state !== "current") continue;
264
+ const proof = graph.proof(file);
265
+ if (value.retryOf !== undefined) graph.edge(ref, graph.target("attempt", value.retryOf, proof), "retryOf", proof);
266
+ const attributions = attemptOutputAttributions(value, file, graph, stageReuseReceipts, ledger, disposals);
267
+ for (const output of value.outputs) { graph.touch();
268
+ const artifact = graph.ref("artifact", output.sha256, { sha256: output.sha256 }), attribution = attributions.get(canonical([output.path, output.sha256, output.bytes]));
269
+ graph.put({ ref: artifact, state: "current", availability: "not-read", proof: attribution?.proof ?? proof, data: { bytes: output.bytes, bodyRead: false } });
270
+ if (attribution) graph.edge(ref, artifact, attribution.relation, attribution.proof, attribution.reuseSource);
271
+ else { graph.issue("unattributed-attempt-output", ref); graph.edge(ref, artifact, "contains", proof); }
272
+ }
273
+ }
274
+ const ideas = foldIdeas(events);
275
+ for (const idea of ideas) { const index = addedIdeas.get(idea.id)!, proof = { ...graph.proof(ledger, index, idea.id), sourceBindingSha256: sha256(canonical(idea)) }, ref = graph.ref("idea", idea.id); graph.put({ ref, state: "current", availability: "available", proof, data: { status: idea.state } }); owned(ref, proof); }
276
+ for (const idea of ideas) {
277
+ const ref = graph.ref("idea", idea.id), index = addedIdeas.get(idea.id)!, proof = graph.proof(ledger, index, idea.id);
278
+ if (idea.parent) graph.edge(ref, graph.target("idea", idea.parent, proof), "parent", proof);
279
+ for (const eventIndex of decisions.get(idea.id) ?? []) {
280
+ const event = events[eventIndex]!;
281
+ if (Array.isArray(event.data.attempts)) for (const id of event.data.attempts) { graph.touch(); if (typeof id === "string" && ATTEMPT.test(id)) { const cited = graph.proof(ledger, eventIndex, idea.id); graph.edge(ref, graph.target("attempt", id, cited), "cites-attempt", cited); } }
282
+ }
283
+ }
284
+ const applied = new Map<LedgerEvent, { output?: unknown; status: string; taskId?: number; hubProject?: string }>();
285
+ const plan = foldPlan(events, (state, event) => {
286
+ if (!["node.intent", "node.observed"].includes(event.type)) return;
287
+ const node = state.nodes.find(value => value.id === event.data.node);
288
+ if (node && node.dispatchId === event.data.dispatchId) applied.set(event, { output: event.type === "node.observed" ? node.lastObserved?.output : undefined, status: node.status, taskId: node.taskId, hubProject: node.hubProject });
289
+ }), revisions = new Set<number>(), definitions = new Map<number, ReturnType<typeof validatePlan>>();
290
+ const planFile = fileJson(source, "plan.json");
291
+ if (planFile && planFile.revision === undefined) graph.issue("missing-stored-plan-revision");
292
+ if (plan && (!planFile || canonical(validatePlan(planFile)) !== canonical(plan.definition))) graph.issue("plan-receipt-mismatch");
293
+ if (planFile && !plan) graph.issue("missing-plan-receipt");
294
+ for (const [index, event] of events.entries()) if (event.type === "plan.set" && Number.isSafeInteger(event.data.revision)) {
295
+ const revision = Number(event.data.revision), definition = validatePlan(event.data.definition); definitions.set(revision, definition); revisions.add(revision); const proof = graph.proof(ledger, index), ref = graph.ref("plan-revision", String(revision), { revision: String(revision) }); graph.put({ ref, state: revision === plan?.revision ? "current" : "historical", availability: "available", proof, ...(definition.nodes.some(node => node.kind === "hub") ? { data: { hubState: "declared-unresolved" } } : {}) }); owned(ref, proof);
296
+ }
297
+ const latestApplied = new Map<string, { output?: unknown; status: string; taskId?: number; hubProject?: string }>();
298
+ const dispatchSources = new Map<string, LedgerEvent[]>();
299
+ for (const [event, value] of applied) if (typeof event.data.dispatchId === "string") {
300
+ latestApplied.set(event.data.dispatchId, value);
301
+ const records = dispatchSources.get(event.data.dispatchId) ?? []; records.push(event); dispatchSources.set(event.data.dispatchId, records);
302
+ }
303
+ const dispatches = new Map<string, ExecutionReferenceV1>(), dispatchCommands = new Map<string, string>();
304
+ for (const [index, event] of events.entries()) if (event.type === "node.intent" && applied.has(event) && typeof event.data.dispatchId === "string" && Number.isSafeInteger(event.data.revision)) {
305
+ const revision = Number(event.data.revision), proof = { ...graph.proof(ledger, index), sourceBindingSha256: sha256(canonical(dispatchSources.get(event.data.dispatchId))) }, ref = graph.ref("dispatch", event.data.dispatchId);
306
+ dispatches.set(event.data.dispatchId, ref);
307
+ const definition = definitions.get(revision)?.nodes.find(node => node.id === event.data.node);
308
+ if (definition?.kind === "step") dispatchCommands.set(event.data.dispatchId, definition.command);
309
+ const latest = latestApplied.get(event.data.dispatchId)!, current = plan?.nodes.find(node => node.dispatchId === event.data.dispatchId), data: NonNullable<ProvenanceNode["data"]> = { status: latest.status, nodeId: text(event.data.node, 256) ? event.data.node : null };
310
+ if (Number.isSafeInteger(latest.taskId) && Number(latest.taskId) > 0) { data.hubTaskId = Number(latest.taskId); data.hubState = "declared-unresolved"; if (text(latest.hubProject, 256)) data.hubProject = latest.hubProject; }
311
+ if (definition?.kind === "hub") data.hubState = "declared-unresolved";
312
+ graph.put({ ref, state: current ? "current" : "historical", availability: "available", proof, data });
313
+ if (revisions.has(revision)) graph.edge(graph.ref("plan-revision", String(revision), { revision: String(revision) }), ref, "dispatched", proof);
314
+ if (typeof event.data.attemptId === "string" && ATTEMPT.test(event.data.attemptId)) graph.edge(ref, graph.target("attempt", event.data.attemptId, proof), "expected-attempt", proof);
315
+ }
316
+ for (const [index, event] of events.entries()) if (event.type === "node.observed" && applied.has(event) && typeof event.data.dispatchId === "string" && dispatches.has(event.data.dispatchId)) {
317
+ const ref = dispatches.get(event.data.dispatchId)!, proof = graph.proof(ledger, index), output = applied.get(event)?.output;
318
+ if (Number.isSafeInteger(event.data.revision) && revisions.has(Number(event.data.revision))) graph.edge(ref, graph.ref("plan-revision", String(event.data.revision), { revision: String(event.data.revision) }), "observed-in", proof);
319
+ if (plain(output) && typeof output.attemptId === "string" && ATTEMPT.test(output.attemptId)) graph.edge(ref, graph.target("attempt", output.attemptId, proof), "observed-attempt", proof);
320
+ }
321
+ // Results and evidence are represented by close/build receipts, never recomputed show values.
322
+ closures(dir, graph, study);
323
+ const digestNodes = new Map<string, ExecutionReferenceV1[]>();
324
+ for (const node of graph.nodes.values()) if (node.ref.sha256) digestNodes.set(node.ref.sha256, [...(digestNodes.get(node.ref.sha256) ?? []), node.ref]);
325
+ for (const [index, event] of events.entries()) if (event.type === "node.observed" && applied.has(event) && typeof event.data.dispatchId === "string") {
326
+ const command = dispatchCommands.get(event.data.dispatchId), output = applied.get(event)?.output, from = dispatches.get(event.data.dispatchId);
327
+ if (!from || !plain(output) || typeof output.sha256 !== "string" || !HASH.test(output.sha256) || !["paper.build", "investigate.close", "ablate.close", "final.close"].includes(command ?? "")) continue;
328
+ const target = digestNodes.get(output.sha256)?.find(ref => ref.kind === (command === "paper.build" ? "paper-evidence" : "closed-result") && graph.nodes.get(key(ref))?.data?.family === command!.split(".")[0]);
329
+ if (target) graph.edge(from, target, "observed-output", graph.proof(ledger, index)); else graph.issue("unresolved-dispatch-output", from);
330
+ }
331
+ for (const review of foldReviews(events)) {
332
+ const index = reviewIndexes.get(review.id)!, proof = graph.proof(ledger, index, review.id), hash = review.report.buildSha256;
333
+ graph.edge(study, graph.target("paper-evidence", hash, proof, { sha256: hash }), "reviewed", proof);
334
+ }
335
+ if ([...source.files.keys()].some(name => name.startsWith("design/harness")) || events.some(event => event.type.startsWith("harness."))) {
336
+ // Native replay validates every historical closure; the bounded view supplies current currency only.
337
+ const view = readHarnessViews(dir);
338
+ const current = new Set(view.flatMap(round => round.transitions.closure?.current ? [round.transitions.closure.sha256] : []));
339
+ for (const [index, event] of events.entries()) {
340
+ if (event.type !== "harness.round.closed") continue;
341
+ const form = event.data.form;
342
+ if (!plain(form) || typeof event.data.round !== "string" || typeof event.data.sha256 !== "string") fail("malformed-harness-closure");
343
+ const ref = graph.ref("harness-closure", event.data.round, {sha256: event.data.sha256}), proof = graph.proof(ledger, index, String(form.id));
344
+ graph.put({ref, state: current.has(event.data.sha256) ? "current" : "historical", availability: "available", proof,
345
+ data: {status: "closed", outcome: String(form.outcome), sourceStrength: "synthetic-fixture", actorKind: event.actor.kind, ...(event.actor.id ? {actorId: event.actor.id} : {}), at: event.at}});
346
+ owned(ref, proof);
347
+ }
348
+ }
349
+ for (const skill of foldSkills(events)) {
350
+ const index = skillIndexes.get(skill.name)!, proof = graph.proof(ledger, index, skill.name), ref = graph.ref("skill-proposal", skill.name, { sha256: skill.sha256 }), file = source.files.get(`proposals/skills/${skill.name}.md`);
351
+ const state = !file ? "unavailable" : file.sha256 !== skill.sha256 ? "corrupt" : "current";
352
+ const evidenceRefs = skill.evidence.map(value => typeof value === "string" ? value : value.tool === "ares" && value.projectKey === source.study.id && value.kind === "attempt" ? `ares:${source.study.id}/attempt:${value.id}` : "unresolved");
353
+ const unresolved = evidenceRefs.some(value => !value.startsWith(`ares:${source.study.id}/attempt:`) || !ATTEMPT.test(value.slice(`ares:${source.study.id}/attempt:`.length)));
354
+ graph.put({ ref, state, availability: file ? "available" : "missing", proof, data: { status: skill.state, ...(unresolved ? { additionalEvidence: "declared-unresolved" } : {}) } }); owned(ref, proof); if (state !== "current") graph.issue(state === "corrupt" ? "proposal-receipt-mismatch" : "missing-proposal", ref);
355
+ for (const evidence of evidenceRefs) {
356
+ const prefix = `ares:${source.study.id}/attempt:`, id = evidence.startsWith(prefix) ? evidence.slice(prefix.length) : undefined;
357
+ if (id && ATTEMPT.test(id)) graph.edge(ref, graph.target("attempt", id, proof), "cites-attempt", proof);
358
+ }
359
+ }
360
+ } catch (error) { if (error instanceof TraversalCap) graph.capped = true; else if (error instanceof SourceFailure) graph.issue(error.code); else graph.issue(error instanceof Error && error.message.includes("unsupported") ? "unsupported-source" : "corrupt-provenance"); }
361
+ return graph;
362
+ }
363
+ interface Closure { ref: ExecutionReferenceV1; file: string; hash: string; proof: ProvenanceProof; family: string; latest: boolean; raw?: Record<string, unknown>; nativeVersion?: ReturnType<typeof paperEvidenceVersion> }
364
+ function closures(dir: string, graph: Graph, study: ExecutionReferenceV1): void {
365
+ const source = graph.source, records: Closure[] = [], latest = new Map<string, number>();
366
+ const selected = fileJson(source, "design/selection.json")?.run;
367
+ for (const [index, event] of source.events.entries()) {
368
+ const family = event.type === "investigate.closed" ? "investigate" : event.type === "ablate.closed" ? "ablate" : event.type === "final.closed" ? "final" : event.type === "paper.built" ? "paper" : undefined;
369
+ if (!family) continue;
370
+ const run = family === "investigate" ? event.data.run : family;
371
+ const hash = family === "paper" ? event.data.evidenceSha256 : event.data.sha256;
372
+ if (typeof run !== "string" || !RUN.test(run) || typeof hash !== "string" || !HASH.test(hash)) { graph.issue("malformed-close-receipt"); continue; }
373
+ latest.set(`${family}:${run}`, index);
374
+ records.push({ family, hash, file: family === "paper" ? "paper/build/evidence.json" : `runs/${run}/${family}.json`, ref: graph.ref(family === "paper" ? "paper-evidence" : "closed-result", family === "paper" ? hash : run, { sha256: hash }), proof: graph.proof("ledger.jsonl", index), latest: false });
375
+ }
376
+ for (const file of source.files.keys()) if ((/^runs\/[^/]+\/(investigate|ablate|final)\.json$/.test(file) || file === "paper/build/evidence.json") && !records.some(record => record.file === file)) graph.issue("unreceipted-closed-artifact");
377
+ for (const record of records) {
378
+ record.latest = latest.get(`${record.family}:${record.ref.kind === "paper-evidence" ? "paper" : record.ref.id}`) === record.proof.ledgerIndex;
379
+ const file = source.files.get(record.file), matches = file?.sha256 === record.hash;
380
+ let state: ProvenanceState = record.latest ? "current" : "historical", availability: ProvenanceNode["availability"] = matches ? "available" : record.latest ? "missing" : "receipt-only";
381
+ if (record.latest && !file) { state = "unavailable"; graph.issue("missing-closed-artifact", record.ref); }
382
+ else if (record.latest && !matches) { state = "corrupt"; availability = "available"; graph.issue("close-receipt-mismatch", record.ref); }
383
+ if (matches) {
384
+ try {
385
+ record.raw = fileJson(source, record.file);
386
+ if (record.raw && record.family === "paper" && (record.raw.v === 1 || record.raw.v === 2)) record.nativeVersion = paperEvidenceVersion(record.raw);
387
+ if (!record.raw || (record.raw.v !== 1 && !(record.family === "paper" && record.raw.v === 2))) { state = "unavailable"; graph.issue("unsupported-closed-version", record.ref); }
388
+ else if (record.family === "paper" ? !Array.isArray(record.raw.placeholders) || typeof record.raw.manuscriptSha256 !== "string" : typeof record.raw.inputsSha256 !== "string" || record.family === "final" && !["qualified", "not_qualified"].includes(String(record.raw.status))) { state = "corrupt"; graph.issue("malformed-closed-artifact", record.ref); }
389
+ else if (record.latest && !(record.family === "investigate" && record.ref.id !== selected)) {
390
+ try {
391
+ const hash = record.family === "paper" ? readCurrentBuild(dir).evidenceSha256 : record.family === "investigate" ? readClosedInvestigation(dir).sha256 : record.family === "ablate" ? readClosedAblate(dir).sha256 : readClosedFinal(dir).sha256;
392
+ if (hash !== record.hash) { state = "unavailable"; graph.issue("closed-source-changed", record.ref); }
393
+ } catch (error) {
394
+ const message = error instanceof Error ? error.message : "";
395
+ state = /stale|current|gate|copilot|fresh/.test(message) ? "historical" : "unavailable";
396
+ graph.issue(/unsupported/.test(message) ? "unsupported-source" : state === "historical" ? "historical-not-current" : "closed-source-unavailable", record.ref);
397
+ }
398
+ } else if (record.family === "investigate" && record.ref.id !== selected) state = "historical";
399
+ } catch { state = "corrupt"; graph.issue("malformed-closed-artifact", record.ref); }
400
+ }
401
+ graph.put({ ref: record.ref, state, availability, proof: record.proof, data: { family: record.family, receiptMatched: matches, ...(record.nativeVersion === undefined ? {} : {nativeVersion: record.nativeVersion}), ...(record.family === "final" && typeof record.raw?.status === "string" ? { status: record.raw.status } : {}), ...(record.family === "investigate" && state === "current" && matches && record.raw && Object.hasOwn(record.raw, "winner") ? { winner: record.raw.winner !== null } : {}) } });
402
+ graph.edge(study, record.ref, "closed", record.proof);
403
+ }
404
+ for (const record of records) {
405
+ if (!record.raw || source.files.get(record.file)?.sha256 !== record.hash || (record.family === "paper" ? record.nativeVersion === undefined : record.raw.v !== 1) || graph.nodes.get(key(record.ref))?.state === "corrupt") continue;
406
+ const raw = record.raw, proof = graph.proof(record.file);
407
+ const attempt = (id: unknown) => { graph.touch(); if (typeof id === "string" && ATTEMPT.test(id)) graph.edge(record.ref, graph.target("attempt", id, proof), "uses-attempt", proof); };
408
+ const statuses = (value: unknown) => {
409
+ if (Array.isArray(value)) { if (value.length > graph.limit * 8) throw new TraversalCap(); for (const row of value) { graph.touch(); if (plain(row)) attempt(row.id); else attempt(row); } }
410
+ else if (plain(value)) for (const status of ["running", "succeeded", "failed", "cancelled", "unknown"]) if (Array.isArray(value[status])) for (const id of value[status]) attempt(id);
411
+ };
412
+ if (record.family === "investigate") {
413
+ if (plain(raw.baseline)) statuses(raw.baseline.attempts);
414
+ if (Array.isArray(raw.candidates)) for (const candidate of raw.candidates) { graph.touch(); if (plain(candidate)) statuses(candidate.attempts); }
415
+ if (plain(raw.winner) && typeof raw.winner.idea === "string") graph.edge(record.ref, graph.target("idea", raw.winner.idea, proof), "names-idea", proof);
416
+ } else if (record.family === "ablate") {
417
+ if (plain(raw.reference)) statuses(raw.reference.attempts);
418
+ if (Array.isArray(raw.ablations)) for (const ablation of raw.ablations) { graph.touch(); if (plain(ablation)) statuses(ablation.attempts); }
419
+ } else if (record.family === "final") statuses(raw.attempts);
420
+ if (Array.isArray(raw.excluded)) for (const row of raw.excluded) { graph.touch(); if (plain(row)) attempt(row.id); }
421
+ for (const name of ["investigateSha256", "ablateSha256"]) if (typeof raw[name] === "string") { const linked = records.find(value => value.hash === raw[name] && value.family === (name === "investigateSha256" ? "investigate" : "ablate")); if (linked) graph.edge(record.ref, linked.ref, "uses-closed-result", proof); }
422
+ if (record.family === "paper" && Array.isArray(raw.placeholders)) for (const placeholder of raw.placeholders) { graph.touch();
423
+ if (!plain(placeholder) || !plain(placeholder.source) || typeof placeholder.source.sha256 !== "string" || typeof placeholder.source.file !== "string") continue;
424
+ const hash = placeholder.source.sha256, file = placeholder.source.file;
425
+ const closed = records.find(value => value.hash === hash && value.file === file);
426
+ if (closed) graph.edge(record.ref, closed.ref, "uses-source", proof);
427
+ else {
428
+ const id = /^runs\/[A-Za-z0-9][A-Za-z0-9_-]{0,63}\/attempts\/([a-f0-9]{16})\.json$/.exec(file)?.[1];
429
+ if (id && source.files.get(file)?.sha256 === hash) graph.edge(record.ref, graph.target("attempt", id, proof), "uses-source", proof);
430
+ }
431
+ }
432
+ }
433
+ }
434
+ interface Cursor { v: 1; source: string; ledgerPosition: number; nodes: number; edges: number; options: string }
435
+ function cursor(value: Cursor): string { const text = JSON.stringify(value); return Buffer.from(text).toString("base64url") + "." + sha256(text); }
436
+ function continuation(value: string): Cursor | undefined {
437
+ try {
438
+ if (Buffer.byteLength(value) > 4096 || !/^[A-Za-z0-9_-]+\.[a-f0-9]{64}$/.test(value)) return undefined;
439
+ const [encoded, hash] = value.split("."), decoded = Buffer.from(encoded!, "base64url").toString("utf8"); if (sha256(decoded) !== hash) return undefined;
440
+ const raw: unknown = JSON.parse(decoded);
441
+ if (!plain(raw) || Object.keys(raw).some(key => !["v", "source", "ledgerPosition", "nodes", "edges", "options"].includes(key)) || raw.v !== 1 || typeof raw.source !== "string" || !HASH.test(raw.source) || typeof raw.options !== "string" || ![raw.ledgerPosition, raw.nodes, raw.edges].every(value => Number.isSafeInteger(value) && Number(value) >= 0)) return undefined;
442
+ return raw as unknown as Cursor;
443
+ } catch { return undefined; }
444
+ }
445
+ function empty(status: ProvenancePage["status"], code: string, source?: Snapshot): ProvenancePage {
446
+ return { v: 1, status, sourceSha256: source?.hash ?? null, ledgerPosition: source?.ledgerPosition ?? null, nodes: [], edges: [], issues: [{ code, message: status === "capped" ? `provenance ${code}; use bounded producer reads such as ares attempt list/show or plan show; this graph is incomplete` : `provenance ${code}; keep unsupported source bytes unchanged, restore malformed originals or retry after the active command completes; restart pagination from the first page` }], totals: null, truncated: status === "capped" };
447
+ }
448
+ /** Walk source-proven relations without spreading through the study's membership edges. */
449
+ function selectRoot(graph: Graph, root: ExecutionReferenceV1): boolean {
450
+ const selected = new Set<string>();
451
+ for (const [id, node] of graph.nodes) if (node.ref.kind === root.kind && node.ref.id === root.id && (root.revision === undefined || node.ref.revision === root.revision) && (root.sha256 === undefined || node.ref.sha256 === root.sha256)) selected.add(id);
452
+ if (!selected.size) return false;
453
+ if (root.kind === "study") return true;
454
+ const adjacency = new Map<string, string[]>();
455
+ for (const edge of graph.edges.values()) if (edge.relation !== "contains") {
456
+ const a = key(edge.from), b = key(edge.to); if (edge.from.kind === "study" || edge.to.kind === "study") continue;
457
+ adjacency.set(a, [...(adjacency.get(a) ?? []), b]); adjacency.set(b, [...(adjacency.get(b) ?? []), a]);
458
+ }
459
+ const queue = [...selected];
460
+ for (let index = 0; index < queue.length; index++) for (const id of adjacency.get(queue[index]!) ?? []) if (!selected.has(id)) { selected.add(id); queue.push(id); }
461
+ for (const [id, edge] of graph.edges) if (!(selected.has(key(edge.to)) && (selected.has(key(edge.from)) || edge.relation === "contains"))) graph.edges.delete(id);
462
+ for (const edge of graph.edges.values()) if (edge.relation === "contains") selected.add(key(edge.from));
463
+ for (const id of graph.nodes.keys()) if (!selected.has(id)) graph.nodes.delete(id);
464
+ return true;
465
+ }
466
+ /** Lock-free, local, in-process projection. Source readers never repair files or read the executor/hub. */
467
+ export function readProvenance(dirArg: string, options: ProvenanceOptions = {}): ProvenancePage {
468
+ if (!plain(options as unknown) || Object.keys(options).some(name => !["cursor", "nodeLimit", "edgeLimit", "traversalLimit", "root"].includes(name)) || Object.hasOwn(options, "cursor") && typeof options.cursor !== "string") throw new Error("provenance options: use only cursor (string), nodeLimit, edgeLimit and traversalLimit, root; correct the options before retrying");
469
+ const root = options.root === undefined ? undefined : validateExecutionReference(options.root);
470
+ const nodeLimit = options.nodeLimit ?? PROVENANCE_NODE_LIMIT, edgeLimit = options.edgeLimit ?? PROVENANCE_EDGE_LIMIT, traversal = options.traversalLimit ?? PROVENANCE_TRAVERSAL;
471
+ if (!Number.isSafeInteger(nodeLimit) || nodeLimit < 1 || nodeLimit > PROVENANCE_NODE_LIMIT || !Number.isSafeInteger(edgeLimit) || edgeLimit < 1 || edgeLimit > PROVENANCE_EDGE_LIMIT || !Number.isSafeInteger(traversal) || traversal < 1 || traversal > PROVENANCE_TRAVERSAL) throw new Error("provenance page bounds: use 1..100 nodes, 1..200 edges and traversal 1..1000 before retrying");
472
+ if (root?.tool === "ahub") {
473
+ const page = empty("unavailable", "foreign-root-unsupported");
474
+ page.issues[0]!.message = "provenance foreign root is unsupported by this local ares reader; keep the address unchanged and inspect it through its source owner before requesting evidence";
475
+ return page;
476
+ }
477
+ let source: Snapshot, dir: string;
478
+ try { dir = realpathSync(resolve(dirArg)); source = capture(dir); }
479
+ catch (error) { const code = error instanceof SourceFailure ? error.code : "unreadable-source"; return empty(error instanceof SourceFailure && error.capped ? "capped" : code === "write-in-progress" ? "changed" : "unavailable", code); }
480
+ const configuration = canonical([nodeLimit, edgeLimit, traversal, root ?? null]), previous = options.cursor === undefined ? undefined : continuation(options.cursor);
481
+ if (options.cursor !== undefined && (!previous || previous.source !== source.hash || previous.ledgerPosition !== source.ledgerPosition || previous.options !== configuration)) return empty("changed", "changed-cursor", source);
482
+ let graph: Graph;
483
+ try { graph = build(dir, source, traversal); } catch { return empty("unavailable", "invalid-source-reference", source); }
484
+ if (root) {
485
+ if (root.projectKey !== source.study.id || !selectRoot(graph, root)) return graph.capped ? empty("capped", "traversal-capped", source) : empty("unavailable", "root-unavailable", source);
486
+ }
487
+ try { const after = capture(dir); if (after.hash !== source.hash || after.ledgerPosition !== source.ledgerPosition) return empty("changed", "source-changed", source); }
488
+ catch { return empty("changed", "source-changed-or-unavailable", source); }
489
+ const nodes = [...graph.nodes.values()].sort((a, b) => (key(a.ref) < key(b.ref) ? -1 : key(a.ref) > key(b.ref) ? 1 : 0)), edges = [...graph.edges.values()].sort((a, b) => (canonical(a) < canonical(b) ? -1 : canonical(a) > canonical(b) ? 1 : 0));
490
+ const n = previous?.nodes ?? 0, e = previous?.edges ?? 0;
491
+ if (n > nodes.length || e > edges.length) return empty("changed", "changed-cursor", source);
492
+ const page: ProvenancePage = { v: 1, status: graph.capped ? "capped" : graph.issues.length ? "unavailable" : "ok", sourceSha256: source.hash, ledgerPosition: source.ledgerPosition, nodes: nodes.slice(n, n + nodeLimit), edges: edges.slice(e, e + edgeLimit), issues: graph.issues, totals: graph.capped || graph.issues.length ? null : { nodes: nodes.length, edges: edges.length }, truncated: graph.capped };
493
+ const next = () => {
494
+ const more = n + page.nodes.length < nodes.length || e + page.edges.length < edges.length;
495
+ page.truncated = graph.capped || more;
496
+ if (more) page.nextCursor = cursor({ v: 1, source: source.hash, ledgerPosition: source.ledgerPosition, nodes: n + page.nodes.length, edges: e + page.edges.length, options: configuration }); else delete page.nextCursor;
497
+ };
498
+ if (graph.capped) page.issues = [...page.issues, { code: "traversal-capped", message: "provenance traversal capped; use bounded producer reads such as ares attempt list/show or plan show instead of treating this as a complete graph" }];
499
+ next();
500
+ while (Buffer.byteLength(JSON.stringify(page)) > PROVENANCE_PAGE_BYTES) {
501
+ if (page.edges.length) page.edges.pop(); else if (page.nodes.length > 1) page.nodes.pop(); else return empty("capped", "page-byte-bound", source);
502
+ next();
503
+ }
504
+ return page;
505
+ }
506
+
507
+ export interface RetentionDisposalView {
508
+ state: "disposed" | "unknown";
509
+ proof?: {scope: "source-study-ledger"; file: "ledger.jsonl"; ledgerIndex: number; recordSha256: string; recordType: "retention.pruned"; fingerprint: string};
510
+ }
511
+ export type RetentionDisposalIndex = ReadonlyMap<string, NonNullable<RetentionDisposalView["proof"]>>;
512
+ const retentionRefKey = (ref: {attemptId: string; stage: string; sha256: string}) => canonical([ref.attemptId, ref.stage, ref.sha256]);
513
+ /** Only an exact successful current-format prune receipt establishes local disposal knowledge. */
514
+ export function retentionDisposalIndex(events: readonly LedgerEvent[]): RetentionDisposalIndex {
515
+ const index = new Map<string, NonNullable<RetentionDisposalView["proof"]>>();
516
+ for (const [ledgerIndex, event] of events.entries()) {
517
+ if (event.type !== "retention.pruned" || !plain(event.data) || !Array.isArray(event.data.refs) || event.data.refs.length < 1 || event.data.refs.length > 500 || event.data.count !== event.data.refs.length || typeof event.data.fingerprint !== "string" || !HASH.test(event.data.fingerprint) || typeof event.data.refsSha256 !== "string" || !HASH.test(event.data.refsSha256)) continue;
518
+ const refs: {attemptId: string; stage: string; sha256: string}[] = [];
519
+ for (const value of event.data.refs) {
520
+ if (!Array.isArray(value) || value.length !== 3 || typeof value[0] !== "string" || !ATTEMPT.test(value[0]) || typeof value[1] !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(value[1]) || ["constructor", "prototype", "__proto__"].includes(value[1]) || typeof value[2] !== "string" || !HASH.test(value[2])) break;
521
+ refs.push({attemptId: value[0], stage: value[1], sha256: value[2]});
522
+ }
523
+ if (refs.length !== event.data.refs.length || new Set(refs.map(retentionRefKey)).size !== refs.length || sha256(JSON.stringify(refs)) !== event.data.refsSha256) continue;
524
+ const proof = {scope: "source-study-ledger" as const, file: "ledger.jsonl" as const, ledgerIndex, recordSha256: sha256(canonical(event)), recordType: "retention.pruned" as const, fingerprint: event.data.fingerprint};
525
+ for (const ref of refs) if (!index.has(retentionRefKey(ref))) index.set(retentionRefKey(ref), proof);
526
+ }
527
+ return index;
528
+ }
529
+ export function retentionDisposalView(ref: {attemptId: string; stage: string; sha256: string}, index: RetentionDisposalIndex): RetentionDisposalView {
530
+ const proof = index.get(retentionRefKey(ref));
531
+ return proof ? {state: "disposed", proof} : {state: "unknown"};
532
+ }
533
+
534
+ export interface AttemptReuseView {
535
+ v: 1; mode: "off" | "eligible"; forceFresh: boolean;
536
+ executedCandidateStages: number; reusedCandidateStages: number; executedStages: number; reusedStages: number; freshEvaluations: number; independentSamples: number;
537
+ sources: { candidateStage: string; key: string; ref: {attemptId: string; stage: string; sha256: string}; retention: RetentionDisposalView; original: {wallSeconds: number | "unknown"; gpuHours: number | "unknown"; cpuSeconds: "unknown"}; verificationMs: number | "unknown"; materializationMs: number | "unknown" }[];
538
+ stages: {name: string; outcome: "fresh" | "reused"; reason: string}[];
539
+ costs: {originalWallSeconds: number | "unknown"; originalGpuHours: number | "unknown"; originalCpuSeconds: "unknown"; verificationMilliseconds: number | "unknown"; materializationMilliseconds: number | "unknown"; observedPreflightFailureMilliseconds: number | "unknown"; totalFailureMilliseconds: "unknown"; clockRelationship: "subsets-of-attempt-wall-do-not-sum"; currentCpuSeconds: "unknown"; storageBytes: "unknown"; transferBytes: "unknown"};
540
+ }
541
+ /** Descriptive projection only: original source computation is never counted as current execution. */
542
+ export function attemptReuseView(value: Attempt, disposalSource: readonly LedgerEvent[] | RetentionDisposalIndex = []): AttemptReuseView | undefined {
543
+ const disposals = Array.isArray(disposalSource) ? retentionDisposalIndex(disposalSource) : disposalSource as RetentionDisposalIndex;
544
+ if (value.v !== 3) return undefined;
545
+ const raw = value.reuse;
546
+ const completed = value.pipeline?.completed ?? [];
547
+ if (completed.length > 16) fail("reuse-view-stage-cap", true);
548
+ const entries = completed.map(parent => ({parent, receipt: parent.reuse}));
549
+ if (raw === undefined && entries.every(entry => entry.receipt === undefined)) return undefined;
550
+ if (!plain(raw) || (raw.mode !== "off" && raw.mode !== "eligible") || typeof raw.forceFresh !== "boolean") fail("malformed-reuse-metadata");
551
+ const measured = (n: unknown): number | "unknown" => typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : "unknown";
552
+ const sources: AttemptReuseView["sources"] = [];
553
+ let executedCandidateStages = 0;
554
+ for (const {parent, receipt} of entries) {
555
+ if (receipt === undefined) { if (typeof parent.record.containerId === "string" && HASH.test(parent.record.containerId)) executedCandidateStages++; continue; }
556
+ if (!plain(receipt) || receipt.v !== 1 || typeof receipt.key !== "string" || !HASH.test(receipt.key) || !plain(receipt.source) || typeof receipt.source.attemptId !== "string" || !ATTEMPT.test(receipt.source.attemptId) || typeof receipt.source.stage !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(receipt.source.stage) || typeof receipt.source.sha256 !== "string" || !HASH.test(receipt.source.sha256) || !plain(receipt.original) || receipt.source.stage !== parent.name || receipt.source.attemptId === value.id || receipt.source.attemptId !== parent.ref.attemptId || receipt.source.stage !== parent.ref.stage || receipt.source.sha256 !== parent.ref.sha256) fail("malformed-reuse-receipt");
557
+ sources.push({candidateStage: parent.name, key: receipt.key, ref: {attemptId: receipt.source.attemptId, stage: receipt.source.stage, sha256: receipt.source.sha256}, retention: retentionDisposalView(receipt.source, disposals),
558
+ original: {wallSeconds: measured(receipt.original.wallSeconds), gpuHours: measured(receipt.original.gpuHours), cpuSeconds: "unknown"}, verificationMs: measured(receipt.verificationMs), materializationMs: measured(receipt.materializationMs)});
559
+ }
560
+ if (value.stage === "candidate" && typeof value.stages.candidate?.containerId === "string" && HASH.test(value.stages.candidate.containerId)) executedCandidateStages++;
561
+ const freshEvaluations = typeof value.stages.evaluator?.containerId === "string" && HASH.test(value.stages.evaluator.containerId) ? 1 : 0;
562
+ const stageMap = plain(raw.stages) ? raw.stages : {};
563
+ const stages: AttemptReuseView["stages"] = [];
564
+ for (const definition of value.pipeline?.definition.candidate.stages ?? []) {
565
+ const entry = stageMap[definition.name];
566
+ if (!plain(entry) || (entry.outcome !== "fresh" && entry.outcome !== "reused")) continue;
567
+ stages.push({name: definition.name, outcome: entry.outcome, reason: typeof entry.reason === "string" && /^[a-z][a-z0-9-]{0,63}$/.test(entry.reason) ? entry.reason : "unknown"});
568
+ }
569
+ const total = (key: "wallSeconds" | "gpuHours"): number | "unknown" => {
570
+ let sum = 0;
571
+ for (const source of sources) { const n = source.original[key]; if (n === "unknown") return "unknown"; sum += n; }
572
+ return Number.isFinite(sum) ? sum : "unknown";
573
+ };
574
+ return {v: 1, mode: raw.mode, forceFresh: raw.forceFresh, executedCandidateStages, reusedCandidateStages: sources.length, executedStages: executedCandidateStages + freshEvaluations, reusedStages: sources.length, freshEvaluations, independentSamples: value.status === "succeeded" && freshEvaluations === 1 && !sources.length && value.retryOf === undefined ? 1 : 0, sources, stages,
575
+ costs: {originalWallSeconds: total("wallSeconds"), originalGpuHours: total("gpuHours"), originalCpuSeconds: "unknown", verificationMilliseconds: measured(raw.verificationMs), materializationMilliseconds: measured(raw.materializationMs), observedPreflightFailureMilliseconds: measured(raw.failureMs), totalFailureMilliseconds: "unknown", clockRelationship: "subsets-of-attempt-wall-do-not-sum", currentCpuSeconds: "unknown", storageBytes: "unknown", transferBytes: "unknown"}};
576
+ }
577
+
578
+ export interface AttemptComparison {
579
+ id: string; code: {commit: string; treeId: string; snapshotSha256: string | null}; protocolHash: string; seed: number; status: Attempt["status"];
580
+ retryOf: string | null; retryAncestry: string[]; sampleGroup: string;
581
+ reuse?: AttemptReuseView;
582
+ comparabilityReasons: string[]; metrics: Attempt["metrics"]; artifactDigests: string[];
583
+ costs: {wallMilliseconds: number | "unknown"; storageBytes: number | "unknown"; compute: "unknown"; transfer: "unknown"; verification: "unknown"; retention: "unknown"; materialization: "unknown"; idle: "unknown"; person: "unknown"};
584
+ }
585
+ export interface LineageComparisonRow { kind: "attempt" | "candidate"; id: string; state: "available" | "unavailable"; attempts: AttemptComparison[]; candidate?: CommitResult; reasons: string[] }
586
+ export interface LineageComparison {
587
+ v: 1; status: ProvenancePage["status"]; sourceSha256: string | null; ledgerPosition: number | null;
588
+ rows: LineageComparisonRow[]; issues: ProvenanceIssue[]; retriesAreIndependent: false;
589
+ aggregation: {performed: false; available: false; compatible: boolean; reasons: string[]}; resultAuthority: "existing-investigation-and-final-only";
590
+ }
591
+ function comparisonAttempt(value: Attempt, attempts: Map<string, Attempt>, disposals: RetentionDisposalIndex): AttemptComparison {
592
+ if (!HASH.test(value.protocolHash) || !/^[a-f0-9]{40}$/.test(value.treeId) || !Array.isArray(value.metrics) || value.metrics.length > METRIC_LIMIT || value.metrics.some(metric => !plain(metric) || typeof metric.name !== "string" || typeof metric.unit !== "string" || metric.provenance !== "ares-observed" || typeof metric.value !== "number" || !Number.isFinite(metric.value))) fail("malformed-comparison-attempt");
593
+ if (value.snapshotSha256 !== undefined && (typeof value.snapshotSha256 !== "string" || !HASH.test(value.snapshotSha256))) fail("malformed-snapshot-sha256");
594
+ let protocol: ReturnType<typeof validateProtocolDefinition>;
595
+ try { protocol = value.pipeline ? validateProtocolDefinition(value.pipeline.definition) : validateStoredProtocol(value.protocol); } catch { return fail("malformed-comparison-protocol"); }
596
+ if (protocolHash(protocol) !== value.protocolHash) fail("protocol-hash-mismatch");
597
+ const reuse = attemptReuseView(value, disposals);
598
+ const metricReasons: string[] = [];
599
+ if (reuse?.reusedStages) metricReasons.push("reused-computation-not-independent");
600
+ if (new Set(value.metrics.map(metric => metric.name)).size !== value.metrics.length) metricReasons.push("duplicate-metric-names");
601
+ if (value.metrics.some(metric => !protocol.metrics.some(declared => declared.name === metric.name && declared.unit === metric.unit))) metricReasons.push("undeclared-metrics");
602
+ if (protocol.metrics.some(declared => !value.metrics.some(metric => metric.name === declared.name && metric.unit === declared.unit))) metricReasons.push("missing-declared-metrics");
603
+ const seen = new Set([value.id]), ancestry: string[] = []; let parent = value.retryOf;
604
+ while (parent !== undefined) {
605
+ if (seen.has(parent)) fail("cyclic-retry-ancestry");
606
+ const ancestor = attempts.get(parent); if (!ancestor) fail("unavailable-retry-ancestor");
607
+ seen.add(parent); ancestry.push(parent); parent = ancestor.retryOf;
608
+ if (ancestry.length > PROVENANCE_TRAVERSAL) fail("retry-traversal-capped", true);
609
+ }
610
+ const start = Date.parse(value.startedAt), end = value.endedAt === undefined ? NaN : Date.parse(value.endedAt), storage = value.outputs.reduce((sum, output) => sum + output.bytes, 0);
611
+ return { id: value.id, code: {commit: value.commit, treeId: value.treeId, snapshotSha256: value.snapshotSha256 ?? null}, protocolHash: value.protocolHash, seed: value.seed, status: value.status,
612
+ retryOf: value.retryOf ?? null, retryAncestry: ancestry, sampleGroup: sha256(canonical([value.commit, value.protocolHash, value.seed])), comparabilityReasons: metricReasons, metrics: value.metrics,
613
+ ...(reuse === undefined ? {} : {reuse}), artifactDigests: [...new Set(value.outputs.map(output => output.sha256))].sort(), costs: {wallMilliseconds: Number.isFinite(start) && Number.isFinite(end) && end >= start ? end - start : "unknown", storageBytes: (value.status === "succeeded" || value.outputs.length > 0) && Number.isSafeInteger(storage) ? storage : "unknown", compute: "unknown", transfer: "unknown", verification: "unknown", retention: "unknown", materialization: "unknown", idle: "unknown", person: "unknown"} };
614
+ }
615
+ /** Descriptive rows only: no arithmetic, new winner, result receipt, executor reads or effects. */
616
+ export function compareLineage(dirArg: string, options: {attempts?: string[]; candidates?: string[]}): LineageComparison {
617
+ if (!plain(options as unknown) || Object.keys(options).some(name => !["attempts", "candidates"].includes(name)) || (options.attempts === undefined) === (options.candidates === undefined)) throw new Error("lineage compare: select exactly one of attempts or candidates; pass 1..8 native ids before retrying");
618
+ const ids = options.attempts ?? options.candidates!, kind = options.attempts ? "attempt" : "candidate";
619
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > 8 || new Set(ids).size !== ids.length || ids.some(id => typeof id !== "string" || !(kind === "attempt" ? ATTEMPT : /^[a-f0-9]{40}$/).test(id))) throw new Error("lineage compare: select 1..8 distinct 16-hex attempt ids or 40-hex candidate commits; correct the selection before retrying");
620
+ const result: LineageComparison = {v: 1, status: "unavailable", sourceSha256: null, ledgerPosition: null, rows: [], issues: [], retriesAreIndependent: false, aggregation: {performed: false, available: false, compatible: false, reasons: []}, resultAuthority: "existing-investigation-and-final-only"};
621
+ let source: Snapshot | undefined, graphCapped = false;
622
+ try {
623
+ const dir = realpathSync(resolve(dirArg)); source = capture(dir); result.sourceSha256 = source.hash; result.ledgerPosition = source.ledgerPosition;
624
+ const graph = build(dir, source, PROVENANCE_TRAVERSAL), attempts = new Map<string, Attempt>();
625
+ graphCapped = graph.capped;
626
+ result.issues = [...graph.issues]; if (graphCapped) result.issues.push({code: "traversal-capped", message: "lineage comparison traversal capped; use bounded producer reads such as ares attempt show; this comparison is incomplete"});
627
+ result.status = graph.capped ? "capped" : graph.issues.length ? "unavailable" : "ok";
628
+ for (const [file, bytes] of source.files) {
629
+ const match = /^runs\/([^/]+)\/attempts\/([a-f0-9]{16})\.json$/.exec(file); if (!match) continue;
630
+ const ref = graph.ref("attempt", match[2]!); if (graph.nodes.get(key(ref))?.state === "current") attempts.set(match[2]!, validateAttemptRecord(parsed(bytes), match[1]!, match[2]!));
631
+ }
632
+ const disposals = retentionDisposalIndex(source.events);
633
+ let candidates: CommitResult[] = [];
634
+ if (kind === "candidate") { const closed = readClosedInvestigation(dir); if (source.files.get(`runs/${closed.result.run}/investigate.json`)?.sha256 !== closed.sha256) fail("closed-source-changed"); candidates = closed.result.candidates; }
635
+ for (const id of ids) {
636
+ const candidate = candidates.find(row => row.commit === id), selected = kind === "attempt" ? [id] : candidate ? Object.values(candidate.attempts).flat() : [];
637
+ const row: LineageComparisonRow = {kind, id, state: "available", attempts: [], reasons: [], ...(candidate ? {candidate} : {})};
638
+ if (kind === "candidate" && !candidate) { row.state = "unavailable"; row.reasons.push("candidate-not-in-closed-investigation"); }
639
+ for (const attemptId of selected) {
640
+ const attempt = attempts.get(attemptId);
641
+ if (!attempt) { row.state = "unavailable"; row.reasons.push("attempt-unavailable:" + attemptId); continue; }
642
+ try { row.attempts.push(comparisonAttempt(attempt, attempts, disposals)); }
643
+ catch (error) {
644
+ if (!(error instanceof SourceFailure) || error.capped) throw error;
645
+ row.state = "unavailable"; row.reasons.push(error.code);
646
+ result.issues.push({code: error.code, message: `lineage compare ${error.code}; restore the valid original attempt record before retrying`});
647
+ }
648
+ }
649
+ if (row.state !== "available") { if (!graphCapped) result.status = "unavailable"; result.issues.push({code: "comparison-selection-unavailable", message: "lineage compare selection unavailable; inspect lineage show and choose existing valid records before retrying"}); }
650
+ result.rows.push(row);
651
+ }
652
+ const values = result.rows.flatMap(row => row.attempts), reasons = new Set<string>();
653
+ for (const value of values) for (const reason of value.comparabilityReasons) reasons.add(reason);
654
+ if (result.status !== "ok" || result.rows.some(row => row.state !== "available")) reasons.add("source-unavailable");
655
+ if (values.some(value => value.status !== "succeeded")) reasons.add("non-successful-outcomes-retained");
656
+ if (new Set(values.map(value => value.protocolHash)).size > 1) reasons.add("protocol-mismatch");
657
+ if (new Set(values.map(value => value.seed)).size > 1) reasons.add("different-seeds");
658
+ if (values.some(value => value.retryOf !== null) || new Set(values.map(value => value.sampleGroup)).size < values.length) reasons.add("retries-or-repeated-samples-not-independent");
659
+ if (new Set(values.map(value => canonical(value.metrics.map(metric => [metric.name, metric.unit]).sort()))).size > 1) reasons.add("incompatible-metrics");
660
+ if (!values.length || values.some(value => !value.metrics.length)) reasons.add("metrics-unavailable");
661
+ result.aggregation = {performed: false, available: false, compatible: reasons.size === 0, reasons: [...reasons].sort()};
662
+ const after = capture(dir); if (after.hash !== source.hash || after.ledgerPosition !== source.ledgerPosition) fail("source-changed");
663
+ if (Buffer.byteLength(JSON.stringify(result)) > PROVENANCE_PAGE_BYTES) fail("comparison-page-capped", true);
664
+ return result;
665
+ } catch (error) {
666
+ const code = error instanceof SourceFailure ? error.code : "comparison-source-unavailable";
667
+ result.status = code === "source-changed" || code === "write-in-progress" ? "changed" : graphCapped || error instanceof SourceFailure && error.capped ? "capped" : "unavailable";
668
+ result.rows = []; result.issues = [...result.issues.filter(issue => issue.code === "traversal-capped"), {code, message: `lineage compare ${code}; inspect lineage show and restore valid source records or retry the read`}];
669
+ result.aggregation = {performed: false, available: false, compatible: false, reasons: [code]}; return result;
670
+ }
671
+ }
672
+
673
+ /** Internal whole-graph read model for a bounded multi-source inspection, never a second store or public page. */
674
+ export function localEvidenceSnapshot(dirArg: string, permit?: StudyReadLock) {
675
+ const dir = realpathSync(resolve(dirArg)), source = capture(dir, permit), graph = build(dir, source, PROVENANCE_TRAVERSAL), after = capture(dir, permit);
676
+ const changed = after.hash !== source.hash || after.ledgerPosition !== source.ledgerPosition;
677
+ const value = {study: source.study, sourceSha256: source.hash, ledgerPosition: source.ledgerPosition, nodes: [...graph.nodes.values()], issues: graph.issues.map(issue => issue.code), status: changed ? "changed" : graph.capped ? "capped" : graph.issues.length ? "unavailable" : "ok"};
678
+ return {...value, bytes: Buffer.byteLength(JSON.stringify(value)), recheck() {try {const current = capture(dir, permit); return current.hash === source.hash && current.ledgerPosition === source.ledgerPosition;} catch {return false;}}};
679
+ }