humemory 0.2.7 → 0.2.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 (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,494 @@
1
+ /**
2
+ * Dreaming — Phase 6.1.
3
+ *
4
+ * A background consolidation pass that detects recurring patterns across
5
+ * sessions *and agents*, then proposes — never silently applies. The human
6
+ * gate is `pnpm cli dream review` / `approve` / `reject`.
7
+ *
8
+ * Invariants (asserted by tests):
9
+ * - The dreamer scores clusters on `base(source)` ONLY — verification informs
10
+ * recall ordering, recurrence informs clustering, they never feed each
11
+ * other (Claude R1, self-confirming loop).
12
+ * - The job is idempotent: `payload_hash` dedups proposals, and a rejected
13
+ * pattern is not resurrected on the next run (re-filing the same hash is an
14
+ * INSERT OR IGNORE no-op while the rejected row exists).
15
+ * - No network, no embeddings: the `Clusterer` is an interface so Phase 7 can
16
+ * swap in vectors without touching the pipeline (owner ruling).
17
+ */
18
+
19
+ import { createHash } from 'crypto';
20
+ import type {
21
+ Memory, Intention, MemoryStore, IntentionStore, ScriptStore,
22
+ DreamKind, DreamProposal,
23
+ } from './types.js';
24
+ import { baseTrust } from './trust.js';
25
+ import { systemClock, type Clock } from './clock.js';
26
+
27
+ export const DREAM_CONFIG = {
28
+ /** Traces younger than this are considered. */
29
+ windowDays: 30,
30
+ /** A cluster qualifies at ≥ K traces from ≥ 2 sessions, or ≥ 2 agents. */
31
+ minClusterSize: 3,
32
+ minDistinctSessions: 2,
33
+ minDistinctAgents: 2,
34
+ /** Corroboration also requires distinct directories — agreement ≠ independence. */
35
+ minDistinctDirectories: 2,
36
+ /** Jaccard similarity threshold for the keyword clusterer. */
37
+ similarityThreshold: 0.34,
38
+ /**
39
+ * FALLBACK cluster threshold, used only for embedders without a calibrated
40
+ * per-model value (HashEmbedder in tests). Production models carry their
41
+ * own in CLUSTER_THRESHOLDS (embeddings.ts, 7.5 rounds 1–4): e5-small
42
+ * 0.855 / e5-base 0.825 / bge-m3 0.740 (best F1 0.89).
43
+ *
44
+ * vectorCorroborateThreshold 0.99 = SENTINEL, auto-corroboration DISABLED.
45
+ * Four calibration rounds (e5-small, e5-base ×2, bge-m3 — 52 labelled pairs
46
+ * incl. same-domain hard negatives) all failed to find a P=1.0 gate
47
+ * (best-case false max 0.908 > true min 0.691 with bge-m3). Re-enabling
48
+ * requires a stronger embedder or an LLM pairwise verifier, not more fixture.
49
+ */
50
+ vectorClusterThreshold: 0.825,
51
+ vectorCorroborateThreshold: 0.99,
52
+ /** Proposal lifetime (owner-approved 14d expiry). */
53
+ proposalTtlDays: 14,
54
+ /** LLM drafting cap per run; skipped entirely without a client. */
55
+ maxDraftsPerRun: 10,
56
+ /** Loops open longer than this are stale-loop candidates. */
57
+ staleLoopDays: 30,
58
+ /** Max traces read per run. */
59
+ collectLimit: 500,
60
+ /**
61
+ * Phase 8.5 — script mining. A "correction" is a trace that WON an active
62
+ * contradiction: 6.0.2 already establishes that mechanism as evidence a
63
+ * prior trace was wrong, so reusing it avoids inventing a new "correction"
64
+ * tag with no producer anywhere in the codebase (Claude's Phase 8
65
+ * annotation flagged the alternative — tagging memoryType — as dead weight
66
+ * without one).
67
+ */
68
+ scriptCandidateMinCluster: 2,
69
+ /** Draft steps are raw trace content, capped — no LLM drafting for this kind (out of scope, PHASE8_PLAN §Out of scope). */
70
+ scriptCandidateMaxSteps: 6,
71
+ };
72
+
73
+ /** Phase 7 seam: swap this implementation for a vector clusterer. */
74
+ export interface Clusterer {
75
+ /** Async since Phase 7.1 — vector clusterers embed before grouping. */
76
+ cluster(memories: Memory[]): Promise<Memory[][]> | Memory[][];
77
+ }
78
+
79
+ /** Tokenize the strongest available retrieval text of a trace. */
80
+ function tokens(m: Memory): Set<string> {
81
+ const text = m.level3Keywords || m.keywords.join(' ') || m.level2Essential || m.content;
82
+ return new Set(
83
+ text
84
+ .toLowerCase()
85
+ .split(/[^a-z0-9àâäéèêëîïôöùûüç_-]+/i)
86
+ .filter((t) => t.length > 2)
87
+ );
88
+ }
89
+
90
+ function jaccard(a: Set<string>, b: Set<string>): number {
91
+ if (!a.size || !b.size) return 0;
92
+ let inter = 0;
93
+ for (const t of a) if (b.has(t)) inter++;
94
+ return inter / (a.size + b.size - inter);
95
+ }
96
+
97
+ /**
98
+ * Keyword clusterer: union-find over pairwise Jaccard similarity. Deterministic
99
+ * (stable iteration order, ties broken by insertion order), local, dependency-free.
100
+ */
101
+ export class KeywordClusterer implements Clusterer {
102
+ constructor(private threshold: number = DREAM_CONFIG.similarityThreshold) {}
103
+
104
+ cluster(memories: Memory[]): Memory[][] {
105
+ const parent = memories.map((_, i) => i);
106
+ const find = (i: number): number => {
107
+ while (parent[i] !== i) {
108
+ parent[i] = parent[parent[i]];
109
+ i = parent[i];
110
+ }
111
+ return i;
112
+ };
113
+ const tokenSets = memories.map(tokens);
114
+ for (let i = 0; i < memories.length; i++) {
115
+ for (let j = i + 1; j < memories.length; j++) {
116
+ if (jaccard(tokenSets[i], tokenSets[j]) >= this.threshold) {
117
+ const ri = find(i);
118
+ const rj = find(j);
119
+ if (ri !== rj) parent[rj] = ri;
120
+ }
121
+ }
122
+ }
123
+ const groups = new Map<number, Memory[]>();
124
+ memories.forEach((m, i) => {
125
+ const root = find(i);
126
+ if (!groups.has(root)) groups.set(root, []);
127
+ groups.get(root)!.push(m);
128
+ });
129
+ return [...groups.values()].filter((g) => g.length > 1);
130
+ }
131
+ }
132
+
133
+ export interface DreamReport {
134
+ considered: number;
135
+ clusters: number;
136
+ filed: number;
137
+ expired: number;
138
+ staleLoopCandidates: number;
139
+ draftsWritten: number;
140
+ /** Traces that earned `corroborated` verification during this run (6.0.1). */
141
+ corroborated: number;
142
+ /** `script_candidate` proposals filed this run (8.5). */
143
+ scriptCandidates: number;
144
+ proposals: DreamProposal[];
145
+ }
146
+
147
+ function hashOf(kind: DreamKind, ids: string[]): string {
148
+ return createHash('sha1').update([kind, ...ids.slice().sort()].join('|')).digest('hex');
149
+ }
150
+
151
+ /** Confidence: cluster size saturates at 8, weighted by mean baseTrust. */
152
+ function confidenceOf(cluster: Memory[]): number {
153
+ const sizeScore = Math.min(cluster.length, 8) / 8;
154
+ const trustScoreAvg = cluster.reduce((s, m) => s + baseTrust(m), 0) / cluster.length / 100;
155
+ return Math.round(sizeScore * (0.4 + 0.6 * trustScoreAvg) * 100) / 100;
156
+ }
157
+
158
+ function qualifies(cluster: Memory[]): boolean {
159
+ const sessions = new Set(cluster.map((m) => m.sessionId));
160
+ const agents = new Set(cluster.map((m) => m.agent).filter(Boolean));
161
+ return (
162
+ (cluster.length >= DREAM_CONFIG.minClusterSize && sessions.size >= DREAM_CONFIG.minDistinctSessions) ||
163
+ agents.size >= DREAM_CONFIG.minDistinctAgents
164
+ );
165
+ }
166
+
167
+ /**
168
+ * Does this cluster constitute *corroboration* — the first of the three
169
+ * evidence paths of 6.0.1, and the only one the dreamer can observe?
170
+ *
171
+ * Agreement is not independence (Claude R1, defect 1): three agents that read
172
+ * the same stale README are one source wearing three names. So distinct agent
173
+ * labels are necessary but not sufficient — the traces must also come from
174
+ * distinct sessions AND distinct directories, which is the cheapest available
175
+ * proxy for "these agents did not look at the same thing at the same time".
176
+ *
177
+ * Corroboration is deliberately the weakest bonus in TRUST_CONFIG (+8). It
178
+ * cannot feed the dreamer back: clustering scores on `baseTrust` only, so a
179
+ * cluster can never raise the trust that makes it qualify (R1, defect 2).
180
+ */
181
+ function corroborates(cluster: Memory[]): boolean {
182
+ const agents = new Set(cluster.map((m) => m.agent).filter(Boolean));
183
+ if (agents.size < DREAM_CONFIG.minDistinctAgents) return false;
184
+ const sessions = new Set(cluster.map((m) => m.sessionId));
185
+ if (sessions.size < DREAM_CONFIG.minDistinctSessions) return false;
186
+ const directories = new Set(cluster.map((m) => m.directory));
187
+ return directories.size >= DREAM_CONFIG.minDistinctDirectories;
188
+ }
189
+
190
+ export interface DreamOptions {
191
+ store: MemoryStore & IntentionStore;
192
+ clusterer?: Clusterer;
193
+ clock?: Clock;
194
+ /**
195
+ * Optional LLM drafting of consolidated wording. Capped and skipped when
196
+ * absent — the job then files proposals with the raw cluster, never fails.
197
+ */
198
+ draft?: (cluster: Memory[]) => Promise<string>;
199
+ /** Human identity for resolvedBy — `git config user.email`, fallback 'cli'. */
200
+ now?: never; // use clock
201
+ /** Override the 30-day collection window (validation / deep retrospectives). */
202
+ windowDays?: number;
203
+ }
204
+
205
+ export async function runDreamer(options: DreamOptions): Promise<DreamReport> {
206
+ const { store } = options;
207
+ const clock = options.clock ?? systemClock;
208
+ const clusterer = options.clusterer ?? new KeywordClusterer();
209
+ const now = clock.now();
210
+ const windowStart =
211
+ now.getTime() - (options.windowDays ?? DREAM_CONFIG.windowDays) * 24 * 3600_000;
212
+
213
+ // 0. Housekeeping: pending proposals past their TTL expire first.
214
+ const expired = (await store.expireDreamProposals?.()) ?? 0;
215
+
216
+ // 1. Collect — exclude contradicted losers and level-4/merged rows.
217
+ const contradicted = new Set(
218
+ ((await store.listContradictions?.({ status: 'active' })) ?? []).map((ct) => ct.loserId)
219
+ );
220
+ const traces = (await store.list({ limit: DREAM_CONFIG.collectLimit })).filter(
221
+ (m) =>
222
+ m.createdAt.getTime() >= windowStart &&
223
+ m.currentLevel < 4 &&
224
+ !m.mergedIntoId &&
225
+ !contradicted.has(m.id)
226
+ );
227
+
228
+ // 2. Cluster. ScoredClusterer (Phase 7.3) also yields each cluster's
229
+ // weakest link — needed for the two-threshold rule (A1).
230
+ const { hasScores } = await import('./vector-clusterer.js');
231
+ const scored = hasScores(clusterer) ? await clusterer.clusterWithScores(traces) : null;
232
+ const clusters: { members: Memory[]; minPairwiseSimilarity: number | null }[] = scored
233
+ ? scored.map((c) => ({ members: c.members, minPairwiseSimilarity: c.minPairwiseSimilarity }))
234
+ : (await clusterer.cluster(traces)).map((members) => ({ members, minPairwiseSimilarity: null }));
235
+
236
+ // 3-4. Qualify, then propose (idempotent via payload_hash).
237
+ let filed = 0;
238
+ let drafts = 0;
239
+ const proposals: DreamProposal[] = [];
240
+ const expiresAt = new Date(now.getTime() + DREAM_CONFIG.proposalTtlDays * 24 * 3600_000);
241
+
242
+ let corroborated = 0;
243
+
244
+ for (const cluster of clusters) {
245
+ if (!qualifies(cluster.members)) continue;
246
+
247
+ // Corroboration is evidence, not a proposal: 6.0.1 lists it as an
248
+ // automatic verification path, so it applies without the human gate.
249
+ // It touches no content — only the `verified` flag and its reason.
250
+ //
251
+ // A1 (two thresholds): when the clusterer scores its clusters, the weakest
252
+ // link must also clear the STRICTER corroborate threshold — grouping
253
+ // tolerates noise because a human reviews proposals; verification does
254
+ // not, because nobody reviews it. Clusterers without scores (keyword)
255
+ // keep the metadata-only rule.
256
+ const similarityOk =
257
+ cluster.minPairwiseSimilarity === null ||
258
+ cluster.minPairwiseSimilarity >= DREAM_CONFIG.vectorCorroborateThreshold;
259
+ if (similarityOk && corroborates(cluster.members) && store.verify) {
260
+ for (const m of cluster.members) {
261
+ if (m.verified) continue; // never downgrade an existing, stronger reason
262
+ await store.verify(m.id, 'corroborated');
263
+ corroborated++;
264
+ }
265
+ }
266
+
267
+ let drafted: string | undefined;
268
+ if (options.draft && drafts < DREAM_CONFIG.maxDraftsPerRun) {
269
+ drafted = await options.draft(cluster.members);
270
+ drafts++;
271
+ }
272
+
273
+ const ids = cluster.members.map((m) => m.id);
274
+ const payload = JSON.stringify({
275
+ clusterIds: ids,
276
+ agents: [...new Set(cluster.members.map((m) => m.agent).filter(Boolean))],
277
+ sessions: new Set(cluster.members.map((m) => m.sessionId)).size,
278
+ samples: cluster.members.slice(0, 3).map((m) => (m.level2Essential ?? m.content).slice(0, 140)),
279
+ drafted,
280
+ });
281
+
282
+ const ok = (await store.fileDreamProposal?.({
283
+ kind: 'promote_semantic',
284
+ payload,
285
+ payloadHash: hashOf('promote_semantic', ids),
286
+ confidence: confidenceOf(cluster.members),
287
+ expiresAt,
288
+ })) ?? false;
289
+ if (ok) filed++;
290
+ }
291
+
292
+ // 5. Stale loops (intentions read-only): open past staleLoopDays whose linked
293
+ // trace has faded to L3+ — propose closing them.
294
+ let staleLoopCandidates = 0;
295
+ const armed = await store.listIntentions({ status: ['armed', 'fired'], limit: 500 });
296
+ for (const intention of armed) {
297
+ const ageMs = now.getTime() - intention.createdAt.getTime();
298
+ if (ageMs < DREAM_CONFIG.staleLoopDays * 24 * 3600_000) continue;
299
+ if (intention.relatedMemoryId) {
300
+ const linked = await store.getById(intention.relatedMemoryId);
301
+ if (linked && linked.currentLevel < 3) continue; // trace still alive → not stale
302
+ }
303
+ staleLoopCandidates++;
304
+ const ok = (await store.fileDreamProposal?.({
305
+ kind: 'close_stale_loop',
306
+ payload: JSON.stringify({ intentionId: intention.id, content: intention.content, ageDays: Math.floor(ageMs / 24 / 3600_000) }),
307
+ payloadHash: hashOf('close_stale_loop', [intention.id]),
308
+ confidence: 0.3,
309
+ expiresAt,
310
+ })) ?? false;
311
+ if (ok) filed++;
312
+ }
313
+
314
+ // 6. Script mining (8.5): a cluster of *corrections* — traces that WON an
315
+ // active contradiction — sharing a directory drafts a script. "11 of 15
316
+ // agents fail the same command, then fix it the same way" is a contradiction
317
+ // per winning trace; clustering the winners finds the repeated pattern.
318
+ let scriptCandidates = 0;
319
+ if (store.listContradictions) {
320
+ const activeContradictions = await store.listContradictions({ status: 'active' });
321
+ const inWindow = activeContradictions.filter((c) => c.createdAt.getTime() >= windowStart);
322
+ // A memory can win more than one contradiction; keep its earliest win —
323
+ // that is when it first established itself as the correction.
324
+ const wonAt = new Map<string, Date>();
325
+ for (const c of inWindow) {
326
+ const prior = wonAt.get(c.winnerId);
327
+ if (!prior || c.createdAt < prior) wonAt.set(c.winnerId, c.createdAt);
328
+ }
329
+ const winners = (
330
+ await Promise.all([...wonAt.keys()].map((id) => store.getById(id)))
331
+ ).filter((m): m is Memory => m !== null && m.currentLevel < 4 && !m.mergedIntoId);
332
+
333
+ const byDirectory = new Map<string, Memory[]>();
334
+ for (const w of winners) {
335
+ const bucket = byDirectory.get(w.directory) ?? [];
336
+ bucket.push(w);
337
+ byDirectory.set(w.directory, bucket);
338
+ }
339
+
340
+ for (const [directory, group] of byDirectory) {
341
+ if (group.length < DREAM_CONFIG.scriptCandidateMinCluster) continue;
342
+ // Cluster within the directory only — a script has one `directory`,
343
+ // mixing corrections from unrelated places would draft a drill nobody
344
+ // asked for. No verification is granted here (unlike step 4's
345
+ // corroboration): this path only ever produces a human-reviewed
346
+ // proposal, so the plain (unscored) grouping is enough.
347
+ const subclusters = await clusterer.cluster(group);
348
+ for (const cluster of subclusters) {
349
+ if (cluster.length < DREAM_CONFIG.scriptCandidateMinCluster) continue;
350
+ const ordered = [...cluster].sort(
351
+ (a, b) => (wonAt.get(a.id)!.getTime() - wonAt.get(b.id)!.getTime())
352
+ );
353
+ const steps = ordered
354
+ .slice(0, DREAM_CONFIG.scriptCandidateMaxSteps)
355
+ .map((m) => (m.level2Essential ?? m.content).slice(0, 200));
356
+ const keywordCounts = new Map<string, number>();
357
+ for (const m of cluster) for (const k of m.keywords) keywordCounts.set(k, (keywordCounts.get(k) ?? 0) + 1);
358
+ const topKeyword = [...keywordCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
359
+ const ids = cluster.map((m) => m.id);
360
+ const name = topKeyword ? `fix-${topKeyword}` : `correction-${hashOf('script_candidate', ids).slice(0, 6)}`;
361
+
362
+ const ok = (await store.fileDreamProposal?.({
363
+ kind: 'script_candidate',
364
+ payload: JSON.stringify({
365
+ directory,
366
+ name,
367
+ description: `Recurring correction across ${cluster.length} traces — steps drafted from what fixed it each time.`,
368
+ steps,
369
+ sourceMemoryIds: ids,
370
+ truncatedSteps: cluster.length > DREAM_CONFIG.scriptCandidateMaxSteps,
371
+ }),
372
+ payloadHash: hashOf('script_candidate', ids),
373
+ confidence: confidenceOf(cluster),
374
+ expiresAt,
375
+ })) ?? false;
376
+ if (ok) { filed++; scriptCandidates++; }
377
+ }
378
+ }
379
+ }
380
+
381
+ const pending = (await store.listDreamProposals?.({ status: 'pending' })) ?? [];
382
+ proposals.push(...pending);
383
+
384
+ return {
385
+ considered: traces.length,
386
+ clusters: clusters.length,
387
+ filed,
388
+ expired,
389
+ staleLoopCandidates,
390
+ draftsWritten: drafts,
391
+ corroborated,
392
+ scriptCandidates,
393
+ proposals,
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Applies an approved proposal. Returns a human-readable summary of the effect.
399
+ * `update_agents_md` never writes the file — it returns the suggested line for
400
+ * the human to paste (level-1 memory stays human-owned, permanently).
401
+ */
402
+ export async function applyDreamProposal(
403
+ store: MemoryStore & IntentionStore & ScriptStore,
404
+ proposal: DreamProposal,
405
+ options?: { clock?: Clock }
406
+ ): Promise<string> {
407
+ const payload = JSON.parse(proposal.payload);
408
+
409
+ switch (proposal.kind) {
410
+ case 'promote_semantic': {
411
+ const ids: string[] = payload.clusterIds;
412
+ const members = (await Promise.all(ids.map((id) => store.getById(id)))).filter(Boolean) as Memory[];
413
+ if (!members.length) return 'cluster vanished — nothing to promote';
414
+ const content = payload.drafted ??
415
+ `Recurring pattern across ${members.length} traces (${payload.sessions} sessions, agents: ${payload.agents.join(', ') || 'n/a'}):\n` +
416
+ members.map((m) => `- ${(m.level2Essential ?? m.content).slice(0, 200)}`).join('\n');
417
+ const created = await store.add({
418
+ content,
419
+ directory: members[0].directory,
420
+ day: (options?.clock ?? systemClock).now().toISOString().split('T')[0],
421
+ keywords: [...new Set(members.flatMap((m) => m.keywords))].slice(0, 8),
422
+ sessionId: 'dream',
423
+ memoryType: 'semantic',
424
+ source: 'dream_proposal',
425
+ verified: true,
426
+ // NOT 'human': `human` is the only reason that renders a trace *bare*,
427
+ // outside the untrusted markers, in the next session's context block
428
+ // (session-context.ts). This content is LLM-drafted or concatenated
429
+ // from agent traces — the human approved a proposal showing three
430
+ // 140-char samples, they did not read this text. `corroborated` is
431
+ // what the evidence actually supports, and it keeps the trace wrapped.
432
+ verificationReason: 'corroborated',
433
+ });
434
+ return `promoted to semantic memory ${created.id.slice(0, 8)}…`;
435
+ }
436
+
437
+ case 'merge_cluster': {
438
+ const ids: string[] = payload.clusterIds;
439
+ if (ids.length < 2) return 'cluster too small to merge';
440
+ const [target, ...sources] = ids;
441
+ for (const src of sources) await store.merge(src, target, {});
442
+ return `merged ${sources.length} trace(s) into ${target.slice(0, 8)}…`;
443
+ }
444
+
445
+ case 'contradiction': {
446
+ const r = await store.contradict!(payload.winnerId, payload.loserId, {
447
+ reason: payload.reason,
448
+ createdBy: 'human', // approved by the human gate
449
+ });
450
+ return r.contradiction
451
+ ? `contradiction applied — loser at ${r.loser.saillance}/100`
452
+ : 'contradiction filed again as proposal';
453
+ }
454
+
455
+ case 'close_stale_loop': {
456
+ await store.updateIntentionStatus(payload.intentionId, 'closed', {});
457
+ return `stale loop ${payload.intentionId.slice(0, 8)}… closed`;
458
+ }
459
+
460
+ case 'update_agents_md': {
461
+ return `suggested AGENTS.md addition (paste it yourself):\n${payload.drafted ?? payload.suggestion ?? ''}`;
462
+ }
463
+
464
+ case 'script_candidate': {
465
+ // Lands as 'draft', never 'active' (8.5): the human reviewing the
466
+ // proposal saw a description and a confidence score, not necessarily
467
+ // every drafted step — same reasoning as promote_semantic not landing
468
+ // as `verificationReason: 'human'` (R1 discussion, Claude's reply).
469
+ // A human still runs `script activate` after reading the actual steps.
470
+ const script = await store.addScript({
471
+ name: payload.name,
472
+ description: payload.description,
473
+ steps: payload.steps,
474
+ directory: payload.directory,
475
+ source: 'dream_proposal',
476
+ status: 'draft',
477
+ pinned: false,
478
+ });
479
+ return `drafted script "${script.name}" (${script.id.slice(0, 8)}…) — ` +
480
+ `\`pnpm cli script activate ${script.id.slice(0, 8)}\` after reviewing the steps`;
481
+ }
482
+
483
+ case 'script_archived': {
484
+ // Notice, not a request (PHASE8_PLAN.md §8.4): the archival already
485
+ // happened — in the disuse sweep, or immediately on a contradiction
486
+ // (`reason` distinguishes the two, both filed by the store). Nothing
487
+ // left to apply — resolving the proposal only acknowledges it.
488
+ return payload.reason === 'contradiction'
489
+ ? `acknowledged: "${payload.name}" archived — contradicted by "${payload.winnerContent}"`
490
+ : `acknowledged: "${payload.name}" archived by disuse ` +
491
+ `(saillance ${payload.storedSaillance} → effective ${payload.effectiveSaillance})`;
492
+ }
493
+ }
494
+ }
@@ -0,0 +1,157 @@
1
+ import { modelCacheDirectory } from './paths.js';
2
+ /**
3
+ * Embedders — Phase 7.1.
4
+ *
5
+ * The test seam (same pattern as `LLMClient`): tests use the deterministic,
6
+ * offline `HashEmbedder`; production uses `OnnxEmbedder` (e5-small, local,
7
+ * loaded lazily — absent model ⇒ disabled, never a crash).
8
+ *
9
+ * e5 models expect `query:`/`passage:` prefixes; the Embedder owns them so
10
+ * callers never think about it.
11
+ */
12
+
13
+ import { createHash } from 'crypto';
14
+
15
+ export interface Embedder {
16
+ readonly modelId: string;
17
+ readonly dims: number;
18
+ /** L2-normalized embeddings, one per input text. `kind` selects the e5 prefix. */
19
+ embed(texts: string[], kind?: 'query' | 'passage'): Promise<Float32Array[]>;
20
+ }
21
+
22
+ /** The text actually embedded for a trace (A5: L3 FIRST — e5 truncates at
23
+ * 512 tokens, and the keywords are what keeps a decayed trace findable). */
24
+ export function embeddableText(input: { content: string; level3Keywords?: string; keywords?: string[] }): string {
25
+ const head = input.level3Keywords ?? input.keywords?.join(' ') ?? '';
26
+ return head ? `${head}\n${input.content}` : input.content;
27
+ }
28
+
29
+ export const HASH_DIMS = 384;
30
+
31
+ /**
32
+ * Deterministic, offline embedder for tests. Hashes each token into a sparse
33
+ * 384-dim space — semantically meaningless, but reproducible, and texts that
34
+ * share tokens get high cosine, so pipeline behavior (clustering shape,
35
+ * thresholds, storage) is fully testable without a model.
36
+ */
37
+ export class HashEmbedder implements Embedder {
38
+ readonly modelId = 'hash-v1';
39
+ readonly dims = HASH_DIMS;
40
+
41
+ async embed(texts: string[]): Promise<Float32Array[]> {
42
+ return texts.map((text) => {
43
+ const vec = new Float32Array(this.dims);
44
+ for (const token of text.toLowerCase().split(/[^a-z0-9àâäéèêëîïôöùûüç_-]+/i).filter((t) => t.length > 2)) {
45
+ const h = createHash('sha1').update(token).digest();
46
+ const idx = h.readUInt32LE(0) % this.dims;
47
+ const sign = h[4] % 2 === 0 ? 1 : -1;
48
+ vec[idx] += sign;
49
+ }
50
+ const norm = Math.sqrt(vec.reduce((s, x) => s + x * x, 0));
51
+ if (norm > 0) for (let i = 0; i < this.dims; i++) vec[i] /= norm;
52
+ return vec;
53
+ });
54
+ }
55
+ }
56
+
57
+ export function cosine(a: Float32Array, b: Float32Array): number {
58
+ let dot = 0;
59
+ for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
60
+ return dot; // inputs are L2-normalized
61
+ }
62
+
63
+ export const E5_MODEL_ID = 'Xenova/multilingual-e5-small';
64
+ export const E5_BASE_MODEL_ID = 'Xenova/multilingual-e5-base';
65
+ export const BGE_M3_MODEL_ID = 'Xenova/bge-m3';
66
+
67
+ /** Known output dims per model — e5-small 384, e5-base 768, bge-m3 1024. */
68
+ export const MODEL_DIMS: Record<string, number> = {
69
+ [E5_MODEL_ID]: 384,
70
+ [E5_BASE_MODEL_ID]: 768,
71
+ [BGE_M3_MODEL_ID]: 1024,
72
+ };
73
+
74
+ /**
75
+ * Calibrated cluster thresholds per model (7.5, 52 labelled pairs incl. hard
76
+ * negatives, scripts/calibrate-embeddings.ts). Thresholds are MODEL-SPECIFIC:
77
+ * bge-m3's cosine space sits lower than e5's. No model reaches a P=1.0
78
+ * corroboration gate — see DREAM_CONFIG.vectorCorroborateThreshold.
79
+ */
80
+ export const CLUSTER_THRESHOLDS: Record<string, number> = {
81
+ [E5_MODEL_ID]: 0.855, // round 1: F1 0.84 (P 0.76 / R 0.93)
82
+ [E5_BASE_MODEL_ID]: 0.825, // round 3: F1 0.80 (P 0.71 / R 0.92)
83
+ [BGE_M3_MODEL_ID]: 0.74, // round 4: F1 0.89 (P 0.83 / R 0.96) — best
84
+ };
85
+
86
+ export interface OnnxEmbedderOptions {
87
+ /** q8 (default) or fp32. fp16 is accepted but BROKEN on win32/onnxruntime-node
88
+ * (graph-fusion error at load, 7.5 calibration) — do not use it there. */
89
+ dtype?: 'q8' | 'fp16' | 'fp32';
90
+ /** Model to load; defaults to bge-m3 (7.5 round-4 calibration: best cluster
91
+ * F1 0.89 vs 0.80 for e5-base; no model reaches a P=1.0 corroborate gate). */
92
+ model?: string;
93
+ cacheDir?: string;
94
+ /** Pre-flight probe: pass false to disable instead of throwing on load failure. */
95
+ onLoadError?: (err: unknown) => void;
96
+ }
97
+
98
+ /**
99
+ * Production embedder: Transformers.js + bge-m3 (default; e5-base / e5-small
100
+ * via `model` option), fully local after the one-time download into
101
+ * `data/models/`. Loaded lazily on first use and reused across calls.
102
+ */
103
+ export class OnnxEmbedder implements Embedder {
104
+ readonly modelId: string;
105
+ readonly dims: number;
106
+ /** Calibrated cluster threshold for this model (see CLUSTER_THRESHOLDS). */
107
+ readonly suggestedClusterThreshold: number;
108
+ private extractor: any = null;
109
+ private loading: Promise<any> | null = null;
110
+
111
+ constructor(private options: OnnxEmbedderOptions = {}) {
112
+ const model = options.model ?? BGE_M3_MODEL_ID;
113
+ this.modelId = `${model}@${options.dtype ?? 'q8'}`;
114
+ const dims = MODEL_DIMS[model];
115
+ if (!dims) throw new Error(`unknown model dims for ${model} — extend MODEL_DIMS`);
116
+ this.dims = dims;
117
+ const threshold = CLUSTER_THRESHOLDS[model];
118
+ if (!threshold) throw new Error(`no calibrated cluster threshold for ${model} — calibrate first`);
119
+ this.suggestedClusterThreshold = threshold;
120
+ }
121
+
122
+ private async load() {
123
+ if (this.extractor) return this.extractor;
124
+ this.loading ??= (async () => {
125
+ const { pipeline, env } = await import('@huggingface/transformers');
126
+ env.cacheDir = this.options.cacheDir ?? modelCacheDirectory();
127
+ env.allowLocalModels = true;
128
+ const model = this.options.model ?? BGE_M3_MODEL_ID;
129
+ return pipeline('feature-extraction', model, { dtype: this.options.dtype ?? 'q8' });
130
+ })();
131
+ try {
132
+ this.extractor = await this.loading;
133
+ } catch (err) {
134
+ this.loading = null;
135
+ this.options.onLoadError?.(err);
136
+ throw err;
137
+ }
138
+ return this.extractor;
139
+ }
140
+
141
+ /** `kind` picks the e5 prefix: queries for search, passages for storage. */
142
+ /** e5 models require `query:`/`passage:` prefixes; bge models must NOT get them. */
143
+ private get usesE5Prefix(): boolean {
144
+ return (this.options.model ?? E5_BASE_MODEL_ID).includes('e5');
145
+ }
146
+
147
+ async embed(texts: string[], kind: 'query' | 'passage' = 'passage'): Promise<Float32Array[]> {
148
+ const extractor = await this.load();
149
+ const prefixed = this.usesE5Prefix ? texts.map((t) => `${kind}: ${t}`) : texts;
150
+ const out = await extractor(prefixed, { pooling: 'mean', normalize: true });
151
+ const dims = this.dims;
152
+ const flat = out.data as Float32Array;
153
+ const rows: Float32Array[] = [];
154
+ for (let i = 0; i < texts.length; i++) rows.push(flat.slice(i * dims, (i + 1) * dims));
155
+ return rows;
156
+ }
157
+ }