@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.
@@ -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
  }
@@ -1,10 +1,11 @@
1
1
  import { readCard } from "../lit/cards.ts";
2
- import { ATTEMPT_BYTES, validateAttemptRecord } from "../exp/attempts.ts";
2
+ import { ATTEMPT_BYTES, validateAttemptRecord, type Attempt } from "../exp/attempts.ts";
3
3
  import { lstatSync, opendirSync } from "node:fs";
4
4
  import { join } from "node:path";
5
- import { openStudy, readTextBounded } from "../study.ts";
5
+ import { openStudy, plain, readTextBounded } from "../study.ts";
6
6
 
7
- export interface PointEvidenceResolution { resolved: boolean; reason?: string; code?: "run-limit" }
7
+ interface EvidenceArtifact { sha256: string; bytes: number; retained?: { attemptId: string; stage: string; sha256: string } }
8
+ export interface PointEvidenceResolution { resolved: boolean; reason?: string; code?: "run-limit"; artifacts?: EvidenceArtifact[] }
8
9
  /** Only typed local failure classes may become advice; never propagate a source's free-text error. */
9
10
  export function pointEvidenceAdvice(resolution: PointEvidenceResolution): string {
10
11
  return resolution.code === "run-limit" ? "more than 4096 run directories; archive the study before checking point evidence" : "restore the referenced card or attempt record, or revise the point evidence";
@@ -15,10 +16,10 @@ function physicalDirectory(file: string): boolean {
15
16
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
16
17
  }
17
18
  /** Read only the addressed payload; unrelated attempts never enter point planning or checking. */
18
- function existingAttempt(dir: string, wanted: string): boolean {
19
+ function existingAttempt(dir: string, wanted: string): Attempt | undefined {
19
20
  const {study} = openStudy(dir), runs = join(dir, "runs");
20
- if (study.mode !== "experiment" || !physicalDirectory(runs)) return false;
21
- const directory = opendirSync(runs); let count = 0, found = false;
21
+ if (study.mode !== "experiment" || !physicalDirectory(runs)) return undefined;
22
+ const directory = opendirSync(runs); let count = 0, found: Attempt | undefined;
22
23
  try {
23
24
  for (let entry = directory.readSync(); entry; entry = directory.readSync()) {
24
25
  if (++count > 4096) throw new PointEvidenceBound("point evidence: more than 4096 run directories; archive the study before checking point evidence");
@@ -30,18 +31,31 @@ function existingAttempt(dir: string, wanted: string): boolean {
30
31
  try {
31
32
  const stat = lstatSync(file);
32
33
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("unsafe attempt record");
33
- if (found) return false; // The address has no run component; duplicate matches are ambiguous.
34
+ if (found) return undefined; // The address has no run component; duplicate matches are ambiguous.
34
35
  raw = readTextBounded(file, ATTEMPT_BYTES, {noFollow: true});
35
36
  }
36
37
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
37
- if (validateAttemptRecord(JSON.parse(raw), entry.name, wanted).studyId !== study.id) return false;
38
- found = true;
38
+ found = validateAttemptRecord(JSON.parse(raw), entry.name, wanted);
39
+ if (found.studyId !== study.id) return undefined;
39
40
  }
40
41
  return found;
41
42
  } finally { directory.closeSync(); }
42
43
  }
44
+ function attemptArtifacts(attempt: Attempt): EvidenceArtifact[] {
45
+ const files = (raw: unknown, retained?: EvidenceArtifact["retained"]): EvidenceArtifact[] => {
46
+ if (!Array.isArray(raw)) return [];
47
+ return raw.flatMap(output => plain(output) && typeof output.sha256 === "string" && /^[a-f0-9]{64}$/.test(output.sha256)
48
+ && typeof output.bytes === "number" && Number.isSafeInteger(output.bytes) && output.bytes >= 0
49
+ ? [{sha256: output.sha256, bytes: output.bytes, ...(retained ? {retained} : {})}] : []);
50
+ };
51
+ if (!attempt.pipeline) return files(attempt.outputs);
52
+ return [
53
+ ...files(attempt.stages.evaluator?.evidence?.outputs),
54
+ ...attempt.pipeline.completed.flatMap(stage => files(stage.record.evidence?.outputs, stage.ref)),
55
+ ];
56
+ }
43
57
  /** Existence and record integrity only, never support, correctness or a successful outcome. */
44
- export function resolvePointEvidence(dir: string, reference: string): PointEvidenceResolution {
58
+ export function resolvePointEvidence(dir: string, reference: string, includeArtifacts = false): PointEvidenceResolution {
45
59
  if (typeof reference !== "string" || Buffer.byteLength(reference) > 4096 || reference.includes("\0")) return {resolved: false, reason: "invalid local evidence address; use card:<paper-id> or attempt:<16-hex-id>"};
46
60
  try {
47
61
  if (reference.startsWith("card:")) {
@@ -52,8 +66,9 @@ export function resolvePointEvidence(dir: string, reference: string): PointEvide
52
66
  if (reference.startsWith("attempt:")) {
53
67
  const id = reference.slice(8);
54
68
  if (!/^[a-f0-9]{16}$/.test(id)) return {resolved: false, reason: "attempt address is invalid; select an id from ares attempt list"};
55
- if (!existingAttempt(dir, id)) return {resolved: false, reason: "attempt is missing, ambiguous or belongs to another source; select a current-study record from ares attempt list"};
56
- return {resolved: true};
69
+ const attempt = existingAttempt(dir, id);
70
+ if (!attempt) return {resolved: false, reason: "attempt is missing, ambiguous or belongs to another source; select a current-study record from ares attempt list"};
71
+ return {resolved: true, ...(includeArtifacts ? {artifacts: attemptArtifacts(attempt)} : {})};
57
72
  }
58
73
  } catch (error) {
59
74
  if (error instanceof PointEvidenceBound) return {resolved: false, code: "run-limit", reason: error.message};
@@ -0,0 +1,113 @@
1
+ import { paperDocument, paperEventFor, type PaperDocument } from "./document.ts";
2
+ import { existsSync, lstatSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { commit, hashFileBounded, openStudy, plain, readBytesBounded, readLedger, sha256, type Actor } from "../study.ts";
5
+ import { readCurrentBuild } from "./build.ts";
6
+
7
+ /**
8
+ * External render receipts (#162). ares records what was rendered from which build; it never runs a renderer and
9
+ * never judges whether the rendering is faithful. `renderReceipt: 1` is renderer-agnostic.
10
+ */
11
+ export const RENDER_RECEIPT_VERSION = 1;
12
+ export const PAPER_RENDER_BYTES = 64 * 1024 * 1024, RENDER_RECEIPT_BYTES = 64 * 1024, RENDER_OUTPUTS = 16;
13
+ const HEX64 = /^[a-f0-9]{64}$/, NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
14
+ const renderFolder = (doc: PaperDocument) => doc === "slides" ? "slides.render" : "render";
15
+ export function paperRenderDir(dir: string, doc: PaperDocument = "manuscript") { return join(dir, "paper", "build", renderFolder(doc)); }
16
+ const receiptPath = (dir: string, doc: PaperDocument) => join(paperRenderDir(dir, doc), "receipt.json");
17
+
18
+ export interface RenderReceipt { v: 1; tool: string; version: string; environment: string; evidenceSha256: string; manuscriptSha256: string; template: string; outputs: { name: string; sha256: string; pages: number }[] }
19
+ function bad(detail: string): never { throw new Error(`paper render: receipt ${detail}; pass a renderReceipt v1 JSON with tool, version, environment, evidenceSha256, manuscriptSha256, template and outputs`); }
20
+ function identity(value: unknown, what: string): string {
21
+ if (typeof value !== "string" || !value.trim() || value.length > 256 || /[\u0000-\u001f]/.test(value)) bad(`${what} must be 1..256 characters without control characters`);
22
+ return value;
23
+ }
24
+ /** Unknown fields stay in the stored bytes; only a newer or unknown version is refused, leaving every file unchanged. */
25
+ export function validateRenderReceipt(raw: unknown): RenderReceipt {
26
+ if (!plain(raw)) bad("is not a JSON object");
27
+ if (raw.v !== RENDER_RECEIPT_VERSION) throw new Error(`paper render: unsupported receipt version ${JSON.stringify(raw.v)?.slice(0, 20)}; use an ares version that supports it; nothing was recorded`);
28
+ for (const key of ["evidenceSha256", "manuscriptSha256"] as const) if (typeof raw[key] !== "string" || !HEX64.test(raw[key] as string)) bad(`${key} must be a lowercase SHA-256`);
29
+ if (!Array.isArray(raw.outputs) || raw.outputs.length < 1 || raw.outputs.length > RENDER_OUTPUTS) bad(`outputs must list 1..${RENDER_OUTPUTS} files`);
30
+ const names = new Set<string>();
31
+ const outputs = raw.outputs.map((item: unknown) => {
32
+ if (!plain(item) || typeof item.name !== "string" || !NAME.test(item.name) || item.name === "receipt.json") bad("output name must be a plain file name other than receipt.json");
33
+ if (typeof item.sha256 !== "string" || !HEX64.test(item.sha256)) bad("output sha256 must be a lowercase SHA-256");
34
+ if (typeof item.pages !== "number" || !Number.isSafeInteger(item.pages) || item.pages < 0) bad("output pages must be a nonnegative integer");
35
+ if (names.has(item.name)) bad(`output ${item.name} is listed twice`);
36
+ names.add(item.name);
37
+ return { name: item.name, sha256: item.sha256, pages: item.pages };
38
+ });
39
+ return { v: 1, tool: identity(raw.tool, "tool"), version: identity(raw.version, "version"), environment: identity(raw.environment, "environment"), evidenceSha256: raw.evidenceSha256 as string, manuscriptSha256: raw.manuscriptSha256 as string, template: identity(raw.template, "template"), outputs };
40
+ }
41
+ function parseReceipt(bytes: Buffer): RenderReceipt {
42
+ let raw: unknown;
43
+ try { raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { bad("is not valid UTF-8 JSON"); }
44
+ return validateRenderReceipt(raw);
45
+ }
46
+ /** The reserved derived path must be real directories, so a stored file never lands outside the study. */
47
+ function assertReservedPath(dir: string, doc: PaperDocument): void {
48
+ for (const part of [join(dir, "paper"), join(dir, "paper", "build"), paperRenderDir(dir, doc)]) {
49
+ if (!existsSync(part)) continue;
50
+ const info = lstatSync(part);
51
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error(`paper render: paper/build/${renderFolder(doc)} must be a real directory without symbolic links; restore it before recording`);
52
+ }
53
+ }
54
+
55
+ /** Caller holds the study lock. Every check precedes the single file-and-receipt commit. */
56
+ export function recordPaperRender(dirArg: string, file: string, receiptFile: string, actor: Actor, doc: PaperDocument = "manuscript") {
57
+ paperDocument(doc);
58
+ const { dir } = openStudy(dirArg);
59
+ let receiptBytes: Buffer, output: Buffer;
60
+ try { receiptBytes = readBytesBounded(receiptFile, RENDER_RECEIPT_BYTES, { noFollow: true }); }
61
+ catch { throw new Error(`paper render: receipt is missing, a symbolic link, not a regular file or larger than ${RENDER_RECEIPT_BYTES} bytes; pass the renderer's receipt JSON file`); }
62
+ const receipt = parseReceipt(receiptBytes);
63
+ try { output = readBytesBounded(file, PAPER_RENDER_BYTES, { noFollow: true }); }
64
+ catch { throw new Error(`paper render: file is missing, a symbolic link, not a regular file or larger than ${PAPER_RENDER_BYTES} bytes; pass the rendered document itself`); }
65
+ const current = readCurrentBuild(dir, doc), outputSha256 = sha256(output);
66
+ if (receipt.evidenceSha256 !== current.evidenceSha256) throw new Error(`paper render: receipt evidenceSha256 does not match the current paper/build/${doc === "slides" ? "slides.evidence.json" : "evidence.json"}; render the current build and retry`);
67
+ if (receipt.manuscriptSha256 !== current.manuscriptSha256) throw new Error("paper render: receipt manuscriptSha256 does not match the current rendered manuscript; render the current build and retry");
68
+ const entry = receipt.outputs.find(item => item.sha256 === outputSha256);
69
+ if (!entry) throw new Error("paper render: the file's SHA-256 matches no output in the receipt; pass the file the receipt describes");
70
+ assertReservedPath(dir, doc);
71
+ const receiptSha256 = sha256(receiptBytes), stored = join(paperRenderDir(dir, doc), entry.name);
72
+ const last = readLedger(dir).findLast(event => paperEventFor(event, "paper.rendered", doc));
73
+ const same = last?.data.receiptSha256 === receiptSha256 && last.data.outputSha256 === outputSha256 && last.data.name === entry.name && stillStored(dir, entry.name, outputSha256, receiptSha256, doc);
74
+ const result = { evidenceSha256: current.evidenceSha256, outputSha256, bytes: output.length, name: entry.name, receiptSha256, path: `paper/build/${renderFolder(doc)}/${entry.name}` };
75
+ if (same) return { ...result, changed: false };
76
+ commit(dir, [[stored, output, PAPER_RENDER_BYTES], [receiptPath(dir, doc), receiptBytes, RENDER_RECEIPT_BYTES]], [{ actor, type: "paper.rendered", data: {
77
+ ...(doc === "slides" ? { doc } : {}), evidenceSha256: current.evidenceSha256, manuscriptSha256: current.manuscriptSha256, outputSha256, bytes: output.length, name: entry.name, receiptSha256,
78
+ renderer: { tool: receipt.tool, version: receipt.version, environment: receipt.environment }, template: receipt.template,
79
+ } }]);
80
+ return { ...result, changed: true };
81
+ }
82
+ function stillStored(dir: string, name: string, outputSha256: string, receiptSha256: string, doc: PaperDocument): boolean {
83
+ try {
84
+ return hashFileBounded(join(paperRenderDir(dir, doc), name), PAPER_RENDER_BYTES, { noFollow: true }).sha256 === outputSha256
85
+ && sha256(readBytesBounded(receiptPath(dir, doc), RENDER_RECEIPT_BYTES, { noFollow: true })) === receiptSha256;
86
+ } catch { return false; }
87
+ }
88
+
89
+ export interface RenderStatus {
90
+ current: boolean;
91
+ reason: string | null;
92
+ render: { evidenceSha256: string; outputSha256: string; bytes: number; name: string; path: string; receiptSha256: string; renderer: unknown; template: unknown; at: string } | null;
93
+ }
94
+ /** Read-only. A rebuild with a new evidence hash makes the last render stale without deleting it. */
95
+ export function showPaperRender(dirArg: string, doc: PaperDocument = "manuscript"): RenderStatus {
96
+ paperDocument(doc);
97
+ const { dir } = openStudy(dirArg), last = readLedger(dir).findLast(event => paperEventFor(event, "paper.rendered", doc));
98
+ if (!last) return { current: false, reason: "no render recorded; run ares paper render record after rendering the current build", render: null };
99
+ const data = last.data, name = typeof data.name === "string" && NAME.test(data.name) ? data.name : undefined;
100
+ if (!name || typeof data.evidenceSha256 !== "string" || typeof data.outputSha256 !== "string" || typeof data.receiptSha256 !== "string") return { current: false, reason: "the last paper.rendered event is malformed; record the render again", render: null };
101
+ const render = { evidenceSha256: data.evidenceSha256, outputSha256: data.outputSha256, bytes: typeof data.bytes === "number" ? data.bytes : 0, name, path: `paper/build/${renderFolder(doc)}/${name}`, receiptSha256: data.receiptSha256, renderer: data.renderer ?? null, template: data.template ?? null, at: last.at };
102
+ let build: ReturnType<typeof readCurrentBuild>;
103
+ try { build = readCurrentBuild(dir, doc); }
104
+ catch { return { current: false, reason: `no current paper build; run ares paper build${doc === "slides" ? " --doc slides" : ""}, render it and record the render`, render }; }
105
+ if (build.evidenceSha256 !== data.evidenceSha256 || build.manuscriptSha256 !== data.manuscriptSha256) return { current: false, reason: "the recorded render belongs to an earlier build; render the current build and record it", render };
106
+ if (!stillStored(dir, name, data.outputSha256, data.receiptSha256, doc)) return { current: false, reason: "the stored render or receipt changed or is missing; record the render again", render };
107
+ return { current: true, reason: null, render };
108
+ }
109
+ /** Never throws: summaries for review show and archive preview. */
110
+ export function renderSummary(dir: string): { current: boolean; reason: string | null } {
111
+ try { const status = showPaperRender(dir); return { current: status.current, reason: status.reason }; }
112
+ catch (error) { return { current: false, reason: error instanceof Error ? error.message : "render status unavailable" }; }
113
+ }