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