@staix/agent-research 0.3.1 → 0.5.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.
package/src/mcp-tools.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { PAPER_DOCUMENTS, paperDocument } from "./paper/document.ts";
2
+ import { PAPER_FIGURES, PAPER_FIGURE_PATH_BYTES, PAPER_FIGURE_WAIVER_BYTES } from "./paper/figures.ts";
1
3
  import { STAGE_REUSE_CONTRACT_SCHEMA } from "./exp/reuse-contract.ts";
2
4
  import {HARNESS_MODEL_BYTES} from "./harness/limits.ts";
3
5
  import { PROVENANCE_KINDS, type ExecutionReferenceV1 } from "./provenance.ts";
@@ -11,9 +13,10 @@ import type { RetainedRef } from "./exp/retention.ts";
11
13
  import { PLAYBOOK } from "./playbook.ts";
12
14
  import { PLAN_ID_BYTES, STEP_COMMANDS } from "./plan/definition.ts";
13
15
  import { PLAN_GATE_BYTES } from "./plan/state.ts";
14
- import { PAPER_PLAN_BYTES, PAPER_PLAN_SECTIONS, PAPER_PLAN_CITES, PAPER_PLAN_POINTS, PAPER_POINT_CLAIM_CHARACTERS, PAPER_POINT_EVIDENCE, PAPER_POINT_EVIDENCE_BYTES } from "./paper/plan.ts";
16
+ import { PAPER_PLAN_BYTES, PAPER_PLAN_SECTIONS, PAPER_PLAN_CITES, PAPER_PLAN_POINTS, PAPER_POINT_CLAIM_CHARACTERS, PAPER_POINT_EVIDENCE, PAPER_POINT_EVIDENCE_BYTES, PAPER_PLAN_DEPENDENCIES, PAPER_DEPENDENCY_WAIVER_BYTES, PAPER_DEPENDENCY_KINDS } from "./paper/plan.ts";
15
17
  import { detectActor, type Actor } from "./study.ts";
16
18
 
19
+ const paperDoc = { type: "string", enum: [...PAPER_DOCUMENTS] };
17
20
  const study = { type: "string", minLength: 1, maxLength: 4096, description: "Absolute path of the study directory (holds study.json)" };
18
21
  const id = { type: "string", minLength: 1, maxLength: 300 };
19
22
  const ids = { type: "array", items: id, maxItems: 200 };
@@ -21,12 +24,27 @@ const reason = { type: "string", minLength: 1, maxLength: 500 };
21
24
  const read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
22
25
  const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
23
26
  const net = { ...write, openWorldHint: true };
27
+ /** An open object whose closed shape the handler validates; the MCP validator passes each member through. */
28
+ const HANDLER_VALIDATED = { type: "object", additionalProperties: {} };
24
29
  const obj = (properties: Record<string, unknown>, required: string[]) => ({ type: "object", properties, required, additionalProperties: false });
25
30
 
26
31
  const text = (max: number) => ({ type: "string", minLength: 1, maxLength: max });
27
32
  const texts = (items: number, max: number) => ({ type: "array", items: text(max), maxItems: items });
28
33
  const year = { type: "integer", minimum: 1000, maximum: 2100 };
29
- const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2]}, sections: {type: "array", maxItems: PAPER_PLAN_SECTIONS, items: obj({
34
+ const PAPER_DEPENDENCY = obj({
35
+ id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
36
+ kind: {type: "string", enum: [...PAPER_DEPENDENCY_KINDS]},
37
+ name: text(PAPER_PLAN_BYTES),
38
+ cites: {type: "array", minItems: 1, maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
39
+ waiver: text(PAPER_DEPENDENCY_WAIVER_BYTES),
40
+ }, ["id", "kind", "name"]);
41
+ const PAPER_FIGURE = obj({
42
+ id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
43
+ file: text(PAPER_FIGURE_PATH_BYTES), kind: {type: "string", enum: ["plot", "diagram"]},
44
+ evidence: {type: "array", minItems: 1, maxItems: PAPER_POINT_EVIDENCE, items: text(PAPER_POINT_EVIDENCE_BYTES)},
45
+ waiver: text(PAPER_FIGURE_WAIVER_BYTES),
46
+ }, ["id", "file", "kind"]);
47
+ const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2, 3]}, sections: {type: "array", maxItems: PAPER_PLAN_SECTIONS, items: obj({
30
48
  id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"}, heading: text(PAPER_PLAN_BYTES),
31
49
  cites: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
32
50
  points: {type: "array", maxItems: PAPER_PLAN_POINTS, items: obj({
@@ -36,7 +54,7 @@ const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2]}, sections: {type: "ar
36
54
  requires: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
37
55
  evidence: {type: "array", maxItems: PAPER_POINT_EVIDENCE, items: {...text(PAPER_POINT_EVIDENCE_BYTES), description: "Existing current-study card:<paper-id> or attempt:<16-hex-id>, at most 4096 UTF-8 bytes; existence only"}},
38
56
  }, ["id", "claim", "requires"])},
39
- }, ["id", "heading", "cites"])}}, ["sections"]);
57
+ }, ["id", "heading", "cites"])}, dependencies: {type: "array", maxItems: PAPER_PLAN_DEPENDENCIES, items: PAPER_DEPENDENCY}, figures: {type: "array", maxItems: PAPER_FIGURES, items: PAPER_FIGURE}}, ["sections"]);
40
58
  const EXECUTION_REFERENCE = obj({ v: { type: "integer", enum: [1] }, tool: { type: "string", enum: ["ares"] }, projectKey: text(256), kind: { type: "string", enum: [...PROVENANCE_KINDS] }, id: text(256), revision: text(128), sha256: { type: "string", minLength: 64, maxLength: 64 } }, ["v", "tool", "projectKey", "kind", "id"]);
41
59
  const LINEAGE_ATTEMPTS = { type: "array", minItems: 1, maxItems: 8, items: { ...text(16), minLength: 16 } };
42
60
  const LINEAGE_CANDIDATES = { type: "array", minItems: 1, maxItems: 8, items: { ...text(40), minLength: 40 } };
@@ -45,6 +63,7 @@ const REVIEW = obj({
45
63
  checklist: obj({ negativeResults: { type: "boolean" }, denominators: { type: "boolean" }, limitations: { type: "boolean" }, reproducibility: { type: "boolean" },
46
64
  survey: obj({ taxonomyPrinciple: { type: "boolean" }, noEnumeration: { type: "boolean" }, specificGaps: { type: "boolean" }, citationRelations: { type: "boolean" }, selectionReported: { type: "boolean" }, scopeControl: { type: "boolean" } }, ["taxonomyPrinciple", "noEnumeration", "specificGaps", "citationRelations", "selectionReported", "scopeControl"]) }, ["negativeResults", "denominators", "limitations", "reproducibility"]),
47
65
  findings: { type: "array", maxItems: 200, items: obj({ id: text(128), kind: { type: "string", enum: ["contradiction", "unsupported-claim", "number", "citation", "method", "clarity", "other"] }, location: text(4000), text: text(4000), blocking: { type: "boolean" }, repair: { type: "string", enum: ["edit", "paragraph", "section"] }, section: text(256) }, ["id", "kind", "location", "text", "blocking"]) },
66
+ readback: obj({ claims: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 1000 } } }, ["claims"]),
48
67
  }, ["v", "reviewer", "buildSha256", "checklist", "findings"]);
49
68
  // Source-specific current-study/exact-id rules are owned by the shared validator; the MCP transport bounds both shapes.
50
69
  const SKILL_REF = {...EXECUTION_REFERENCE, type: ["string", "object"], minLength: 1, maxLength: 4096, required: ["v", "tool", "id"], properties: {...EXECUTION_REFERENCE.properties, tool: {type: "string", enum: ["ares", "amem"]}}};
@@ -71,6 +90,10 @@ const PROTOCOL_V1 = obj({
71
90
  network: { type: "string", enum: ["none"] },
72
91
  inputs: { type: "object", maxProperties: 8, properties: {}, additionalProperties: obj({ path: text(4096), sha256: text(64), mount: obj({ candidate: text(256), evaluator: text(256) }, []) }, ["path", "sha256", "mount"]) },
73
92
  budget: obj({ maxAttempts: integer(1, 1_000_000), maxWallHours: { type: "number", minimum: 0.000001, maximum: 1_000_000 }, maxGpuHours: { type: "number", minimum: 0, maximum: 64_000_000 } }, ["maxAttempts", "maxWallHours", "maxGpuHours"]),
93
+ screen: obj({
94
+ evaluatorInputs: { type: "boolean", enum: [true], description: "Refuse a candidate commit that carries a byte copy of an input mounted only for the evaluator" },
95
+ literals: { type: "array", minItems: 1, maxItems: 64, items: { type: "string", minLength: 8, maxLength: 200 }, description: "Fixed strings of 8..200 bytes searched over the candidate commit's files" },
96
+ }, []),
74
97
  }, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"]);
75
98
 
76
99
  const STAGE_PROTOCOL = obj({ ...PROTOCOL_V1.properties,
@@ -102,34 +125,46 @@ const PLAN = obj({
102
125
  edges: { type: "array", maxItems: 512, items: { type: "array", minItems: 2, maxItems: 2, items: planId } },
103
126
  }, ["v", "nodes", "edges"]);
104
127
 
105
- const SELECTION = obj({
106
- v: { type: "integer", enum: [1] }, run: text(64), metric: text(128),
128
+ const SELECTION_FIELDS = {
129
+ run: text(64), metric: text(128),
107
130
  baseline: obj({ commit: { type: "string", minLength: 40, maxLength: 40 } }, ["commit"]),
108
131
  minSeeds: integer(1, 1000), minDelta: { type: "number", minimum: 0 },
109
- }, ["v", "run", "metric", "baseline", "minSeeds", "minDelta"]);
132
+ };
133
+ const SELECTION_REQUIRED = ["v", "run", "metric", "baseline", "minSeeds", "minDelta"];
134
+ const SELECTION = { oneOf: [
135
+ obj({ v: { type: "integer", enum: [1] }, ...SELECTION_FIELDS }, SELECTION_REQUIRED),
136
+ obj({
137
+ v: { type: "integer", enum: [2] }, ...SELECTION_FIELDS,
138
+ guards: { type: "array", maxItems: 8, items: obj({ metric: text(128), maxRegression: { type: "number", minimum: 0 } }, ["metric", "maxRegression"]) },
139
+ cost: obj({ metric: text(128), free: { type: "number", minimum: 0 }, perUnit: { type: "number", minimum: 0 } }, ["metric", "free", "perUnit"]),
140
+ calibration: obj({ sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$" } }, ["sha256"]),
141
+ }, SELECTION_REQUIRED),
142
+ ] };
110
143
 
111
- const IDEA = obj({ id: text(64), title: text(500), hypothesis: text(4000), parent: text(64), commit: { type: "string", minLength: 40, maxLength: 40 } }, ["id", "title", "hypothesis"]);
144
+ const PREDICTION = obj({ metric: text(128), expect: { type: "string", enum: ["improve", "no-change", "regress"] }, minDelta: { type: "number", minimum: 0 } }, ["metric", "expect"]);
145
+ const IDEA = obj({ id: text(64), title: text(500), hypothesis: text(4000), parent: text(64), commit: { type: "string", minLength: 40, maxLength: 40 },
146
+ category: text(64), bundle: integer(1, 16), predicts: { type: "array", minItems: 1, maxItems: 4, items: PREDICTION } }, ["id", "title", "hypothesis"]);
112
147
 
113
148
  export const ARES_TOOLS: readonly McpTool[] = [
114
149
  { name: "ares_retention_inspect", description: "Inspect executor-local retained identities, quota reservations and tombstones without a study write. Active sources/consumers remain explicit; no artifact bodies are returned.", inputSchema: obj({study, offset: integer(0, 16_000_000), limit: integer(1, 500)}, ["study"]), annotations: {...read, openWorldHint: true} },
115
150
  { name: "ares_retention_prune", description: "Preview explicit retained references by default. Confirm the returned fingerprint to dispose bytes under current design policy; active producers/consumers refuse. Tombstones preserve provenance. Executor tombstones remain authoritative after a crash before the local audit receipt; inspect them before retrying.", inputSchema: obj({study, refs: RETAINED_REFS, fingerprint: {...text(64), minLength: 64}}, ["study", "refs"]), annotations: {...net, destructiveHint: true} },
116
- {name: "ares_lesson_propose", description: "Propose a bounded lesson from a closed native harness round. Inspect required evidence/counterevidence explicitly; fixture-only single-task observations never establish real behavior, success or transfer.", inputSchema: obj({study, proposal: {type: "object"}}, ["study", "proposal"]), annotations: net},
151
+ {name: "ares_lesson_propose", description: "Propose a bounded lesson from a closed native harness round. Inspect required evidence/counterevidence explicitly; fixture-only single-task observations never establish real behavior, success or transfer. The handler validates the proposal shape and refuses unknown fields.", inputSchema: obj({study, proposal: HANDLER_VALIDATED}, ["study", "proposal"]), annotations: net},
117
152
  {name: "ares_lesson_list", description: "Read stored lesson proposals and dispositions locally, without current source checks. Stored eligibility is not fresh proof; no body or activation.", inputSchema: obj({study}, ["study"]), annotations: read},
118
153
  {name: "ares_lesson_check", description: "Explicitly recheck a lesson's current native closure and screened evidence/counterevidence without writing. Integrity never establishes support; no body is retained.", inputSchema: obj({study, name: text(64)}, ["study", "name"]), annotations: {...read, openWorldHint: true}},
119
154
  {name: "ares_lesson_decide", description: "Record a hash-bound lesson disposition. Acceptance rechecks sources under the study lock and requires exact fixture-strength acknowledgement; not adoption, activation or transfer evidence.", inputSchema: obj({study, name: text(64), decision: obj({decision: {type: "string", enum: ["accept", "reject", "withdraw"]}, proposalSha256: text(64), evidenceFingerprint: text(64), reason: text(2000), acknowledgeStrength: text(1000)}, ["decision", "proposalSha256", "evidenceFingerprint", "reason"])}, ["study", "name", "decision"]), annotations: net},
120
155
  { name: "ares_skill_check", description: "Explicit read-only source check of a proposal under one 25s/256KiB aggregate response budget. Evidence and counterevidence share the same owner-screened exact-id/local snapshot rules. Integrity/outcome never imply support; no body, export or installation.", inputSchema: obj({study, name: text(64)}, ["study", "name"]), annotations: {...read, openWorldHint: true} },
121
- { name: "ares_harness_close", description: "Preview/confirm an immutable baseline-kept, inconclusive or withdrawn closure without any adoption. Record binding, current evidence fingerprint, outcome, actor and reason; source/evidence drift marks it stale and preserves it. Never scientific success or transfer.", inputSchema: obj({study, round: text(64), closure: {type: "object"}, confirm: text(64)}, ["study", "round", "closure"]), annotations: write },
122
- { name: "ares_harness_contrast", description: "Record an actor-attributed fixture contrast against current admitted probe/output hashes and evidence fingerprint. Subjective judgments stay separate from task checks; no native metric or transfer authority.", inputSchema: obj({study, round: text(64), contrast: {type: "object"}}, ["study", "round", "contrast"]), annotations: write },
123
- { name: "ares_harness_compose", description: "Record per-section keep/drop/revise decisions linked to current contrasts, declaring at most one successor hash. A new successor remains unexecuted until its own exact fixture execution; real evidence is unavailable.", inputSchema: obj({study, round: text(64), composition: {type: "object"}}, ["study", "round", "composition"]), annotations: write },
124
- { name: "ares_harness_adopt", description: "Preview an experimental fixture-only adoption with a distinct independent deterministic check (unavailable for current fixtures); confirm its returned fingerprint to commit disposition and closure together under the round gate. Does not create correctness, scientific success or demonstrated transfer.", inputSchema: obj({study, round: text(64), decision: {type: "object"}, confirm: text(64)}, ["study", "round", "decision"]), annotations: write },
125
- { name: "ares_harness_stream_set", description: "Fix an immutable ordered 1..16-task experiment stream before its first harness round. No source reads or execution.", inputSchema: obj({study, stream: {type: "object"}}, ["study", "stream"]), annotations: write },
156
+ { name: "ares_harness_close", description: "Preview/confirm an immutable baseline-kept, inconclusive or withdrawn closure without any adoption. Record binding, current evidence fingerprint, outcome, actor and reason; source/evidence drift marks it stale and preserves it. Never scientific success or transfer. The handler validates the closure shape and refuses unknown fields.", inputSchema: obj({study, round: text(64), closure: HANDLER_VALIDATED, confirm: text(64)}, ["study", "round", "closure"]), annotations: write },
157
+ { name: "ares_harness_contrast", description: "Record an actor-attributed fixture contrast against current admitted probe/output hashes and evidence fingerprint. Subjective judgments stay separate from task checks; no native metric or transfer authority. The handler validates the contrast shape and refuses unknown fields.", inputSchema: obj({study, round: text(64), contrast: HANDLER_VALIDATED}, ["study", "round", "contrast"]), annotations: write },
158
+ { name: "ares_harness_compose", description: "Record per-section keep/drop/revise decisions linked to current contrasts, declaring at most one successor hash. A new successor remains unexecuted until its own exact fixture execution; real evidence is unavailable. The handler validates the composition shape and refuses unknown fields.", inputSchema: obj({study, round: text(64), composition: HANDLER_VALIDATED}, ["study", "round", "composition"]), annotations: write },
159
+ { name: "ares_harness_adopt", description: "Preview an experimental fixture-only adoption with a distinct independent deterministic check (unavailable for current fixtures); confirm its returned fingerprint to commit disposition and closure together under the round gate. Does not create correctness, scientific success or demonstrated transfer. The handler validates the decision shape and refuses unknown fields.", inputSchema: obj({study, round: text(64), decision: HANDLER_VALIDATED, confirm: text(64)}, ["study", "round", "decision"]), annotations: write },
160
+ { name: "ares_harness_stream_set", description: "Fix an immutable ordered 1..16-task experiment stream before its first harness round. No source reads or execution. The handler validates the stream shape and refuses unknown fields.", inputSchema: obj({study, stream: HANDLER_VALIDATED}, ["study", "stream"]), annotations: write },
126
161
  { name: "ares_harness_stream_show", description: "Read the receipted immutable local harness stream without writes or source reads.", inputSchema: obj({study}, ["study"]), annotations: read },
127
- { name: "ares_experience_select", description: "Rank project lessons, then screen only explicit full ids backed by earlier same-study accepted unchanged lesson/archive receipts. Fixture-only preparation, never live/controlled eligibility; stores no bodies or memory writes.", inputSchema: obj({study, selection: {type: "object"}}, ["study", "selection"]), annotations: {...read, openWorldHint: true} },
128
- { name: "ares_experience_freeze", description: "Freeze immutable body-free source pins before a round. Empty controls or screened earlier reviewed/archived fixture lessons only; model/runtime/toolset must match. Synthetic context refuses controlled/live use. No activation or memory write.", inputSchema: obj({study, context: {type: "object"}}, ["study", "context"]), annotations: net },
162
+ { name: "ares_experience_select", description: "Rank project lessons, then screen only explicit full ids backed by earlier same-study accepted unchanged lesson/archive receipts. Fixture-only preparation, never live/controlled eligibility; stores no bodies or memory writes. The handler validates the selection shape and refuses unknown fields.", inputSchema: obj({study, selection: HANDLER_VALIDATED}, ["study", "selection"]), annotations: {...read, openWorldHint: true} },
163
+ { name: "ares_experience_freeze", description: "Freeze immutable body-free source pins before a round. Empty controls or screened earlier reviewed/archived fixture lessons only; model/runtime/toolset must match. Synthetic context refuses controlled/live use. No activation or memory write. The handler validates the context shape and refuses unknown fields.", inputSchema: obj({study, context: HANDLER_VALIDATED}, ["study", "context"]), annotations: net },
129
164
  { name: "ares_experience_check", description: "Pre-handoff local integrity and model/runtime check plus owning screened exact-id source recheck. Unavailable/changed sources block the frozen context. Does not launch improvement or worker sessions.", inputSchema: obj({study, round: text(64), model: text(HARNESS_MODEL_BYTES), runtime: text(128), toolsetSha256: text(64)}, ["study", "round", "model", "runtime"]), annotations: {...read, openWorldHint: true} },
130
- { name: "ares_harness_set", description: "Set an experiment's bounded ares-owned harness round definition; no model/probe launch. Guidance and frozen refs bind a separate harness gate.", inputSchema: obj({study, round: {type: "object"}}, ["study", "round"]), annotations: write },
165
+ { name: "ares_harness_set", description: "Set an experiment's bounded ares-owned harness round definition; no model/probe launch. Guidance and frozen refs bind a separate harness gate. The handler validates the round shape and refuses unknown fields.", inputSchema: obj({study, round: HANDLER_VALIDATED}, ["study", "round"]), annotations: write },
131
166
  { name: "ares_harness_show", description: "Read local harness definitions and synthetic fixture declarations. End-to-end evaluation and real producer import stay unavailable.", inputSchema: obj({study, round: text(64)}, ["study"]), annotations: read },
132
- { name: "ares_harness_import", description: "Record a declared ares-owned synthetic probe fixture under the round gate. Not producer wire import, host-observed evidence or a matched execution; never starts probes.", inputSchema: obj({study, round: text(64), fixture: {type: "object"}}, ["study", "round", "fixture"]), annotations: write },
167
+ { name: "ares_harness_import", description: "Record a declared ares-owned synthetic probe fixture under the round gate. Not producer wire import, host-observed evidence or a matched execution; never starts probes. The handler validates the fixture shape and refuses unknown fields.", inputSchema: obj({study, round: text(64), fixture: HANDLER_VALIDATED}, ["study", "round", "fixture"]), annotations: write },
133
168
  { name: "ares_lineage_show", description: "Read bounded local source-proven lineage, optionally rooted at a local ExecutionReferenceV1 and continued with an opaque cursor. No executor, hub, network, repair, gate decision or result authority.", inputSchema: obj({ study, root: EXECUTION_REFERENCE, cursor: text(4096) }, ["study"]), annotations: read },
134
169
  { name: "ares_lineage_compare", description: "Compare existing source-derived attempt or closed-candidate rows. Select either 1..8 attempts or 1..8 full candidate commits. Failed/unknown outcomes remain visible; retries are not independent samples. No new arithmetic aggregation, winner or verdict.", inputSchema: obj({ study, attempts: LINEAGE_ATTEMPTS, candidates: LINEAGE_CANDIDATES }, ["study"]), annotations: read },
135
170
  { name: "ares_autonomy_show", description: "Read the study autonomy policy and effective mode for each phase; no writes.", inputSchema: obj({ study }, ["study"]), annotations: read },
@@ -156,6 +191,8 @@ export const ARES_TOOLS: readonly McpTool[] = [
156
191
  { name: "ares_gate", description: "List gates, or approve/reject scope, screen, design, final, review, plan:node-id, accept:hypotheses|paper|reviews or harness:<round-id>. Copilot accepts bind current draft hashes and are never automatic. Plan approvals bind all upstream output references and need complete upstream outputs; skip never bypasses them. The ledger records the actor; approval authority is workspace policy.", inputSchema: obj({ study, action: { type: "string", enum: ["list", "approve", "reject"] }, gate: text(PLAN_GATE_BYTES), reason }, ["study", "action"]), annotations: write },
157
192
  { name: "ares_idea_add", description: "Add an experiment idea to the ledger, with optional existing parent and frozen commit. Unique run-name ids and commit ownership; at most 1000 ideas. Starts no work.", inputSchema: obj({ study, idea: IDEA }, ["study", "idea"]), annotations: write },
158
193
  { name: "ares_idea_decide", description: "Record refine/pivot with a reason of at most 2000 bytes. Ideas with commits require terminal own-commit attempts (at most 200). Untested ideas omit attempts to attach a first commit or pivot. Refine requires --commit with unique idea ownership; Pivot accepts optional cause/retryWhen (2000 bytes each); refine refuses them. Pivot rejects commit and closes further decisions. Starts no work.", inputSchema: obj({ study, id: text(64), decision: { type: "string", enum: ["refine", "pivot"] }, reason: text(2000), cause: text(2000), retryWhen: text(2000), attempts: { type: "array", maxItems: 200, items: attemptId }, commit: { type: "string", minLength: 40, maxLength: 40 } }, ["study", "id", "decision", "reason"]), annotations: write },
194
+ { name: "ares_idea_categories", description: "Declare the study-local idea category vocabulary (1..32 names) in design/idea-categories.json. Later idea add refuses unknown categories. A planning aid outside the design seal; starts no work.", inputSchema: obj({ study, categories: obj({ v: { type: "integer", enum: [1] }, categories: { type: "array", minItems: 1, maxItems: 32, items: text(64) } }, ["v", "categories"]) }, ["study", "categories"]), annotations: write },
195
+ { name: "ares_idea_report", description: "Read an advisory idea report: prediction timing and hit/miss against the investigation pairing, unpredicted regressions, per-category recent gain, confounded bundles, stalled search and untried categories. Writes nothing, opens no gate.", inputSchema: obj({ study, run: text(64), window: integer(1, 1000) }, ["study"]), annotations: read },
159
196
  { name: "ares_investigate_show", description: "Read investigation candidate/baseline paired-seed scores, winner or no-winner reason and all run attempt totals/exclusions. No executor or network calls.", inputSchema: obj({ study }, ["study"]), annotations: read },
160
197
  { name: "ares_investigate_close", description: "Close the selected investigation run after all its attempts stop. Write a deterministic winner or no-winner result and ledger receipt; identical inputs write nothing. The no-arg investigate.close plan step emits {sha256,winner} for gates. Starts no attempts.", inputSchema: obj({ study }, ["study"]), annotations: write },
161
198
  { name: "ares_ablate_add", description: "Declare what a unique frozen ablation removes, at most 200 declarations. Winner/baseline commits are refused. Requires a current closed investigation winner; writes one journal event and starts no work.", inputSchema: obj({ study, ablation: obj({ id: text(64), commit: { type: "string", minLength: 40, maxLength: 40 }, removes: text(2000) }, ["id", "commit", "removes"]) }, ["study", "ablation"]), annotations: write },
@@ -165,6 +202,7 @@ export const ARES_TOOLS: readonly McpTool[] = [
165
202
  { name: "ares_final_close", description: "Close one-shot reserved-seed evaluation under the currently approved final gate. Re-approval keeps first attempt data fixed; later retries never replace it. Winner changes cannot buy a new final; changed protocol is not comparable. Refuses running or missing decisive attempts; writes deterministic qualified/not_qualified with unchanged inputs a no-op. The no-arg final.close plan step emits {sha256,status}; both qualification outcomes complete the step.", inputSchema: obj({ study }, ["study"]), annotations: write },
166
203
  { name: "ares_final_seeds", description: "Reserve unused unique declared protocol seeds for final evaluation (new/changed values reject prior use in every run/status), at least one and at most half the declared seeds. New/changed raw file bytes join the design seal; identical bytes are a no-op. Experiment mode only; starts no work.", inputSchema: obj({ study, final: obj({ v: { type: "integer", enum: [1] }, seeds: { type: "array", minItems: 1, maxItems: 500, items: seed } }, ["v", "seeds"]) }, ["study", "final"]), annotations: write },
167
204
  { name: "ares_selection_set", description: "Set a declared investigation selection rule before results: run (not reserved ablate/final/posthoc), primary metric, frozen baseline commit, minimum paired seeds and nonnegative improvement. Changes reopen the design gate; identical bytes leave the cutoff unchanged. Requires experiment mode and a protocol; starts no investigation or executor.", inputSchema: obj({ study, selection: SELECTION }, ["study", "selection"]), annotations: write },
205
+ { name: "ares_selection_calibrate", description: "Record a recommended minimum delta from baseline variance (or paired A/A deltas for identical trees). Requires three non-reserved seeds. Never changes the selection rule or starts attempts.", inputSchema: obj({ study, fromRun: text(64), nullCommit: { type: "string", minLength: 40, maxLength: 40 }, z: { type: "number", minimum: 0 } }, ["study", "fromRun"]), annotations: write },
168
206
  { name: "ares_protocol_set", description: "Set an experiment protocol after bounded validation of protocol and task/. Sealed identity changes reopen design approval; same-identity input locator-only edits preserve approval. Comparable attempt identity excludes budget and input locators.", inputSchema: obj({ study, protocol: PROTOCOL }, ["study", "protocol"]), annotations: write },
169
207
  { name: "ares_executor_set", description: "Configure local or SSH Docker execution with an explicit private absolute workdir. Stores the host alias only, never credentials. Optional gpu settings enable a one-pass device/memory/load admission check; failed admission defers without an attempt.", inputSchema: obj({ study, kind: { type: "string", enum: ["local", "ssh"] }, host: text(128), workdir: text(4096), retentionCapBytes: integer(1, 1024 ** 4), gpu: obj({ devices: { type: "array", minItems: 1, maxItems: 64, items: { type: ["string", "integer"], maxLength: 40 } }, minFreeMemoryMb: integer(0, 2147483647), maxLoadRatio: { type: "number", exclusiveMinimum: 0, maximum: 1000000 } }, ["devices", "minFreeMemoryMb", "maxLoadRatio"]) }, ["study", "kind", "workdir"]), annotations: write },
170
208
  { name: "ares_executor_inputs_hash", description: "Hash a pre-staged input directory on the configured local or SSH executor host. Returns only sha256, files and bytes; never copies input paths or bodies into the study. Read-only external host access, with no gate or ledger write.", inputSchema: obj({ study, path: text(4096) }, ["study", "path"]), annotations: { ...read, openWorldHint: true } },
@@ -188,12 +226,17 @@ export const ARES_TOOLS: readonly McpTool[] = [
188
226
  { name: "ares_lit_bib", description: "Write refs/references.bib from included and verified candidates. Needs the screen gate. Citekeys never change once assigned.", inputSchema: obj({ study }, ["study"]), annotations: write },
189
227
  { name: "ares_review_add", description: "Record a bounded current-evidence-hash review with self-reported model family and checklist. Contradictions are always blocking; 100 reports per build, 200 findings per report, 4000-byte texts and a 60 KiB combined payload ceiling. Starts no build or controller.", inputSchema: obj({ study, review: REVIEW }, ["study", "review"]), annotations: write },
190
228
  { name: "ares_review_resolve", description: "Resolve a recorded review-id/finding-id with an explicit reason and actor. No votes or automatic contradiction resolution; historical reports stay in the ledger.", inputSchema: obj({ study, target: text(257), reason: text(4000) }, ["study", "target", "reason"]), annotations: write },
191
- { name: "ares_review_show", description: "Read current build/check readiness, review families, checklists and unresolved blocking findings. Claims readiness is unavailable (agent-hub#931) and nonblocking. Starts no network, build or controller.", inputSchema: obj({ study }, ["study"]), annotations: read },
229
+ { name: "ares_review_show", description: "Read current build/check readiness, review families, checklists, reviewer read-backs beside plan point claims (never matched or scored) and unresolved blocking findings. Claims readiness is unavailable (agent-hub#931) and nonblocking. Starts no network, build or controller.", inputSchema: obj({ study }, ["study"]), annotations: read },
192
230
  { name: "ares_review_checklist", description: "List the six optional survey checklist keys with their questions, the same wording reviewers answer in checklist.survey. Answers are displayed and never gate. Opens no study.", inputSchema: obj({}, []), annotations: read },
193
- { name: "ares_paper_plan_set", description: "Validate and atomically store a declared citation routing plan, at most 64 sections/300 keys per section and 64 KiB. Only current included, identifier-verified bibliography keys. Optional writing points (40 per section) require citation presence in their own anchor windows; claims/evidence never establish support. Points select stored v2; no points keep v1. No automatic routing or relevance judgment. Starts no build/controller/network calls.", inputSchema: obj({study, plan: PAPER_PLAN}, ["study", "plan"]), annotations: write },
194
- { name: "ares_paper_plan_show", description: "Read the optional paper citation plan and routing coverage (included references routed/total). Revalidates current references; starts no build/controller/network calls or writes.", inputSchema: obj({study}, ["study"]), annotations: read },
195
- { name: "ares_paper_build", description: "Check the bounded manuscript and refuse blocking findings before writing. Commit rendered Markdown, v1 evidence without a plan or v2 plan-bound evidence, and paper.built together; identical inputs/outputs record nothing. Unknown evidence versions are preserved. The no-arg paper.build plan step emits the committed evidence {sha256} for downstream gates. Starts no controller, executor or network calls.", inputSchema: obj({ study }, ["study"]), annotations: write },
196
- { name: "ares_paper_check", description: "Read-only manuscript readiness check: positioned bare-number, placeholder, citation, optional paper-plan scope and missing-negative-result findings plus every literal escape. Experiment numbers require closed evidence; survey checks citations and refuses experiment refs. Reads bounded paper/manuscript.md, starts no build/controller/network calls.", inputSchema: obj({ study }, ["study"]), annotations: read },
231
+ { name: "ares_paper_plan_set", description: "Validate and atomically store a declared citation routing plan, at most 64 sections/300 keys per section and 64 KiB. Only current included, identifier-verified bibliography keys. Optional experiment dependencies (at most 200; dataset, metric, baseline, model, method or software) each carry verified cites or a written waiver and select stored v3. Optional writing points (40 per section) require citation presence in their own anchor windows; claims/evidence never establish support. Points select stored v2; no dependencies or points keep v1. No automatic routing or relevance judgment. Starts no build/controller/network calls.", inputSchema: obj({study, plan: PAPER_PLAN}, ["study", "plan"]), annotations: write },
232
+ { name: "ares_paper_plan_show", description: "Read the optional paper citation plan, routing coverage (included references routed/total) and dependency coverage (cited/waived/total). Revalidates current references; starts no build/controller/network calls or writes.", inputSchema: obj({study}, ["study"]), annotations: read },
233
+ { name: "ares_paper_build", description: "Check the bounded manuscript or slides and refuse blocking findings before writing. Commit rendered Markdown, versioned evidence, and paper.built together; identical inputs/outputs record nothing. Unknown evidence versions are preserved. The no-arg paper.build plan step emits the committed evidence {sha256} for downstream gates. Starts no controller, executor or network calls.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: write },
234
+ { name: "ares_paper_render_record", description: "Record an externally rendered document of the current build under paper/build/render/ with its renderReceipt v1 and one paper.rendered event. Refuses before any write unless the receipt's evidence and manuscript hashes match the current build and the file's SHA-256 matches a receipt output; regular files only, at most 64 MiB. Identical file and receipt record nothing. Never runs a renderer or judges fidelity.", inputSchema: obj({ study, doc: paperDoc, file: text(4096), receipt: text(4096) }, ["study", "file", "receipt"]), annotations: write },
235
+ { name: "ares_paper_render_show", description: "Read-only: the last recorded render and whether it matches the current build. A rebuild with a new evidence hash makes it stale without deleting it.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: read },
236
+ { name: "ares_renderer_set", description: "Set this machine's renderer for the study: an argv array (program first, then arguments with {study} and {out} placeholders) and an optional wall time in seconds. Stored under the family home, never in the study or plan.json; the paper.render plan step runs it.", inputSchema: obj({ study, command: { type: "array", minItems: 1, maxItems: 64, items: text(4096) }, timeoutS: { type: "integer", minimum: 1, maximum: 86400 } }, ["study", "command"]), annotations: write },
237
+ { name: "ares_renderer_show", description: "Read-only: this machine's renderer for the study, or that none is configured.", inputSchema: obj({ study }, ["study"]), annotations: read },
238
+ { name: "ares_renderer_check", description: "Read-only: check the renderer configuration and that its program is on PATH, without running it.", inputSchema: obj({ study }, ["study"]), annotations: read },
239
+ { name: "ares_paper_check", description: "Read-only manuscript readiness check: positioned bare-number, placeholder, citation, optional paper-plan scope and missing-negative-result findings plus every literal escape. Experiment numbers require closed evidence; survey checks citations and refuses experiment refs. Reads bounded paper/manuscript.md or paper/slides.md, starts no build/controller/network calls.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: read },
197
240
  { name: "ares_cite_check", description: "Check [@key] citations in a draft against verified references; lists unknown and unverified keys.", inputSchema: obj({ study, draft: { type: "string", minLength: 1, maxLength: 4096 } }, ["study", "draft"]), annotations: read },
198
241
  { name: "ares_playbook", description: "Standalone literature, experiment and plan/conductor workflows, CLI-only controller startup, gate rules and evidence boundaries.", inputSchema: obj({}, []), annotations: read },
199
242
  ];
@@ -252,6 +295,8 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
252
295
  ares_scope_set: a => ops.scope(dir(a), a.scope, ctx),
253
296
  ares_idea_add: a => ops.ideaAdd(dir(a), a.idea, ctx),
254
297
  ares_idea_decide: a => ops.ideaDecide(dir(a), a.id as string, { decision: a.decision, reason: a.reason, ...(a.cause !== undefined ? { cause: a.cause } : {}), ...(a.retryWhen !== undefined ? { retryWhen: a.retryWhen } : {}), ...(a.attempts !== undefined ? { attempts: a.attempts } : {}), ...(a.commit !== undefined ? { commit: a.commit } : {}) }, ctx),
298
+ ares_idea_categories: a => ops.ideaCategories(dir(a), a.categories, ctx),
299
+ ares_idea_report: a => ops.ideaReport(dir(a), { ...(a.run !== undefined ? { run: a.run as string } : {}), ...(a.window !== undefined ? { window: a.window as number } : {}) }),
255
300
  ares_investigate_show: a => ops.investigateShow(dir(a)),
256
301
  ares_investigate_close: a => ops.investigateClose(dir(a), ctx),
257
302
  ares_ablate_add: a => ops.ablateAdd(dir(a), a.ablation, ctx),
@@ -261,6 +306,11 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
261
306
  ares_final_close: a => ops.finalClose(dir(a), ctx),
262
307
  ares_final_seeds: a => ops.finalSeeds(dir(a), a.final, ctx),
263
308
  ares_selection_set: a => ops.selection(dir(a), a.selection, ctx),
309
+ ares_selection_calibrate: a => ops.selectionCalibrate(dir(a), {
310
+ fromRun: a.fromRun as string,
311
+ ...(a.nullCommit === undefined ? {} : { nullCommit: a.nullCommit as string }),
312
+ ...(a.z === undefined ? {} : { z: a.z as number }),
313
+ }, ctx),
264
314
  ares_protocol_set: a => ops.protocol(dir(a), a.protocol, ctx),
265
315
  ares_harness_set: a => ops.harnessSet(dir(a), a.round, ctx),
266
316
  ares_harness_show: a => ops.harnessShow(dir(a), a.round as string | undefined),
@@ -294,10 +344,15 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
294
344
  ares_review_resolve: a => ops.reviewResolve(dir(a), a.target as string, a.reason as string, ctx),
295
345
  ares_review_show: a => ops.reviewShow(dir(a)),
296
346
  ares_review_checklist: () => ops.reviewChecklistShow(),
297
- ares_paper_build: a => ops.paperBuild(dir(a), ctx),
347
+ ares_paper_build: a => ops.paperBuild(dir(a), ctx, paperDocument(a.doc)),
348
+ ares_paper_render_record: a => ops.paperRenderRecord(dir(a), absolute(a.file, "file"), absolute(a.receipt, "receipt"), ctx, paperDocument(a.doc)),
349
+ ares_paper_render_show: a => ops.paperRenderShow(dir(a), paperDocument(a.doc)),
350
+ ares_renderer_set: a => ops.rendererSet(dir(a), { command: a.command, ...(a.timeoutS !== undefined ? { timeoutS: a.timeoutS } : {}) }, env),
351
+ ares_renderer_show: a => ops.rendererShow(dir(a), env),
352
+ ares_renderer_check: a => ops.rendererCheck(dir(a), env),
298
353
  ares_paper_plan_set: a => ops.paperPlanSet(dir(a), a.plan, ctx),
299
354
  ares_paper_plan_show: a => ops.paperPlanShow(dir(a)),
300
- ares_paper_check: a => ops.paperCheck(dir(a)),
355
+ ares_paper_check: a => ops.paperCheck(dir(a), paperDocument(a.doc)),
301
356
  ares_cite_check: a => ops.cite(dir(a), absolute(a.draft, "draft")),
302
357
  ares_playbook: () => ({ playbook: PLAYBOOK }),
303
358
  };
@@ -1,8 +1,11 @@
1
+ import { paperEventFor } from "../paper/document.ts";
1
2
  import {recheckLessonExports, boundLessonExportBatch} from "../harness/lesson-candidates.ts";
2
3
  import type {SkillCheckOptions} from "./skill-check.ts";
3
4
  import { ACCEPT_ARTIFACTS } from "../autonomy.ts";
4
5
  import { requireCopilotAccept } from "../copilot.ts";
5
- import { commit, prepareCommit, openStudy, plain, sha256, type Actor, type LedgerEvent } from "../study.ts";
6
+ import { commit, prepareCommit, openStudy, plain, readLedger, sha256, type Actor, type LedgerEvent } from "../study.ts";
7
+ import { renderSummary } from "../paper/render.ts";
8
+ const readLedgerSafe = (dir: string) => { try { return readLedger(dir); } catch { return []; } };
6
9
  import { canonical } from "../plan/state.ts";
7
10
  import { createAmemClient, type AmemNote } from "./amem.ts";
8
11
  import { deriveLessons, readLessonSources } from "./lessons.ts";
@@ -10,7 +13,7 @@ import type { ProcessRunner } from "../exp/executor.ts";
10
13
 
11
14
  export const ARCHIVE_NOTES = 200;
12
15
  export interface ArchiveReceipt { sha256: string; id: string }
13
- export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
16
+ export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[]; render?: { current: boolean; reason: string | null } }
14
17
  export interface ArchiveResult extends ArchivePreview { written: ArchiveReceipt[]; remaining: number }
15
18
  /** Carries receipt progress for adapters; CLI/MCP retain the existing retry instruction verbatim. */
16
19
  export class ArchivePartialError extends Error {
@@ -43,7 +46,9 @@ export function previewArchive(dir: string): ArchivePreview {
43
46
  const sources = readLessonSources(dir), notes = deriveLessons(sources), known = new Set(archiveReceiptIndex(sources.events).keys());
44
47
  const unique = new Map(notes.map(note => [sha256(canonical(note)), note]));
45
48
  const pending = [...unique].filter(([hash]) => !known.has(hash)).map(([sha256, note]) => ({ sha256, note }));
46
- return {fingerprint: sha256(canonical(notes)), notes: pending, ...(sources.contrastNotes?.length ? {recovery: "Receipt-only dedupe: if an earlier archive was interrupted after amem add, operator reconciliation is required before retry; unreceipted writes cannot be detected and may duplicate"} : {})};
49
+ // Render status is display-only and never enters the fingerprint; shown once a render was recorded (#162).
50
+ const render = readLedgerSafe(dir).some(event => paperEventFor(event, "paper.rendered")) ? { render: renderSummary(dir) } : {};
51
+ return {fingerprint: sha256(canonical(notes)), notes: pending, ...render, ...(sources.contrastNotes?.length ? {recovery: "Receipt-only dedupe: if an earlier archive was interrupted after amem add, operator reconciliation is required before retry; unreceipted writes cannot be detected and may duplicate"} : {})};
47
52
  }
48
53
  /** Preview and confirmed export use the same note/source bounds and ordered prefix. */
49
54
  export function archiveExportBatch(dir: string, notes: ArchivePreview["notes"]) {
@@ -1,8 +1,10 @@
1
+ import { paperDocument, paperEventFor, paperSourcePath, type PaperDocument } from "./document.ts";
2
+ import { figuresStillMatch, validFigureEvidence, type FigureEvidence } from "./figures.ts";
1
3
  import { requireCopilotAccept } from "../copilot.ts";
2
4
  import { existsSync } from "node:fs";
3
- import { join } from "node:path";
5
+ import { basename, join } from "node:path";
4
6
  import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, sha256, type Actor } from "../study.ts";
5
- import { checkPaper, manuscriptPath } from "./check.ts";
7
+ import { checkPaper } from "./check.ts";
6
8
  import { MANUSCRIPT_BYTES } from "./placeholders.ts";
7
9
  import { readPaperPlanSnapshot } from "./plan.ts";
8
10
 
@@ -15,41 +17,50 @@ interface EvidenceBody {
15
17
  source: { file: string; sha256: string };
16
18
  }[];
17
19
  }
18
- export type PaperEvidence = EvidenceBody & ({ v: 1 } | { v: 2; planSha256: string });
20
+ export type PaperEvidence = EvidenceBody & ({ v: 1 } | { v: 2; planSha256: string } | { v: 3; planSha256: string; figures: FigureEvidence[] });
19
21
  /** Legacy evidence stays readable; plan-bound evidence requires a reader that understands its binding. */
20
- export function paperEvidenceVersion(raw: unknown): 1 | 2 {
21
- if (!plain(raw) || (raw.v !== 1 && raw.v !== 2)) throw new Error("paper evidence: unsupported version; use an ares version that supports it, keeping paper/build/evidence.json unchanged");
22
+ export function paperEvidenceVersion(raw: unknown): 1 | 2 | 3 {
23
+ if (!plain(raw) || (raw.v !== 1 && raw.v !== 2 && raw.v !== 3)) throw new Error("paper evidence: unsupported version; use an ares version that supports it, keeping paper/build/evidence.json unchanged");
22
24
  if (raw.v === 2 && (Object.keys(raw).some(key => !["v", "manuscriptSha256", "placeholders", "planSha256"].includes(key)) || typeof raw.planSha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.planSha256))) throw new Error("paper evidence: invalid v2 plan binding or unknown field; restore the last valid paper/build/evidence.json, then run ares paper check and paper build");
25
+ if (raw.v === 3 && (Object.keys(raw).some(key => !["v", "manuscriptSha256", "placeholders", "planSha256", "figures"].includes(key))
26
+ || typeof raw.planSha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.planSha256) || !validFigureEvidence(raw.figures))) {
27
+ throw new Error("paper evidence: invalid v3 plan binding or figure evidence; restore paper/build/evidence.json, then run ares paper check and paper build");
28
+ }
23
29
  return raw.v;
24
30
  }
25
- export function paperBuildPaths(dir: string) { return { manuscript: join(dir, "paper", "build", "manuscript.md"), evidence: join(dir, "paper", "build", "evidence.json") }; }
31
+ export function paperBuildPaths(dir: string, doc: PaperDocument = "manuscript") {
32
+ return { manuscript: join(dir, "paper", "build", `${doc}.md`), evidence: join(dir, "paper", "build", doc === "slides" ? "slides.evidence.json" : "evidence.json") };
33
+ }
26
34
  function previous(file: string, bound: number): string | undefined {
27
35
  if (!existsSync(file)) return undefined;
28
36
  try { return readTextBounded(file, bound); }
29
- catch { throw new Error(`paper build: previous output is unreadable, non-regular, invalid UTF-8 or oversized; restore the last valid ${file.endsWith("evidence.json") ? "paper/build/evidence.json" : "paper/build/manuscript.md"} before rebuilding`); }
37
+ catch { throw new Error(`paper build: previous output is unreadable, non-regular, invalid UTF-8 or oversized; restore the last valid paper/build/${basename(file)} before rebuilding`); }
30
38
  }
31
- function evidenceBytes(dir: string): string | undefined {
32
- const oldEvidence = previous(paperBuildPaths(dir).evidence, PAPER_EVIDENCE_BYTES);
39
+ function evidenceBytes(dir: string, doc: PaperDocument): string | undefined {
40
+ const oldEvidence = previous(paperBuildPaths(dir, doc).evidence, PAPER_EVIDENCE_BYTES);
33
41
  if (oldEvidence !== undefined) {
34
42
  let raw: unknown;
35
- try { raw = JSON.parse(oldEvidence); } catch { throw new Error("paper evidence: invalid JSON; restore the last valid paper/build/evidence.json before rebuilding"); }
43
+ try { raw = JSON.parse(oldEvidence); } catch { throw new Error(`paper evidence: invalid JSON; restore the last valid paper/build/${doc === "slides" ? "slides.evidence.json" : "evidence.json"} before rebuilding`); }
36
44
  paperEvidenceVersion(raw);
37
45
  }
38
46
  return oldEvidence;
39
47
  }
40
- function calculatePaper(dir: string) {
41
- const report = checkPaper(dir);
48
+ function calculatePaper(dir: string, doc: PaperDocument) {
49
+ const report = checkPaper(dir, doc);
42
50
  if (!report.ok) {
43
51
  const blocking = report.findings.filter(f => f.severity === "blocking");
44
52
  const reasons = blocking.slice(0, 10).map(f => `${f.code} at ${f.line}:${f.column}`).join(", ");
45
- throw new Error(`paper build: paper check found ${blocking.length} blocking finding(s): ${reasons}; run ares paper check <dir> --json and fix every finding before rebuilding`);
53
+ throw new Error(`paper build: paper check found ${blocking.length} blocking finding(s): ${reasons}; run ares paper check <dir>${doc === "slides" ? " --doc slides" : ""} --json and fix every finding before rebuilding`);
46
54
  }
47
- const evidence: PaperEvidence = { ...(report.planSha256 === undefined ? { v: 1 as const } : { v: 2 as const, planSha256: report.planSha256 }), manuscriptSha256: report.manuscriptSha256, placeholders: report.placeholders.map(entry => {
55
+ const version = report.planSha256 === undefined ? { v: 1 as const }
56
+ : report.figures === undefined ? { v: 2 as const, planSha256: report.planSha256 }
57
+ : { v: 3 as const, planSha256: report.planSha256, figures: report.figures };
58
+ const evidence: PaperEvidence = { ...version, manuscriptSha256: report.manuscriptSha256, placeholders: report.placeholders.map(entry => {
48
59
  const token = entry.placeholder;
49
60
  return { kind: token.kind, raw: token.raw, start: token.start, end: token.end, line: token.line, column: token.column,
50
61
  ...(token.kind === "number" ? { ref: token.ref, ...(token.format === undefined ? {} : { format: token.format }) } : {}),
51
62
  value: entry.value, rendered: entry.rendered,
52
- source: entry.source ?? { file: "paper/manuscript.md", sha256: report.manuscriptSha256 },
63
+ source: entry.source ?? { file: `paper/${doc}.md`, sha256: report.manuscriptSha256 },
53
64
  };
54
65
  }) };
55
66
  const text = JSON.stringify(evidence, null, 2) + "\n";
@@ -58,25 +69,28 @@ function calculatePaper(dir: string) {
58
69
  return { report, evidence, text, manuscriptSha256: sha256(report.rendered), evidenceSha256: sha256(text) };
59
70
  }
60
71
  /** Caller holds the study lock. Refusals precede the single output-and-receipt commit. */
61
- export function buildPaper(dirArg: string, actor: Actor) {
72
+ export function buildPaper(dirArg: string, actor: Actor, doc: PaperDocument = "manuscript") {
73
+ paperDocument(doc);
62
74
  const { dir } = openStudy(dirArg);
63
75
  requireCopilotAccept(dir, "hypotheses");
64
- const paths = paperBuildPaths(dir), oldEvidence = evidenceBytes(dir);
65
- const { report, text, manuscriptSha256, evidenceSha256 } = calculatePaper(dir), oldManuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
66
- const receipt = readLedger(dir).findLast(event => event.type === "paper.built");
76
+ const paths = paperBuildPaths(dir, doc), oldEvidence = evidenceBytes(dir, doc);
77
+ const { report, text, manuscriptSha256, evidenceSha256 } = calculatePaper(dir, doc), oldManuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
78
+ const receipt = readLedger(dir).findLast(event => paperEventFor(event, "paper.built", doc));
67
79
  const changed = oldManuscript !== report.rendered || oldEvidence !== text || receipt?.data.manuscriptSha256 !== manuscriptSha256 || receipt.data.evidenceSha256 !== evidenceSha256;
68
- if (sha256(readTextBounded(manuscriptPath(dir), MANUSCRIPT_BYTES)) !== report.manuscriptSha256) throw new Error("paper build: source manuscript changed during checking; rerun ares paper check and paper build on the current manuscript");
69
- if (readPaperPlanSnapshot(dir)?.sha256 !== report.planSha256) throw new Error("paper build: source plan was added, removed or changed during checking; rerun ares paper check and paper build on the current paper/plan.json");
70
- if (changed) commit(dir, [[paths.manuscript, report.rendered, MANUSCRIPT_BYTES], [paths.evidence, text, PAPER_EVIDENCE_BYTES]], [{ actor, type: "paper.built", data: { manuscriptSha256, evidenceSha256, sourceManuscriptSha256: report.manuscriptSha256, ...(report.planSha256 === undefined ? {} : {planSha256: report.planSha256}) } }]);
80
+ if (sha256(readTextBounded(paperSourcePath(dir, doc), MANUSCRIPT_BYTES)) !== report.manuscriptSha256) throw new Error("paper build: source manuscript changed during checking; rerun ares paper check and paper build on the current manuscript");
81
+ if (doc === "manuscript" && readPaperPlanSnapshot(dir)?.sha256 !== report.planSha256) throw new Error("paper build: source plan was added, removed or changed during checking; rerun ares paper check and paper build on the current paper/plan.json");
82
+ if (report.figures && !figuresStillMatch(dir, report.figures)) throw new Error("paper build: figure bytes or paths changed during checking; restore the figures and rerun ares paper check and paper build");
83
+ if (changed) commit(dir, [[paths.manuscript, report.rendered, MANUSCRIPT_BYTES], [paths.evidence, text, PAPER_EVIDENCE_BYTES]], [{ actor, type: "paper.built", data: { ...(doc === "slides" ? { doc } : {}), manuscriptSha256, evidenceSha256, sourceManuscriptSha256: report.manuscriptSha256, ...(report.planSha256 === undefined ? {} : {planSha256: report.planSha256}) } }]);
71
84
  return { manuscriptSha256, evidenceSha256, changed };
72
85
  }
73
86
 
74
87
 
75
88
  /** The exact fresh build and both output receipts must agree; never repairs or writes files. */
76
- export function readCurrentBuild(dirArg: string) {
77
- const { dir } = openStudy(dirArg), paths = paperBuildPaths(dir), evidence = evidenceBytes(dir), manuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
89
+ export function readCurrentBuild(dirArg: string, doc: PaperDocument = "manuscript") {
90
+ paperDocument(doc);
91
+ const { dir } = openStudy(dirArg), paths = paperBuildPaths(dir, doc), evidence = evidenceBytes(dir, doc), manuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
78
92
  if (evidence === undefined || manuscript === undefined) throw new Error("paper build: missing output; run ares paper build before reviewing");
79
- const fresh = calculatePaper(dir), receipt = readLedger(dir).findLast(event => event.type === "paper.built");
93
+ const fresh = calculatePaper(dir, doc), receipt = readLedger(dir).findLast(event => paperEventFor(event, "paper.built", doc));
80
94
  if (evidence !== fresh.text || manuscript !== fresh.report.rendered || receipt?.data.manuscriptSha256 !== fresh.manuscriptSha256 || receipt.data.evidenceSha256 !== fresh.evidenceSha256 || receipt.data.sourceManuscriptSha256 !== fresh.report.manuscriptSha256) throw new Error("paper build: stale outputs or missing/mismatched receipt; run ares paper check and ares paper build before reviewing");
81
95
  return { manuscriptSha256: fresh.manuscriptSha256, evidenceSha256: fresh.evidenceSha256, check: fresh.report };
82
96
  }
@@ -1,3 +1,5 @@
1
+ import { paperDocument, paperSourcePath, type PaperDocument } from "./document.ts";
2
+ import { inspectFigures, type FigureFindingCode, type ImageLink } from "./figures.ts";
1
3
  import { CopilotAcceptError } from "../copilot.ts";
2
4
  import { existsSync } from "node:fs";
3
5
  import { join } from "node:path";
@@ -12,16 +14,17 @@ import { finalResultPath } from "../exp/final.ts";
12
14
  import { MANUSCRIPT_BYTES, parsePlaceholders, resolvePlaceholders } from "./placeholders.ts";
13
15
  import { hygieneFindings, readPaperSettings, type HygieneCode } from "./hygiene.ts";
14
16
  import { readPaperPlanCheckSnapshot } from "./plan.ts";
17
+ import { paperDependencyFindings, type DependencyFindingCode } from "./dependencies.ts";
15
18
  import { paperPointFindings, type PointFindingCode } from "./points.ts";
16
19
  import { paperPlanFindings, type ScopeFindingCode } from "./scopes.ts";
17
20
 
18
21
  export const MAX_CODE_NUMBERS = 500;
19
- export interface PaperFinding { code: "bare-number" | "unresolved-ref" | "unaccepted-draft" | "bad-format" | "unknown-citation" | "unverified-citation" | "missing-negative-result" | HygieneCode | ScopeFindingCode | PointFindingCode; severity: "blocking" | "warning"; section?: string[]; sectionId?: string; pointId?: string; start: number; end: number; line: number; column: number; message: string }
22
+ export interface PaperFinding { code: "bare-number" | "unresolved-ref" | "unaccepted-draft" | "bad-format" | "unknown-citation" | "unverified-citation" | "missing-negative-result" | HygieneCode | ScopeFindingCode | PointFindingCode | DependencyFindingCode | FigureFindingCode; severity: "blocking" | "warning"; section?: string[]; sectionId?: string; pointId?: string; dependencyId?: string; figureId?: string; start: number; end: number; line: number; column: number; message: string }
20
23
  function blank(text: string, mask: Uint8Array): string { return text.split("").map((char, index) => mask[index] && char !== "\n" && char !== "\r" ? " " : char).join(""); }
21
24
  function mark(mask: Uint8Array, start: number, end: number) { mask.fill(1, start, end); }
22
25
  function escaped(text: string, index: number): boolean { let slashes = 0; while (index > 0 && text[--index] === "\\") slashes++; return slashes % 2 === 1; }
23
26
  /** Masks syntax-only destinations and code while retaining original offsets. Visible link labels remain prose. */
24
- function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Array; code: Uint8Array; hidden: Uint8Array; headingHidden: Uint8Array; anchorHidden: Uint8Array } {
27
+ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Array; code: Uint8Array; hidden: Uint8Array; headingHidden: Uint8Array; anchorHidden: Uint8Array; images: ImageLink[] } {
25
28
  const mask = new Uint8Array(text.length), protectedText = new Uint8Array(text.length), tokens = parsePlaceholders(text);
26
29
  for (const token of [...tokens.placeholders, ...tokens.findings]) mark(protectedText, token.start, token.end);
27
30
  let fence: { char: string; length: number } | undefined, paragraph = false, indented = false;
@@ -74,7 +77,11 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
74
77
  if (close !== undefined) { mark(mask, runs[i]!.index, runs[close]!.index + runs[close]![0].length); i = close; }
75
78
  }
76
79
  const code = mask.slice(), anchorHidden = code.slice();
77
- const labels: number[] = [];
80
+ const labels: number[] = [], images: ImageLink[] = [];
81
+ const referenceImages: {label: string; start: number; end: number}[] = [];
82
+ const references = new Map<string, string>();
83
+ const referenceLabel = /\[([^\[\]\n]*)\]/y;
84
+ const referenceKey = (label: string) => label.trim().replace(/\s+/g, " ").toLowerCase();
78
85
  for (let i = 0; i < text.length; i++) {
79
86
  if (mask[i] || protectedText[i] || knownHidden?.[i] || (text[i] !== "<" && text[i] !== "]" && text[i] !== "[") || escaped(text, i)) continue;
80
87
  if (text[i] === "[") { labels.push(i); continue; }
@@ -84,7 +91,16 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
84
91
  }
85
92
  if (text[i] !== "]") continue;
86
93
  const label = labels.pop();
87
- if (label === undefined || text[i + 1] !== "(") continue;
94
+ if (label === undefined) continue;
95
+ const image = label > 0 && text[label - 1] === "!" && !escaped(text, label - 1);
96
+ if (text[i + 1] !== "(") {
97
+ if (image) {
98
+ referenceLabel.lastIndex = i + 1;
99
+ const reference = referenceLabel.exec(text);
100
+ referenceImages.push({label: referenceKey(reference?.[1] || text.slice(label + 1, i)), start: label - 1, end: i + 1 + (reference?.[0].length ?? 0)});
101
+ }
102
+ continue;
103
+ }
88
104
  let start = i + 2; while (/\s/.test(text[start] ?? "") && start < text.length) start++;
89
105
  let end = start, depth = 0;
90
106
  if (text[start] === "<") { end = text.indexOf(">", start + 1); if (end < 0) continue; end++; }
@@ -104,7 +120,10 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
104
120
  const quote = text[tail++]!; while (tail < text.length && (text[tail] !== quote || escaped(text, tail))) tail++;
105
121
  if (tail >= text.length) continue; tail++; while (/\s/.test(text[tail] ?? "") && tail < text.length) tail++;
106
122
  }
107
- if (text[tail] === ")") { mark(mask, start, end); mark(anchorHidden, i + 1, tail + 1); }
123
+ if (text[tail] === ")") {
124
+ mark(mask, start, end); mark(anchorHidden, i + 1, tail + 1);
125
+ if (image) images.push({target: text.slice(start, end), start: label - 1, end: tail + 1});
126
+ }
108
127
  }
109
128
  // Point anchors are comments in prose, never examples in syntax-only destinations/titles or placeholders.
110
129
  for (let i = 0; i < mask.length; i++) if (mask[i] || protectedText[i]) anchorHidden[i] = 1;
@@ -113,24 +132,30 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
113
132
  if (!code[comment.index] && !protectedText[comment.index]) { mark(mask, comment.index, comment.index + comment[0].length); mark(hidden, comment.index, comment.index + comment[0].length); hasComment = true; }
114
133
  }
115
134
  // Reference definitions do not count as visible negative-result prose; labels/titles still get numeric checks.
116
- for (const match of text.matchAll(/^ {0,3}\[[^\]\n]+\]:[ \t]*(<[^>\n]*>|[^\s]+)(?:[ \t]|$)/gm)) {
117
- const target = match[1]!, start = match.index + match[0].lastIndexOf(target);
135
+ for (const match of text.matchAll(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(<[^>\n]*>|[^\s]+)(?:[ \t]|$)/gm)) {
136
+ const target = match[2]!, start = match.index + match[0].lastIndexOf(target);
118
137
  if (!mask[start] && !protectedText[start]) {
119
138
  mark(mask, start, start + target.length);
139
+ const key = referenceKey(match[1]!);
140
+ if (!references.has(key)) references.set(key, target);
120
141
  const lineEnd = text.indexOf("\n", match.index); mark(hidden, match.index, lineEnd < 0 ? text.length : lineEnd); mark(anchorHidden, match.index, lineEnd < 0 ? text.length : lineEnd);
121
142
  }
122
143
  }
123
144
  // Reclassify once with non-code comments excluded, so a fence inside a comment cannot hide later prose.
124
145
  if (!knownHidden && hasComment) return markdownMask(text, hidden);
125
146
  const headingHidden = blockCode.slice(); for (let i = 0; i < hidden.length; i++) if (hidden[i]) headingHidden[i] = 1;
126
- return { mask, code, hidden, headingHidden, anchorHidden };
147
+ for (const reference of referenceImages) {
148
+ const target = references.get(reference.label);
149
+ if (target !== undefined) images.push({target, start: reference.start, end: reference.end});
150
+ }
151
+ return { mask, code, hidden, headingHidden, anchorHidden, images };
127
152
  }
128
- export function manuscriptPath(dir: string): string { return join(dir, "paper", "manuscript.md"); }
129
- export function checkPaper(dirArg: string) {
130
- const { dir, study } = openStudy(dirArg), file = manuscriptPath(dir), settings = readPaperSettings(dir);
153
+ export function manuscriptPath(dir: string): string { return paperSourcePath(dir, "manuscript"); }
154
+ export function checkPaper(dirArg: string, doc: PaperDocument = "manuscript") {
155
+ const { dir, study } = openStudy(dirArg), file = paperSourcePath(dir, paperDocument(doc)), settings = readPaperSettings(dir);
131
156
  let manuscript: string;
132
157
  try { manuscript = readTextBounded(file, MANUSCRIPT_BYTES); }
133
- catch { throw new Error("paper manuscript: missing, unreadable, invalid UTF-8, non-regular or larger than 2 MiB; restore paper/manuscript.md as a bounded UTF-8 regular file before paper check"); }
158
+ catch { throw new Error(`paper ${doc}: missing, unreadable, invalid UTF-8, non-regular or larger than 2 MiB; restore paper/${doc}.md as a bounded UTF-8 regular file before paper check`); }
134
159
  const masks = markdownMask(manuscript), prose = blank(manuscript, masks.mask), parsed = parsePlaceholders(prose), resolution = resolvePlaceholders(dir, prose);
135
160
  const lines = [0]; for (let i = 0; i < manuscript.length; i++) if (manuscript[i] === "\n") lines.push(i + 1);
136
161
  const location = (start: number) => {
@@ -153,7 +178,7 @@ export function checkPaper(dirArg: string) {
153
178
  }
154
179
  for (const problem of parsed.findings) { mark(numberMask, problem.start, problem.end); mark(citationMask, problem.start, problem.end); }
155
180
  const citationText = blank(manuscript, citationMask), candidates = loadCandidates(dir), citations = checkCitations(citationText, candidates);
156
- const plan = readPaperPlanCheckSnapshot(dir, candidates);
181
+ const plan = doc === "manuscript" ? readPaperPlanCheckSnapshot(dir, candidates) : undefined;
157
182
  const groups = new Map<number, number>();
158
183
  for (const hit of citationOccurrences(citationText)) {
159
184
  mark(numberMask, hit.start, hit.end); groups.set(hit.groupStart, hit.groupEnd);
@@ -169,6 +194,7 @@ export function checkPaper(dirArg: string) {
169
194
  mark(numberMask, offset, offset + numbers.length);
170
195
  }
171
196
  }
197
+ let protocolMetrics: readonly string[] = [];
172
198
  if (study.mode === "experiment") {
173
199
  for (const match of manuscript.matchAll(/^ {0,3}[0-9]+[.)](?=[ \t])/gm)) mark(numberMask, match.index, match.index + match[0].length);
174
200
  for (const match of blank(manuscript, numberMask).matchAll(/\p{Nd}+(?:[.,]\p{Nd}+)*/gu)) findings.push(finding("bare-number", match.index, match.index + match[0].length, "prose number has no evidence ref; use {{n:REF}} for a measured value or {{lit:TEXT}} for a reviewer-visible literal"));
@@ -177,7 +203,9 @@ export function checkPaper(dirArg: string) {
177
203
  };
178
204
  if (existsSync(finalResultPath(dir))) requireRef("final.status");
179
205
  try {
180
- const protocol = readProtocol(dir), rule = protocol ? readSelection(dir, protocol) : undefined;
206
+ const protocol = readProtocol(dir);
207
+ if (protocol) protocolMetrics = protocol.metrics.map(metric => metric.name);
208
+ const rule = protocol ? readSelection(dir, protocol) : undefined;
181
209
  if (rule && existsSync(investigateResultPath(dir, rule.run))) {
182
210
  try { if (readClosedInvestigation(dir).result.winner === null) requireRef("investigate.reason"); }
183
211
  catch (error) { findings.push(error instanceof CopilotAcceptError ? finding("unaccepted-draft", 0, 0, error.message) : finding("unresolved-ref", 0, 0, "investigate result is not current and closed; run ares investigate close before checking the paper")); }
@@ -191,6 +219,9 @@ export function checkPaper(dirArg: string) {
191
219
  }
192
220
  if (plan) for (const hit of paperPlanFindings(manuscript, masks.headingHidden, citationText, plan.plan, candidates)) findings.push({...hit, ...location(hit.start)});
193
221
  if (plan) for (const hit of paperPointFindings(dir, manuscript, masks.anchorHidden, masks.headingHidden, citationText, plan.plan)) findings.push({...hit, ...location(hit.start)});
222
+ if (plan) for (const hit of paperDependencyFindings(citationText, plan.plan, candidates, protocolMetrics)) findings.push({...hit, ...location(hit.start)});
223
+ const figures = plan?.plan.figures === undefined ? undefined : inspectFigures(dir, plan.plan.figures, masks.images);
224
+ if (figures) for (const hit of figures.findings) findings.push({ ...hit, ...location(hit.start) });
194
225
  let rendered = "", cursor = 0;
195
226
  for (const entry of resolution.placeholders) { rendered += manuscript.slice(cursor, entry.placeholder.start) + entry.rendered; cursor = entry.placeholder.end; }
196
227
  rendered += manuscript.slice(cursor);
@@ -204,5 +235,5 @@ export function checkPaper(dirArg: string) {
204
235
  catch (error) { unreadableCards.push({ citekey: key, id: candidate!.id, message: error instanceof Error ? error.message : "card unreadable; record it again with ares lit card" }); return []; }
205
236
  return card?.reused ? [{ citekey: key, id: candidate!.id, vault: card.reused.vault, note: card.reused.note, at: card.reused.at, provenance: card.reused.provenance }] : [];
206
237
  });
207
- return { ok: !findings.some(f => f.severity === "blocking"), settings, manuscriptSha256: sha256(manuscript), ...(plan ? {planSha256: plan.sha256} : {}), rendered, placeholders: resolution.placeholders, findings: findings.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code)), literals: resolution.literals, codeNumbers, codeNumberCount, citations, ...(reusedCards.length ? { reusedCards } : {}), ...(unreadableCards.length ? { unreadableCards } : {}) };
238
+ return { ok: !findings.some(f => f.severity === "blocking"), settings, manuscriptSha256: sha256(manuscript), ...(plan ? {planSha256: plan.sha256} : {}), rendered, ...(figures ? { figures: figures.evidence } : {}), placeholders: resolution.placeholders, findings: findings.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code)), literals: resolution.literals, codeNumbers, codeNumberCount, citations, ...(reusedCards.length ? { reusedCards } : {}), ...(unreadableCards.length ? { unreadableCards } : {}) };
208
239
  }