@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,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hand-written path.
|
|
3
|
+
*
|
|
4
|
+
* Its whole reason for existing is that it does NOT depend on the machinery the
|
|
5
|
+
* rest of memory depends on: no conversation to read, and no model to read it
|
|
6
|
+
* with. An instance where recording has never worked — no model configured, which
|
|
7
|
+
* is the default until someone visits a settings page — is exactly the instance
|
|
8
|
+
* whose graph is empty, and therefore exactly the one where a person needs to be
|
|
9
|
+
* able to write something down.
|
|
10
|
+
*
|
|
11
|
+
* So the model is optional at every step, and what it produces is a DRAFT rather
|
|
12
|
+
* than a row: what the user types is one field and what the graph stores is six,
|
|
13
|
+
* and filling the other five without showing the result would mean a store whose
|
|
14
|
+
* contents nobody had read.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
|
18
|
+
import { Database } from 'bun:sqlite';
|
|
19
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
20
|
+
import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
|
|
21
|
+
|
|
22
|
+
let db: Database;
|
|
23
|
+
|
|
24
|
+
// The whole module surface, not just `getDatabase`. `mock.module` replaces the
|
|
25
|
+
// module for the entire test PROCESS, so a partial stub leaves any file that runs
|
|
26
|
+
// afterwards unable to import the missing names — surfacing as
|
|
27
|
+
// "Export named 'closeDatabase' not found" in a test that never touched memory.
|
|
28
|
+
mock.module('$backend/database', () => ({
|
|
29
|
+
getDatabase: () => db,
|
|
30
|
+
initializeDatabase: async () => db,
|
|
31
|
+
closeDatabase: () => {},
|
|
32
|
+
resetDatabase: async () => {},
|
|
33
|
+
getDatabaseInfo: async () => ({}),
|
|
34
|
+
vacuumDatabase: async () => {}
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
/** No model, which is both the default and the case worth protecting. */
|
|
38
|
+
mock.module('./config', () => ({
|
|
39
|
+
getMemoryConfig: () => ({
|
|
40
|
+
enabled: true,
|
|
41
|
+
recordCode: true,
|
|
42
|
+
recordMemories: true,
|
|
43
|
+
autoRecall: true,
|
|
44
|
+
recallBudget: 2_400,
|
|
45
|
+
model: null
|
|
46
|
+
}),
|
|
47
|
+
setMemoryConfig: () => {}
|
|
48
|
+
}));
|
|
49
|
+
|
|
50
|
+
mock.module('./indexer', () => ({ scheduleVectorIndexing: () => {} }));
|
|
51
|
+
mock.module('./notify', () => ({ notifyGraphChanged: () => {}, notifyMemoryStatus: () => {} }));
|
|
52
|
+
|
|
53
|
+
const { graphQueries } = await import('$backend/database/queries/graph-queries');
|
|
54
|
+
const { draftMemory, createMemory } = await import('./compose');
|
|
55
|
+
const { retrieve } = await import('./retrieval');
|
|
56
|
+
|
|
57
|
+
const PROJECT = 'project-a';
|
|
58
|
+
|
|
59
|
+
beforeEach(() => {
|
|
60
|
+
db = new Database(':memory:');
|
|
61
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
62
|
+
migration066.up(db as unknown as DatabaseConnection);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('drafting', () => {
|
|
66
|
+
it('works with no model configured, and says so', async () => {
|
|
67
|
+
const draft = (await draftMemory({
|
|
68
|
+
text: 'Never touch the vendored directory.\nIt is generated by the build and any edit is lost.',
|
|
69
|
+
projectId: PROJECT
|
|
70
|
+
}))!;
|
|
71
|
+
|
|
72
|
+
expect(draft.structured).toBe(false);
|
|
73
|
+
expect(draft.label).toBe('Never touch the vendored directory.');
|
|
74
|
+
expect(draft.body).toContain('generated by the build');
|
|
75
|
+
expect(draft.note).toContain('No memory model is configured');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('splits a single paragraph at the first sentence rather than at a character count', () => {
|
|
79
|
+
// A label is a claim. The first 140 characters of a paragraph is not one.
|
|
80
|
+
const text =
|
|
81
|
+
'Staging runs the old schema until March. Anything that assumes the new columns has to be feature-flagged until the cutover lands.';
|
|
82
|
+
|
|
83
|
+
return draftMemory({ text, projectId: PROJECT }).then(draft => {
|
|
84
|
+
expect(draft!.label).toBe('Staging runs the old schema until March.');
|
|
85
|
+
expect(draft!.body).toContain('feature-flagged');
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('redacts a secret the user pasted in passing', async () => {
|
|
90
|
+
const draft = (await draftMemory({
|
|
91
|
+
text: 'Remember the deploy key is AKIAIOSFODNN7EXAMPLE for the staging bucket.',
|
|
92
|
+
projectId: PROJECT
|
|
93
|
+
}))!;
|
|
94
|
+
|
|
95
|
+
expect(draft.label + draft.body).not.toContain('AKIAIOSFODNN7EXAMPLE');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('returns nothing for nothing', async () => {
|
|
99
|
+
expect(await draftMemory({ text: ' ', projectId: PROJECT })).toBeNull();
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('saving', () => {
|
|
104
|
+
it('records it as the user\'s, which is what exempts it from every automatic removal', () => {
|
|
105
|
+
const node = createMemory({
|
|
106
|
+
subkind: 'preference',
|
|
107
|
+
scope: 'global',
|
|
108
|
+
label: 'Prefers tabs',
|
|
109
|
+
body: 'Stated outright.',
|
|
110
|
+
projectId: PROJECT
|
|
111
|
+
})!;
|
|
112
|
+
|
|
113
|
+
expect(node.source).toBe('user');
|
|
114
|
+
expect(node.confidence).toBe(0.95);
|
|
115
|
+
// Global memories belong to the person, not to the repository they were
|
|
116
|
+
// noticed in — which is what lets them apply before any project is selected.
|
|
117
|
+
expect(node.projectId).toBeNull();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('records the entities it names as an attribute, not as nodes', () => {
|
|
121
|
+
// Entities used to be stub nodes so statements about one subject would
|
|
122
|
+
// converge. On a real graph that made 115 of 208 nodes empty-bodied names,
|
|
123
|
+
// with `about` pointing at a stub 220 times and at a file 6 — the graph was
|
|
124
|
+
// "memories about the names of technologies" rather than about code.
|
|
125
|
+
const node = createMemory({
|
|
126
|
+
subkind: 'observation',
|
|
127
|
+
scope: 'project',
|
|
128
|
+
label: 'Phoenix owns the billing cutover',
|
|
129
|
+
body: 'Agreed in the planning call.',
|
|
130
|
+
entities: ['Phoenix'],
|
|
131
|
+
projectId: PROJECT
|
|
132
|
+
})!;
|
|
133
|
+
|
|
134
|
+
expect(graphQueries.entityNamesOf(node.id)).toContain('Phoenix');
|
|
135
|
+
expect(graphQueries.neighbours(node.id, 1).some(n => n.node.subkind === 'entity')).toBe(false);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('finds the memory by the entity it named, without a hop', () => {
|
|
139
|
+
const node = createMemory({
|
|
140
|
+
subkind: 'observation',
|
|
141
|
+
scope: 'project',
|
|
142
|
+
label: 'The billing cutover is scheduled for March',
|
|
143
|
+
body: 'Agreed in the planning call.',
|
|
144
|
+
entities: ['Phoenix'],
|
|
145
|
+
projectId: PROJECT
|
|
146
|
+
})!;
|
|
147
|
+
|
|
148
|
+
// The name is not in the prose at all — it is only an attribute — so this
|
|
149
|
+
// only passes because entity names are folded into the lexical index.
|
|
150
|
+
const hits = retrieve({ query: 'Phoenix', projectId: PROJECT, expandHops: 0 }).hits;
|
|
151
|
+
expect(hits.map(h => h.node.id)).toContain(node.id);
|
|
152
|
+
expect(graphQueries.memoriesAboutEntity('phoenix').map(n => n.id)).toContain(node.id);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it('reinforces an existing memory instead of storing a second copy', () => {
|
|
156
|
+
// Agreeing with something already stored should make it stronger, not add a
|
|
157
|
+
// near-copy that competes with it for the same recall budget.
|
|
158
|
+
const existing = graphQueries.upsert({
|
|
159
|
+
kind: 'episodic',
|
|
160
|
+
subkind: 'preference',
|
|
161
|
+
projectId: PROJECT,
|
|
162
|
+
label: 'Prefers tabs',
|
|
163
|
+
confidence: 0.6
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const node = createMemory({
|
|
167
|
+
subkind: 'preference',
|
|
168
|
+
scope: 'project',
|
|
169
|
+
label: 'Prefers tabs over spaces',
|
|
170
|
+
body: '',
|
|
171
|
+
projectId: PROJECT,
|
|
172
|
+
reinforceId: existing.id
|
|
173
|
+
})!;
|
|
174
|
+
|
|
175
|
+
expect(node.id).toBe(existing.id);
|
|
176
|
+
expect(node.confidence).toBe(0.95);
|
|
177
|
+
expect(graphQueries.count({ projectId: PROJECT, kinds: ['episodic'] })).toBe(1);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('makes it findable at once', () => {
|
|
181
|
+
const node = createMemory({
|
|
182
|
+
subkind: 'observation',
|
|
183
|
+
scope: 'project',
|
|
184
|
+
label: 'The vendored directory is generated',
|
|
185
|
+
body: 'Any edit is lost on the next build.',
|
|
186
|
+
projectId: PROJECT
|
|
187
|
+
})!;
|
|
188
|
+
|
|
189
|
+
const row = db
|
|
190
|
+
.prepare(`SELECT node_id FROM graph_nodes_fts WHERE graph_nodes_fts MATCH ?`)
|
|
191
|
+
.get('"vendored"*') as { node_id: string } | null;
|
|
192
|
+
expect(row?.node_id).toBe(node.id);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('refuses an empty claim', () => {
|
|
196
|
+
expect(createMemory({ subkind: 'observation', scope: 'project', label: ' ', body: '', projectId: PROJECT })).toBeNull();
|
|
197
|
+
});
|
|
198
|
+
});
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing a memory by hand.
|
|
3
|
+
*
|
|
4
|
+
* Automatic extraction has a hard limit that no amount of tuning removes: it can
|
|
5
|
+
* only record what a conversation happened to state. A constraint the user
|
|
6
|
+
* already knows — "never touch the vendored directory", "staging is on the old
|
|
7
|
+
* schema until March", "this client insists on tabs" — has to be said to an
|
|
8
|
+
* agent before it can be remembered, which means the mistake it would have
|
|
9
|
+
* prevented has usually already happened once. This is the way in that does not
|
|
10
|
+
* require staging a conversation to say something out loud.
|
|
11
|
+
*
|
|
12
|
+
* ── one field, then a review ──
|
|
13
|
+
* The input is one free-text box, because the alternative is a six-field form
|
|
14
|
+
* for a store whose whole promise is that you do not have to curate it. But what
|
|
15
|
+
* gets stored IS six fields, and letting a model fill the other five without
|
|
16
|
+
* showing its work would mean a graph whose contents nobody had read. So the
|
|
17
|
+
* write is two steps: shape it, show it, then save what was shown. The preview
|
|
18
|
+
* is editable, and the user can decline the shaping entirely.
|
|
19
|
+
*
|
|
20
|
+
* ── and it never depends on a model ──
|
|
21
|
+
* `structure: false` — or a missing/failing memory model — falls back to
|
|
22
|
+
* splitting the text into a heading and a body. That fallback is not a
|
|
23
|
+
* degradation to apologise for; it is what makes this the one part of memory
|
|
24
|
+
* that works on an instance with no model configured at all, which is exactly
|
|
25
|
+
* the instance whose graph is otherwise empty.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { graphQueries } from '$backend/database/queries/graph-queries';
|
|
29
|
+
import { initializeEngine } from '$backend/engine';
|
|
30
|
+
import { resolveGenerationTarget } from '$backend/engine/resolve-model';
|
|
31
|
+
import { debug } from '$shared/utils/logger';
|
|
32
|
+
import type { EpisodicSubkind, GraphNode, MemoryDraft } from '$shared/types/memory';
|
|
33
|
+
import { getMemoryConfig, type MemoryModelConfig } from './config';
|
|
34
|
+
import { scheduleVectorIndexing } from './indexer';
|
|
35
|
+
import { notifyGraphChanged } from './notify';
|
|
36
|
+
import { redactSecrets } from './redact';
|
|
37
|
+
import { findRelatedCandidates, linkEntities } from './revise';
|
|
38
|
+
import { resetGraphEmptiness } from './context';
|
|
39
|
+
|
|
40
|
+
/** Longest free-text input accepted. A memory is a claim, not a document. */
|
|
41
|
+
const MAX_INPUT_CHARS = 4_000;
|
|
42
|
+
|
|
43
|
+
const SUBKINDS: EpisodicSubkind[] = ['decision', 'pattern', 'failure', 'preference', 'observation', 'entity'];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Same lowest-common-denominator strict-mode shape as extraction: every property
|
|
47
|
+
* required, no additional properties, optionality as a nullable union.
|
|
48
|
+
*/
|
|
49
|
+
const DRAFT_SCHEMA = {
|
|
50
|
+
type: 'object',
|
|
51
|
+
additionalProperties: false,
|
|
52
|
+
properties: {
|
|
53
|
+
subkind: {
|
|
54
|
+
type: 'string',
|
|
55
|
+
enum: SUBKINDS,
|
|
56
|
+
description:
|
|
57
|
+
'entity = who or what something is; preference = how the user wants things done; decision = a choice and its reason; pattern = a convention that holds; failure = something that broke and why; observation = any other durable fact',
|
|
58
|
+
},
|
|
59
|
+
scope: {
|
|
60
|
+
type: 'string',
|
|
61
|
+
enum: ['project', 'global'],
|
|
62
|
+
description:
|
|
63
|
+
'global = true of how the user works everywhere; project = true only of the project this was written in'
|
|
64
|
+
},
|
|
65
|
+
label: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
description:
|
|
68
|
+
'MUST BE IN ENGLISH. One sentence stating the memory with its subject named, useful out of context. Max 140 characters.'
|
|
69
|
+
},
|
|
70
|
+
body: {
|
|
71
|
+
type: 'string',
|
|
72
|
+
description:
|
|
73
|
+
'MUST BE IN ENGLISH. Why this is true, what it rules out, what breaks without it. Two or three sentences. Never invent detail the input does not contain — if there is nothing to add, restate the claim precisely.'
|
|
74
|
+
},
|
|
75
|
+
entities: {
|
|
76
|
+
type: 'array',
|
|
77
|
+
description: 'People, tools or systems this memory is ABOUT, by name. Empty when none apply.',
|
|
78
|
+
items: { type: 'string' }
|
|
79
|
+
},
|
|
80
|
+
relatedPaths: {
|
|
81
|
+
type: 'array',
|
|
82
|
+
description: 'Repo-relative paths named in the input. Never invent one. Usually empty.',
|
|
83
|
+
items: { type: 'string' }
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
required: ['subkind', 'scope', 'label', 'body', 'entities', 'relatedPaths']
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export interface DraftInput {
|
|
90
|
+
/** What the user typed. */
|
|
91
|
+
text: string;
|
|
92
|
+
projectId: string | null;
|
|
93
|
+
/** False to skip the model and split the text as written. */
|
|
94
|
+
structure?: boolean;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Turn free text into a reviewable memory. Never throws — a model failure
|
|
99
|
+
* degrades to the split-as-written form with the reason attached.
|
|
100
|
+
*/
|
|
101
|
+
export async function draftMemory(input: DraftInput): Promise<MemoryDraft | null> {
|
|
102
|
+
const text = redactSecrets(input.text.trim().slice(0, MAX_INPUT_CHARS)).text.trim();
|
|
103
|
+
if (!text) return null;
|
|
104
|
+
|
|
105
|
+
const config = getMemoryConfig();
|
|
106
|
+
const wantsModel = input.structure !== false;
|
|
107
|
+
|
|
108
|
+
let draft: MemoryDraft;
|
|
109
|
+
if (!wantsModel) {
|
|
110
|
+
draft = splitAsWritten(text, input.projectId, null);
|
|
111
|
+
} else if (!config.model) {
|
|
112
|
+
draft = splitAsWritten(
|
|
113
|
+
text,
|
|
114
|
+
input.projectId,
|
|
115
|
+
'No memory model is configured, so this was saved as written. Choose one under Settings → Model → Memory.'
|
|
116
|
+
);
|
|
117
|
+
} else {
|
|
118
|
+
draft = (await structure(config.model, text, input.projectId)) ?? splitAsWritten(
|
|
119
|
+
text,
|
|
120
|
+
input.projectId,
|
|
121
|
+
'The memory model could not be reached, so this was kept as written.'
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Shown, not enforced. Two people can legitimately want both statements, and
|
|
126
|
+
// a duplicate check that silently refused the save would be the second-worst
|
|
127
|
+
// version of this feature — the worst being one that stores the same fact
|
|
128
|
+
// twice and lets ranking sort it out.
|
|
129
|
+
//
|
|
130
|
+
// This is the one caller that still shows a raw similarity neighbour, and it
|
|
131
|
+
// is the one where doing so is safe: a PERSON reads the suggestion and decides.
|
|
132
|
+
// The threshold that used to make this decision automatically is gone
|
|
133
|
+
// everywhere it acted alone, because cosine scores a claim and its negation
|
|
134
|
+
// higher than a claim and its own restatement.
|
|
135
|
+
const nearest = findRelatedCandidates({
|
|
136
|
+
text: `${draft.label}\n${draft.body}`,
|
|
137
|
+
subkind: draft.subkind,
|
|
138
|
+
projectId: draft.scope === 'global' ? null : input.projectId
|
|
139
|
+
})[0];
|
|
140
|
+
if (nearest) {
|
|
141
|
+
draft.duplicateOf = {
|
|
142
|
+
id: nearest.node.id,
|
|
143
|
+
label: nearest.node.label,
|
|
144
|
+
score: Number(nearest.score.toFixed(3))
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return draft;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface CreateInput {
|
|
152
|
+
subkind: EpisodicSubkind;
|
|
153
|
+
scope: 'project' | 'global';
|
|
154
|
+
label: string;
|
|
155
|
+
body: string;
|
|
156
|
+
entities?: string[];
|
|
157
|
+
relatedPaths?: string[];
|
|
158
|
+
projectId: string | null;
|
|
159
|
+
/**
|
|
160
|
+
* Whether this applies beyond the project it is written in. Omitted leaves it
|
|
161
|
+
* unjudged, and the maintenance pass decides — which is the right default for
|
|
162
|
+
* a one-box composer where asking would be a seventh field.
|
|
163
|
+
*/
|
|
164
|
+
reach?: 'here' | 'anywhere';
|
|
165
|
+
/** Exempt from decay and from every automatic removal. */
|
|
166
|
+
pinned?: boolean;
|
|
167
|
+
/** Reinforce this existing memory instead of storing a second copy. */
|
|
168
|
+
reinforceId?: string | null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Store a reviewed draft.
|
|
173
|
+
*
|
|
174
|
+
* `source: 'user'`, which is not bookkeeping — it is what exempts the node from
|
|
175
|
+
* structural decay, from eviction and from being archived into a consolidation,
|
|
176
|
+
* and what makes the injected block tell the agent a person said this rather
|
|
177
|
+
* than that a model inferred it.
|
|
178
|
+
*/
|
|
179
|
+
export function createMemory(input: CreateInput): GraphNode | null {
|
|
180
|
+
const label = redactSecrets(input.label.trim()).text.slice(0, 300);
|
|
181
|
+
if (!label) return null;
|
|
182
|
+
const body = redactSecrets((input.body ?? '').trim()).text;
|
|
183
|
+
|
|
184
|
+
const scope = input.scope === 'global' ? 'global' : 'project';
|
|
185
|
+
const projectId = scope === 'global' ? null : input.projectId;
|
|
186
|
+
|
|
187
|
+
// Reinforcing goes through the EXISTING node's identity, so a person agreeing
|
|
188
|
+
// with a memory raises its weight instead of adding a near-copy that competes
|
|
189
|
+
// with it for the same recall budget.
|
|
190
|
+
if (input.reinforceId) {
|
|
191
|
+
const existing = graphQueries.getById(input.reinforceId);
|
|
192
|
+
if (existing) {
|
|
193
|
+
const node = graphQueries.update(
|
|
194
|
+
existing.id,
|
|
195
|
+
{ confidence: Math.max(existing.confidence, 0.95), pinned: input.pinned ?? existing.pinned },
|
|
196
|
+
'user'
|
|
197
|
+
);
|
|
198
|
+
if (node) {
|
|
199
|
+
linkEntities(node.id, input.entities ?? []);
|
|
200
|
+
scheduleVectorIndexing();
|
|
201
|
+
notifyGraphChanged('created', projectId);
|
|
202
|
+
}
|
|
203
|
+
return node;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const node = graphQueries.upsert({
|
|
208
|
+
kind: 'episodic',
|
|
209
|
+
subkind: input.subkind,
|
|
210
|
+
scope,
|
|
211
|
+
projectId,
|
|
212
|
+
label,
|
|
213
|
+
body,
|
|
214
|
+
// Stated outright by a person, which is the highest confidence anything in
|
|
215
|
+
// the graph can have — extraction only reaches 0.95 for exactly this case.
|
|
216
|
+
confidence: 0.95,
|
|
217
|
+
source: 'user',
|
|
218
|
+
// A person typed this, so it carries the highest authority the graph
|
|
219
|
+
// recognises: nothing a model writes may retire it, and it goes into the
|
|
220
|
+
// standing-instructions section of every turn rather than competing for a
|
|
221
|
+
// recall slot.
|
|
222
|
+
assertedBy: 'user',
|
|
223
|
+
reach: input.reach ?? 'here',
|
|
224
|
+
reachJudged: input.reach !== undefined,
|
|
225
|
+
pinned: input.pinned ?? false
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
linkEntities(node.id, input.entities ?? []);
|
|
229
|
+
|
|
230
|
+
for (const raw of input.relatedPaths ?? []) {
|
|
231
|
+
const path = raw.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
232
|
+
const target = input.projectId ? graphQueries.getByPath(input.projectId, path) : null;
|
|
233
|
+
if (!target) continue;
|
|
234
|
+
graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about', source: 'user' });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
scheduleVectorIndexing();
|
|
238
|
+
resetGraphEmptiness();
|
|
239
|
+
notifyGraphChanged('created', projectId);
|
|
240
|
+
debug.log('memory', `Stored a hand-written memory: ${label.slice(0, 60)}`);
|
|
241
|
+
return node;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The text, split rather than interpreted.
|
|
246
|
+
*
|
|
247
|
+
* First line (or first sentence) is the claim, the rest is the reasoning. The
|
|
248
|
+
* subkind is `observation` because guessing without a model would be worse than
|
|
249
|
+
* a neutral default the user can change in the preview — the point of the
|
|
250
|
+
* preview is that nothing here has to be right, only visible.
|
|
251
|
+
*/
|
|
252
|
+
function splitAsWritten(text: string, projectId: string | null, note: string | null): MemoryDraft {
|
|
253
|
+
const lines = text.split('\n').map(line => line.trim()).filter(Boolean);
|
|
254
|
+
let label = lines[0] ?? text;
|
|
255
|
+
let body = lines.slice(1).join('\n');
|
|
256
|
+
|
|
257
|
+
// One paragraph carrying several sentences: the first is the claim and the rest
|
|
258
|
+
// is the reasoning, which is exactly the split the graph stores. Done on the
|
|
259
|
+
// SENTENCE rather than on a character count, because a label truncated at 140
|
|
260
|
+
// characters is not a claim, it is the first 140 characters of one.
|
|
261
|
+
if (!body) {
|
|
262
|
+
const stop = label.search(/[.!?](\s|$)/);
|
|
263
|
+
const rest = stop === -1 ? '' : label.slice(stop + 1).trim();
|
|
264
|
+
// A first sentence too short to stand alone, or nothing after it, is better
|
|
265
|
+
// left whole than cut in half.
|
|
266
|
+
if (stop > 20 && stop < 200 && rest.length > 0) {
|
|
267
|
+
body = rest;
|
|
268
|
+
label = label.slice(0, stop + 1).trim();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
subkind: 'observation',
|
|
274
|
+
scope: projectId ? 'project' : 'global',
|
|
275
|
+
label: label.slice(0, 300),
|
|
276
|
+
body,
|
|
277
|
+
entities: [],
|
|
278
|
+
relatedPaths: [],
|
|
279
|
+
structured: false,
|
|
280
|
+
duplicateOf: null,
|
|
281
|
+
note
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function structure(
|
|
286
|
+
model: MemoryModelConfig,
|
|
287
|
+
text: string,
|
|
288
|
+
projectId: string | null
|
|
289
|
+
): Promise<MemoryDraft | null> {
|
|
290
|
+
const prompt = `A person is writing one memory into a long-term store by hand. Below is exactly what they typed. Turn it into a single structured memory.
|
|
291
|
+
|
|
292
|
+
Change as little as possible. This is not a summary and not an improvement — the person already decided what they wanted to record, and your job is to file it. Do not add a claim they did not make, do not soften one they did, and do not invent a reason they did not give.
|
|
293
|
+
|
|
294
|
+
Write both fields in English, whatever language the input is in.
|
|
295
|
+
|
|
296
|
+
Choose "global" scope when the statement is about how this person works everywhere; "project" when it is only true of the codebase they are working in${projectId ? '' : '. There is no project selected, so this is almost certainly global'}.
|
|
297
|
+
|
|
298
|
+
What they typed:
|
|
299
|
+
${text}`;
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
const engine = await initializeEngine(model.engine);
|
|
303
|
+
if (!engine.generateStructured) return null;
|
|
304
|
+
|
|
305
|
+
const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
|
|
306
|
+
const accountId = model.accountId ?? target.accountId;
|
|
307
|
+
|
|
308
|
+
const result = await engine.generateStructured<{
|
|
309
|
+
subkind: EpisodicSubkind;
|
|
310
|
+
scope: 'project' | 'global';
|
|
311
|
+
label: string;
|
|
312
|
+
body: string;
|
|
313
|
+
entities: string[];
|
|
314
|
+
relatedPaths: string[];
|
|
315
|
+
}>({
|
|
316
|
+
prompt,
|
|
317
|
+
providerSlug: target.providerSlug,
|
|
318
|
+
modelId: target.modelId,
|
|
319
|
+
schema: DRAFT_SCHEMA,
|
|
320
|
+
projectPath: process.cwd(),
|
|
321
|
+
...(accountId != null && { accountId })
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
if (!result?.label?.trim()) return null;
|
|
325
|
+
|
|
326
|
+
return {
|
|
327
|
+
subkind: SUBKINDS.includes(result.subkind) ? result.subkind : 'observation',
|
|
328
|
+
// A model cannot promote a memory to project scope when there is no
|
|
329
|
+
// project to scope it to.
|
|
330
|
+
scope: result.scope === 'project' && projectId ? 'project' : 'global',
|
|
331
|
+
label: redactSecrets(result.label.trim()).text.slice(0, 300),
|
|
332
|
+
body: redactSecrets((result.body ?? '').trim()).text,
|
|
333
|
+
entities: Array.isArray(result.entities) ? result.entities.slice(0, 6) : [],
|
|
334
|
+
relatedPaths: Array.isArray(result.relatedPaths) ? result.relatedPaths.slice(0, 10) : [],
|
|
335
|
+
structured: true,
|
|
336
|
+
duplicateOf: null,
|
|
337
|
+
note: null
|
|
338
|
+
};
|
|
339
|
+
} catch (error) {
|
|
340
|
+
debug.warn('memory', 'Could not structure a hand-written memory', error);
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory Graph configuration.
|
|
3
|
+
*
|
|
4
|
+
* Split across two settings screens on purpose, mirroring how Artifacts works:
|
|
5
|
+
* the MODEL lives in Settings → Model → Memory next to the other model choices,
|
|
6
|
+
* and the BEHAVIOUR lives in Settings → Infrastructure → Memory. They answer different questions
|
|
7
|
+
* ("which model writes memories" vs "what should memory do"), and putting them
|
|
8
|
+
* on one page made both harder to find.
|
|
9
|
+
*
|
|
10
|
+
* The model only runs episodic extraction, after a turn has finished streaming
|
|
11
|
+
* and once the session has gone quiet (see `extract/scheduler.ts`). Nothing a
|
|
12
|
+
* user waits on calls a model: retrieval is BM25 plus a local lookup table plus
|
|
13
|
+
* SQL. That is why a slow model is acceptable here and would not be on the read
|
|
14
|
+
* path.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { settingsQueries } from '$backend/database/queries/settings-queries';
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
import type { EngineType } from '$shared/types/unified';
|
|
20
|
+
|
|
21
|
+
export interface MemoryModelConfig {
|
|
22
|
+
engine: EngineType;
|
|
23
|
+
providerSlug?: string;
|
|
24
|
+
modelId: string;
|
|
25
|
+
accountId?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface MemoryConfig {
|
|
29
|
+
/** Master switch: off means no recording, no retrieval, no injection. */
|
|
30
|
+
enabled: boolean;
|
|
31
|
+
/** Record the files and symbols each turn touches, read from the disk diff. */
|
|
32
|
+
recordCode: boolean;
|
|
33
|
+
/** Summarise finished turns into memories using `model`. */
|
|
34
|
+
recordMemories: boolean;
|
|
35
|
+
/** Hand relevant memories to the agent automatically at the start of a turn. */
|
|
36
|
+
autoRecall: boolean;
|
|
37
|
+
/** Model used for episodic extraction; null leaves memories unrecorded. */
|
|
38
|
+
model: MemoryModelConfig | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* THERE IS NO "HOW MUCH TO RECALL" SETTING, and its absence is deliberate.
|
|
43
|
+
*
|
|
44
|
+
* It was a character budget first, which did not bound what it claimed to —
|
|
45
|
+
* measured, its lowest setting produced a block 79% over the number chosen, and
|
|
46
|
+
* its highest silently undershot because the corpus ran out. Replacing it with a
|
|
47
|
+
* count of memories fixed the arithmetic and left the real problem: relevance is
|
|
48
|
+
* not uniform across turns. Six is too many for "ok, continue" and too few for a
|
|
49
|
+
* turn that touches a subject the graph knows a great deal about, and no fixed
|
|
50
|
+
* number can be right for both.
|
|
51
|
+
*
|
|
52
|
+
* The block now takes hits while they are still close to the best one for THAT
|
|
53
|
+
* query and stops when they fall away (see `RELATIVE_FLOOR` in context.ts), so
|
|
54
|
+
* the count follows the question. A hard ceiling remains, in code, as a cost
|
|
55
|
+
* backstop rather than as a control anyone is asked to reason about.
|
|
56
|
+
*/
|
|
57
|
+
const KEYS = {
|
|
58
|
+
enabled: 'memory_enabled',
|
|
59
|
+
recordCode: 'memory_record_code',
|
|
60
|
+
recordMemories: 'memory_record_memories',
|
|
61
|
+
autoRecall: 'memory_auto_recall',
|
|
62
|
+
model: 'memory_model'
|
|
63
|
+
} as const;
|
|
64
|
+
|
|
65
|
+
function readBoolean(key: string, fallback: boolean): boolean {
|
|
66
|
+
const row = settingsQueries.get(key);
|
|
67
|
+
return row ? row.value === 'true' : fallback;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function getMemoryConfig(): MemoryConfig {
|
|
71
|
+
let model: MemoryModelConfig | null = null;
|
|
72
|
+
const raw = settingsQueries.get(KEYS.model)?.value;
|
|
73
|
+
if (raw) {
|
|
74
|
+
try {
|
|
75
|
+
const parsed = JSON.parse(raw) as MemoryModelConfig;
|
|
76
|
+
if (parsed?.engine && parsed?.modelId) model = parsed;
|
|
77
|
+
} catch {
|
|
78
|
+
debug.warn('memory', 'memory_model setting is not valid JSON; memory recording disabled');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
enabled: readBoolean(KEYS.enabled, true),
|
|
84
|
+
recordCode: readBoolean(KEYS.recordCode, true),
|
|
85
|
+
recordMemories: readBoolean(KEYS.recordMemories, true),
|
|
86
|
+
autoRecall: readBoolean(KEYS.autoRecall, true),
|
|
87
|
+
model
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function setMemoryConfig(patch: Partial<MemoryConfig>): MemoryConfig {
|
|
92
|
+
if (patch.enabled !== undefined) settingsQueries.set(KEYS.enabled, String(patch.enabled));
|
|
93
|
+
if (patch.recordCode !== undefined) settingsQueries.set(KEYS.recordCode, String(patch.recordCode));
|
|
94
|
+
if (patch.recordMemories !== undefined) settingsQueries.set(KEYS.recordMemories, String(patch.recordMemories));
|
|
95
|
+
if (patch.autoRecall !== undefined) settingsQueries.set(KEYS.autoRecall, String(patch.autoRecall));
|
|
96
|
+
if (patch.model !== undefined) {
|
|
97
|
+
settingsQueries.set(KEYS.model, patch.model ? JSON.stringify(patch.model) : '');
|
|
98
|
+
}
|
|
99
|
+
return getMemoryConfig();
|
|
100
|
+
}
|