@myrialabs/clopen 0.4.26 → 0.4.28
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/claude/message-converter.ts +5 -24
- 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/engine/claude/accounts.ts +4 -12
- package/backend/ws/engine/codex/accounts.ts +4 -13
- package/backend/ws/engine/pty-output.test.ts +37 -0
- package/backend/ws/engine/pty-output.ts +43 -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/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
- package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
- package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
- package/dist/assets/main-BrqMMMRX.css +1 -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-Dh-MTGNR.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
# Memory Graph
|
|
2
|
+
|
|
3
|
+
Persistent memory for Clopen. One SQLite graph holding what past sessions decided
|
|
4
|
+
and what the codebase looks like, shared by every engine, retrieved locally with
|
|
5
|
+
no model call and no service to run.
|
|
6
|
+
|
|
7
|
+
Clopen otherwise forgets everything between sessions: each conversation re-derives
|
|
8
|
+
what was already settled, and switching engine loses it entirely.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Table of Contents
|
|
13
|
+
|
|
14
|
+
- [The Shape of It](#the-shape-of-it)
|
|
15
|
+
- [Two Halves, One Store](#two-halves-one-store)
|
|
16
|
+
- [Reading: How Retrieval Works](#reading-how-retrieval-works)
|
|
17
|
+
- [Writing: How Memories Get In](#writing-how-memories-get-in)
|
|
18
|
+
- [Keeping the Graph Honest](#keeping-the-graph-honest)
|
|
19
|
+
- [The Embedding Artifact](#the-embedding-artifact)
|
|
20
|
+
- [Readiness and Setup](#readiness-and-setup)
|
|
21
|
+
- [Agent Access (MCP)](#agent-access-mcp)
|
|
22
|
+
- [Configuration](#configuration)
|
|
23
|
+
- [Schema](#schema)
|
|
24
|
+
- [File Map](#file-map)
|
|
25
|
+
- [Testing](#testing)
|
|
26
|
+
- [Design Decisions Worth Knowing](#design-decisions-worth-knowing)
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## The Shape of It
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
a turn finishes
|
|
34
|
+
│
|
|
35
|
+
├── snapshot disk diff ──→ structural extraction ──┐
|
|
36
|
+
│ │
|
|
37
|
+
└── transcript ──→ episodic extraction (model) ────┤
|
|
38
|
+
▼
|
|
39
|
+
┌─────────────┐
|
|
40
|
+
│ graph_nodes │
|
|
41
|
+
│ graph_edges │
|
|
42
|
+
└──────┬──────┘
|
|
43
|
+
│
|
|
44
|
+
┌──────────────────┴─────────┐
|
|
45
|
+
▼ ▼
|
|
46
|
+
graph_nodes_fts graph_vectors
|
|
47
|
+
(BM25) (int8, local)
|
|
48
|
+
│ │
|
|
49
|
+
└────────── RRF ─────────────┘
|
|
50
|
+
│
|
|
51
|
+
spreading activation, 1 hop
|
|
52
|
+
│
|
|
53
|
+
▼
|
|
54
|
+
injected into the next turn's prompt
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Nothing on the read path calls a model or touches the network.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Two Halves, One Store
|
|
62
|
+
|
|
63
|
+
| Kind | Holds | Written by |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `episodic` | decisions, patterns, failures, preferences, observations | a model reading each finished turn |
|
|
66
|
+
| `structural` | files, symbols, modules, dependencies | the snapshot service's disk diff |
|
|
67
|
+
|
|
68
|
+
They live in **one** graph, joined by an `about` edge. That join is the whole
|
|
69
|
+
point: asking "what touches this module" also surfaces the decisions made around
|
|
70
|
+
it, and asking "what did we decide about X" surfaces the code it governs.
|
|
71
|
+
|
|
72
|
+
Structural nodes come from the **disk diff**, not from tool calls, so a file
|
|
73
|
+
rewritten through Bash or a codemod is captured as reliably as one edited with an
|
|
74
|
+
edit tool.
|
|
75
|
+
|
|
76
|
+
Structural hits are deliberately excluded from the injected block — an agent can
|
|
77
|
+
read the repository itself. They earn their place by being the path retrieval
|
|
78
|
+
*travels* to reach the relevant episodic memories.
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## Reading: How Retrieval Works
|
|
83
|
+
|
|
84
|
+
`retrieval.ts` runs two channels on every query and fuses them with Reciprocal
|
|
85
|
+
Rank Fusion, weighted by whether the query reads as an identifier or as prose.
|
|
86
|
+
|
|
87
|
+
- **BM25** (`graph_nodes_fts`) finds identifiers, paths and error strings.
|
|
88
|
+
- **Vector** (`graph_vectors`) finds paraphrases and cross-language matches.
|
|
89
|
+
|
|
90
|
+
Neither is a fallback for the other; they fail in different directions and each
|
|
91
|
+
corrects the other's characteristic misses. Results then spread one hop through
|
|
92
|
+
the graph, so a memory adjacent to the match is reachable.
|
|
93
|
+
|
|
94
|
+
### How much gets recalled
|
|
95
|
+
|
|
96
|
+
There is no setting for this, and its absence is deliberate. A character budget
|
|
97
|
+
overshot by 79% at its lowest setting; a fixed count cannot be right for both
|
|
98
|
+
"ok, continue" and a question the graph knows a great deal about.
|
|
99
|
+
|
|
100
|
+
Each turn keeps the hits that stay close to **its own** best match
|
|
101
|
+
(`RELATIVE_FLOOR` in `context.ts`) and takes only the top few when the scores
|
|
102
|
+
never fall away — a ranking that does not separate has not ranked anything. A
|
|
103
|
+
hard ceiling remains in code as a cost backstop, not as a control.
|
|
104
|
+
|
|
105
|
+
### Standing instructions
|
|
106
|
+
|
|
107
|
+
What the user has **stated** is selected structurally and sent every turn,
|
|
108
|
+
regardless of what was asked. It is not retrieved, because a rule like "never use
|
|
109
|
+
the agent tool" has no topical overlap with "analyse this project", and static
|
|
110
|
+
embeddings cannot represent negation — asking *"jangan gunakan agent tool"* once
|
|
111
|
+
returned *"requested use of agent tool"* as the top hit.
|
|
112
|
+
|
|
113
|
+
Measured: human-stated rules reached the prompt on 3 of 20 opportunities before
|
|
114
|
+
this existed, and 30 of 30 after.
|
|
115
|
+
|
|
116
|
+
### Cross-project recall
|
|
117
|
+
|
|
118
|
+
Every memory records **where it was learned** (`project_id`) and, separately,
|
|
119
|
+
**whether it applies anywhere** (`reach`). A Svelte gotcha debugged in one
|
|
120
|
+
project reaches the next project that hits it; "this project deploys to Fly.io"
|
|
121
|
+
stays put.
|
|
122
|
+
|
|
123
|
+
`reach` defaults to `here` and is widened only by the reclassification pass in
|
|
124
|
+
`judge.ts`. That asymmetry is intentional: a memory wrongly held back is
|
|
125
|
+
invisible until the pass reaches it, while one wrongly released is in every
|
|
126
|
+
prompt immediately — and only the first is recoverable by waiting.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Writing: How Memories Get In
|
|
131
|
+
|
|
132
|
+
**Exactly one path creates memories:** the extraction that reads each finished
|
|
133
|
+
turn (`extract/episodic.ts`), scheduled by `extract/scheduler.ts`. It runs the
|
|
134
|
+
moment a turn ends, at most `MAX_CONCURRENT` at a time.
|
|
135
|
+
|
|
136
|
+
A person can also write one by hand through the composer (`compose.ts`) —
|
|
137
|
+
extraction can only record what a conversation happened to state, so a constraint
|
|
138
|
+
the user already knows has to be said out loud to an agent before it can be
|
|
139
|
+
remembered, usually after the mistake it would have prevented.
|
|
140
|
+
|
|
141
|
+
The MCP tool **cannot create a memory**. It can recall, correct, link, archive
|
|
142
|
+
and restore, but there is no `remember` action. Two creating paths meant the same
|
|
143
|
+
fact arriving by either route, phrased differently, with no way for an agent to
|
|
144
|
+
know which had already happened.
|
|
145
|
+
|
|
146
|
+
### The queue is a table
|
|
147
|
+
|
|
148
|
+
`memory_extraction_queue` is durable, not a `Map`. Extraction is the only write
|
|
149
|
+
path in the feature, so every way of losing an entry costs a conversation that
|
|
150
|
+
cannot be recovered — a failed model call, a restart, or a silent drop. Failures
|
|
151
|
+
retry with backoff; exhausted entries are marked `failed` and stay visible.
|
|
152
|
+
|
|
153
|
+
**One row per session**, enforced by a unique index. That is the "bank the oldest
|
|
154
|
+
boundary" rule expressed in the schema: a new turn in an already-queued session
|
|
155
|
+
merges into the existing row and keeps its `user_message_id`, because the
|
|
156
|
+
transcript runs from that message to the end of the chain.
|
|
157
|
+
|
|
158
|
+
### Secrets
|
|
159
|
+
|
|
160
|
+
`redact.ts` runs **before** the model sees the transcript. A summariser asked to
|
|
161
|
+
record what a turn established will happily quote the API key it was shown, and
|
|
162
|
+
by then the secret is in a durable, re-injected, instance-wide store.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Keeping the Graph Honest
|
|
167
|
+
|
|
168
|
+
| Mechanism | File | What it does |
|
|
169
|
+
| --- | --- | --- |
|
|
170
|
+
| Belief revision | `revise.ts` | Records that two memories disagree (`contradicts`) |
|
|
171
|
+
| Read-time resolution | `context.ts` | Decides which is current, per turn |
|
|
172
|
+
| Structural invalidation | `invalidate.ts` | Sets `stale_at` when code a memory is `about` changes |
|
|
173
|
+
| Consolidation | `consolidate.ts` | Merges memories stating the same thing |
|
|
174
|
+
| Retention | `retention.ts` | Bounds growth; retires unreferenced code entities |
|
|
175
|
+
| Reach classification | `judge.ts` | Decides which memories travel between projects |
|
|
176
|
+
| Maintenance loop | `maintenance.ts` | Runs the above on a timer |
|
|
177
|
+
|
|
178
|
+
**Belief revision happens on the READ path.** The write path only notices and
|
|
179
|
+
records a disagreement; which memory is current is decided fresh each turn from
|
|
180
|
+
who asserted it and how recently, by a rule with no model in it.
|
|
181
|
+
|
|
182
|
+
Deciding at write time let one model reading one turn retire a rule permanently,
|
|
183
|
+
and it did — a task-local exception retired a hand-written standing prohibition
|
|
184
|
+
in half the runs of a scripted test, and once in a real graph.
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## The Embedding Artifact
|
|
189
|
+
|
|
190
|
+
Semantic recall runs on a **static embedding table** (Model2Vec): embedding a
|
|
191
|
+
string is tokenize → look each token's row up → mean-pool → L2-normalize. No
|
|
192
|
+
forward pass, so no ONNX, no WASM, no native binary, no API key, no network call
|
|
193
|
+
at query time. A query costs ~0.05 ms.
|
|
194
|
+
|
|
195
|
+
The upstream model (`minishlab/potion-multilingual-128M`, MIT) is 512 MB.
|
|
196
|
+
Pruning non-Latin tokens, keeping the 150k most frequent and quantizing each row
|
|
197
|
+
to int8 brings it to **44 MB**, holding recall@3 at 91% against the full model's
|
|
198
|
+
94%.
|
|
199
|
+
|
|
200
|
+
It is **not in the repository** — it is weights, not code, and bundling it would
|
|
201
|
+
add 44 MB to every install whether or not memory is used. It downloads on demand
|
|
202
|
+
from a GitHub release into `~/.clopen/stack/embedding/<version>/`, checksum-
|
|
203
|
+
verified per file, written to a `.partial` directory that is renamed only once
|
|
204
|
+
complete.
|
|
205
|
+
|
|
206
|
+
> **Publishing a new artifact version:** see *Publishing the Memory Graph
|
|
207
|
+
> Embedding Artifact* in `MAINTAINERS.md`. The checksums in
|
|
208
|
+
> `embedding/paths.ts` and the files on the release must move together.
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
## Readiness and Setup
|
|
213
|
+
|
|
214
|
+
The artifact is a **prerequisite, not an enhancement**. `readiness.ts` splits the
|
|
215
|
+
two halves because they have different needs:
|
|
216
|
+
|
|
217
|
+
| Capability | Needs | Gated? |
|
|
218
|
+
| --- | --- | --- |
|
|
219
|
+
| **Recall** — injection, MCP `recall` | the embedding artifact | Yes, until installed |
|
|
220
|
+
| **Recording** — extraction | an extraction model | Runs during setup |
|
|
221
|
+
|
|
222
|
+
Recall is gated rather than degraded to BM25 alone: a lexical-only result set is
|
|
223
|
+
indistinguishable from a complete one to whatever consumes it, so an agent would
|
|
224
|
+
read "no shared keywords" as "nothing was decided" and act on it. The MCP tool
|
|
225
|
+
says so explicitly instead of returning an empty list.
|
|
226
|
+
|
|
227
|
+
Recording is deliberately **not** gated. The turns a user has while a 44 MB
|
|
228
|
+
download runs are usually the ones that establish a project; the indexer
|
|
229
|
+
backfills their vectors when the artifact lands, so nothing is lost.
|
|
230
|
+
|
|
231
|
+
**Nothing waits on a settings page.** The extraction model is chosen
|
|
232
|
+
automatically (`model.ts`) using the same rule as Settings → Model → Assistant —
|
|
233
|
+
the most capable model the default engine offers. It is picked at bootstrap and
|
|
234
|
+
again before the first extraction, because the engine catalog is often not loaded
|
|
235
|
+
at startup but certainly is by the time a turn has finished. An explicit choice
|
|
236
|
+
is never overwritten.
|
|
237
|
+
|
|
238
|
+
Failures retry with backoff (15s → 45s → 2m → 6m → 15m). A checksum mismatch or
|
|
239
|
+
an unpublished release stop instead, because waiting cannot turn the wrong bytes
|
|
240
|
+
into the right ones. `MemorySetupBanner.svelte` reports what is missing and
|
|
241
|
+
Settings → Infrastructure → Memory has a manual install.
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
## Agent Access (MCP)
|
|
246
|
+
|
|
247
|
+
One internal MCP server, one tool, eight actions — served over the existing
|
|
248
|
+
Streamable HTTP endpoint, so every engine that can consume an MCP URL reaches the
|
|
249
|
+
same store with no per-engine work.
|
|
250
|
+
|
|
251
|
+
| Action | Purpose |
|
|
252
|
+
| --- | --- |
|
|
253
|
+
| `recall` | Natural-language search; `scope: "all"` searches every project |
|
|
254
|
+
| `neighbours` | Walk outward from a node — often where the answer actually is |
|
|
255
|
+
| `timeline` | Recent memories in order |
|
|
256
|
+
| `update` | Correct a memory in place, keeping its edges and history |
|
|
257
|
+
| `link` | Connect two nodes (`supersedes`, `contradicts`, `about`, …) |
|
|
258
|
+
| `forget` | Archive a memory that was never true — retired, not deleted |
|
|
259
|
+
| `restore` | Undo a `forget` |
|
|
260
|
+
| `stats` | Size and composition |
|
|
261
|
+
|
|
262
|
+
`recall` answers with what **matches**, with expansion off (`expandHops: 0,
|
|
263
|
+
precise: true`). Expansion belongs to turn-start injection, where a weak lead is
|
|
264
|
+
still worth ranking and the agent never sees the ranking. Asked a direct
|
|
265
|
+
question, one hop turns three correct rows into sixty neighbours-of-neighbours
|
|
266
|
+
and an agent cannot tell which is which.
|
|
267
|
+
|
|
268
|
+
An agent's `update` is recorded as `source: 'agent'`. Recording it as the user's
|
|
269
|
+
would exempt the node from decay, eviction and consolidation, and advertise it to
|
|
270
|
+
every future turn as user-stated — a human's authority for a model's edit.
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Configuration
|
|
275
|
+
|
|
276
|
+
Split across two settings screens on purpose:
|
|
277
|
+
|
|
278
|
+
- **Settings → Model → Memory** — which model writes memories. The only place
|
|
279
|
+
memory uses a model at all.
|
|
280
|
+
- **Settings → Infrastructure → Memory** — what memory does: master switch, record code, record
|
|
281
|
+
memories, auto-recall.
|
|
282
|
+
|
|
283
|
+
Stored in the `settings` table via `config.ts`. Mutations are admin-only
|
|
284
|
+
(`backend/auth/permissions.ts`), matching skills and MCP servers: memory is
|
|
285
|
+
instance-global, so one member editing it changes what every agent is told.
|
|
286
|
+
|
|
287
|
+
Reads are open to any authenticated member — except the cross-project view, which
|
|
288
|
+
is admin-only. Memory spans the instance, so "every project at once" would show a
|
|
289
|
+
member repositories they have no access to.
|
|
290
|
+
|
|
291
|
+
---
|
|
292
|
+
|
|
293
|
+
## Schema
|
|
294
|
+
|
|
295
|
+
Created by migration `066_create_memory_graph.ts`.
|
|
296
|
+
|
|
297
|
+
```
|
|
298
|
+
graph_nodes the memories and code entities
|
|
299
|
+
graph_edges typed relations between them
|
|
300
|
+
graph_node_entities subjects a memory is about (an ATTRIBUTE, not nodes)
|
|
301
|
+
graph_vectors one int8 vector per node, 260 bytes at 256 dims
|
|
302
|
+
graph_nodes_fts FTS5 mirror for BM25
|
|
303
|
+
memory_extraction_queue durable queue of turns awaiting summarisation
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
`graph_nodes` groups its columns four ways:
|
|
307
|
+
|
|
308
|
+
| Group | Columns | Answers |
|
|
309
|
+
| --- | --- | --- |
|
|
310
|
+
| Identity | `digest`, `digest_version`, `entity_key` | Is this the same memory? |
|
|
311
|
+
| Standing | `weight`, `access_count`, `useful_count`, `unhelpful_count`, `pinned` | How much does it matter? |
|
|
312
|
+
| Authority & reach | `source`, `asserted_by`, `reach`, `reach_judged` | Whose claim, and where does it apply? |
|
|
313
|
+
| Lifecycle | `superseded_by`, `stale_at`, `archived_at` | Is it still current? |
|
|
314
|
+
|
|
315
|
+
Authority and reach are **four** columns rather than two, deliberately. Each
|
|
316
|
+
collapse produced a measured bug: `source` meaning both "which write path" and
|
|
317
|
+
"whose claim" let an inference retire what a person typed; `project_id` meaning
|
|
318
|
+
both "where learned" and "where it applies" made cross-project recall impossible.
|
|
319
|
+
|
|
320
|
+
### Relations
|
|
321
|
+
|
|
322
|
+
```
|
|
323
|
+
structural ↔ structural : imports | calls | defines | contains
|
|
324
|
+
episodic ↔ episodic : caused_by | supersedes | contradicts | generalizes
|
|
325
|
+
episodic → structural : about ← the bridge between both halves
|
|
326
|
+
any ↔ any : relates_to (user-drawn only)
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
`relates_to` is **never** inferred. An automatic similarity linker used to write
|
|
330
|
+
it from vector neighbourhoods and fabricated most of the graph: against a corpus
|
|
331
|
+
of sentences all shaped "X is a project that does Y", every pair is similar in
|
|
332
|
+
shape rather than in subject, so 144 of one graph's 371 edges were pairings like
|
|
333
|
+
*"Vantum monorepo phase 1.8"* ↔ *"ChatKit runs on Node.js 18+"*. The fault was
|
|
334
|
+
never that they connected memories — it was that **cosine chose which**. Edges are
|
|
335
|
+
now derived at read time from the subjects extraction already recorded, and never
|
|
336
|
+
stored.
|
|
337
|
+
|
|
338
|
+
---
|
|
339
|
+
|
|
340
|
+
## File Map
|
|
341
|
+
|
|
342
|
+
```
|
|
343
|
+
config.ts settings read/write
|
|
344
|
+
readiness.ts can memory recall / record, and what is missing
|
|
345
|
+
model.ts picks the extraction model when none is set
|
|
346
|
+
bootstrap.ts startup; idempotent, also re-run after Clear All Data
|
|
347
|
+
|
|
348
|
+
retrieval.ts BM25 + vector, RRF fusion, spreading activation
|
|
349
|
+
context.ts builds the injected block; standing instructions
|
|
350
|
+
view.ts graph serialization for the UI
|
|
351
|
+
|
|
352
|
+
extract/
|
|
353
|
+
scheduler.ts durable queue, retries, concurrency
|
|
354
|
+
episodic.ts model-driven summarisation of a finished turn
|
|
355
|
+
structural.ts file/symbol/dependency nodes from the disk diff
|
|
356
|
+
languages.ts per-language symbol extraction
|
|
357
|
+
|
|
358
|
+
embedding/
|
|
359
|
+
paths.ts version, pinned checksums, install location
|
|
360
|
+
install.ts on-demand download, verification, retry
|
|
361
|
+
embedder.ts int8 table loading, tokenize + mean-pool
|
|
362
|
+
vector-cache.ts resident vector cache
|
|
363
|
+
|
|
364
|
+
revise.ts contradictions, duplicates, entity linking
|
|
365
|
+
invalidate.ts staleness when code changes
|
|
366
|
+
consolidate.ts merges near-duplicates
|
|
367
|
+
retention.ts the bound on growth
|
|
368
|
+
judge.ts reach reclassification
|
|
369
|
+
maintenance.ts the timer that runs the above
|
|
370
|
+
compose.ts hand-written memories
|
|
371
|
+
redact.ts secret removal before the model sees a transcript
|
|
372
|
+
indexer.ts vector backfill
|
|
373
|
+
notify.ts WebSocket broadcasts to open views
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
---
|
|
377
|
+
|
|
378
|
+
## Testing
|
|
379
|
+
|
|
380
|
+
Tests run against a real in-memory SQLite database with migration 066 applied,
|
|
381
|
+
because most of the behaviour under test **is** SQL — which rows a superseded node
|
|
382
|
+
disappears from, which subkinds decay, what retention may touch. A mocked query
|
|
383
|
+
layer would assert the test's idea of that SQL rather than the database's.
|
|
384
|
+
|
|
385
|
+
```bash
|
|
386
|
+
bun test backend/memory
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
> **Run test files individually when a result looks surprising.**
|
|
390
|
+
> `mock.module` in Bun is process-wide, so a mock in one file follows every file
|
|
391
|
+
> that runs after it, and `embedder.load()` in one test can make another test's
|
|
392
|
+
> gate pass for the wrong reason. Several files here mock `$backend/database`,
|
|
393
|
+
> which leaks into unrelated suites in a full run. Every file in this directory
|
|
394
|
+
> passes on its own; that is the signal to trust.
|
|
395
|
+
|
|
396
|
+
Tests needing the embedding artifact are skipped when it is absent
|
|
397
|
+
(`describeIfEmbedding`), so they neither fail nor silently pass on CI.
|
|
398
|
+
|
|
399
|
+
---
|
|
400
|
+
|
|
401
|
+
## Design Decisions Worth Knowing
|
|
402
|
+
|
|
403
|
+
Each of these was reversed at least once, and the reversal is the reason for the
|
|
404
|
+
current shape.
|
|
405
|
+
|
|
406
|
+
**Nothing is a node unless it is a claim.** Canonical entity nodes made 115 of one
|
|
407
|
+
graph's 208 episodic nodes bare technology names with empty bodies. A name cannot
|
|
408
|
+
agree or disagree with anything, and an empty body means no vector — so a stub
|
|
409
|
+
could never be found semantically while still being offered to the model as
|
|
410
|
+
something to adjudicate against. Subjects are now rows in `graph_node_entities`,
|
|
411
|
+
folded into the FTS text.
|
|
412
|
+
|
|
413
|
+
**Revision resolves at read time.** See [Keeping the Graph Honest](#keeping-the-graph-honest).
|
|
414
|
+
|
|
415
|
+
**Retrieval never calls a model.** This is what makes injection on *every* turn
|
|
416
|
+
affordable. The moment a read costs a model call, memory becomes something an
|
|
417
|
+
agent must decide to use, and it will forget to.
|
|
418
|
+
|
|
419
|
+
**The digest is SHA-256, not `Bun.hash`.** The hash is persisted as a node's
|
|
420
|
+
identity, so it must mean the same thing after a runtime upgrade. `Bun.hash`
|
|
421
|
+
documents no cross-version stability guarantee, and a seed change would not fail
|
|
422
|
+
loudly — it would silently re-duplicate every memory in the graph.
|
|
423
|
+
|
|
424
|
+
**The FTS mirror is deleted by rowid.** `graph_nodes_fts.node_id` is `UNINDEXED`,
|
|
425
|
+
so `DELETE ... WHERE node_id = ?` is a full scan of the content table — and that
|
|
426
|
+
runs on every upsert. One busy turn is roughly fifteen hundred full scans of a
|
|
427
|
+
table that only grows. `graph_nodes.fts_rowid` turns each into a primary-key
|
|
428
|
+
lookup.
|
|
429
|
+
|
|
430
|
+
**Bootstrap has no latch.** A `started` flag made `bootstrapMemoryGraph` a no-op
|
|
431
|
+
on its second call — which is the call that matters, because "Clear All Data"
|
|
432
|
+
re-runs it on the live process after wiping the settings table.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Graph startup.
|
|
3
|
+
*
|
|
4
|
+
* Fetching the embedding artifact and backfilling vectors both happen in the
|
|
5
|
+
* background. The artifact is REQUIRED for recall (see `readiness.ts`), but
|
|
6
|
+
* blocking startup on a 44 MB download would hold the whole app hostage to one
|
|
7
|
+
* feature — and it is unnecessary, because the half that must not miss anything
|
|
8
|
+
* is RECORDING, which needs no artifact. Turns are captured from the first
|
|
9
|
+
* second; the indexer backfills their vectors when the download lands.
|
|
10
|
+
*
|
|
11
|
+
* Called from `bootstrapAfterDbInit`, which also runs after "Clear All Data"
|
|
12
|
+
* wipes `~/.clopen` on the live process — so the artifact is re-fetched then too,
|
|
13
|
+
* rather than staying missing until the next restart.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { memoryQueueQueries } from '$backend/database/queries/memory-queue-queries';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
import { ensureEmbeddingArtifact, onEmbeddingInstallChange, vectorCache } from './embedding';
|
|
19
|
+
import { notifyMemoryReadiness } from './notify';
|
|
20
|
+
import { resetGraphEmptiness } from './context';
|
|
21
|
+
import { reconcileVectorIndex } from './indexer';
|
|
22
|
+
import { startMemoryMaintenance } from './maintenance';
|
|
23
|
+
import { ensureMemoryModel } from './model';
|
|
24
|
+
import { startExtractionRunner } from './extract';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Ensure the embedding artifact is present, then reconcile the vector index.
|
|
28
|
+
* Fire-and-forget; a failed download schedules its own retry.
|
|
29
|
+
*
|
|
30
|
+
* IDEMPOTENT, WITH NO LATCH, and that is load-bearing. A `started` flag here made
|
|
31
|
+
* the whole function a no-op on its second call — which is exactly the call that
|
|
32
|
+
* matters, because "Clear All Data" re-runs this on the LIVE process after wiping
|
|
33
|
+
* the settings table. The result was a workspace that came back with no
|
|
34
|
+
* extraction model and no way to get one but choosing it by hand, while a fresh
|
|
35
|
+
* install configured itself. Everything below either guards itself
|
|
36
|
+
* (`startMemoryMaintenance`, `startExtractionRunner`, `ensureMemoryModel`) or is
|
|
37
|
+
* something a wipe genuinely requires re-running.
|
|
38
|
+
*/
|
|
39
|
+
export function bootstrapMemoryGraph(): void {
|
|
40
|
+
// "Clear All Data" wipes the database under a live process, so anything the
|
|
41
|
+
// cache is still holding describes rows that no longer exist.
|
|
42
|
+
vectorCache.reset();
|
|
43
|
+
resetGraphEmptiness();
|
|
44
|
+
|
|
45
|
+
// Duplicate collapse and retention are pure SQL and are worth running whether
|
|
46
|
+
// or not the artifact ever lands, so maintenance starts independently of the
|
|
47
|
+
// download. Its own first tick is minutes away, well clear of startup.
|
|
48
|
+
startMemoryMaintenance();
|
|
49
|
+
|
|
50
|
+
// Entries whose session is gone can never succeed and would be retried
|
|
51
|
+
// forever, showing in the status counts as outstanding work. Sessions are
|
|
52
|
+
// deleted through several paths and only some of them cancel their extraction
|
|
53
|
+
// — a project being removed takes its sessions with it without this queue ever
|
|
54
|
+
// hearing about it.
|
|
55
|
+
try {
|
|
56
|
+
const orphans = memoryQueueQueries.pruneOrphans();
|
|
57
|
+
if (orphans > 0) debug.log('memory', `Dropped ${orphans} extraction entr(ies) for deleted sessions`);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
debug.warn('memory', 'Failed to prune the extraction queue', error);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Pick up anything the previous process left queued, and put entries that had
|
|
63
|
+
// exhausted their attempts back in line — a restart usually means whatever was
|
|
64
|
+
// broken (a missing model, an expired account, an engine that was down) has
|
|
65
|
+
// just been changed.
|
|
66
|
+
startExtractionRunner();
|
|
67
|
+
|
|
68
|
+
// Any change to install progress is a change to what the setup banner says.
|
|
69
|
+
// Wired here rather than inside the installer so that module stays free of
|
|
70
|
+
// transport concerns and remains testable without a WebSocket.
|
|
71
|
+
onEmbeddingInstallChange(notifyMemoryReadiness);
|
|
72
|
+
|
|
73
|
+
// Choose an extraction model if none has been set, so a fresh install records
|
|
74
|
+
// from its very first turn instead of waiting for someone to find the settings
|
|
75
|
+
// page. Best-effort here — the engine catalog is often not loaded this early,
|
|
76
|
+
// which is why extraction asks again before its first run (see `model.ts`).
|
|
77
|
+
void ensureMemoryModel()
|
|
78
|
+
.then(model => {
|
|
79
|
+
if (model) notifyMemoryReadiness();
|
|
80
|
+
})
|
|
81
|
+
.catch(error => {
|
|
82
|
+
debug.warn('memory', 'Could not pick a default memory model at startup', error);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
void (async () => {
|
|
86
|
+
try {
|
|
87
|
+
// Recall is GATED on this, not merely improved by it (see `readiness.ts`),
|
|
88
|
+
// so a failure schedules its own retry rather than settling for lexical
|
|
89
|
+
// search. Startup is still not blocked: recording runs regardless, and the
|
|
90
|
+
// indexer backfills vectors for everything written meanwhile.
|
|
91
|
+
const ready = await ensureEmbeddingArtifact();
|
|
92
|
+
if (!ready) {
|
|
93
|
+
debug.log('memory', 'Embedding artifact unavailable — recall stays off until it installs');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
await reconcileVectorIndex();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
debug.warn('memory', 'Memory graph bootstrap failed (non-fatal)', error);
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
}
|