mlx-bun 0.0.8 → 0.0.10

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 (144) hide show
  1. package/README.md +112 -20
  2. package/docs/design/batching-perf-path.md +232 -0
  3. package/docs/design/batching-v2-plan.md +515 -0
  4. package/docs/design/bucketing-stage.md +196 -0
  5. package/docs/design/compat-cli-surface-design.md +11 -11
  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/omlx-adoption-map.md +90 -0
  15. package/docs/design/orpo-dynamic-lambda.md +41 -0
  16. package/docs/design/orpo-training.md +35 -5
  17. package/docs/design/parallel-slots.md +12 -1
  18. package/docs/design/parity-tier-dag.md +13 -5
  19. package/docs/design/segmented-backward-training.md +15 -0
  20. package/docs/design/spec-decode-larger-targets.md +229 -0
  21. package/docs/design/ssd-kv-cold-tier.md +158 -0
  22. package/docs/design/tauri-desktop-app.md +2 -2
  23. package/docs/design/the-dreaming-handoff.md +141 -0
  24. package/docs/design/the-dreaming-master-plan.md +446 -0
  25. package/docs/design/write-pipeline-entity.md +468 -0
  26. package/docs/investigations/curve-bisector-routing.md +1 -1
  27. package/docs/investigations/decode-roofline-lookagain.md +348 -0
  28. package/docs/investigations/dspark-handoff.md +58 -0
  29. package/docs/investigations/kernel-perf-review-2026-07.md +171 -0
  30. package/docs/planning/PRODUCT_ROADMAP.md +2 -2
  31. package/docs/planning/curve-sampler-research-plan.md +331 -0
  32. package/docs/planning/memory-docs-and-dag-plan.md +185 -0
  33. package/docs/planning/pi-integration-review.md +178 -0
  34. package/docs/planning/release-notes-v0.0.10.md +57 -0
  35. package/docs/planning/release-notes-v0.0.9.md +122 -0
  36. package/docs/planning/web-ui-pass-plan.md +213 -0
  37. package/docs/planning/website-readme-pass-plan.md +224 -0
  38. package/docs/reference/cli.md +255 -0
  39. package/docs/reference/embedding.md +7 -2
  40. package/docs/reference/library-api.md +22 -3
  41. package/docs/reference/memory.md +5 -5
  42. package/docs/reference/models.md +137 -0
  43. package/docs/reference/orpo-quickstart.md +6 -0
  44. package/docs/reference/server-api.md +187 -9
  45. package/docs/reference/server-config.md +43 -9
  46. package/docs/reference/training.md +31 -12
  47. package/package.json +1 -1
  48. package/src/anthropic.ts +22 -0
  49. package/src/assets/curve-designer.html +1 -1
  50. package/src/chat-template.ts +25 -7
  51. package/src/cli.ts +1077 -90
  52. package/src/config.ts +4 -1
  53. package/src/download.ts +99 -8
  54. package/src/embed.ts +77 -0
  55. package/src/eval/perplexity.ts +164 -0
  56. package/src/eval/runner.ts +15 -6
  57. package/src/eval/tasks/bfcl.ts +1 -1
  58. package/src/generate.ts +149 -18
  59. package/src/harness-pi.ts +43 -17
  60. package/src/index.ts +2 -0
  61. package/src/kv-store.ts +240 -98
  62. package/src/lora.ts +2 -2
  63. package/src/memory/article.ts +558 -0
  64. package/src/memory/chunk-validation.ts +150 -0
  65. package/src/memory/chunk.ts +305 -12
  66. package/src/memory/cluster.ts +344 -17
  67. package/src/memory/coverage.ts +134 -0
  68. package/src/memory/crosslink.ts +0 -0
  69. package/src/memory/db.ts +184 -45
  70. package/src/memory/entity.ts +203 -0
  71. package/src/memory/gate.ts +187 -0
  72. package/src/memory/history.ts +152 -0
  73. package/src/memory/ingest.ts +324 -11
  74. package/src/memory/model.ts +321 -0
  75. package/src/memory/normalize.ts +671 -0
  76. package/src/memory/parse.ts +22 -0
  77. package/src/memory/pipeline.ts +242 -30
  78. package/src/memory/prompts.ts +42 -0
  79. package/src/memory/query.ts +334 -0
  80. package/src/memory/reconcile.ts +734 -0
  81. package/src/memory/redirect.ts +108 -0
  82. package/src/memory/reindex.ts +325 -0
  83. package/src/memory/resolve.ts +307 -0
  84. package/src/memory/route.ts +272 -0
  85. package/src/memory/schedule.ts +6 -4
  86. package/src/memory/stages.ts +774 -0
  87. package/src/memory/synthesize.ts +1629 -20
  88. package/src/memory/tools.ts +446 -96
  89. package/src/memory/vault.ts +462 -35
  90. package/src/memory/wikify.ts +1057 -16
  91. package/src/mlx/array.ts +21 -0
  92. package/src/mlx/ffi.ts +3 -0
  93. package/src/mlx/ops.ts +72 -0
  94. package/src/model/compiled-decode.ts +43 -8
  95. package/src/model/factory.ts +29 -8
  96. package/src/model/flash-attention.ts +4 -2
  97. package/src/model/fused-decode-kernel.ts +14 -7
  98. package/src/model/fused-mlp-kernel.ts +169 -0
  99. package/src/model/fused-swiglu-kernel.ts +240 -0
  100. package/src/model/gemma4-base.ts +96 -7
  101. package/src/model/gemma4.ts +33 -2
  102. package/src/model/minicpm5.ts +106 -8
  103. package/src/model/qwen3-delta.ts +48 -1
  104. package/src/model/qwen3.ts +276 -0
  105. package/src/model/qwen3_5.ts +11 -2
  106. package/src/model/steel-linear-kernel.ts +96 -0
  107. package/src/model/support.ts +38 -8
  108. package/src/model/universal/archs.ts +332 -0
  109. package/src/model/universal/dense.ts +576 -0
  110. package/src/model/universal/modules.ts +163 -0
  111. package/src/model/universal/rope.ts +366 -0
  112. package/src/pi-provider.ts +1 -1
  113. package/src/pi-terminal.ts +29 -8
  114. package/src/pi-web.ts +19 -2
  115. package/src/prompt-cache.ts +55 -9
  116. package/src/quantize/config-writer.ts +1 -1
  117. package/src/registry.ts +219 -8
  118. package/src/responses.ts +23 -0
  119. package/src/sampler.ts +220 -9
  120. package/src/serve/batch-scheduler.ts +307 -83
  121. package/src/serve/generation-gateway.ts +156 -29
  122. package/src/server.ts +746 -73
  123. package/src/spec/drafter.ts +81 -49
  124. package/src/spec/dspark/data-dflash.ts +156 -0
  125. package/src/spec/dspark/data.ts +201 -0
  126. package/src/spec/dspark/generate-dflash.ts +193 -0
  127. package/src/spec/dspark/generate.ts +290 -0
  128. package/src/spec/dspark/loss.ts +213 -0
  129. package/src/spec/dspark/module-dflash.ts +361 -0
  130. package/src/spec/dspark/module.ts +540 -0
  131. package/src/spec/dspark/sample.ts +112 -0
  132. package/src/spec/generate.ts +40 -19
  133. package/src/ssd-cache.ts +213 -0
  134. package/src/status-page.html +1 -1
  135. package/src/tokenizer.ts +7 -0
  136. package/src/train/flash-cce.ts +81 -23
  137. package/src/train/fuse.ts +243 -0
  138. package/src/train/index.ts +3 -0
  139. package/src/train/job.ts +8 -0
  140. package/src/train/loss.ts +341 -40
  141. package/src/train/prefix-shared.ts +62 -11
  142. package/src/train/segmented.ts +215 -55
  143. package/src/train/trainer.ts +112 -38
  144. package/src/web/skills/memory/SKILL.md +40 -17
@@ -0,0 +1,774 @@
1
+ // mlx-bun memory — "The Dreaming" STAGE WORKERS (pipeline decomposition).
2
+ //
3
+ // The monolithic runPipeline (segment-ALL → extract-ALL → route → create, one
4
+ // blocking call) is decomposed here into four INDEPENDENT, DB-state-keyed stage
5
+ // workers — exactly the split Lucien made between chunk-recent / cluster-assign /
6
+ // synthesize. Each worker:
7
+ // • pulls its eligible work from the DB *by state* (a watermark / the absence
8
+ // of a downstream row), so it is RESUMABLE — an interrupted run continues;
9
+ // • processes a bounded batch and PERSISTS, so two of them can run as separate
10
+ // concurrent processes on different slices;
11
+ // • is individually runnable (`mlx-bun memory segment|extract|route|synthesize`).
12
+ //
13
+ // CHRONOLOGY IS LOAD-BEARING. Every stage walks oldest-conversation-first
14
+ // (conversations.updated_at ASC, then intra-conversation chunks.start ASC).
15
+ // `messages` carry only a position, so conv-level updated_at + start is the
16
+ // chronological key. This is what makes self-healing correct: the synthesis chunk
17
+ // feed for an entity is chronological, so the user's LATEST statement dominates a
18
+ // contradicted claim — never "whichever conversation UUID sorts last wins" (the
19
+ // old ORDER BY chunk-id == conv-UUID, which is random w.r.t. time).
20
+ //
21
+ // runPipeline (pipeline.ts) now simply drives these four in sequence, so the full
22
+ // DAG and the existing tests still pass.
23
+
24
+ import { toEntityKind, type EntityKind } from "./article";
25
+ import { chunkConversations, type ChunkCall, type ChunkResult } from "./chunk";
26
+ import {
27
+ firstSentences,
28
+ routeSections,
29
+ type SectionCall,
30
+ type SectionRouteArticle,
31
+ type SectionRouteChunk,
32
+ } from "./cluster";
33
+ import type { MemoryStore } from "./db";
34
+ import { buildEntityPrompt, extractEntities, type ExtractCall } from "./entity";
35
+ import { callLocalBatch, MAX_OUTPUT_TOKENS } from "./model";
36
+ import type { SynthesisEvent } from "./pipeline";
37
+ import { loadMetaPolicy } from "./prompts";
38
+ import {
39
+ EntityResolver,
40
+ goldSeeds,
41
+ loadDreamingGold,
42
+ type DreamingGold,
43
+ } from "./resolve";
44
+ import {
45
+ RouteAccumulator,
46
+ engagesAsSubject,
47
+ CAPTURED_BUCKET,
48
+ type CreateStats,
49
+ type RouteAction,
50
+ } from "./route";
51
+ import { reconcileArticle } from "./reconcile";
52
+ import { registerRedirect, relatedArticleStem } from "./redirect";
53
+ import {
54
+ entityStem,
55
+ synthesizeCreate,
56
+ synthesizeNewSection,
57
+ synthesizePatch,
58
+ type SynthesisCall,
59
+ } from "./synthesize";
60
+ import { commitVault, listArticles, readArticle, vaultRoot } from "./vault";
61
+
62
+ /** Default CREATE cap per synthesize pass (bounds a run's GPU cost). */
63
+ export const DEFAULT_ARTICLE_CAP = 20;
64
+
65
+ // ---- chronological selectors (shared) --------------------------------------
66
+
67
+ /**
68
+ * Every chunk id in CHRONOLOGICAL order — conversations.updated_at ASC, then
69
+ * chunks.start ASC — optionally restricted to `convIds`. Also returns the
70
+ * distinct conversation count. This replaces the old `ORDER BY chunks.id` (chunk
71
+ * id == conv UUID, which sorts RANDOMLY w.r.t. time).
72
+ */
73
+ export function chronoChunkIds(
74
+ store: MemoryStore,
75
+ convIds?: string[],
76
+ ): { convs: number; chunkIds: string[] } {
77
+ const base =
78
+ "SELECT chunks.id AS id, chunks.conv AS conv FROM chunks " +
79
+ "JOIN conversations c ON c.conv = chunks.conv";
80
+ const order = " ORDER BY c.updated_at ASC, chunks.start ASC";
81
+ let rows: { id: string; conv: string }[];
82
+ if (convIds && convIds.length) {
83
+ const ph = convIds.map(() => "?").join(",");
84
+ rows = store.db.query(`${base} WHERE chunks.conv IN (${ph})${order}`).all(...convIds) as {
85
+ id: string;
86
+ conv: string;
87
+ }[];
88
+ } else {
89
+ rows = store.db.query(`${base}${order}`).all() as { id: string; conv: string }[];
90
+ }
91
+ return { convs: new Set(rows.map((r) => r.conv)).size, chunkIds: rows.map((r) => r.id) };
92
+ }
93
+
94
+ /**
95
+ * Routed chunk ids for ONE entity in CHRONOLOGICAL order (conv.updated_at ASC,
96
+ * chunks.start ASC), optionally restricted to a run's chunk set. The synthesis
97
+ * feed rides this order so the latest statement dominates.
98
+ */
99
+ export function entityChunkIdsChrono(
100
+ store: MemoryStore,
101
+ entity: string,
102
+ runChunks?: Set<string>,
103
+ ): string[] {
104
+ const rows = store.db
105
+ .query(
106
+ "SELECT ce.chunk_id AS id FROM chunk_entities ce " +
107
+ "JOIN chunks ch ON ch.id = ce.chunk_id " +
108
+ "JOIN conversations c ON c.conv = ch.conv " +
109
+ "WHERE ce.entity_name = ? ORDER BY c.updated_at ASC, ch.start ASC",
110
+ )
111
+ .all(entity) as { id: string }[];
112
+ const ids = rows.map((r) => r.id);
113
+ return runChunks ? ids.filter((id) => runChunks.has(id)) : ids;
114
+ }
115
+
116
+ /** The earliest source-conversation updated_at across an entity's in-scope
117
+ * chunks — the chronological sort key for ordering entities oldest-first. */
118
+ function entityEarliestAt(store: MemoryStore, entity: string, runChunks?: Set<string>): number {
119
+ const ids = entityChunkIdsChrono(store, entity, runChunks);
120
+ if (ids.length === 0) return Number.POSITIVE_INFINITY;
121
+ const row = store.db
122
+ .query(
123
+ "SELECT c.updated_at AS at FROM chunks ch JOIN conversations c ON c.conv = ch.conv WHERE ch.id = ?",
124
+ )
125
+ .get(ids[0]!) as { at: number | null } | null;
126
+ return row?.at ?? Number.POSITIVE_INFINITY;
127
+ }
128
+
129
+ /** A chunk's label (the SECTION-ROUTE note label), or null. */
130
+ function chunkLabel(store: MemoryStore, chunkId: string): string | null {
131
+ const row = store.db.query("SELECT label FROM chunks WHERE id = ?").get(chunkId) as
132
+ | { label: string | null }
133
+ | null;
134
+ return row?.label ?? null;
135
+ }
136
+
137
+ /** `loadMetaPolicy` that never throws — a missing Meta page yields "" so a
138
+ * fixture/smoke vault without seeded Meta still runs. */
139
+ function loadMetaPolicyQuiet(names: string[]): string {
140
+ try {
141
+ return loadMetaPolicy(names);
142
+ } catch {
143
+ return "";
144
+ }
145
+ }
146
+
147
+ // ---- gold-derived entity metadata (kind + aliases) -------------------------
148
+
149
+ /** Map every gold canonical → its declared kind + alias set, so a created
150
+ * article carries the right `kind:` and seeds its `aliases:`. Non-gold entities
151
+ * default to `thing`. (Lives here so the synthesize stage can stand alone.) */
152
+ export interface EntityMeta {
153
+ kindByCanonical: Map<string, EntityKind>;
154
+ aliasesByCanonical: Map<string, string[]>;
155
+ }
156
+
157
+ export function buildEntityMeta(gold: DreamingGold = loadDreamingGold()): EntityMeta {
158
+ const kindByCanonical = new Map<string, EntityKind>();
159
+ const aliasesByCanonical = new Map<string, string[]>();
160
+ const addAliases = (canonical: string, aliases: string[]): void => {
161
+ const set = new Set(aliasesByCanonical.get(canonical) ?? []);
162
+ for (const a of aliases) set.add(a);
163
+ aliasesByCanonical.set(canonical, [...set]);
164
+ };
165
+ for (const g of gold.variantGroups) {
166
+ if (!kindByCanonical.has(g.canonical)) kindByCanonical.set(g.canonical, toEntityKind(g.kind));
167
+ addAliases(g.canonical, g.variants);
168
+ }
169
+ for (const n of gold.notableEntities) {
170
+ if (!kindByCanonical.has(n.name)) kindByCanonical.set(n.name, toEntityKind(n.kind));
171
+ addAliases(n.name, n.aliases);
172
+ }
173
+ return { kindByCanonical, aliasesByCanonical };
174
+ }
175
+
176
+ // ---- CREATE-target selection (pure) ----------------------------------------
177
+
178
+ export interface RouteDecision {
179
+ entity: string;
180
+ action: RouteAction;
181
+ stats: CreateStats;
182
+ }
183
+
184
+ /**
185
+ * Pick which `create` decisions actually become articles this run: rank by
186
+ * routed-chunk count (then name) and cap, but ALWAYS keep the `mustInclude`
187
+ * entities when they earned a `create`. Pure. Retained for callers/tests that
188
+ * want the routed-count ranking; the chronological synthesize stage orders by
189
+ * earliest-chunk time instead.
190
+ */
191
+ export function selectCreateTargets(
192
+ decisions: RouteDecision[],
193
+ cap: number,
194
+ mustInclude: Iterable<string> = [],
195
+ ): string[] {
196
+ const creatable = decisions.filter((d) => d.action === "create");
197
+ const byEntity = new Map(creatable.map((d) => [d.entity, d]));
198
+ const must = [...mustInclude].filter((e) => byEntity.has(e));
199
+ const ranked = creatable
200
+ .slice()
201
+ .sort((a, b) => b.stats.routedChunks - a.stats.routedChunks || a.entity.localeCompare(b.entity))
202
+ .map((d) => d.entity);
203
+ const out: string[] = [];
204
+ const seen = new Set<string>();
205
+ for (const e of [...must, ...ranked]) {
206
+ if (seen.has(e)) continue;
207
+ seen.add(e);
208
+ out.push(e);
209
+ if (out.length >= cap) break;
210
+ }
211
+ return out;
212
+ }
213
+
214
+ // ---- result shapes (shared with pipeline.ts) -------------------------------
215
+
216
+ export interface PipelineCreated {
217
+ stem: string;
218
+ hasInfobox: boolean;
219
+ citedSections: number;
220
+ chunkEdges: number;
221
+ }
222
+
223
+ export interface PipelinePatched {
224
+ stem: string;
225
+ anchor: string;
226
+ chunkId: string;
227
+ footnote: number | null;
228
+ }
229
+
230
+ // ===========================================================================
231
+ // STAGE 1 — SEGMENT
232
+ // ===========================================================================
233
+
234
+ export interface SegmentStageOptions {
235
+ /** Restrict to these conversation ids (default: every eligible conversation). */
236
+ convIds?: string[];
237
+ /** Cap the number of conversations (re)segmented this pass. */
238
+ limit?: number;
239
+ /** Generation budget per conversation. */
240
+ maxTokens?: number;
241
+ /** Model-call seam (default `callLocal("chunk", …)`). Tests inject a fake. */
242
+ call?: ChunkCall;
243
+ onEvent?: (e: SynthesisEvent) => void;
244
+ }
245
+
246
+ /**
247
+ * SEGMENT — (re)chunk every conversation whose `chunked_at` is NULL or stale
248
+ * (`updated_at > chunked_at`), oldest-first, DELETE+rewrite per conv with OUR
249
+ * adapter, and set `chunked_at`. Resumable by the watermark (a re-run is a
250
+ * no-op). This is a thin, named wrapper over `chunkConversations` so SEGMENT is
251
+ * an independently-runnable worker.
252
+ */
253
+ export async function runSegmentStage(
254
+ store: MemoryStore,
255
+ opts: SegmentStageOptions = {},
256
+ ): Promise<ChunkResult> {
257
+ const result = await chunkConversations(
258
+ store,
259
+ { convs: opts.convIds, limit: opts.limit, maxTokens: opts.maxTokens, call: opts.call },
260
+ opts.onEvent,
261
+ );
262
+ opts.onEvent?.({
263
+ type: "stage",
264
+ stage: "segment",
265
+ message: `segment: ${result.valid} conversation(s) segmented, ${result.chunks} chunk(s) written (${result.skipped} skipped, ${result.errored} errored)`,
266
+ });
267
+ return result;
268
+ }
269
+
270
+ // ===========================================================================
271
+ // STAGE 2 — ENTITY-EXTRACT
272
+ // ===========================================================================
273
+
274
+ export interface ExtractStageOptions {
275
+ /** Restrict to these conversation ids (default: all). */
276
+ convIds?: string[];
277
+ /** Cap the number of chunks extracted this pass (default: all pending). */
278
+ limit?: number;
279
+ /** Pre-rendered Entities policy (cached across passes); default loads it. */
280
+ policy?: string;
281
+ /** Model-call seam (default the local `entity` stage). Tests inject a fake. */
282
+ call?: ExtractCall;
283
+ onEvent?: (e: SynthesisEvent) => void;
284
+ }
285
+
286
+ export interface ExtractStageResult {
287
+ /** Chunks extracted this pass. */
288
+ extracted: number;
289
+ /** Pending chunks still un-extracted after the cap (0 ⇒ stage drained). */
290
+ remaining: number;
291
+ }
292
+
293
+ /** Chunks that have NO `chunk_entities` row yet, CHRONOLOGICAL — the extract
294
+ * work queue (state-keyed: presence of a downstream row ⇒ done). */
295
+ function pendingExtractChunkIds(store: MemoryStore, convIds?: string[]): string[] {
296
+ const base =
297
+ "SELECT chunks.id AS id FROM chunks JOIN conversations c ON c.conv = chunks.conv " +
298
+ "WHERE NOT EXISTS (SELECT 1 FROM chunk_entities ce WHERE ce.chunk_id = chunks.id)";
299
+ const order = " ORDER BY c.updated_at ASC, chunks.start ASC";
300
+ if (convIds && convIds.length) {
301
+ const ph = convIds.map(() => "?").join(",");
302
+ return (store.db.query(`${base} AND chunks.conv IN (${ph})${order}`).all(...convIds) as {
303
+ id: string;
304
+ }[]).map((r) => r.id);
305
+ }
306
+ return (store.db.query(`${base}${order}`).all() as { id: string }[]).map((r) => r.id);
307
+ }
308
+
309
+ /**
310
+ * ENTITY-EXTRACT — read each not-yet-extracted chunk (CHRONOLOGICAL: oldest
311
+ * conversation first, then by position) and persist the entities it is about via
312
+ * the store-seeded + gold-seeded resolver, so canonicals fold across the pass.
313
+ * Resumable: a chunk with `chunk_entities` rows is skipped. Returns how many were
314
+ * extracted and how many remain (so a bounded pass can be repeated to drain).
315
+ */
316
+ export async function runExtractStage(
317
+ store: MemoryStore,
318
+ opts: ExtractStageOptions = {},
319
+ ): Promise<ExtractStageResult> {
320
+ const policy = opts.policy ?? loadMetaPolicyQuiet(["Entities"]);
321
+ const resolver = EntityResolver.fromStore(store);
322
+ for (const s of goldSeeds()) resolver.register(s.canonical, s.aliases);
323
+
324
+ const pending = pendingExtractChunkIds(store, opts.convIds);
325
+ const cap = opts.limit ?? pending.length;
326
+ const target = Math.min(cap, pending.length);
327
+ opts.onEvent?.({
328
+ type: "stage",
329
+ stage: "extract",
330
+ message: `extract: ${target} of ${pending.length} pending chunk(s) for the entities they are about`,
331
+ });
332
+
333
+ const targetIds = pending.slice(0, target);
334
+
335
+ // BATCHED model path (the prime uniform-prompt win: one 128-tok call per chunk,
336
+ // independent). Only when no `call` is injected (tests inject a string-matching
337
+ // fake → keep the serial seam) — callLocalBatch itself falls back to a serial
338
+ // bit-exact loop when batching is disabled, so this stays correct either way.
339
+ // The model calls run in a batch; PARSE + RESOLVE + PERSIST stay sequential so
340
+ // the shared resolver folds canonicals in chronological order.
341
+ if (!opts.call && targetIds.length > 1) {
342
+ const inputs = targetIds.map((id) => ({ user: buildEntityPrompt(store.chunkText(id), policy) }));
343
+ const outputs = await callLocalBatch("entity", inputs, { maxTokens: MAX_OUTPUT_TOKENS });
344
+ let extracted = 0;
345
+ for (let i = 0; i < targetIds.length; i++) {
346
+ const out = outputs[i] ?? "";
347
+ await extractEntities(store, targetIds[i]!, { resolver, policy, call: async () => out });
348
+ extracted++;
349
+ if (extracted % 10 === 0) {
350
+ opts.onEvent?.({ type: "log", message: ` extracted ${extracted}/${target} chunks` });
351
+ }
352
+ }
353
+ return { extracted, remaining: pending.length - extracted };
354
+ }
355
+
356
+ // SERIAL fallback (injected `call`, single chunk, or batching disabled).
357
+ let extracted = 0;
358
+ for (const id of targetIds) {
359
+ await extractEntities(store, id, { resolver, policy: policy || undefined, call: opts.call });
360
+ extracted++;
361
+ if (extracted % 10 === 0) {
362
+ opts.onEvent?.({ type: "log", message: ` extracted ${extracted}/${target} chunks` });
363
+ }
364
+ }
365
+ return { extracted, remaining: pending.length - extracted };
366
+ }
367
+
368
+ // ===========================================================================
369
+ // STAGE 3 — ROUTE
370
+ // ===========================================================================
371
+
372
+ export interface RouteStageOptions {
373
+ /** Restrict the routed chunk set to these conversation ids (default: all). */
374
+ convIds?: string[];
375
+ /** Run the subject-engagement model gate to promote a thin (single-chunk)
376
+ * genuine-subject candidate to a `create` stub. Off by default (a recurring
377
+ * subject already creates without it). */
378
+ useSubjectGate?: boolean;
379
+ onEvent?: (e: SynthesisEvent) => void;
380
+ }
381
+
382
+ export interface RouteStageResult {
383
+ /** Per-entity create/capture/routed decisions (name-sorted). */
384
+ decisions: RouteDecision[];
385
+ /** Count of entities the gate marked create-eligible. */
386
+ createEligible: number;
387
+ /** Subjects captured (not yet articled) — their chunks land in `_captured`,
388
+ * still retrievable by search, never dropped. */
389
+ captured: string[];
390
+ }
391
+
392
+ /**
393
+ * ROUTE — recompute the create/capture decisions over `chunk_entities` with the
394
+ * deterministic `RouteAccumulator` + the CREATE gate (Bucketing.md), then PERSIST
395
+ * the outcome so SYNTHESIZE can read it without recomputing: `entities.notable =
396
+ * 1` for a create-eligible (or already-homed) entity, `0` for a captured one, and
397
+ * the captured subjects' chunks into the reserved `_captured` bucket (still
398
+ * searchable — capture is not a drop). Deterministic/CPU (only the optional
399
+ * subject gate touches the GPU). Resumable/idempotent — re-running rewrites the
400
+ * same flags.
401
+ */
402
+ export async function runRouteStage(
403
+ store: MemoryStore,
404
+ opts: RouteStageOptions = {},
405
+ ): Promise<RouteStageResult> {
406
+ const { chunkIds } = chronoChunkIds(store, opts.convIds);
407
+ const chunkSet = new Set(chunkIds);
408
+
409
+ const known = (
410
+ store.db.query("SELECT name FROM entities WHERE article_stem IS NOT NULL").all() as {
411
+ name: string;
412
+ }[]
413
+ ).map((r) => r.name);
414
+ const acc = new RouteAccumulator(known);
415
+
416
+ // Feed the fan-out CHRONOLOGICALLY (oldest conversation first).
417
+ const rows = store.db
418
+ .query(
419
+ "SELECT ce.chunk_id AS chunk_id, ce.entity_name AS entity_name FROM chunk_entities ce " +
420
+ "JOIN chunks ch ON ch.id = ce.chunk_id JOIN conversations c ON c.conv = ch.conv " +
421
+ "ORDER BY c.updated_at ASC, ch.start ASC, ce.entity_name ASC",
422
+ )
423
+ .all() as { chunk_id: string; entity_name: string }[];
424
+ for (const r of rows) {
425
+ if (!chunkSet.has(r.chunk_id)) continue;
426
+ acc.enqueue(r.entity_name, r.chunk_id);
427
+ }
428
+
429
+ // Optional model gate: promote a thin genuine-subject candidate to a `create`
430
+ // stub (chronological scan). NO ownership test — pure subject engagement.
431
+ if (opts.useSubjectGate) {
432
+ for (const d of acc.decisions()) {
433
+ if (d.action !== "capture") continue;
434
+ for (const cid of entityChunkIdsChrono(store, d.entity, chunkSet)) {
435
+ if (await engagesAsSubject(d.entity, store.chunkText(cid))) {
436
+ acc.enqueue(d.entity, cid, { subjectEngagement: true });
437
+ break;
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+ const decisions = acc.decisions() as RouteDecision[];
444
+ const captured = decisions.filter((d) => d.action === "capture").map((d) => d.entity);
445
+
446
+ // PERSIST: notable flag + capture chunks into the reserved _captured bucket
447
+ // (still searchable — capture is not a drop).
448
+ const setNotable = store.db.query("UPDATE entities SET notable = ? WHERE name = ?");
449
+ const ensureBucket = store.db.query(
450
+ "INSERT OR IGNORE INTO buckets (name, article_stem, description) VALUES (?, '', ?)",
451
+ );
452
+ const insChunkBucket = store.db.query(
453
+ "INSERT OR IGNORE INTO chunk_buckets (chunk_id, bucket) VALUES (?, ?)",
454
+ );
455
+ const capturedChunks = new Map<string, string[]>();
456
+ for (const e of captured) capturedChunks.set(e, entityChunkIdsChrono(store, e, chunkSet));
457
+ const tx = store.db.transaction(() => {
458
+ for (const d of decisions) {
459
+ const notable = d.action === "create" || d.action === "routed" ? 1 : 0;
460
+ setNotable.run(notable, d.entity);
461
+ }
462
+ if (captured.length) {
463
+ ensureBucket.run(CAPTURED_BUCKET, "subjects captured but not yet articled — still retrievable by search");
464
+ for (const [, cids] of capturedChunks) for (const cid of cids) insChunkBucket.run(cid, CAPTURED_BUCKET);
465
+ }
466
+ });
467
+ tx();
468
+
469
+ // REDIRECTS: every discussed subject must resolve to a home, even when it never
470
+ // earns its own article. A subject FOLDED into an existing article (action
471
+ // "routed") registers its surfaces → that article; a CAPTURED subject registers
472
+ // its surfaces → the article it most co-occurs with (its neighbourhood), so a
473
+ // later resolveName reaches its home instead of NOT FOUND. Idempotent; reindex
474
+ // projects these into entity_aliases. Purely additive — does not affect routing.
475
+ const stemOf = store.db.query("SELECT article_stem AS stem FROM entities WHERE name = ?");
476
+ const surfacesOf = (entity: string): string[] =>
477
+ (
478
+ store.db
479
+ .query("SELECT DISTINCT surface_form AS s FROM chunk_entities WHERE entity_name = ? AND surface_form IS NOT NULL")
480
+ .all(entity) as { s: string }[]
481
+ ).map((r) => r.s);
482
+ const registerHome = (entity: string, home: string, kind: "fold" | "capture"): void => {
483
+ if (!home) return;
484
+ registerRedirect(store, entity, home, kind);
485
+ for (const s of surfacesOf(entity)) registerRedirect(store, s, home, kind);
486
+ };
487
+ for (const d of decisions) {
488
+ if (d.action === "routed") {
489
+ const home = (stemOf.get(d.entity) as { stem: string | null } | null)?.stem;
490
+ if (home) registerHome(d.entity, home, "fold");
491
+ } else if (d.action === "capture") {
492
+ const home = relatedArticleStem(store, d.entity, chunkSet);
493
+ if (home) registerHome(d.entity, home, "capture");
494
+ }
495
+ }
496
+
497
+ const createEligible = decisions.filter((d) => d.action === "create").length;
498
+ opts.onEvent?.({
499
+ type: "stage",
500
+ stage: "route",
501
+ message: `route: ${decisions.length} entities — ${createEligible} create, ${captured.length} captured`,
502
+ });
503
+ return { decisions, createEligible, captured };
504
+ }
505
+
506
+ // ===========================================================================
507
+ // STAGE 4 — SYNTHESIZE (CREATE + PATCH)
508
+ // ===========================================================================
509
+
510
+ export interface SynthesizeStageOptions {
511
+ /** Vault root (honors MLX_BUN_WIKI); defaults to `vaultRoot()`. */
512
+ root?: string;
513
+ /** Max articles to CREATE this pass (defaults to DEFAULT_ARTICLE_CAP). */
514
+ limit?: number;
515
+ /** Restrict the run to these conversation ids (default: all). */
516
+ convIds?: string[];
517
+ /** Entities to force into the CREATE set when create-eligible. */
518
+ mustCreate?: string[];
519
+ /** Model-call seam for CREATE drafting AND PATCH integration. */
520
+ call?: SynthesisCall;
521
+ /** Model-call seam for SECTION-ROUTE (which existing section a patch folds into). */
522
+ sectionCall?: SectionCall;
523
+ /** Skip the final git commit (tests). */
524
+ commit?: boolean;
525
+ now?: number;
526
+ onEvent?: (e: SynthesisEvent) => void;
527
+ }
528
+
529
+ export interface SynthesizeStageResult {
530
+ created: PipelineCreated[];
531
+ patched: PipelinePatched[];
532
+ skippedByGate: string[];
533
+ /** Article stems a reconcile pass updated to stay consistent with the latest
534
+ * position (infobox field refresh and/or stale sibling-section rewrite). */
535
+ reconciled: string[];
536
+ }
537
+
538
+ /**
539
+ * SYNTHESIZE — the write stage, CHRONOLOGICAL throughout.
540
+ *
541
+ * (a) CREATE: for each create-eligible entity (`notable = 1`) with NO article
542
+ * file yet, draft via `synthesizeCreate` FEEDING ITS CHUNKS OLDEST-FIRST so
543
+ * the latest statement dominates; entities are processed in order of their
544
+ * EARLIEST chunk (oldest entity first), capped by `limit`.
545
+ * (b) PATCH: for each chunk routed to an EXISTING article and not already in the
546
+ * `synthesized_chunk_sections` ledger, SECTION-ROUTE then fold via
547
+ * `synthesizePatch`, oldest chunk first (so a newer correction overwrites an
548
+ * older take, not the reverse).
549
+ * (c) RECONCILE: after the PATCH loop, for every article it touched, run
550
+ * `reconcileArticle` so a fold that flipped the verdict also updates whatever
551
+ * it made stale (infobox relationship fields + sibling sections still asserting
552
+ * the old value). Bounded + idempotent — a consistent article is a NO-OP.
553
+ *
554
+ * Resumable via article presence + the ledger. Commits once at the end.
555
+ */
556
+ export async function runSynthesizeStage(
557
+ store: MemoryStore,
558
+ opts: SynthesizeStageOptions = {},
559
+ ): Promise<SynthesizeStageResult> {
560
+ const root = opts.root ?? vaultRoot();
561
+ const cap = opts.limit ?? DEFAULT_ARTICLE_CAP;
562
+ const emit = opts.onEvent ?? (() => {});
563
+ const { chunkIds } = chronoChunkIds(store, opts.convIds);
564
+ const runChunks = new Set(chunkIds);
565
+
566
+ // Snapshot the EXISTING article files BEFORE drafting, so the create-vs-patch
567
+ // split is stable (an entity created THIS run is not also patched this run).
568
+ const existingStems = new Set(await listArticles(root));
569
+ const dbStemByEntity = new Map(
570
+ (
571
+ store.db.query("SELECT name, article_stem FROM entities WHERE article_stem IS NOT NULL").all() as {
572
+ name: string;
573
+ article_stem: string;
574
+ }[]
575
+ ).map((r) => [r.name, r.article_stem] as const),
576
+ );
577
+ const existingArticleStem = (entity: string): string | null => {
578
+ const dbStem = dbStemByEntity.get(entity);
579
+ if (dbStem && existingStems.has(dbStem)) return dbStem;
580
+ const s = entityStem(entity);
581
+ return existingStems.has(s) ? s : null;
582
+ };
583
+
584
+ const meta = buildEntityMeta();
585
+ const created: PipelineCreated[] = [];
586
+ const skippedByGate: string[] = [];
587
+
588
+ // ---- CREATE: notable=1, no article file, in scope, oldest entity first ----
589
+ const convFilter = opts.convIds?.length ? `AND ch.conv IN (${opts.convIds.map(() => "?").join(",")})` : "";
590
+ const createRows = store.db
591
+ .query(
592
+ "SELECT e.name AS name, MIN(c.updated_at) AS first_at FROM entities e " +
593
+ "JOIN chunk_entities ce ON ce.entity_name = e.name " +
594
+ "JOIN chunks ch ON ch.id = ce.chunk_id " +
595
+ "JOIN conversations c ON c.conv = ch.conv " +
596
+ `WHERE e.notable = 1 ${convFilter} ` +
597
+ "GROUP BY e.name ORDER BY first_at ASC, e.name ASC",
598
+ )
599
+ .all(...(opts.convIds ?? [])) as { name: string; first_at: number }[];
600
+ const eligible = createRows.map((r) => r.name).filter((n) => existingArticleStem(n) == null);
601
+ const must = (opts.mustCreate ?? []).filter((n) => eligible.includes(n));
602
+ const targets: string[] = [];
603
+ const seen = new Set<string>();
604
+ for (const e of [...must, ...eligible]) {
605
+ if (seen.has(e)) continue;
606
+ seen.add(e);
607
+ targets.push(e);
608
+ if (targets.length >= cap) break;
609
+ }
610
+ emit({ type: "stage", stage: "create", message: `create: drafting ${targets.length} entity article(s) (cap ${cap})` });
611
+
612
+ for (const entity of targets) {
613
+ const cids = entityChunkIdsChrono(store, entity, runChunks); // chronological feed
614
+ const kind = meta.kindByCanonical.get(entity) ?? "thing";
615
+ let res;
616
+ try {
617
+ res = await synthesizeCreate(store, {
618
+ entity,
619
+ kind,
620
+ chunkIds: cids,
621
+ root,
622
+ aliases: meta.aliasesByCanonical.get(entity) ?? [],
623
+ call: opts.call,
624
+ commit: false,
625
+ now: opts.now,
626
+ });
627
+ } catch (err) {
628
+ skippedByGate.push(entity);
629
+ emit({ type: "log", message: ` skipped ${entity} (error: ${String(err)})` });
630
+ continue;
631
+ }
632
+ if (res.created) {
633
+ created.push({ stem: res.stem, hasInfobox: res.hasInfobox, citedSections: res.citedSections, chunkEdges: cids.length });
634
+ emit({ type: "log", message: ` created ${res.stem} (infobox=${res.hasInfobox}, cited=${res.citedSections})` });
635
+ } else if (res.skippedByGate) {
636
+ skippedByGate.push(res.stem);
637
+ emit({ type: "log", message: ` skipped ${res.stem} (gate: ${res.reason})` });
638
+ } else {
639
+ emit({ type: "log", message: ` skipped ${res.stem} (${res.reason})` });
640
+ }
641
+ }
642
+
643
+ // ---- SECTION-ROUTE → PATCH: existing-article entities, oldest chunk first ----
644
+ const patchEntities = (
645
+ opts.convIds?.length
646
+ ? (store.db
647
+ .query(
648
+ `SELECT DISTINCT ce.entity_name AS name FROM chunk_entities ce JOIN chunks ch ON ch.id = ce.chunk_id WHERE ch.conv IN (${opts.convIds
649
+ .map(() => "?")
650
+ .join(",")})`,
651
+ )
652
+ .all(...opts.convIds) as { name: string }[])
653
+ : (store.db.query("SELECT DISTINCT entity_name AS name FROM chunk_entities").all() as { name: string }[])
654
+ ).map((r) => r.name);
655
+
656
+ const patchTargets = patchEntities
657
+ .map((entity) => ({ entity, stem: existingArticleStem(entity) }))
658
+ .filter((t): t is { entity: string; stem: string } => t.stem != null)
659
+ .sort(
660
+ (a, b) =>
661
+ entityEarliestAt(store, a.entity, runChunks) - entityEarliestAt(store, b.entity, runChunks) ||
662
+ a.entity.localeCompare(b.entity),
663
+ );
664
+ emit({
665
+ type: "stage",
666
+ stage: "section-route",
667
+ message: `section-route: ${patchTargets.length} existing-article entit${patchTargets.length === 1 ? "y" : "ies"} to fold into`,
668
+ });
669
+
670
+ const patched: PipelinePatched[] = [];
671
+ let patchNoops = 0;
672
+ for (const { entity, stem } of patchTargets) {
673
+ for (const cid of entityChunkIdsChrono(store, entity, runChunks)) {
674
+ let article: SectionRouteArticle;
675
+ try {
676
+ const { content } = await readArticle(root, stem);
677
+ article = { stem, content };
678
+ } catch {
679
+ break; // article vanished mid-run
680
+ }
681
+ const chunk: SectionRouteChunk = {
682
+ id: cid,
683
+ label: chunkLabel(store, cid),
684
+ gist: firstSentences(store.chunkText(cid), 2),
685
+ };
686
+ const routeRes = await routeSections(chunk, article, { call: opts.sectionCall });
687
+ for (const anchor of routeRes.matchedAnchors) {
688
+ const pr = await synthesizePatch(store, {
689
+ stem,
690
+ anchor,
691
+ chunkId: cid,
692
+ root,
693
+ call: opts.call,
694
+ commit: false,
695
+ now: opts.now,
696
+ });
697
+ if (pr.patched) {
698
+ patched.push({ stem, anchor, chunkId: cid, footnote: pr.footnote });
699
+ emit({ type: "log", message: ` patched ${stem} #${anchor} (+chunk ${cid}, [^${pr.footnote}])` });
700
+ } else if (!pr.alreadyIntegrated) {
701
+ patchNoops++;
702
+ emit({ type: "log", message: ` patch NO-OP ${stem} #${anchor} (${pr.reason})` });
703
+ }
704
+ }
705
+ // No existing section fit but the chunk is substantive ⇒ SECTION-ROUTE
706
+ // named a NEW section. HONOR it (mint heading + fold the chunk) instead of
707
+ // dropping the chunk — silent loss is the self-healing bug we are fixing.
708
+ if (routeRes.newSection && routeRes.matchedAnchors.length === 0) {
709
+ const { title, anchor } = routeRes.newSection;
710
+ const nr = await synthesizeNewSection(store, {
711
+ stem,
712
+ title,
713
+ anchor,
714
+ chunkId: cid,
715
+ root,
716
+ call: opts.call,
717
+ commit: false,
718
+ now: opts.now,
719
+ });
720
+ if (nr.patched) {
721
+ patched.push({ stem, anchor, chunkId: cid, footnote: nr.footnote });
722
+ emit({ type: "log", message: ` new section ${stem} #${anchor} (+chunk ${cid}, [^${nr.footnote}])` });
723
+ } else if (!nr.alreadyIntegrated) {
724
+ patchNoops++;
725
+ emit({ type: "log", message: ` new-section NO-OP ${stem} #${anchor} (${nr.reason})` });
726
+ }
727
+ }
728
+ }
729
+ }
730
+ emit({ type: "stage", stage: "patch", message: `patch: ${patched.length} section fold(s), ${patchNoops} NO-OP(s)` });
731
+
732
+ // ---- RECONCILE: after a fold flips an article's verdict, update everything it
733
+ // made stale (infobox relationship fields + sibling sections still asserting the
734
+ // old value) so the article ends consistent with the latest position. Runs once
735
+ // per article touched this run; a consistent article is a NO-OP.
736
+ const reconciled: string[] = [];
737
+ const touchedStems = [...new Set(patched.map((p) => p.stem))];
738
+ for (const stem of touchedStems) {
739
+ let rr;
740
+ try {
741
+ rr = await reconcileArticle(store, stem, { root, call: opts.call, commit: false, now: opts.now });
742
+ } catch (err) {
743
+ emit({ type: "log", message: ` reconcile error ${stem}: ${String(err)}` });
744
+ continue;
745
+ }
746
+ if (rr.reconciled) {
747
+ reconciled.push(stem);
748
+ emit({
749
+ type: "log",
750
+ message: ` reconciled ${stem} (fields: ${rr.refreshedFields.join(", ") || "none"}; sections: ${rr.rewrittenSections.join(", ") || "none"}${rr.retried ? "; retried" : ""})`,
751
+ });
752
+ } else if (rr.gateVetoed) {
753
+ emit({ type: "log", message: ` reconcile NO-OP ${stem} (gate: ${rr.reason})` });
754
+ }
755
+ if (rr.unresolved.length) {
756
+ emit({
757
+ type: "log",
758
+ message: ` reconcile UNRESOLVED ${stem} — base-model left a stale present-tense assertion in: ${[...new Set(rr.unresolved)].join(", ")} (a memory-synthesis LoRA / P10-T1 would close it)`,
759
+ });
760
+ }
761
+ }
762
+ emit({ type: "stage", stage: "reconcile", message: `reconcile: ${reconciled.length} article(s) made consistent` });
763
+
764
+ const wrote = created.length + patched.length + reconciled.length;
765
+ if (opts.commit !== false && wrote) {
766
+ await commitVault(
767
+ root,
768
+ `memory: synthesis (${created.length} created, ${patched.length} patched, ${reconciled.length} reconciled)`,
769
+ );
770
+ }
771
+ emit({ type: "stage", stage: "commit", message: `commit: ${created.length} created + ${patched.length} patched + ${reconciled.length} reconciled written to ${root}` });
772
+
773
+ return { created, patched, skippedByGate, reconciled };
774
+ }