@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.
Files changed (96) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/copilot/stream.ts +37 -1
  15. package/backend/engine/adapters/pi/models.ts +19 -7
  16. package/backend/engine/adapters/pi/stream.ts +2 -1
  17. package/backend/engine/docs/adapter-contract.md +25 -8
  18. package/backend/engine/docs/adding-an-engine.md +40 -4
  19. package/backend/engine/docs/frontend-and-chat.md +66 -1
  20. package/backend/engine/docs/lessons-learned.md +165 -6
  21. package/backend/engine/docs/quick-reference.md +10 -0
  22. package/backend/engine/docs/stack.md +10 -0
  23. package/backend/engine/docs/websocket-routes.md +15 -1
  24. package/backend/engine/engine-setup.ts +1 -1
  25. package/backend/engine/index.test.ts +186 -0
  26. package/backend/engine/index.ts +117 -71
  27. package/backend/engine/install-recipes.test.ts +105 -0
  28. package/backend/engine/install-recipes.ts +4 -1
  29. package/backend/index.ts +9 -0
  30. package/backend/mcp/internal/config.ts +6 -0
  31. package/backend/mcp/internal/servers/index.ts +2 -0
  32. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  33. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  34. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  35. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  36. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  37. package/backend/memory/README.md +432 -0
  38. package/backend/memory/bootstrap.ts +101 -0
  39. package/backend/memory/compose.test.ts +198 -0
  40. package/backend/memory/compose.ts +343 -0
  41. package/backend/memory/config.ts +100 -0
  42. package/backend/memory/consolidate.ts +280 -0
  43. package/backend/memory/context.test.ts +321 -0
  44. package/backend/memory/context.ts +451 -0
  45. package/backend/memory/embedding/embedder.test.ts +141 -0
  46. package/backend/memory/embedding/embedder.ts +269 -0
  47. package/backend/memory/embedding/index.ts +17 -0
  48. package/backend/memory/embedding/install.ts +254 -0
  49. package/backend/memory/embedding/paths.ts +101 -0
  50. package/backend/memory/embedding/vector-cache.ts +270 -0
  51. package/backend/memory/extract/episodic.ts +725 -0
  52. package/backend/memory/extract/index.ts +133 -0
  53. package/backend/memory/extract/languages.ts +176 -0
  54. package/backend/memory/extract/scheduler.test.ts +352 -0
  55. package/backend/memory/extract/scheduler.ts +406 -0
  56. package/backend/memory/extract/structural.test.ts +215 -0
  57. package/backend/memory/extract/structural.ts +364 -0
  58. package/backend/memory/index.ts +37 -0
  59. package/backend/memory/indexer.ts +150 -0
  60. package/backend/memory/invalidate.ts +134 -0
  61. package/backend/memory/judge.ts +285 -0
  62. package/backend/memory/maintenance.ts +132 -0
  63. package/backend/memory/model.ts +91 -0
  64. package/backend/memory/notify.ts +102 -0
  65. package/backend/memory/readiness.ts +74 -0
  66. package/backend/memory/redact.test.ts +101 -0
  67. package/backend/memory/redact.ts +133 -0
  68. package/backend/memory/retention.ts +139 -0
  69. package/backend/memory/retrieval.eval.test.ts +301 -0
  70. package/backend/memory/retrieval.test.ts +1023 -0
  71. package/backend/memory/retrieval.ts +707 -0
  72. package/backend/memory/revise.test.ts +693 -0
  73. package/backend/memory/revise.ts +400 -0
  74. package/backend/memory/time.ts +31 -0
  75. package/backend/memory/view.ts +164 -0
  76. package/backend/shipped-runtime-imports.test.ts +228 -0
  77. package/backend/ws/index.ts +5 -1
  78. package/backend/ws/memory/crud.ts +631 -0
  79. package/backend/ws/memory/index.ts +41 -0
  80. package/backend/ws/sessions/crud.ts +10 -0
  81. package/backend/ws/snapshot/content.ts +85 -0
  82. package/backend/ws/snapshot/index.ts +4 -1
  83. package/backend/ws/snapshot/restore.ts +38 -4
  84. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  85. package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
  86. package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
  87. package/dist/assets/main-BrqMMMRX.css +1 -0
  88. package/dist/assets/main-CgmAFpU3.js +1036 -0
  89. package/dist/index.html +2 -2
  90. package/package.json +8 -2
  91. package/shared/types/database/connection.ts +9 -0
  92. package/shared/types/memory.ts +519 -0
  93. package/shared/utils/logger.ts +1 -0
  94. package/dist/assets/main-B0AA-88X.js +0 -622
  95. package/dist/assets/main-OsjA5Ab5.css +0 -1
  96. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Consolidation — compressing many small memories into fewer large ones.
3
+ *
4
+ * A graph of four hundred observations is less intelligent than a graph of forty
5
+ * principles with four hundred observations hanging under them, even though it
6
+ * contains strictly more text. Retrieval has a fixed budget: eighteen hits, a
7
+ * few thousand characters. Spending that budget on eight variations of one idea
8
+ * is the difference between an agent that knows how this project works and one
9
+ * that gets eight anecdotes.
10
+ *
11
+ * So the graph periodically does what a person does overnight: takes a cluster of
12
+ * related memories and writes down what they have in common. The children are not
13
+ * deleted — they are archived and joined to the summary with `generalizes`, so
14
+ * the evidence for a generalisation is always one hop away and a wrong summary
15
+ * can be undone.
16
+ *
17
+ * This also IS the retention policy for episodic memory. Growth is bounded by
18
+ * compression rather than by deletion, which is the only bound that does not
19
+ * throw information away.
20
+ *
21
+ * It runs on a maintenance timer, never on a path anyone waits on, and it uses
22
+ * the same configured model as extraction. Clusters come from the Louvain
23
+ * communities already computed for the graph view, so the grouping the user sees
24
+ * as coloured lobes is the grouping that gets consolidated.
25
+ */
26
+
27
+ import Graph from 'graphology';
28
+ import louvain from 'graphology-communities-louvain';
29
+ import { graphQueries } from '$backend/database/queries/graph-queries';
30
+ import { initializeEngine } from '$backend/engine';
31
+ import { resolveGenerationTarget } from '$backend/engine/resolve-model';
32
+ import { debug } from '$shared/utils/logger';
33
+ import { getMemoryConfig, type MemoryModelConfig } from './config';
34
+ import { notifyGraphChanged } from './notify';
35
+ import { redactSecrets } from './redact';
36
+ import { ageInDays } from './time';
37
+ import type { EpisodicSubkind, GraphNode } from '$shared/types/memory';
38
+
39
+ /**
40
+ * Fewest memories a cluster needs before summarising it is worth a model call.
41
+ * Below this the summary tends to be longer than the memories it replaces.
42
+ */
43
+ const MIN_CLUSTER = 6;
44
+
45
+ /** Most memories fed into one summary, to keep the prompt bounded. */
46
+ const MAX_CLUSTER = 24;
47
+
48
+ /** Clusters consolidated per maintenance pass. */
49
+ const MAX_CLUSTERS_PER_RUN = 3;
50
+
51
+ /**
52
+ * Age a memory must reach before it can be consolidated.
53
+ *
54
+ * Recent memories are still being used as memories. Summarising something
55
+ * written this morning would remove the detail from exactly the sessions most
56
+ * likely to need it, which is the opposite of the intent.
57
+ */
58
+ const MIN_AGE_DAYS = 7;
59
+
60
+ const SUMMARY_SCHEMA = {
61
+ type: 'object',
62
+ additionalProperties: false,
63
+ properties: {
64
+ worthSummarising: {
65
+ type: 'boolean',
66
+ description:
67
+ 'False when the memories below have no common thread and forcing one would invent a claim none of them make.'
68
+ },
69
+ subkind: {
70
+ type: 'string',
71
+ enum: ['decision', 'pattern', 'failure', 'preference', 'observation'],
72
+ description: 'The kind of the consolidated memory. Usually pattern.'
73
+ },
74
+ label: {
75
+ type: 'string',
76
+ description:
77
+ 'MUST BE IN ENGLISH. One sentence stating what all of these memories share, specific enough to be useful on its own. Max 160 characters.'
78
+ },
79
+ body: {
80
+ type: 'string',
81
+ description:
82
+ 'MUST BE IN ENGLISH. The generalisation: what holds across these, what it rules out, where it does not apply. Three or four sentences.'
83
+ },
84
+ /**
85
+ * Not every member of a Louvain community belongs to the same idea —
86
+ * communities are a structural clustering, not a semantic one — so the model
87
+ * says which ones it actually summarised. The rest are left alone.
88
+ */
89
+ coveredIds: {
90
+ type: 'array',
91
+ description: 'Ids of the memories this summary genuinely covers. Omit any that do not fit.',
92
+ items: { type: 'string' }
93
+ }
94
+ },
95
+ required: ['worthSummarising', 'subkind', 'label', 'body', 'coveredIds']
96
+ };
97
+
98
+ interface Summary {
99
+ worthSummarising: boolean;
100
+ subkind: EpisodicSubkind;
101
+ label: string;
102
+ body: string;
103
+ coveredIds: string[];
104
+ }
105
+
106
+ export interface ConsolidationResult {
107
+ clusters: number;
108
+ summaries: number;
109
+ archived: number;
110
+ }
111
+
112
+ /**
113
+ * Find dense clusters of consolidatable memories and summarise them.
114
+ *
115
+ * Never throws. Returns what it did, for the log and for tests.
116
+ */
117
+ export async function consolidateMemories(projectId: string | null, projectPath: string): Promise<ConsolidationResult> {
118
+ const result: ConsolidationResult = { clusters: 0, summaries: 0, archived: 0 };
119
+
120
+ const config = getMemoryConfig();
121
+ if (!config.enabled || !config.recordMemories || !config.model) return result;
122
+
123
+ try {
124
+ const clusters = findClusters(projectId);
125
+ result.clusters = clusters.length;
126
+
127
+ for (const cluster of clusters.slice(0, MAX_CLUSTERS_PER_RUN)) {
128
+ const summary = await summarise(config.model, cluster, projectPath);
129
+ if (!summary?.worthSummarising || !summary.label?.trim()) continue;
130
+
131
+ // Only members the model said it covered, and only ones that were really
132
+ // in the cluster — an id from outside it was not summarised by anything.
133
+ const clusterIds = new Set(cluster.map(node => node.id));
134
+ const covered = cluster.filter(node => summary.coveredIds?.includes(node.id) && clusterIds.has(node.id));
135
+ if (covered.length < MIN_CLUSTER) continue;
136
+
137
+ const node = graphQueries.upsert({
138
+ kind: 'episodic',
139
+ subkind: summary.subkind,
140
+ scope: projectId ? 'project' : 'global',
141
+ projectId,
142
+ label: summary.label.trim().slice(0, 300),
143
+ body: summary.body.trim(),
144
+ // A generalisation is only as good as its evidence, and it was inferred
145
+ // rather than stated, so it starts below the memories it summarises.
146
+ confidence: 0.65,
147
+ source: 'agent'
148
+ });
149
+ result.summaries++;
150
+
151
+ for (const child of covered) {
152
+ // The edge is written BEFORE the archive, so a crash between the two
153
+ // leaves the evidence attached rather than orphaned.
154
+ graphQueries.link({ srcId: node.id, dstId: child.id, rel: 'generalizes', source: 'agent' });
155
+ graphQueries.archive(child.id);
156
+ result.archived++;
157
+ }
158
+ }
159
+
160
+ if (result.summaries > 0) {
161
+ notifyGraphChanged('consolidation', projectId);
162
+ debug.log(
163
+ 'memory',
164
+ `Consolidated ${result.archived} memory/memories into ${result.summaries} generalisation(s)`
165
+ );
166
+ }
167
+ } catch (error) {
168
+ debug.warn('memory', 'Consolidation failed (non-fatal)', error);
169
+ }
170
+
171
+ return result;
172
+ }
173
+
174
+ /**
175
+ * Groups of related memories, from the same Louvain communities the graph view
176
+ * renders as lobes.
177
+ *
178
+ * Pinned, user-authored and entity nodes are excluded before clustering rather
179
+ * than after: they must never be archived into a summary, and leaving them in
180
+ * would let them shape a cluster they cannot be part of.
181
+ */
182
+ function findClusters(projectId: string | null): GraphNode[][] {
183
+ const nodes = graphQueries
184
+ .list({ projectId, kinds: ['episodic'], limit: 2_000 })
185
+ .filter(
186
+ node =>
187
+ node.source === 'agent' &&
188
+ !node.pinned &&
189
+ !node.entityKey &&
190
+ // Already a generalisation, or old enough to become part of one.
191
+ ageInDays(node.updatedAt) >= MIN_AGE_DAYS
192
+ );
193
+
194
+ if (nodes.length < MIN_CLUSTER) return [];
195
+
196
+ const ids = new Set(nodes.map(node => node.id));
197
+ const graph = new Graph({ type: 'undirected', multi: false });
198
+ for (const node of nodes) graph.addNode(node.id);
199
+
200
+ for (const edge of graphQueries.edgesWithin([...ids])) {
201
+ if (edge.srcId === edge.dstId) continue;
202
+ if (!ids.has(edge.srcId) || !ids.has(edge.dstId)) continue;
203
+ if (!graph.hasEdge(edge.srcId, edge.dstId)) {
204
+ graph.addUndirectedEdge(edge.srcId, edge.dstId, { weight: edge.weight });
205
+ }
206
+ }
207
+
208
+ // No edges means no clusters. That is a graph where similarity linking has not
209
+ // run yet, and consolidating it would be guessing.
210
+ if (graph.size === 0) return [];
211
+
212
+ let communities: Record<string, number>;
213
+ try {
214
+ communities = louvain(graph, { getEdgeWeight: 'weight' });
215
+ } catch (error) {
216
+ debug.warn('memory', 'Clustering for consolidation failed', error);
217
+ return [];
218
+ }
219
+
220
+ const byCommunity = new Map<number, GraphNode[]>();
221
+ const nodeById = new Map(nodes.map(node => [node.id, node]));
222
+ for (const [id, community] of Object.entries(communities)) {
223
+ const node = nodeById.get(id);
224
+ if (!node) continue;
225
+ const bucket = byCommunity.get(community) ?? [];
226
+ bucket.push(node);
227
+ byCommunity.set(community, bucket);
228
+ }
229
+
230
+ return [...byCommunity.values()]
231
+ .filter(bucket => bucket.length >= MIN_CLUSTER)
232
+ // Densest first: a large cluster is where the redundancy is.
233
+ .sort((a, b) => b.length - a.length)
234
+ .map(bucket => bucket.slice(0, MAX_CLUSTER));
235
+ }
236
+
237
+ async function summarise(
238
+ model: MemoryModelConfig,
239
+ cluster: GraphNode[],
240
+ projectPath: string
241
+ ): Promise<Summary | null> {
242
+ const listing = cluster
243
+ .map(node => `- [${node.id}] (${node.subkind}) ${node.label}${node.body ? ` — ${node.body.split('\n')[0].slice(0, 200)}` : ''}`)
244
+ .join('\n');
245
+
246
+ // The memories were redacted on the way in, but a summary is a new durable
247
+ // artifact and this is the last point before it is written.
248
+ const prompt = redactSecrets(`You maintain a long-term memory. Below is a cluster of memories that the graph has found to be related.
249
+
250
+ Write ONE memory that states what they have in common — the principle, convention or conclusion they are all instances of. It replaces them in day-to-day recall, so it has to carry the useful content of the group, not merely name the topic.
251
+
252
+ WRITE IN ENGLISH, both label and body.
253
+
254
+ Set worthSummarising to false if these memories do not actually share a thread. Inventing a generalisation that none of them supports is far worse than leaving them as they are — they would be archived behind a claim that is not true.
255
+
256
+ List in coveredIds only the memories your summary genuinely covers. Anything that does not fit stays as it is.
257
+
258
+ Memories:
259
+ ${listing}`).text;
260
+
261
+ try {
262
+ const engine = await initializeEngine(model.engine);
263
+ if (!engine.generateStructured) return null;
264
+
265
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
266
+ const accountId = model.accountId ?? target.accountId;
267
+
268
+ return await engine.generateStructured<Summary>({
269
+ prompt,
270
+ providerSlug: target.providerSlug,
271
+ modelId: target.modelId,
272
+ schema: SUMMARY_SCHEMA,
273
+ projectPath,
274
+ ...(accountId != null && { accountId })
275
+ });
276
+ } catch (error) {
277
+ debug.warn('memory', 'Cluster summary failed', error);
278
+ return null;
279
+ }
280
+ }
@@ -0,0 +1,321 @@
1
+ /**
2
+ * What actually reaches the prompt.
3
+ *
4
+ * Two failures here were invisible from anywhere else, because both produce a
5
+ * turn that simply has no memory in it — which is indistinguishable from a graph
6
+ * that had nothing to say.
7
+ *
8
+ * THE BLOCK CAME OUT EMPTY ON THE TURNS WITH THE MOST TO OFFER. Retrieval ranks
9
+ * structural and episodic nodes together and the block only ever shows episodic
10
+ * ones, so asking for eighteen hits and then filtering meant a project's file and
11
+ * symbol nodes could take every slot. They win exactly when the turn mentions a
12
+ * path or a symbol — and they outnumber memories by an order of magnitude, and
13
+ * every anchor seed is one.
14
+ *
15
+ * THE DIRECTIVE WAS SENT INTO AN EMPTY GRAPH. A few hundred characters on every
16
+ * turn of every session on every engine, telling an agent about a store with
17
+ * nothing in it.
18
+ */
19
+
20
+ import { beforeEach, describe, expect, it, mock } from 'bun:test';
21
+ import { Database } from 'bun:sqlite';
22
+ import type { DatabaseConnection } from '$shared/types/database/connection';
23
+ import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
24
+
25
+ let db: Database;
26
+
27
+ // The whole module surface, not just `getDatabase`. `mock.module` replaces the
28
+ // module for the entire test PROCESS, so a partial stub leaves any file that runs
29
+ // afterwards unable to import the missing names — surfacing as
30
+ // "Export named 'closeDatabase' not found" in a test that never touched memory.
31
+ mock.module('$backend/database', () => ({
32
+ getDatabase: () => db,
33
+ initializeDatabase: async () => db,
34
+ closeDatabase: () => {},
35
+ resetDatabase: async () => {},
36
+ getDatabaseInfo: async () => ({}),
37
+ vacuumDatabase: async () => {}
38
+ }));
39
+
40
+ mock.module('./config', () => ({
41
+ getMemoryConfig: () => ({
42
+ enabled: true,
43
+ recordCode: true,
44
+ recordMemories: true,
45
+ autoRecall: true,
46
+ model: null
47
+ }),
48
+ setMemoryConfig: () => {}
49
+ }));
50
+
51
+ // Recall is gated on the embedding artifact being installed and loaded, which is
52
+ // a property of the MACHINE, not of the behaviour under test. Mocked so these
53
+ // tests assert what the block contains rather than whether this checkout happens
54
+ // to have a 44 MB download sitting in ~/.clopen.
55
+ mock.module('./readiness', () => ({
56
+ getMemoryReadiness: () => ({
57
+ enabled: true,
58
+ canRecall: true,
59
+ canRecord: true,
60
+ setupRequired: false,
61
+ blockers: [],
62
+ embedding: {
63
+ ready: true,
64
+ phase: 'installed',
65
+ attempts: 0,
66
+ error: null,
67
+ failure: null,
68
+ permanent: false,
69
+ nextAttemptAt: null,
70
+ receivedBytes: 0,
71
+ totalBytes: 0
72
+ },
73
+ model: { configured: true, engine: 'opencode', modelId: 'test-model' }
74
+ })
75
+ }));
76
+
77
+ const { graphQueries } = await import('$backend/database/queries/graph-queries');
78
+ const { buildMemoryContext, resetGraphEmptiness, takeInjectedMemories } = await import('./context');
79
+
80
+ const PROJECT = 'project-a';
81
+
82
+ function memory(label: string, body: string) {
83
+ return graphQueries.upsert({
84
+ kind: 'episodic',
85
+ subkind: 'decision',
86
+ projectId: PROJECT,
87
+ label,
88
+ body,
89
+ confidence: 0.8
90
+ });
91
+ }
92
+
93
+ /** A project's structural half: the nodes that outnumber and outrank memories. */
94
+ function floodWithCode(count: number, token: string): void {
95
+ for (let i = 0; i < count; i++) {
96
+ graphQueries.upsert({
97
+ kind: 'structural',
98
+ subkind: 'file',
99
+ projectId: PROJECT,
100
+ label: `${token}-${i}.ts`,
101
+ body: `src/${token}/${token}-${i}.ts`,
102
+ path: `src/${token}/${token}-${i}.ts`
103
+ });
104
+ }
105
+ }
106
+
107
+ beforeEach(() => {
108
+ db = new Database(':memory:');
109
+ db.exec('PRAGMA foreign_keys = ON');
110
+ migration066.up(db as unknown as DatabaseConnection);
111
+ resetGraphEmptiness();
112
+ });
113
+
114
+ describe('the injected block', () => {
115
+ it('says nothing at all while the graph is empty', () => {
116
+ expect(buildMemoryContext({ query: 'how does the stream manager work', projectId: PROJECT, sessionId: 's' })).toBeNull();
117
+ });
118
+
119
+ it('appears as soon as there is something to say', () => {
120
+ memory('The stream manager owns snapshot capture', 'It captures in its finally block.');
121
+ resetGraphEmptiness();
122
+
123
+ const block = buildMemoryContext({
124
+ query: 'how does the stream manager work',
125
+ projectId: PROJECT,
126
+ sessionId: 's'
127
+ });
128
+ expect(block).not.toBeNull();
129
+ expect(block!.text).toContain('<clopen-memory>');
130
+ });
131
+
132
+ it('still finds the memory when the code half floods the ranking', () => {
133
+ // Forty file nodes all matching the query's tokens, which is what a real
134
+ // project looks like. With a limit of eighteen applied BEFORE the episodic
135
+ // filter, none of the one memory that matters survived.
136
+ const note = memory('Snapshot capture must not run mid-stream', 'It corrupts the working tree.');
137
+ floodWithCode(40, 'snapshot');
138
+ resetGraphEmptiness();
139
+
140
+ const block = buildMemoryContext({
141
+ query: 'snapshot capture',
142
+ projectId: PROJECT,
143
+ sessionId: 's'
144
+ })!;
145
+
146
+ expect(block.nodeIds).toContain(note.id);
147
+ });
148
+
149
+ it('never lists a code entity — the agent can read the repository itself', () => {
150
+ memory('Snapshot capture must not run mid-stream', 'It corrupts the working tree.');
151
+ floodWithCode(10, 'snapshot');
152
+ resetGraphEmptiness();
153
+
154
+ const block = buildMemoryContext({ query: 'snapshot capture', projectId: PROJECT, sessionId: 's' })!;
155
+ const structural = graphQueries.list({ projectId: PROJECT, kinds: ['structural'] }).map(node => node.id);
156
+
157
+ expect(block.nodeIds.filter(id => structural.includes(id))).toHaveLength(0);
158
+ });
159
+
160
+ it('carries as many memories as the question earns, never more than the ceiling', () => {
161
+ // There is no setting for this any more. A character budget did not bound what
162
+ // it claimed to, and a count could not be right for both "ok, continue" and a
163
+ // turn that lands on a well-known subject. Each turn now keeps the hits that
164
+ // stay close to its own best match.
165
+ for (let i = 0; i < 40; i++) {
166
+ memory(`Decision number ${i} about routing`, 'A reason long enough to cost real budget. '.repeat(4));
167
+ }
168
+ resetGraphEmptiness();
169
+
170
+ const block = buildMemoryContext({ query: 'decision about routing', projectId: PROJECT, sessionId: 's' })!;
171
+ const lines = block.text.split('\n').filter(line => line.startsWith('- ('));
172
+ expect(lines.length).toBeGreaterThan(0);
173
+ expect(lines.length).toBeLessThanOrEqual(12);
174
+ });
175
+
176
+ it('takes only a few when the ranking never falls away', () => {
177
+ // A plateau is a ranker with no opinion. Forty memories phrased alike, against
178
+ // a query that matches all of them equally, used to fill the block with twelve
179
+ // weak lines — the relative floor cannot tell that from twelve strong ones,
180
+ // because it is the same shape. Not falling away is the signal.
181
+ for (let i = 0; i < 40; i++) {
182
+ memory(`Interchangeable note ${i}`, 'Every one of these says the same kind of thing as the others.');
183
+ }
184
+ resetGraphEmptiness();
185
+
186
+ const block = buildMemoryContext({ query: 'interchangeable note thing', projectId: PROJECT, sessionId: 's' })!;
187
+ const lines = block.text.split('\n').filter(l => l.startsWith('- ('));
188
+ expect(lines.length).toBeLessThanOrEqual(3);
189
+ });
190
+
191
+ it('sends fewer memories for a question the graph barely matches', () => {
192
+ // The point of a relative cutoff: a weak question should not drag in the same
193
+ // number of lines as a strong one merely because a fixed count said so.
194
+ for (let i = 0; i < 40; i++) {
195
+ memory(`Decision number ${i} about routing`, 'A reason long enough to cost real budget. '.repeat(4));
196
+ }
197
+ memory('Deployment runs through a distinctivetoken pipeline', 'Nothing else mentions it.');
198
+ resetGraphEmptiness();
199
+
200
+ const strong = buildMemoryContext({ query: 'decision about routing', projectId: PROJECT, sessionId: 'a' })!;
201
+ const weak = buildMemoryContext({ query: 'distinctivetoken', projectId: PROJECT, sessionId: 'b' })!;
202
+
203
+ const count = (block: { text: string }) => block.text.split('\n').filter(l => l.startsWith('- (')).length;
204
+ expect(count(weak)).toBeLessThan(count(strong));
205
+ });
206
+
207
+ it('trims a verbose memory rather than letting it eat the block', () => {
208
+ memory('One very wordy decision about routing', 'An explanation that simply keeps going. '.repeat(40));
209
+ resetGraphEmptiness();
210
+
211
+ const block = buildMemoryContext({ query: 'wordy decision routing', projectId: PROJECT, sessionId: 's' })!;
212
+ for (const line of block.text.split('\n')) expect(line.length).toBeLessThanOrEqual(300);
213
+ });
214
+
215
+ it('hands the injected ids over exactly once', () => {
216
+ // They are adjudicated by the extraction that reads the turn they were given
217
+ // to. Reading rather than consuming would let a skipped extraction score the
218
+ // same memories twice.
219
+ memory('A memory to be judged', 'Something distinctive to match on.');
220
+ resetGraphEmptiness();
221
+ const block = buildMemoryContext({ query: 'distinctive memory judged', projectId: PROJECT, sessionId: 's' })!;
222
+
223
+ expect(takeInjectedMemories('s')).toEqual(block.nodeIds);
224
+ expect(takeInjectedMemories('s')).toEqual([]);
225
+ });
226
+
227
+ it('names the project a transferred memory was learned in', () => {
228
+ // Cross-project recall is only usable if the agent can tell "a convention
229
+ // proven in the other repo" from "a description of this codebase". Without
230
+ // the name, a travelling memory reads as a claim about the project in front
231
+ // of it.
232
+ graphQueries.upsert({
233
+ kind: 'episodic',
234
+ subkind: 'pattern',
235
+ scope: 'project',
236
+ projectId: 'project-b',
237
+ label: 'Guard factories keep authorisation off individual route files',
238
+ body: 'Proven elsewhere.',
239
+ confidence: 0.9,
240
+ source: 'agent',
241
+ reach: 'anywhere'
242
+ });
243
+ resetGraphEmptiness();
244
+
245
+ const block = buildMemoryContext({
246
+ query: 'guard factories authorisation route files',
247
+ projectId: PROJECT,
248
+ sessionId: 's',
249
+ projectNames: new Map([['project-b', 'oneinbox']])
250
+ })!;
251
+ expect(block.text).toContain('learned in oneinbox');
252
+ });
253
+
254
+ it('sends what the user stated whether or not the turn is about it', () => {
255
+ // The failure this whole split exists for. A standing instruction has no
256
+ // topical overlap with an unrelated question, so similarity search will
257
+ // always rank it below whatever was actually asked — measured, human-stated
258
+ // rules reached the prompt on 3 of 20 opportunities.
259
+ graphQueries.upsert({
260
+ kind: 'episodic',
261
+ subkind: 'preference',
262
+ scope: 'global',
263
+ projectId: null,
264
+ label: 'Never use the agent tool',
265
+ body: 'Forbidden outright, to conserve tokens.',
266
+ confidence: 0.95,
267
+ source: 'user',
268
+ assertedBy: 'user'
269
+ });
270
+ memory('Routing is handled by the gateway', 'Nothing to do with tooling.');
271
+ resetGraphEmptiness();
272
+
273
+ const block = buildMemoryContext({ query: 'how does routing work here', projectId: PROJECT, sessionId: 's' })!;
274
+ expect(block.text).toContain('STANDING INSTRUCTIONS');
275
+ expect(block.text).toContain('Never use the agent tool');
276
+ });
277
+
278
+ it('does not repeat a standing instruction in the recalled section', () => {
279
+ graphQueries.upsert({
280
+ kind: 'episodic',
281
+ subkind: 'preference',
282
+ scope: 'global',
283
+ projectId: null,
284
+ label: 'Never use the agent tool for distinctive analysis',
285
+ body: 'Forbidden outright.',
286
+ confidence: 0.95,
287
+ source: 'user',
288
+ assertedBy: 'user'
289
+ });
290
+ resetGraphEmptiness();
291
+
292
+ const block = buildMemoryContext({
293
+ query: 'distinctive analysis agent tool',
294
+ projectId: PROJECT,
295
+ sessionId: 's'
296
+ })!;
297
+ const occurrences = block.text.split('Never use the agent tool for distinctive analysis').length - 1;
298
+ expect(occurrences).toBe(1);
299
+ });
300
+
301
+ it('does not put an inference into the standing section', () => {
302
+ // Only what a person stated gets imperative framing. A model's conclusion
303
+ // about how the user works is background, and promoting it would make the
304
+ // most privileged position in the prompt reachable by inference.
305
+ graphQueries.upsert({
306
+ kind: 'episodic',
307
+ subkind: 'preference',
308
+ scope: 'global',
309
+ projectId: null,
310
+ label: 'The user probably prefers terse replies',
311
+ body: 'Guessed from their message lengths.',
312
+ confidence: 0.6,
313
+ source: 'agent',
314
+ assertedBy: 'inferred'
315
+ });
316
+ resetGraphEmptiness();
317
+
318
+ const block = buildMemoryContext({ query: 'terse replies preference', projectId: PROJECT, sessionId: 's' })!;
319
+ expect(block.text).not.toContain('STANDING INSTRUCTIONS');
320
+ });
321
+ });