@staix/agent-research 0.1.0 → 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 +137 -0
- package/README.md +356 -31
- package/package.json +4 -2
- package/src/autonomy.ts +50 -0
- package/src/cli.ts +134 -14
- package/src/commands-table.ts +43 -9
- package/src/commands.ts +244 -43
- package/src/copilot.ts +91 -0
- package/src/exp/attempts.ts +512 -69
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/investigate.ts +7 -2
- 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 +88 -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/http.ts +46 -2
- 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/lit/watch.ts +14 -1
- package/src/manifest.ts +15 -7
- package/src/mcp-tools.ts +140 -32
- package/src/mcp.ts +6 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +20 -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 +20 -8
- package/src/paper/check.ts +40 -12
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +21 -4
- 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 +116 -11
- package/src/paper/scopes.ts +51 -0
- package/src/plan/controller.ts +42 -12
- package/src/plan/definition.ts +22 -6
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +58 -17
- package/src/playbook.ts +47 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +282 -0
- package/src/study.ts +94 -26
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +271 -9
- package/src/ui/plugin.ts +89 -17
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readTextBounded } from "../study.ts";
|
|
4
|
+
import { citationOccurrences } from "../lit/cite.ts";
|
|
5
|
+
|
|
6
|
+
/** Deterministic citation hygiene codes (#99). Warnings unless listed in study.toml [paper] blocking. */
|
|
7
|
+
export const HYGIENE_CODES = ["adjacent-duplicate-citation", "citation-stack", "repeated-bundle", "bare-identifier", "duplicate-heading"] as const;
|
|
8
|
+
export type HygieneCode = typeof HYGIENE_CODES[number];
|
|
9
|
+
export interface PaperSettings { maxGroup: number; maxBundleRepeats: number; reviewRounds: number; blocking: HygieneCode[] }
|
|
10
|
+
export const DEFAULT_PAPER_SETTINGS: PaperSettings = { maxGroup: 6, maxBundleRepeats: 2, reviewRounds: 3, blocking: [] };
|
|
11
|
+
export const SETTINGS_BYTES = 64 * 1024;
|
|
12
|
+
export interface HygieneHit { code: HygieneCode; start: number; end: number; section: string[]; message: string }
|
|
13
|
+
|
|
14
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
15
|
+
function refuse(detail: string): never { throw new Error(`study.toml: ${detail}; fix the [paper] or [review] settings (paper keys maxGroup, maxBundleRepeats, reviewRounds, blocking; review key surveyChecklist) or remove study.toml to use the defaults`); }
|
|
16
|
+
function count(value: unknown, name: string, min: number): number {
|
|
17
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > 1000) refuse(`paper.${name} must be an integer from ${min} to 1000`);
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Optional study.toml; absence keeps the defaults so existing studies keep their blocking set. */
|
|
22
|
+
export function readPaperSettings(dir: string): PaperSettings { return readStudySettings(dir).paper; }
|
|
23
|
+
export const SURVEY_CHECKLIST_MODES = ["off", "show", "require"] as const;
|
|
24
|
+
export type SurveyChecklistMode = typeof SURVEY_CHECKLIST_MODES[number];
|
|
25
|
+
/** [review] settings; `surveyChecklist` is undefined when unset so the caller applies the study-mode default. */
|
|
26
|
+
export interface ReviewSettings { surveyChecklist?: SurveyChecklistMode }
|
|
27
|
+
export function readReviewSettings(dir: string): ReviewSettings { return readStudySettings(dir).review; }
|
|
28
|
+
/** One closed reader for both tables, so an unknown key in either refuses for every caller. */
|
|
29
|
+
function readStudySettings(dir: string): { paper: PaperSettings; review: ReviewSettings } {
|
|
30
|
+
const file = join(dir, "study.toml");
|
|
31
|
+
if (!existsSync(file)) return { paper: { ...DEFAULT_PAPER_SETTINGS, blocking: [] }, review: {} };
|
|
32
|
+
let raw: unknown;
|
|
33
|
+
try { raw = Bun.TOML.parse(readTextBounded(file, SETTINGS_BYTES)); }
|
|
34
|
+
catch { refuse("unreadable, non-regular, larger than 64 KiB or invalid TOML"); }
|
|
35
|
+
if (!isRecord(raw)) refuse("must be a TOML table");
|
|
36
|
+
for (const key of Object.keys(raw)) if (key !== "paper" && key !== "review") refuse(`unknown setting ${JSON.stringify(key).slice(0, 80)}`);
|
|
37
|
+
const review = raw.review ?? {};
|
|
38
|
+
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)}`);
|
|
40
|
+
const reviewSettings: ReviewSettings = {};
|
|
41
|
+
if (review.surveyChecklist !== undefined) {
|
|
42
|
+
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
|
+
reviewSettings.surveyChecklist = review.surveyChecklist as SurveyChecklistMode;
|
|
44
|
+
}
|
|
45
|
+
const paper = raw.paper ?? {};
|
|
46
|
+
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)}`);
|
|
48
|
+
const settings: PaperSettings = { ...DEFAULT_PAPER_SETTINGS, blocking: [] };
|
|
49
|
+
if (paper.maxGroup !== undefined) settings.maxGroup = count(paper.maxGroup, "maxGroup", 1);
|
|
50
|
+
if (paper.maxBundleRepeats !== undefined) settings.maxBundleRepeats = count(paper.maxBundleRepeats, "maxBundleRepeats", 1);
|
|
51
|
+
if (paper.reviewRounds !== undefined) settings.reviewRounds = count(paper.reviewRounds, "reviewRounds", 1);
|
|
52
|
+
if (paper.blocking !== undefined) {
|
|
53
|
+
if (!Array.isArray(paper.blocking)) refuse("paper.blocking must be an array of finding codes");
|
|
54
|
+
for (const code of paper.blocking) {
|
|
55
|
+
if (typeof code !== "string" || !(HYGIENE_CODES as readonly string[]).includes(code)) refuse(`paper.blocking has unknown code ${JSON.stringify(code).slice(0, 80)}; allowed: ${HYGIENE_CODES.join(", ")}`);
|
|
56
|
+
if (settings.blocking.includes(code as HygieneCode)) refuse(`paper.blocking lists ${code} twice`);
|
|
57
|
+
settings.blocking.push(code as HygieneCode);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { paper: settings, review: reviewSettings };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* `manuscript` is the original text; `hiddenCode` marks fenced/indented code and comments, `proseMask` additionally marks
|
|
65
|
+
* code spans, link/autolink targets and reference definition targets; `citationText` is the citation-eligible text.
|
|
66
|
+
*/
|
|
67
|
+
export function hygieneFindings(manuscript: string, hiddenCode: Uint8Array, proseMask: Uint8Array, citationText: string, settings: PaperSettings): HygieneHit[] {
|
|
68
|
+
const hits: HygieneHit[] = [];
|
|
69
|
+
// Headings (ATX and Setext) and their section paths, in source order.
|
|
70
|
+
const headings: { start: number; end: number; level: number; text: string; parent: number; path: string[] }[] = [];
|
|
71
|
+
const stack: number[] = [];
|
|
72
|
+
const addHeading = (start: number, end: number, level: number, raw: string) => {
|
|
73
|
+
const text = raw.trim().replace(/\s+/g, " ");
|
|
74
|
+
while (stack.length && headings[stack.at(-1)!]!.level >= level) stack.pop();
|
|
75
|
+
const parent = stack.at(-1) ?? -1;
|
|
76
|
+
headings.push({ start, end, level, text, parent, path: [...(parent >= 0 ? headings[parent]!.path : []), text] }); stack.push(headings.length - 1);
|
|
77
|
+
};
|
|
78
|
+
let paragraph: { start: number; end: number; lines: string[] } | undefined;
|
|
79
|
+
for (const match of manuscript.matchAll(/[^\n]*(?:\n|$)/g)) {
|
|
80
|
+
if (!match[0]) break;
|
|
81
|
+
const start = match.index, line = match[0].replace(/\r?\n$/, "");
|
|
82
|
+
if (hiddenCode[start + /^[ \t]*/.exec(line)![0].length] || !line.trim()) { paragraph = undefined; continue; }
|
|
83
|
+
const atx = /^ {0,3}(#{1,6})(?:[ \t]+([^\r\n]*?))?(?:[ \t]+#+)?[ \t]*$/.exec(line);
|
|
84
|
+
if (atx) { addHeading(start, start + line.length, atx[1]!.length, atx[2] ?? ""); paragraph = undefined; continue; }
|
|
85
|
+
const underline = /^ {0,3}(=+|-+)[ \t]*$/.exec(line);
|
|
86
|
+
if (underline && paragraph) { addHeading(paragraph.start, start + line.length, underline[1]![0] === "=" ? 1 : 2, paragraph.lines.join(" ")); paragraph = undefined; continue; }
|
|
87
|
+
// Block starts that cannot become Setext heading content.
|
|
88
|
+
if (/^ {0,3}(?:[-+*]|[0-9]+[.)])(?:[ \t]|$)|^ {0,3}>|^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/.test(line) && !paragraph) { paragraph = undefined; continue; }
|
|
89
|
+
if (paragraph) paragraph.lines.push(line); else paragraph = { start, end: start + line.length, lines: [line] };
|
|
90
|
+
}
|
|
91
|
+
/** Binary search over heading offsets; paths are precomputed per heading. */
|
|
92
|
+
const section = (offset: number): string[] => {
|
|
93
|
+
let lo = 0, hi = headings.length;
|
|
94
|
+
while (lo < hi) { const mid = (lo + hi) >>> 1; if (headings[mid]!.start <= offset) lo = mid + 1; else hi = mid; }
|
|
95
|
+
return lo ? headings[lo - 1]!.path : [];
|
|
96
|
+
};
|
|
97
|
+
const push = (code: HygieneCode, start: number, end: number, message: string) => hits.push({ code, start, end, section: section(start), message });
|
|
98
|
+
const seen = new Map<string, number>();
|
|
99
|
+
for (const [index, heading] of headings.entries()) {
|
|
100
|
+
const key = `${heading.parent}\u0000${heading.level}\u0000${heading.text}`;
|
|
101
|
+
if (seen.has(key)) push("duplicate-heading", heading.start, heading.end, `heading "${heading.text.slice(0, 80)}" repeats a sibling at level ${heading.level}; merge the two sections or rename one`);
|
|
102
|
+
else seen.set(key, index);
|
|
103
|
+
}
|
|
104
|
+
// Citation groups in source order.
|
|
105
|
+
const groups: { start: number; end: number; keys: { key: string; start: number; end: number }[] }[] = [];
|
|
106
|
+
for (const hit of citationOccurrences(citationText)) {
|
|
107
|
+
const last = groups.at(-1);
|
|
108
|
+
if (last && last.start === hit.groupStart) last.keys.push(hit);
|
|
109
|
+
else groups.push({ start: hit.groupStart, end: hit.groupEnd, keys: [hit] });
|
|
110
|
+
}
|
|
111
|
+
const bundles = new Map<string, { start: number; end: number }[]>();
|
|
112
|
+
for (const [index, group] of groups.entries()) {
|
|
113
|
+
const keys = new Set<string>();
|
|
114
|
+
for (const entry of group.keys) {
|
|
115
|
+
if (keys.has(entry.key)) push("adjacent-duplicate-citation", entry.start, entry.end, `citation @${entry.key} repeats within one bracket group; cite it once`);
|
|
116
|
+
keys.add(entry.key);
|
|
117
|
+
}
|
|
118
|
+
const previous = groups[index - 1];
|
|
119
|
+
if (previous && !citationText.slice(previous.end, group.start).trim()) {
|
|
120
|
+
const before = new Set(previous.keys.map(entry => entry.key));
|
|
121
|
+
for (const entry of group.keys) if (before.has(entry.key)) push("adjacent-duplicate-citation", entry.start, entry.end, `citation @${entry.key} repeats in the adjacent bracket group with no prose between; merge the groups and cite it once`);
|
|
122
|
+
}
|
|
123
|
+
if (keys.size > settings.maxGroup) push("citation-stack", group.start, group.end, `bracket group cites ${keys.size} keys, more than paper.maxGroup ${settings.maxGroup}; split the claim or cite the most relevant works`);
|
|
124
|
+
if (keys.size >= 3) {
|
|
125
|
+
const bundle = [...keys].sort().join("\u0000"), list = bundles.get(bundle) ?? [];
|
|
126
|
+
list.push({ start: group.start, end: group.end }); bundles.set(bundle, list);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const [bundle, places] of bundles) {
|
|
130
|
+
if (places.length <= settings.maxBundleRepeats) continue;
|
|
131
|
+
for (const place of places) push("repeated-bundle", place.start, place.end, `the same ${bundle.split("\u0000").length}-key citation group appears ${places.length} times, more than paper.maxBundleRepeats ${settings.maxBundleRepeats}; cite only the works each claim needs`);
|
|
132
|
+
}
|
|
133
|
+
// Bare identifiers: prose outside code, link targets, reference definitions and citation groups.
|
|
134
|
+
const prose = proseMask.slice();
|
|
135
|
+
for (const group of groups) prose.fill(1, group.start, group.end);
|
|
136
|
+
for (const match of manuscript.matchAll(/^ {0,3}\[[^\]\n]+\]:[^\n]*/gm)) prose.fill(1, match.index, match.index + match[0].length);
|
|
137
|
+
// A URL shown as its own link text ([https://x](https://x)) is a link, not a bare identifier.
|
|
138
|
+
for (const match of manuscript.matchAll(/\[([^\[\]\n]+)\]\(\s*<?([^\s<>()]+)>?\s*\)/g)) if (match[1]!.trim() === match[2]) prose.fill(1, match.index, match.index + match[0].length);
|
|
139
|
+
const text = manuscript.split("").map((char, index) => prose[index] && char !== "\n" ? " " : char).join("");
|
|
140
|
+
const patterns: [RegExp, string][] = [
|
|
141
|
+
[/\bhttps?:\/\/[^\s<>()\]]+/gi, "URL"],
|
|
142
|
+
[/\barXiv:[ \t]*(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?\/\d{7})(?:v\d+)?\b/gi, "arXiv id"],
|
|
143
|
+
[/\b(?:doi:[ \t]*)?10\.\d{4,9}\/[^\s<>\]]+/gi, "DOI"],
|
|
144
|
+
];
|
|
145
|
+
const taken = new Uint8Array(text.length);
|
|
146
|
+
for (const [pattern, kind] of patterns) for (const match of text.matchAll(pattern)) {
|
|
147
|
+
if (taken[match.index]) continue;
|
|
148
|
+
const value = match[0].replace(/[.,;:]+$/, "");
|
|
149
|
+
taken.fill(1, match.index, match.index + value.length);
|
|
150
|
+
push("bare-identifier", match.index, match.index + value.length, `bare ${kind} in prose; cite the work with a verified [@key] or make it a link`);
|
|
151
|
+
}
|
|
152
|
+
return hits.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code));
|
|
153
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CopilotAcceptError } from "../copilot.ts";
|
|
1
2
|
import { join, relative } from "node:path";
|
|
2
3
|
import { openStudy, plain, readLedger, readTextBounded, sha256 } from "../study.ts";
|
|
3
4
|
import { ATTEMPT_BYTES, listAttempts, type Attempt, type AttemptStatus } from "../exp/attempts.ts";
|
|
@@ -5,11 +6,13 @@ import { protocolHash, readProtocol } from "../exp/protocol.ts";
|
|
|
5
6
|
import { INVESTIGATE_BYTES, investigateResultPath, metricValue, readClosedInvestigation } from "../exp/investigate.ts";
|
|
6
7
|
import { ABLATE_BYTES, ablateResultPath, readClosedAblate } from "../exp/ablate.ts";
|
|
7
8
|
import { FINAL_RESULT_BYTES, finalResultPath, readClosedFinal, requirePosthocClosed } from "../exp/final.ts";
|
|
9
|
+
import { CANDIDATES_BYTES, candidatesPath, loadCandidates } from "../lit/candidates.ts";
|
|
10
|
+
import { flowFrom, flowValue, screenApproved } from "../lit/flow.ts";
|
|
8
11
|
|
|
9
12
|
export const MANUSCRIPT_BYTES = 2 * 1024 * 1024, MAX_PLACEHOLDERS = 5000;
|
|
10
13
|
interface Position { start: number; end: number; line: number; column: number; raw: string }
|
|
11
14
|
export type Placeholder = Position & ({ kind: "number"; ref: string; format?: number } | { kind: "literal"; text: string });
|
|
12
|
-
export interface PlaceholderFinding extends Position { code: "bad-format" | "unresolved-ref"; message: string }
|
|
15
|
+
export interface PlaceholderFinding extends Position { code: "bad-format" | "unresolved-ref" | "unaccepted-draft"; message: string }
|
|
13
16
|
export interface ResolvedPlaceholder { placeholder: Placeholder; value: number | string; rendered: string; source?: { file: string; sha256: string } }
|
|
14
17
|
/** Offsets are UTF-16 string indices; line and column are 1-based, as used by the Markdown checker. */
|
|
15
18
|
export function parsePlaceholders(text: string): { placeholders: Placeholder[]; findings: PlaceholderFinding[] } {
|
|
@@ -59,12 +62,16 @@ export function resolvePlaceholders(dirArg: string, text: string) {
|
|
|
59
62
|
const { dir, study } = openStudy(dirArg), parsed = parsePlaceholders(text), findings = [...parsed.findings], resolved: ResolvedPlaceholder[] = [], literals: Placeholder[] = [];
|
|
60
63
|
const cache = new Map<string, Source<unknown> | Error>();
|
|
61
64
|
const cached = <T>(key: string, read: () => Source<T>): Source<T> => {
|
|
62
|
-
if (!cache.has(key)) { try { cache.set(key, read()); } catch { cache.set(key, new Error("absent, unclosed, stale or invalid source")); } }
|
|
65
|
+
if (!cache.has(key)) { try { cache.set(key, read()); } catch (error) { cache.set(key, error instanceof CopilotAcceptError ? error : new Error("absent, unclosed, stale or invalid source")); } }
|
|
63
66
|
const value = cache.get(key)!; if (value instanceof Error) throw value; return value as Source<T>;
|
|
64
67
|
};
|
|
65
68
|
const investigate = () => cached("investigate", () => { const closed = readClosedInvestigation(dir); return source(dir, investigateResultPath(dir, closed.result.run), INVESTIGATE_BYTES, closed.result, closed.sha256); });
|
|
66
69
|
const ablate = () => cached("ablate", () => { const closed = readClosedAblate(dir); return source(dir, ablateResultPath(dir), ABLATE_BYTES, closed.result, closed.sha256); });
|
|
67
70
|
const final = () => cached("final", () => { const closed = readClosedFinal(dir); return source(dir, finalResultPath(dir), FINAL_RESULT_BYTES, closed.result, closed.sha256); });
|
|
71
|
+
const litFlowSource = () => cached("lit.flow", () => {
|
|
72
|
+
const events = readLedger(dir), candidates = loadCandidates(dir), read = source(dir, candidatesPath(dir), CANDIDATES_BYTES, candidates);
|
|
73
|
+
return { value: { flow: flowFrom(dir, events, candidates), approved: screenApproved(events, candidates) }, source: read.source };
|
|
74
|
+
});
|
|
68
75
|
let attemptIndex: Map<string, Attempt[]> | undefined;
|
|
69
76
|
const attempt = (id: string, posthoc: boolean): Source<Attempt> => cached(`attempt:${id}:${posthoc}`, () => {
|
|
70
77
|
if (!attemptIndex) {
|
|
@@ -83,9 +90,17 @@ export function resolvePlaceholders(dirArg: string, text: string) {
|
|
|
83
90
|
if (placeholder.kind === "literal") { literals.push(placeholder); resolved.push({ placeholder, value: placeholder.text, rendered: placeholder.text }); continue; }
|
|
84
91
|
const ref = placeholder.ref;
|
|
85
92
|
try {
|
|
93
|
+
let match: RegExpExecArray | null;
|
|
94
|
+
// Selection flow refs work in both modes, only while the screen gate is approved for the current included set.
|
|
95
|
+
if ((match = /^lit\.flow\.(.+)$/.exec(ref))) {
|
|
96
|
+
const read = litFlowSource(), value = flowValue(read.value.flow, match[1]!);
|
|
97
|
+
if (!read.value.approved) throw new Error("screen gate not approved for the current included set");
|
|
98
|
+
if (value === undefined) throw new Error("unknown flow field");
|
|
99
|
+
if (placeholder.format !== undefined) { findings.push({ ...placeholder, code: "bad-format", message: `placeholder ${ref}: flow counts take no numeric format; remove |.Nf` }); continue; }
|
|
100
|
+
resolved.push({ placeholder, value, rendered: String(value), source: read.source }); continue;
|
|
101
|
+
}
|
|
86
102
|
if (study.mode !== "experiment") throw new Error("experiment refs unavailable in survey");
|
|
87
103
|
let value: unknown, provenance: Source<unknown>, exploratory = false;
|
|
88
|
-
let match: RegExpExecArray | null;
|
|
89
104
|
if ((match = /^final\.(status|reason|delta|mean|baselineMean)$/.exec(ref))) { const read = final(); provenance = read; value = read.value[match[1] as "status"]; }
|
|
90
105
|
else if ((match = /^final\.attempts\.([a-z]+)$/.exec(ref)) && statuses.includes(match[1]!)) { const read = final(); provenance = read; value = read.value.attempts.filter(a => a.status === match![1]).length; }
|
|
91
106
|
else if ((match = /^investigate\.(winner|reason)$/.exec(ref))) { const read = investigate(); provenance = read; value = match[1] === "winner" ? read.value.winner?.commit.slice(0, 12) : read.value.reason; }
|
|
@@ -104,7 +119,9 @@ export function resolvePlaceholders(dirArg: string, text: string) {
|
|
|
104
119
|
}
|
|
105
120
|
const rendered = (typeof value === "number" && placeholder.format !== undefined ? value.toFixed(placeholder.format) : String(value)) + (exploratory ? " (exploratory)" : "");
|
|
106
121
|
resolved.push({ placeholder, value, rendered, source: provenance.source });
|
|
107
|
-
} catch {
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error instanceof CopilotAcceptError) { findings.push({ ...placeholder, code: "unaccepted-draft", message: error.message }); continue; }
|
|
124
|
+
if (/^lit\.flow\./.test(ref)) { findings.push({ ...placeholder, code: "unresolved-ref", message: `placeholder ${ref}: unknown flow field or screen gate not approved for the current included set; run ares lit flow <dir> for the fields and approve the screen gate (ares gate approve <dir> screen) before retrying` }); continue; }
|
|
108
125
|
findings.push({ ...placeholder, code: "unresolved-ref", message: `placeholder ${ref}: unknown ref or absent, unclosed, stale or invalid source; inspect the attempt and close the current phase results before retrying` });
|
|
109
126
|
}
|
|
110
127
|
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { resolvePointEvidence, pointEvidenceAdvice, type PointEvidenceResolution } from "./point-evidence.ts";
|
|
2
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { commit, openStudy, plain, readBytesBounded, sha256, type Actor } from "../study.ts";
|
|
5
|
+
import { isVerified, loadCandidates, type Candidate } from "../lit/candidates.ts";
|
|
6
|
+
|
|
7
|
+
export interface PaperPoint { id: string; claim: string; requires: string[]; evidence?: string[] }
|
|
8
|
+
export interface PaperSection { id: string; heading: string; cites: string[]; points?: PaperPoint[] }
|
|
9
|
+
export interface PaperPlan { v: 1 | 2; sections: PaperSection[] }
|
|
10
|
+
export interface PaperPlanSnapshot { plan: PaperPlan; sha256: string }
|
|
11
|
+
export interface PaperPlanView { plan: PaperPlan | null; coverage: { routed: number; total: number } }
|
|
12
|
+
export const PAPER_PLAN_BYTES = 65_536, PAPER_PLAN_SECTIONS = 64, PAPER_PLAN_CITES = 300;
|
|
13
|
+
export const PAPER_PLAN_POINTS = 40, PAPER_POINT_CLAIM_CHARACTERS = 500, PAPER_POINT_EVIDENCE = 64, PAPER_POINT_EVIDENCE_BYTES = 4096;
|
|
14
|
+
export type PaperPointEvidenceResolver = (ref: string) => PointEvidenceResolution;
|
|
15
|
+
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
|
+
function invalid(cause: string): never { throw new Error(`paper plan: ${cause}; ${next}`); }
|
|
17
|
+
function object(raw: unknown, keys: readonly string[], label: string): Record<string, unknown> {
|
|
18
|
+
if (!plain(raw)) invalid(`${label} must be an object`);
|
|
19
|
+
if (Object.keys(raw).some(key => !keys.includes(key))) invalid(`${label} has an unknown field; use only ${keys.join(", ")}`);
|
|
20
|
+
return raw;
|
|
21
|
+
}
|
|
22
|
+
function candidateKeys(candidates: Candidate[]): Map<string, Candidate[]> {
|
|
23
|
+
const result = new Map<string, Candidate[]>();
|
|
24
|
+
for (const candidate of candidates) if (typeof candidate.citekey === "string" && candidate.citekey.length) {
|
|
25
|
+
const existing = result.get(candidate.citekey);
|
|
26
|
+
if (!existing) result.set(candidate.citekey, [candidate]);
|
|
27
|
+
else if (existing.length < 2) existing.push(candidate); // Two entries already establish ambiguity.
|
|
28
|
+
}
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
function pointReference(raw: unknown): string {
|
|
32
|
+
if (typeof raw !== "string" || !raw.length || raw.trim() !== raw || /\p{Cc}/u.test(raw) || /\p{Zl}|\p{Zp}/u.test(raw) || Buffer.byteLength(raw) > PAPER_POINT_EVIDENCE_BYTES) invalid("point evidence must be a bounded card or attempt reference without whitespace controls");
|
|
33
|
+
if (/^attempt:[a-f0-9]{16}$/.test(raw)) return raw;
|
|
34
|
+
if (raw.startsWith("card:") && raw.length > 5 && raw.slice(5).trim() === raw.slice(5) && !/\s/u.test(raw.slice(5))) return raw;
|
|
35
|
+
invalid("point evidence must use card:<paper-id> or attempt:<16 lowercase hex digits>");
|
|
36
|
+
}
|
|
37
|
+
function points(raw: unknown, scope: ReadonlySet<string>, ids: Set<string>, resolver: PaperPointEvidenceResolver | undefined, resolutions: Map<string, PointEvidenceResolution>): PaperPoint[] {
|
|
38
|
+
if (raw === undefined) return [];
|
|
39
|
+
if (!Array.isArray(raw) || raw.length > PAPER_PLAN_POINTS) invalid("section points must be an array of at most 40 points");
|
|
40
|
+
return raw.map((value): PaperPoint => {
|
|
41
|
+
const point = object(value, ["id", "claim", "requires", "evidence"], "point");
|
|
42
|
+
if (typeof point.id !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(point.id) || point.id.length > 64) invalid("point id must be a lowercase alphanumeric hyphenated slug of 1..64 characters");
|
|
43
|
+
if (ids.has(point.id)) invalid("point ids must be unique across the whole plan"); ids.add(point.id);
|
|
44
|
+
if (typeof point.claim !== "string" || !point.claim.trim() || Array.from(point.claim).length > PAPER_POINT_CLAIM_CHARACTERS || /[\r\n]|\p{Zl}|\p{Zp}/u.test(point.claim) || Array.from(point.claim).some(character => character !== "\t" && /\p{Cc}/u.test(character))) invalid("point claim must be nonempty single-line text of at most 500 Unicode characters");
|
|
45
|
+
if (!Array.isArray(point.requires) || point.requires.length > PAPER_PLAN_CITES) invalid("point requires must be a bounded array of section citation keys");
|
|
46
|
+
const seen = new Set<string>();
|
|
47
|
+
const requires = point.requires.map((key): string => {
|
|
48
|
+
if (typeof key !== "string" || !scope.has(key)) invalid("point requires contains a key outside its section citation scope");
|
|
49
|
+
if (seen.has(key)) invalid("point requires keys must be unique"); seen.add(key); return key;
|
|
50
|
+
});
|
|
51
|
+
let evidence: string[] | undefined;
|
|
52
|
+
if (point.evidence !== undefined) {
|
|
53
|
+
if (!Array.isArray(point.evidence) || point.evidence.length > PAPER_POINT_EVIDENCE) invalid("point evidence must be an array of at most 64 references");
|
|
54
|
+
evidence = point.evidence.map(value => {
|
|
55
|
+
const ref = pointReference(value);
|
|
56
|
+
if (!resolver) invalid("point evidence needs a source-owned resolver context; set or read the plan through the study");
|
|
57
|
+
let resolution = resolutions.get(ref);
|
|
58
|
+
if (!resolution) {
|
|
59
|
+
try { resolution = resolver(ref); } catch { invalid("point evidence could not be resolved; restore its extraction card or attempt record"); }
|
|
60
|
+
if (!resolution || typeof resolution.resolved !== "boolean") invalid("point evidence resolver returned an invalid source result");
|
|
61
|
+
resolutions.set(ref, resolution);
|
|
62
|
+
}
|
|
63
|
+
if (!resolution.resolved) invalid(`point evidence does not resolve to an existing extraction card or attempt record; ${pointEvidenceAdvice(resolution)}`);
|
|
64
|
+
return ref;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return { id: point.id, claim: point.claim, requires, ...(evidence === undefined ? {} : { evidence }) };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export function validatePaperPlan(raw: unknown, candidates: Candidate[], resolveEvidence?: PaperPointEvidenceResolver): PaperPlan {
|
|
71
|
+
const value = object(raw, ["v", "sections"], "plan");
|
|
72
|
+
if (value.v !== undefined && value.v !== 1 && value.v !== 2) invalid("unsupported plan version; use a compatible version-1 or version-2 plan reader, keeping unsupported plan bytes unchanged");
|
|
73
|
+
if (!Array.isArray(value.sections) || value.sections.length > PAPER_PLAN_SECTIONS) invalid("sections must be an array of at most 64 sections");
|
|
74
|
+
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");
|
|
75
|
+
const pointIds = new Set<string>(), resolutions = new Map<string, PointEvidenceResolution>();
|
|
76
|
+
const byKey = candidateKeys(candidates), ids = new Set<string>(), headings = new Set<string>(), verifiedKeys = new Set<string>();
|
|
77
|
+
const sections = value.sections.map((rawSection): PaperSection => {
|
|
78
|
+
const section = object(rawSection, ["id", "heading", "cites", "points"], "section");
|
|
79
|
+
if (typeof section.id !== "string" || (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(section.id) || section.id.length > 64)) invalid("section id must be a lowercase alphanumeric hyphenated slug of 1..64 characters");
|
|
80
|
+
if (ids.has(section.id)) invalid("section ids must be unique"); ids.add(section.id);
|
|
81
|
+
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
|
+
if (headings.has(section.heading)) invalid("section headings must be unique exact text"); headings.add(section.heading);
|
|
83
|
+
if (!Array.isArray(section.cites) || section.cites.length > PAPER_PLAN_CITES) invalid("section cites must be an array of at most 300 citation keys");
|
|
84
|
+
const seen = new Set<string>();
|
|
85
|
+
const cites = section.cites.map((key): string => {
|
|
86
|
+
if (typeof key !== "string" || !key.length) invalid("each citation key must be a nonempty exact bibliography key");
|
|
87
|
+
if (seen.has(key)) invalid("citation keys must be unique within each section"); seen.add(key);
|
|
88
|
+
const matches = byKey.get(key);
|
|
89
|
+
if (!matches?.length) invalid("scope contains an unknown or unassigned citation key");
|
|
90
|
+
if (matches.length !== 1) invalid("scope contains an ambiguous citation key; restore unique bibliography keys");
|
|
91
|
+
if (!verifiedKeys.has(key)) {
|
|
92
|
+
const candidate = matches[0]!;
|
|
93
|
+
if (candidate.status !== "included") invalid("scope reference is excluded or unscreened; include it through ares lit screen before routing it");
|
|
94
|
+
if (!isVerified(candidate)) invalid("scope reference is not identifier-verified or its verification is stale");
|
|
95
|
+
verifiedKeys.add(key);
|
|
96
|
+
}
|
|
97
|
+
return key;
|
|
98
|
+
});
|
|
99
|
+
const pointList = points(section.points, seen, pointIds, resolveEvidence, resolutions);
|
|
100
|
+
return { id: section.id, heading: section.heading, cites, ...(pointList.length ? { points: pointList } : {}) };
|
|
101
|
+
});
|
|
102
|
+
const plan: PaperPlan = { v: pointIds.size ? 2 : 1, sections };
|
|
103
|
+
if (Buffer.byteLength(JSON.stringify(plan, null, 2) + "\n") > PAPER_PLAN_BYTES) invalid("formatted plan exceeds the 64 KiB bound; reduce sections, citation keys or heading lengths");
|
|
104
|
+
return plan;
|
|
105
|
+
}
|
|
106
|
+
function metadata(file: string) {
|
|
107
|
+
try { return lstatSync(file); }
|
|
108
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; invalid("fixed paper directory or plan metadata is unreadable"); }
|
|
109
|
+
}
|
|
110
|
+
/** Resolve only the fixed paper/plan.json address, refusing links rather than following plan locators. */
|
|
111
|
+
function address(dirArg: string): { dir: string; file: string; present: boolean } {
|
|
112
|
+
const dir = resolve(dirArg), paper = join(dir, "paper"), info = metadata(paper);
|
|
113
|
+
if (!info) {
|
|
114
|
+
let root: string;
|
|
115
|
+
try { root = realpathSync(dir); } catch { invalid("study directory must be readable before accessing the fixed paper plan"); }
|
|
116
|
+
return { dir: root, file: join(root, "paper", "plan.json"), present: false };
|
|
117
|
+
}
|
|
118
|
+
if (!info.isDirectory() || info.isSymbolicLink()) invalid("paper must be a physical directory, not a link or special file");
|
|
119
|
+
let root: string;
|
|
120
|
+
try { root = realpathSync(dir); if (realpathSync(paper) !== join(root, "paper")) invalid("paper directory escapes the study"); }
|
|
121
|
+
catch { invalid("fixed paper directory must be readable and physically contained in the study"); }
|
|
122
|
+
const file = join(root, "paper", "plan.json"), stat = metadata(file);
|
|
123
|
+
if (stat && (!stat.isFile() || stat.isSymbolicLink())) invalid("paper/plan.json must be a regular physical file, not a link or special file");
|
|
124
|
+
return { dir: root, file, present: !!stat };
|
|
125
|
+
}
|
|
126
|
+
function currentCandidates(dir: string): Candidate[] {
|
|
127
|
+
try { return loadCandidates(dir); } catch { return invalid("current reference records are unreadable or malformed"); }
|
|
128
|
+
}
|
|
129
|
+
function snapshot(dir: string, candidates: Candidate[] | undefined, strictEvidence: boolean): PaperPlanSnapshot | undefined {
|
|
130
|
+
// An absent optional plan must not impose new restrictions on a legacy manuscript location.
|
|
131
|
+
if (!metadata(join(resolve(dir), "paper", "plan.json"))) return undefined;
|
|
132
|
+
const target = address(dir);
|
|
133
|
+
if (!target.present) return undefined;
|
|
134
|
+
let bytes: Buffer, raw: unknown;
|
|
135
|
+
try { bytes = readBytesBounded(target.file, PAPER_PLAN_BYTES, { noFollow: true }); }
|
|
136
|
+
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
|
+
try { raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
|
|
138
|
+
catch { invalid("paper/plan.json is not valid UTF-8 JSON"); }
|
|
139
|
+
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2)) invalid("stored plan must carry supported v: 1 or v: 2; use paper plan set to version an unversioned input, or a compatible ares reader while keeping unsupported version bytes unchanged");
|
|
140
|
+
const resolver: PaperPointEvidenceResolver = strictEvidence ? ref => resolvePointEvidence(target.dir, ref) : () => ({ resolved: true });
|
|
141
|
+
const plan = validatePaperPlan(raw, candidates ?? currentCandidates(target.dir), resolver);
|
|
142
|
+
if (plan.v !== raw.v) invalid("stored plan version does not match its points; use paper plan set to normalize the known plan format");
|
|
143
|
+
return { plan, sha256: sha256(bytes) };
|
|
144
|
+
}
|
|
145
|
+
export function readPaperPlanSnapshot(dir: string, candidates?: Candidate[]): PaperPlanSnapshot | undefined { return snapshot(dir, candidates, true); }
|
|
146
|
+
/** Paper check validates all plan syntax/references, then reports evidence disappearance as findings. */
|
|
147
|
+
export function readPaperPlanCheckSnapshot(dir: string, candidates?: Candidate[]): PaperPlanSnapshot | undefined { return snapshot(dir, candidates, false); }
|
|
148
|
+
export function readPaperPlan(dir: string, candidates?: Candidate[]): PaperPlan | undefined { return readPaperPlanSnapshot(dir, candidates)?.plan; }
|
|
149
|
+
export function paperPlanCoverage(plan: PaperPlan, candidates: Candidate[]): { routed: number; total: number } {
|
|
150
|
+
const routed = new Set(plan.sections.flatMap(section => section.cites)), included = candidates.filter(candidate => candidate.status === "included");
|
|
151
|
+
return { routed: included.filter(candidate => !!candidate.citekey && routed.has(candidate.citekey) && isVerified(candidate)).length, total: included.length };
|
|
152
|
+
}
|
|
153
|
+
/** Caller owns the study lock. All validation precedes the command's one file+event commit. */
|
|
154
|
+
export function setPaperPlan(dirArg: string, raw: unknown, actor: Actor): PaperPlan {
|
|
155
|
+
const { dir } = openStudy(dirArg), plan = validatePaperPlan(raw, currentCandidates(dir), ref => resolvePointEvidence(dir, ref)), target = address(dir);
|
|
156
|
+
if (target.present) {
|
|
157
|
+
let previous: unknown;
|
|
158
|
+
try { previous = JSON.parse(new TextDecoder("utf-8", {fatal: true}).decode(readBytesBounded(target.file, PAPER_PLAN_BYTES, {noFollow: true}))); }
|
|
159
|
+
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");
|
|
161
|
+
}
|
|
162
|
+
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");
|
|
164
|
+
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
|
+
return plan;
|
|
166
|
+
}
|
|
167
|
+
export function showPaperPlan(dirArg: string): PaperPlanView {
|
|
168
|
+
const { dir } = openStudy(dirArg), candidates = currentCandidates(dir), plan = readPaperPlan(dir, candidates);
|
|
169
|
+
return { plan: plan ?? null, coverage: paperPlanCoverage(plan ?? { v: 1, sections: [] }, candidates) };
|
|
170
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { readCard } from "../lit/cards.ts";
|
|
2
|
+
import { ATTEMPT_BYTES, validateAttemptRecord } from "../exp/attempts.ts";
|
|
3
|
+
import { lstatSync, opendirSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { openStudy, readTextBounded } from "../study.ts";
|
|
6
|
+
|
|
7
|
+
export interface PointEvidenceResolution { resolved: boolean; reason?: string; code?: "run-limit" }
|
|
8
|
+
/** Only typed local failure classes may become advice; never propagate a source's free-text error. */
|
|
9
|
+
export function pointEvidenceAdvice(resolution: PointEvidenceResolution): string {
|
|
10
|
+
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";
|
|
11
|
+
}
|
|
12
|
+
class PointEvidenceBound extends Error {}
|
|
13
|
+
function physicalDirectory(file: string): boolean {
|
|
14
|
+
try { const stat = lstatSync(file); if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("unsafe attempt directory"); return true; }
|
|
15
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
|
|
16
|
+
}
|
|
17
|
+
/** Read only the addressed payload; unrelated attempts never enter point planning or checking. */
|
|
18
|
+
function existingAttempt(dir: string, wanted: string): boolean {
|
|
19
|
+
const {study} = openStudy(dir), runs = join(dir, "runs");
|
|
20
|
+
if (study.mode !== "experiment" || !physicalDirectory(runs)) return false;
|
|
21
|
+
const directory = opendirSync(runs); let count = 0, found = false;
|
|
22
|
+
try {
|
|
23
|
+
for (let entry = directory.readSync(); entry; entry = directory.readSync()) {
|
|
24
|
+
if (++count > 4096) throw new PointEvidenceBound("point evidence: more than 4096 run directories; archive the study before checking point evidence");
|
|
25
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(entry.name)) throw new Error("unsafe run name");
|
|
26
|
+
const run = join(runs, entry.name), attempts = join(run, "attempts");
|
|
27
|
+
if (!physicalDirectory(run) || !physicalDirectory(attempts)) continue;
|
|
28
|
+
const file = join(attempts, `${wanted}.json`);
|
|
29
|
+
let raw: string;
|
|
30
|
+
try {
|
|
31
|
+
const stat = lstatSync(file);
|
|
32
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("unsafe attempt record");
|
|
33
|
+
if (found) return false; // The address has no run component; duplicate matches are ambiguous.
|
|
34
|
+
raw = readTextBounded(file, ATTEMPT_BYTES, {noFollow: true});
|
|
35
|
+
}
|
|
36
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
37
|
+
if (validateAttemptRecord(JSON.parse(raw), entry.name, wanted).studyId !== study.id) return false;
|
|
38
|
+
found = true;
|
|
39
|
+
}
|
|
40
|
+
return found;
|
|
41
|
+
} finally { directory.closeSync(); }
|
|
42
|
+
}
|
|
43
|
+
/** Existence and record integrity only, never support, correctness or a successful outcome. */
|
|
44
|
+
export function resolvePointEvidence(dir: string, reference: string): PointEvidenceResolution {
|
|
45
|
+
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
|
+
try {
|
|
47
|
+
if (reference.startsWith("card:")) {
|
|
48
|
+
const id = reference.slice(5);
|
|
49
|
+
if (!id || !readCard(dir, id)) return {resolved: false, reason: "extraction card is missing; record it with ares lit card before setting the plan"};
|
|
50
|
+
return {resolved: true};
|
|
51
|
+
}
|
|
52
|
+
if (reference.startsWith("attempt:")) {
|
|
53
|
+
const id = reference.slice(8);
|
|
54
|
+
if (!/^[a-f0-9]{16}$/.test(id)) return {resolved: false, reason: "attempt address is invalid; select an id from ares attempt list"};
|
|
55
|
+
if (!existingAttempt(dir, id)) return {resolved: false, reason: "attempt is missing, ambiguous or belongs to another source; select a current-study record from ares attempt list"};
|
|
56
|
+
return {resolved: true};
|
|
57
|
+
}
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof PointEvidenceBound) return {resolved: false, code: "run-limit", reason: error.message};
|
|
60
|
+
return {resolved: false, reason: "local evidence is missing, malformed or unsupported; restore its last valid card/attempt record and rerun ares paper check"};
|
|
61
|
+
}
|
|
62
|
+
return {resolved: false, reason: "unsupported evidence address; use only current-study card:<paper-id> or attempt:<16-hex-id>"};
|
|
63
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { citationOccurrences } from "../lit/cite.ts";
|
|
2
|
+
import { markdownHeadings, type MarkdownHeading } from "./headings.ts";
|
|
3
|
+
import type { PaperPlan } from "./plan.ts";
|
|
4
|
+
import * as pointEvidence from "./point-evidence.ts";
|
|
5
|
+
|
|
6
|
+
export const POINT_CODES = ["missing-point", "missing-required-citation", "unresolved-point-evidence"] as const;
|
|
7
|
+
export type PointFindingCode = typeof POINT_CODES[number];
|
|
8
|
+
export interface PaperPointHit {
|
|
9
|
+
code: PointFindingCode;
|
|
10
|
+
severity: "blocking";
|
|
11
|
+
pointId: string;
|
|
12
|
+
sectionId: string;
|
|
13
|
+
section?: string[];
|
|
14
|
+
start: number;
|
|
15
|
+
end: number;
|
|
16
|
+
message: string;
|
|
17
|
+
}
|
|
18
|
+
type PlannedSection = PaperPlan["sections"][number];
|
|
19
|
+
interface SectionWindow { section: PlannedSection; heading: MarkdownHeading; end: number }
|
|
20
|
+
interface PointAnchor { id: string; start: number; end: number; window?: SectionWindow }
|
|
21
|
+
|
|
22
|
+
/** Tokenize whole comments first, so an anchor-looking substring inside a normal comment is not an anchor. */
|
|
23
|
+
function anchors(manuscript: string, codeMask: Uint8Array): PointAnchor[] {
|
|
24
|
+
const result: PointAnchor[] = [];
|
|
25
|
+
let cursor = 0;
|
|
26
|
+
for (;;) {
|
|
27
|
+
const start = manuscript.indexOf("<!--", cursor);
|
|
28
|
+
if (start < 0) break;
|
|
29
|
+
// A masked or Markdown-escaped opener cannot consume a later prose comment's closer.
|
|
30
|
+
let backslashes = 0;
|
|
31
|
+
for (let index = start - 1; index >= 0 && manuscript[index] === "\\"; index--) backslashes++;
|
|
32
|
+
if (codeMask[start] || backslashes % 2 === 1) { cursor = start + 4; continue; }
|
|
33
|
+
const close = manuscript.indexOf("-->", start + 4), end = close < 0 ? manuscript.length : close + 3;
|
|
34
|
+
const match = /^<!--[\s]*point:([a-z0-9]+(?:-[a-z0-9]+)*)[\s]*-->$/.exec(manuscript.slice(start, end));
|
|
35
|
+
if (match && match[1]!.length <= 64) result.push({id: match[1]!, start, end});
|
|
36
|
+
cursor = end;
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Literal point anchors and citation keys only; claim prose is intentionally never inspected. */
|
|
42
|
+
export function paperPointFindings(dir: string, manuscript: string, codeMask: Uint8Array, headingHidden: Uint8Array, citationText: string, plan: PaperPlan): PaperPointHit[] {
|
|
43
|
+
if (!plan.sections.some(section => section.points?.length)) return [];
|
|
44
|
+
if (citationText.length !== manuscript.length) throw new Error("paper writing points: masked citation text changed source offsets; pass offset-preserving citationText before checking points");
|
|
45
|
+
const byHeading = new Map(plan.sections.map(section => [section.heading, section]));
|
|
46
|
+
const boundaries = markdownHeadings(manuscript, headingHidden).filter(heading => byHeading.has(heading.rawText));
|
|
47
|
+
const windows: SectionWindow[] = boundaries.map((heading, index) => ({section: byHeading.get(heading.rawText)!, heading, end: boundaries[index + 1]?.start ?? manuscript.length}));
|
|
48
|
+
const tokens = anchors(manuscript, codeMask), own = new Map<string, PointAnchor[]>(), citations = citationOccurrences(citationText), hits: PaperPointHit[] = [];
|
|
49
|
+
const evidenceResults = new Map<string, pointEvidence.PointEvidenceResolution>();
|
|
50
|
+
let windowCursor = 0, citationCursor = 0;
|
|
51
|
+
for (const [index, anchor] of tokens.entries()) {
|
|
52
|
+
while (windowCursor < windows.length && windows[windowCursor]!.heading.start <= anchor.start) windowCursor++;
|
|
53
|
+
const window = windowCursor ? windows[windowCursor - 1] : undefined;
|
|
54
|
+
if (window && anchor.start < window.end) anchor.window = window;
|
|
55
|
+
const point = anchor.window?.section.points?.find(point => point.id === anchor.id);
|
|
56
|
+
if (!point) continue; // Unknown and wrong-section tokens still end the preceding window through tokens[index + 1].
|
|
57
|
+
const matches = own.get(point.id) ?? []; matches.push(anchor); own.set(point.id, matches);
|
|
58
|
+
const end = Math.min(tokens[index + 1]?.start ?? manuscript.length, anchor.window!.end), keys = new Set<string>();
|
|
59
|
+
while (citationCursor < citations.length && citations[citationCursor]!.start < anchor.end) citationCursor++;
|
|
60
|
+
while (citationCursor < citations.length && citations[citationCursor]!.start < end) keys.add(citations[citationCursor++]!.key);
|
|
61
|
+
for (const key of new Set(point.requires)) if (!keys.has(key)) hits.push({
|
|
62
|
+
code: "missing-required-citation", severity: "blocking", pointId: point.id, sectionId: anchor.window!.section.id, section: anchor.window!.heading.path, start: anchor.start, end: anchor.end,
|
|
63
|
+
message: `point ${point.id} requires citation @${key.slice(0, 80)} in this anchor window; cite it here or revise the declared point requirements`,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
for (const section of plan.sections) for (const point of section.points ?? []) {
|
|
67
|
+
const first = own.get(point.id)?.[0], sectionWindow = first?.window ?? windows.find(window => window.section.id === section.id);
|
|
68
|
+
const start = first?.start ?? sectionWindow?.heading.start ?? 0, end = first?.end ?? sectionWindow?.heading.end ?? 0;
|
|
69
|
+
const context = {pointId: point.id, sectionId: section.id, ...(sectionWindow ? {section: sectionWindow.heading.path} : {}), start, end};
|
|
70
|
+
if (!first) hits.push({code: "missing-point", severity: "blocking", ...context,
|
|
71
|
+
message: `point ${point.id} has no anchor in section ${section.id}; add an exact <!-- point:${point.id} --> comment in that section before its paragraph`});
|
|
72
|
+
for (const ref of new Set(point.evidence ?? [])) {
|
|
73
|
+
let resolution = evidenceResults.get(ref);
|
|
74
|
+
if (resolution === undefined) {
|
|
75
|
+
try { resolution = pointEvidence.resolvePointEvidence(dir, ref); } catch { resolution = {resolved: false}; }
|
|
76
|
+
evidenceResults.set(ref, resolution);
|
|
77
|
+
}
|
|
78
|
+
if (!resolution.resolved) hits.push({code: "unresolved-point-evidence", severity: "blocking", ...context,
|
|
79
|
+
message: `point ${point.id} evidence ${ref.slice(0, 80)} does not resolve; ${pointEvidence.pointEvidenceAdvice(resolution)}`});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return hits.sort((a, b) => a.start - b.start || a.code.localeCompare(b.code));
|
|
83
|
+
}
|