@staix/agent-research 0.2.1 → 0.3.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 +107 -0
- package/README.md +255 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +192 -32
- package/src/exp/attempts.ts +500 -65
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +6 -5
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +85 -18
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +63 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +87 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +3 -3
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
package/src/memory/skills.ts
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {inspectSkillEvidenceSet, compareSkillInspections, evidenceFingerprint, requireSkillEvidence, unsupportedSourceGuidance, type SkillCheckOptions} from "./skill-check.ts";
|
|
2
|
+
import type {EvidenceInspection} from "./evidence.ts";
|
|
3
|
+
import {canonical} from "../plan/state.ts";
|
|
4
|
+
import {skillMarkdownV2, validateSkillProposalV2, validateSkillInputV2, validateSkillInspections, type SkillProposalV2} from "./skill-format.ts";
|
|
5
|
+
import { lstatSync } from "node:fs";
|
|
2
6
|
import { join } from "node:path";
|
|
3
|
-
import { assertWritable, boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, sha256, type Actor, type LedgerEvent } from "../study.ts";
|
|
7
|
+
import { assertWritable, boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, sha256, assertStudyReadLock, type Actor, type LedgerEvent } from "../study.ts";
|
|
4
8
|
|
|
5
|
-
export const SKILL_PROPOSAL_VERSION =
|
|
9
|
+
export const SKILL_PROPOSAL_VERSION = 2, SKILL_PROPOSALS = 100, SKILL_BYTES = 16 * 1024, SKILL_EVIDENCE = 64;
|
|
6
10
|
export interface SkillProposal { name: string; summary: string; steps: string[]; evidence: string[] }
|
|
7
11
|
export type SkillDecision = "accept" | "reject" | "withdraw";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
decision?: { action: SkillDecision; reason: string; pr?: string; actor: Actor; at: string };
|
|
12
|
+
interface SkillRecordState {
|
|
13
|
+
state: "proposed" | "accepted" | "rejected" | "withdrawn"; sha256: string; actor: Actor; at: string;
|
|
14
|
+
decision?: { action: SkillDecision; reason: string; pr?: string; actor: Actor; at: string; evidenceFingerprint?: string; inspections?: EvidenceInspection[]; localGeneration?: string | null };
|
|
11
15
|
}
|
|
16
|
+
export type SkillRecord = SkillRecordState & (SkillProposal & {skillProposal: 1; evidenceStatus: "legacy-unresolved"} | SkillProposalV2 & {skillProposal: 2; evidenceStatus: "inspection-required"});
|
|
17
|
+
|
|
12
18
|
function bad(message: string): never { throw new Error(`skill: ${message}; inspect ares skill list, correct the input or restore the last valid proposal and retry`); }
|
|
13
19
|
function nameOf(value: unknown): string {
|
|
14
20
|
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value)) bad("name must follow the run-name rule (1..64 letters, digits, underscores or hyphens)");
|
|
@@ -47,22 +53,32 @@ function prOf(value: unknown, action: SkillDecision): string | undefined {
|
|
|
47
53
|
catch { bad("PR must be an HTTP(S) URL without credentials"); }
|
|
48
54
|
return result;
|
|
49
55
|
}
|
|
50
|
-
function version(event: LedgerEvent):
|
|
51
|
-
if (event.data.skillProposal !== 1) throw new Error("skill proposal: unsupported version; use an ares version supporting this journal and keep its files unchanged");
|
|
56
|
+
function version(event: LedgerEvent): 1 | 2 {
|
|
57
|
+
if (event.data.skillProposal !== 1 && event.data.skillProposal !== 2) throw new Error("skill proposal: unsupported version; use an ares version supporting this journal and keep its files unchanged");
|
|
58
|
+
return event.data.skillProposal;
|
|
52
59
|
}
|
|
53
60
|
export function foldSkills(events: LedgerEvent[]): SkillRecord[] {
|
|
54
61
|
const rows = new Map<string, SkillRecord>();
|
|
55
62
|
for (const event of events) {
|
|
56
63
|
if (event.type === "skill.proposed") {
|
|
57
|
-
version(event)
|
|
64
|
+
const v = version(event), proposal = v === 1 ? validateSkillProposal(event.data.proposal, false) : validateSkillProposalV2(event.data.proposal), hash = sha256(v === 1 ? markdown(proposal as SkillProposal) : skillMarkdownV2(proposal as SkillProposalV2));
|
|
58
65
|
if (event.data.sha256 !== hash || rows.has(proposal.name) || rows.size >= SKILL_PROPOSALS) bad("journal has a mismatched hash, duplicate name or more than 100 proposals");
|
|
59
|
-
rows.set(proposal.name, { ...proposal, skillProposal: 1, state: "proposed", sha256: hash, actor: event.actor, at: event.at });
|
|
66
|
+
rows.set(proposal.name, { ...proposal, skillProposal: v, evidenceStatus: v === 1 ? "legacy-unresolved" : "inspection-required", state: "proposed", sha256: hash, actor: event.actor, at: event.at } as SkillRecord);
|
|
60
67
|
} else if (event.type === "skill.decided") {
|
|
61
|
-
version(event)
|
|
62
|
-
if (!row || row.state !== "proposed") bad("decision references a missing or already decided proposal");
|
|
68
|
+
const v = version(event), name = nameOf(event.data.name), row = rows.get(name), action = decisionOf(event.data.decision);
|
|
69
|
+
if (!row || row.state !== "proposed" || row.skillProposal !== v) bad("decision references a missing, mismatched-version or already decided proposal");
|
|
63
70
|
const reason = text(event.data.reason, "reason"), pr = prOf(event.data.pr, action);
|
|
71
|
+
if (v === 2 && action === "accept" && (typeof event.data.evidenceFingerprint !== "string" || !/^[a-f0-9]{64}$/.test(event.data.evidenceFingerprint))) bad("v2 acceptance lacks its evidence fingerprint; restore the original decision event");
|
|
72
|
+
let observed: EvidenceInspection[] | undefined, localGeneration: string | null | undefined;
|
|
73
|
+
if (row.skillProposal === 2 && action === "accept") {
|
|
74
|
+
observed = validateSkillInspections(event.data.inspections, [...row.evidence, ...row.counterevidence]);
|
|
75
|
+
localGeneration = event.data.localGeneration as string | null;
|
|
76
|
+
const hasLocal = observed.some(inspection => inspection.ref?.tool === "ares");
|
|
77
|
+
if (hasLocal ? typeof localGeneration !== "string" || localGeneration.length !== 64 || !/^[a-f0-9]{64}$/.test(localGeneration) : localGeneration !== null) bad("v2 acceptance localGeneration must be a 64-hex digest exactly when inspections include ares refs, otherwise null; restore its original receipt");
|
|
78
|
+
if (compareSkillInspections(row.inspections, observed).length || event.data.evidenceFingerprint !== evidenceFingerprint(row.sha256, observed, localGeneration)) bad("v2 acceptance has mismatched evidence inspection/fingerprint; restore its original receipt");
|
|
79
|
+
}
|
|
64
80
|
row.state = action === "accept" ? "accepted" : action === "reject" ? "rejected" : "withdrawn";
|
|
65
|
-
row.decision = { action, reason, ...(pr === undefined ? {} : { pr }), actor: event.actor, at: event.at };
|
|
81
|
+
row.decision = { action, reason, ...(pr === undefined ? {} : { pr }), actor: event.actor, at: event.at, ...(v === 2 && action === "accept" ? {evidenceFingerprint: event.data.evidenceFingerprint as string, inspections: observed!, localGeneration: localGeneration!} : {}) };
|
|
66
82
|
}
|
|
67
83
|
}
|
|
68
84
|
return [...rows.values()];
|
|
@@ -71,29 +87,59 @@ function file(dir: string, name: string): string { return join(dir, "proposals",
|
|
|
71
87
|
/** Read only tracked proposals; every file is regular/bounded and bound to its original event. */
|
|
72
88
|
function readSkills(dirArg: string) {
|
|
73
89
|
const { dir } = openStudy(dirArg), events = readLedger(dir), rows = foldSkills(events);
|
|
90
|
+
for (const parent of [join(dir, "proposals"), join(dir, "proposals", "skills")]) {const stat = lstatSync(parent, {throwIfNoEntry: false}); if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) bad("proposal directory is linked or not regular; restore the committed study tree");}
|
|
74
91
|
for (const row of rows) {
|
|
75
92
|
let content: string;
|
|
76
|
-
try { content = readTextBounded(file(dir, row.name), SKILL_BYTES); } catch { bad("proposal file missing, unreadable or larger than 16 KiB; restore its committed Markdown"); }
|
|
77
|
-
if (!content.startsWith(
|
|
93
|
+
try { content = readTextBounded(file(dir, row.name), SKILL_BYTES, {noFollow: true}); } catch { bad("proposal file missing, unreadable or larger than 16 KiB; restore its committed Markdown"); }
|
|
94
|
+
if (!content.startsWith(`---\nskillProposal: ${row.skillProposal}\n`)) throw new Error("skill proposal file: unsupported version; use an ares version supporting this file and keep it unchanged");
|
|
78
95
|
if (sha256(content) !== row.sha256) bad("proposal file differs from its receipt; restore the original Markdown");
|
|
79
96
|
}
|
|
80
97
|
return { dir, events, rows };
|
|
81
98
|
}
|
|
82
99
|
export function listSkills(dir: string): SkillRecord[] { return readSkills(dir).rows; }
|
|
83
100
|
/** Caller holds the study lock. One bounded file and one event share the existing commit preflight. */
|
|
84
|
-
export function proposeSkill(dirArg: string, raw: unknown, actor: Actor): SkillRecord {
|
|
85
|
-
const
|
|
86
|
-
if (rows.length >= SKILL_PROPOSALS) bad("100-proposal limit reached; start a new study for further proposals");
|
|
87
|
-
if (rows.some(row => row.name ===
|
|
88
|
-
const
|
|
89
|
-
const
|
|
90
|
-
|
|
101
|
+
export async function proposeSkill(dirArg: string, raw: unknown, actor: Actor, options: SkillCheckOptions = {}): Promise<SkillRecord> {
|
|
102
|
+
const {dir, study} = openStudy(dirArg), input = validateSkillInputV2(raw, study.id), current = readSkills(dir);
|
|
103
|
+
if (current.rows.length >= SKILL_PROPOSALS) bad("100-proposal limit reached; start a new study for further proposals");
|
|
104
|
+
if (current.rows.some(row => row.name === input.name) || lstatSync(file(dir, input.name), {throwIfNoEntry: false})) bad("name or proposal file already exists; choose a new name without replacing prior work");
|
|
105
|
+
const refs = [...new Map([...input.evidence, ...input.counterevidence].map(ref => [canonical(ref), ref])).values()];
|
|
106
|
+
const checked = await inspectSkillEvidenceSet(dir, refs, options);
|
|
107
|
+
if (canonical(readSkills(dir).rows) !== canonical(current.rows)) requireSkillEvidence("proposal journal changed during inspection", "propose");
|
|
108
|
+
if (!checked.recheck()) requireSkillEvidence(checked.localFailure === "unsupported" ? "unsupported ares source record version" : "local source changed or aggregate source budget exhausted during proposal inspection", "propose", checked.inspections);
|
|
109
|
+
const proposal = validateSkillProposalV2({...input, inspections: checked.inspections}, study.id);
|
|
110
|
+
const content = skillMarkdownV2(proposal), hash = sha256(content);
|
|
111
|
+
const added = commit(dir, [[file(dir, proposal.name), content, SKILL_BYTES]], [{actor, type: "skill.proposed", data: {skillProposal: 2, proposal, sha256: hash}}]);
|
|
112
|
+
return foldSkills([...current.events, ...added]).find(row => row.name === proposal.name)!;
|
|
113
|
+
}
|
|
114
|
+
export async function checkSkill(dir: string, name: string, options: SkillCheckOptions = {}) {
|
|
115
|
+
const target = nameOf(name); let row: SkillRecord | undefined;
|
|
116
|
+
try {row = readSkills(dir).rows.find(row => row.name === target);}
|
|
117
|
+
catch (cause) {return {name: target, state: cause instanceof Error && cause.message.includes("unsupported") ? "unsupported" : "unavailable", inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: cause instanceof Error && cause.message.includes("unsupported") ? "use a compatible ares version or restore the local record, keeping bytes unchanged; run ares skill check again" : "Restore the versioned study/proposal and its receipts, then run ares skill check again; keep unsupported versions unchanged"};}
|
|
118
|
+
if (!row) return {name: target, state: "missing", inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: "Select a recorded name with ares skill list or create a new proposal"};
|
|
119
|
+
if (row.skillProposal === 1) return {name: row.name, proposalSha256: row.sha256, skillProposal: 1, state: "unsupported", legacyUnresolved: true, inspections: [], acceptReady: false, support: "reviewer-judgment", nextStep: row.state === "proposed" ? "Legacy bytes/decisions are preserved; create a new v2 proposal for evidence-backed checks" : "Decision is final; create a revised v2 proposal for new evidence. Legacy bytes and the recorded decision remain unchanged"};
|
|
120
|
+
const refs = [...new Map([...row.evidence, ...row.counterevidence].map(ref => [canonical(ref), ref])).values()], checked = await inspectSkillEvidenceSet(dir, refs, options), reasons = compareSkillInspections(row.inspections, checked.inspections);
|
|
121
|
+
try {if (canonical(readSkills(dir).rows.find(current => current.name === row.name)) !== canonical(row)) reasons.push("proposal-changed");} catch {reasons.push("proposal-changed");}
|
|
122
|
+
if (!checked.recheck()) reasons.push(checked.localFailure ?? "local-source-changed-or-budget-exhausted");
|
|
123
|
+
const sourceGuidance = unsupportedSourceGuidance(checked.inspections);
|
|
124
|
+
const sourcesReady = reasons.length === 0, ready = sourcesReady && row.state === "proposed", state = sourcesReady ? "available" : checked.remainingMs <= 0 ? "unavailable" : reasons.some(reason => reason.includes("changed")) ? "changed" : reasons.includes("unsupported") ? "unsupported" : reasons.includes("missing") ? "missing" : "unavailable";
|
|
125
|
+
return {name: row.name, proposalSha256: row.sha256, skillProposal: 2, state, inspections: checked.inspections, acceptReady: ready, support: "reviewer-judgment", evidenceFingerprint: evidenceFingerprint(row.sha256, checked.inspections, checked.localGeneration), localGeneration: checked.localGeneration, responseBytes: checked.bytes, reasons, nextStep: row.state !== "proposed" ? `Decision is final; create a revised proposal for new evidence${sourceGuidance ? `; ${sourceGuidance}` : ""}` : ready ? "Source integrity is not support: a reviewer decides using the supplied PR reference" : state === "unsupported" ? `${sourceGuidance || "use a supporting source reader"}; create a revised proposal with current evidence/counterevidence and honest limitations` : "Create a revised proposal with current evidence/counterevidence and honest limitations"};
|
|
91
126
|
}
|
|
92
|
-
/** Final
|
|
93
|
-
export function decideSkill(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, actor: Actor): SkillRecord {
|
|
94
|
-
const target = nameOf(name), action = decisionOf(decision), why = text(reason, "reason"), reference = prOf(pr, action), {
|
|
127
|
+
/** Caller holds the owned study lock. Final decisions never open, inspect or merge a PR. */
|
|
128
|
+
export async function decideSkill(dirArg: string, name: string, decision: string, reason: string, pr: string | undefined, actor: Actor, options: SkillCheckOptions = {}): Promise<SkillRecord> {
|
|
129
|
+
const target = nameOf(name), action = decisionOf(decision), why = text(reason, "reason"), reference = prOf(pr, action), {dir, events, rows} = readSkills(dirArg);
|
|
95
130
|
const row = rows.find(row => row.name === target);
|
|
96
131
|
if (!row || row.state !== "proposed") bad("proposal is missing or already decided; decisions including withdrawal are final");
|
|
97
|
-
|
|
132
|
+
let evidence: {evidenceFingerprint: string; inspections: EvidenceInspection[]; localGeneration: string | null} | undefined;
|
|
133
|
+
if (row.skillProposal === 2 && action === "accept") {
|
|
134
|
+
if (!options.lock) requireSkillEvidence("v2 acceptance requires an owned study transaction"); assertStudyReadLock(dir, options.lock);
|
|
135
|
+
const checked = await inspectSkillEvidenceSet(dir, [...new Map([...row.evidence, ...row.counterevidence].map(ref => [canonical(ref), ref])).values()], options), reasons = compareSkillInspections(row.inspections, checked.inspections);
|
|
136
|
+
if (reasons.length) requireSkillEvidence(`required evidence or counterevidence is changed/unavailable (${[...new Set(reasons)].join(", ")})`, "accept", checked.inspections);
|
|
137
|
+
if (canonical(readSkills(dir).rows) !== canonical(rows) || !checked.recheck()) requireSkillEvidence("local source/proposal changed or aggregate source budget exhausted before decision");
|
|
138
|
+
assertStudyReadLock(dir, options.lock);
|
|
139
|
+
evidence = {evidenceFingerprint: evidenceFingerprint(row.sha256, checked.inspections, checked.localGeneration), inspections: checked.inspections, localGeneration: checked.localGeneration};
|
|
140
|
+
}
|
|
141
|
+
const pending = {actor, type: "skill.decided", data: {skillProposal: row.skillProposal, name: target, decision: action, reason: why, ...(reference === undefined ? {} : {pr: reference}), ...evidence}};
|
|
142
|
+
foldSkills([...events, {v: 1, at: new Date().toISOString(), ...pending}]);
|
|
143
|
+
const added = commit(dir, [], [pending]);
|
|
98
144
|
return foldSkills([...events, ...added]).find(row => row.name === target)!;
|
|
99
145
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** One check/accept owns one response budget; local producer projections and all amem stdio bytes share it. */
|
|
2
|
+
export const SOURCE_MS = 25_000, SOURCE_BYTES = 262_144;
|
|
3
|
+
export interface SourceBudget {remainingBytes: number; remainingMs(): number; consume(bytes: number): boolean; exhaust(): void}
|
|
4
|
+
export function sourceBudget(now: () => number = Date.now): SourceBudget {
|
|
5
|
+
const start = now(), wallStart = performance.now(); let last = start;
|
|
6
|
+
return {remainingBytes: SOURCE_BYTES,
|
|
7
|
+
remainingMs() {const current = now(); if (!Number.isFinite(current) || current < last || !Number.isFinite(start)) return 0; last = current; return Math.max(0, Math.min(SOURCE_MS - (current - start), SOURCE_MS - (performance.now() - wallStart)));},
|
|
8
|
+
consume(bytes) {if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.remainingBytes) {this.remainingBytes = 0; return false;} this.remainingBytes -= bytes; return this.remainingMs() > 0;},
|
|
9
|
+
exhaust() {this.remainingBytes = 0;},
|
|
10
|
+
};
|
|
11
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { PROCESS_CONTEXT_ENV_KEYS, spawnRunner, type ProcessRunner } from "../exp/executor.ts";
|
|
2
|
+
import { isVerified, loadCandidates, type Candidate } from "../lit/candidates.ts";
|
|
3
|
+
import { CARD_BYTES, CARD_FIELDS, cardPath, readCard, validateCard, validateProvenance, type Card, type CardProvenance, type StoredCard } from "../lit/cards.ts";
|
|
4
|
+
import { boundedText, commit, onlyKeys, openStudy, plain, prepareCommit, readLedger, sha256, withLock, type Actor, type PendingEvent } from "../study.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Cross-study card reuse through vault-mem reference notes (#101). A reused card is a planning aid only:
|
|
8
|
+
* nothing here touches verification, screening, gates or the bibliography.
|
|
9
|
+
*/
|
|
10
|
+
export const VAULT_OUTPUT_BYTES = 262_144, CARD_SECTION = "ares card", MAX_CARD_IDS = 50;
|
|
11
|
+
const VAULT_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/, NOTE = /^[a-z0-9][a-z0-9._-]{0,199}$/, SHA = /^[a-f0-9]{64}$/;
|
|
12
|
+
export interface VaultNoteRef { path: string; doi?: string; arxivId?: string }
|
|
13
|
+
export interface VaultClient {
|
|
14
|
+
/** Reference notes whose frontmatter doi/arxiv_id equals the identifier exactly. */
|
|
15
|
+
findReference(identifier: { doi?: string; arxivId?: string; citekey?: string; title?: string }): Promise<VaultNoteRef[]>;
|
|
16
|
+
/** The note's current hash and the ares card block, or undefined when the note has no card section. */
|
|
17
|
+
readCard(path: string): Promise<{ hash: string; block?: string }>;
|
|
18
|
+
/** Append the card section, guarded by the hash just read. */
|
|
19
|
+
appendCard(path: string, expectedSha: string, markdown: string): Promise<void>;
|
|
20
|
+
/** Replace an existing card section's block, guarded by the hash just read. */
|
|
21
|
+
replaceCard(path: string, expectedSha: string, oldBlock: string, newBlock: string): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fail(what: string): never { throw new Error(`vault-mem ${what}; check vmem --version and vmem status, then retry`); }
|
|
25
|
+
/** The process boundary returns projections only; raw output and note bodies never reach errors or the study. */
|
|
26
|
+
export function createVaultClient(vault: string, cwd: string, runner: ProcessRunner = spawnRunner, env: NodeJS.ProcessEnv = process.env): VaultClient {
|
|
27
|
+
if (!VAULT_ID.test(vault)) throw new Error("--vault: registered vault id (lower-case letters, digits, - or _); list them with vmem vaults list");
|
|
28
|
+
const context = Object.fromEntries([...PROCESS_CONTEXT_ENV_KEYS, "HOME", "PATH", "VMEM_HOME"].flatMap(key => env[key] === undefined ? [] : [[key, env[key]!]]));
|
|
29
|
+
const call = async (args: string[], stdin?: string): Promise<{ code: number; json: unknown; unknownSection: boolean }> => {
|
|
30
|
+
let result;
|
|
31
|
+
try { result = await runner({ command: "vmem", args: [...args, "--json"], cwd, env: context, ...(stdin === undefined ? {} : { stdin: Buffer.from(stdin, "utf8") }), maxOutputBytes: VAULT_OUTPUT_BYTES, timeoutMs: 30_000 }); }
|
|
32
|
+
catch { fail("spawn failure (is vmem on PATH?)"); }
|
|
33
|
+
if (result.truncated || Buffer.byteLength(result.stdout) > VAULT_OUTPUT_BYTES) fail("over-bound output");
|
|
34
|
+
if (result.timedOut) fail("timeout");
|
|
35
|
+
let json: unknown;
|
|
36
|
+
try { json = result.stdout.trim() ? JSON.parse(result.stdout) : undefined; } catch { fail("bad JSON"); }
|
|
37
|
+
// Only this exact diagnostic is classified; stderr is never copied into errors or the study.
|
|
38
|
+
return { code: result.exitCode, json, unknownSection: result.exitCode !== 0 && /section: unknown H2 heading/.test(result.stderr) };
|
|
39
|
+
};
|
|
40
|
+
const notePath = (path: string) => { if (!NOTE.test(path)) fail("returned an invalid note path"); return path; };
|
|
41
|
+
// vmem parses any argument that starts with "-" as an option and has no "--" separator, so such terms are never sent.
|
|
42
|
+
const term = (value: string) => value && !value.startsWith("-") && Buffer.byteLength(value) <= 1024 && !/[\r\n]/.test(value) ? value : undefined;
|
|
43
|
+
return {
|
|
44
|
+
async findReference(identifier) {
|
|
45
|
+
// vault-mem indexes a reference note's doi and citekey for search, not arxiv_id. An arXiv-only candidate is found
|
|
46
|
+
// through its arXiv DOI, its citekey, the bare id or its title in the note text; every hit is then matched on
|
|
47
|
+
// frontmatter exactly, so a broad title search can never select the wrong note.
|
|
48
|
+
const title = identifier.title?.replace(/[^\p{L}\p{N}\s]+/gu, " ").trim().split(/\s+/).slice(0, 12).join(" ");
|
|
49
|
+
const terms = [...new Set([identifier.doi, identifier.arxivId ? `10.48550/arxiv.${identifier.arxivId.replace(/v\d+$/, "")}` : undefined, identifier.citekey, identifier.arxivId?.replace(/v\d+$/, ""), identifier.arxivId ? title : undefined].flatMap(v => v && term(v) ? [v] : []))];
|
|
50
|
+
const paths = new Set<string>();
|
|
51
|
+
for (const query of terms) {
|
|
52
|
+
const { code, json } = await call(["search", vault, query, "--type", "reference", "--limit", "20"]);
|
|
53
|
+
if (code !== 0 || !Array.isArray(json)) fail("search failed");
|
|
54
|
+
for (const row of json) { if (!plain(row) || typeof row.path !== "string") fail("search returned an invalid row"); paths.add(notePath(row.path)); }
|
|
55
|
+
}
|
|
56
|
+
const found: VaultNoteRef[] = [], wantDoi = identifier.doi?.toLowerCase(), wantArxiv = identifier.arxivId?.replace(/v\d+$/, "");
|
|
57
|
+
for (const path of paths) {
|
|
58
|
+
const shown = await call(["show", vault, path, "--max-bytes", "65536"]);
|
|
59
|
+
if (shown.code !== 0 || !plain(shown.json) || typeof shown.json.content !== "string") fail("show failed");
|
|
60
|
+
const head = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(shown.json.content)?.[1];
|
|
61
|
+
// A frontmatter block that does not close within the read bound is refused, never read as "no identifier".
|
|
62
|
+
if (head === undefined) fail(`note ${path} has no complete frontmatter within 64 KiB`);
|
|
63
|
+
const doi = /^doi:\s*["']?([^"'\s]+)["']?\s*$/m.exec(head)?.[1]?.toLowerCase(), arxivId = /^arxiv_id:\s*["']?([^"'\s]+)["']?\s*$/m.exec(head)?.[1]?.replace(/v\d+$/, "");
|
|
64
|
+
const arxivDoi = doi && /^10\.48550\/arxiv\.(.+)$/.exec(doi)?.[1];
|
|
65
|
+
if ((wantDoi && doi === wantDoi) || (wantArxiv && (arxivId === wantArxiv || arxivDoi === wantArxiv.toLowerCase()))) found.push({ path, ...(doi ? { doi } : {}), ...(arxivId ? { arxivId } : {}) });
|
|
66
|
+
}
|
|
67
|
+
return found;
|
|
68
|
+
},
|
|
69
|
+
async readCard(path) {
|
|
70
|
+
const whole = await call(["show", vault, notePath(path), "--max-bytes", "1"]);
|
|
71
|
+
if (whole.code !== 0 || !plain(whole.json) || typeof whole.json.hash !== "string" || !SHA.test(whole.json.hash)) fail("show failed");
|
|
72
|
+
const section = await call(["show", vault, path, "--section", CARD_SECTION, "--max-bytes", "65536"]);
|
|
73
|
+
if (section.code !== 0) { if (section.unknownSection) return { hash: whole.json.hash }; fail(`could not read the ${CARD_SECTION} section (it may be duplicated)`); }
|
|
74
|
+
if (!plain(section.json) || typeof section.json.content !== "string" || section.json.hash !== whole.json.hash) fail("show changed during the read");
|
|
75
|
+
// A section over the bound is refused rather than read as absent, so export never appends a second card section.
|
|
76
|
+
if (section.json.truncated === true) fail(`the ${CARD_SECTION} section of ${path} exceeds 64 KiB; shorten it in the vault note`);
|
|
77
|
+
const blocks = [...section.json.content.matchAll(/```json\n([\s\S]*?)\n```/g)];
|
|
78
|
+
if (blocks.length > 1) fail(`the ${CARD_SECTION} section of ${path} holds more than one json block; keep one`);
|
|
79
|
+
if (!blocks.length) fail(`the ${CARD_SECTION} section of ${path} has no json block; restore it or remove the section`);
|
|
80
|
+
return { hash: whole.json.hash, block: blocks[0]![1]! };
|
|
81
|
+
},
|
|
82
|
+
async appendCard(path, expectedSha, markdown) {
|
|
83
|
+
const { code, json } = await call(["append", vault, notePath(path), "--section", CARD_SECTION, "--markdown", markdown, "--expected-sha", expectedSha]);
|
|
84
|
+
if (code !== 0 || !plain(json) || json.ok !== true || json.applied !== true) fail("append refused (the note may have changed or failed validation)");
|
|
85
|
+
},
|
|
86
|
+
async replaceCard(path, expectedSha, oldBlock, newBlock) {
|
|
87
|
+
const { code, json } = await call(["patch", vault, notePath(path), "--old", oldBlock, "--new", newBlock, "--expected-sha", expectedSha]);
|
|
88
|
+
if (code !== 0 || !plain(json) || json.ok !== true || json.applied !== true) fail("patch refused (the note may have changed or failed validation)");
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The vault payload: card fields plus provenance, the study hashed and nothing else from the study. */
|
|
94
|
+
interface VaultCardPayload { v: 1; card: Card; provenance: CardProvenance }
|
|
95
|
+
function payloadText(payload: VaultCardPayload): string { return JSON.stringify(payload, null, 2); }
|
|
96
|
+
function parsePayload(text: string, where: string): VaultCardPayload {
|
|
97
|
+
let raw: unknown;
|
|
98
|
+
try { raw = JSON.parse(text); } catch { throw new Error(`${where}: the ares card block is not valid JSON; fix or re-export the card in the vault note`); }
|
|
99
|
+
if (!plain(raw)) throw new Error(`${where}: card block must be an object`);
|
|
100
|
+
onlyKeys(raw, ["v", "card", "provenance"], where);
|
|
101
|
+
if (raw.v !== 1) throw new Error(`${where}: unsupported card block version; use an ares version that supports it`);
|
|
102
|
+
return { v: 1, card: validateCard(raw.card), provenance: validateProvenance(raw.provenance, `${where}.provenance`) };
|
|
103
|
+
}
|
|
104
|
+
function receipt(actor: Actor, vault: string, fingerprint: string, cards: { id: string; note: string; sha256: string }[]): PendingEvent {
|
|
105
|
+
return { actor, type: "lit.card.exported", data: { vault, fingerprint, cards } };
|
|
106
|
+
}
|
|
107
|
+
const identifierOf = (c: Candidate) => ({ ...(c.doi ? { doi: c.doi } : {}), ...(c.arxivId ? { arxivId: c.arxivId } : {}), ...(c.citekey ? { citekey: c.citekey } : {}), title: c.title });
|
|
108
|
+
|
|
109
|
+
function cardIds(values: string[]): string[] {
|
|
110
|
+
if (!values.length || values.length > MAX_CARD_IDS) throw new Error(`lit card: give 1..${MAX_CARD_IDS} candidate ids`);
|
|
111
|
+
const ids = values.map((v, i) => boundedText(v, `id[${i}]`, 300));
|
|
112
|
+
if (new Set(ids).size !== ids.length) throw new Error("lit card: duplicate candidate id; list each id once");
|
|
113
|
+
return ids;
|
|
114
|
+
}
|
|
115
|
+
function ownCard(dir: string, candidates: Candidate[], id: string): { candidate: Candidate; card: StoredCard } {
|
|
116
|
+
const candidate = candidates.find(c => c.id === id);
|
|
117
|
+
if (!candidate) throw new Error(`lit card export: unknown candidate ${id}; check ares lit list`);
|
|
118
|
+
if (!isVerified(candidate) || !(candidate.doi || candidate.arxivId)) throw new Error(`lit card export: ${id} has no identifier verified in this study; run ares lit verify first`);
|
|
119
|
+
const card = readCard(dir, id);
|
|
120
|
+
if (!card) throw new Error(`lit card export: ${id} has no card; record one with ares lit card`);
|
|
121
|
+
if (card.reused) throw new Error(`lit card export: ${id} holds a card reused from the vault; only cards extracted in this study are exported`);
|
|
122
|
+
return { candidate, card };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Read-only preview: the exact payloads, keyed by candidate, and a fingerprint binding them and the target vault. */
|
|
126
|
+
export function previewCardExport(dirArg: string, vault: string, values: string[], modelFamily?: string) {
|
|
127
|
+
const { dir, study } = openStudy(dirArg), ids = cardIds(values), candidates = loadCandidates(dir), events = readLedger(dir);
|
|
128
|
+
if (!VAULT_ID.test(vault)) throw new Error("--vault: registered vault id (lower-case letters, digits, - or _); list them with vmem vaults list");
|
|
129
|
+
const family = modelFamily?.trim().toLowerCase();
|
|
130
|
+
const cards = ids.map(id => {
|
|
131
|
+
const { candidate, card } = ownCard(dir, candidates, id);
|
|
132
|
+
// extractedAt and extractor.kind come from the lit.card event that recorded these bytes, never from the exporter.
|
|
133
|
+
const recorded = events.filter(e => e.type === "lit.card" && e.data.id === id).at(-1);
|
|
134
|
+
if (!recorded) throw new Error(`lit card export: ${id} has no lit.card event recording its card; record the card again with ares lit card`);
|
|
135
|
+
const { id: _id, reused: _r, ...fields } = card;
|
|
136
|
+
const payload: VaultCardPayload = { v: 1, card: fields, provenance: { studySha256: sha256(study.id), extractedAt: recorded.at, extractor: { kind: recorded.actor.kind, ...(family ? { modelFamily: family } : {}) } } };
|
|
137
|
+
validateProvenance(payload.provenance, "card provenance");
|
|
138
|
+
return { id, identifier: identifierOf(candidate), payload };
|
|
139
|
+
});
|
|
140
|
+
const fingerprint = sha256(JSON.stringify([vault, cards.map(c => [c.id, c.identifier, payloadText(c.payload)])]));
|
|
141
|
+
return { vault, fingerprint, cards: cards.map(c => ({ id: c.id, identifier: c.identifier, fields: CARD_FIELDS.filter(f => (c.payload.card as unknown as Record<string, unknown>)[f] !== undefined), provenance: c.payload.provenance })), payloads: cards };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Returns the scope-gate approval events to carry in the command's commit, or throws when the gate refuses. */
|
|
145
|
+
export type GateCheck = () => PendingEvent[];
|
|
146
|
+
const NOTE_PATH_MAX = 200;
|
|
147
|
+
/**
|
|
148
|
+
* Writes each card to the single matching reference note. The study lock is held only to check the gate, the fingerprint
|
|
149
|
+
* and the receipt capacity, and to commit the receipt, never across vmem calls; each vault write is guarded by the note
|
|
150
|
+
* hash it just read. The largest possible receipt is preflighted before any vault write, so a full ledger changes nothing.
|
|
151
|
+
*/
|
|
152
|
+
export async function exportCards(dirArg: string, vault: string, values: string[], fingerprint: string, actor: Actor, client: VaultClient, gate: GateCheck, modelFamily?: string) {
|
|
153
|
+
const { dir } = openStudy(dirArg);
|
|
154
|
+
const { preview, approval } = await withLock(dir, () => {
|
|
155
|
+
const preview = previewCardExport(dir, vault, values, modelFamily);
|
|
156
|
+
if (fingerprint !== preview.fingerprint) throw new Error("lit card export: stale fingerprint; run ares lit card export again without --confirm and confirm its current fingerprint");
|
|
157
|
+
const approval = gate();
|
|
158
|
+
prepareCommit(dir, [], [...approval, receipt(actor, vault, fingerprint, preview.payloads.map(p => ({ id: p.id, note: "x".repeat(NOTE_PATH_MAX), sha256: "0".repeat(64) })))]);
|
|
159
|
+
return { preview, approval };
|
|
160
|
+
});
|
|
161
|
+
const written: { id: string; note: string; sha256: string }[] = [];
|
|
162
|
+
try {
|
|
163
|
+
for (const item of preview.payloads) {
|
|
164
|
+
const notes = await client.findReference(item.identifier);
|
|
165
|
+
if (notes.length !== 1) throw new Error(`lit card export: ${item.id} matches ${notes.length} reference notes by identifier in vault ${vault}; create exactly one reference note with this doi/arxiv_id (vmem new ... --type reference) and retry`);
|
|
166
|
+
const note = notes[0]!.path, text = payloadText(item.payload), current = await client.readCard(note);
|
|
167
|
+
if (current.block === undefined) await client.appendCard(note, current.hash, "```json\n" + text + "\n```");
|
|
168
|
+
else if (current.block !== text) await client.replaceCard(note, current.hash, current.block, text);
|
|
169
|
+
written.push({ id: item.id, note, sha256: sha256(text) });
|
|
170
|
+
}
|
|
171
|
+
} finally {
|
|
172
|
+
// Receipt what reached the vault even when a later card fails, so the next run can tell.
|
|
173
|
+
if (written.length) await withLock(dir, () => commit(dir, [], [...approval, receipt(actor, vault, fingerprint, written)]));
|
|
174
|
+
}
|
|
175
|
+
return { vault, fingerprint, written };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function importPlan(dir: string, ids: string[]) {
|
|
179
|
+
const candidates = loadCandidates(dir);
|
|
180
|
+
return ids.map(id => {
|
|
181
|
+
const candidate = candidates.find(c => c.id === id);
|
|
182
|
+
if (!candidate) throw new Error(`lit card import: unknown candidate ${id}; check ares lit list`);
|
|
183
|
+
if (!isVerified(candidate) || !(candidate.doi || candidate.arxivId)) throw new Error(`lit card import: ${id} has no identifier verified in this study; run ares lit verify first`);
|
|
184
|
+
if (candidate.status !== "included") throw new Error(`lit card import: ${id} is not included; cards are recorded for included candidates only`);
|
|
185
|
+
const existing = readCard(dir, id);
|
|
186
|
+
if (existing && !existing.reused) throw new Error(`lit card import: ${id} already has a card extracted in this study; keep it, or remove it before importing`);
|
|
187
|
+
return { id, candidate, key: JSON.stringify([candidate.status, candidate.verify, identifierOf(candidate), existing ?? null]) };
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Imports only for included candidates whose identifier is verified in this study. Eligibility is checked under the
|
|
192
|
+
* lock, vault reads run unlocked, and the commit re-checks eligibility under the lock so nothing changed in between.
|
|
193
|
+
*/
|
|
194
|
+
export async function importCards(dirArg: string, vault: string, values: string[], actor: Actor, client: VaultClient, gate: GateCheck) {
|
|
195
|
+
const { dir } = openStudy(dirArg), ids = cardIds(values), at = new Date().toISOString();
|
|
196
|
+
// Import reads the vault only; the gate is checked up front, then checked again with the commit so a scope change
|
|
197
|
+
// during the vault reads refuses instead of committing under an outdated approval.
|
|
198
|
+
const plan = await withLock(dir, () => { gate(); return importPlan(dir, ids); });
|
|
199
|
+
const files: [string, string, number][] = [], rows: { id: string; note: string; sha256: string }[] = [];
|
|
200
|
+
for (const { id, candidate } of plan) {
|
|
201
|
+
const notes = await client.findReference(identifierOf(candidate));
|
|
202
|
+
if (notes.length !== 1) throw new Error(`lit card import: ${id} matches ${notes.length} reference notes by identifier in vault ${vault}; resolve the duplicates or export a card first`);
|
|
203
|
+
const note = notes[0]!.path, read = await client.readCard(note);
|
|
204
|
+
if (read.block === undefined) throw new Error(`lit card import: reference note ${note} has no ares card section; export a card to it first`);
|
|
205
|
+
const payload = parsePayload(read.block, `vault note ${note}`);
|
|
206
|
+
const stored: StoredCard = { id, ...payload.card, reused: { from: "vault", vault, note, at, provenance: payload.provenance } };
|
|
207
|
+
const text = JSON.stringify(stored, null, 2) + "\n";
|
|
208
|
+
if (Buffer.byteLength(text) > CARD_BYTES) throw new Error(`lit card import: card for ${id} exceeds 64 KiB; shorten it in the vault note`);
|
|
209
|
+
files.push([cardPath(dir, id), text, CARD_BYTES]); rows.push({ id, note, sha256: sha256(text) });
|
|
210
|
+
}
|
|
211
|
+
// One commit for every imported card; the candidate file, verification and gates are not written.
|
|
212
|
+
await withLock(dir, () => {
|
|
213
|
+
if (JSON.stringify(importPlan(dir, ids).map(p => p.key)) !== JSON.stringify(plan.map(p => p.key))) throw new Error("lit card import: a candidate or its card changed during the vault read; nothing was written, run the import again");
|
|
214
|
+
commit(dir, files, [...gate(), { actor, type: "lit.card.imported", data: { vault, cards: rows } }]);
|
|
215
|
+
});
|
|
216
|
+
return { vault, imported: rows };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Every stored card with its reuse record, for review before citing. */
|
|
220
|
+
export function listCards(dirArg: string) {
|
|
221
|
+
const { dir } = openStudy(dirArg);
|
|
222
|
+
return { cards: loadCandidates(dir).flatMap(c => {
|
|
223
|
+
const card = readCard(dir, c.id);
|
|
224
|
+
return card ? [{ id: c.id, status: c.status, fields: CARD_FIELDS.filter(f => (card as unknown as Record<string, unknown>)[f] !== undefined), reused: card.reused ?? null }] : [];
|
|
225
|
+
}) };
|
|
226
|
+
}
|
package/src/paper/build.ts
CHANGED
|
@@ -4,10 +4,10 @@ import { join } from "node:path";
|
|
|
4
4
|
import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, sha256, type Actor } from "../study.ts";
|
|
5
5
|
import { checkPaper, manuscriptPath } from "./check.ts";
|
|
6
6
|
import { MANUSCRIPT_BYTES } from "./placeholders.ts";
|
|
7
|
+
import { readPaperPlanSnapshot } from "./plan.ts";
|
|
7
8
|
|
|
8
9
|
export const PAPER_EVIDENCE_BYTES = 8 * 1024 * 1024;
|
|
9
|
-
|
|
10
|
-
v: 1;
|
|
10
|
+
interface EvidenceBody {
|
|
11
11
|
manuscriptSha256: string;
|
|
12
12
|
placeholders: {
|
|
13
13
|
kind: "number" | "literal"; raw: string; start: number; end: number; line: number; column: number;
|
|
@@ -15,6 +15,13 @@ export interface PaperEvidence {
|
|
|
15
15
|
source: { file: string; sha256: string };
|
|
16
16
|
}[];
|
|
17
17
|
}
|
|
18
|
+
export type PaperEvidence = EvidenceBody & ({ v: 1 } | { v: 2; planSha256: string });
|
|
19
|
+
/** Legacy evidence stays readable; plan-bound evidence requires a reader that understands its binding. */
|
|
20
|
+
export function paperEvidenceVersion(raw: unknown): 1 | 2 {
|
|
21
|
+
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2)) throw new Error("paper evidence: unsupported version; use an ares version that supports it, keeping paper/build/evidence.json unchanged");
|
|
22
|
+
if (raw.v === 2 && (Object.keys(raw).some(key => !["v", "manuscriptSha256", "placeholders", "planSha256"].includes(key)) || typeof raw.planSha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.planSha256))) throw new Error("paper evidence: invalid v2 plan binding or unknown field; restore the last valid paper/build/evidence.json, then run ares paper check and paper build");
|
|
23
|
+
return raw.v;
|
|
24
|
+
}
|
|
18
25
|
export function paperBuildPaths(dir: string) { return { manuscript: join(dir, "paper", "build", "manuscript.md"), evidence: join(dir, "paper", "build", "evidence.json") }; }
|
|
19
26
|
function previous(file: string, bound: number): string | undefined {
|
|
20
27
|
if (!existsSync(file)) return undefined;
|
|
@@ -26,17 +33,18 @@ function evidenceBytes(dir: string): string | undefined {
|
|
|
26
33
|
if (oldEvidence !== undefined) {
|
|
27
34
|
let raw: unknown;
|
|
28
35
|
try { raw = JSON.parse(oldEvidence); } catch { throw new Error("paper evidence: invalid JSON; restore the last valid paper/build/evidence.json before rebuilding"); }
|
|
29
|
-
|
|
36
|
+
paperEvidenceVersion(raw);
|
|
30
37
|
}
|
|
31
38
|
return oldEvidence;
|
|
32
39
|
}
|
|
33
40
|
function calculatePaper(dir: string) {
|
|
34
41
|
const report = checkPaper(dir);
|
|
35
42
|
if (!report.ok) {
|
|
36
|
-
const
|
|
37
|
-
|
|
43
|
+
const blocking = report.findings.filter(f => f.severity === "blocking");
|
|
44
|
+
const reasons = blocking.slice(0, 10).map(f => `${f.code} at ${f.line}:${f.column}`).join(", ");
|
|
45
|
+
throw new Error(`paper build: paper check found ${blocking.length} blocking finding(s): ${reasons}; run ares paper check <dir> --json and fix every finding before rebuilding`);
|
|
38
46
|
}
|
|
39
|
-
const evidence: PaperEvidence = { v: 1, manuscriptSha256: report.manuscriptSha256, placeholders: report.placeholders.map(entry => {
|
|
47
|
+
const evidence: PaperEvidence = { ...(report.planSha256 === undefined ? { v: 1 as const } : { v: 2 as const, planSha256: report.planSha256 }), manuscriptSha256: report.manuscriptSha256, placeholders: report.placeholders.map(entry => {
|
|
40
48
|
const token = entry.placeholder;
|
|
41
49
|
return { kind: token.kind, raw: token.raw, start: token.start, end: token.end, line: token.line, column: token.column,
|
|
42
50
|
...(token.kind === "number" ? { ref: token.ref, ...(token.format === undefined ? {} : { format: token.format }) } : {}),
|
|
@@ -58,7 +66,8 @@ export function buildPaper(dirArg: string, actor: Actor) {
|
|
|
58
66
|
const receipt = readLedger(dir).findLast(event => event.type === "paper.built");
|
|
59
67
|
const changed = oldManuscript !== report.rendered || oldEvidence !== text || receipt?.data.manuscriptSha256 !== manuscriptSha256 || receipt.data.evidenceSha256 !== evidenceSha256;
|
|
60
68
|
if (sha256(readTextBounded(manuscriptPath(dir), MANUSCRIPT_BYTES)) !== report.manuscriptSha256) throw new Error("paper build: source manuscript changed during checking; rerun ares paper check and paper build on the current manuscript");
|
|
61
|
-
if (
|
|
69
|
+
if (readPaperPlanSnapshot(dir)?.sha256 !== report.planSha256) throw new Error("paper build: source plan was added, removed or changed during checking; rerun ares paper check and paper build on the current paper/plan.json");
|
|
70
|
+
if (changed) commit(dir, [[paths.manuscript, report.rendered, MANUSCRIPT_BYTES], [paths.evidence, text, PAPER_EVIDENCE_BYTES]], [{ actor, type: "paper.built", data: { manuscriptSha256, evidenceSha256, sourceManuscriptSha256: report.manuscriptSha256, ...(report.planSha256 === undefined ? {} : {planSha256: report.planSha256}) } }]);
|
|
62
71
|
return { manuscriptSha256, evidenceSha256, changed };
|
|
63
72
|
}
|
|
64
73
|
|
package/src/paper/check.ts
CHANGED
|
@@ -4,19 +4,24 @@ import { join } from "node:path";
|
|
|
4
4
|
import { openStudy, readTextBounded, sha256 } from "../study.ts";
|
|
5
5
|
import { loadCandidates } from "../lit/candidates.ts";
|
|
6
6
|
import { checkCitations, citationOccurrences } from "../lit/cite.ts";
|
|
7
|
+
import { readCard } from "../lit/cards.ts";
|
|
7
8
|
import { readProtocol } from "../exp/protocol.ts";
|
|
8
9
|
import { readSelection } from "../exp/selection.ts";
|
|
9
10
|
import { investigateResultPath, readClosedInvestigation } from "../exp/investigate.ts";
|
|
10
11
|
import { finalResultPath } from "../exp/final.ts";
|
|
11
12
|
import { MANUSCRIPT_BYTES, parsePlaceholders, resolvePlaceholders } from "./placeholders.ts";
|
|
13
|
+
import { hygieneFindings, readPaperSettings, type HygieneCode } from "./hygiene.ts";
|
|
14
|
+
import { readPaperPlanCheckSnapshot } from "./plan.ts";
|
|
15
|
+
import { paperPointFindings, type PointFindingCode } from "./points.ts";
|
|
16
|
+
import { paperPlanFindings, type ScopeFindingCode } from "./scopes.ts";
|
|
12
17
|
|
|
13
18
|
export const MAX_CODE_NUMBERS = 500;
|
|
14
|
-
export interface PaperFinding { code: "bare-number" | "unresolved-ref" | "unaccepted-draft" | "bad-format" | "unknown-citation" | "unverified-citation" | "missing-negative-result"; start: number; end: number; line: number; column: number; message: string }
|
|
19
|
+
export interface PaperFinding { code: "bare-number" | "unresolved-ref" | "unaccepted-draft" | "bad-format" | "unknown-citation" | "unverified-citation" | "missing-negative-result" | HygieneCode | ScopeFindingCode | PointFindingCode; severity: "blocking" | "warning"; section?: string[]; sectionId?: string; pointId?: string; start: number; end: number; line: number; column: number; message: string }
|
|
15
20
|
function blank(text: string, mask: Uint8Array): string { return text.split("").map((char, index) => mask[index] && char !== "\n" && char !== "\r" ? " " : char).join(""); }
|
|
16
21
|
function mark(mask: Uint8Array, start: number, end: number) { mask.fill(1, start, end); }
|
|
17
22
|
function escaped(text: string, index: number): boolean { let slashes = 0; while (index > 0 && text[--index] === "\\") slashes++; return slashes % 2 === 1; }
|
|
18
23
|
/** Masks syntax-only destinations and code while retaining original offsets. Visible link labels remain prose. */
|
|
19
|
-
function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Array; code: Uint8Array; hidden: Uint8Array } {
|
|
24
|
+
function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Array; code: Uint8Array; hidden: Uint8Array; headingHidden: Uint8Array; anchorHidden: Uint8Array } {
|
|
20
25
|
const mask = new Uint8Array(text.length), protectedText = new Uint8Array(text.length), tokens = parsePlaceholders(text);
|
|
21
26
|
for (const token of [...tokens.placeholders, ...tokens.findings]) mark(protectedText, token.start, token.end);
|
|
22
27
|
let fence: { char: string; length: number } | undefined, paragraph = false, indented = false;
|
|
@@ -50,6 +55,7 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
50
55
|
}
|
|
51
56
|
}
|
|
52
57
|
}
|
|
58
|
+
const blockCode = mask.slice();
|
|
53
59
|
// Backtick runs must have an exactly matching closer; unmatched delimiters remain prose.
|
|
54
60
|
const runs = [...text.matchAll(/`+/g)].filter(hit => !mask[hit.index] && !protectedText[hit.index] && !knownHidden?.[hit.index]);
|
|
55
61
|
const regions: number[] = []; let region = 0, previous = 0;
|
|
@@ -67,7 +73,7 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
67
73
|
const close = next.get(i);
|
|
68
74
|
if (close !== undefined) { mark(mask, runs[i]!.index, runs[close]!.index + runs[close]![0].length); i = close; }
|
|
69
75
|
}
|
|
70
|
-
const code = mask.slice();
|
|
76
|
+
const code = mask.slice(), anchorHidden = code.slice();
|
|
71
77
|
const labels: number[] = [];
|
|
72
78
|
for (let i = 0; i < text.length; i++) {
|
|
73
79
|
if (mask[i] || protectedText[i] || knownHidden?.[i] || (text[i] !== "<" && text[i] !== "]" && text[i] !== "[") || escaped(text, i)) continue;
|
|
@@ -98,8 +104,10 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
98
104
|
const quote = text[tail++]!; while (tail < text.length && (text[tail] !== quote || escaped(text, tail))) tail++;
|
|
99
105
|
if (tail >= text.length) continue; tail++; while (/\s/.test(text[tail] ?? "") && tail < text.length) tail++;
|
|
100
106
|
}
|
|
101
|
-
if (text[tail] === ")") mark(mask, start, end);
|
|
107
|
+
if (text[tail] === ")") { mark(mask, start, end); mark(anchorHidden, i + 1, tail + 1); }
|
|
102
108
|
}
|
|
109
|
+
// Point anchors are comments in prose, never examples in syntax-only destinations/titles or placeholders.
|
|
110
|
+
for (let i = 0; i < mask.length; i++) if (mask[i] || protectedText[i]) anchorHidden[i] = 1;
|
|
103
111
|
const hidden = new Uint8Array(text.length); let hasComment = false;
|
|
104
112
|
for (const comment of text.matchAll(/<!--[\s\S]*?(?:-->|$)/g)) {
|
|
105
113
|
if (!code[comment.index] && !protectedText[comment.index]) { mark(mask, comment.index, comment.index + comment[0].length); mark(hidden, comment.index, comment.index + comment[0].length); hasComment = true; }
|
|
@@ -109,16 +117,17 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
109
117
|
const target = match[1]!, start = match.index + match[0].lastIndexOf(target);
|
|
110
118
|
if (!mask[start] && !protectedText[start]) {
|
|
111
119
|
mark(mask, start, start + target.length);
|
|
112
|
-
const lineEnd = text.indexOf("\n", match.index); mark(hidden, match.index, lineEnd < 0 ? text.length : lineEnd);
|
|
120
|
+
const lineEnd = text.indexOf("\n", match.index); mark(hidden, match.index, lineEnd < 0 ? text.length : lineEnd); mark(anchorHidden, match.index, lineEnd < 0 ? text.length : lineEnd);
|
|
113
121
|
}
|
|
114
122
|
}
|
|
115
123
|
// Reclassify once with non-code comments excluded, so a fence inside a comment cannot hide later prose.
|
|
116
124
|
if (!knownHidden && hasComment) return markdownMask(text, hidden);
|
|
117
|
-
|
|
125
|
+
const headingHidden = blockCode.slice(); for (let i = 0; i < hidden.length; i++) if (hidden[i]) headingHidden[i] = 1;
|
|
126
|
+
return { mask, code, hidden, headingHidden, anchorHidden };
|
|
118
127
|
}
|
|
119
128
|
export function manuscriptPath(dir: string): string { return join(dir, "paper", "manuscript.md"); }
|
|
120
129
|
export function checkPaper(dirArg: string) {
|
|
121
|
-
const { dir, study } = openStudy(dirArg), file = manuscriptPath(dir);
|
|
130
|
+
const { dir, study } = openStudy(dirArg), file = manuscriptPath(dir), settings = readPaperSettings(dir);
|
|
122
131
|
let manuscript: string;
|
|
123
132
|
try { manuscript = readTextBounded(file, MANUSCRIPT_BYTES); }
|
|
124
133
|
catch { throw new Error("paper manuscript: missing, unreadable, invalid UTF-8, non-regular or larger than 2 MiB; restore paper/manuscript.md as a bounded UTF-8 regular file before paper check"); }
|
|
@@ -128,7 +137,7 @@ export function checkPaper(dirArg: string) {
|
|
|
128
137
|
let lo = 0, hi = lines.length; while (lo + 1 < hi) { const mid = (lo + hi) >>> 1; if (lines[mid]! <= start) lo = mid; else hi = mid; }
|
|
129
138
|
return { line: lo + 1, column: start - lines[lo]! + 1 };
|
|
130
139
|
};
|
|
131
|
-
const finding = (code: PaperFinding["code"], start: number, end: number, message: string): PaperFinding => ({ code, start, end, ...location(start), message });
|
|
140
|
+
const finding = (code: PaperFinding["code"], start: number, end: number, message: string): PaperFinding => ({ code, severity: "blocking", start, end, ...location(start), message });
|
|
132
141
|
const findings: PaperFinding[] = resolution.findings.map(f => finding(f.code, f.start, f.end, f.message));
|
|
133
142
|
const codeNumbers: { value: string; line: number; column: number }[] = [];
|
|
134
143
|
let codeNumberCount = 0;
|
|
@@ -143,7 +152,8 @@ export function checkPaper(dirArg: string) {
|
|
|
143
152
|
if (placeholder.kind === "number") mark(citationMask, placeholder.start, placeholder.end);
|
|
144
153
|
}
|
|
145
154
|
for (const problem of parsed.findings) { mark(numberMask, problem.start, problem.end); mark(citationMask, problem.start, problem.end); }
|
|
146
|
-
const citationText = blank(manuscript, citationMask), citations = checkCitations(citationText,
|
|
155
|
+
const citationText = blank(manuscript, citationMask), candidates = loadCandidates(dir), citations = checkCitations(citationText, candidates);
|
|
156
|
+
const plan = readPaperPlanCheckSnapshot(dir, candidates);
|
|
147
157
|
const groups = new Map<number, number>();
|
|
148
158
|
for (const hit of citationOccurrences(citationText)) {
|
|
149
159
|
mark(numberMask, hit.start, hit.end); groups.set(hit.groupStart, hit.groupEnd);
|
|
@@ -174,8 +184,25 @@ export function checkPaper(dirArg: string) {
|
|
|
174
184
|
}
|
|
175
185
|
} catch (error) { findings.push(error instanceof CopilotAcceptError ? finding("unaccepted-draft", 0, 0, error.message) : finding("unresolved-ref", 0, 0, "experiment design or selection is invalid; restore the current validated inputs before paper check")); }
|
|
176
186
|
}
|
|
187
|
+
// Code and comments only: link targets stay visible so headings and bare-identifier masking use the full prose mask.
|
|
188
|
+
const hiddenCode = masks.code.slice(); for (let i = 0; i < hiddenCode.length; i++) if (masks.hidden[i]) hiddenCode[i] = 1;
|
|
189
|
+
for (const hit of hygieneFindings(manuscript, hiddenCode, masks.mask, citationText, settings)) {
|
|
190
|
+
findings.push({ code: hit.code, severity: settings.blocking.includes(hit.code) ? "blocking" : "warning", section: hit.section, start: hit.start, end: hit.end, ...location(hit.start), message: hit.message });
|
|
191
|
+
}
|
|
192
|
+
if (plan) for (const hit of paperPlanFindings(manuscript, masks.headingHidden, citationText, plan.plan, candidates)) findings.push({...hit, ...location(hit.start)});
|
|
193
|
+
if (plan) for (const hit of paperPointFindings(dir, manuscript, masks.anchorHidden, masks.headingHidden, citationText, plan.plan)) findings.push({...hit, ...location(hit.start)});
|
|
177
194
|
let rendered = "", cursor = 0;
|
|
178
195
|
for (const entry of resolution.placeholders) { rendered += manuscript.slice(cursor, entry.placeholder.start) + entry.rendered; cursor = entry.placeholder.end; }
|
|
179
196
|
rendered += manuscript.slice(cursor);
|
|
180
|
-
|
|
197
|
+
// Reused cards are planning aids: list every cited candidate whose card came from the vault, with its provenance.
|
|
198
|
+
const cited = loadCandidates(dir), unreadableCards: { citekey: string; id: string; message: string }[] = [];
|
|
199
|
+
const reusedCards = citations.keys.flatMap(key => {
|
|
200
|
+
const candidate = cited.find(c => c.citekey === key);
|
|
201
|
+
let card: ReturnType<typeof readCard>;
|
|
202
|
+
// An unreadable card is reported (not hidden), but does not block the check: cards are planning aids, never evidence.
|
|
203
|
+
try { card = candidate ? readCard(dir, candidate.id) : undefined; }
|
|
204
|
+
catch (error) { unreadableCards.push({ citekey: key, id: candidate!.id, message: error instanceof Error ? error.message : "card unreadable; record it again with ares lit card" }); return []; }
|
|
205
|
+
return card?.reused ? [{ citekey: key, id: candidate!.id, vault: card.reused.vault, note: card.reused.note, at: card.reused.at, provenance: card.reused.provenance }] : [];
|
|
206
|
+
});
|
|
207
|
+
return { ok: !findings.some(f => f.severity === "blocking"), settings, manuscriptSha256: sha256(manuscript), ...(plan ? {planSha256: plan.sha256} : {}), rendered, placeholders: resolution.placeholders, findings: findings.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code)), literals: resolution.literals, codeNumbers, codeNumberCount, citations, ...(reusedCards.length ? { reusedCards } : {}), ...(unreadableCards.length ? { unreadableCards } : {}) };
|
|
181
208
|
}
|