@staix/agent-research 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/README.md +92 -19
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +210 -67
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +75 -13
- package/src/exp/attempts.ts +66 -13
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +131 -15
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/protocol.ts +26 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/stages.ts +3 -1
- package/src/harness/hub-guidance.ts +16 -11
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +79 -24
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +20 -10
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
|
@@ -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
|
+
}
|
package/src/paper/hygiene.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
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
|
|
103
|
-
|
|
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:
|
|
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
|
|
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
|
-
|
|
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):
|
|
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
|
|
21
|
-
const directory = opendirSync(runs); let count = 0, found
|
|
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
|
|
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
|
-
|
|
38
|
-
found
|
|
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
|
-
|
|
56
|
-
return {resolved:
|
|
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};
|