@myrialabs/clopen 0.4.26 → 0.4.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +21 -0
- package/backend/bootstrap.ts +18 -1
- package/backend/chat/engine-handoff.test.ts +229 -0
- package/backend/chat/engine-handoff.ts +439 -0
- package/backend/chat/stream-manager.ts +200 -16
- package/backend/database/migrations/066_create_memory_graph.ts +369 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/audit-log-queries.test.ts +10 -1
- package/backend/database/queries/graph-queries.ts +1764 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/memory-queue-queries.ts +381 -0
- package/backend/database/queries/snapshot-queries.ts +20 -0
- package/backend/engine/README.md +45 -2
- package/backend/engine/adapters/copilot/stream.ts +37 -1
- package/backend/engine/adapters/pi/models.ts +19 -7
- package/backend/engine/adapters/pi/stream.ts +2 -1
- package/backend/engine/docs/adapter-contract.md +25 -8
- package/backend/engine/docs/adding-an-engine.md +40 -4
- package/backend/engine/docs/frontend-and-chat.md +66 -1
- package/backend/engine/docs/lessons-learned.md +165 -6
- package/backend/engine/docs/quick-reference.md +10 -0
- package/backend/engine/docs/stack.md +10 -0
- package/backend/engine/docs/websocket-routes.md +15 -1
- package/backend/engine/engine-setup.ts +1 -1
- package/backend/engine/index.test.ts +186 -0
- package/backend/engine/index.ts +117 -71
- package/backend/engine/install-recipes.test.ts +105 -0
- package/backend/engine/install-recipes.ts +4 -1
- package/backend/index.ts +9 -0
- package/backend/mcp/internal/config.ts +6 -0
- package/backend/mcp/internal/servers/index.ts +2 -0
- package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
- package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
- package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
- package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
- package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
- package/backend/memory/README.md +432 -0
- package/backend/memory/bootstrap.ts +101 -0
- package/backend/memory/compose.test.ts +198 -0
- package/backend/memory/compose.ts +343 -0
- package/backend/memory/config.ts +100 -0
- package/backend/memory/consolidate.ts +280 -0
- package/backend/memory/context.test.ts +321 -0
- package/backend/memory/context.ts +451 -0
- package/backend/memory/embedding/embedder.test.ts +141 -0
- package/backend/memory/embedding/embedder.ts +269 -0
- package/backend/memory/embedding/index.ts +17 -0
- package/backend/memory/embedding/install.ts +254 -0
- package/backend/memory/embedding/paths.ts +101 -0
- package/backend/memory/embedding/vector-cache.ts +270 -0
- package/backend/memory/extract/episodic.ts +725 -0
- package/backend/memory/extract/index.ts +133 -0
- package/backend/memory/extract/languages.ts +176 -0
- package/backend/memory/extract/scheduler.test.ts +352 -0
- package/backend/memory/extract/scheduler.ts +406 -0
- package/backend/memory/extract/structural.test.ts +215 -0
- package/backend/memory/extract/structural.ts +364 -0
- package/backend/memory/index.ts +37 -0
- package/backend/memory/indexer.ts +150 -0
- package/backend/memory/invalidate.ts +134 -0
- package/backend/memory/judge.ts +285 -0
- package/backend/memory/maintenance.ts +132 -0
- package/backend/memory/model.ts +91 -0
- package/backend/memory/notify.ts +102 -0
- package/backend/memory/readiness.ts +74 -0
- package/backend/memory/redact.test.ts +101 -0
- package/backend/memory/redact.ts +133 -0
- package/backend/memory/retention.ts +139 -0
- package/backend/memory/retrieval.eval.test.ts +301 -0
- package/backend/memory/retrieval.test.ts +1023 -0
- package/backend/memory/retrieval.ts +707 -0
- package/backend/memory/revise.test.ts +693 -0
- package/backend/memory/revise.ts +400 -0
- package/backend/memory/time.ts +31 -0
- package/backend/memory/view.ts +164 -0
- package/backend/shipped-runtime-imports.test.ts +228 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/memory/crud.ts +631 -0
- package/backend/ws/memory/index.ts +41 -0
- package/backend/ws/sessions/crud.ts +10 -0
- package/backend/ws/snapshot/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
- 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,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn ingestion — the Memory Graph's write path.
|
|
3
|
+
*
|
|
4
|
+
* Called once per turn, after the snapshot has been captured. Structural
|
|
5
|
+
* extraction runs first and returns its path → node map, which episodic
|
|
6
|
+
* extraction then uses to attach `about` edges: the memory has to be able to
|
|
7
|
+
* name the code it concerns, and the code node must therefore already exist.
|
|
8
|
+
* Between the two, structural invalidation ages the memories whose code just
|
|
9
|
+
* changed underneath them.
|
|
10
|
+
*
|
|
11
|
+
* Writes are automatic rather than left to the agent's initiative. A graph that
|
|
12
|
+
* only fills when a model remembers to call a `remember` tool stays empty — the
|
|
13
|
+
* agent has no reason to believe anything is worth storing while it is busy
|
|
14
|
+
* solving the immediate problem. The `remember` action exists for deliberate,
|
|
15
|
+
* user-directed memories; this is what makes the graph accumulate on its own.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
import { getMemoryConfig } from '../config';
|
|
20
|
+
import { takeInjectedMemories } from '../context';
|
|
21
|
+
import { scheduleVectorIndexing } from '../indexer';
|
|
22
|
+
import { invalidateForChanges } from '../invalidate';
|
|
23
|
+
import { notifyGraphChanged } from '../notify';
|
|
24
|
+
import { scheduleEpisodicIngest } from './scheduler';
|
|
25
|
+
import { ingestStructuralChanges } from './structural';
|
|
26
|
+
|
|
27
|
+
export { ingestStructuralChanges } from './structural';
|
|
28
|
+
export { ingestEpisodicMemories } from './episodic';
|
|
29
|
+
export {
|
|
30
|
+
deferEpisodicIngest,
|
|
31
|
+
cancel as cancelEpisodicIngest,
|
|
32
|
+
flushEpisodicIngest,
|
|
33
|
+
hasPendingExtraction,
|
|
34
|
+
startExtractionRunner,
|
|
35
|
+
stopExtractionRunner,
|
|
36
|
+
runningExtractions
|
|
37
|
+
} from './scheduler';
|
|
38
|
+
|
|
39
|
+
export interface TurnIngestInput {
|
|
40
|
+
projectId: string;
|
|
41
|
+
projectPath: string;
|
|
42
|
+
sessionId: string;
|
|
43
|
+
userMessageId: string;
|
|
44
|
+
/**
|
|
45
|
+
* Repo-relative paths that changed on disk DURING THIS TURN.
|
|
46
|
+
*
|
|
47
|
+
* A delta, not the session's cumulative change set. The caller computes it by
|
|
48
|
+
* differencing the snapshot against its parent — see `stream-manager.ts`. The
|
|
49
|
+
* distinction is load-bearing: `session_changes` grows monotonically for the
|
|
50
|
+
* life of a session, so passing it directly meant the file cap kept re-ingesting
|
|
51
|
+
* whatever came first alphabetically while genuinely new files were dropped, and
|
|
52
|
+
* the extraction prompt described a hundred files as "changed this turn".
|
|
53
|
+
*/
|
|
54
|
+
changedPaths: string[];
|
|
55
|
+
/** Paths that no longer exist on disk, so their nodes can be retired. */
|
|
56
|
+
deletedPaths?: string[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Ingest one completed turn: structural nodes now, episodic summary later.
|
|
61
|
+
*
|
|
62
|
+
* Fire-and-forget from the caller's perspective and guaranteed not to throw —
|
|
63
|
+
* the turn is already over, so nothing here may surface as a user-visible
|
|
64
|
+
* failure.
|
|
65
|
+
*/
|
|
66
|
+
export async function ingestTurn(input: TurnIngestInput): Promise<void> {
|
|
67
|
+
const config = getMemoryConfig();
|
|
68
|
+
if (!config.enabled) return;
|
|
69
|
+
|
|
70
|
+
// The structural half is allowed to fail on its own.
|
|
71
|
+
//
|
|
72
|
+
// It reads the disk, and reading the disk can go wrong in ways the episodic
|
|
73
|
+
// half has no stake in — a file that vanished mid-turn, a permission error, a
|
|
74
|
+
// snapshot that never completed. Sharing one `try` meant any of those cost the
|
|
75
|
+
// TRANSCRIPT too, and the transcript is the irreplaceable half: the code can
|
|
76
|
+
// be re-read on the next turn, while the conversation that explained why it
|
|
77
|
+
// changed exists once.
|
|
78
|
+
let fileNodes = new Map<string, string>();
|
|
79
|
+
if (config.recordCode) {
|
|
80
|
+
try {
|
|
81
|
+
const structural = await ingestStructuralChanges({
|
|
82
|
+
projectId: input.projectId,
|
|
83
|
+
projectPath: input.projectPath,
|
|
84
|
+
sessionId: input.sessionId,
|
|
85
|
+
changedPaths: input.changedPaths
|
|
86
|
+
});
|
|
87
|
+
fileNodes = structural.fileNodes;
|
|
88
|
+
|
|
89
|
+
// Structural nodes are searchable immediately; ask for their vectors now
|
|
90
|
+
// rather than waiting for episodic extraction to finish talking to a model.
|
|
91
|
+
if (structural.files > 0) {
|
|
92
|
+
scheduleVectorIndexing();
|
|
93
|
+
notifyGraphChanged('code', input.projectId);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The code just moved. Memories that described how it worked are now
|
|
97
|
+
// standing on something that changed, and the ones that explain WHY it
|
|
98
|
+
// changed are not — see `invalidate.ts` for why one rate would be worse
|
|
99
|
+
// than doing nothing.
|
|
100
|
+
invalidateForChanges({
|
|
101
|
+
projectId: input.projectId,
|
|
102
|
+
changedPaths: input.changedPaths,
|
|
103
|
+
deletedPaths: input.deletedPaths
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
debug.warn('memory', 'Structural ingestion failed (non-fatal)', error);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!config.recordMemories) return;
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// Queued rather than awaited, and it runs immediately: the queue is durable,
|
|
114
|
+
// so a crash between here and the model call costs nothing, and the entry
|
|
115
|
+
// carries everything the extraction needs. It is only held back while the
|
|
116
|
+
// session is actually streaming — see `extract/scheduler.ts`.
|
|
117
|
+
scheduleEpisodicIngest({
|
|
118
|
+
projectId: input.projectId,
|
|
119
|
+
projectPath: input.projectPath,
|
|
120
|
+
sessionId: input.sessionId,
|
|
121
|
+
userMessageId: input.userMessageId,
|
|
122
|
+
changedPaths: input.changedPaths,
|
|
123
|
+
deletedPaths: input.deletedPaths,
|
|
124
|
+
fileNodes,
|
|
125
|
+
// Consumed here rather than read: the memories injected into this turn are
|
|
126
|
+
// adjudicated exactly once, by the extraction that reads the turn they
|
|
127
|
+
// were given to.
|
|
128
|
+
injectedMemoryIds: takeInjectedMemories(input.sessionId)
|
|
129
|
+
});
|
|
130
|
+
} catch (error) {
|
|
131
|
+
debug.warn('memory', 'Turn ingestion failed (non-fatal)', error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Language detection and source-level pattern extraction.
|
|
3
|
+
*
|
|
4
|
+
* Imports and definitions are recovered with regular expressions, not a parser.
|
|
5
|
+
* That is a deliberate trade: a real AST per language would mean a tree-sitter
|
|
6
|
+
* grammar (and a WASM runtime) for every language a user might open, on a hot
|
|
7
|
+
* path that runs after every turn. What the graph needs is the *shape* of the
|
|
8
|
+
* codebase — which files reference which, and roughly what each defines — and
|
|
9
|
+
* regexes recover that well enough to be useful while costing microseconds.
|
|
10
|
+
*
|
|
11
|
+
* The limits are real and worth stating: a commented-out import still counts, a
|
|
12
|
+
* dynamic `import(variable)` is invisible, and a declaration split across lines
|
|
13
|
+
* may be missed. Structural nodes are therefore treated as evidence rather than
|
|
14
|
+
* ground truth, and every one carries `confidence` below 1.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** File extension → language label. */
|
|
18
|
+
const EXTENSIONS: Record<string, string> = {
|
|
19
|
+
ts: 'typescript',
|
|
20
|
+
tsx: 'typescript',
|
|
21
|
+
mts: 'typescript',
|
|
22
|
+
cts: 'typescript',
|
|
23
|
+
js: 'javascript',
|
|
24
|
+
jsx: 'javascript',
|
|
25
|
+
mjs: 'javascript',
|
|
26
|
+
cjs: 'javascript',
|
|
27
|
+
svelte: 'svelte',
|
|
28
|
+
vue: 'vue',
|
|
29
|
+
py: 'python',
|
|
30
|
+
pyi: 'python',
|
|
31
|
+
go: 'go',
|
|
32
|
+
rs: 'rust',
|
|
33
|
+
java: 'java',
|
|
34
|
+
kt: 'kotlin',
|
|
35
|
+
kts: 'kotlin',
|
|
36
|
+
swift: 'swift',
|
|
37
|
+
rb: 'ruby',
|
|
38
|
+
php: 'php',
|
|
39
|
+
cs: 'csharp',
|
|
40
|
+
c: 'c',
|
|
41
|
+
h: 'c',
|
|
42
|
+
cc: 'cpp',
|
|
43
|
+
cpp: 'cpp',
|
|
44
|
+
hpp: 'cpp',
|
|
45
|
+
css: 'css',
|
|
46
|
+
scss: 'scss',
|
|
47
|
+
html: 'html',
|
|
48
|
+
json: 'json',
|
|
49
|
+
yml: 'yaml',
|
|
50
|
+
yaml: 'yaml',
|
|
51
|
+
toml: 'toml',
|
|
52
|
+
sql: 'sql',
|
|
53
|
+
sh: 'shell',
|
|
54
|
+
bash: 'shell',
|
|
55
|
+
md: 'markdown'
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Extensions tried when resolving an extensionless relative import. */
|
|
59
|
+
const RESOLVE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.svelte', '.vue', '.py', '.go', '.rs'];
|
|
60
|
+
|
|
61
|
+
/** Languages worth reading the contents of; others become bare file nodes. */
|
|
62
|
+
const PARSEABLE = new Set([
|
|
63
|
+
'typescript',
|
|
64
|
+
'javascript',
|
|
65
|
+
'svelte',
|
|
66
|
+
'vue',
|
|
67
|
+
'python',
|
|
68
|
+
'go',
|
|
69
|
+
'rust',
|
|
70
|
+
'java',
|
|
71
|
+
'kotlin',
|
|
72
|
+
'ruby',
|
|
73
|
+
'php',
|
|
74
|
+
'csharp',
|
|
75
|
+
'c',
|
|
76
|
+
'cpp'
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
export function detectLanguage(path: string): string | null {
|
|
80
|
+
const ext = path.split('.').pop()?.toLowerCase();
|
|
81
|
+
return ext ? (EXTENSIONS[ext] ?? null) : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function isParseable(language: string | null): boolean {
|
|
85
|
+
return language !== null && PARSEABLE.has(language);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export { RESOLVE_EXTENSIONS };
|
|
89
|
+
|
|
90
|
+
/** Import/include specifiers per language family. */
|
|
91
|
+
const IMPORT_PATTERNS: Record<string, RegExp[]> = {
|
|
92
|
+
typescript: [
|
|
93
|
+
/\bimport\s+(?:type\s+)?(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+)['"]/g,
|
|
94
|
+
/\bexport\s+(?:type\s+)?[\w*{}\s,$]+\s+from\s+['"]([^'"]+)['"]/g,
|
|
95
|
+
/\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,
|
|
96
|
+
/\bimport\(\s*['"]([^'"]+)['"]\s*\)/g
|
|
97
|
+
],
|
|
98
|
+
python: [
|
|
99
|
+
/^\s*from\s+([\w.]+)\s+import\b/gm,
|
|
100
|
+
/^\s*import\s+([\w.]+)/gm
|
|
101
|
+
],
|
|
102
|
+
go: [/^\s*(?:\w+\s+)?"([^"]+)"\s*$/gm],
|
|
103
|
+
rust: [/^\s*use\s+([\w:]+)/gm],
|
|
104
|
+
java: [/^\s*import\s+(?:static\s+)?([\w.]+);/gm],
|
|
105
|
+
ruby: [/\brequire(?:_relative)?\s+['"]([^'"]+)['"]/g],
|
|
106
|
+
php: [/\b(?:require|include)(?:_once)?\s*\(?\s*['"]([^'"]+)['"]/g],
|
|
107
|
+
csharp: [/^\s*using\s+(?:static\s+)?([\w.]+)\s*;/gm],
|
|
108
|
+
c: [/^\s*#include\s*[<"]([^>"]+)[>"]/gm]
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
IMPORT_PATTERNS.javascript = IMPORT_PATTERNS.typescript;
|
|
112
|
+
IMPORT_PATTERNS.svelte = IMPORT_PATTERNS.typescript;
|
|
113
|
+
IMPORT_PATTERNS.vue = IMPORT_PATTERNS.typescript;
|
|
114
|
+
IMPORT_PATTERNS.kotlin = IMPORT_PATTERNS.java;
|
|
115
|
+
IMPORT_PATTERNS.cpp = IMPORT_PATTERNS.c;
|
|
116
|
+
|
|
117
|
+
/** Top-level definitions worth naming as their own node. */
|
|
118
|
+
const DEFINITION_PATTERNS: Record<string, RegExp[]> = {
|
|
119
|
+
typescript: [
|
|
120
|
+
/^\s*export\s+(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/gm,
|
|
121
|
+
/^\s*export\s+(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/gm,
|
|
122
|
+
/^\s*export\s+(?:interface|type|enum)\s+([A-Za-z_$][\w$]*)/gm,
|
|
123
|
+
/^\s*export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/gm
|
|
124
|
+
],
|
|
125
|
+
python: [
|
|
126
|
+
/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/gm,
|
|
127
|
+
/^\s*class\s+([A-Za-z_]\w*)/gm
|
|
128
|
+
],
|
|
129
|
+
go: [
|
|
130
|
+
/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/gm,
|
|
131
|
+
/^\s*type\s+([A-Za-z_]\w*)/gm
|
|
132
|
+
],
|
|
133
|
+
rust: [
|
|
134
|
+
/^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/gm,
|
|
135
|
+
/^\s*(?:pub\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)/gm
|
|
136
|
+
],
|
|
137
|
+
java: [
|
|
138
|
+
/^\s*(?:public|protected|private)?\s*(?:static\s+)?(?:final\s+)?(?:class|interface|enum|record)\s+([A-Za-z_]\w*)/gm
|
|
139
|
+
],
|
|
140
|
+
php: [/^\s*(?:abstract\s+|final\s+)?(?:class|interface|trait)\s+([A-Za-z_]\w*)/gm, /^\s*function\s+([A-Za-z_]\w*)/gm],
|
|
141
|
+
csharp: [/^\s*(?:public|internal|private|protected)?\s*(?:static\s+)?(?:sealed\s+)?(?:class|interface|record|struct|enum)\s+([A-Za-z_]\w*)/gm],
|
|
142
|
+
ruby: [/^\s*(?:class|module)\s+([A-Z]\w*)/gm, /^\s*def\s+([a-z_]\w*[?!]?)/gm]
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
DEFINITION_PATTERNS.javascript = DEFINITION_PATTERNS.typescript;
|
|
146
|
+
DEFINITION_PATTERNS.svelte = DEFINITION_PATTERNS.typescript;
|
|
147
|
+
DEFINITION_PATTERNS.vue = DEFINITION_PATTERNS.typescript;
|
|
148
|
+
DEFINITION_PATTERNS.kotlin = DEFINITION_PATTERNS.java;
|
|
149
|
+
DEFINITION_PATTERNS.cpp = DEFINITION_PATTERNS.c ?? [];
|
|
150
|
+
|
|
151
|
+
function collect(source: string, patterns: RegExp[] | undefined, limit: number): string[] {
|
|
152
|
+
if (!patterns) return [];
|
|
153
|
+
const found = new Set<string>();
|
|
154
|
+
for (const pattern of patterns) {
|
|
155
|
+
// Patterns are module-level and carry /g, so lastIndex must be reset or a
|
|
156
|
+
// previous file's position leaks into this one.
|
|
157
|
+
pattern.lastIndex = 0;
|
|
158
|
+
let match: RegExpExecArray | null;
|
|
159
|
+
while ((match = pattern.exec(source)) !== null) {
|
|
160
|
+
const value = match[1]?.trim();
|
|
161
|
+
if (value) found.add(value);
|
|
162
|
+
if (found.size >= limit) return [...found];
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return [...found];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Import specifiers referenced by a source file, verbatim. */
|
|
169
|
+
export function extractImports(source: string, language: string, limit = 80): string[] {
|
|
170
|
+
return collect(source, IMPORT_PATTERNS[language], limit);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Names of top-level definitions in a source file. */
|
|
174
|
+
export function extractDefinitions(source: string, language: string, limit = 40): string[] {
|
|
175
|
+
return collect(source, DEFINITION_PATTERNS[language], limit);
|
|
176
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extraction scheduling and its durability.
|
|
3
|
+
*
|
|
4
|
+
* Two behaviours are under test here and both were once silently wrong.
|
|
5
|
+
*
|
|
6
|
+
* WHICH TURN gets summarised when a session never pauses. Parking the NEWEST
|
|
7
|
+
* boundary — the original behaviour — discarded every turn but the last, because
|
|
8
|
+
* the transcript is built by slicing from the parked message to the end of the
|
|
9
|
+
* chain. Parking the OLDEST makes one extraction cover the whole span.
|
|
10
|
+
*
|
|
11
|
+
* WHAT HAPPENS WHEN IT FAILS. The queue used to be a `Map` and a `catch` that
|
|
12
|
+
* logged: a failed model call dropped the turn permanently, and a restart dropped
|
|
13
|
+
* everything. Since extraction is the ONLY write path in the feature, "failed
|
|
14
|
+
* once, gave up" is an unusually expensive default.
|
|
15
|
+
*
|
|
16
|
+
* `ingestEpisodicMemories` is mocked: what matters is which input reaches it,
|
|
17
|
+
* when, and what the queue does with each kind of answer.
|
|
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
|
+
interface Call {
|
|
41
|
+
sessionId: string;
|
|
42
|
+
userMessageId: string;
|
|
43
|
+
changedPaths: string[];
|
|
44
|
+
injectedMemoryIds: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const calls: Call[] = [];
|
|
48
|
+
type Reply = { ok: true; written: number } | { ok: false; error: string; countsAsAttempt: boolean };
|
|
49
|
+
let reply: Reply = { ok: true, written: 1 };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Held open to keep an extraction in flight.
|
|
53
|
+
*
|
|
54
|
+
* Extraction now starts the moment a turn is queued, so "a turn arrives while the
|
|
55
|
+
* previous one is still being summarised" — the case the revision counter exists
|
|
56
|
+
* for — cannot be produced by simply calling the scheduler twice. This makes the
|
|
57
|
+
* model call block until the test lets it finish.
|
|
58
|
+
*/
|
|
59
|
+
let gate: { promise: Promise<void>; open: () => void } | null = null;
|
|
60
|
+
|
|
61
|
+
function holdExtraction(): void {
|
|
62
|
+
let open!: () => void;
|
|
63
|
+
const promise = new Promise<void>(resolve => {
|
|
64
|
+
open = resolve;
|
|
65
|
+
});
|
|
66
|
+
gate = { promise, open };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
mock.module('./episodic', () => ({
|
|
70
|
+
ingestEpisodicMemories: async (input: Call) => {
|
|
71
|
+
calls.push({
|
|
72
|
+
sessionId: input.sessionId,
|
|
73
|
+
userMessageId: input.userMessageId,
|
|
74
|
+
changedPaths: [...input.changedPaths],
|
|
75
|
+
injectedMemoryIds: [...(input.injectedMemoryIds ?? [])]
|
|
76
|
+
});
|
|
77
|
+
if (gate) await gate.promise;
|
|
78
|
+
return reply;
|
|
79
|
+
}
|
|
80
|
+
}));
|
|
81
|
+
|
|
82
|
+
mock.module('../indexer', () => ({ scheduleVectorIndexing: () => {} }));
|
|
83
|
+
mock.module('../notify', () => ({ notifyGraphChanged: () => {}, notifyMemoryStatus: () => {} }));
|
|
84
|
+
|
|
85
|
+
const { memoryQueueQueries } = await import('$backend/database/queries/memory-queue-queries');
|
|
86
|
+
const { scheduleEpisodicIngest, deferEpisodicIngest, cancel, flushEpisodicIngest, hasPendingExtraction } =
|
|
87
|
+
await import('./scheduler');
|
|
88
|
+
|
|
89
|
+
function turn(userMessageId: string, changedPaths: string[] = [], injected: string[] = []) {
|
|
90
|
+
return {
|
|
91
|
+
projectId: 'p',
|
|
92
|
+
projectPath: '/tmp/p',
|
|
93
|
+
sessionId: 's',
|
|
94
|
+
userMessageId,
|
|
95
|
+
changedPaths,
|
|
96
|
+
fileNodes: new Map<string, string>(),
|
|
97
|
+
injectedMemoryIds: injected
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Make everything queued eligible now, so `flush` sees it without waiting. */
|
|
102
|
+
function makeDue(): void {
|
|
103
|
+
db.prepare(`UPDATE memory_extraction_queue SET ready_at = datetime('now', '-1 second')`).run();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Let the immediate drain that `scheduleEpisodicIngest` starts run to completion. */
|
|
107
|
+
async function settle(): Promise<void> {
|
|
108
|
+
for (let i = 0; i < 8; i++) await new Promise(resolve => setTimeout(resolve, 0));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
beforeEach(() => {
|
|
112
|
+
db = new Database(':memory:');
|
|
113
|
+
migration066.up(db as unknown as DatabaseConnection);
|
|
114
|
+
gate = null;
|
|
115
|
+
calls.length = 0;
|
|
116
|
+
reply = { ok: true, written: 1 };
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
describe('banking a turn', () => {
|
|
120
|
+
it('summarises a finished turn immediately, without waiting for a quiet period', async () => {
|
|
121
|
+
scheduleEpisodicIngest(turn('msg-1', ['a.ts']));
|
|
122
|
+
await settle();
|
|
123
|
+
|
|
124
|
+
expect(calls).toHaveLength(1);
|
|
125
|
+
expect(calls[0].userMessageId).toBe('msg-1');
|
|
126
|
+
// Gone from the queue: it was summarised, not parked.
|
|
127
|
+
expect(memoryQueueQueries.get('s')).toBeNull();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('keeps the oldest boundary when turns arrive faster than they can be summarised', async () => {
|
|
131
|
+
holdExtraction();
|
|
132
|
+
scheduleEpisodicIngest(turn('msg-1', ['a.ts']));
|
|
133
|
+
await settle();
|
|
134
|
+
expect(calls).toHaveLength(1);
|
|
135
|
+
|
|
136
|
+
// Two more turns land while the first is still with the model. They merge
|
|
137
|
+
// into the row in flight and keep the oldest boundary that is still
|
|
138
|
+
// unsummarised, so one later extraction covers the whole span.
|
|
139
|
+
scheduleEpisodicIngest(turn('msg-2', ['b.ts']));
|
|
140
|
+
scheduleEpisodicIngest(turn('msg-3', ['c.ts']));
|
|
141
|
+
|
|
142
|
+
gate!.open();
|
|
143
|
+
gate = null;
|
|
144
|
+
await settle();
|
|
145
|
+
|
|
146
|
+
expect(calls).toHaveLength(2);
|
|
147
|
+
// Still msg-1, deliberately. The merge keeps the oldest boundary because the
|
|
148
|
+
// transcript runs from it to the end of the chain, and nothing here can know
|
|
149
|
+
// how much of that span the in-flight extraction actually got through. The
|
|
150
|
+
// second pass therefore re-reads a superset rather than risking a gap —
|
|
151
|
+
// re-extracting a turn costs a duplicate that the digest and the cosine check
|
|
152
|
+
// both absorb, while skipping one loses it for good.
|
|
153
|
+
expect(calls[1].userMessageId).toBe('msg-1');
|
|
154
|
+
expect(memoryQueueQueries.get('s')).toBeNull();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('never deletes a turn that merged in while the previous one was running', async () => {
|
|
158
|
+
// The race the revision counter exists for. An unconditional delete on
|
|
159
|
+
// success would take the merged-in turn's boundary and paths with it —
|
|
160
|
+
// silently, on the only write path in the feature.
|
|
161
|
+
holdExtraction();
|
|
162
|
+
scheduleEpisodicIngest(turn('msg-1', ['a.ts'], ['mem-1']));
|
|
163
|
+
await settle();
|
|
164
|
+
|
|
165
|
+
scheduleEpisodicIngest(turn('msg-2', ['b.ts'], ['mem-2']));
|
|
166
|
+
gate!.open();
|
|
167
|
+
gate = null;
|
|
168
|
+
await settle();
|
|
169
|
+
|
|
170
|
+
expect(calls).toHaveLength(2);
|
|
171
|
+
expect(calls[1].changedPaths.sort()).toEqual(['a.ts', 'b.ts']);
|
|
172
|
+
expect(calls[1].injectedMemoryIds.sort()).toEqual(['mem-1', 'mem-2']);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('reports imminent work, which is what maintenance stands down for', async () => {
|
|
176
|
+
expect(hasPendingExtraction()).toBe(false);
|
|
177
|
+
holdExtraction();
|
|
178
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
179
|
+
expect(hasPendingExtraction()).toBe(true);
|
|
180
|
+
|
|
181
|
+
gate!.open();
|
|
182
|
+
gate = null;
|
|
183
|
+
await settle();
|
|
184
|
+
expect(hasPendingExtraction()).toBe(false);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('ignores an entry whose next attempt is far away', () => {
|
|
188
|
+
// An entry waiting on something the user has to fix — no model configured —
|
|
189
|
+
// stays pending by design. Counting that as "somebody is working" stood the
|
|
190
|
+
// whole maintenance loop down permanently on a default install.
|
|
191
|
+
memoryQueueQueries.enqueue({
|
|
192
|
+
sessionId: 's',
|
|
193
|
+
projectId: 'p',
|
|
194
|
+
projectPath: '/tmp/p',
|
|
195
|
+
userMessageId: 'msg-1',
|
|
196
|
+
changedPaths: [],
|
|
197
|
+
delaySeconds: 3_600
|
|
198
|
+
});
|
|
199
|
+
expect(memoryQueueQueries.status().pending).toBe(1);
|
|
200
|
+
expect(hasPendingExtraction()).toBe(false);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('drops a cancelled session without running it', async () => {
|
|
204
|
+
// Queued directly, with a delay, so it is still parked when the session is
|
|
205
|
+
// deleted — which is the situation `cancel` exists for.
|
|
206
|
+
memoryQueueQueries.enqueue({
|
|
207
|
+
sessionId: 's',
|
|
208
|
+
projectId: 'p',
|
|
209
|
+
projectPath: '/tmp/p',
|
|
210
|
+
userMessageId: 'msg-1',
|
|
211
|
+
changedPaths: [],
|
|
212
|
+
delaySeconds: 60
|
|
213
|
+
});
|
|
214
|
+
cancel('s');
|
|
215
|
+
|
|
216
|
+
await flushEpisodicIngest();
|
|
217
|
+
expect(calls).toHaveLength(0);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it('holds a banked turn while its session is streaming', async () => {
|
|
221
|
+
memoryQueueQueries.enqueue({
|
|
222
|
+
sessionId: 's',
|
|
223
|
+
projectId: 'p',
|
|
224
|
+
projectPath: '/tmp/p',
|
|
225
|
+
userMessageId: 'msg-1',
|
|
226
|
+
changedPaths: [],
|
|
227
|
+
delaySeconds: 0
|
|
228
|
+
});
|
|
229
|
+
deferEpisodicIngest('s');
|
|
230
|
+
|
|
231
|
+
// Pushed out of reach, so a summary is never generated mid-answer.
|
|
232
|
+
expect(memoryQueueQueries.dueWithin(0)).toBe(0);
|
|
233
|
+
|
|
234
|
+
makeDue();
|
|
235
|
+
await flushEpisodicIngest();
|
|
236
|
+
expect(calls[0].userMessageId).toBe('msg-1');
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('survives a restart, because the queue is a table', () => {
|
|
240
|
+
holdExtraction();
|
|
241
|
+
scheduleEpisodicIngest(turn('msg-1', ['a.ts']));
|
|
242
|
+
// Nothing in memory is consulted: a fresh read of the table is all a new
|
|
243
|
+
// process would have.
|
|
244
|
+
const entry = memoryQueueQueries.get('s');
|
|
245
|
+
expect(entry?.userMessageId).toBe('msg-1');
|
|
246
|
+
expect(entry?.changedPaths).toEqual(['a.ts']);
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
describe('when extraction fails', () => {
|
|
251
|
+
it('keeps the turn and schedules a retry', async () => {
|
|
252
|
+
reply = { ok: false, error: 'rate limited', countsAsAttempt: true };
|
|
253
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
254
|
+
|
|
255
|
+
await flushEpisodicIngest();
|
|
256
|
+
|
|
257
|
+
const entry = memoryQueueQueries.get('s');
|
|
258
|
+
expect(entry).not.toBeNull();
|
|
259
|
+
expect(entry!.attempts).toBe(1);
|
|
260
|
+
expect(entry!.lastError).toBe('rate limited');
|
|
261
|
+
expect(entry!.status).toBe('pending');
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('gives up only after repeated failures, and keeps the row', async () => {
|
|
265
|
+
reply = { ok: false, error: 'engine down', countsAsAttempt: true };
|
|
266
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
267
|
+
|
|
268
|
+
for (let i = 0; i < 6; i++) {
|
|
269
|
+
makeDue();
|
|
270
|
+
await flushEpisodicIngest();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const entry = memoryQueueQueries.get('s');
|
|
274
|
+
expect(entry!.status).toBe('failed');
|
|
275
|
+
// Kept rather than deleted, so it stays visible and can be retried.
|
|
276
|
+
expect(entry!.lastError).toBe('engine down');
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('does not burn attempts when no model is configured', async () => {
|
|
280
|
+
// Retrying harder will never configure a model. Spending the attempt budget
|
|
281
|
+
// on it would park the turn as failed within minutes, for something the user
|
|
282
|
+
// fixes by visiting a settings page — after which the turn should still be
|
|
283
|
+
// there.
|
|
284
|
+
reply = { ok: false, error: 'No model is configured', countsAsAttempt: false };
|
|
285
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
286
|
+
|
|
287
|
+
for (let i = 0; i < 4; i++) {
|
|
288
|
+
makeDue();
|
|
289
|
+
await flushEpisodicIngest();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const entry = memoryQueueQueries.get('s');
|
|
293
|
+
expect(entry!.attempts).toBe(0);
|
|
294
|
+
expect(entry!.status).toBe('pending');
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it('runs the banked turn once the model starts working', async () => {
|
|
298
|
+
reply = { ok: false, error: 'No model is configured', countsAsAttempt: false };
|
|
299
|
+
scheduleEpisodicIngest(turn('msg-1', ['a.ts']));
|
|
300
|
+
makeDue();
|
|
301
|
+
await flushEpisodicIngest();
|
|
302
|
+
expect(calls).toHaveLength(1);
|
|
303
|
+
|
|
304
|
+
reply = { ok: true, written: 2 };
|
|
305
|
+
makeDue();
|
|
306
|
+
await flushEpisodicIngest();
|
|
307
|
+
|
|
308
|
+
expect(calls).toHaveLength(2);
|
|
309
|
+
expect(calls[1].userMessageId).toBe('msg-1');
|
|
310
|
+
expect(memoryQueueQueries.get('s')).toBeNull();
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it('puts failed entries back on request', async () => {
|
|
314
|
+
reply = { ok: false, error: 'engine down', countsAsAttempt: true };
|
|
315
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
316
|
+
for (let i = 0; i < 6; i++) {
|
|
317
|
+
makeDue();
|
|
318
|
+
await flushEpisodicIngest();
|
|
319
|
+
}
|
|
320
|
+
expect(memoryQueueQueries.get('s')!.status).toBe('failed');
|
|
321
|
+
|
|
322
|
+
expect(memoryQueueQueries.retryFailed()).toBe(1);
|
|
323
|
+
const entry = memoryQueueQueries.get('s')!;
|
|
324
|
+
expect(entry.status).toBe('pending');
|
|
325
|
+
expect(entry.attempts).toBe(0);
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it('drops the turn when there was simply nothing to record', async () => {
|
|
329
|
+
// A conversation that established nothing durable is a success, not a
|
|
330
|
+
// failure, and must not sit in the queue forever being retried.
|
|
331
|
+
reply = { ok: true, written: 0 };
|
|
332
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
333
|
+
|
|
334
|
+
await flushEpisodicIngest();
|
|
335
|
+
expect(memoryQueueQueries.get('s')).toBeNull();
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
describe('queue status', () => {
|
|
340
|
+
it('counts what is waiting, retrying and stuck', async () => {
|
|
341
|
+
reply = { ok: false, error: 'nope', countsAsAttempt: true };
|
|
342
|
+
scheduleEpisodicIngest(turn('msg-1'));
|
|
343
|
+
makeDue();
|
|
344
|
+
await flushEpisodicIngest();
|
|
345
|
+
|
|
346
|
+
const status = memoryQueueQueries.status();
|
|
347
|
+
expect(status.pending).toBe(1);
|
|
348
|
+
expect(status.retrying).toBe(1);
|
|
349
|
+
expect(status.failed).toBe(0);
|
|
350
|
+
expect(status.lastError).toBe('nope');
|
|
351
|
+
});
|
|
352
|
+
});
|