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.
- package/README.md +112 -20
- package/docs/design/batching-v2-plan.md +515 -0
- package/docs/design/bucketing-stage.md +196 -0
- package/docs/design/compat-cli-surface-design.md +11 -11
- package/docs/design/diffusion-gemma-port.md +602 -0
- package/docs/design/docs-reorg-plan.md +1 -1
- package/docs/design/dreaming-nightly-pipeline.md +291 -0
- package/docs/design/dspark-speculative-decoding.md +106 -0
- package/docs/design/generic-model-support.md +381 -0
- package/docs/design/memory-inference-path.md +422 -0
- package/docs/design/memory-synthesis.md +287 -0
- package/docs/design/minicpm5-decode-megakernel.md +484 -0
- package/docs/design/mlx-lm-tool-parity-plan.md +535 -0
- package/docs/design/orpo-dynamic-lambda.md +41 -0
- package/docs/design/orpo-training.md +35 -5
- package/docs/design/parallel-slots.md +12 -1
- package/docs/design/parity-tier-dag.md +13 -5
- package/docs/design/spec-decode-larger-targets.md +229 -0
- package/docs/design/tauri-desktop-app.md +2 -2
- package/docs/design/the-dreaming-handoff.md +141 -0
- package/docs/design/the-dreaming-master-plan.md +446 -0
- package/docs/design/write-pipeline-entity.md +468 -0
- package/docs/investigations/curve-bisector-routing.md +1 -1
- package/docs/investigations/decode-roofline-lookagain.md +262 -0
- package/docs/investigations/dspark-handoff.md +58 -0
- package/docs/investigations/kernel-perf-review-2026-07.md +92 -0
- package/docs/planning/PRODUCT_ROADMAP.md +2 -2
- package/docs/planning/curve-sampler-research-plan.md +331 -0
- package/docs/planning/memory-docs-and-dag-plan.md +185 -0
- package/docs/planning/pi-integration-review.md +178 -0
- package/docs/planning/release-notes-v0.0.9.md +122 -0
- package/docs/planning/web-ui-pass-plan.md +213 -0
- package/docs/planning/website-readme-pass-plan.md +224 -0
- package/docs/reference/cli.md +255 -0
- package/docs/reference/embedding.md +7 -2
- package/docs/reference/library-api.md +22 -3
- package/docs/reference/memory.md +5 -5
- package/docs/reference/models.md +137 -0
- package/docs/reference/orpo-quickstart.md +6 -0
- package/docs/reference/server-api.md +187 -9
- package/docs/reference/server-config.md +40 -9
- package/docs/reference/training.md +25 -11
- package/package.json +1 -1
- package/src/anthropic.ts +22 -0
- package/src/assets/curve-designer.html +1 -1
- package/src/chat-template.ts +25 -7
- package/src/cli.ts +1029 -86
- package/src/config.ts +54 -3
- package/src/diffusion/diffusion-generate.ts +436 -0
- package/src/download.ts +99 -8
- package/src/embed.ts +77 -0
- package/src/eval/perplexity.ts +164 -0
- package/src/eval/runner.ts +19 -7
- package/src/eval/tasks/bfcl.ts +1 -1
- package/src/generate.ts +196 -19
- package/src/harness-pi.ts +43 -17
- package/src/index.ts +2 -0
- package/src/lora.ts +2 -2
- package/src/memory/article.ts +558 -0
- package/src/memory/chunk-validation.ts +150 -0
- package/src/memory/chunk.ts +305 -12
- package/src/memory/cluster.ts +344 -17
- package/src/memory/coverage.ts +134 -0
- package/src/memory/crosslink.ts +0 -0
- package/src/memory/db.ts +184 -45
- package/src/memory/entity.ts +203 -0
- package/src/memory/gate.ts +187 -0
- package/src/memory/history.ts +152 -0
- package/src/memory/ingest.ts +324 -11
- package/src/memory/model.ts +321 -0
- package/src/memory/normalize.ts +671 -0
- package/src/memory/parse.ts +22 -0
- package/src/memory/pipeline.ts +242 -30
- package/src/memory/prompts.ts +42 -0
- package/src/memory/query.ts +334 -0
- package/src/memory/reconcile.ts +734 -0
- package/src/memory/redirect.ts +108 -0
- package/src/memory/reindex.ts +325 -0
- package/src/memory/resolve.ts +307 -0
- package/src/memory/route.ts +272 -0
- package/src/memory/schedule.ts +6 -4
- package/src/memory/stages.ts +774 -0
- package/src/memory/synthesize.ts +1629 -20
- package/src/memory/tools.ts +446 -96
- package/src/memory/vault.ts +462 -35
- package/src/memory/wikify.ts +1057 -16
- package/src/mlx/ffi.ts +11 -0
- package/src/mlx/ops.ts +113 -0
- package/src/model/compiled-decode.ts +43 -8
- package/src/model/diffusion-gemma.ts +1026 -0
- package/src/model/factory.ts +35 -8
- package/src/model/flash-attention.ts +4 -2
- package/src/model/fused-decode-kernel.ts +14 -7
- package/src/model/fused-mlp-kernel.ts +169 -0
- package/src/model/fused-swiglu-kernel.ts +240 -0
- package/src/model/gemma4-base.ts +62 -6
- package/src/model/gemma4.ts +33 -2
- package/src/model/minicpm5.ts +106 -8
- package/src/model/qwen3.ts +276 -0
- package/src/model/steel-linear-kernel.ts +96 -0
- package/src/model/support.ts +45 -7
- package/src/model/universal/archs.ts +332 -0
- package/src/model/universal/dense.ts +576 -0
- package/src/model/universal/modules.ts +163 -0
- package/src/model/universal/rope.ts +366 -0
- package/src/pi-provider.ts +1 -1
- package/src/pi-terminal.ts +29 -8
- package/src/pi-web.ts +19 -2
- package/src/quantize/config-writer.ts +1 -1
- package/src/registry.ts +215 -7
- package/src/responses.ts +23 -0
- package/src/sampler.ts +220 -9
- package/src/serve/batch-scheduler.ts +272 -80
- package/src/serve/generation-gateway.ts +90 -18
- package/src/server.ts +643 -50
- package/src/spec/drafter.ts +81 -49
- package/src/spec/dspark/data-dflash.ts +156 -0
- package/src/spec/dspark/data.ts +201 -0
- package/src/spec/dspark/generate-dflash.ts +193 -0
- package/src/spec/dspark/generate.ts +290 -0
- package/src/spec/dspark/loss.ts +213 -0
- package/src/spec/dspark/module-dflash.ts +361 -0
- package/src/spec/dspark/module.ts +540 -0
- package/src/spec/dspark/sample.ts +112 -0
- package/src/spec/generate.ts +40 -19
- package/src/status-page.html +1 -1
- package/src/tokenizer.ts +7 -0
- package/src/train/diffusion-lora.ts +216 -0
- package/src/train/flash-cce.ts +70 -15
- package/src/train/fuse.ts +243 -0
- package/src/train/index.ts +3 -0
- package/src/train/job.ts +8 -0
- package/src/train/loss.ts +289 -30
- package/src/train/prefix-shared.ts +33 -5
- package/src/train/segmented.ts +67 -11
- package/src/train/trainer.ts +92 -28
- package/src/vision/diffusion-vision.ts +620 -0
- package/src/web/skills/memory/SKILL.md +40 -17
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// mlx-bun memory — the contradiction classifier + the "## History" section.
|
|
2
|
+
//
|
|
3
|
+
// When a later-dated note contradicts a claim already in an article, the resolve
|
|
4
|
+
// must decide WHICH KIND of contradiction it is before it edits:
|
|
5
|
+
//
|
|
6
|
+
// (a) EVOLUTION — the USER changed their own position / opinion / preference /
|
|
7
|
+
// relationship over time (both statements were true when made; the view
|
|
8
|
+
// simply moved). The LEAD/BODY resolve to the CURRENT state, and the
|
|
9
|
+
// trajectory is PRESERVED in a dedicated "## History" section (we KEEP the
|
|
10
|
+
// history) — both the earlier and the later source cited.
|
|
11
|
+
//
|
|
12
|
+
// (b) ERROR — the earlier value was simply a WRONG world-fact / spec, or a flat
|
|
13
|
+
// "no, that is wrong, it is actually <value>" correction. The wrong value is
|
|
14
|
+
// SILENTLY overwritten with the correct one: NO History entry, the wrong
|
|
15
|
+
// value pruned entirely as if it had never been there.
|
|
16
|
+
//
|
|
17
|
+
// The classifier is a bounded yes/no the small local model can answer reliably:
|
|
18
|
+
// "is this the user changing their own view over time, or correcting a wrong
|
|
19
|
+
// fact?". Everything in this module is schematic (the prompt carries ONLY
|
|
20
|
+
// instructions + the two real values under comparison, never a copyable example).
|
|
21
|
+
|
|
22
|
+
import { LEAD_ANCHOR } from "./cluster";
|
|
23
|
+
|
|
24
|
+
export const HISTORY_TITLE = "History";
|
|
25
|
+
export const HISTORY_ANCHOR = "history";
|
|
26
|
+
const HISTORY_HEADING_RE = /^##\s+History\s*$/i;
|
|
27
|
+
|
|
28
|
+
/** The two outcomes of a contradiction classification. */
|
|
29
|
+
export type ContradictionKind = "evolution" | "error";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The bounded EVOLUTION-vs-ERROR classifier prompt. It carries ONLY the two real
|
|
33
|
+
* values under comparison (the article data being reconciled) plus the decision
|
|
34
|
+
* rule — no copyable illustrative example. Answered with a single word.
|
|
35
|
+
*/
|
|
36
|
+
export function buildContradictionClassifierPrompt(earlier: string, later: string): string {
|
|
37
|
+
return (
|
|
38
|
+
`Two statements by the SAME user conflict. Decide which KIND of conflict this is.\n\n` +
|
|
39
|
+
`EARLIER value: ${earlier}\n` +
|
|
40
|
+
`LATER value: ${later}\n\n` +
|
|
41
|
+
`Answer EVOLUTION if the user CHANGED THEIR OWN position, opinion, preference, stance, or relationship over time — ` +
|
|
42
|
+
`both were genuine at the time they were said, and the view simply moved.\n` +
|
|
43
|
+
`Answer ERROR if the earlier value was simply a WRONG fact now being corrected — ` +
|
|
44
|
+
`a mistaken world-fact or spec, or a flat "no, that is wrong, it is actually <value>" fix where the earlier value was never a real position.\n\n` +
|
|
45
|
+
`Answer with EXACTLY one word: EVOLUTION or ERROR.`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse a classifier reply to a {@link ContradictionKind}. Defaults to
|
|
51
|
+
* `"evolution"` — the NON-DESTRUCTIVE branch (keep the history) — unless the reply
|
|
52
|
+
* unambiguously says ERROR, so an ambiguous answer never silently destroys a
|
|
53
|
+
* genuine trajectory. Pure.
|
|
54
|
+
*/
|
|
55
|
+
export function classifyContradiction(raw: string): ContradictionKind {
|
|
56
|
+
const t = (raw ?? "").toLowerCase();
|
|
57
|
+
if (/\berror\b/.test(t) && !/\bevolution\b/.test(t)) return "error";
|
|
58
|
+
return "evolution";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** True when the article already has a `## History` section. Pure. */
|
|
62
|
+
export function hasHistorySection(article: string): boolean {
|
|
63
|
+
return article.split("\n").some((l) => HISTORY_HEADING_RE.test(l.trim()));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A `[^k]` suffix for a marker number, or `""` when none is known. */
|
|
67
|
+
function markerSuffix(n: number | null | undefined): string {
|
|
68
|
+
return n != null ? `[^${n}]` : "";
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Build ONE History trajectory line preserving BOTH sources' citation markers:
|
|
73
|
+
* the earlier position (past) carries `[^earlierMarker]`, the later/current one
|
|
74
|
+
* carries `[^laterMarker]`, so no provenance is lost. Both values are real article
|
|
75
|
+
* data, not copyable example values. Pure.
|
|
76
|
+
*/
|
|
77
|
+
export function buildHistoryEntry(opts: {
|
|
78
|
+
earlier: string;
|
|
79
|
+
earlierMarker?: number | null;
|
|
80
|
+
later: string;
|
|
81
|
+
laterMarker?: number | null;
|
|
82
|
+
laterDate?: string | null;
|
|
83
|
+
}): string {
|
|
84
|
+
const when =
|
|
85
|
+
opts.laterDate && opts.laterDate !== "undated" ? `as of ${opts.laterDate}` : "now";
|
|
86
|
+
return (
|
|
87
|
+
`- Previously ${opts.earlier.trim()}${markerSuffix(opts.earlierMarker)}; ` +
|
|
88
|
+
`${when} ${opts.later.trim()}${markerSuffix(opts.laterMarker)}.`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Insert `entry` into the article's `## History` section, creating the section
|
|
94
|
+
* (just before `## See also` / `## References`, never after the references) when
|
|
95
|
+
* it is absent. Idempotent for an identical entry already present — never
|
|
96
|
+
* duplicates a line. Pure.
|
|
97
|
+
*/
|
|
98
|
+
export function upsertHistoryEntry(article: string, entry: string): string {
|
|
99
|
+
const trimmedEntry = entry.trim();
|
|
100
|
+
const lines = article.replace(/\s+$/, "").split("\n");
|
|
101
|
+
|
|
102
|
+
const headingIdx = lines.findIndex((l) => HISTORY_HEADING_RE.test(l.trim()));
|
|
103
|
+
if (headingIdx >= 0) {
|
|
104
|
+
// Find the end of the existing History block (next heading, or EOF).
|
|
105
|
+
let end = lines.length;
|
|
106
|
+
for (let i = headingIdx + 1; i < lines.length; i++) {
|
|
107
|
+
if (/^#{1,6}\s+/.test(lines[i]!.trim())) {
|
|
108
|
+
end = i;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const block = lines.slice(headingIdx + 1, end);
|
|
113
|
+
if (block.some((l) => l.trim() === trimmedEntry)) {
|
|
114
|
+
return article; // already recorded — idempotent
|
|
115
|
+
}
|
|
116
|
+
// Append after the last non-blank line of the block.
|
|
117
|
+
let last = end - 1;
|
|
118
|
+
while (last > headingIdx && lines[last]!.trim() === "") last--;
|
|
119
|
+
const next = [...lines.slice(0, last + 1), trimmedEntry, "", ...lines.slice(end)];
|
|
120
|
+
return next.join("\n") + "\n";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// No History section yet — insert one before See also / References.
|
|
124
|
+
const tailIdx = lines.findIndex((l) => /^##\s+(see also|references)\s*$/i.test(l.trim()));
|
|
125
|
+
const section = [`## ${HISTORY_TITLE}`, "", trimmedEntry, ""];
|
|
126
|
+
if (tailIdx < 0) return [...lines, "", ...section].join("\n") + "\n";
|
|
127
|
+
return [...lines.slice(0, tailIdx), ...section, ...lines.slice(tailIdx)].join("\n") + "\n";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The `[^N]` marker number that CITES `value`, so a resolve can preserve the right
|
|
132
|
+
* source when it moves a value into History. By the citation-after-claim
|
|
133
|
+
* convention the marker follows the claim, so we take the FIRST marker at/after the
|
|
134
|
+
* value's first occurrence; failing that, the nearest marker before it. Returns
|
|
135
|
+
* null when `value` carries no nearby marker. Pure.
|
|
136
|
+
*/
|
|
137
|
+
export function markerNear(text: string, value: string): number | null {
|
|
138
|
+
const v = value.trim().toLowerCase();
|
|
139
|
+
if (!v) return null;
|
|
140
|
+
const idx = text.toLowerCase().indexOf(v);
|
|
141
|
+
if (idx < 0) return null;
|
|
142
|
+
// First marker AT/AFTER the value (the citation follows the claim).
|
|
143
|
+
const after = text.slice(idx).match(/\[\^(\d+)\]/);
|
|
144
|
+
if (after) return parseInt(after[1]!, 10);
|
|
145
|
+
// Fallback: the LAST marker before the value.
|
|
146
|
+
const before = [...text.slice(0, idx).matchAll(/\[\^(\d+)\]/g)];
|
|
147
|
+
const last = before[before.length - 1];
|
|
148
|
+
return last ? parseInt(last[1]!, 10) : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Re-export so callers can name the lead target without reaching into cluster. */
|
|
152
|
+
export { LEAD_ANCHOR };
|
package/src/memory/ingest.ts
CHANGED
|
@@ -1,22 +1,335 @@
|
|
|
1
|
-
// mlx-bun memory — synthesis stage 1: INGEST.
|
|
1
|
+
// mlx-bun memory — synthesis stage 1: INGEST. (P5-T1)
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
// memory.sqlite, normalized to {conv, source, title, transcript}, watermark-
|
|
5
|
-
// gated so each run only processes what's new. No web scraping, no Playwright:
|
|
6
|
-
// mlx-bun synthesizes ITS OWN sessions only. Mirrors lucien's ingest-recent.ts.
|
|
3
|
+
// Two sources feed the synthesis ledger, both watermark-gated per `source`:
|
|
7
4
|
//
|
|
8
|
-
//
|
|
5
|
+
// • pi sessions — SessionManager.listAll() walks every on-disk pi session
|
|
6
|
+
// (the same JSONL store pi-web / pi-terminal write). Each becomes a
|
|
7
|
+
// conversation; its resolved messages become `messages` rows. This is the
|
|
8
|
+
// steady-state, "synthesize my own sessions" path.
|
|
9
|
+
//
|
|
10
|
+
// • the Lucien bootstrap — a one-time import of the read-only Lucien corpus
|
|
11
|
+
// (`~/Code/lucien/.lucien/lucien.db`) so the vault starts from a real body
|
|
12
|
+
// of prior conversations. Lucien's column names differ (B9 mapping below);
|
|
13
|
+
// critically we also REUSE Lucien's existing `chunks` by re-pointing each
|
|
14
|
+
// UUID span to mlx-bun `(start,end)` positions, so SEGMENT (P5-T2) only has
|
|
15
|
+
// to run on conversations Lucien never chunked.
|
|
16
|
+
//
|
|
17
|
+
// Everything is idempotent. Each source carries a watermark (max conversation
|
|
18
|
+
// `updated_at`, as epoch-ms); a re-run only looks at conversations newer than
|
|
19
|
+
// the cursor, and even a conversation that IS re-touched is rewritten in place
|
|
20
|
+
// (delete-then-insert its messages/chunks), so re-ingesting changes nothing.
|
|
21
|
+
//
|
|
22
|
+
// Lucien → mlx-bun column map (B9):
|
|
23
|
+
// conversations.uuid→conv, name→title, source→source, updated_at→updated_at
|
|
24
|
+
// messages.conversation_uuid→conv, position→position, sender→role,
|
|
25
|
+
// uuid→uuid, text→text
|
|
26
|
+
// chunks.start_message_uuid/end_message_uuid → messages.position (per conv)
|
|
27
|
+
// → chunks.start/.end; id = `${conv}:${start}-${end}` (Lucien's
|
|
28
|
+
// INTEGER chunk id is discarded). chunked_at from
|
|
29
|
+
// chunked_conversations.chunked_at where present.
|
|
9
30
|
|
|
31
|
+
import { Database } from "bun:sqlite";
|
|
32
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
33
|
+
import { MemoryStore, chunkId } from "./db";
|
|
10
34
|
import type { SynthesisEvent } from "./pipeline";
|
|
11
35
|
|
|
36
|
+
/** Default read-only Lucien source DB for the bootstrap import. */
|
|
37
|
+
export const DEFAULT_LUCIEN_DB = `${process.env.HOME}/Code/lucien/.lucien/lucien.db`;
|
|
38
|
+
|
|
12
39
|
export interface IngestResult {
|
|
40
|
+
/** Conversations examined this run (across every source). */
|
|
13
41
|
scanned: number;
|
|
42
|
+
/** Conversations written/refreshed this run (past the watermark). */
|
|
14
43
|
ingested: number;
|
|
44
|
+
/** Message rows written this run. */
|
|
45
|
+
messages: number;
|
|
46
|
+
/** Chunk-pointer rows written this run (Lucien bootstrap only). */
|
|
47
|
+
chunks: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function emptyResult(): IngestResult {
|
|
51
|
+
return { scanned: 0, ingested: 0, messages: 0, chunks: 0 };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Parse an ISO-8601 / Date string to epoch-ms; 0 when unparseable. */
|
|
55
|
+
function toEpoch(value: string | number | null | undefined): number {
|
|
56
|
+
if (value == null) return 0;
|
|
57
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : 0;
|
|
58
|
+
const t = Date.parse(value);
|
|
59
|
+
return Number.isFinite(t) ? t : 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Read a source's watermark cursor as epoch-ms (0 when none). */
|
|
63
|
+
function readWatermark(store: MemoryStore, source: string): number {
|
|
64
|
+
const row = store.db
|
|
65
|
+
.query("SELECT cursor FROM watermarks WHERE source = ?")
|
|
66
|
+
.get(source) as { cursor: string | null } | null;
|
|
67
|
+
// cursor is stored as an epoch-ms numeric string (see writeWatermark).
|
|
68
|
+
const n = row ? Number(row.cursor) : 0;
|
|
69
|
+
return Number.isFinite(n) ? n : 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Advance a source's watermark to `cursorEpoch` (epoch-ms, stored as text). */
|
|
73
|
+
function writeWatermark(store: MemoryStore, source: string, cursorEpoch: number): void {
|
|
74
|
+
store.db.run(
|
|
75
|
+
`INSERT INTO watermarks (source, cursor, updated_at) VALUES (?, ?, ?)
|
|
76
|
+
ON CONFLICT(source) DO UPDATE SET cursor = excluded.cursor, updated_at = excluded.updated_at`,
|
|
77
|
+
[source, String(cursorEpoch), Date.now()],
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Upsert one conversation header. */
|
|
82
|
+
function upsertConversation(
|
|
83
|
+
store: MemoryStore,
|
|
84
|
+
conv: string,
|
|
85
|
+
source: string,
|
|
86
|
+
title: string,
|
|
87
|
+
updatedAt: number,
|
|
88
|
+
chunkedAt: number | null,
|
|
89
|
+
): void {
|
|
90
|
+
store.db.run(
|
|
91
|
+
`INSERT INTO conversations (conv, source, title, updated_at, chunked_at) VALUES (?, ?, ?, ?, ?)
|
|
92
|
+
ON CONFLICT(conv) DO UPDATE SET
|
|
93
|
+
source = excluded.source, title = excluded.title,
|
|
94
|
+
updated_at = excluded.updated_at, chunked_at = excluded.chunked_at`,
|
|
95
|
+
[conv, source, title, updatedAt, chunkedAt],
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Replace a conversation's messages with `rows` (delete-then-insert, so a
|
|
101
|
+
* re-ingested conversation ends up with exactly its current message set).
|
|
102
|
+
* Returns the number of message rows written.
|
|
103
|
+
*/
|
|
104
|
+
function replaceMessages(
|
|
105
|
+
store: MemoryStore,
|
|
106
|
+
conv: string,
|
|
107
|
+
rows: { position: number; role: string; uuid: string; text: string }[],
|
|
108
|
+
): number {
|
|
109
|
+
store.db.run("DELETE FROM messages WHERE conv = ?", [conv]);
|
|
110
|
+
const ins = store.db.query(
|
|
111
|
+
"INSERT INTO messages (conv, position, role, uuid, text) VALUES (?, ?, ?, ?, ?)",
|
|
112
|
+
);
|
|
113
|
+
for (const r of rows) ins.run(conv, r.position, r.role, r.uuid, r.text);
|
|
114
|
+
return rows.length;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ───────────────────────────── pi sessions ──────────────────────────────────
|
|
118
|
+
|
|
119
|
+
/** First 8 lowercase hex digits of a session UUID — the conv:HASH citation id. */
|
|
120
|
+
function convIdFromSessionId(id: string): string {
|
|
121
|
+
const hex = id.replace(/[^0-9a-fA-F]/g, "").toLowerCase();
|
|
122
|
+
return hex.slice(0, 8) || id.slice(0, 8);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Flatten a pi message's content to plain text (text parts only). */
|
|
126
|
+
function piMessageText(content: unknown): string {
|
|
127
|
+
if (typeof content === "string") return content;
|
|
128
|
+
if (!Array.isArray(content)) return "";
|
|
129
|
+
const parts: string[] = [];
|
|
130
|
+
for (const part of content as { type?: string; text?: string }[]) {
|
|
131
|
+
if (part && part.type === "text" && typeof part.text === "string") parts.push(part.text);
|
|
132
|
+
}
|
|
133
|
+
return parts.join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Ingest pi sessions (every on-disk session SessionManager.listAll() finds)
|
|
138
|
+
* into the store under source "pi", watermark-gated by session modified time.
|
|
139
|
+
*/
|
|
140
|
+
export async function ingestSessions(
|
|
141
|
+
store: MemoryStore,
|
|
142
|
+
onEvent?: (e: SynthesisEvent) => void,
|
|
143
|
+
): Promise<IngestResult> {
|
|
144
|
+
const result = emptyResult();
|
|
145
|
+
const source = "pi";
|
|
146
|
+
let infos: Awaited<ReturnType<typeof SessionManager.listAll>>;
|
|
147
|
+
try {
|
|
148
|
+
infos = await SessionManager.listAll();
|
|
149
|
+
} catch (err) {
|
|
150
|
+
onEvent?.({ type: "log", stage: "ingest", message: `pi sessions: none readable (${String(err)})` });
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const cursor = readWatermark(store, source);
|
|
155
|
+
let maxEpoch = cursor;
|
|
156
|
+
|
|
157
|
+
for (const info of infos) {
|
|
158
|
+
result.scanned++;
|
|
159
|
+
const updatedAt = info.modified instanceof Date ? info.modified.getTime() : toEpoch(info.modified as never);
|
|
160
|
+
if (updatedAt <= cursor) continue;
|
|
161
|
+
|
|
162
|
+
let messages: { role: string; content: unknown }[] = [];
|
|
163
|
+
try {
|
|
164
|
+
const mgr = SessionManager.open(info.path);
|
|
165
|
+
messages = mgr.buildSessionContext().messages as { role: string; content: unknown }[];
|
|
166
|
+
} catch (err) {
|
|
167
|
+
onEvent?.({ type: "log", stage: "ingest", message: `skip session ${info.id}: ${String(err)}` });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const conv = convIdFromSessionId(info.id);
|
|
172
|
+
const rows: { position: number; role: string; uuid: string; text: string }[] = [];
|
|
173
|
+
let pos = 0;
|
|
174
|
+
for (const m of messages) {
|
|
175
|
+
if (m.role !== "user" && m.role !== "assistant") continue; // drop tool-result/system noise
|
|
176
|
+
const text = piMessageText(m.content);
|
|
177
|
+
if (text.trim() === "") continue;
|
|
178
|
+
rows.push({ position: pos, role: m.role, uuid: `${conv}-${pos}`, text });
|
|
179
|
+
pos++;
|
|
180
|
+
}
|
|
181
|
+
if (rows.length === 0) continue;
|
|
182
|
+
|
|
183
|
+
const title = info.name?.trim() || info.firstMessage?.trim() || conv;
|
|
184
|
+
const tx = store.db.transaction(() => {
|
|
185
|
+
upsertConversation(store, conv, source, title, updatedAt, null);
|
|
186
|
+
result.messages += replaceMessages(store, conv, rows);
|
|
187
|
+
});
|
|
188
|
+
tx();
|
|
189
|
+
result.ingested++;
|
|
190
|
+
if (updatedAt > maxEpoch) maxEpoch = updatedAt;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (maxEpoch > cursor) writeWatermark(store, source, maxEpoch);
|
|
194
|
+
onEvent?.({
|
|
195
|
+
type: "log",
|
|
196
|
+
stage: "ingest",
|
|
197
|
+
message: `pi sessions: scanned ${result.scanned}, ingested ${result.ingested} (${result.messages} messages)`,
|
|
198
|
+
});
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ──────────────────────────── Lucien bootstrap ──────────────────────────────
|
|
203
|
+
|
|
204
|
+
interface LucienConv {
|
|
205
|
+
uuid: string;
|
|
206
|
+
name: string | null;
|
|
207
|
+
source: string;
|
|
208
|
+
updated_at: string | null;
|
|
209
|
+
created_at: string | null;
|
|
210
|
+
}
|
|
211
|
+
interface LucienMsg {
|
|
212
|
+
uuid: string;
|
|
213
|
+
position: number;
|
|
214
|
+
sender: string;
|
|
215
|
+
text: string | null;
|
|
15
216
|
}
|
|
217
|
+
interface LucienChunk {
|
|
218
|
+
start_message_uuid: string;
|
|
219
|
+
end_message_uuid: string;
|
|
220
|
+
label: string | null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One-time bootstrap import of the read-only Lucien corpus. Watermark-gated per
|
|
225
|
+
* Lucien `source` (chatgpt / claude-ai / …) so a re-run is a no-op. Reuses
|
|
226
|
+
* Lucien's existing chunks as mlx-bun chunk pointers (UUID span → positions).
|
|
227
|
+
*/
|
|
228
|
+
export async function ingestLucien(
|
|
229
|
+
store: MemoryStore,
|
|
230
|
+
dbPath: string = DEFAULT_LUCIEN_DB,
|
|
231
|
+
onEvent?: (e: SynthesisEvent) => void,
|
|
232
|
+
): Promise<IngestResult> {
|
|
233
|
+
const result = emptyResult();
|
|
234
|
+
const src = new Database(dbPath, { readonly: true });
|
|
235
|
+
try {
|
|
236
|
+
// Map each conversation to its (optional) chunked_at epoch up front.
|
|
237
|
+
const chunkedAt = new Map<string, number>();
|
|
238
|
+
for (const row of src
|
|
239
|
+
.query("SELECT conversation_uuid AS conv, chunked_at FROM chunked_conversations")
|
|
240
|
+
.all() as { conv: string; chunked_at: string | null }[]) {
|
|
241
|
+
chunkedAt.set(row.conv, toEpoch(row.chunked_at));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const sources = (
|
|
245
|
+
src.query("SELECT DISTINCT source FROM conversations WHERE source IS NOT NULL").all() as {
|
|
246
|
+
source: string;
|
|
247
|
+
}[]
|
|
248
|
+
).map((r) => r.source);
|
|
249
|
+
|
|
250
|
+
const convsBySource = src.query(
|
|
251
|
+
"SELECT uuid, name, source, updated_at, created_at FROM conversations WHERE source = ?",
|
|
252
|
+
);
|
|
253
|
+
const msgsByConv = src.query(
|
|
254
|
+
"SELECT uuid, position, sender, text FROM messages WHERE conversation_uuid = ? ORDER BY position, uuid",
|
|
255
|
+
);
|
|
256
|
+
const chunksByConv = src.query(
|
|
257
|
+
"SELECT start_message_uuid, end_message_uuid, label FROM chunks WHERE conversation_uuid = ?",
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
for (const source of sources) {
|
|
261
|
+
const cursor = readWatermark(store, source);
|
|
262
|
+
let maxEpoch = cursor;
|
|
263
|
+
const convs = convsBySource.all(source) as LucienConv[];
|
|
264
|
+
|
|
265
|
+
const pending: { conv: LucienConv; epoch: number }[] = [];
|
|
266
|
+
for (const conv of convs) {
|
|
267
|
+
result.scanned++;
|
|
268
|
+
const epoch = toEpoch(conv.updated_at) || toEpoch(conv.created_at);
|
|
269
|
+
if (epoch <= cursor) continue;
|
|
270
|
+
pending.push({ conv, epoch });
|
|
271
|
+
if (epoch > maxEpoch) maxEpoch = epoch;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const tx = store.db.transaction(() => {
|
|
275
|
+
for (const { conv, epoch } of pending) {
|
|
276
|
+
const id = conv.uuid; // B9: conversations.uuid → conv (full uuid)
|
|
277
|
+
const msgs = msgsByConv.all(id) as LucienMsg[];
|
|
278
|
+
|
|
279
|
+
// Renumber positions densely (0..n-1) in source order. Lucien keys
|
|
280
|
+
// messages by uuid, so a branched conversation can repeat a position;
|
|
281
|
+
// mlx-bun's (conv,position) PK requires uniqueness. Order is preserved,
|
|
282
|
+
// so chunk spans (resolved via this same map) stay contiguous.
|
|
283
|
+
const posByUuid = new Map<string, number>();
|
|
284
|
+
const rows = msgs.map((m, i) => {
|
|
285
|
+
posByUuid.set(m.uuid, i);
|
|
286
|
+
return { position: i, role: m.sender, uuid: m.uuid, text: m.text ?? "" };
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
upsertConversation(
|
|
290
|
+
store,
|
|
291
|
+
id,
|
|
292
|
+
conv.source,
|
|
293
|
+
conv.name ?? "",
|
|
294
|
+
epoch,
|
|
295
|
+
chunkedAt.get(id) ?? null,
|
|
296
|
+
);
|
|
297
|
+
result.messages += replaceMessages(store, id, rows);
|
|
298
|
+
|
|
299
|
+
// Re-point Lucien's chunks to mlx-bun positions, discarding its int id.
|
|
300
|
+
store.db.run("DELETE FROM chunks WHERE conv = ?", [id]);
|
|
301
|
+
const insChunk = store.db.query(
|
|
302
|
+
"INSERT OR IGNORE INTO chunks (id, conv, start, end, label) VALUES (?, ?, ?, ?, ?)",
|
|
303
|
+
);
|
|
304
|
+
for (const c of chunksByConv.all(id) as LucienChunk[]) {
|
|
305
|
+
const start = posByUuid.get(c.start_message_uuid);
|
|
306
|
+
const end = posByUuid.get(c.end_message_uuid);
|
|
307
|
+
if (start === undefined || end === undefined) continue; // unresolvable span
|
|
308
|
+
const lo = Math.min(start, end);
|
|
309
|
+
const hi = Math.max(start, end);
|
|
310
|
+
const info = insChunk.run(chunkId(id, lo, hi), id, lo, hi, c.label);
|
|
311
|
+
result.chunks += info.changes; // count only rows actually inserted
|
|
312
|
+
}
|
|
313
|
+
result.ingested++;
|
|
314
|
+
}
|
|
315
|
+
if (maxEpoch > cursor) writeWatermark(store, source, maxEpoch);
|
|
316
|
+
});
|
|
317
|
+
tx();
|
|
318
|
+
|
|
319
|
+
onEvent?.({
|
|
320
|
+
type: "log",
|
|
321
|
+
stage: "ingest",
|
|
322
|
+
message: `lucien[${source}]: ${pending.length} new conversations`,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
} finally {
|
|
326
|
+
src.close();
|
|
327
|
+
}
|
|
16
328
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
329
|
+
onEvent?.({
|
|
330
|
+
type: "log",
|
|
331
|
+
stage: "ingest",
|
|
332
|
+
message: `lucien bootstrap: scanned ${result.scanned}, ingested ${result.ingested} (${result.messages} messages, ${result.chunks} chunks)`,
|
|
333
|
+
});
|
|
334
|
+
return result;
|
|
22
335
|
}
|