@staix/agent-research 0.3.1 → 0.4.1
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/CHANGELOG.md +48 -0
- package/README.md +84 -19
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +75 -13
- package/src/exp/attempts.ts +13 -1
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +98 -13
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/protocol.ts +26 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +20 -10
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
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 };
|
|
@@ -26,7 +29,20 @@ const obj = (properties: Record<string, unknown>, required: string[]) => ({ type
|
|
|
26
29
|
const text = (max: number) => ({ type: "string", minLength: 1, maxLength: max });
|
|
27
30
|
const texts = (items: number, max: number) => ({ type: "array", items: text(max), maxItems: items });
|
|
28
31
|
const year = { type: "integer", minimum: 1000, maximum: 2100 };
|
|
29
|
-
const
|
|
32
|
+
const PAPER_DEPENDENCY = obj({
|
|
33
|
+
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
|
|
34
|
+
kind: {type: "string", enum: [...PAPER_DEPENDENCY_KINDS]},
|
|
35
|
+
name: text(PAPER_PLAN_BYTES),
|
|
36
|
+
cites: {type: "array", minItems: 1, maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
37
|
+
waiver: text(PAPER_DEPENDENCY_WAIVER_BYTES),
|
|
38
|
+
}, ["id", "kind", "name"]);
|
|
39
|
+
const PAPER_FIGURE = obj({
|
|
40
|
+
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
|
|
41
|
+
file: text(PAPER_FIGURE_PATH_BYTES), kind: {type: "string", enum: ["plot", "diagram"]},
|
|
42
|
+
evidence: {type: "array", minItems: 1, maxItems: PAPER_POINT_EVIDENCE, items: text(PAPER_POINT_EVIDENCE_BYTES)},
|
|
43
|
+
waiver: text(PAPER_FIGURE_WAIVER_BYTES),
|
|
44
|
+
}, ["id", "file", "kind"]);
|
|
45
|
+
const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2, 3]}, sections: {type: "array", maxItems: PAPER_PLAN_SECTIONS, items: obj({
|
|
30
46
|
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"}, heading: text(PAPER_PLAN_BYTES),
|
|
31
47
|
cites: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
32
48
|
points: {type: "array", maxItems: PAPER_PLAN_POINTS, items: obj({
|
|
@@ -36,7 +52,7 @@ const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2]}, sections: {type: "ar
|
|
|
36
52
|
requires: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
37
53
|
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
54
|
}, ["id", "claim", "requires"])},
|
|
39
|
-
}, ["id", "heading", "cites"])}}, ["sections"]);
|
|
55
|
+
}, ["id", "heading", "cites"])}, dependencies: {type: "array", maxItems: PAPER_PLAN_DEPENDENCIES, items: PAPER_DEPENDENCY}, figures: {type: "array", maxItems: PAPER_FIGURES, items: PAPER_FIGURE}}, ["sections"]);
|
|
40
56
|
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
57
|
const LINEAGE_ATTEMPTS = { type: "array", minItems: 1, maxItems: 8, items: { ...text(16), minLength: 16 } };
|
|
42
58
|
const LINEAGE_CANDIDATES = { type: "array", minItems: 1, maxItems: 8, items: { ...text(40), minLength: 40 } };
|
|
@@ -45,6 +61,7 @@ const REVIEW = obj({
|
|
|
45
61
|
checklist: obj({ negativeResults: { type: "boolean" }, denominators: { type: "boolean" }, limitations: { type: "boolean" }, reproducibility: { type: "boolean" },
|
|
46
62
|
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
63
|
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"]) },
|
|
64
|
+
readback: obj({ claims: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 1000 } } }, ["claims"]),
|
|
48
65
|
}, ["v", "reviewer", "buildSha256", "checklist", "findings"]);
|
|
49
66
|
// Source-specific current-study/exact-id rules are owned by the shared validator; the MCP transport bounds both shapes.
|
|
50
67
|
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 +88,10 @@ const PROTOCOL_V1 = obj({
|
|
|
71
88
|
network: { type: "string", enum: ["none"] },
|
|
72
89
|
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
90
|
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"]),
|
|
91
|
+
screen: obj({
|
|
92
|
+
evaluatorInputs: { type: "boolean", enum: [true], description: "Refuse a candidate commit that carries a byte copy of an input mounted only for the evaluator" },
|
|
93
|
+
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" },
|
|
94
|
+
}, []),
|
|
74
95
|
}, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"]);
|
|
75
96
|
|
|
76
97
|
const STAGE_PROTOCOL = obj({ ...PROTOCOL_V1.properties,
|
|
@@ -102,13 +123,25 @@ const PLAN = obj({
|
|
|
102
123
|
edges: { type: "array", maxItems: 512, items: { type: "array", minItems: 2, maxItems: 2, items: planId } },
|
|
103
124
|
}, ["v", "nodes", "edges"]);
|
|
104
125
|
|
|
105
|
-
const
|
|
106
|
-
|
|
126
|
+
const SELECTION_FIELDS = {
|
|
127
|
+
run: text(64), metric: text(128),
|
|
107
128
|
baseline: obj({ commit: { type: "string", minLength: 40, maxLength: 40 } }, ["commit"]),
|
|
108
129
|
minSeeds: integer(1, 1000), minDelta: { type: "number", minimum: 0 },
|
|
109
|
-
}
|
|
130
|
+
};
|
|
131
|
+
const SELECTION_REQUIRED = ["v", "run", "metric", "baseline", "minSeeds", "minDelta"];
|
|
132
|
+
const SELECTION = { oneOf: [
|
|
133
|
+
obj({ v: { type: "integer", enum: [1] }, ...SELECTION_FIELDS }, SELECTION_REQUIRED),
|
|
134
|
+
obj({
|
|
135
|
+
v: { type: "integer", enum: [2] }, ...SELECTION_FIELDS,
|
|
136
|
+
guards: { type: "array", maxItems: 8, items: obj({ metric: text(128), maxRegression: { type: "number", minimum: 0 } }, ["metric", "maxRegression"]) },
|
|
137
|
+
cost: obj({ metric: text(128), free: { type: "number", minimum: 0 }, perUnit: { type: "number", minimum: 0 } }, ["metric", "free", "perUnit"]),
|
|
138
|
+
calibration: obj({ sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$" } }, ["sha256"]),
|
|
139
|
+
}, SELECTION_REQUIRED),
|
|
140
|
+
] };
|
|
110
141
|
|
|
111
|
-
const
|
|
142
|
+
const PREDICTION = obj({ metric: text(128), expect: { type: "string", enum: ["improve", "no-change", "regress"] }, minDelta: { type: "number", minimum: 0 } }, ["metric", "expect"]);
|
|
143
|
+
const IDEA = obj({ id: text(64), title: text(500), hypothesis: text(4000), parent: text(64), commit: { type: "string", minLength: 40, maxLength: 40 },
|
|
144
|
+
category: text(64), bundle: integer(1, 16), predicts: { type: "array", minItems: 1, maxItems: 4, items: PREDICTION } }, ["id", "title", "hypothesis"]);
|
|
112
145
|
|
|
113
146
|
export const ARES_TOOLS: readonly McpTool[] = [
|
|
114
147
|
{ 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} },
|
|
@@ -156,6 +189,8 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
156
189
|
{ 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
190
|
{ 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
191
|
{ 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 },
|
|
192
|
+
{ 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 },
|
|
193
|
+
{ 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
194
|
{ 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
195
|
{ 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
196
|
{ 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 +200,7 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
165
200
|
{ 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
201
|
{ 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
202
|
{ 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 },
|
|
203
|
+
{ 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
204
|
{ 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
205
|
{ 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
206
|
{ 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 +224,17 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
188
224
|
{ 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
225
|
{ 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
226
|
{ 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 },
|
|
227
|
+
{ 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
228
|
{ 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
|
|
195
|
-
{ name: "ares_paper_build", description: "Check the bounded manuscript and refuse blocking findings before writing. Commit rendered Markdown,
|
|
196
|
-
{ name: "
|
|
229
|
+
{ 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 },
|
|
230
|
+
{ 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 },
|
|
231
|
+
{ 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 },
|
|
232
|
+
{ 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 },
|
|
233
|
+
{ 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 },
|
|
234
|
+
{ 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 },
|
|
235
|
+
{ 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 },
|
|
236
|
+
{ 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 },
|
|
237
|
+
{ 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
238
|
{ 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
239
|
{ 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
240
|
];
|
|
@@ -252,6 +293,8 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
252
293
|
ares_scope_set: a => ops.scope(dir(a), a.scope, ctx),
|
|
253
294
|
ares_idea_add: a => ops.ideaAdd(dir(a), a.idea, ctx),
|
|
254
295
|
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),
|
|
296
|
+
ares_idea_categories: a => ops.ideaCategories(dir(a), a.categories, ctx),
|
|
297
|
+
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
298
|
ares_investigate_show: a => ops.investigateShow(dir(a)),
|
|
256
299
|
ares_investigate_close: a => ops.investigateClose(dir(a), ctx),
|
|
257
300
|
ares_ablate_add: a => ops.ablateAdd(dir(a), a.ablation, ctx),
|
|
@@ -261,6 +304,11 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
261
304
|
ares_final_close: a => ops.finalClose(dir(a), ctx),
|
|
262
305
|
ares_final_seeds: a => ops.finalSeeds(dir(a), a.final, ctx),
|
|
263
306
|
ares_selection_set: a => ops.selection(dir(a), a.selection, ctx),
|
|
307
|
+
ares_selection_calibrate: a => ops.selectionCalibrate(dir(a), {
|
|
308
|
+
fromRun: a.fromRun as string,
|
|
309
|
+
...(a.nullCommit === undefined ? {} : { nullCommit: a.nullCommit as string }),
|
|
310
|
+
...(a.z === undefined ? {} : { z: a.z as number }),
|
|
311
|
+
}, ctx),
|
|
264
312
|
ares_protocol_set: a => ops.protocol(dir(a), a.protocol, ctx),
|
|
265
313
|
ares_harness_set: a => ops.harnessSet(dir(a), a.round, ctx),
|
|
266
314
|
ares_harness_show: a => ops.harnessShow(dir(a), a.round as string | undefined),
|
|
@@ -294,10 +342,15 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
294
342
|
ares_review_resolve: a => ops.reviewResolve(dir(a), a.target as string, a.reason as string, ctx),
|
|
295
343
|
ares_review_show: a => ops.reviewShow(dir(a)),
|
|
296
344
|
ares_review_checklist: () => ops.reviewChecklistShow(),
|
|
297
|
-
ares_paper_build: a => ops.paperBuild(dir(a), ctx),
|
|
345
|
+
ares_paper_build: a => ops.paperBuild(dir(a), ctx, paperDocument(a.doc)),
|
|
346
|
+
ares_paper_render_record: a => ops.paperRenderRecord(dir(a), absolute(a.file, "file"), absolute(a.receipt, "receipt"), ctx, paperDocument(a.doc)),
|
|
347
|
+
ares_paper_render_show: a => ops.paperRenderShow(dir(a), paperDocument(a.doc)),
|
|
348
|
+
ares_renderer_set: a => ops.rendererSet(dir(a), { command: a.command, ...(a.timeoutS !== undefined ? { timeoutS: a.timeoutS } : {}) }, env),
|
|
349
|
+
ares_renderer_show: a => ops.rendererShow(dir(a), env),
|
|
350
|
+
ares_renderer_check: a => ops.rendererCheck(dir(a), env),
|
|
298
351
|
ares_paper_plan_set: a => ops.paperPlanSet(dir(a), a.plan, ctx),
|
|
299
352
|
ares_paper_plan_show: a => ops.paperPlanShow(dir(a)),
|
|
300
|
-
ares_paper_check: a => ops.paperCheck(dir(a)),
|
|
353
|
+
ares_paper_check: a => ops.paperCheck(dir(a), paperDocument(a.doc)),
|
|
301
354
|
ares_cite_check: a => ops.cite(dir(a), absolute(a.draft, "draft")),
|
|
302
355
|
ares_playbook: () => ({ playbook: PLAYBOOK }),
|
|
303
356
|
};
|
package/src/memory/archive.ts
CHANGED
|
@@ -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
|
-
|
|
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"]) {
|
package/src/paper/build.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
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(
|
|
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 (
|
|
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
|
-
|
|
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
|
|
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
|
}
|
package/src/paper/check.ts
CHANGED
|
@@ -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
|
|
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] === ")") {
|
|
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]
|
|
117
|
-
const target = match[
|
|
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
|
-
|
|
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
|
|
129
|
-
export function checkPaper(dirArg: string) {
|
|
130
|
-
const { dir, study } = openStudy(dirArg), file =
|
|
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(
|
|
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)
|
|
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
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { citationOccurrences } from "../lit/cite.ts";
|
|
2
|
+
import { isVerified, type Candidate } from "../lit/candidates.ts";
|
|
3
|
+
import type { PaperPlan } from "./plan.ts";
|
|
4
|
+
|
|
5
|
+
export const DEPENDENCY_CODES = ["uncited-dependency", "undeclared-metric"] as const;
|
|
6
|
+
export type DependencyFindingCode = typeof DEPENDENCY_CODES[number];
|
|
7
|
+
export interface PaperDependencyHit {
|
|
8
|
+
code: DependencyFindingCode;
|
|
9
|
+
severity: "blocking";
|
|
10
|
+
dependencyId?: string;
|
|
11
|
+
start: number;
|
|
12
|
+
end: number;
|
|
13
|
+
message: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Literal citation presence and current verification only; dependency names are never matched to prose. */
|
|
17
|
+
export function paperDependencyFindings(citationText: string, plan: PaperPlan, candidates: Candidate[], protocolMetrics: readonly string[]): PaperDependencyHit[] {
|
|
18
|
+
const dependencies = plan.dependencies ?? [];
|
|
19
|
+
if (!dependencies.length) return [];
|
|
20
|
+
const occurring = new Set(citationOccurrences(citationText).map(hit => hit.key)), verified = new Map<string, boolean>(), hits: PaperDependencyHit[] = [];
|
|
21
|
+
for (const dependency of dependencies) {
|
|
22
|
+
if (!dependency.cites?.length) continue;
|
|
23
|
+
const absent = dependency.cites.every(key => !occurring.has(key));
|
|
24
|
+
let stale: string | undefined;
|
|
25
|
+
for (const key of dependency.cites) {
|
|
26
|
+
let current = verified.get(key);
|
|
27
|
+
if (current === undefined) {
|
|
28
|
+
const matches = candidates.filter(candidate => candidate.citekey === key);
|
|
29
|
+
current = matches.length === 1 && matches[0]!.status === "included" && isVerified(matches[0]!);
|
|
30
|
+
verified.set(key, current);
|
|
31
|
+
}
|
|
32
|
+
if (!current) stale ??= key;
|
|
33
|
+
}
|
|
34
|
+
if (absent) hits.push({code: "uncited-dependency", severity: "blocking", dependencyId: dependency.id, start: 0, end: 0,
|
|
35
|
+
message: `dependency ${dependency.id.slice(0, 64)} (${dependency.kind}) has no citation in the manuscript; cite @${dependency.cites[0]!.slice(0, 80)} or another of its keys in prose, or replace its cites with a written waiver`});
|
|
36
|
+
else if (stale) hits.push({code: "uncited-dependency", severity: "blocking", dependencyId: dependency.id, start: 0, end: 0,
|
|
37
|
+
message: `dependency ${dependency.id.slice(0, 64)} citation @${stale.slice(0, 80)} is no longer included and identifier-verified; re-verify it with ares lit verify, route another verified key, or write a waiver`});
|
|
38
|
+
}
|
|
39
|
+
const declared = new Set(dependencies.filter(dependency => dependency.kind === "metric").map(dependency => dependency.name));
|
|
40
|
+
for (const metric of protocolMetrics) {
|
|
41
|
+
const name = metric.trim();
|
|
42
|
+
if (declared.has(name)) continue;
|
|
43
|
+
hits.push({code: "undeclared-metric", severity: "blocking", start: 0, end: 0,
|
|
44
|
+
message: `protocol metric ${name.slice(0, 80)} has no metric dependency; declare it in paper plan set with verified cites or a written waiver`});
|
|
45
|
+
}
|
|
46
|
+
return hits;
|
|
47
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import type { LedgerEvent } from "../study.ts";
|
|
3
|
+
|
|
4
|
+
export const PAPER_DOCUMENTS = ["manuscript", "slides"] as const;
|
|
5
|
+
export type PaperDocument = typeof PAPER_DOCUMENTS[number];
|
|
6
|
+
|
|
7
|
+
export function paperDocument(value: unknown): PaperDocument {
|
|
8
|
+
if (value === undefined || value === "manuscript") return "manuscript";
|
|
9
|
+
if (value === "slides") return "slides";
|
|
10
|
+
throw new Error("paper document: use manuscript or slides with --doc");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function paperSourcePath(dir: string, doc: PaperDocument): string {
|
|
14
|
+
return join(dir, "paper", `${doc}.md`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function paperEventFor(event: LedgerEvent, type: "paper.built" | "paper.rendered", doc: PaperDocument = "manuscript"): boolean {
|
|
18
|
+
return event.type === type && (event.data.doc === doc || doc === "manuscript" && event.data.doc === undefined);
|
|
19
|
+
}
|