@staix/agent-research 0.3.0 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +93 -22
  3. package/package.json +4 -1
  4. package/src/cli-output.ts +446 -0
  5. package/src/cli.ts +208 -66
  6. package/src/commands-table.ts +213 -93
  7. package/src/commands.ts +86 -17
  8. package/src/exp/artifacts.ts +20 -2
  9. package/src/exp/attempts.ts +26 -9
  10. package/src/exp/calibrate.ts +125 -0
  11. package/src/exp/executor.ts +130 -21
  12. package/src/exp/final.ts +12 -3
  13. package/src/exp/idea-report.ts +97 -0
  14. package/src/exp/ideas.ts +90 -6
  15. package/src/exp/investigate.ts +25 -22
  16. package/src/exp/metrics.ts +3 -5
  17. package/src/exp/protocol.ts +28 -3
  18. package/src/exp/reuse-admission.ts +3 -1
  19. package/src/exp/reuse-runtime.ts +5 -1
  20. package/src/exp/screen.ts +83 -0
  21. package/src/exp/selection.ts +110 -4
  22. package/src/exp/snapshot.ts +28 -8
  23. package/src/exp/stages.ts +3 -1
  24. package/src/harness/transitions.ts +37 -5
  25. package/src/manifest.ts +13 -5
  26. package/src/mcp-tools.ts +67 -14
  27. package/src/memory/archive.ts +8 -3
  28. package/src/paper/build.ts +39 -25
  29. package/src/paper/check.ts +46 -15
  30. package/src/paper/dependencies.ts +47 -0
  31. package/src/paper/document.ts +19 -0
  32. package/src/paper/figures.ts +152 -0
  33. package/src/paper/hygiene.ts +16 -5
  34. package/src/paper/plan.ts +71 -29
  35. package/src/paper/point-evidence.ts +27 -12
  36. package/src/paper/render.ts +113 -0
  37. package/src/paper/renderer.ts +128 -0
  38. package/src/paper/review.ts +41 -5
  39. package/src/plan/definition.ts +6 -1
  40. package/src/playbook.ts +21 -11
  41. package/src/provenance.ts +4 -3
  42. package/src/study-export.ts +7 -4
  43. package/src/study.ts +9 -4
  44. package/src/ui/plugin.ts +3 -1
@@ -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
  }
@@ -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
+ }
@@ -0,0 +1,152 @@
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { plain, readBytesBounded, readLedger, sha256 } from "../study.ts";
4
+ import { retentionDisposalIndex } from "../provenance.ts";
5
+ import { resolvePointEvidence } from "./point-evidence.ts";
6
+ import { canonical } from "../plan/state.ts";
7
+
8
+ export const PAPER_FIGURES = 100, PAPER_FIGURE_BYTES = 16 * 1024 * 1024;
9
+ export const PAPER_FIGURE_PATH_BYTES = 4096, PAPER_FIGURE_WAIVER_BYTES = 500;
10
+ export interface PaperFigure { id: string; file: string; kind: "plot" | "diagram"; evidence?: string[]; waiver?: string }
11
+ const PROVENANCE = ["artifact", "referenced", "waived", "diagram"] as const;
12
+ export type FigureProvenance = typeof PROVENANCE[number];
13
+ export interface FigureEvidence { id: string; file: string; sha256: string; bytes: number; provenance: FigureProvenance }
14
+ export type FigureFindingCode = "undeclared-figure" | "missing-figure" | "unresolved-figure-evidence";
15
+ export interface ImageLink { target: string; start: number; end: number }
16
+ interface FigureFinding { code: FigureFindingCode; severity: "blocking"; start: number; end: number; figureId?: string; message: string }
17
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+ const HASH = /^[a-f0-9]{64}$/;
19
+ const repair = "correct the figure declaration, then rerun ares paper plan set <dir> --file PATH";
20
+ function invalid(reason: string): never { throw new Error(`paper plan figures: ${reason}; ${repair}`); }
21
+
22
+ function figureFile(raw: unknown): raw is string {
23
+ return typeof raw === "string" && raw.startsWith("paper/") && raw.trim() === raw
24
+ && Buffer.byteLength(raw) <= PAPER_FIGURE_PATH_BYTES && !/[\\:\p{Cc}\p{Zl}\p{Zp}?#]/u.test(raw)
25
+ && raw.split("/").every(part => part !== "" && part !== "." && part !== "..");
26
+ }
27
+ function figureId(raw: unknown): raw is string { return typeof raw === "string" && raw.length <= 64 && ID.test(raw); }
28
+
29
+ export function validateFigures(raw: unknown, pointReference: (raw: unknown) => string): PaperFigure[] {
30
+ if (!Array.isArray(raw) || raw.length > PAPER_FIGURES) invalid("figures must be an array of at most 100 entries");
31
+ const ids = new Set<string>(), files = new Set<string>();
32
+ return raw.map((value): PaperFigure => {
33
+ if (!plain(value) || Object.keys(value).some(key => !["id", "file", "kind", "evidence", "waiver"].includes(key))) invalid("each figure must be a closed object");
34
+ const { id, file, kind, evidence, waiver } = value;
35
+ if (!figureId(id) || ids.has(id)) invalid("figure id must be a unique lowercase alphanumeric hyphenated slug of 1..64 characters");
36
+ if (!figureFile(file) || files.has(file)) invalid(`figure ${id} needs a unique relative file under paper/ without traversal`);
37
+ if (kind !== "plot" && kind !== "diagram") invalid(`figure ${id} kind must be plot or diagram`);
38
+ ids.add(id); files.add(file);
39
+ const base: PaperFigure = { id, file, kind };
40
+ if (kind === "diagram") {
41
+ if (evidence !== undefined || waiver !== undefined) invalid(`diagram ${id} takes neither evidence nor waiver`);
42
+ return base;
43
+ }
44
+ if ((evidence === undefined) === (waiver === undefined)) invalid(`plot ${id} needs exactly one of evidence and waiver`);
45
+ if (evidence !== undefined) {
46
+ if (!Array.isArray(evidence) || !evidence.length || evidence.length > 64) invalid(`plot ${id} needs 1..64 evidence references`);
47
+ const refs = evidence.map(pointReference);
48
+ if (new Set(refs).size !== refs.length) invalid(`plot ${id} has duplicate evidence references`);
49
+ return { ...base, evidence: refs };
50
+ }
51
+ if (typeof waiver !== "string" || !waiver.trim() || waiver.includes("\0") || Buffer.byteLength(waiver) > PAPER_FIGURE_WAIVER_BYTES) {
52
+ invalid(`plot ${id} waiver must be nonempty written text of at most 500 UTF-8 bytes without NUL`);
53
+ }
54
+ return { ...base, waiver };
55
+ });
56
+ }
57
+
58
+ export function validFigureEvidence(raw: unknown): raw is FigureEvidence[] {
59
+ if (!Array.isArray(raw) || raw.length > PAPER_FIGURES) return false;
60
+ const ids = new Set<string>(), files = new Set<string>();
61
+ return raw.every(row => {
62
+ if (!plain(row) || Object.keys(row).some(key => !["id", "file", "sha256", "bytes", "provenance"].includes(key))
63
+ || !figureId(row.id) || ids.has(row.id) || !figureFile(row.file) || files.has(row.file)
64
+ || typeof row.sha256 !== "string" || !HASH.test(row.sha256)
65
+ || typeof row.bytes !== "number" || !Number.isSafeInteger(row.bytes) || row.bytes < 0 || row.bytes > PAPER_FIGURE_BYTES
66
+ || !PROVENANCE.includes(row.provenance as FigureProvenance)) return false;
67
+ ids.add(row.id); files.add(row.file);
68
+ return true;
69
+ });
70
+ }
71
+
72
+ function physicalFigure(dir: string, file: string) {
73
+ if (!figureFile(file)) throw new Error("figure path outside paper/");
74
+ const parts = file.split("/"), root = realpathSync(dir);
75
+ let path = root;
76
+ for (const [index, part] of parts.entries()) {
77
+ path = join(path, part);
78
+ const metadata = lstatSync(path);
79
+ if (metadata.isSymbolicLink() || (index === parts.length - 1 ? !metadata.isFile() : !metadata.isDirectory())) throw new Error("figure is not a regular physical file");
80
+ }
81
+ if (realpathSync(path) !== path) throw new Error("figure escapes the physical paper directory");
82
+ const bytes = readBytesBounded(path, PAPER_FIGURE_BYTES, { noFollow: true });
83
+ if (realpathSync(path) !== path) throw new Error("figure path changed during read");
84
+ return { sha256: sha256(bytes), bytes: bytes.length };
85
+ }
86
+
87
+ export function figuresStillMatch(dir: string, figures: readonly FigureEvidence[]): boolean {
88
+ try {
89
+ return figures.every(figure => {
90
+ const current = physicalFigure(dir, figure.file);
91
+ return current.sha256 === figure.sha256 && current.bytes === figure.bytes;
92
+ });
93
+ } catch { return false; }
94
+ }
95
+
96
+ function linkFile(raw: string): string | undefined {
97
+ let target = raw.startsWith("<") && raw.endsWith(">") ? raw.slice(1, -1) : raw;
98
+ try { target = decodeURIComponent(target.replace(/\\([\\()[\] <>])/g, "$1")).replace(/^\.\//, ""); } catch { return undefined; }
99
+ if (target.startsWith("/") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(target)) return undefined;
100
+ const candidate = target.startsWith("paper/") ? target : `paper/${target}`;
101
+ return figureFile(candidate) ? candidate : undefined;
102
+ }
103
+
104
+ export function inspectFigures(dir: string, figures: readonly PaperFigure[], links?: readonly ImageLink[]) {
105
+ const findings: FigureFinding[] = [], evidence: FigureEvidence[] = [];
106
+ const hit = (code: FigureFindingCode, message: string, link?: ImageLink, figureId?: string) =>
107
+ findings.push({ code, severity: "blocking", start: link?.start ?? 0, end: link?.end ?? 0, ...(figureId === undefined ? {} : { figureId }), message });
108
+ const declared = new Map(figures.map(figure => [figure.file, figure]));
109
+ const used = new Map<string, ImageLink>();
110
+ for (const link of links ?? []) {
111
+ const file = linkFile(link.target);
112
+ if (!file || !declared.has(file)) {
113
+ hit("undeclared-figure", "image link has no declared figure id; declare its local paper/ file with ares paper plan set or remove the link", link);
114
+ } else if (!used.has(file)) used.set(file, link);
115
+ }
116
+ const resolutions = new Map<string, ReturnType<typeof resolvePointEvidence>>();
117
+ const disposals = figures.some(figure => figure.evidence?.some(ref => ref.startsWith("attempt:"))) ? retentionDisposalIndex(readLedger(dir)) : undefined;
118
+ for (const figure of figures) {
119
+ const link = used.get(figure.file);
120
+ if (links !== undefined && !link) hit("missing-figure", `figure ${figure.id}: manuscript has no image link; link ${figure.file} or remove the declaration`, undefined, figure.id);
121
+ let bytes: ReturnType<typeof physicalFigure> | undefined;
122
+ try { bytes = physicalFigure(dir, figure.file); }
123
+ catch {
124
+ hit("missing-figure", `figure ${figure.id}: file is absent, linked, unreadable, special or larger than 16 MiB; restore a regular file under paper/ and rerun ares paper check`, link, figure.id);
125
+ }
126
+ let provenance: FigureProvenance = figure.kind === "diagram" ? "diagram" : figure.waiver !== undefined ? "waived" : "referenced";
127
+ let resolvedAll = true;
128
+ for (const ref of figure.evidence ?? []) {
129
+ let resolved = resolutions.get(ref);
130
+ if (!resolved) {
131
+ resolved = resolvePointEvidence(dir, ref, true);
132
+ resolutions.set(ref, resolved);
133
+ }
134
+ if (!resolved.resolved) {
135
+ resolvedAll = false;
136
+ hit("unresolved-figure-evidence", `figure ${figure.id}: evidence does not resolve; restore the referenced card or attempt record, or update the plan`, link, figure.id);
137
+ continue;
138
+ }
139
+ const artifacts = resolved.artifacts ?? [];
140
+ if (bytes && artifacts.some(artifact => artifact.sha256 === bytes?.sha256 && artifact.bytes === bytes?.bytes && (!artifact.retained || !disposals?.has(canonical([artifact.retained.attemptId, artifact.retained.stage, artifact.retained.sha256]))))) provenance = "artifact";
141
+ }
142
+ if (bytes && resolvedAll) evidence.push({ id: figure.id, file: figure.file, ...bytes, provenance });
143
+ }
144
+ return { findings, evidence };
145
+ }
146
+
147
+ export function figureCoverage(dir: string, figures: readonly PaperFigure[]) {
148
+ const { evidence } = inspectFigures(dir, figures);
149
+ const coverage = { artifact: 0, referenced: 0, waived: 0, diagram: 0, total: figures.length };
150
+ for (const entry of evidence) coverage[entry.provenance]++;
151
+ return coverage;
152
+ }
@@ -6,13 +6,13 @@ import { citationOccurrences } from "../lit/cite.ts";
6
6
  /** Deterministic citation hygiene codes (#99). Warnings unless listed in study.toml [paper] blocking. */
7
7
  export const HYGIENE_CODES = ["adjacent-duplicate-citation", "citation-stack", "repeated-bundle", "bare-identifier", "duplicate-heading"] as const;
8
8
  export type HygieneCode = typeof HYGIENE_CODES[number];
9
- export interface PaperSettings { maxGroup: number; maxBundleRepeats: number; reviewRounds: number; blocking: HygieneCode[] }
9
+ export interface PaperSettings { maxGroup: number; maxBundleRepeats: number; reviewRounds: number; blocking: HygieneCode[]; requireRender?: boolean }
10
10
  export const DEFAULT_PAPER_SETTINGS: PaperSettings = { maxGroup: 6, maxBundleRepeats: 2, reviewRounds: 3, blocking: [] };
11
11
  export const SETTINGS_BYTES = 64 * 1024;
12
12
  export interface HygieneHit { code: HygieneCode; start: number; end: number; section: string[]; message: string }
13
13
 
14
14
  const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
15
- function refuse(detail: string): never { throw new Error(`study.toml: ${detail}; fix the [paper] or [review] settings (paper keys maxGroup, maxBundleRepeats, reviewRounds, blocking; review key surveyChecklist) or remove study.toml to use the defaults`); }
15
+ function refuse(detail: string): never { throw new Error(`study.toml: ${detail}; fix the [paper] or [review] settings (paper keys maxGroup, maxBundleRepeats, reviewRounds, blocking, requireRender; review keys surveyChecklist, readback) or remove study.toml to use the defaults`); }
16
16
  function count(value: unknown, name: string, min: number): number {
17
17
  if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > 1000) refuse(`paper.${name} must be an integer from ${min} to 1000`);
18
18
  return value;
@@ -23,7 +23,9 @@ export function readPaperSettings(dir: string): PaperSettings { return readStudy
23
23
  export const SURVEY_CHECKLIST_MODES = ["off", "show", "require"] as const;
24
24
  export type SurveyChecklistMode = typeof SURVEY_CHECKLIST_MODES[number];
25
25
  /** [review] settings; `surveyChecklist` is undefined when unset so the caller applies the study-mode default. */
26
- export interface ReviewSettings { surveyChecklist?: SurveyChecklistMode }
26
+ export const READBACK_MODES = ["off", "show", "require"] as const;
27
+ export type ReadbackMode = typeof READBACK_MODES[number];
28
+ export interface ReviewSettings { surveyChecklist?: SurveyChecklistMode; readback?: ReadbackMode }
27
29
  export function readReviewSettings(dir: string): ReviewSettings { return readStudySettings(dir).review; }
28
30
  /** One closed reader for both tables, so an unknown key in either refuses for every caller. */
29
31
  function readStudySettings(dir: string): { paper: PaperSettings; review: ReviewSettings } {
@@ -36,19 +38,28 @@ function readStudySettings(dir: string): { paper: PaperSettings; review: ReviewS
36
38
  for (const key of Object.keys(raw)) if (key !== "paper" && key !== "review") refuse(`unknown setting ${JSON.stringify(key).slice(0, 80)}`);
37
39
  const review = raw.review ?? {};
38
40
  if (!isRecord(review)) refuse("review must be a table");
39
- for (const key of Object.keys(review)) if (key !== "surveyChecklist") refuse(`unknown setting review.${JSON.stringify(key).slice(0, 80)}`);
41
+ for (const key of Object.keys(review)) if (key !== "surveyChecklist" && key !== "readback") refuse(`unknown setting review.${JSON.stringify(key).slice(0, 80)}`);
40
42
  const reviewSettings: ReviewSettings = {};
41
43
  if (review.surveyChecklist !== undefined) {
42
44
  if (typeof review.surveyChecklist !== "string" || !(SURVEY_CHECKLIST_MODES as readonly string[]).includes(review.surveyChecklist)) refuse(`review.surveyChecklist must be one of ${SURVEY_CHECKLIST_MODES.join(", ")}`);
43
45
  reviewSettings.surveyChecklist = review.surveyChecklist as SurveyChecklistMode;
44
46
  }
47
+ if (review.readback !== undefined) {
48
+ if (typeof review.readback !== "string" || !(READBACK_MODES as readonly string[]).includes(review.readback)) refuse(`review.readback must be one of ${READBACK_MODES.join(", ")}`);
49
+ reviewSettings.readback = review.readback as ReadbackMode;
50
+ }
45
51
  const paper = raw.paper ?? {};
46
52
  if (!isRecord(paper)) refuse("paper must be a table");
47
- for (const key of Object.keys(paper)) if (!["maxGroup", "maxBundleRepeats", "reviewRounds", "blocking"].includes(key)) refuse(`unknown setting paper.${JSON.stringify(key).slice(0, 80)}`);
53
+ for (const key of Object.keys(paper)) if (!["maxGroup", "maxBundleRepeats", "reviewRounds", "blocking", "requireRender"].includes(key)) refuse(`unknown setting paper.${JSON.stringify(key).slice(0, 80)}`);
48
54
  const settings: PaperSettings = { ...DEFAULT_PAPER_SETTINGS, blocking: [] };
49
55
  if (paper.maxGroup !== undefined) settings.maxGroup = count(paper.maxGroup, "maxGroup", 1);
50
56
  if (paper.maxBundleRepeats !== undefined) settings.maxBundleRepeats = count(paper.maxBundleRepeats, "maxBundleRepeats", 1);
51
57
  if (paper.reviewRounds !== undefined) settings.reviewRounds = count(paper.reviewRounds, "reviewRounds", 1);
58
+ // Set only when present, so paper check settings stay byte-identical for studies without it.
59
+ if (paper.requireRender !== undefined) {
60
+ if (typeof paper.requireRender !== "boolean") refuse("paper.requireRender must be true or false");
61
+ settings.requireRender = paper.requireRender;
62
+ }
52
63
  if (paper.blocking !== undefined) {
53
64
  if (!Array.isArray(paper.blocking)) refuse("paper.blocking must be an array of finding codes");
54
65
  for (const code of paper.blocking) {
package/src/paper/plan.ts CHANGED
@@ -1,16 +1,22 @@
1
+ import { figureCoverage, validateFigures, type PaperFigure } from "./figures.ts";
1
2
  import { resolvePointEvidence, pointEvidenceAdvice, type PointEvidenceResolution } from "./point-evidence.ts";
2
3
  import { lstatSync, realpathSync } from "node:fs";
3
4
  import { join, resolve } from "node:path";
4
5
  import { commit, openStudy, plain, readBytesBounded, sha256, type Actor } from "../study.ts";
5
6
  import { isVerified, loadCandidates, type Candidate } from "../lit/candidates.ts";
6
7
 
8
+ export const PAPER_DEPENDENCY_KINDS = ["dataset", "metric", "baseline", "model", "method", "software"] as const;
9
+ export type PaperDependencyKind = typeof PAPER_DEPENDENCY_KINDS[number];
7
10
  export interface PaperPoint { id: string; claim: string; requires: string[]; evidence?: string[] }
11
+ export interface PaperDependency { id: string; kind: PaperDependencyKind; name: string; cites?: string[]; waiver?: string }
8
12
  export interface PaperSection { id: string; heading: string; cites: string[]; points?: PaperPoint[] }
9
- export interface PaperPlan { v: 1 | 2; sections: PaperSection[] }
13
+ export interface PaperPlan { v: 1 | 2 | 3; sections: PaperSection[]; dependencies?: PaperDependency[]; figures?: PaperFigure[] }
10
14
  export interface PaperPlanSnapshot { plan: PaperPlan; sha256: string }
11
- export interface PaperPlanView { plan: PaperPlan | null; coverage: { routed: number; total: number } }
15
+ export interface PaperDependencyCoverage { cited: number; waived: number; total: number }
16
+ export interface PaperPlanView { plan: PaperPlan | null; coverage: { routed: number; total: number }; dependencyCoverage: PaperDependencyCoverage; figureCoverage?: ReturnType<typeof figureCoverage> }
12
17
  export const PAPER_PLAN_BYTES = 65_536, PAPER_PLAN_SECTIONS = 64, PAPER_PLAN_CITES = 300;
13
18
  export const PAPER_PLAN_POINTS = 40, PAPER_POINT_CLAIM_CHARACTERS = 500, PAPER_POINT_EVIDENCE = 64, PAPER_POINT_EVIDENCE_BYTES = 4096;
19
+ export const PAPER_PLAN_DEPENDENCIES = 200, PAPER_DEPENDENCY_WAIVER_BYTES = 500;
14
20
  export type PaperPointEvidenceResolver = (ref: string) => PointEvidenceResolution;
15
21
  const next = "inspect ares lit list, run ares lit verify and ares lit bib as needed, then retry ares paper plan set <dir> --file PATH|-";
16
22
  function invalid(cause: string): never { throw new Error(`paper plan: ${cause}; ${next}`); }
@@ -67,11 +73,57 @@ function points(raw: unknown, scope: ReadonlySet<string>, ids: Set<string>, reso
67
73
  return { id: point.id, claim: point.claim, requires, ...(evidence === undefined ? {} : { evidence }) };
68
74
  });
69
75
  }
70
- export function validatePaperPlan(raw: unknown, candidates: Candidate[], resolveEvidence?: PaperPointEvidenceResolver): PaperPlan {
71
- const value = object(raw, ["v", "sections"], "plan");
72
- if (value.v !== undefined && value.v !== 1 && value.v !== 2) invalid("unsupported plan version; use a compatible version-1 or version-2 plan reader, keeping unsupported plan bytes unchanged");
76
+ function citationKeys(raw: unknown, label: string, unique: string, byKey: Map<string, Candidate[]>, verifiedKeys: Set<string>, verify: boolean): { keys: string[]; seen: Set<string> } {
77
+ if (!Array.isArray(raw) || raw.length > PAPER_PLAN_CITES) invalid(`${label} must be an array of at most 300 citation keys`);
78
+ const seen = new Set<string>();
79
+ const keys = raw.map((key): string => {
80
+ if (typeof key !== "string" || !key.length) invalid("each citation key must be a nonempty exact bibliography key");
81
+ if (seen.has(key)) invalid(unique); seen.add(key);
82
+ if (!verify) return key;
83
+ const matches = byKey.get(key);
84
+ if (!matches?.length) invalid("scope contains an unknown or unassigned citation key");
85
+ if (matches.length !== 1) invalid("scope contains an ambiguous citation key; restore unique bibliography keys");
86
+ if (!verifiedKeys.has(key)) {
87
+ const candidate = matches[0]!;
88
+ if (candidate.status !== "included") invalid("scope reference is excluded or unscreened; include it through ares lit screen before routing it");
89
+ if (!isVerified(candidate)) invalid("scope reference is not identifier-verified or its verification is stale");
90
+ verifiedKeys.add(key);
91
+ }
92
+ return key;
93
+ });
94
+ return { keys, seen };
95
+ }
96
+ /** Dependency citations are verified when the plan is set; reads defer so later staleness is a check finding, not a read error. */
97
+ function dependencies(raw: unknown, byKey: Map<string, Candidate[]>, verifiedKeys: Set<string>, verify: boolean): PaperDependency[] {
98
+ if (raw === undefined) return [];
99
+ if (!Array.isArray(raw) || raw.length > PAPER_PLAN_DEPENDENCIES) invalid("dependencies must be an array of at most 200 entries");
100
+ const ids = new Set<string>();
101
+ return raw.map((value): PaperDependency => {
102
+ const dependency = object(value, ["id", "kind", "name", "cites", "waiver"], "dependency");
103
+ if (typeof dependency.id !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(dependency.id) || dependency.id.length > 64) invalid("dependency id must be a lowercase alphanumeric hyphenated slug of 1..64 characters");
104
+ if (ids.has(dependency.id)) invalid("dependency ids must be unique"); ids.add(dependency.id);
105
+ if (typeof dependency.kind !== "string" || !PAPER_DEPENDENCY_KINDS.includes(dependency.kind as PaperDependencyKind)) invalid(`dependency kind must be one of ${PAPER_DEPENDENCY_KINDS.join(", ")}`);
106
+ if (typeof dependency.name !== "string" || !dependency.name.trim() || /\p{Cc}/u.test(dependency.name) || /\p{Zl}|\p{Zp}/u.test(dependency.name)) invalid("dependency name must be nonempty single-line text");
107
+ if ((dependency.cites === undefined) === (dependency.waiver === undefined)) invalid("dependency needs exactly one of cites or waiver; cite verified keys or write a waiver");
108
+ const base = { id: dependency.id, kind: dependency.kind as PaperDependencyKind, name: dependency.name.trim() };
109
+ if (dependency.cites !== undefined) {
110
+ if (!Array.isArray(dependency.cites) || !dependency.cites.length) invalid("dependency cites must be a nonempty array of citation keys");
111
+ const { keys } = citationKeys(dependency.cites, "dependency cites", "citation keys must be unique within each dependency", byKey, verifiedKeys, verify);
112
+ return { ...base, cites: keys };
113
+ }
114
+ if (typeof dependency.waiver !== "string" || !dependency.waiver.trim() || dependency.waiver.includes("\0")) invalid("dependency waiver must be nonempty written text without NUL");
115
+ if (Buffer.byteLength(dependency.waiver) > PAPER_DEPENDENCY_WAIVER_BYTES) invalid("dependency waiver must be at most 500 UTF-8 bytes; shorten the written waiver or cite verified keys instead");
116
+ return { ...base, waiver: dependency.waiver };
117
+ });
118
+ }
119
+ export function validatePaperPlan(raw: unknown, candidates: Candidate[], resolveEvidence?: PaperPointEvidenceResolver, deferDependencyCitations = false): PaperPlan {
120
+ const value = object(raw, ["v", "sections", "dependencies", "figures"], "plan");
121
+ if (value.v !== undefined && value.v !== 1 && value.v !== 2 && value.v !== 3) invalid("unsupported plan version; use a compatible version-1, version-2 or version-3 plan reader, keeping unsupported plan bytes unchanged");
73
122
  if (!Array.isArray(value.sections) || value.sections.length > PAPER_PLAN_SECTIONS) invalid("sections must be an array of at most 64 sections");
74
123
  if (value.v === 1 && value.sections.some(section => plain(section) && Array.isArray(section.points) && section.points.length)) invalid("version-1 plan cannot contain writing points; omit v or use v: 2 for a points plan");
124
+ if ((value.v === 1 || value.v === 2) && Array.isArray(value.dependencies) && value.dependencies.length) invalid(`version-${value.v} plan cannot contain experiment dependencies; omit v or use v: 3 for a dependencies plan`);
125
+ if ((value.v === 1 || value.v === 2) && value.figures !== undefined) invalid("figures require paper plan v: 3");
126
+ const figures = value.figures === undefined ? undefined : validateFigures(value.figures, pointReference);
75
127
  const pointIds = new Set<string>(), resolutions = new Map<string, PointEvidenceResolution>();
76
128
  const byKey = candidateKeys(candidates), ids = new Set<string>(), headings = new Set<string>(), verifiedKeys = new Set<string>();
77
129
  const sections = value.sections.map((rawSection): PaperSection => {
@@ -80,27 +132,13 @@ export function validatePaperPlan(raw: unknown, candidates: Candidate[], resolve
80
132
  if (ids.has(section.id)) invalid("section ids must be unique"); ids.add(section.id);
81
133
  if (typeof section.heading !== "string" || !section.heading.length || section.heading.trim() !== section.heading || section.heading.includes("\0")) invalid("section heading must be nonempty exact text without outer whitespace or NUL");
82
134
  if (headings.has(section.heading)) invalid("section headings must be unique exact text"); headings.add(section.heading);
83
- if (!Array.isArray(section.cites) || section.cites.length > PAPER_PLAN_CITES) invalid("section cites must be an array of at most 300 citation keys");
84
- const seen = new Set<string>();
85
- const cites = section.cites.map((key): string => {
86
- if (typeof key !== "string" || !key.length) invalid("each citation key must be a nonempty exact bibliography key");
87
- if (seen.has(key)) invalid("citation keys must be unique within each section"); seen.add(key);
88
- const matches = byKey.get(key);
89
- if (!matches?.length) invalid("scope contains an unknown or unassigned citation key");
90
- if (matches.length !== 1) invalid("scope contains an ambiguous citation key; restore unique bibliography keys");
91
- if (!verifiedKeys.has(key)) {
92
- const candidate = matches[0]!;
93
- if (candidate.status !== "included") invalid("scope reference is excluded or unscreened; include it through ares lit screen before routing it");
94
- if (!isVerified(candidate)) invalid("scope reference is not identifier-verified or its verification is stale");
95
- verifiedKeys.add(key);
96
- }
97
- return key;
98
- });
135
+ const { keys: cites, seen } = citationKeys(section.cites, "section cites", "citation keys must be unique within each section", byKey, verifiedKeys, true);
99
136
  const pointList = points(section.points, seen, pointIds, resolveEvidence, resolutions);
100
137
  return { id: section.id, heading: section.heading, cites, ...(pointList.length ? { points: pointList } : {}) };
101
138
  });
102
- const plan: PaperPlan = { v: pointIds.size ? 2 : 1, sections };
103
- if (Buffer.byteLength(JSON.stringify(plan, null, 2) + "\n") > PAPER_PLAN_BYTES) invalid("formatted plan exceeds the 64 KiB bound; reduce sections, citation keys or heading lengths");
139
+ const dependencyList = dependencies(value.dependencies, byKey, verifiedKeys, !deferDependencyCitations);
140
+ const plan: PaperPlan = { v: value.v === 3 || dependencyList.length || figures !== undefined ? 3 : pointIds.size ? 2 : 1, sections, ...(dependencyList.length ? { dependencies: dependencyList } : {}), ...(figures === undefined ? {} : { figures }) };
141
+ if (Buffer.byteLength(JSON.stringify(plan, null, 2) + "\n") > PAPER_PLAN_BYTES) invalid("formatted plan exceeds the 64 KiB bound; reduce sections, dependencies, citation keys or heading lengths");
104
142
  return plan;
105
143
  }
106
144
  function metadata(file: string) {
@@ -136,10 +174,10 @@ function snapshot(dir: string, candidates: Candidate[] | undefined, strictEviden
136
174
  catch { invalid("paper/plan.json is unreadable, non-regular or larger than 64 KiB; restore a readable regular file or reduce sections, citation keys or heading lengths if oversized"); }
137
175
  try { raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
138
176
  catch { invalid("paper/plan.json is not valid UTF-8 JSON"); }
139
- if (!plain(raw) || (raw.v !== 1 && raw.v !== 2)) invalid("stored plan must carry supported v: 1 or v: 2; use paper plan set to version an unversioned input, or a compatible ares reader while keeping unsupported version bytes unchanged");
177
+ if (!plain(raw) || (raw.v !== 1 && raw.v !== 2 && raw.v !== 3)) invalid("stored plan must carry supported v: 1, v: 2 or v: 3; use paper plan set to version an unversioned input, or a compatible ares reader while keeping unsupported version bytes unchanged");
140
178
  const resolver: PaperPointEvidenceResolver = strictEvidence ? ref => resolvePointEvidence(target.dir, ref) : () => ({ resolved: true });
141
- const plan = validatePaperPlan(raw, candidates ?? currentCandidates(target.dir), resolver);
142
- if (plan.v !== raw.v) invalid("stored plan version does not match its points; use paper plan set to normalize the known plan format");
179
+ const plan = validatePaperPlan(raw, candidates ?? currentCandidates(target.dir), resolver, true);
180
+ if (plan.v !== raw.v) invalid("stored plan version does not match its declared content; use paper plan set to normalize the known plan format");
143
181
  return { plan, sha256: sha256(bytes) };
144
182
  }
145
183
  export function readPaperPlanSnapshot(dir: string, candidates?: Candidate[]): PaperPlanSnapshot | undefined { return snapshot(dir, candidates, true); }
@@ -150,6 +188,10 @@ export function paperPlanCoverage(plan: PaperPlan, candidates: Candidate[]): { r
150
188
  const routed = new Set(plan.sections.flatMap(section => section.cites)), included = candidates.filter(candidate => candidate.status === "included");
151
189
  return { routed: included.filter(candidate => !!candidate.citekey && routed.has(candidate.citekey) && isVerified(candidate)).length, total: included.length };
152
190
  }
191
+ export function paperDependencyCoverage(plan: PaperPlan): PaperDependencyCoverage {
192
+ const dependencies = plan.dependencies ?? [];
193
+ return { cited: dependencies.filter(dependency => dependency.cites !== undefined).length, waived: dependencies.filter(dependency => dependency.waiver !== undefined).length, total: dependencies.length };
194
+ }
153
195
  /** Caller owns the study lock. All validation precedes the command's one file+event commit. */
154
196
  export function setPaperPlan(dirArg: string, raw: unknown, actor: Actor): PaperPlan {
155
197
  const { dir } = openStudy(dirArg), plan = validatePaperPlan(raw, currentCandidates(dir), ref => resolvePointEvidence(dir, ref)), target = address(dir);
@@ -157,14 +199,14 @@ export function setPaperPlan(dirArg: string, raw: unknown, actor: Actor): PaperP
157
199
  let previous: unknown;
158
200
  try { previous = JSON.parse(new TextDecoder("utf-8", {fatal: true}).decode(readBytesBounded(target.file, PAPER_PLAN_BYTES, {noFollow: true}))); }
159
201
  catch { invalid("previous paper/plan.json is unreadable, oversized or invalid JSON; restore the last valid bounded plan before replacing it"); }
160
- if (plain(previous) && previous.v !== undefined && previous.v !== 1 && previous.v !== 2) invalid("unsupported stored plan version; use a compatible ares reader, keeping paper/plan.json unchanged");
202
+ if (plain(previous) && previous.v !== undefined && previous.v !== 1 && previous.v !== 2 && previous.v !== 3) invalid("unsupported stored plan version; use a compatible ares reader, keeping paper/plan.json unchanged");
161
203
  }
162
204
  const text = JSON.stringify(plan, null, 2) + "\n";
163
- if (Buffer.byteLength(text) > PAPER_PLAN_BYTES) invalid("formatted plan exceeds the 64 KiB bound; reduce sections, citation keys or heading lengths");
205
+ if (Buffer.byteLength(text) > PAPER_PLAN_BYTES) invalid("formatted plan exceeds the 64 KiB bound; reduce sections, dependencies, citation keys or heading lengths");
164
206
  commit(target.dir, [[target.file, text, PAPER_PLAN_BYTES]], [{ actor, type: "paper.plan.set", data: { sha256: sha256(text), sectionCount: plan.sections.length, citationCount: plan.sections.reduce((sum, section) => sum + section.cites.length, 0) } }]);
165
207
  return plan;
166
208
  }
167
209
  export function showPaperPlan(dirArg: string): PaperPlanView {
168
210
  const { dir } = openStudy(dirArg), candidates = currentCandidates(dir), plan = readPaperPlan(dir, candidates);
169
- return { plan: plan ?? null, coverage: paperPlanCoverage(plan ?? { v: 1, sections: [] }, candidates) };
211
+ return { plan: plan ?? null, coverage: paperPlanCoverage(plan ?? { v: 1, sections: [] }, candidates), dependencyCoverage: paperDependencyCoverage(plan ?? { v: 1, sections: [] }), ...(plan?.figures === undefined ? {} : { figureCoverage: figureCoverage(dir, plan.figures) }) };
170
212
  }