@myrialabs/clopen 0.4.25 → 0.4.27
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/backend/auth/permissions.ts +21 -0
- package/backend/bootstrap.ts +18 -1
- package/backend/chat/engine-handoff.test.ts +229 -0
- package/backend/chat/engine-handoff.ts +439 -0
- package/backend/chat/stream-manager.ts +200 -16
- package/backend/database/migrations/066_create_memory_graph.ts +369 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/audit-log-queries.test.ts +10 -1
- package/backend/database/queries/graph-queries.ts +1764 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/memory-queue-queries.ts +381 -0
- package/backend/database/queries/snapshot-queries.ts +20 -0
- package/backend/engine/README.md +45 -2
- package/backend/engine/adapters/copilot/stream.ts +37 -1
- package/backend/engine/adapters/pi/models.ts +19 -7
- package/backend/engine/adapters/pi/stream.ts +2 -1
- package/backend/engine/docs/adapter-contract.md +25 -8
- package/backend/engine/docs/adding-an-engine.md +40 -4
- package/backend/engine/docs/frontend-and-chat.md +66 -1
- package/backend/engine/docs/lessons-learned.md +165 -6
- package/backend/engine/docs/quick-reference.md +10 -0
- package/backend/engine/docs/stack.md +10 -0
- package/backend/engine/docs/websocket-routes.md +15 -1
- package/backend/engine/engine-setup.ts +1 -1
- package/backend/engine/index.test.ts +186 -0
- package/backend/engine/index.ts +117 -71
- package/backend/engine/install-recipes.test.ts +105 -0
- package/backend/engine/install-recipes.ts +4 -1
- package/backend/index.ts +9 -0
- package/backend/mcp/internal/config.ts +6 -0
- package/backend/mcp/internal/servers/index.ts +2 -0
- package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
- package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
- package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
- package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
- package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
- package/backend/memory/README.md +432 -0
- package/backend/memory/bootstrap.ts +101 -0
- package/backend/memory/compose.test.ts +198 -0
- package/backend/memory/compose.ts +343 -0
- package/backend/memory/config.ts +100 -0
- package/backend/memory/consolidate.ts +280 -0
- package/backend/memory/context.test.ts +321 -0
- package/backend/memory/context.ts +451 -0
- package/backend/memory/embedding/embedder.test.ts +141 -0
- package/backend/memory/embedding/embedder.ts +269 -0
- package/backend/memory/embedding/index.ts +17 -0
- package/backend/memory/embedding/install.ts +254 -0
- package/backend/memory/embedding/paths.ts +101 -0
- package/backend/memory/embedding/vector-cache.ts +270 -0
- package/backend/memory/extract/episodic.ts +725 -0
- package/backend/memory/extract/index.ts +133 -0
- package/backend/memory/extract/languages.ts +176 -0
- package/backend/memory/extract/scheduler.test.ts +352 -0
- package/backend/memory/extract/scheduler.ts +406 -0
- package/backend/memory/extract/structural.test.ts +215 -0
- package/backend/memory/extract/structural.ts +364 -0
- package/backend/memory/index.ts +37 -0
- package/backend/memory/indexer.ts +150 -0
- package/backend/memory/invalidate.ts +134 -0
- package/backend/memory/judge.ts +285 -0
- package/backend/memory/maintenance.ts +132 -0
- package/backend/memory/model.ts +91 -0
- package/backend/memory/notify.ts +102 -0
- package/backend/memory/readiness.ts +74 -0
- package/backend/memory/redact.test.ts +101 -0
- package/backend/memory/redact.ts +133 -0
- package/backend/memory/retention.ts +139 -0
- package/backend/memory/retrieval.eval.test.ts +301 -0
- package/backend/memory/retrieval.test.ts +1023 -0
- package/backend/memory/retrieval.ts +707 -0
- package/backend/memory/revise.test.ts +693 -0
- package/backend/memory/revise.ts +400 -0
- package/backend/memory/time.ts +31 -0
- package/backend/memory/view.ts +164 -0
- package/backend/shipped-runtime-imports.test.ts +228 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/memory/crud.ts +631 -0
- package/backend/ws/memory/index.ts +41 -0
- package/backend/ws/sessions/crud.ts +10 -0
- package/backend/ws/snapshot/content.ts +85 -0
- package/backend/ws/snapshot/index.ts +4 -1
- package/backend/ws/snapshot/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/main-CgmAFpU3.js +1036 -0
- package/dist/index.html +2 -2
- package/package.json +8 -2
- package/shared/types/database/connection.ts +9 -0
- package/shared/types/memory.ts +519 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-B0AA-88X.js +0 -622
- package/dist/assets/main-OsjA5Ab5.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Belief revision: keeping the graph's opinion of itself up to date.
|
|
3
|
+
*
|
|
4
|
+
* Migration 066 gave memory a place to accumulate. Accumulation alone produces a
|
|
5
|
+
* landfill — the decision made in March and the decision that reversed it in
|
|
6
|
+
* August both sit there, both get retrieved, and the agent re-adjudicates them
|
|
7
|
+
* on every single turn. The schema has carried `supersedes` and `contradicts`
|
|
8
|
+
* since the beginning and nothing ever wrote one.
|
|
9
|
+
*
|
|
10
|
+
* The judgement is made by the model that is ALREADY summarising the turn. That
|
|
11
|
+
* is the design constraint that makes this affordable: extraction is handed the
|
|
12
|
+
* memories the graph already holds about this topic, with their ids, and returns
|
|
13
|
+
* `supersedes` / `duplicateOf` alongside the new memories. No second model call,
|
|
14
|
+
* and the adjudication is better informed than a separate pass would be, because
|
|
15
|
+
* it happens with the transcript in view.
|
|
16
|
+
*
|
|
17
|
+
* Three mechanisms, applied in order of confidence:
|
|
18
|
+
*
|
|
19
|
+
* 1. **Exact identity** (`digest`) — the same claim, same words. Handled by
|
|
20
|
+
* the upsert in graph-queries; reinforces, never duplicates.
|
|
21
|
+
* 2. **Semantic near-duplicate** (cosine, here) — the same claim, different
|
|
22
|
+
* words. This is the one that decides whether the graph is still usable
|
|
23
|
+
* after six months, because a model rephrases the same fact every time it
|
|
24
|
+
* sees it and exact identity catches none of that.
|
|
25
|
+
* 3. **Contradiction** (the model, here) — a DIFFERENT claim about the same
|
|
26
|
+
* thing. Only a reader of the turn can tell this from a near-duplicate.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { entityKeyFor, graphQueries } from '$backend/database/queries/graph-queries';
|
|
30
|
+
import { getDatabase } from '$backend/database';
|
|
31
|
+
import { debug } from '$shared/utils/logger';
|
|
32
|
+
import { cosineToPacked, embedder, unpackVector } from './embedding';
|
|
33
|
+
import { EMBEDDING_VERSION } from './embedding/paths';
|
|
34
|
+
import { retrieve } from './retrieval';
|
|
35
|
+
import type { GraphNode, GraphScope, MemoryVerdict } from '$shared/types/memory';
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Cosine floor for CANDIDATE GENERATION — not for deciding anything.
|
|
39
|
+
*
|
|
40
|
+
* The threshold this replaces tried to answer "are these the same claim" with a
|
|
41
|
+
* similarity score, and the measurements say no score can. Against the shipped
|
|
42
|
+
* artifact, on labelled pairs:
|
|
43
|
+
*
|
|
44
|
+
* same claim, reworded 0.63 – 0.77
|
|
45
|
+
* opposite claim 0.70 – 0.99
|
|
46
|
+
* different claim 0.11 – 0.92
|
|
47
|
+
*
|
|
48
|
+
* Every genuine duplicate scores BELOW the median opposite. "User prefers to use
|
|
49
|
+
* the agent tool" against "…prefers not to use the agent tool" scores 0.9938,
|
|
50
|
+
* because a mean-pooled static embedding has no representation for negation;
|
|
51
|
+
* "Run bun run check after coding" against "Run bun run lint after coding" scores
|
|
52
|
+
* 0.9202 while making two different claims. On the real graph the shipped 0.85
|
|
53
|
+
* rule matched 2 pairs out of 5,356 — and one of those two was a wrong merge —
|
|
54
|
+
* while five near-identical copies of "Arga is a full-stack developer" sat at
|
|
55
|
+
* 0.76 and were kept, filling the recall budget for months.
|
|
56
|
+
*
|
|
57
|
+
* The same twelve pairs put to the extraction model: 11 of 12 correct on the
|
|
58
|
+
* harder THREE-way question, against 6 of 12 for cosine on the easier two-way
|
|
59
|
+
* one. So cosine keeps the job it is good at — pulling a handful of plausible
|
|
60
|
+
* neighbours out of thousands — and the model, which is already being called to
|
|
61
|
+
* summarise the turn, makes the call.
|
|
62
|
+
*/
|
|
63
|
+
const CANDIDATE_FLOOR = 0.6;
|
|
64
|
+
|
|
65
|
+
/** Existing memories shown to the extraction model for adjudication. */
|
|
66
|
+
const MAX_RELATED_SHOWN = 12;
|
|
67
|
+
|
|
68
|
+
/** Neighbours offered per new memory for the same/opposite/different decision. */
|
|
69
|
+
const MAX_CANDIDATES_PER_MEMORY = 5;
|
|
70
|
+
|
|
71
|
+
/** Candidate vectors scanned when looking for neighbours. */
|
|
72
|
+
const MAX_DUPLICATE_CANDIDATES = 4_000;
|
|
73
|
+
|
|
74
|
+
export interface RelatedMemory {
|
|
75
|
+
id: string;
|
|
76
|
+
subkind: string;
|
|
77
|
+
scope: GraphScope;
|
|
78
|
+
label: string;
|
|
79
|
+
body: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Memories the graph already holds that bear on this turn.
|
|
84
|
+
*
|
|
85
|
+
* Retrieved with the same engine agents use, against the transcript rather than
|
|
86
|
+
* against a single message: the point is to surface anything the turn might
|
|
87
|
+
* contradict, and a contradiction can be buried anywhere in it.
|
|
88
|
+
*/
|
|
89
|
+
export function gatherRelatedMemories(options: {
|
|
90
|
+
transcript: string;
|
|
91
|
+
projectId: string | null;
|
|
92
|
+
sessionId: string | null;
|
|
93
|
+
}): RelatedMemory[] {
|
|
94
|
+
// The tail carries the turn's conclusions, which is where a reversal lives.
|
|
95
|
+
const query = options.transcript.slice(-4_000);
|
|
96
|
+
|
|
97
|
+
const { hits } = retrieve({
|
|
98
|
+
query,
|
|
99
|
+
projectId: options.projectId,
|
|
100
|
+
sessionId: options.sessionId ?? undefined,
|
|
101
|
+
kinds: ['episodic'],
|
|
102
|
+
limit: MAX_RELATED_SHOWN,
|
|
103
|
+
expandHops: 0
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
return hits
|
|
107
|
+
// A memory the graph is barely confident in is not worth asking the model to
|
|
108
|
+
// adjudicate against, and every line shown costs prompt budget.
|
|
109
|
+
.filter(hit => hit.node.confidence >= 0.25)
|
|
110
|
+
.map(hit => ({
|
|
111
|
+
id: hit.node.id,
|
|
112
|
+
subkind: hit.node.subkind,
|
|
113
|
+
scope: hit.node.scope,
|
|
114
|
+
label: hit.node.label,
|
|
115
|
+
body: hit.node.body.split('\n')[0].slice(0, 200)
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Render the related memories for the extraction prompt. */
|
|
120
|
+
export function renderRelatedMemories(related: RelatedMemory[]): string {
|
|
121
|
+
if (related.length === 0) return '- (nothing related is stored yet)';
|
|
122
|
+
return related
|
|
123
|
+
.map(memory => `- [${memory.id}] (${memory.subkind}, ${memory.scope}) ${memory.label}${memory.body ? ` — ${memory.body}` : ''}`)
|
|
124
|
+
.join('\n');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Neighbours a new memory might be restating or contradicting.
|
|
129
|
+
*
|
|
130
|
+
* RECALL, not precision. Everything above `CANDIDATE_FLOOR` is offered to the
|
|
131
|
+
* model, which decides what each of them actually is; a candidate that turns out
|
|
132
|
+
* to be unrelated costs a line of prompt, while a missed one costs a duplicate
|
|
133
|
+
* or an undetected contradiction.
|
|
134
|
+
*
|
|
135
|
+
* `extra` carries memories written EARLIER IN THE SAME EXTRACTION. Vector
|
|
136
|
+
* indexing is scheduled rather than synchronous, so a memory written moments ago
|
|
137
|
+
* has no row in `graph_vectors` yet and was invisible to the check meant to
|
|
138
|
+
* catch it. Measured: one turn about a Svelte gotcha produced three memories
|
|
139
|
+
* stating the same rule, two of them at cosine 0.8955 — above even the old
|
|
140
|
+
* threshold — and all three were stored, because none of them could see the
|
|
141
|
+
* others.
|
|
142
|
+
*
|
|
143
|
+
* Returns an empty list when the embedder is not loaded. Without vectors there
|
|
144
|
+
* is no way to recognise a rephrasing, and guessing from string overlap would
|
|
145
|
+
* offer memories that share vocabulary but not meaning.
|
|
146
|
+
*/
|
|
147
|
+
export function findRelatedCandidates(options: {
|
|
148
|
+
text: string;
|
|
149
|
+
subkind: string;
|
|
150
|
+
projectId: string | null;
|
|
151
|
+
excludeId?: string;
|
|
152
|
+
/** Nodes not yet in `graph_vectors` — this extraction's own earlier writes. */
|
|
153
|
+
extra?: { node: GraphNode; vector: Float32Array }[];
|
|
154
|
+
}): { node: GraphNode; score: number }[] {
|
|
155
|
+
const query = embedder.embed(options.text, { minTokens: 6 });
|
|
156
|
+
if (!query) return [];
|
|
157
|
+
|
|
158
|
+
const scored: { node: GraphNode; score: number }[] = [];
|
|
159
|
+
|
|
160
|
+
for (const candidate of options.extra ?? []) {
|
|
161
|
+
if (candidate.node.id === options.excludeId) continue;
|
|
162
|
+
if (candidate.node.subkind !== options.subkind) continue;
|
|
163
|
+
const score = cosine(query, candidate.vector);
|
|
164
|
+
if (score >= CANDIDATE_FLOOR) scored.push({ node: candidate.node, score });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
const rows = getDatabase()
|
|
169
|
+
.prepare(
|
|
170
|
+
`SELECT v.node_id AS id, v.vec AS vec
|
|
171
|
+
FROM graph_vectors v
|
|
172
|
+
INNER JOIN graph_nodes n ON n.id = v.node_id
|
|
173
|
+
WHERE v.model = ? AND v.dim = ?
|
|
174
|
+
AND n.kind = 'episodic' AND n.subkind = ?
|
|
175
|
+
AND n.archived_at IS NULL AND n.superseded_by IS NULL
|
|
176
|
+
AND COALESCE(n.project_id, '') = COALESCE(?, '')
|
|
177
|
+
ORDER BY n.weight DESC, n.updated_at DESC
|
|
178
|
+
LIMIT ?`
|
|
179
|
+
)
|
|
180
|
+
.all(EMBEDDING_VERSION, query.length, options.subkind, options.projectId, MAX_DUPLICATE_CANDIDATES) as {
|
|
181
|
+
id: string;
|
|
182
|
+
vec: Uint8Array;
|
|
183
|
+
}[];
|
|
184
|
+
|
|
185
|
+
const seen = new Set(scored.map(entry => entry.node.id));
|
|
186
|
+
for (const row of rows) {
|
|
187
|
+
if (row.id === options.excludeId || seen.has(row.id)) continue;
|
|
188
|
+
const score = cosineToPacked(query, row.vec);
|
|
189
|
+
if (score < CANDIDATE_FLOOR) continue;
|
|
190
|
+
const node = graphQueries.getById(row.id);
|
|
191
|
+
if (node) scored.push({ node, score });
|
|
192
|
+
}
|
|
193
|
+
} catch (error) {
|
|
194
|
+
debug.warn('memory', 'Candidate lookup failed', error);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return scored.sort((a, b) => b.score - a.score).slice(0, MAX_CANDIDATES_PER_MEMORY);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function cosine(a: Float32Array, b: Float32Array): number {
|
|
201
|
+
let dot = 0;
|
|
202
|
+
let na = 0;
|
|
203
|
+
let nb = 0;
|
|
204
|
+
for (let i = 0; i < a.length; i++) {
|
|
205
|
+
dot += a[i] * b[i];
|
|
206
|
+
na += a[i] * a[i];
|
|
207
|
+
nb += b[i] * b[i];
|
|
208
|
+
}
|
|
209
|
+
const denom = Math.sqrt(na) * Math.sqrt(nb);
|
|
210
|
+
return denom === 0 ? 0 : dot / denom;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Record the disagreements the model found, without acting on them.
|
|
215
|
+
*
|
|
216
|
+
* This used to call `supersede`, which removed the older memory from every
|
|
217
|
+
* future recall on the strength of one model reading one turn. Measured, that
|
|
218
|
+
* retired a hand-written standing prohibition in one run out of two, on the
|
|
219
|
+
* basis of a task-local exception whose own body said it might be "a specific
|
|
220
|
+
* exception for this task". The judgement was not obviously wrong — the evidence
|
|
221
|
+
* genuinely was ambiguous — but the ACTION was irreversible in practice, because
|
|
222
|
+
* nobody audits a store that appears to be working.
|
|
223
|
+
*
|
|
224
|
+
* A `contradicts` edge keeps the same information and defers the decision to the
|
|
225
|
+
* read path, which re-makes it every turn under a rule with no model in it (see
|
|
226
|
+
* `resolveConflicts` in retrieval.ts). The write path's job is to notice; the
|
|
227
|
+
* read path's job is to choose.
|
|
228
|
+
*
|
|
229
|
+
* `candidateIds` is the set the model was actually shown. An id outside it was
|
|
230
|
+
* hallucinated or copied from somewhere else, and acting on it would draw a
|
|
231
|
+
* relation to a memory the model never read.
|
|
232
|
+
*/
|
|
233
|
+
export function recordContradictions(newNodeId: string, contradictedIds: string[], candidateIds: Set<string>): number {
|
|
234
|
+
let applied = 0;
|
|
235
|
+
for (const oldId of contradictedIds) {
|
|
236
|
+
if (!candidateIds.has(oldId) || oldId === newNodeId) continue;
|
|
237
|
+
try {
|
|
238
|
+
if (graphQueries.contradict(newNodeId, oldId)) applied++;
|
|
239
|
+
} catch (error) {
|
|
240
|
+
debug.warn('memory', `Failed to record contradiction with ${oldId}`, error);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (applied > 0) debug.log('memory', `Recorded ${applied} contradiction(s)`);
|
|
244
|
+
return applied;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Record what the turn did with the memories it was given.
|
|
249
|
+
*
|
|
250
|
+
* Same containment rule as supersession: only ids that were genuinely injected
|
|
251
|
+
* are accepted, so a model cannot down-rank a memory it was never shown.
|
|
252
|
+
*/
|
|
253
|
+
export function applyFeedback(verdicts: { id: string; verdict: MemoryVerdict }[], injectedIds: Set<string>): number {
|
|
254
|
+
let applied = 0;
|
|
255
|
+
for (const entry of verdicts) {
|
|
256
|
+
if (!entry?.id || !injectedIds.has(entry.id)) continue;
|
|
257
|
+
if (entry.verdict !== 'used' && entry.verdict !== 'wrong' && entry.verdict !== 'ignored') continue;
|
|
258
|
+
try {
|
|
259
|
+
graphQueries.recordFeedback(entry.id, entry.verdict);
|
|
260
|
+
applied++;
|
|
261
|
+
} catch (error) {
|
|
262
|
+
debug.warn('memory', `Failed to record feedback for ${entry.id}`, error);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return applied;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Record the people, tools and systems a memory is about.
|
|
270
|
+
*
|
|
271
|
+
* The purpose is unchanged and still right: "Arga prefers Svelte", "Arga works
|
|
272
|
+
* in TypeScript" and "Arga is based in Indonesia" must be findable together
|
|
273
|
+
* rather than being three islands that cosine has to rediscover — and cosine
|
|
274
|
+
* between two short sentences about the same person is not reliably higher than
|
|
275
|
+
* between two about different people.
|
|
276
|
+
*
|
|
277
|
+
* WHAT CHANGED is that they are an ATTRIBUTE now rather than a node, and the
|
|
278
|
+
* measurements are not close. On a graph built by asking "what is this project?"
|
|
279
|
+
* in 84 repositories, 115 of 208 episodic nodes were entity stubs with an empty
|
|
280
|
+
* body, and `about` pointed at a stub 220 times against 6 times at a file — so
|
|
281
|
+
* the graph was not "memories about code", it was "memories about the names of
|
|
282
|
+
* technologies". They duplicated on spelling ("Myria Labs" / "MyriaLabs",
|
|
283
|
+
* "Express" / "Express.js", "Vue" / "Vue 3"). And an empty body is below
|
|
284
|
+
* `MIN_TOKENS_FOR_VECTOR`, so a stub could never be found semantically while
|
|
285
|
+
* still being offered to the model to adjudicate against — which produced a
|
|
286
|
+
* `contradicts` edge between a real memory and the bare string "ClickTrainer
|
|
287
|
+
* Platform". A name is not a claim; it cannot agree or disagree with one.
|
|
288
|
+
*
|
|
289
|
+
* As a row in `graph_node_entities` joined into the FTS text, "what do we know
|
|
290
|
+
* about Bun" is an index lookup that returns the memories directly, instead of a
|
|
291
|
+
* hop through a hub whose forty edges made it contribute almost nothing anyway
|
|
292
|
+
* (see `SPREAD_DAMPING` in retrieval.ts).
|
|
293
|
+
*/
|
|
294
|
+
export function linkEntities(memoryNodeId: string, names: string[]): number {
|
|
295
|
+
const entities: { key: string; name: string }[] = [];
|
|
296
|
+
for (const raw of names.slice(0, 8)) {
|
|
297
|
+
const name = String(raw ?? '').trim();
|
|
298
|
+
const key = entityKeyFor(name);
|
|
299
|
+
if (!key) continue;
|
|
300
|
+
if (entities.some(entry => entry.key === key)) continue;
|
|
301
|
+
entities.push({ key, name: name.slice(0, 140) });
|
|
302
|
+
}
|
|
303
|
+
if (entities.length === 0) return 0;
|
|
304
|
+
|
|
305
|
+
try {
|
|
306
|
+
return graphQueries.setEntities(memoryNodeId, entities);
|
|
307
|
+
} catch (error) {
|
|
308
|
+
debug.warn('memory', `Failed to record entities for ${memoryNodeId}`, error);
|
|
309
|
+
return 0;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Pairs of live memories that MIGHT be saying the same thing, for a model to
|
|
315
|
+
* adjudicate on the maintenance timer.
|
|
316
|
+
*
|
|
317
|
+
* This replaces a pass that merged them itself, by cosine, keeping whichever was
|
|
318
|
+
* updated more recently. Every part of that was wrong at once: cosine cannot
|
|
319
|
+
* tell a restatement from a reversal (the reversal scores HIGHER — 0.99 against
|
|
320
|
+
* 0.76 for a genuine duplicate), and "most recently updated wins" meant a rule
|
|
321
|
+
* and its opposite could be silently collapsed into whichever had been touched
|
|
322
|
+
* last, with no record that the other had existed. On the real graph the pass
|
|
323
|
+
* matched two pairs out of 5,356 and one of the two was a wrong merge, so what
|
|
324
|
+
* it actually did was nothing, occasionally destructively.
|
|
325
|
+
*
|
|
326
|
+
* Returning candidates instead moves the decision to `consolidate.ts`, which
|
|
327
|
+
* already has a model call on the maintenance path.
|
|
328
|
+
*
|
|
329
|
+
* Bounded per call, because it is O(n²) and runs on a timer rather than on any
|
|
330
|
+
* path a user waits on.
|
|
331
|
+
*/
|
|
332
|
+
export function findDuplicateCandidates(limit = 200): { a: GraphNode; b: GraphNode; score: number }[] {
|
|
333
|
+
if (!embedder.ready) return [];
|
|
334
|
+
|
|
335
|
+
const pairs: { a: GraphNode; b: GraphNode; score: number }[] = [];
|
|
336
|
+
try {
|
|
337
|
+
const rows = getDatabase()
|
|
338
|
+
.prepare(
|
|
339
|
+
`SELECT n.id AS id, n.subkind AS subkind, n.project_id AS project_id, v.vec AS vec
|
|
340
|
+
FROM graph_nodes n
|
|
341
|
+
INNER JOIN graph_vectors v ON v.node_id = n.id AND v.model = ?
|
|
342
|
+
WHERE n.kind = 'episodic' AND n.archived_at IS NULL AND n.superseded_by IS NULL
|
|
343
|
+
AND n.entity_key IS NULL AND n.pinned = 0
|
|
344
|
+
ORDER BY n.updated_at DESC
|
|
345
|
+
LIMIT ?`
|
|
346
|
+
)
|
|
347
|
+
.all(EMBEDDING_VERSION, limit) as {
|
|
348
|
+
id: string;
|
|
349
|
+
subkind: string;
|
|
350
|
+
project_id: string | null;
|
|
351
|
+
vec: Uint8Array;
|
|
352
|
+
}[];
|
|
353
|
+
|
|
354
|
+
const paired = new Set<string>();
|
|
355
|
+
for (let i = 0; i < rows.length; i++) {
|
|
356
|
+
const a = rows[i];
|
|
357
|
+
if (paired.has(a.id)) continue;
|
|
358
|
+
|
|
359
|
+
for (let j = i + 1; j < rows.length; j++) {
|
|
360
|
+
const b = rows[j];
|
|
361
|
+
if (paired.has(b.id)) continue;
|
|
362
|
+
if (b.subkind !== a.subkind) continue;
|
|
363
|
+
if ((b.project_id ?? '') !== (a.project_id ?? '')) continue;
|
|
364
|
+
|
|
365
|
+
// Both are packed int8 vectors; unpack one side to score them.
|
|
366
|
+
const score = cosineToPacked(unpackVector(a.vec), b.vec);
|
|
367
|
+
if (score < CANDIDATE_FLOOR) continue;
|
|
368
|
+
|
|
369
|
+
const nodeA = graphQueries.getById(a.id);
|
|
370
|
+
const nodeB = graphQueries.getById(b.id);
|
|
371
|
+
if (!nodeA || !nodeB) continue;
|
|
372
|
+
pairs.push({ a: nodeA, b: nodeB, score });
|
|
373
|
+
paired.add(a.id);
|
|
374
|
+
paired.add(b.id);
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
} catch (error) {
|
|
379
|
+
debug.warn('memory', 'Duplicate candidate scan failed', error);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return pairs;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Merge `loser` into `winner` after something has decided they state the same
|
|
387
|
+
* claim.
|
|
388
|
+
*
|
|
389
|
+
* Uses `supersede`, so the authority and durability guards apply: a merge that
|
|
390
|
+
* would retire a person's memory behind a model's is refused there rather than
|
|
391
|
+
* here, and the pair simply stays as two memories.
|
|
392
|
+
*/
|
|
393
|
+
export function mergeDuplicate(winnerId: string, loserId: string): boolean {
|
|
394
|
+
try {
|
|
395
|
+
return graphQueries.supersede(loserId, winnerId);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
debug.warn('memory', `Failed to merge ${loserId} into ${winnerId}`, error);
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading SQLite timestamps as the UTC they actually are.
|
|
3
|
+
*
|
|
4
|
+
* `CURRENT_TIMESTAMP` writes `YYYY-MM-DD HH:MM:SS` in UTC, with no zone marker.
|
|
5
|
+
* Handed to `Date.parse`, that string is not ISO-8601, so V8 falls back to its
|
|
6
|
+
* legacy parser and interprets it as LOCAL time. On a machine at UTC+7 every row
|
|
7
|
+
* therefore reads as seven hours in the future: `Date.now() - parsed` is
|
|
8
|
+
* negative, every age is understated by the offset, and the `Math.max(0, …)`
|
|
9
|
+
* that guards against a negative age hides the whole thing — a memory written
|
|
10
|
+
* this morning simply looks brand new all day.
|
|
11
|
+
*
|
|
12
|
+
* Nothing crashes, which is why it survived: retrieval's recency term stays
|
|
13
|
+
* pinned at its maximum for the length of the offset, and consolidation's
|
|
14
|
+
* "at least seven days old" gate silently means seven days and seven hours.
|
|
15
|
+
* Appending the zone is the entire fix.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Milliseconds since the epoch for a SQLite `datetime` value, or NaN. */
|
|
19
|
+
export function parseSqliteTime(value: string | null | undefined): number {
|
|
20
|
+
if (!value) return Number.NaN;
|
|
21
|
+
// Already carries a zone or a `T` separator (an ISO value from elsewhere).
|
|
22
|
+
if (value.includes('T') || value.endsWith('Z')) return Date.parse(value);
|
|
23
|
+
return Date.parse(`${value.replace(' ', 'T')}Z`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Age of a SQLite timestamp in days, never negative, 0 when unparseable. */
|
|
27
|
+
export function ageInDays(value: string | null | undefined): number {
|
|
28
|
+
const parsed = parseSqliteTime(value);
|
|
29
|
+
if (Number.isNaN(parsed)) return 0;
|
|
30
|
+
return Math.max(0, (Date.now() - parsed) / 86_400_000);
|
|
31
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph view assembly for the visualization.
|
|
3
|
+
*
|
|
4
|
+
* Community detection runs HERE, not in the browser. Louvain is O(n log n)-ish
|
|
5
|
+
* but iterative, and running it on the client would compete with the force
|
|
6
|
+
* simulation for the same main thread on exactly the low-powered devices this
|
|
7
|
+
* has to stay usable on. It is also stable per dataset, so computing it server
|
|
8
|
+
* side lets the result be sent once instead of recomputed on every mount.
|
|
9
|
+
*
|
|
10
|
+
* Communities are what make the view legible: each becomes a coloured "lobe", so
|
|
11
|
+
* the clustering the user sees comes out of their own memory's structure rather
|
|
12
|
+
* than being imposed by a layout algorithm.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import Graph from 'graphology';
|
|
16
|
+
import louvain from 'graphology-communities-louvain';
|
|
17
|
+
import { graphQueries } from '$backend/database/queries/graph-queries';
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
import type {
|
|
20
|
+
GraphNodeKind,
|
|
21
|
+
GraphScope,
|
|
22
|
+
GraphSource,
|
|
23
|
+
GraphView,
|
|
24
|
+
GraphViewEdge,
|
|
25
|
+
GraphViewNode
|
|
26
|
+
} from '$shared/types/memory';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Nodes sent to the client at once.
|
|
30
|
+
*
|
|
31
|
+
* Beyond a few thousand, a force layout stops communicating structure — it
|
|
32
|
+
* becomes a hairball — and the payload starts costing more than it explains. The
|
|
33
|
+
* cap is reported through `truncated` so the UI can say so rather than implying
|
|
34
|
+
* the graph is smaller than it is.
|
|
35
|
+
*/
|
|
36
|
+
const MAX_VIEW_NODES = 3_000;
|
|
37
|
+
|
|
38
|
+
export interface GraphViewFilter {
|
|
39
|
+
/** `undefined` = every project (cross-project view); `null` = global only. */
|
|
40
|
+
projectId?: string | null;
|
|
41
|
+
/** The multi-select's answer: absent = every project, empty = global only. */
|
|
42
|
+
projectIds?: string[];
|
|
43
|
+
kinds?: GraphNodeKind[];
|
|
44
|
+
/** Narrow to particular subkinds — decisions only, failures only, and so on. */
|
|
45
|
+
subkinds?: string[];
|
|
46
|
+
scopes?: GraphScope[];
|
|
47
|
+
/** Narrow by who wrote it: inferred, agent-requested, or hand-written. */
|
|
48
|
+
sources?: GraphSource[];
|
|
49
|
+
includeArchived?: boolean;
|
|
50
|
+
/** Show memories that have been replaced by a newer belief. Off by default. */
|
|
51
|
+
includeSuperseded?: boolean;
|
|
52
|
+
limit?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function buildGraphView(filter: GraphViewFilter): GraphView {
|
|
56
|
+
const limit = Math.min(filter.limit ?? MAX_VIEW_NODES, MAX_VIEW_NODES);
|
|
57
|
+
|
|
58
|
+
// `list` orders by pinned, then weight, then recency — so when the cap bites,
|
|
59
|
+
// what survives is what the user reinforced and touched most recently.
|
|
60
|
+
const nodes = graphQueries.list({ ...filter, limit });
|
|
61
|
+
const totalNodes = graphQueries.count(filter);
|
|
62
|
+
|
|
63
|
+
if (nodes.length === 0) {
|
|
64
|
+
return { nodes: [], edges: [], totalNodes, truncated: false };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const ids = nodes.map(n => n.id);
|
|
68
|
+
const stored = graphQueries.edgesWithin(ids);
|
|
69
|
+
|
|
70
|
+
// Two memories about the same subject ARE connected, and that connection is
|
|
71
|
+
// stated by extraction rather than inferred from how they are worded. It is
|
|
72
|
+
// derived here rather than stored, so it can never outlive the claim it came
|
|
73
|
+
// from — see `derivedEntityEdges`.
|
|
74
|
+
//
|
|
75
|
+
// Without it the episodic half has almost no structure at all. Similarity
|
|
76
|
+
// linking used to supply it, badly: on a real graph 144 of 371 edges were
|
|
77
|
+
// fabricated by cosine over a corpus with no variance. Removing that was right
|
|
78
|
+
// and removing it ALONE was not — the view became ninety-three disconnected
|
|
79
|
+
// dots, which is a less honest picture than the wrong one, because these
|
|
80
|
+
// memories genuinely do belong together.
|
|
81
|
+
const derived: GraphViewEdge[] = graphQueries.derivedEdges(ids).map((edge, index) => ({
|
|
82
|
+
// Negative ids, so nothing can mistake a derived edge for a stored row and
|
|
83
|
+
// try to delete or re-weight it.
|
|
84
|
+
id: -(index + 1),
|
|
85
|
+
source: edge.srcId,
|
|
86
|
+
target: edge.dstId,
|
|
87
|
+
rel: 'relates_to' as const,
|
|
88
|
+
weight: edge.weight
|
|
89
|
+
}));
|
|
90
|
+
|
|
91
|
+
// Undirected for community detection: `about` and `imports` point one way, but
|
|
92
|
+
// whether two nodes belong to the same cluster does not depend on direction,
|
|
93
|
+
// and treating them as directed splits obvious groups in half.
|
|
94
|
+
const graph = new Graph({ type: 'undirected', multi: false });
|
|
95
|
+
for (const node of nodes) graph.addNode(node.id);
|
|
96
|
+
|
|
97
|
+
const degree = new Map<string, number>();
|
|
98
|
+
const link = (srcId: string, dstId: string, weight: number): void => {
|
|
99
|
+
degree.set(srcId, (degree.get(srcId) ?? 0) + 1);
|
|
100
|
+
degree.set(dstId, (degree.get(dstId) ?? 0) + 1);
|
|
101
|
+
if (srcId === dstId) return;
|
|
102
|
+
if (!graph.hasNode(srcId) || !graph.hasNode(dstId)) return;
|
|
103
|
+
if (!graph.hasEdge(srcId, dstId)) graph.addUndirectedEdge(srcId, dstId, { weight });
|
|
104
|
+
};
|
|
105
|
+
for (const edge of stored) link(edge.srcId, edge.dstId, edge.weight);
|
|
106
|
+
for (const edge of derived) link(edge.source, edge.target, edge.weight);
|
|
107
|
+
|
|
108
|
+
let communities: Record<string, number> = {};
|
|
109
|
+
try {
|
|
110
|
+
// Louvain needs at least one edge; an edgeless graph leaves every node in
|
|
111
|
+
// its own community, which is also the honest answer.
|
|
112
|
+
if (graph.size > 0) {
|
|
113
|
+
communities = louvain(graph, { getEdgeWeight: 'weight' });
|
|
114
|
+
}
|
|
115
|
+
} catch (error) {
|
|
116
|
+
// A failed clustering must not cost the user their graph — the view just
|
|
117
|
+
// renders in one colour.
|
|
118
|
+
debug.warn('memory', 'Community detection failed; rendering without lobes', error);
|
|
119
|
+
communities = {};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const viewNodes: GraphViewNode[] = nodes.map(node => ({
|
|
123
|
+
id: node.id,
|
|
124
|
+
kind: node.kind,
|
|
125
|
+
subkind: node.subkind,
|
|
126
|
+
scope: node.scope,
|
|
127
|
+
label: node.label,
|
|
128
|
+
projectId: node.projectId,
|
|
129
|
+
degree: degree.get(node.id) ?? 0,
|
|
130
|
+
weight: node.weight,
|
|
131
|
+
pinned: node.pinned,
|
|
132
|
+
community: communities[node.id] ?? 0,
|
|
133
|
+
createdAt: node.createdAt
|
|
134
|
+
}));
|
|
135
|
+
|
|
136
|
+
const viewEdges: GraphViewEdge[] = [
|
|
137
|
+
...stored.map(edge => ({
|
|
138
|
+
id: edge.id,
|
|
139
|
+
source: edge.srcId,
|
|
140
|
+
target: edge.dstId,
|
|
141
|
+
rel: edge.rel,
|
|
142
|
+
weight: edge.weight
|
|
143
|
+
})),
|
|
144
|
+
...derived
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
nodes: viewNodes,
|
|
149
|
+
edges: viewEdges,
|
|
150
|
+
totalNodes,
|
|
151
|
+
truncated: totalNodes > nodes.length
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A node plus the nodes it reaches — what the inspector renders. */
|
|
156
|
+
export function buildNodeDetail(nodeId: string, hops = 1) {
|
|
157
|
+
const node = graphQueries.getById(nodeId);
|
|
158
|
+
if (!node) return null;
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
node,
|
|
162
|
+
neighbours: graphQueries.neighbours(nodeId, hops).map(n => ({ node: n.node, hops: n.hops }))
|
|
163
|
+
};
|
|
164
|
+
}
|