mlx-bun 0.0.7 → 0.0.9

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.
Files changed (138) hide show
  1. package/README.md +112 -20
  2. package/docs/design/batching-v2-plan.md +515 -0
  3. package/docs/design/bucketing-stage.md +196 -0
  4. package/docs/design/compat-cli-surface-design.md +11 -11
  5. package/docs/design/diffusion-gemma-port.md +602 -0
  6. package/docs/design/docs-reorg-plan.md +1 -1
  7. package/docs/design/dreaming-nightly-pipeline.md +291 -0
  8. package/docs/design/dspark-speculative-decoding.md +106 -0
  9. package/docs/design/generic-model-support.md +381 -0
  10. package/docs/design/memory-inference-path.md +422 -0
  11. package/docs/design/memory-synthesis.md +287 -0
  12. package/docs/design/minicpm5-decode-megakernel.md +484 -0
  13. package/docs/design/mlx-lm-tool-parity-plan.md +535 -0
  14. package/docs/design/orpo-dynamic-lambda.md +41 -0
  15. package/docs/design/orpo-training.md +35 -5
  16. package/docs/design/parallel-slots.md +12 -1
  17. package/docs/design/parity-tier-dag.md +13 -5
  18. package/docs/design/spec-decode-larger-targets.md +229 -0
  19. package/docs/design/tauri-desktop-app.md +2 -2
  20. package/docs/design/the-dreaming-handoff.md +141 -0
  21. package/docs/design/the-dreaming-master-plan.md +446 -0
  22. package/docs/design/write-pipeline-entity.md +468 -0
  23. package/docs/investigations/curve-bisector-routing.md +1 -1
  24. package/docs/investigations/decode-roofline-lookagain.md +262 -0
  25. package/docs/investigations/dspark-handoff.md +58 -0
  26. package/docs/investigations/kernel-perf-review-2026-07.md +92 -0
  27. package/docs/planning/PRODUCT_ROADMAP.md +2 -2
  28. package/docs/planning/curve-sampler-research-plan.md +331 -0
  29. package/docs/planning/memory-docs-and-dag-plan.md +185 -0
  30. package/docs/planning/pi-integration-review.md +178 -0
  31. package/docs/planning/release-notes-v0.0.9.md +122 -0
  32. package/docs/planning/web-ui-pass-plan.md +213 -0
  33. package/docs/planning/website-readme-pass-plan.md +224 -0
  34. package/docs/reference/cli.md +255 -0
  35. package/docs/reference/embedding.md +7 -2
  36. package/docs/reference/library-api.md +22 -3
  37. package/docs/reference/memory.md +5 -5
  38. package/docs/reference/models.md +137 -0
  39. package/docs/reference/orpo-quickstart.md +6 -0
  40. package/docs/reference/server-api.md +187 -9
  41. package/docs/reference/server-config.md +40 -9
  42. package/docs/reference/training.md +25 -11
  43. package/package.json +1 -1
  44. package/src/anthropic.ts +22 -0
  45. package/src/assets/curve-designer.html +1 -1
  46. package/src/chat-template.ts +25 -7
  47. package/src/cli.ts +1029 -86
  48. package/src/config.ts +54 -3
  49. package/src/diffusion/diffusion-generate.ts +436 -0
  50. package/src/download.ts +99 -8
  51. package/src/embed.ts +77 -0
  52. package/src/eval/perplexity.ts +164 -0
  53. package/src/eval/runner.ts +19 -7
  54. package/src/eval/tasks/bfcl.ts +1 -1
  55. package/src/generate.ts +196 -19
  56. package/src/harness-pi.ts +43 -17
  57. package/src/index.ts +2 -0
  58. package/src/lora.ts +2 -2
  59. package/src/memory/article.ts +558 -0
  60. package/src/memory/chunk-validation.ts +150 -0
  61. package/src/memory/chunk.ts +305 -12
  62. package/src/memory/cluster.ts +344 -17
  63. package/src/memory/coverage.ts +134 -0
  64. package/src/memory/crosslink.ts +0 -0
  65. package/src/memory/db.ts +184 -45
  66. package/src/memory/entity.ts +203 -0
  67. package/src/memory/gate.ts +187 -0
  68. package/src/memory/history.ts +152 -0
  69. package/src/memory/ingest.ts +324 -11
  70. package/src/memory/model.ts +321 -0
  71. package/src/memory/normalize.ts +671 -0
  72. package/src/memory/parse.ts +22 -0
  73. package/src/memory/pipeline.ts +242 -30
  74. package/src/memory/prompts.ts +42 -0
  75. package/src/memory/query.ts +334 -0
  76. package/src/memory/reconcile.ts +734 -0
  77. package/src/memory/redirect.ts +108 -0
  78. package/src/memory/reindex.ts +325 -0
  79. package/src/memory/resolve.ts +307 -0
  80. package/src/memory/route.ts +272 -0
  81. package/src/memory/schedule.ts +6 -4
  82. package/src/memory/stages.ts +774 -0
  83. package/src/memory/synthesize.ts +1629 -20
  84. package/src/memory/tools.ts +446 -96
  85. package/src/memory/vault.ts +462 -35
  86. package/src/memory/wikify.ts +1057 -16
  87. package/src/mlx/ffi.ts +11 -0
  88. package/src/mlx/ops.ts +113 -0
  89. package/src/model/compiled-decode.ts +43 -8
  90. package/src/model/diffusion-gemma.ts +1026 -0
  91. package/src/model/factory.ts +35 -8
  92. package/src/model/flash-attention.ts +4 -2
  93. package/src/model/fused-decode-kernel.ts +14 -7
  94. package/src/model/fused-mlp-kernel.ts +169 -0
  95. package/src/model/fused-swiglu-kernel.ts +240 -0
  96. package/src/model/gemma4-base.ts +62 -6
  97. package/src/model/gemma4.ts +33 -2
  98. package/src/model/minicpm5.ts +106 -8
  99. package/src/model/qwen3.ts +276 -0
  100. package/src/model/steel-linear-kernel.ts +96 -0
  101. package/src/model/support.ts +45 -7
  102. package/src/model/universal/archs.ts +332 -0
  103. package/src/model/universal/dense.ts +576 -0
  104. package/src/model/universal/modules.ts +163 -0
  105. package/src/model/universal/rope.ts +366 -0
  106. package/src/pi-provider.ts +1 -1
  107. package/src/pi-terminal.ts +29 -8
  108. package/src/pi-web.ts +19 -2
  109. package/src/quantize/config-writer.ts +1 -1
  110. package/src/registry.ts +215 -7
  111. package/src/responses.ts +23 -0
  112. package/src/sampler.ts +220 -9
  113. package/src/serve/batch-scheduler.ts +272 -80
  114. package/src/serve/generation-gateway.ts +90 -18
  115. package/src/server.ts +643 -50
  116. package/src/spec/drafter.ts +81 -49
  117. package/src/spec/dspark/data-dflash.ts +156 -0
  118. package/src/spec/dspark/data.ts +201 -0
  119. package/src/spec/dspark/generate-dflash.ts +193 -0
  120. package/src/spec/dspark/generate.ts +290 -0
  121. package/src/spec/dspark/loss.ts +213 -0
  122. package/src/spec/dspark/module-dflash.ts +361 -0
  123. package/src/spec/dspark/module.ts +540 -0
  124. package/src/spec/dspark/sample.ts +112 -0
  125. package/src/spec/generate.ts +40 -19
  126. package/src/status-page.html +1 -1
  127. package/src/tokenizer.ts +7 -0
  128. package/src/train/diffusion-lora.ts +216 -0
  129. package/src/train/flash-cce.ts +70 -15
  130. package/src/train/fuse.ts +243 -0
  131. package/src/train/index.ts +3 -0
  132. package/src/train/job.ts +8 -0
  133. package/src/train/loss.ts +289 -30
  134. package/src/train/prefix-shared.ts +33 -5
  135. package/src/train/segmented.ts +67 -11
  136. package/src/train/trainer.ts +92 -28
  137. package/src/vision/diffusion-vision.ts +620 -0
  138. package/src/web/skills/memory/SKILL.md +40 -17
@@ -1,24 +1,351 @@
1
- // mlx-bun memory — synthesis stage 3: CLUSTER. ⚠️ M1 STUB.
1
+ // mlx-bun memory — SECTION-ROUTE (P7-T1): chunk → article sections (M×N binary).
2
2
  //
3
- // Assign each new chunk to an existing bucket or propose a new one (local-model
4
- // call). Buckets are emergent (Meta/Buckets.md), each mapping to a target
5
- // article. Mirrors lucien's cluster-assign-recent.ts.
3
+ // The steady-state counterpart to ROUTE. ROUTE (route.ts) decides WHICH articles
4
+ // a chunk touches; SECTION-ROUTE decides, for each of those articles, WHICH
5
+ // section(s) the chunk should update — the join from a routed chunk to the
6
+ // concrete `[^N]`-patch targets P7-T2 then integrates.
6
7
  //
7
- // See docs/design/memory-system.md → "The nightly pipeline".
8
+ // The shape is M×N binary, repurposed from lucien's `cluster-assign-recent.ts`
9
+ // ASSIGN_OR_PROPOSE_PROMPT + buildPrompt (assign-to-existing-or-propose-new), but
10
+ // decomposed into bounded single-section yes/no calls instead of one batched
11
+ // JSON object — the same capacity-by-decomposition the CREATE flow uses, and the
12
+ // same parseBinary gate ROUTE's disambiguation rides:
13
+ //
14
+ // for each section S of article A (A already matched by ROUTE for this chunk):
15
+ // "article title + S heading + S's first ~2 sentences + chunk label + 1-line
16
+ // gist → Should this chunk update THIS section? yes/no" (parseBinary)
17
+ // if EVERY section said no AND the chunk is substantive for A:
18
+ // "Name a new section (2–5 words) or NONE." (parseLines)
19
+ //
20
+ // Hierarchical pruning is structural: the caller only ever hands us the articles
21
+ // ROUTE matched, so we never run the M×N grid over the whole vault. A chunk that
22
+ // fits no existing section yields a NAMED new section (P7-T2 creates it on patch),
23
+ // never a silent drop.
24
+ //
25
+ // The deterministic scaffolding (TOC iteration, section gists, new-section parse,
26
+ // the ledger write) is pure and unit-tested; only the binary/name calls touch the
27
+ // GPU, behind an injectable `call` seam so tests run model-free.
28
+
29
+ import { parseLead } from "./article";
30
+ import type { MemoryStore } from "./db";
31
+ import { callLocal, MAX_OUTPUT_TOKENS } from "./model";
32
+ import { parseBinary, parseLines } from "./parse";
33
+ import { extractSection, parseToc, slugifyHeading } from "./vault";
34
+
35
+ /** The synthetic anchor for an article's LEAD (its opening summary / verdict).
36
+ * The lead is not a `## heading` section, but it is where an entity's headline
37
+ * claim lives — so it is a first-class PATCH target: a correction that
38
+ * contradicts the verdict (a newer value reversing the lead's stated value)
39
+ * must rewrite the LEAD toward the latest, not leave it standing while only a
40
+ * body section is updated. SECTION-ROUTE offers the lead as a routable
41
+ * candidate; synthesize's patch path swaps exactly the lead bytes. */
42
+ export const LEAD_ANCHOR = "__lead__";
43
+
44
+ // ---- structural tail sections (never chunk-update targets) ------------------
45
+
46
+ /** Headings that are article scaffolding, not topical sections — a chunk never
47
+ * "updates" them, so they are excluded from the routable section set. */
48
+ const NON_TOPICAL_HEADINGS = new Set(["references", "see also", "notes"]);
49
+
50
+ // ---- section enumeration (pure) --------------------------------------------
51
+
52
+ /** One routable section of an article: its anchor, heading, and a short gist
53
+ * (the first ~2 sentences of its body) for the binary prompt. */
54
+ export interface SectionCandidate {
55
+ anchor: string;
56
+ heading: string;
57
+ gist: string;
58
+ }
59
+
60
+ /** Strip a section body down to plain gist prose: drop the heading line, fenced
61
+ * blocks, footnote DEFINITION lines, list/quote markers, footnote MARKERS, and
62
+ * wikilink brackets, then collapse whitespace. Pure. */
63
+ function sectionBodyProse(section: string): string {
64
+ const lines = section.split(/\r?\n/);
65
+ const kept: string[] = [];
66
+ let inFence = false;
67
+ let first = true;
68
+ for (const line of lines) {
69
+ if (/^(```|~~~)/.test(line.trim())) {
70
+ inFence = !inFence;
71
+ continue;
72
+ }
73
+ if (inFence) continue;
74
+ if (first) {
75
+ first = false; // the heading line itself
76
+ continue;
77
+ }
78
+ const t = line.trim();
79
+ if (!t) continue;
80
+ if (/^\[\^[^\]]+\]:/.test(t)) continue; // footnote definition line
81
+ kept.push(t.replace(/^[-*+>]\s+/, "").replace(/^\d+[.)]\s+/, ""));
82
+ }
83
+ return kept
84
+ .join(" ")
85
+ .replace(/\[\^[^\]]+\]/g, "") // footnote markers
86
+ .replace(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g, "$1") // wikilinks → display text
87
+ .replace(/[*_`]/g, "")
88
+ .replace(/\s+/g, " ")
89
+ .trim();
90
+ }
91
+
92
+ /** First `n` sentences of `text` (sentence = run ending in . ! or ?), falling
93
+ * back to a hard character cap so a punctuation-free body still yields a gist. */
94
+ export function firstSentences(text: string, n = 2, cap = 320): string {
95
+ const s = text.trim();
96
+ if (!s) return "";
97
+ const parts = s.split(/(?<=[.!?])\s+/);
98
+ const gist = parts.slice(0, n).join(" ").trim();
99
+ return gist.length > cap ? gist.slice(0, cap).trim() : gist;
100
+ }
101
+
102
+ /**
103
+ * Enumerate an article's routable sections from its markdown: every TOC heading
104
+ * deeper than the H1 title, minus the non-topical tail (References / See also /
105
+ * Notes), each carrying a ~2-sentence gist of its body. Pure — no model, no disk.
106
+ */
107
+ export function articleSections(markdown: string): SectionCandidate[] {
108
+ const out: SectionCandidate[] = [];
109
+ const seen = new Set<string>();
110
+ for (const entry of parseToc(markdown)) {
111
+ if (entry.depth <= 1) continue; // the H1 title is not a section
112
+ if (NON_TOPICAL_HEADINGS.has(entry.title.trim().toLowerCase())) continue;
113
+ if (seen.has(entry.anchor)) continue;
114
+ seen.add(entry.anchor);
115
+ const body = extractSection(markdown, entry.anchor);
116
+ const gist = body ? firstSentences(sectionBodyProse(body)) : "";
117
+ out.push({ anchor: entry.anchor, heading: entry.title, gist });
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /** The article's display title — its H1 if present, else the stem with `_`→space. */
123
+ export function articleTitle(markdown: string, stem: string): string {
124
+ const h1 = parseToc(markdown).find((e) => e.depth === 1);
125
+ return h1 ? h1.title : stem.replace(/_/g, " ");
126
+ }
127
+
128
+ /**
129
+ * The article's LEAD as a routable section candidate (anchor {@link LEAD_ANCHOR}),
130
+ * or null when the article has no lead prose. The gist is the lead's first ~2
131
+ * sentences, footnote/wikilink-stripped — so the binary matcher can decide
132
+ * whether a chunk's claim belongs in (and may CORRECT) the headline summary. Pure.
133
+ */
134
+ export function leadCandidate(markdown: string): SectionCandidate | null {
135
+ const lead = parseLead(markdown);
136
+ if (!lead || !lead.trim()) return null;
137
+ const prose = lead
138
+ .replace(/\[\^[^\]]+\]/g, "") // footnote markers
139
+ .replace(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g, "$1") // wikilinks → display text
140
+ .replace(/[*_`]/g, "")
141
+ .replace(/\s+/g, " ")
142
+ .trim();
143
+ return { anchor: LEAD_ANCHOR, heading: "Lead Summary", gist: firstSentences(prose) };
144
+ }
145
+
146
+ // ---- new-section parse (pure) ----------------------------------------------
147
+
148
+ /**
149
+ * Parse the CREATE-NEW-SECTION reply into a clean 2–5-word section title, or
150
+ * null when the model declined (NONE / empty) or the name is out of range.
151
+ * Strips heading/bullet/quote markup so a stray `## ` or `- ` prefix is tolerated.
152
+ */
153
+ export function parseNewSection(raw: string): { title: string; anchor: string } | null {
154
+ const [line] = parseLines(raw);
155
+ if (!line) return null;
156
+ const title = line
157
+ .replace(/^#{1,6}\s+/, "")
158
+ .replace(/^[-*+>]\s+/, "")
159
+ .replace(/^\d+[.)]\s+/, "")
160
+ .replace(/[`*_]/g, "")
161
+ .replace(/[.:;,]+$/, "")
162
+ .trim();
163
+ if (!title) return null;
164
+ const words = title.split(/\s+/).filter(Boolean);
165
+ if (words.length < 2 || words.length > 5) return null;
166
+ return { title, anchor: slugifyHeading(title) };
167
+ }
8
168
 
9
- import type { SynthesisEvent } from "./pipeline";
169
+ // ---- prompt builders (pure, schematic — no parrot-able example values) ------
10
170
 
11
- export interface ClusterResult {
12
- assigned: number;
13
- newBuckets: number;
171
+ /**
172
+ * Bounded binary: should THIS chunk update THIS section? Kept schematic on
173
+ * purpose — no concrete example the small model could copy into its answer.
174
+ *
175
+ * Framed around the SUBJECT the heading names, NOT a value comparison: the small
176
+ * model otherwise defaults to "no" whenever the note states a different value than
177
+ * the section currently records (a newer value vs the section's older value), which
178
+ * is exactly the correction we must catch. Empirically (e4b, maxTokens 4) this phrasing matches a
179
+ * contradicting same-subject correction 3/3 while still declining off-topic and
180
+ * cross-section notes; the chunk LABEL is deliberately omitted — including it
181
+ * flipped the model back to value-comparison and dropped the match rate.
182
+ */
183
+ export function buildSectionBinaryPrompt(
184
+ title: string,
185
+ section: SectionCandidate,
186
+ chunkGist: string,
187
+ ): string {
188
+ return (
189
+ `Article: "${title}"\n` +
190
+ `Section heading: "${section.heading}"\n` +
191
+ `What this section is about: ${section.gist || "(empty)"}\n\n` +
192
+ `New note: ${chunkGist || "(none)"}\n\n` +
193
+ `A note BELONGS in this section when it is about the SAME subject the heading ` +
194
+ `names — the same preference, attribute, or topic — EVEN IF the note gives a ` +
195
+ `different, newer, or contradicting value than the section currently records ` +
196
+ `(a changed favourite is a correction to THIS section, not a new topic). It ` +
197
+ `does NOT belong only if it is about a clearly different subject. Does the new ` +
198
+ `note belong in the "${section.heading}" section? Answer yes or no.`
199
+ );
14
200
  }
15
201
 
16
- /** Chunks → buckets (local model). STUB. */
17
- export async function clusterChunks(
18
- _model: unknown,
19
- _onEvent?: (e: SynthesisEvent) => void,
20
- ): Promise<ClusterResult> {
21
- // TODO(M1): for each unbucketed chunk, classify into Meta/Buckets.md taxonomy
22
- // (or propose a new bucket → new article stem); persist chunk.bucket.
23
- throw new Error("memory.cluster is not implemented yet (M1)");
202
+ /** CREATE-NEW-SECTION sub-task: name a section for a chunk that fit no existing
203
+ * one, or NONE. Lists the existing headings so the model proposes something new. */
204
+ export function buildNewSectionPrompt(
205
+ title: string,
206
+ existingHeadings: string[],
207
+ chunkLabel: string | null,
208
+ chunkGist: string,
209
+ ): string {
210
+ const existing = existingHeadings.length ? existingHeadings.map((h) => `- ${h}`).join("\n") : "(none)";
211
+ return (
212
+ `Article: "${title}"\n` +
213
+ `Existing sections:\n${existing}\n\n` +
214
+ `New note label: ${chunkLabel ?? "(none)"}\n` +
215
+ `New note gist: ${chunkGist || "(none)"}\n\n` +
216
+ `The new note does not fit any existing section above. If it is substantive ` +
217
+ `enough to deserve its own section of this article, name that NEW section in ` +
218
+ `2 to 5 words (a heading distinct from the ones listed). Otherwise answer NONE. ` +
219
+ `Output only the section name or NONE.`
220
+ );
221
+ }
222
+
223
+ // ---- model seam ------------------------------------------------------------
224
+
225
+ /** Per-call model seam (defaults to the local `section` stage). Injected by
226
+ * tests + the eval so the deterministic scaffolding runs with no GPU. */
227
+ export type SectionCall = (prompt: string, opts?: { maxTokens?: number }) => Promise<string>;
228
+
229
+ const defaultCall: SectionCall = (p, o) => callLocal("section", { user: p }, o);
230
+
231
+ // ---- routing inputs / outputs ----------------------------------------------
232
+
233
+ /** The chunk side of section routing: its id, label, and a 1-line gist. */
234
+ export interface SectionRouteChunk {
235
+ id: string;
236
+ label: string | null;
237
+ /** A short, 1-line gist of the chunk's content (caller derives it). */
238
+ gist: string;
239
+ }
240
+
241
+ /** The article side: its stem and current markdown (TOC + section bodies). */
242
+ export interface SectionRouteArticle {
243
+ stem: string;
244
+ content: string;
245
+ }
246
+
247
+ export interface SectionRouteResult {
248
+ stem: string;
249
+ /** Existing-section anchors the chunk should update (the patch targets). */
250
+ matchedAnchors: string[];
251
+ /** A newly-named section when no existing section fit AND the chunk is
252
+ * substantive for this article; null when it fit something or the model
253
+ * declined to name one. */
254
+ newSection: { title: string; anchor: string } | null;
255
+ }
256
+
257
+ export interface SectionRouteOpts {
258
+ /** Model-call override (tests/eval inject a fake). */
259
+ call?: SectionCall;
260
+ /** Whether the chunk is substantive for THIS article (gates the new-section
261
+ * sub-task on an all-no result). ROUTE already vouched the chunk is about the
262
+ * article, so this defaults to true. */
263
+ substantive?: boolean;
264
+ }
265
+
266
+ /**
267
+ * Route ONE chunk against ONE (ROUTE-matched) article's sections. Runs the M×N
268
+ * grid's N binary calls for this article; if every section says no and the chunk
269
+ * is substantive, runs the CREATE-NEW-SECTION sub-task. Returns the matched
270
+ * existing anchors and/or a named new section. Pure w.r.t. disk.
271
+ */
272
+ export async function routeSections(
273
+ chunk: SectionRouteChunk,
274
+ article: SectionRouteArticle,
275
+ opts: SectionRouteOpts = {},
276
+ ): Promise<SectionRouteResult> {
277
+ const call = opts.call ?? defaultCall;
278
+ const substantive = opts.substantive ?? true;
279
+ const title = articleTitle(article.content, article.stem);
280
+ const sections = articleSections(article.content);
281
+
282
+ // The LEAD is a routable target too: a correction that contradicts the
283
+ // headline claim must be able to rewrite the verdict, not just a body section.
284
+ const lead = leadCandidate(article.content);
285
+ const candidates = lead ? [lead, ...sections] : sections;
286
+
287
+ const matchedAnchors: string[] = [];
288
+ for (const section of candidates) {
289
+ const yes = parseBinary(
290
+ await call(buildSectionBinaryPrompt(title, section, chunk.gist), { maxTokens: MAX_OUTPUT_TOKENS }),
291
+ );
292
+ if (yes) matchedAnchors.push(section.anchor);
293
+ }
294
+
295
+ let newSection: { title: string; anchor: string } | null = null;
296
+ if (matchedAnchors.length === 0 && substantive) {
297
+ const raw = await call(
298
+ buildNewSectionPrompt(title, sections.map((s) => s.heading), chunk.label, chunk.gist),
299
+ { maxTokens: MAX_OUTPUT_TOKENS },
300
+ );
301
+ const named = parseNewSection(raw);
302
+ // Guard against the model echoing an existing heading as its "new" name.
303
+ if (named && !sections.some((s) => s.anchor === named.anchor)) newSection = named;
304
+ }
305
+
306
+ return { stem: article.stem, matchedAnchors, newSection };
307
+ }
308
+
309
+ /**
310
+ * SECTION-ROUTE a chunk across the articles ROUTE matched for it — the hierarchical
311
+ * pruning is exactly this: callers pass ONLY the matched articles, so the M×N grid
312
+ * is bounded to (matched articles × their sections), never the whole vault.
313
+ */
314
+ export async function routeChunkSections(
315
+ chunk: SectionRouteChunk,
316
+ routeMatchedArticles: SectionRouteArticle[],
317
+ opts: SectionRouteOpts = {},
318
+ ): Promise<SectionRouteResult[]> {
319
+ const out: SectionRouteResult[] = [];
320
+ for (const article of routeMatchedArticles) {
321
+ out.push(await routeSections(chunk, article, opts));
322
+ }
323
+ return out;
324
+ }
325
+
326
+ // ---- ledger write ----------------------------------------------------------
327
+
328
+ /**
329
+ * Persist a chunk's section routes to `chunk_sections` (the routing ledger P7-T2
330
+ * patches from). Existing-section matches write their anchor; a named new section
331
+ * writes its slug (the section P7-T2 will create). Idempotent via the table PK.
332
+ * Returns the number of rows inserted (excluding PK collisions).
333
+ */
334
+ export function persistSectionRoutes(
335
+ store: MemoryStore,
336
+ chunkId: string,
337
+ results: SectionRouteResult[],
338
+ ): number {
339
+ const ins = store.db.query(
340
+ "INSERT OR IGNORE INTO chunk_sections (chunk_id, article_stem, section_anchor) VALUES (?, ?, ?)",
341
+ );
342
+ let rows = 0;
343
+ const tx = store.db.transaction(() => {
344
+ for (const r of results) {
345
+ for (const anchor of r.matchedAnchors) rows += ins.run(chunkId, r.stem, anchor).changes;
346
+ if (r.newSection) rows += ins.run(chunkId, r.stem, r.newSection.anchor).changes;
347
+ }
348
+ });
349
+ tx();
350
+ return rows;
24
351
  }
@@ -0,0 +1,134 @@
1
+ // P9-T4 — migration parity / coverage.
2
+ //
3
+ // The migration thesis: synthesizing the old Lucien topic-bin vault (385 bins)
4
+ // into sharp entity articles DROPS article count, but must LOSE ZERO
5
+ // engaged-with things. This module is the proof harness: every notable entity
6
+ // in the hand-curated gold (`goldens/dreaming-entities-gold.json`
7
+ // notableEntities — owned/decided/recurring/opinion, NOT the bucket taxonomy
8
+ // we replace) must resolve to an article (or alias) in the new vault.
9
+ //
10
+ // Pure read-path: reindex (file I/O) + alias resolution. No model load, no
11
+ // embedder — the read-path tripwire (`src/embed.ts` counter) stays 0.
12
+
13
+ import { readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ import type { MemoryStore } from "./db";
17
+ import { resolveName } from "./reindex";
18
+ import { articlesDir } from "./vault";
19
+
20
+ /** A hand-curated notable entity (the personal-notability oracle). */
21
+ export interface NotableEntity {
22
+ name: string;
23
+ kind: string;
24
+ domain: string;
25
+ aliases: string[];
26
+ whyNotable: string;
27
+ }
28
+
29
+ /** The shape of `goldens/dreaming-entities-gold.json` (the slice we read). */
30
+ export interface EntitiesGold {
31
+ notableEntities: NotableEntity[];
32
+ }
33
+
34
+ /** Per-entity coverage verdict. */
35
+ export interface CoverageRow {
36
+ /** Canonical gold name. */
37
+ name: string;
38
+ domain: string;
39
+ /** True when the name or any alias resolves to an article stem. */
40
+ covered: boolean;
41
+ /** The resolved article stem, or null when missing. */
42
+ stem: string | null;
43
+ /** The surface form (name/alias) that resolved, or null. */
44
+ matchedVia: string | null;
45
+ /** Covered, but the target article body is below the stub threshold. */
46
+ stub: boolean;
47
+ }
48
+
49
+ export interface CoverageReport {
50
+ goldNotable: number;
51
+ coveredCount: number;
52
+ missingCount: number;
53
+ stubCount: number;
54
+ covered: CoverageRow[];
55
+ missing: CoverageRow[];
56
+ stubs: CoverageRow[];
57
+ rows: CoverageRow[];
58
+ }
59
+
60
+ /** Below this many chars of prose (infobox + headings stripped) an article is
61
+ * flagged a stub: present but not yet a real article. Informational. */
62
+ export const STUB_PROSE_CHARS = 300;
63
+
64
+ /** Prose length of an article body, excluding the ```info fence and headings —
65
+ * the signal for "is this a real article or a placeholder?". */
66
+ function prosePulse(root: string, stem: string): number {
67
+ let content: string;
68
+ try {
69
+ content = readFileSync(join(articlesDir(root), `${stem}.md`), "utf8");
70
+ } catch {
71
+ return 0;
72
+ }
73
+ const withoutInfo = content.replace(/```info[\s\S]*?```/g, "");
74
+ const prose = withoutInfo
75
+ .split(/\r?\n/)
76
+ .filter((line) => !/^\s*#/.test(line)) // drop headings
77
+ .join("\n")
78
+ .trim();
79
+ return prose.length;
80
+ }
81
+
82
+ /** Resolve one notable entity against the vault: try the canonical name first,
83
+ * then each alias. Returns the first hit (stem + the surface that matched). */
84
+ function resolveEntity(
85
+ store: MemoryStore,
86
+ entity: NotableEntity,
87
+ ): { stem: string; via: string } | null {
88
+ for (const surface of [entity.name, ...entity.aliases]) {
89
+ const stem = resolveName(store, surface);
90
+ if (stem) return { stem, via: surface };
91
+ }
92
+ return null;
93
+ }
94
+
95
+ /**
96
+ * Coverage report for the notable-entity gold against a (reindexed) vault.
97
+ * `store` MUST already be reindexed from `root` (the caller owns the load).
98
+ */
99
+ export function coverageReport(
100
+ store: MemoryStore,
101
+ notable: NotableEntity[],
102
+ root: string,
103
+ ): CoverageReport {
104
+ const rows: CoverageRow[] = notable.map((entity) => {
105
+ const hit = resolveEntity(store, entity);
106
+ if (!hit) {
107
+ return { name: entity.name, domain: entity.domain, covered: false, stem: null, matchedVia: null, stub: false };
108
+ }
109
+ const stub = prosePulse(root, hit.stem) < STUB_PROSE_CHARS;
110
+ return {
111
+ name: entity.name,
112
+ domain: entity.domain,
113
+ covered: true,
114
+ stem: hit.stem,
115
+ matchedVia: hit.via,
116
+ stub,
117
+ };
118
+ });
119
+
120
+ const covered = rows.filter((r) => r.covered);
121
+ const missing = rows.filter((r) => !r.covered);
122
+ const stubs = covered.filter((r) => r.stub);
123
+
124
+ return {
125
+ goldNotable: notable.length,
126
+ coveredCount: covered.length,
127
+ missingCount: missing.length,
128
+ stubCount: stubs.length,
129
+ covered,
130
+ missing,
131
+ stubs,
132
+ rows,
133
+ };
134
+ }
Binary file