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.
- package/README.md +112 -20
- package/docs/design/batching-perf-path.md +232 -0
- 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/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/omlx-adoption-map.md +90 -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/segmented-backward-training.md +15 -0
- package/docs/design/spec-decode-larger-targets.md +229 -0
- package/docs/design/ssd-kv-cold-tier.md +158 -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 +348 -0
- package/docs/investigations/dspark-handoff.md +58 -0
- package/docs/investigations/kernel-perf-review-2026-07.md +171 -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.10.md +57 -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 +43 -9
- package/docs/reference/training.md +31 -12
- 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 +1077 -90
- package/src/config.ts +4 -1
- package/src/download.ts +99 -8
- package/src/embed.ts +77 -0
- package/src/eval/perplexity.ts +164 -0
- package/src/eval/runner.ts +15 -6
- package/src/eval/tasks/bfcl.ts +1 -1
- package/src/generate.ts +149 -18
- package/src/harness-pi.ts +43 -17
- package/src/index.ts +2 -0
- package/src/kv-store.ts +240 -98
- 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/array.ts +21 -0
- package/src/mlx/ffi.ts +3 -0
- package/src/mlx/ops.ts +72 -0
- package/src/model/compiled-decode.ts +43 -8
- package/src/model/factory.ts +29 -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 +96 -7
- package/src/model/gemma4.ts +33 -2
- package/src/model/minicpm5.ts +106 -8
- package/src/model/qwen3-delta.ts +48 -1
- package/src/model/qwen3.ts +276 -0
- package/src/model/qwen3_5.ts +11 -2
- package/src/model/steel-linear-kernel.ts +96 -0
- package/src/model/support.ts +38 -8
- 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/prompt-cache.ts +55 -9
- package/src/quantize/config-writer.ts +1 -1
- package/src/registry.ts +219 -8
- package/src/responses.ts +23 -0
- package/src/sampler.ts +220 -9
- package/src/serve/batch-scheduler.ts +307 -83
- package/src/serve/generation-gateway.ts +156 -29
- package/src/server.ts +746 -73
- 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/ssd-cache.ts +213 -0
- package/src/status-page.html +1 -1
- package/src/tokenizer.ts +7 -0
- package/src/train/flash-cce.ts +81 -23
- 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 +341 -40
- package/src/train/prefix-shared.ts +62 -11
- package/src/train/segmented.ts +215 -55
- package/src/train/trainer.ts +112 -38
- package/src/web/skills/memory/SKILL.md +40 -17
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
// mlx-bun memory — surface-variant RESOLUTION (the dedup fix for P5-T3/T4).
|
|
2
|
+
//
|
|
3
|
+
// canonicalize() in entity.ts is a *pure string normal form*: casefold, collapse
|
|
4
|
+
// whitespace, strip articles/possessives. That is necessary but NOT sufficient —
|
|
5
|
+
// the self-check turned the spacing, brand-only, and possessive surfaces of ONE
|
|
6
|
+
// product name into several different stems:
|
|
7
|
+
// - "<name>" vs "<na me>" (internal spacing the normal form keeps)
|
|
8
|
+
// - "<brand>" / "<brand> <model>" (brand-only and compositional surfaces that
|
|
9
|
+
// no purely-lexical normalizer can fold onto one canonical)
|
|
10
|
+
//
|
|
11
|
+
// The resolver adds three layers on top of canonicalize():
|
|
12
|
+
// 1. SQUEEZE — strip ALL non-alphanumerics so "<na me>" / "<name>" / "<nam e>"
|
|
13
|
+
// collapse to one key deterministically (fixes the spacing split).
|
|
14
|
+
// 2. ALIAS SEED — a known-entity index (entities + entity_aliases in the store,
|
|
15
|
+
// seeded from goldens/dreaming-entities-gold.json) so brand-only / nickname
|
|
16
|
+
// surfaces (a "<the brand>", a "<the role>") resolve by exact alias hit.
|
|
17
|
+
// 3. TOKEN-SUBSET FUZZY — a conservative compositional match: a surface folds
|
|
18
|
+
// onto an entity iff its content tokens are a SUBSET of that entity's tokens
|
|
19
|
+
// AND the overlap carries at least one DISTINCTIVE token (a token unique to
|
|
20
|
+
// that entity among all known entities). This merges "<my brand model>" → the
|
|
21
|
+
// entity via the distinctive model token while REFUSING to merge
|
|
22
|
+
// "<brand A>" into "<brand B>" (a shared brand token is not distinctive;
|
|
23
|
+
// the model-number tokens differ) — the over-merge guard.
|
|
24
|
+
//
|
|
25
|
+
// Resolution is conservative by construction: when in doubt it MINTS a new
|
|
26
|
+
// canonical rather than fusing two distinct things. ROUTE (route.ts) escalates
|
|
27
|
+
// the genuine misses to the model for binary disambiguation.
|
|
28
|
+
|
|
29
|
+
import { readFileSync } from "node:fs";
|
|
30
|
+
import { join } from "node:path";
|
|
31
|
+
|
|
32
|
+
import { canonicalize } from "./entity";
|
|
33
|
+
import type { MemoryStore } from "./db";
|
|
34
|
+
|
|
35
|
+
/** Tokens that carry no disambiguating signal on their own (articles, glue, and
|
|
36
|
+
* generic gear nouns shared across many entities). Used only for the fuzzy
|
|
37
|
+
* token-subset layer — never for the exact alias index. */
|
|
38
|
+
const STOP = new Set([
|
|
39
|
+
"the", "a", "an", "and", "or", "of", "to", "for", "in", "on", "with", "is",
|
|
40
|
+
"as", "my", "your", "his", "her", "its", "our", "their",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** Strip ALL non-alphanumerics and casefold: the spacing/punct-insensitive key.
|
|
44
|
+
* A name's spacing and punctuation variants all collapse here. */
|
|
45
|
+
export function squeeze(surface: string): string {
|
|
46
|
+
return surface.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Content tokens of a surface (casefold, split on non-alphanumerics, drop
|
|
50
|
+
* stopwords and single characters). Order-insensitive set. */
|
|
51
|
+
export function contentTokens(surface: string): Set<string> {
|
|
52
|
+
const out = new Set<string>();
|
|
53
|
+
for (const t of surface.toLowerCase().split(/[^a-z0-9]+/)) {
|
|
54
|
+
if (t.length > 1 && !STOP.has(t)) out.add(t);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** How a surface resolved (for instrumentation + the deterministic gates). */
|
|
60
|
+
export type MatchKind = "stem" | "squeeze" | "alias" | "fuzzy" | "new";
|
|
61
|
+
|
|
62
|
+
export interface ResolveResult {
|
|
63
|
+
/** The canonical entity name the surface resolved to (or was minted as). */
|
|
64
|
+
name: string;
|
|
65
|
+
/** Which layer produced the resolution. "new" ⇒ a canonical was minted. */
|
|
66
|
+
matched: MatchKind;
|
|
67
|
+
/** True iff this call minted a NEW canonical (no existing entity matched). */
|
|
68
|
+
created: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface Seed {
|
|
72
|
+
canonical: string;
|
|
73
|
+
aliases: string[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* In-memory variant resolver over a KNOWN-ENTITY set. Indexes each canonical by
|
|
78
|
+
* its normal-form stem, its squeeze key, and its content tokens, then resolves a
|
|
79
|
+
* surface through stem → squeeze → alias → token-subset-fuzzy, minting a new
|
|
80
|
+
* canonical only when every layer misses.
|
|
81
|
+
*
|
|
82
|
+
* Construct from a seed list, from a {@link MemoryStore} (entities +
|
|
83
|
+
* entity_aliases), or from the curated gold — and compose them (store first,
|
|
84
|
+
* gold to backfill notable brand-only aliases).
|
|
85
|
+
*/
|
|
86
|
+
export class EntityResolver {
|
|
87
|
+
/** normal-form stem → canonical. */
|
|
88
|
+
private byStem = new Map<string, string>();
|
|
89
|
+
/** squeeze key → canonical. */
|
|
90
|
+
private bySqueeze = new Map<string, string>();
|
|
91
|
+
/** canonical → union of content tokens across its name + aliases. */
|
|
92
|
+
private tokensOf = new Map<string, Set<string>>();
|
|
93
|
+
/** content token → set of canonicals carrying it (distinctiveness check). */
|
|
94
|
+
private tokenOwners = new Map<string, Set<string>>();
|
|
95
|
+
|
|
96
|
+
constructor(seeds: Seed[] = []) {
|
|
97
|
+
for (const s of seeds) this.register(s.canonical, s.aliases);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** All known canonical names (registration order is not guaranteed). */
|
|
101
|
+
canonicals(): string[] {
|
|
102
|
+
return [...this.tokensOf.keys()];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Is `name` an already-known canonical entity? */
|
|
106
|
+
has(name: string): boolean {
|
|
107
|
+
return this.tokensOf.has(name);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Register a canonical and its aliases into every index. Idempotent; adding
|
|
111
|
+
* aliases to an existing canonical merges them. The canonical's own surface is
|
|
112
|
+
* always indexed as an alias of itself. */
|
|
113
|
+
register(canonical: string, aliases: string[] = []): void {
|
|
114
|
+
if (!this.tokensOf.has(canonical)) this.tokensOf.set(canonical, new Set());
|
|
115
|
+
const tokset = this.tokensOf.get(canonical)!;
|
|
116
|
+
for (const surface of [canonical, ...aliases]) {
|
|
117
|
+
const stem = canonicalize(surface);
|
|
118
|
+
const sq = squeeze(surface);
|
|
119
|
+
if (stem && !this.byStem.has(stem)) this.byStem.set(stem, canonical);
|
|
120
|
+
if (sq && !this.bySqueeze.has(sq)) this.bySqueeze.set(sq, canonical);
|
|
121
|
+
for (const t of contentTokens(surface)) {
|
|
122
|
+
tokset.add(t);
|
|
123
|
+
let owners = this.tokenOwners.get(t);
|
|
124
|
+
if (!owners) this.tokenOwners.set(t, (owners = new Set()));
|
|
125
|
+
owners.add(canonical);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A token is DISTINCTIVE iff exactly one known canonical carries it — the
|
|
131
|
+
* signal the fuzzy layer requires to merge a compositional surface. */
|
|
132
|
+
private distinctive(token: string): string | null {
|
|
133
|
+
const owners = this.tokenOwners.get(token);
|
|
134
|
+
if (!owners || owners.size !== 1) return null;
|
|
135
|
+
return [...owners][0]!;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Conservative token-subset fuzzy match: the surface's content tokens must be a
|
|
140
|
+
* non-empty SUBSET of some entity's tokens, and at least one of them must be
|
|
141
|
+
* distinctive to that same entity. Returns the canonical, or null if no
|
|
142
|
+
* unambiguous owner (zero or conflicting distinctive owners ⇒ refuse to merge).
|
|
143
|
+
*/
|
|
144
|
+
private fuzzy(surface: string): string | null {
|
|
145
|
+
const toks = contentTokens(surface);
|
|
146
|
+
if (toks.size === 0) return null;
|
|
147
|
+
// The distinctive tokens present in the surface, and who owns them.
|
|
148
|
+
const owners = new Set<string>();
|
|
149
|
+
for (const t of toks) {
|
|
150
|
+
const owner = this.distinctive(t);
|
|
151
|
+
if (owner) owners.add(owner);
|
|
152
|
+
}
|
|
153
|
+
if (owners.size !== 1) return null; // none, or a tie across entities → no merge
|
|
154
|
+
const cand = [...owners][0]!;
|
|
155
|
+
// Subset guard: every surface token must belong to the candidate, else the
|
|
156
|
+
// surface names something MORE than (a variant of) the candidate.
|
|
157
|
+
const ets = this.tokensOf.get(cand)!;
|
|
158
|
+
for (const t of toks) if (!ets.has(t)) return null;
|
|
159
|
+
return cand;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Resolve a surface to an EXISTING canonical, or null if every layer misses.
|
|
163
|
+
* Pure: never mutates the index. */
|
|
164
|
+
match(surface: string): { name: string; matched: MatchKind } | null {
|
|
165
|
+
const stem = canonicalize(surface);
|
|
166
|
+
if (stem) {
|
|
167
|
+
const byStem = this.byStem.get(stem);
|
|
168
|
+
if (byStem) return { name: byStem, matched: "stem" };
|
|
169
|
+
}
|
|
170
|
+
const sq = squeeze(surface);
|
|
171
|
+
if (sq) {
|
|
172
|
+
const bySq = this.bySqueeze.get(sq);
|
|
173
|
+
if (bySq) return { name: bySq, matched: "squeeze" };
|
|
174
|
+
}
|
|
175
|
+
const fz = this.fuzzy(surface);
|
|
176
|
+
if (fz) return { name: fz, matched: "fuzzy" };
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Resolve a surface, MINTING a new canonical when nothing matches. The minted
|
|
182
|
+
* canonical is the cleaned surface; it is registered so later variants of the
|
|
183
|
+
* same thing fold onto it. Brand-only nicknames still need a gold/store seed —
|
|
184
|
+
* fuzzy cannot invent a "<the brand>" ≡ "<brand model>" link from lexis alone.
|
|
185
|
+
*/
|
|
186
|
+
resolve(surface: string, mintName?: string): ResolveResult {
|
|
187
|
+
const hit = this.match(surface);
|
|
188
|
+
if (hit) return { name: hit.name, matched: hit.matched, created: false };
|
|
189
|
+
const canonical = (mintName ?? surface).trim();
|
|
190
|
+
this.register(canonical, surface === canonical ? [] : [surface]);
|
|
191
|
+
return { name: canonical, matched: "new", created: true };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Register one canonical per stem with its alias surfaces, grouped from a
|
|
195
|
+
* normalized `alias → stem` map (the read-index's `aliasToStem`). The stem is
|
|
196
|
+
* the canonical; its surfaces become aliases. */
|
|
197
|
+
static fromAliasMap(aliasToStem: Iterable<readonly [string, string]>): EntityResolver {
|
|
198
|
+
const byStem = new Map<string, string[]>();
|
|
199
|
+
for (const [alias, stem] of aliasToStem) {
|
|
200
|
+
let list = byStem.get(stem);
|
|
201
|
+
if (!list) byStem.set(stem, (list = []));
|
|
202
|
+
list.push(alias);
|
|
203
|
+
}
|
|
204
|
+
const r = new EntityResolver();
|
|
205
|
+
for (const [stem, aliases] of byStem) r.register(stem, aliases);
|
|
206
|
+
return r;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Load the known-entity index from a store's entities + entity_aliases. */
|
|
210
|
+
static fromStore(store: MemoryStore): EntityResolver {
|
|
211
|
+
const r = new EntityResolver();
|
|
212
|
+
const ents = store.db.query("SELECT name FROM entities").all() as { name: string }[];
|
|
213
|
+
for (const e of ents) r.register(e.name, []);
|
|
214
|
+
const aliases = store.db
|
|
215
|
+
.query("SELECT alias, entity_name FROM entity_aliases")
|
|
216
|
+
.all() as { alias: string; entity_name: string }[];
|
|
217
|
+
for (const a of aliases) {
|
|
218
|
+
if (!r.has(a.entity_name)) r.register(a.entity_name, [a.alias]);
|
|
219
|
+
else r.register(a.entity_name, [a.alias]);
|
|
220
|
+
}
|
|
221
|
+
return r;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ---- near-name resolution (sub-concept → its home article) -----------------
|
|
226
|
+
|
|
227
|
+
/** Generic "kind-of-thing" suffix words a discussed sub-concept drops when it is
|
|
228
|
+
* the SAME subject as an existing article (a query that is the article title
|
|
229
|
+
* minus a generic tail — "<subject>" for "<subject> Theory"). They carry no
|
|
230
|
+
* disambiguating signal alone, so a query made ONLY of these never redirects. */
|
|
231
|
+
const GENERIC_SUFFIX = new Set([
|
|
232
|
+
"theory", "framework", "system", "model", "method", "methodology", "approach",
|
|
233
|
+
"principle", "principles", "technique", "concept", "paradigm", "effect", "law",
|
|
234
|
+
"hypothesis", "problem", "process", "pattern", "practice",
|
|
235
|
+
]);
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* NEAR-NAME match: resolve a surface to an EXISTING article when it is clearly the
|
|
239
|
+
* SAME subject — the conservative token-subset fuzzy (a query whose content tokens
|
|
240
|
+
* are a distinctive subset of an article's, e.g. the title minus a generic suffix).
|
|
241
|
+
* Reuses {@link EntityResolver.match} (stem → squeeze → token-subset fuzzy) but
|
|
242
|
+
* REFUSES a query made only of generic suffix words (just "Theory"/"Framework"),
|
|
243
|
+
* which would over-merge onto an arbitrary article. Returns the canonical (== the
|
|
244
|
+
* article stem the resolver was seeded with), or null. Pure.
|
|
245
|
+
*/
|
|
246
|
+
export function nearNameMatch(resolver: EntityResolver, surface: string): string | null {
|
|
247
|
+
const toks = contentTokens(surface);
|
|
248
|
+
if (toks.size === 0) return null;
|
|
249
|
+
let hasContentToken = false;
|
|
250
|
+
for (const t of toks) {
|
|
251
|
+
if (!GENERIC_SUFFIX.has(t)) {
|
|
252
|
+
hasContentToken = true;
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (!hasContentToken) return null; // a purely-generic query must not redirect
|
|
257
|
+
const hit = resolver.match(surface);
|
|
258
|
+
return hit ? hit.name : null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---- gold seed -------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
export interface VariantGroup {
|
|
264
|
+
canonical: string;
|
|
265
|
+
kind: string;
|
|
266
|
+
domain: string;
|
|
267
|
+
variants: string[];
|
|
268
|
+
}
|
|
269
|
+
export interface NotableEntity {
|
|
270
|
+
name: string;
|
|
271
|
+
kind: string;
|
|
272
|
+
domain: string;
|
|
273
|
+
aliases: string[];
|
|
274
|
+
whyNotable: string;
|
|
275
|
+
}
|
|
276
|
+
export interface DreamingGold {
|
|
277
|
+
variantGroups: VariantGroup[];
|
|
278
|
+
notableEntities: NotableEntity[];
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const GOLD_PATH = join(import.meta.dir, "..", "..", "goldens", "dreaming-entities-gold.json");
|
|
282
|
+
|
|
283
|
+
/** Read the curated entity gold (variantGroups + notableEntities). */
|
|
284
|
+
export function loadDreamingGold(path: string = GOLD_PATH): DreamingGold {
|
|
285
|
+
return JSON.parse(readFileSync(path, "utf8")) as DreamingGold;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Seeds derived from the gold: every variant group AND every notable entity
|
|
289
|
+
* becomes a (canonical, aliases) seed. Notable entries that share a canonical
|
|
290
|
+
* with a variant group merge their aliases. */
|
|
291
|
+
export function goldSeeds(gold: DreamingGold = loadDreamingGold()): Seed[] {
|
|
292
|
+
const byName = new Map<string, Set<string>>();
|
|
293
|
+
const add = (canonical: string, aliases: string[]): void => {
|
|
294
|
+
let set = byName.get(canonical);
|
|
295
|
+
if (!set) byName.set(canonical, (set = new Set()));
|
|
296
|
+
for (const a of aliases) set.add(a);
|
|
297
|
+
};
|
|
298
|
+
for (const g of gold.variantGroups) add(g.canonical, g.variants);
|
|
299
|
+
for (const n of gold.notableEntities) add(n.name, n.aliases);
|
|
300
|
+
return [...byName].map(([canonical, aliases]) => ({ canonical, aliases: [...aliases] }));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** A resolver pre-seeded with the curated gold — the production seed for the
|
|
304
|
+
* notable brand-only aliases the model/lexis cannot derive on its own. */
|
|
305
|
+
export function goldResolver(gold?: DreamingGold): EntityResolver {
|
|
306
|
+
return new EntityResolver(goldSeeds(gold));
|
|
307
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// mlx-bun memory — ROUTE: chunk-entities → subject articles.
|
|
2
|
+
//
|
|
3
|
+
// Routing is the deterministic-first join from a chunk's extracted entity
|
|
4
|
+
// surfaces to subject articles, with the model used ONLY to break genuine ties.
|
|
5
|
+
// It is the routing thesis under test: read the subjects a chunk is *about* and
|
|
6
|
+
// fan it out to EVERY article it touches (a single chunk routes to many).
|
|
7
|
+
//
|
|
8
|
+
// The policy here is Lucien's `Bucketing.md` / `Editorial_Guidelines.md`, ported
|
|
9
|
+
// faithfully: SURFACE EVERYTHING (nothing is dropped as trivia), STRONGLY PREFER
|
|
10
|
+
// EXISTING articles (existing wins ties), and mint a NEW article only for a
|
|
11
|
+
// substantive subject with no existing home. There is NO ownership/usefulness
|
|
12
|
+
// test — "anything that recurs in your thinking is notable enough."
|
|
13
|
+
//
|
|
14
|
+
// Per surface, in order:
|
|
15
|
+
// 1. RESOLVE — squeeze/alias/token-subset against the known-entity index
|
|
16
|
+
// (resolve.ts). A hit routes deterministically (folds into that existing
|
|
17
|
+
// article), no model call.
|
|
18
|
+
// 2. DISAMBIGUATE — a miss gets a trigram shortlist of existing entities; each
|
|
19
|
+
// candidate is put to the model as a bounded binary "is {surface} the same
|
|
20
|
+
// thing as {candidate}?" (callLocal("route"), 4 tokens, parseBinary). The
|
|
21
|
+
// first yes routes (existing wins).
|
|
22
|
+
// 3. CREATE / CAPTURE — a surface that matches nothing runs the CREATE gate: a
|
|
23
|
+
// subject earns its OWN article when it RECURS (≥ RECURRENCE_THRESHOLD
|
|
24
|
+
// routed chunks) OR the chunk engages it as a genuine subject (stubs are
|
|
25
|
+
// encouraged for emerging topics). A thin single fleeting mention with no
|
|
26
|
+
// existing home is CAPTURED — left in its chunk, retrievable by search,
|
|
27
|
+
// never dropped and never forced into a junk article. It earns an article
|
|
28
|
+
// later if it recurs.
|
|
29
|
+
//
|
|
30
|
+
// The deterministic pieces (resolve-to-one, trigram shortlist, fan-out, the
|
|
31
|
+
// CREATE gate arithmetic) are pure and unit-tested; only disambiguate() and
|
|
32
|
+
// engagesAsSubject() touch the GPU.
|
|
33
|
+
|
|
34
|
+
import type { MemoryStore } from "./db";
|
|
35
|
+
import { callLocal, MAX_OUTPUT_TOKENS } from "./model";
|
|
36
|
+
import { parseBinary } from "./parse";
|
|
37
|
+
import { EntityResolver, type MatchKind } from "./resolve";
|
|
38
|
+
|
|
39
|
+
/** Reserved bucket for subjects captured (not yet articled) — still retrievable
|
|
40
|
+
* by search, NOT a trivia graveyard. The leading underscore keeps it out of the
|
|
41
|
+
* emergent bucket namespace. */
|
|
42
|
+
export const CAPTURED_BUCKET = "_captured";
|
|
43
|
+
|
|
44
|
+
/** A subject RECURS (and so is notable enough for its own article) once it has
|
|
45
|
+
* routed this many distinct chunks. Tunable (Bucketing.md: lower = more/smaller
|
|
46
|
+
* articles, raise = fewer/larger); ≥2 == "recurs in your thinking." */
|
|
47
|
+
export const RECURRENCE_THRESHOLD = 2;
|
|
48
|
+
|
|
49
|
+
// ---- trigram shortlist -----------------------------------------------------
|
|
50
|
+
|
|
51
|
+
/** Character trigrams of a casefolded, space-collapsed surface (padded so short
|
|
52
|
+
* names still yield boundary grams). */
|
|
53
|
+
function trigrams(surface: string): Set<string> {
|
|
54
|
+
const s = ` ${surface.toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim()} `;
|
|
55
|
+
const out = new Set<string>();
|
|
56
|
+
for (let i = 0; i + 3 <= s.length; i++) out.add(s.slice(i, i + 3));
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Overlap coefficient |A∩B| / min(|A|,|B|) — credits a short name CONTAINED in
|
|
61
|
+
* a longer one rather than penalizing the length gap a Jaccard would. */
|
|
62
|
+
function overlap(a: Set<string>, b: Set<string>): number {
|
|
63
|
+
const m = Math.min(a.size, b.size);
|
|
64
|
+
if (m === 0) return 0;
|
|
65
|
+
const [small, big] = a.size <= b.size ? [a, b] : [b, a];
|
|
66
|
+
let inter = 0;
|
|
67
|
+
for (const x of small) if (big.has(x)) inter++;
|
|
68
|
+
return inter / m;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Trigram-ranked shortlist of existing canonicals for a surface that the
|
|
73
|
+
* resolver missed — the candidate set handed to the model for disambiguation.
|
|
74
|
+
* Returns up to `k` canonicals with nonzero overlap, best first.
|
|
75
|
+
*/
|
|
76
|
+
export function trigramShortlist(
|
|
77
|
+
resolver: EntityResolver,
|
|
78
|
+
surface: string,
|
|
79
|
+
k = 5,
|
|
80
|
+
): string[] {
|
|
81
|
+
const q = trigrams(surface);
|
|
82
|
+
const scored: { name: string; score: number }[] = [];
|
|
83
|
+
for (const name of resolver.canonicals()) {
|
|
84
|
+
const s = overlap(q, trigrams(name));
|
|
85
|
+
if (s > 0) scored.push({ name, score: s });
|
|
86
|
+
}
|
|
87
|
+
scored.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
|
|
88
|
+
return scored.slice(0, k).map((c) => c.name);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---- model gates -----------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Bounded binary disambiguation: is `surface` (in the chunk's `label` context)
|
|
95
|
+
* the same thing as the candidate `entity` (one-line `lead`)? One short call,
|
|
96
|
+
* parsed by parseBinary.
|
|
97
|
+
*/
|
|
98
|
+
export async function disambiguate(
|
|
99
|
+
surface: string,
|
|
100
|
+
label: string | null,
|
|
101
|
+
entity: string,
|
|
102
|
+
lead: string,
|
|
103
|
+
): Promise<boolean> {
|
|
104
|
+
const prompt =
|
|
105
|
+
`Is "${surface}" (context: ${label ?? "—"}) the same thing as ` +
|
|
106
|
+
`"${entity}" — ${lead}? Answer yes or no.`;
|
|
107
|
+
return parseBinary(await callLocal("route", { user: prompt }, { maxTokens: MAX_OUTPUT_TOKENS }));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Bounded subject-engagement gate: does this chunk engage with `entity` as a
|
|
112
|
+
* genuine SUBJECT — a topic/idea/person/project/thing the user is actually
|
|
113
|
+
* thinking about and discussing — rather than mentioning it only in passing?
|
|
114
|
+
* Feeds the CREATE gate's single-chunk stub path (NOT an ownership test).
|
|
115
|
+
*/
|
|
116
|
+
export async function engagesAsSubject(
|
|
117
|
+
entity: string,
|
|
118
|
+
chunkText: string,
|
|
119
|
+
): Promise<boolean> {
|
|
120
|
+
const prompt =
|
|
121
|
+
`${chunkText}\n\n---\n` +
|
|
122
|
+
`Based on the note above, does it engage with "${entity}" as a genuine ` +
|
|
123
|
+
`SUBJECT — a topic, idea, person, project, or thing the user is actually ` +
|
|
124
|
+
`thinking about and discussing — rather than mentioning it only in passing? ` +
|
|
125
|
+
`Answer yes or no.`;
|
|
126
|
+
return parseBinary(await callLocal("route", { user: prompt }, { maxTokens: MAX_OUTPUT_TOKENS }));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---- CREATE gate (pure) ----------------------------------------------------
|
|
130
|
+
|
|
131
|
+
export interface CreateStats {
|
|
132
|
+
/** Distinct chunks that routed to this candidate entity. */
|
|
133
|
+
routedChunks: number;
|
|
134
|
+
/** At least one routed chunk engages this entity as a genuine subject. */
|
|
135
|
+
subjectEngagement: boolean;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* CREATE gate (Bucketing.md / Editorial_Guidelines.md): a subject earns its own
|
|
140
|
+
* article when it RECURS (≥ RECURRENCE_THRESHOLD routed chunks — "recurs in your
|
|
141
|
+
* thinking is notable enough") OR a chunk engages it as a genuine subject (stubs
|
|
142
|
+
* are encouraged for emerging topics). Otherwise it is CAPTURED — kept in its
|
|
143
|
+
* chunk, retrievable by search, never dropped. Pure — the model fills
|
|
144
|
+
* `subjectEngagement` upstream. NO ownership/usefulness test.
|
|
145
|
+
*/
|
|
146
|
+
export function createGate(stats: CreateStats): "create" | "capture" {
|
|
147
|
+
if (stats.routedChunks >= RECURRENCE_THRESHOLD) return "create";
|
|
148
|
+
if (stats.subjectEngagement) return "create";
|
|
149
|
+
return "capture";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- fan-out accumulation --------------------------------------------------
|
|
153
|
+
|
|
154
|
+
export type RouteAction = "routed" | "create" | "capture";
|
|
155
|
+
|
|
156
|
+
export interface SurfaceRoute {
|
|
157
|
+
surface: string;
|
|
158
|
+
/** Resolved/candidate canonical, or null when no entity could be assigned. */
|
|
159
|
+
entity: string | null;
|
|
160
|
+
matched: MatchKind | "disambig" | "none";
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Accumulates the chunk→entity fan-out across a run so the CREATE gate can see
|
|
165
|
+
* each candidate's full chunk count + subject-engagement signal before deciding
|
|
166
|
+
* create-vs-capture. Deterministic and model-free: callers route surfaces (via
|
|
167
|
+
* the resolver + optional model disambig) and `enqueue` the resolved canonicals.
|
|
168
|
+
*/
|
|
169
|
+
export class RouteAccumulator {
|
|
170
|
+
/** canonical → set of chunk ids routed to it (fan-in). */
|
|
171
|
+
private chunks = new Map<string, Set<string>>();
|
|
172
|
+
/** canonical → at least one chunk engages it as a genuine subject. */
|
|
173
|
+
private engaged = new Map<string, boolean>();
|
|
174
|
+
/** canonicals that already exist as known entities (resolver hits) vs minted. */
|
|
175
|
+
private known = new Set<string>();
|
|
176
|
+
|
|
177
|
+
constructor(knownCanonicals: Iterable<string> = []) {
|
|
178
|
+
for (const c of knownCanonicals) this.known.add(c);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Record that `chunkId` routes to `entity` (idempotent per chunk). */
|
|
182
|
+
enqueue(entity: string, chunkId: string, opts?: { subjectEngagement?: boolean }): void {
|
|
183
|
+
let set = this.chunks.get(entity);
|
|
184
|
+
if (!set) this.chunks.set(entity, (set = new Set()));
|
|
185
|
+
set.add(chunkId);
|
|
186
|
+
if (opts?.subjectEngagement) this.engaged.set(entity, true);
|
|
187
|
+
else if (!this.engaged.has(entity)) this.engaged.set(entity, false);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Stats for an entity (for the CREATE gate). */
|
|
191
|
+
stats(entity: string): CreateStats {
|
|
192
|
+
return {
|
|
193
|
+
routedChunks: this.chunks.get(entity)?.size ?? 0,
|
|
194
|
+
subjectEngagement: this.engaged.get(entity) ?? false,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Final decision per accumulated entity. Existing known entities are always
|
|
200
|
+
* `routed` (they already have a home — existing wins); minted candidates run
|
|
201
|
+
* the CREATE gate (create vs capture). Returns a stable, name-sorted report.
|
|
202
|
+
*/
|
|
203
|
+
decisions(): { entity: string; action: RouteAction; stats: CreateStats }[] {
|
|
204
|
+
const out: { entity: string; action: RouteAction; stats: CreateStats }[] = [];
|
|
205
|
+
for (const entity of [...this.chunks.keys()].sort((a, b) => a.localeCompare(b))) {
|
|
206
|
+
const stats = this.stats(entity);
|
|
207
|
+
const action: RouteAction = this.known.has(entity) ? "routed" : createGate(stats);
|
|
208
|
+
out.push({ entity, action, stats });
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---- chunk routing (deterministic resolve; model only on misses) -----------
|
|
215
|
+
|
|
216
|
+
export interface RouteChunkOpts {
|
|
217
|
+
/** Shortlist width for the model disambiguation fallback. */
|
|
218
|
+
shortlistK?: number;
|
|
219
|
+
/** One-line lead per canonical, for the disambiguation prompt. */
|
|
220
|
+
leads?: Map<string, string>;
|
|
221
|
+
/** Disable the model fallback (deterministic-only routing) — misses become
|
|
222
|
+
* `none`. Used by the pure tests + dry runs. */
|
|
223
|
+
noModel?: boolean;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Route ONE chunk's surfaces to canonicals, fanning out to every entity it
|
|
228
|
+
* touches. Resolver hits route deterministically; misses get a trigram shortlist
|
|
229
|
+
* disambiguated by the model (unless `noModel`). Returns one {@link SurfaceRoute}
|
|
230
|
+
* per surface (entity null when nothing matched — a CREATE candidate upstream).
|
|
231
|
+
*/
|
|
232
|
+
export async function routeChunkSurfaces(
|
|
233
|
+
resolver: EntityResolver,
|
|
234
|
+
surfaces: { surface: string }[],
|
|
235
|
+
label: string | null,
|
|
236
|
+
opts: RouteChunkOpts = {},
|
|
237
|
+
): Promise<SurfaceRoute[]> {
|
|
238
|
+
const out: SurfaceRoute[] = [];
|
|
239
|
+
for (const { surface } of surfaces) {
|
|
240
|
+
const hit = resolver.match(surface);
|
|
241
|
+
if (hit) {
|
|
242
|
+
out.push({ surface, entity: hit.name, matched: hit.matched });
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (opts.noModel) {
|
|
246
|
+
out.push({ surface, entity: null, matched: "none" });
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
let routed: string | null = null;
|
|
250
|
+
for (const cand of trigramShortlist(resolver, surface, opts.shortlistK ?? 5)) {
|
|
251
|
+
const lead = opts.leads?.get(cand) ?? cand;
|
|
252
|
+
if (await disambiguate(surface, label, cand, lead)) {
|
|
253
|
+
routed = cand;
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
out.push({ surface, entity: routed, matched: routed ? "disambig" : "none" });
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Read a chunk's persisted entity surfaces (chunk_entities.surface_form). The
|
|
264
|
+
* routing input when extraction has already run; surfaces preserve their raw
|
|
265
|
+
* form so the resolver/model see what the user actually typed.
|
|
266
|
+
*/
|
|
267
|
+
export function chunkSurfaces(store: MemoryStore, chunkId: string): { surface: string }[] {
|
|
268
|
+
const rows = store.db
|
|
269
|
+
.query("SELECT surface_form FROM chunk_entities WHERE chunk_id = ? ORDER BY surface_form")
|
|
270
|
+
.all(chunkId) as { surface_form: string }[];
|
|
271
|
+
return rows.map((r) => ({ surface: r.surface_form }));
|
|
272
|
+
}
|
package/src/memory/schedule.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
// mlx-bun memory — nightly scheduling via launchd. ✅ REAL
|
|
2
|
-
//
|
|
1
|
+
// mlx-bun memory — nightly scheduling via launchd. ✅ REAL — install/remove/
|
|
2
|
+
// status here are fully functional, and the job they run (`mlx-bun memory
|
|
3
|
+
// synthesize`) now drives the real synthesis DAG (create + editorial wikify
|
|
4
|
+
// sweep), not a stub.
|
|
3
5
|
//
|
|
4
6
|
// mlx-bun is macOS/Apple-silicon-only by identity, so launchd is the native
|
|
5
7
|
// choice over crontab: it survives reboot, runs jobs missed while asleep on
|
|
6
8
|
// next wake, and gives clean install/uninstall. `memory schedule` writes
|
|
7
9
|
// ~/Library/LaunchAgents/com.mlx-bun.memory.plist (a StartCalendarInterval that
|
|
8
10
|
// runs `mlx-bun memory synthesize`) and loads it; `unschedule` unloads + removes
|
|
9
|
-
// it.
|
|
10
|
-
//
|
|
11
|
+
// it. That job runs the full synthesis DAG and produces/updates articles on the
|
|
12
|
+
// schedule with no further configuration.
|
|
11
13
|
//
|
|
12
14
|
// See docs/design/memory-system.md → "Scheduling (launchd)".
|
|
13
15
|
|