@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,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
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
import { requireCopilotAccept } from "../copilot.ts";
|
|
1
2
|
import { existsSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, sha256, type Actor } from "../study.ts";
|
|
4
5
|
import { checkPaper, manuscriptPath } from "./check.ts";
|
|
5
6
|
import { MANUSCRIPT_BYTES } from "./placeholders.ts";
|
|
7
|
+
import { readPaperPlanSnapshot } from "./plan.ts";
|
|
6
8
|
|
|
7
9
|
export const PAPER_EVIDENCE_BYTES = 8 * 1024 * 1024;
|
|
8
|
-
|
|
9
|
-
v: 1;
|
|
10
|
+
interface EvidenceBody {
|
|
10
11
|
manuscriptSha256: string;
|
|
11
12
|
placeholders: {
|
|
12
13
|
kind: "number" | "literal"; raw: string; start: number; end: number; line: number; column: number;
|
|
@@ -14,6 +15,13 @@ export interface PaperEvidence {
|
|
|
14
15
|
source: { file: string; sha256: string };
|
|
15
16
|
}[];
|
|
16
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
|
+
}
|
|
17
25
|
export function paperBuildPaths(dir: string) { return { manuscript: join(dir, "paper", "build", "manuscript.md"), evidence: join(dir, "paper", "build", "evidence.json") }; }
|
|
18
26
|
function previous(file: string, bound: number): string | undefined {
|
|
19
27
|
if (!existsSync(file)) return undefined;
|
|
@@ -25,17 +33,18 @@ function evidenceBytes(dir: string): string | undefined {
|
|
|
25
33
|
if (oldEvidence !== undefined) {
|
|
26
34
|
let raw: unknown;
|
|
27
35
|
try { raw = JSON.parse(oldEvidence); } catch { throw new Error("paper evidence: invalid JSON; restore the last valid paper/build/evidence.json before rebuilding"); }
|
|
28
|
-
|
|
36
|
+
paperEvidenceVersion(raw);
|
|
29
37
|
}
|
|
30
38
|
return oldEvidence;
|
|
31
39
|
}
|
|
32
40
|
function calculatePaper(dir: string) {
|
|
33
41
|
const report = checkPaper(dir);
|
|
34
42
|
if (!report.ok) {
|
|
35
|
-
const
|
|
36
|
-
|
|
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`);
|
|
37
46
|
}
|
|
38
|
-
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 => {
|
|
39
48
|
const token = entry.placeholder;
|
|
40
49
|
return { kind: token.kind, raw: token.raw, start: token.start, end: token.end, line: token.line, column: token.column,
|
|
41
50
|
...(token.kind === "number" ? { ref: token.ref, ...(token.format === undefined ? {} : { format: token.format }) } : {}),
|
|
@@ -50,12 +59,15 @@ function calculatePaper(dir: string) {
|
|
|
50
59
|
}
|
|
51
60
|
/** Caller holds the study lock. Refusals precede the single output-and-receipt commit. */
|
|
52
61
|
export function buildPaper(dirArg: string, actor: Actor) {
|
|
53
|
-
const { dir } = openStudy(dirArg)
|
|
62
|
+
const { dir } = openStudy(dirArg);
|
|
63
|
+
requireCopilotAccept(dir, "hypotheses");
|
|
64
|
+
const paths = paperBuildPaths(dir), oldEvidence = evidenceBytes(dir);
|
|
54
65
|
const { report, text, manuscriptSha256, evidenceSha256 } = calculatePaper(dir), oldManuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
|
|
55
66
|
const receipt = readLedger(dir).findLast(event => event.type === "paper.built");
|
|
56
67
|
const changed = oldManuscript !== report.rendered || oldEvidence !== text || receipt?.data.manuscriptSha256 !== manuscriptSha256 || receipt.data.evidenceSha256 !== evidenceSha256;
|
|
57
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");
|
|
58
|
-
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}) } }]);
|
|
59
71
|
return { manuscriptSha256, evidenceSha256, changed };
|
|
60
72
|
}
|
|
61
73
|
|
package/src/paper/check.ts
CHANGED
|
@@ -1,21 +1,27 @@
|
|
|
1
|
+
import { CopilotAcceptError } from "../copilot.ts";
|
|
1
2
|
import { existsSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { openStudy, readTextBounded, sha256 } from "../study.ts";
|
|
4
5
|
import { loadCandidates } from "../lit/candidates.ts";
|
|
5
6
|
import { checkCitations, citationOccurrences } from "../lit/cite.ts";
|
|
7
|
+
import { readCard } from "../lit/cards.ts";
|
|
6
8
|
import { readProtocol } from "../exp/protocol.ts";
|
|
7
9
|
import { readSelection } from "../exp/selection.ts";
|
|
8
10
|
import { investigateResultPath, readClosedInvestigation } from "../exp/investigate.ts";
|
|
9
11
|
import { finalResultPath } from "../exp/final.ts";
|
|
10
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";
|
|
11
17
|
|
|
12
18
|
export const MAX_CODE_NUMBERS = 500;
|
|
13
|
-
export interface PaperFinding { code: "bare-number" | "unresolved-ref" | "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 }
|
|
14
20
|
function blank(text: string, mask: Uint8Array): string { return text.split("").map((char, index) => mask[index] && char !== "\n" && char !== "\r" ? " " : char).join(""); }
|
|
15
21
|
function mark(mask: Uint8Array, start: number, end: number) { mask.fill(1, start, end); }
|
|
16
22
|
function escaped(text: string, index: number): boolean { let slashes = 0; while (index > 0 && text[--index] === "\\") slashes++; return slashes % 2 === 1; }
|
|
17
23
|
/** Masks syntax-only destinations and code while retaining original offsets. Visible link labels remain prose. */
|
|
18
|
-
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 } {
|
|
19
25
|
const mask = new Uint8Array(text.length), protectedText = new Uint8Array(text.length), tokens = parsePlaceholders(text);
|
|
20
26
|
for (const token of [...tokens.placeholders, ...tokens.findings]) mark(protectedText, token.start, token.end);
|
|
21
27
|
let fence: { char: string; length: number } | undefined, paragraph = false, indented = false;
|
|
@@ -49,6 +55,7 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
49
55
|
}
|
|
50
56
|
}
|
|
51
57
|
}
|
|
58
|
+
const blockCode = mask.slice();
|
|
52
59
|
// Backtick runs must have an exactly matching closer; unmatched delimiters remain prose.
|
|
53
60
|
const runs = [...text.matchAll(/`+/g)].filter(hit => !mask[hit.index] && !protectedText[hit.index] && !knownHidden?.[hit.index]);
|
|
54
61
|
const regions: number[] = []; let region = 0, previous = 0;
|
|
@@ -66,7 +73,7 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
66
73
|
const close = next.get(i);
|
|
67
74
|
if (close !== undefined) { mark(mask, runs[i]!.index, runs[close]!.index + runs[close]![0].length); i = close; }
|
|
68
75
|
}
|
|
69
|
-
const code = mask.slice();
|
|
76
|
+
const code = mask.slice(), anchorHidden = code.slice();
|
|
70
77
|
const labels: number[] = [];
|
|
71
78
|
for (let i = 0; i < text.length; i++) {
|
|
72
79
|
if (mask[i] || protectedText[i] || knownHidden?.[i] || (text[i] !== "<" && text[i] !== "]" && text[i] !== "[") || escaped(text, i)) continue;
|
|
@@ -97,8 +104,10 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
97
104
|
const quote = text[tail++]!; while (tail < text.length && (text[tail] !== quote || escaped(text, tail))) tail++;
|
|
98
105
|
if (tail >= text.length) continue; tail++; while (/\s/.test(text[tail] ?? "") && tail < text.length) tail++;
|
|
99
106
|
}
|
|
100
|
-
if (text[tail] === ")") mark(mask, start, end);
|
|
107
|
+
if (text[tail] === ")") { mark(mask, start, end); mark(anchorHidden, i + 1, tail + 1); }
|
|
101
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;
|
|
102
111
|
const hidden = new Uint8Array(text.length); let hasComment = false;
|
|
103
112
|
for (const comment of text.matchAll(/<!--[\s\S]*?(?:-->|$)/g)) {
|
|
104
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; }
|
|
@@ -108,16 +117,17 @@ function markdownMask(text: string, knownHidden?: Uint8Array): { mask: Uint8Arra
|
|
|
108
117
|
const target = match[1]!, start = match.index + match[0].lastIndexOf(target);
|
|
109
118
|
if (!mask[start] && !protectedText[start]) {
|
|
110
119
|
mark(mask, start, start + target.length);
|
|
111
|
-
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);
|
|
112
121
|
}
|
|
113
122
|
}
|
|
114
123
|
// Reclassify once with non-code comments excluded, so a fence inside a comment cannot hide later prose.
|
|
115
124
|
if (!knownHidden && hasComment) return markdownMask(text, hidden);
|
|
116
|
-
|
|
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 };
|
|
117
127
|
}
|
|
118
128
|
export function manuscriptPath(dir: string): string { return join(dir, "paper", "manuscript.md"); }
|
|
119
129
|
export function checkPaper(dirArg: string) {
|
|
120
|
-
const { dir, study } = openStudy(dirArg), file = manuscriptPath(dir);
|
|
130
|
+
const { dir, study } = openStudy(dirArg), file = manuscriptPath(dir), settings = readPaperSettings(dir);
|
|
121
131
|
let manuscript: string;
|
|
122
132
|
try { manuscript = readTextBounded(file, MANUSCRIPT_BYTES); }
|
|
123
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"); }
|
|
@@ -127,7 +137,7 @@ export function checkPaper(dirArg: string) {
|
|
|
127
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; }
|
|
128
138
|
return { line: lo + 1, column: start - lines[lo]! + 1 };
|
|
129
139
|
};
|
|
130
|
-
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 });
|
|
131
141
|
const findings: PaperFinding[] = resolution.findings.map(f => finding(f.code, f.start, f.end, f.message));
|
|
132
142
|
const codeNumbers: { value: string; line: number; column: number }[] = [];
|
|
133
143
|
let codeNumberCount = 0;
|
|
@@ -142,7 +152,8 @@ export function checkPaper(dirArg: string) {
|
|
|
142
152
|
if (placeholder.kind === "number") mark(citationMask, placeholder.start, placeholder.end);
|
|
143
153
|
}
|
|
144
154
|
for (const problem of parsed.findings) { mark(numberMask, problem.start, problem.end); mark(citationMask, problem.start, problem.end); }
|
|
145
|
-
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);
|
|
146
157
|
const groups = new Map<number, number>();
|
|
147
158
|
for (const hit of citationOccurrences(citationText)) {
|
|
148
159
|
mark(numberMask, hit.start, hit.end); groups.set(hit.groupStart, hit.groupEnd);
|
|
@@ -169,12 +180,29 @@ export function checkPaper(dirArg: string) {
|
|
|
169
180
|
const protocol = readProtocol(dir), rule = protocol ? readSelection(dir, protocol) : undefined;
|
|
170
181
|
if (rule && existsSync(investigateResultPath(dir, rule.run))) {
|
|
171
182
|
try { if (readClosedInvestigation(dir).result.winner === null) requireRef("investigate.reason"); }
|
|
172
|
-
catch { findings.push(finding("unresolved-ref", 0, 0, "investigate result is not current and closed; run ares investigate close before checking the paper")); }
|
|
183
|
+
catch (error) { findings.push(error instanceof CopilotAcceptError ? finding("unaccepted-draft", 0, 0, error.message) : finding("unresolved-ref", 0, 0, "investigate result is not current and closed; run ares investigate close before checking the paper")); }
|
|
173
184
|
}
|
|
174
|
-
} catch { findings.push(finding("unresolved-ref", 0, 0, "experiment design or selection is invalid; restore the current validated inputs before paper check")); }
|
|
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")); }
|
|
175
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)});
|
|
176
194
|
let rendered = "", cursor = 0;
|
|
177
195
|
for (const entry of resolution.placeholders) { rendered += manuscript.slice(cursor, entry.placeholder.start) + entry.rendered; cursor = entry.placeholder.end; }
|
|
178
196
|
rendered += manuscript.slice(cursor);
|
|
179
|
-
|
|
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 } : {}) };
|
|
180
208
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Original UTF-16 source offsets; text/path preserve the legacy hygiene scanner's normalization. */
|
|
2
|
+
export interface MarkdownHeading {
|
|
3
|
+
start: number;
|
|
4
|
+
end: number;
|
|
5
|
+
level: number;
|
|
6
|
+
text: string;
|
|
7
|
+
rawText: string;
|
|
8
|
+
parent: number;
|
|
9
|
+
path: string[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Deterministic ATX/Setext extraction; the caller controls which block/comment positions are hidden. */
|
|
13
|
+
export function markdownHeadings(manuscript: string, hidden: Uint8Array): MarkdownHeading[] {
|
|
14
|
+
const headings: MarkdownHeading[] = [], stack: number[] = [];
|
|
15
|
+
const add = (start: number, end: number, level: number, legacyRaw: string, exactRaw = legacyRaw) => {
|
|
16
|
+
const text = legacyRaw.trim().replace(/\s+/g, " ");
|
|
17
|
+
while (stack.length && headings[stack.at(-1)!]!.level >= level) stack.pop();
|
|
18
|
+
const parent = stack.at(-1) ?? -1;
|
|
19
|
+
headings.push({start, end, level, text, rawText: exactRaw.trim(), parent, path: [...(parent >= 0 ? headings[parent]!.path : []), text]});
|
|
20
|
+
stack.push(headings.length - 1);
|
|
21
|
+
};
|
|
22
|
+
let paragraph: {start: number; end: number; lines: string[]} | undefined;
|
|
23
|
+
for (const match of manuscript.matchAll(/[^\n]*(?:\n|$)/g)) {
|
|
24
|
+
if (!match[0]) break;
|
|
25
|
+
const start = match.index, line = match[0].replace(/\r?\n$/, "");
|
|
26
|
+
if (hidden[start + /^[ \t]*/.exec(line)![0].length] || !line.trim()) { paragraph = undefined; continue; }
|
|
27
|
+
const atx = /^ {0,3}(#{1,6})(?:[ \t]+([^\r\n]*?))?(?:[ \t]+#+)?[ \t]*$/.exec(line);
|
|
28
|
+
if (atx) { add(start, start + line.length, atx[1]!.length, atx[2] ?? ""); paragraph = undefined; continue; }
|
|
29
|
+
const underline = /^ {0,3}(=+|-+)[ \t]*$/.exec(line);
|
|
30
|
+
if (underline && paragraph) {
|
|
31
|
+
add(paragraph.start, start + line.length, underline[1]![0] === "=" ? 1 : 2, paragraph.lines.join(" "), manuscript.slice(paragraph.start, paragraph.end));
|
|
32
|
+
paragraph = undefined; continue;
|
|
33
|
+
}
|
|
34
|
+
if (/^ {0,3}(?:[-+*]|[0-9]+[.)])(?:[ \t]|$)|^ {0,3}>|^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/.test(line) && !paragraph) { paragraph = undefined; continue; }
|
|
35
|
+
if (paragraph) { paragraph.lines.push(line); paragraph.end = start + line.length; }
|
|
36
|
+
else paragraph = {start, end: start + line.length, lines: [line]};
|
|
37
|
+
}
|
|
38
|
+
return headings;
|
|
39
|
+
}
|