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
@@ -0,0 +1,150 @@
1
+ // mlx-bun memory — deterministic validation/repair of model-emitted chunk
2
+ // anchors (ported from lucien scripts/chunk-validation.ts, P5-T2).
3
+ //
4
+ // Same philosophy as the rest of the synthesis ledger: enforce the invariant in
5
+ // code, don't trust the model. The local e4b chunk adapter emits anchors that
6
+ // don't resolve a few percent of the time — the conversation uuid pasted where a
7
+ // message uuid belongs, or two adjacent message uuids spliced into a chimera.
8
+ // Left unvalidated those land in `chunks` and silently break pointer resolution
9
+ // (chunkText resolves a position range from each anchor's message). Repairs, in
10
+ // order:
11
+ // - exact match → use as-is
12
+ // - anchor == conversation uuid → first message (start) / last (end)
13
+ // - unique long-prefix match → that message (handles chimera splices)
14
+ // - otherwise → ChunkValidationError: fail the whole
15
+ // conversation so it retries on the next run (the errored path)
16
+ // A trailing coverage gap (the model stopped before the final exchange) extends
17
+ // the latest-ending chunk to the last message it was shown.
18
+
19
+ export interface RawChunk {
20
+ start_message_uuid: string;
21
+ end_message_uuid: string;
22
+ label: string;
23
+ }
24
+
25
+ export interface ChunkMessage {
26
+ uuid: string;
27
+ }
28
+
29
+ export interface ValidationResult {
30
+ chunks: RawChunk[];
31
+ repairs: string[];
32
+ }
33
+
34
+ export class ChunkValidationError extends Error {}
35
+
36
+ // A chimera splice keeps one anchor's leading bytes intact; distinct uuids share
37
+ // at most a few hex chars by chance, so 8 (the first uuid group) is an
38
+ // unambiguous threshold. Below it we'd be guessing, so the conversation fails
39
+ // instead and retries on the next run.
40
+ const MIN_PREFIX = 8;
41
+
42
+ function commonPrefixLen(a: string, b: string): number {
43
+ const n = Math.min(a.length, b.length);
44
+ let i = 0;
45
+ while (i < n && a[i] === b[i]) i++;
46
+ return i;
47
+ }
48
+
49
+ function resolveAnchor(
50
+ anchor: string,
51
+ kind: "start" | "end",
52
+ positions: Map<string, number>,
53
+ messages: ChunkMessage[],
54
+ conversationUuid: string,
55
+ repairs: string[],
56
+ label: string,
57
+ ): number {
58
+ const exact = positions.get(anchor);
59
+ if (exact !== undefined) return exact;
60
+
61
+ if (anchor === conversationUuid) {
62
+ const pos = kind === "start" ? 0 : messages.length - 1;
63
+ repairs.push(`"${label}": ${kind} anchor was the conversation uuid, snapped to message ${pos}`);
64
+ return pos;
65
+ }
66
+
67
+ let best = -1;
68
+ let bestLen = 0;
69
+ let secondLen = 0;
70
+ for (let i = 0; i < messages.length; i++) {
71
+ const len = commonPrefixLen(anchor, messages[i]!.uuid);
72
+ if (len > bestLen) {
73
+ secondLen = bestLen;
74
+ bestLen = len;
75
+ best = i;
76
+ } else if (len > secondLen) {
77
+ secondLen = len;
78
+ }
79
+ }
80
+ if (best !== -1 && bestLen >= MIN_PREFIX && bestLen > secondLen) {
81
+ repairs.push(
82
+ `"${label}": ${kind} anchor ${anchor.slice(0, 13)}… not found, ` +
83
+ `prefix-matched (${bestLen} chars) to message ${best}`,
84
+ );
85
+ return best;
86
+ }
87
+
88
+ throw new ChunkValidationError(
89
+ `chunk "${label}": ${kind} anchor "${anchor}" does not resolve to any ` +
90
+ `message uuid (no exact match, not the conversation uuid, best prefix ` +
91
+ `${bestLen} < ${MIN_PREFIX} or ambiguous)`,
92
+ );
93
+ }
94
+
95
+ export function validateChunks(
96
+ raw: RawChunk[],
97
+ messages: ChunkMessage[],
98
+ conversationUuid: string,
99
+ ): ValidationResult {
100
+ const repairs: string[] = [];
101
+
102
+ if (messages.length === 0) return { chunks: [], repairs };
103
+
104
+ const positions = new Map<string, number>();
105
+ messages.forEach((m, i) => positions.set(m.uuid, i));
106
+
107
+ const resolved: { start: number; end: number; label: string }[] = [];
108
+ for (const chunk of raw) {
109
+ const label = chunk.label ?? "(unlabeled)";
110
+ let start = resolveAnchor(chunk.start_message_uuid, "start", positions, messages, conversationUuid, repairs, label);
111
+ let end = resolveAnchor(chunk.end_message_uuid, "end", positions, messages, conversationUuid, repairs, label);
112
+ if (start > end) {
113
+ repairs.push(`"${label}": inverted range [${start}, ${end}], swapped`);
114
+ [start, end] = [end, start];
115
+ }
116
+ resolved.push({ start, end, label });
117
+ }
118
+
119
+ // Trailing coverage: if the model stopped short of the final exchange, extend
120
+ // the latest-ending chunk to the last message. Interior gaps are left alone
121
+ // (often deliberately-skipped command noise); an empty chunk list is respected
122
+ // (some conversations legitimately produce nothing).
123
+ if (resolved.length > 0) {
124
+ const last = messages.length - 1;
125
+ let maxEnd = -1;
126
+ let maxIdx = -1;
127
+ resolved.forEach((c, i) => {
128
+ if (c.end > maxEnd) {
129
+ maxEnd = c.end;
130
+ maxIdx = i;
131
+ }
132
+ });
133
+ if (maxEnd < last) {
134
+ repairs.push(
135
+ `"${resolved[maxIdx]!.label}": trailing gap [${maxEnd + 1}, ${last}] uncovered, ` +
136
+ `extended chunk end ${maxEnd} → ${last}`,
137
+ );
138
+ resolved[maxIdx]!.end = last;
139
+ }
140
+ }
141
+
142
+ return {
143
+ chunks: resolved.map((c) => ({
144
+ start_message_uuid: messages[c.start]!.uuid,
145
+ end_message_uuid: messages[c.end]!.uuid,
146
+ label: c.label,
147
+ })),
148
+ repairs,
149
+ };
150
+ }
@@ -1,25 +1,318 @@
1
- // mlx-bun memory — synthesis stage 2: CHUNK. ⚠️ M1 STUB.
1
+ // mlx-bun memory — synthesis stage 2: SEGMENT (chunking). (P5-T2)
2
2
  //
3
- // Segment each new conversation into topic chunks (a local-model call — this is
4
- // the segmentation track distilled from gold; eval by boundary/label accuracy).
5
- // Re-chunk only conversations whose updated_at > chunked_at. Mirrors lucien's
6
- // chunk-recent.ts. The prompt is the future "chunk" LoRA seam (prompts.ts).
3
+ // Segment each new/grown conversation into topic chunks with the local model.
4
+ // This is the segmentation track distilled from gold: the validated Gemma-4-e4b
5
+ // chunk SFT adapter (`e4b-chunk-300`, symlinked to `memory-chunk`) drives it via
6
+ // callLocal("chunk", …). The CHUNK_PROMPT below is ported from lucien's
7
+ // chunk-recent.ts; the editorial knobs (granularity, overlap, what to ignore)
8
+ // are NOT hard-coded here — they are inlined from the vault's Meta/ pages
9
+ // (Chunking.md + Topics_to_Ignore.md) so the policy is edit-in-the-vault.
7
10
  //
8
- // See docs/design/memory-system.md → "The nightly pipeline".
11
+ // Chunks are stored as POINTERS, exactly like the Lucien bootstrap: a chunk is a
12
+ // [start,end] position range into its conversation's messages (id =
13
+ // chunkId(conv,start,end)); chunkText() reassembles the slice on demand. The
14
+ // model emits message UUIDs, which we resolve (with anchor repair, see
15
+ // chunk-validation.ts) back to positions before writing.
16
+ //
17
+ // Re-chunk only conversations whose updated_at > chunked_at (NULL chunked_at = a
18
+ // never-segmented conversation). Setting chunked_at after a successful run makes
19
+ // re-running a no-op. See docs/design/the-dreaming-master-plan.md → P5-T2.
9
20
 
21
+ import { MemoryStore, chunkId } from "./db";
22
+ import { callLocal, type LocalInput } from "./model";
23
+ import { loadMetaPolicy } from "./prompts";
24
+ import { validateChunks, ChunkValidationError, type ChunkMessage } from "./chunk-validation";
10
25
  import type { SynthesisEvent } from "./pipeline";
11
26
 
27
+ // The EXACT system turn the `e4b-chunk-300` adapter was SFT'd with (the verbatim
28
+ // `messages[0].content` from chunk-data-le4000/train.jsonl). It MUST match training
29
+ // byte-for-byte: the e4b template emits a distinct `<|turn>system…<turn|>` block
30
+ // for it, and live inference previously dropped the whole system segment (decoded
31
+ // the chunk adapter off-distribution). The chunk SEGMENT call passes this as the
32
+ // system turn so the only trained adapter decodes on-distribution.
33
+ export const CHUNK_SYSTEM = `You are a precise conversation-segmentation engine, not a coding assistant and not a chat assistant. You receive ONE conversation transcript and return its topic segmentation.
34
+
35
+ Absolute output contract (overrides any conversational instinct):
36
+ - Your entire response MUST be a single JSON object, parseable by JSON.parse with no edits.
37
+ - No prose, no preamble, no explanation, no follow-up question, no markdown code fences, no tool calls. The first character you emit is "{" and the last is "}".
38
+ - Never ask for clarification or more data — the transcript in the message IS the data. If it has no meaningful content, return {"chunks": []}.
39
+ - Use only message UUIDs present in the provided transcript; never invent or alter a UUID.
40
+
41
+ Follow the segmentation rules and JSON schema in the message exactly.`;
42
+
43
+ // Ported verbatim-in-spirit from lucien scripts/chunk-recent.ts. The {{META_DOCS}}
44
+ // placeholder is filled at run time with the inlined Meta/ policy pages. This is
45
+ // the USER turn; CHUNK_SYSTEM above is the trained system turn.
46
+ export const CHUNK_PROMPT = `You will analyze ONE conversation between a user and an AI assistant. Identify ALL distinct topic chunks within it.
47
+
48
+ Use ONLY content from the conversation provided below; never copy any name, value, or example from these instructions into a label.
49
+
50
+ CRITICAL INSTRUCTIONS:
51
+ - Most substantive conversations contain MULTIPLE chunks, not one. Look hard for topic shifts.
52
+ - A topic shift happens when the user moves from one subject to a substantially different subject. Examples:
53
+ - Discussing one feature, then asking about a different feature
54
+ - Working through a problem, then pivoting to a related but distinct concern
55
+ - Asking about topic X, then asking about topic Y
56
+ - Even within a single broad topic, you should identify sub-chunks for specific aspects.
57
+ - Short conversations (under 4 messages) with a single Q&A may legitimately be one chunk. Most longer conversations are multiple chunks.
58
+ - Chunks MAY overlap. When a message at a topic boundary is genuinely substantive to BOTH the topic that is ending and the one beginning, include it in BOTH chunks — it is the end_message_uuid of one and falls within the range of the next. Do this only for genuine dual-membership, never for connective filler.
59
+
60
+ POLICY — the user's editorial policy pages are reproduced IN FULL under META POLICY PAGES below. Do not read any files; everything you need is in this prompt. Two things there govern you:
61
+ (1) Ignore rules — do NOT emit a chunk for any span whose subject falls under one; simply omit it.
62
+ (2) Chunking style — the instructions above (how fine a chunk is, how aggressively to overlap vs. draw hard boundaries, when a whole conversation is one chunk) are DEFAULTS. If a Meta doc specifies different chunking-style preferences, follow it over those defaults.
63
+ - You MUST still segment the conversation into topic chunks in the output schema below — that is not optional and no Meta doc overrides it. This prompt defines WHAT to do (segment into chunks; this schema); the Meta docs define HOW (granularity, overlap aggressiveness, boundary hardness, what to ignore).
64
+
65
+ META POLICY PAGES:
66
+ {{META_DOCS}}
67
+
68
+ For each chunk, output:
69
+ - start_message_uuid: uuid of the first message in the chunk
70
+ - end_message_uuid: uuid of the last message in the chunk
71
+ - label: a specific, descriptive label. Aim for 4-10 words. It must name the concrete subject AND the facet discussed, drawn ENTIRELY from this conversation — never from these instructions.
72
+ GOOD shape: "<specific subject> <facet discussed>" — the named topic plus the angle on it (e.g. a named subject followed by the specific decision, problem, or aspect covered).
73
+ BAD shape: a vague catch-all that names no specific subject (e.g. "a technical discussion", "a Q&A", "a conversation about <topic>").
74
+
75
+ OUTPUT FORMAT:
76
+ Output ONLY a JSON object, nothing else. No markdown fences, no explanation, no preamble.
77
+
78
+ If the conversation has meaningful content:
79
+ {"chunks": [{"start_message_uuid": "...", "end_message_uuid": "...", "label": "..."}, ...]}
80
+
81
+ If the conversation has no meaningful content (all messages empty or pure noise):
82
+ {"chunks": []}
83
+
84
+ Here is the conversation:
85
+ `;
86
+
87
+ /** The Meta/ policy pages SEGMENT inlines (P1-T7 / B10). Order is stable. */
88
+ const META_POLICY_PAGES = ["Chunking", "Topics_to_Ignore"];
89
+
90
+ /** Wrap a rendered chunk prompt as the trained {system, user} input. */
91
+ export function chunkInput(prompt: string): LocalInput {
92
+ return { system: CHUNK_SYSTEM, user: prompt };
93
+ }
94
+
12
95
  export interface ChunkResult {
96
+ /** Conversations eligible this run (NULL chunked_at or updated_at > chunked_at). */
13
97
  conversations: number;
98
+ /** Of those, the ones sent to the model (non-empty + at least one assistant turn). */
99
+ attempted: number;
100
+ /** Conversations whose output parsed to valid JSON with in-range anchors. */
101
+ valid: number;
102
+ /** Conversations skipped as empty / no-assistant and marked complete. */
103
+ skipped: number;
104
+ /** Conversations whose output failed to parse/validate (not marked; retried next run). */
105
+ errored: number;
106
+ /** Total chunk-pointer rows written this run. */
14
107
  chunks: number;
15
108
  }
16
109
 
17
- /** Conversations → topic chunks (local model). STUB. */
110
+ /** Model-call seam for SEGMENT — same shape as the other stage seams. Defaults
111
+ * to `callLocal("chunk", …)` (the e4b-chunk-300 / `memory-chunk` adapter); tests
112
+ * inject a fake so the pipeline can be driven without a real model load. */
113
+ export type ChunkCall = (prompt: string, opts?: { maxTokens?: number }) => Promise<string>;
114
+
115
+ export interface ChunkOptions {
116
+ /** Restrict to these conv ids (the smoke/eval path). Default: all eligible. */
117
+ convs?: string[];
118
+ /** Cap the number of conversations processed this run. */
119
+ limit?: number;
120
+ /** Generation budget per conversation. */
121
+ maxTokens?: number;
122
+ /** Override the model call (default `callLocal("chunk", …)`). Tests inject a fake. */
123
+ call?: ChunkCall;
124
+ }
125
+
126
+ interface ConvRow {
127
+ conv: string;
128
+ title: string | null;
129
+ updated_at: number;
130
+ chunked_at: number | null;
131
+ }
132
+
133
+ interface MsgRow {
134
+ position: number;
135
+ role: string;
136
+ uuid: string;
137
+ text: string;
138
+ }
139
+
140
+ function emptyResult(): ChunkResult {
141
+ return { conversations: 0, attempted: 0, valid: 0, skipped: 0, errored: 0, chunks: 0 };
142
+ }
143
+
144
+ /** Format a conversation the way the e4b chunk adapter was trained: a header line
145
+ * then each non-empty message as `[role] (uuid: …) text`, joined by `---`. */
146
+ export function formatConversation(title: string, conv: string, messages: MsgRow[]): string {
147
+ const body = messages
148
+ .map((m) => `[${m.role}] (uuid: ${m.uuid})\n${m.text}\n`)
149
+ .join("\n---\n");
150
+ return `Conversation: ${title || "(untitled)"} (uuid: ${conv})\n\n${body}`;
151
+ }
152
+
153
+ /** Best-effort JSON extraction from a model completion (ported from chunk-recent.ts). */
154
+ function extractJSON(response: string): { chunks?: unknown } {
155
+ const trimmed = response.trim();
156
+ try {
157
+ return JSON.parse(trimmed);
158
+ } catch {
159
+ /* fall through */
160
+ }
161
+ const stripped = trimmed
162
+ .replace(/^```json\s*/i, "")
163
+ .replace(/^```\s*/i, "")
164
+ .replace(/```\s*$/, "");
165
+ try {
166
+ return JSON.parse(stripped);
167
+ } catch {
168
+ /* fall through */
169
+ }
170
+ const firstBrace = response.indexOf("{");
171
+ const lastBrace = response.lastIndexOf("}");
172
+ if (firstBrace !== -1 && lastBrace > firstBrace) {
173
+ try {
174
+ return JSON.parse(response.slice(firstBrace, lastBrace + 1));
175
+ } catch {
176
+ /* fall through */
177
+ }
178
+ }
179
+ throw new Error("could not extract valid JSON from response");
180
+ }
181
+
182
+ /** Select the conversations to (re)segment, honoring the watermark rule. */
183
+ function selectEligible(store: MemoryStore, opts: ChunkOptions): ConvRow[] {
184
+ const rows = store.db
185
+ .query(
186
+ `SELECT conv, title, updated_at, chunked_at FROM conversations
187
+ WHERE chunked_at IS NULL OR updated_at > chunked_at
188
+ ORDER BY updated_at ASC`,
189
+ )
190
+ .all() as ConvRow[];
191
+ let eligible = rows;
192
+ if (opts.convs && opts.convs.length > 0) {
193
+ const allow = new Set(opts.convs);
194
+ eligible = eligible.filter((r) => allow.has(r.conv));
195
+ }
196
+ if (opts.limit !== undefined) eligible = eligible.slice(0, opts.limit);
197
+ return eligible;
198
+ }
199
+
200
+ /**
201
+ * Conversations → topic chunks (local model). For each eligible conversation,
202
+ * render the CHUNK_PROMPT with inlined Meta policy, call the chunk adapter,
203
+ * repair + validate the emitted anchors, and write pointer rows. Idempotent:
204
+ * sets chunked_at on success so a re-run is a no-op.
205
+ */
18
206
  export async function chunkConversations(
19
- _model: unknown,
20
- _onEvent?: (e: SynthesisEvent) => void,
207
+ store: MemoryStore,
208
+ opts: ChunkOptions = {},
209
+ onEvent?: (e: SynthesisEvent) => void,
21
210
  ): Promise<ChunkResult> {
22
- // TODO(M1): for each conv with updated_at > chunked_at, run the chunk prompt
23
- // on the local model, write chunks, set chunked_at.
24
- throw new Error("memory.chunk is not implemented yet (M1)");
211
+ const result = emptyResult();
212
+ // Default seam renders the trained {system: CHUNK_SYSTEM, user: <prompt>} shape
213
+ // so the chunk adapter decodes on-distribution. Tests inject a `call` that
214
+ // ignores the role split (it pattern-matches the prompt string).
215
+ const call: ChunkCall = opts.call ?? ((prompt, o) => callLocal("chunk", chunkInput(prompt), o));
216
+
217
+ // Inline the Meta policy once per run — pages change only by hand-edit, so a
218
+ // single bounded prefill per conversation (no agent loop) is all we need. LAZY:
219
+ // loadMetaPolicy reads the (global) vault and THROWS on a missing page, so we
220
+ // defer it until a conversation is actually sent to the model — a run with no
221
+ // eligible/attempted conversations (the common pipeline no-op) never needs it.
222
+ let promptHeadCache: string | undefined;
223
+ const promptHead = (): string =>
224
+ (promptHeadCache ??= CHUNK_PROMPT.replace("{{META_DOCS}}", loadMetaPolicy(META_POLICY_PAGES)));
225
+
226
+ const eligible = selectEligible(store, opts);
227
+ result.conversations = eligible.length;
228
+ onEvent?.({
229
+ type: "log",
230
+ stage: "chunk",
231
+ message: `segment: ${eligible.length} conversation(s) eligible`,
232
+ });
233
+
234
+ const msgQuery = store.db.query(
235
+ "SELECT position, role, uuid, text FROM messages WHERE conv = ? ORDER BY position",
236
+ );
237
+ const delChunks = store.db.query("DELETE FROM chunks WHERE conv = ?");
238
+ const insChunk = store.db.query(
239
+ "INSERT OR IGNORE INTO chunks (id, conv, start, end, label) VALUES (?, ?, ?, ?, ?)",
240
+ );
241
+ const setChunkedAt = store.db.query("UPDATE conversations SET chunked_at = ? WHERE conv = ?");
242
+
243
+ let i = 0;
244
+ for (const c of eligible) {
245
+ i++;
246
+ const allMsgs = msgQuery.all(c.conv) as MsgRow[];
247
+ const nonEmpty = allMsgs.filter((m) => m.text && m.text.trim());
248
+
249
+ // Skip 1: fully empty conversation (likely deleted) — mark complete.
250
+ if (nonEmpty.length === 0) {
251
+ setChunkedAt.run(Date.now(), c.conv);
252
+ result.skipped++;
253
+ continue;
254
+ }
255
+ // Skip 2: no assistant turn — nothing to segment — mark complete.
256
+ if (!nonEmpty.some((m) => m.role === "assistant")) {
257
+ setChunkedAt.run(Date.now(), c.conv);
258
+ result.skipped++;
259
+ continue;
260
+ }
261
+
262
+ result.attempted++;
263
+ const prompt = promptHead() + formatConversation(c.title ?? "", c.conv, nonEmpty);
264
+
265
+ let response: string;
266
+ try {
267
+ response = await call(prompt, { maxTokens: opts.maxTokens ?? 2048 });
268
+ } catch (err) {
269
+ onEvent?.({ type: "log", stage: "chunk", message: `[${i}/${eligible.length}] ${c.conv}: model error: ${String(err)}` });
270
+ result.errored++;
271
+ continue;
272
+ }
273
+
274
+ try {
275
+ const parsed = extractJSON(response);
276
+ const rawChunks = Array.isArray(parsed.chunks) ? parsed.chunks : [];
277
+ const anchorMsgs: ChunkMessage[] = nonEmpty.map((m) => ({ uuid: m.uuid }));
278
+ const { chunks, repairs } = validateChunks(rawChunks as never, anchorMsgs, c.conv);
279
+ for (const r of repairs) onEvent?.({ type: "log", stage: "chunk", message: ` repair: ${r}` });
280
+
281
+ // Resolve validated uuid anchors back to mlx-bun positions and write pointers.
282
+ const posByUuid = new Map<string, number>();
283
+ for (const m of nonEmpty) posByUuid.set(m.uuid, m.position);
284
+
285
+ const tx = store.db.transaction(() => {
286
+ delChunks.run(c.conv); // re-chunk: drop the prior segmentation
287
+ let wrote = 0;
288
+ for (const ch of chunks) {
289
+ const s = posByUuid.get(ch.start_message_uuid);
290
+ const e = posByUuid.get(ch.end_message_uuid);
291
+ if (s === undefined || e === undefined) continue; // unreachable post-validation
292
+ const lo = Math.min(s, e);
293
+ const hi = Math.max(s, e);
294
+ const info = insChunk.run(chunkId(c.conv, lo, hi), c.conv, lo, hi, ch.label);
295
+ wrote += info.changes;
296
+ }
297
+ setChunkedAt.run(Date.now(), c.conv);
298
+ return wrote;
299
+ });
300
+ const wrote = tx();
301
+ result.chunks += wrote;
302
+ result.valid++;
303
+ onEvent?.({ type: "log", stage: "chunk", message: `[${i}/${eligible.length}] ${c.conv}: ${chunks.length} chunk(s)` });
304
+ } catch (err) {
305
+ // Parse/validation failure: do NOT mark complete — it retries next run.
306
+ const kind = err instanceof ChunkValidationError ? "validation" : "parse";
307
+ onEvent?.({ type: "log", stage: "chunk", message: `[${i}/${eligible.length}] ${c.conv}: ${kind} error: ${String(err)}` });
308
+ result.errored++;
309
+ }
310
+ }
311
+
312
+ onEvent?.({
313
+ type: "log",
314
+ stage: "chunk",
315
+ message: `segment done: ${result.attempted} attempted, ${result.valid} valid, ${result.skipped} skipped, ${result.errored} errored, ${result.chunks} chunks`,
316
+ });
317
+ return result;
25
318
  }