remimem 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,272 @@
1
+ import { matchesGlob } from 'node:path';
2
+ import { z } from 'zod';
3
+ import { RemimemError } from '../errors.js';
4
+ import { describeSymbol, findReferences } from '../graph/describe.js';
5
+ import { indexRepo, pendingChanges } from '../indexer/index.js';
6
+ import { log } from '../log.js';
7
+ import { forget, formatMemory, linkedMemories, MEMORY_KINDS, recall, remember, } from '../memory/index.js';
8
+ import { pack } from '../packer/index.js';
9
+ import { LANGS, languageOf } from '../parser/index.js';
10
+ import { search } from '../retriever/index.js';
11
+ import { countTokens } from '../tokens.js';
12
+ /** How long a tool call waits for the index to catch up with the files. */
13
+ export const REFRESH_WAIT_MS = 2000;
14
+ const REFRESH_NOTE = '(index refresh still running: results may not include your latest edits)';
15
+ /** Room kept in the budget for the note above. */
16
+ const REFRESH_NOTE_TOKENS = 20;
17
+ export class EmptyIndexError extends RemimemError {
18
+ constructor(building = false) {
19
+ super(building
20
+ ? 'The index is still being built for the first time. Try again in a moment.'
21
+ : 'The index is empty. Run `remimem index` (or `remimem init`) in the project first.');
22
+ }
23
+ }
24
+ const withTokens = (text) => `${text}\n\n~${countTokens(text).toLocaleString('en-US')} tokens`;
25
+ function requireIndex(ctx) {
26
+ if (ctx.store.counts().files === 0)
27
+ throw new EmptyIndexError(ctx.refreshPending);
28
+ }
29
+ /** Search, filter by language and path globs, and pack into the budget. */
30
+ export async function query(ctx, text, options) {
31
+ requireIndex(ctx);
32
+ const { language, paths } = options;
33
+ const filtered = language !== undefined || (paths !== undefined && paths.length > 0);
34
+ // Filters are applied after ranking, so look further down the list when they are set.
35
+ const pool = filtered ? Math.min(options.k * 10, 200) : options.k;
36
+ let results = await search(ctx.store, text, ctx.config.retrieval, ctx.provider, pool);
37
+ if (filtered) {
38
+ let kept = 0;
39
+ results = results.filter((r) => {
40
+ const ok = (language === undefined || languageOf(r.chunk.path) === language) &&
41
+ (!paths?.length || paths.some((glob) => matchesGlob(r.chunk.path, glob)));
42
+ // Neighbors (signature only) ride along; only full results count toward k.
43
+ return ok && (r.detail === 'signature' || ++kept <= options.k);
44
+ });
45
+ }
46
+ const budget = options.budget - (ctx.refreshPending ? REFRESH_NOTE_TOKENS : 0);
47
+ const preamble = options.memories ? await memoryBlock(ctx, text, results, budget) : '';
48
+ const packed = pack(results, budget, preamble, ctx.config.retrieval.neighborBudgetShare);
49
+ // Only results shown in full count toward the baseline: an agent would have had to read
50
+ // those files, while the signature-only neighbors are an extra it would not have loaded.
51
+ const files = packed.included
52
+ .filter((item) => item.detail === 'full')
53
+ .map((item) => item.chunk.path);
54
+ const ranked = [...results].sort((a, b) => b.score - a.score).map((r) => r.chunk.path);
55
+ return { text: packed.text, files: [...new Set(files)], rankedFiles: [...new Set(ranked)] };
56
+ }
57
+ /**
58
+ * Runs a quick re-index if files changed, waiting at most `REFRESH_WAIT_MS`. A refresh that
59
+ * takes longer keeps running in the background and `ctx.refreshPending` says so.
60
+ */
61
+ export async function refreshIndex(ctx, waitMs = REFRESH_WAIT_MS) {
62
+ ctx.refreshing ??= indexRepo(ctx.root, ctx.store, ctx.config, {
63
+ quick: true,
64
+ provider: ctx.provider,
65
+ })
66
+ .catch((error) => log.warn(`index refresh failed: ${String(error)}`))
67
+ .finally(() => {
68
+ ctx.refreshing = undefined;
69
+ ctx.refreshPending = false;
70
+ });
71
+ let timer;
72
+ const timedOut = await Promise.race([
73
+ ctx.refreshing.then(() => false),
74
+ new Promise((done) => {
75
+ timer = setTimeout(() => done(true), waitMs);
76
+ }),
77
+ ]);
78
+ clearTimeout(timer);
79
+ ctx.refreshPending = timedOut;
80
+ }
81
+ /**
82
+ * Runs one tool the way every caller should: refresh the index first, run, add the refresh
83
+ * note when the index is behind, and log the query for `remimem stats`.
84
+ */
85
+ export async function runTool(ctx, tool, args, options = {}) {
86
+ const started = performance.now();
87
+ if (options.refresh !== false && tool.name !== 'index_status')
88
+ await refreshIndex(ctx);
89
+ const result = await tool.run(ctx, args);
90
+ const { text, files = [] } = typeof result === 'string' ? { text: result } : result;
91
+ const answer = ctx.refreshPending ? `${text}\n${REFRESH_NOTE}` : text;
92
+ const tokens = countTokens(answer);
93
+ const queryText = args['task'] ??
94
+ args['query'] ??
95
+ args['name'] ??
96
+ args['path'] ??
97
+ args['text'] ??
98
+ args['id'] ??
99
+ '';
100
+ try {
101
+ ctx.store.logQuery({
102
+ tool: tool.name,
103
+ query: String(queryText).slice(0, 500),
104
+ tokensReturned: tokens,
105
+ // Reading the same code without remimem means reading those files in full.
106
+ baselineTokens: Math.max(tokens, ctx.store.fileTokens(files)),
107
+ latencyMs: Math.round(performance.now() - started),
108
+ });
109
+ }
110
+ catch (error) {
111
+ log.warn(`could not log the query: ${String(error)}`);
112
+ }
113
+ return answer;
114
+ }
115
+ /**
116
+ * Project memory for a task: memories linked to a result's file as a whole or to a symbol
117
+ * in the results, then memories that match the task text. At most a quarter of the budget, so code keeps most of it.
118
+ */
119
+ async function memoryBlock(ctx, task, results, budget) {
120
+ if (ctx.config.retrieval.memoryLimit === 0)
121
+ return '';
122
+ const matched = await recall(ctx.root, ctx.store, ctx.provider, task, ctx.config.retrieval, {
123
+ limit: ctx.config.retrieval.memoryLimit,
124
+ });
125
+ const linked = linkedMemories(ctx.store, results.map((r) => ({ path: r.chunk.path, symbol: r.chunk.symbol })));
126
+ const seen = new Set();
127
+ const memories = [...linked, ...matched].filter((m) => !seen.has(m.id) && seen.add(m.id));
128
+ const lines = ['=== Project memory (decisions and conventions recorded for this repo) ==='];
129
+ for (const memory of memories) {
130
+ const next = [...lines, formatMemory(memory)];
131
+ if (countTokens(next.join('\n')) > budget / 4)
132
+ break;
133
+ lines.push(formatMemory(memory));
134
+ }
135
+ return lines.length > 1 ? lines.join('\n') : '';
136
+ }
137
+ const budgetSchema = z
138
+ .number()
139
+ .int()
140
+ .min(100)
141
+ .max(100_000)
142
+ .optional()
143
+ .describe('Maximum tokens to return. Default 4000.');
144
+ const pathsSchema = z
145
+ .array(z.string())
146
+ .optional()
147
+ .describe('Only return code from files matching these globs, e.g. ["src/api/**"].');
148
+ function tool(name, description, shape, run, readOnly = true) {
149
+ return { name, description, shape, readOnly, run: run };
150
+ }
151
+ // Descriptions are loaded into the agent's context on every session: keep them short.
152
+ export const TOOLS = [
153
+ tool('get_context', 'Best starting point for a coding task. Returns the most relevant code for the task within a token budget: full source of the top matches plus signatures of what they call and what calls them. Example: get_context({ task: "add rate limiting to the login endpoint" }).', {
154
+ task: z.string().min(1).describe('What you are about to do, in plain language.'),
155
+ budget_tokens: budgetSchema,
156
+ paths: pathsSchema,
157
+ }, (ctx, args) => query(ctx, args.task, {
158
+ k: ctx.config.retrieval.contextK,
159
+ budget: args.budget_tokens ?? ctx.config.retrieval.defaultBudgetTokens,
160
+ paths: args.paths,
161
+ memories: true,
162
+ })),
163
+ tool('search_code', 'Search the codebase by meaning and by identifier. Returns ranked code with the reason each result matched. Example: search_code({ query: "parse JWT token", k: 5 }).', {
164
+ query: z.string().min(1).describe('Words, a description, or a symbol name.'),
165
+ k: z.number().int().min(1).max(50).optional().describe('Number of results. Default 10.'),
166
+ budget_tokens: budgetSchema,
167
+ language: z.enum(LANGS).optional(),
168
+ paths: pathsSchema,
169
+ }, (ctx, args) => query(ctx, args.query, {
170
+ k: args.k ?? ctx.config.retrieval.defaultK,
171
+ budget: args.budget_tokens ?? ctx.config.retrieval.defaultBudgetTokens,
172
+ language: args.language,
173
+ paths: args.paths,
174
+ })),
175
+ tool('get_symbol', 'Fetch one function, class, or type by name, with its callers and callees. Use it to read a body that search returned as a signature. Example: get_symbol({ name: "UserService.login" }).', {
176
+ name: z
177
+ .string()
178
+ .min(1)
179
+ .describe('Plain or qualified name, e.g. "login" or "UserService.login".'),
180
+ include: z.enum(['signature', 'body']).optional().describe('Default "body".'),
181
+ depth: z
182
+ .number()
183
+ .int()
184
+ .min(0)
185
+ .max(2)
186
+ .optional()
187
+ .describe('Hops of callers and callees. Default 1.'),
188
+ }, (ctx, args) => {
189
+ requireIndex(ctx);
190
+ const files = ctx.store.symbolsNamed(args.name).map((symbol) => symbol.path);
191
+ return {
192
+ text: withTokens(describeSymbol(ctx.store, args.name, args)),
193
+ files: [...new Set(files)].slice(0, 1),
194
+ };
195
+ }),
196
+ tool('get_file_outline', 'List the symbols in a file with signatures and line numbers, without bodies. Example: get_file_outline({ path: "src/auth.ts" }).', { path: z.string().min(1).describe('File path relative to the project root.') }, (ctx, args) => {
197
+ requireIndex(ctx);
198
+ const path = args.path.replaceAll('\\', '/').replace(/^\.\//, '');
199
+ return { text: withTokens(fileOutline(ctx.store, path)), files: [path] };
200
+ }),
201
+ tool('find_references', 'Find where a symbol is called, extended, used as a type, or imported, as path:line grouped by file. Run it before changing a symbol. Example: find_references({ name: "findUser" }).', { name: z.string().min(1).describe('Plain or qualified symbol name.') }, (ctx, args) => {
202
+ requireIndex(ctx);
203
+ return withTokens(findReferences(ctx.store, args.name));
204
+ }),
205
+ tool('remember', 'Save a decision, convention, gotcha, or todo about this codebase so future sessions see it. Link it to files or symbols so it is shown with them and flagged when they change. Example: remember({ text: "Passwords are hashed with argon2, never bcrypt", kind: "decision", symbols: ["hash"] }).', {
206
+ text: z.string().min(1).describe('The fact to keep, in one or two sentences.'),
207
+ kind: z.enum(MEMORY_KINDS),
208
+ paths: z.array(z.string()).optional().describe('Files this is about.'),
209
+ symbols: z.array(z.string()).optional().describe('Symbols this is about.'),
210
+ tags: z.array(z.string()).optional(),
211
+ }, (ctx, args) => {
212
+ const { memory, unlinked } = remember(ctx.root, ctx.store, args);
213
+ const links = memory.links.map((l) => (l.symbol ? `${l.path} ${l.symbol}` : l.path));
214
+ return [
215
+ `Stored memory ${memory.id} (${memory.kind})${links.length > 0 ? `, linked to ${links.join(', ')}` : ''}.`,
216
+ ...unlinked.map((name) => `Not linked: ${name}.`),
217
+ ].join('\n');
218
+ }, false),
219
+ tool('recall', 'Search saved project memory: decisions, conventions, gotchas, todos. Stale ones (their linked code changed) are marked. Example: recall({ query: "password hashing" }).', {
220
+ query: z.string().describe('What to look for. Empty lists everything.'),
221
+ kind: z.enum(MEMORY_KINDS).optional(),
222
+ }, async (ctx, args) => {
223
+ const memories = await recall(ctx.root, ctx.store, ctx.provider, args.query, ctx.config.retrieval, { kind: args.kind });
224
+ if (memories.length === 0)
225
+ return 'No memories match.';
226
+ return withTokens(memories.map(formatMemory).join('\n'));
227
+ }),
228
+ tool('forget', 'Delete a saved memory by id, e.g. one that recall marked stale and is no longer true. Example: forget({ id: "m_3f9a2c1b" }).', { id: z.string().min(1).describe('The memory id, as shown by recall.') }, (ctx, args) => {
229
+ if (!forget(ctx.root, ctx.store, args.id)) {
230
+ throw new RemimemError(`No memory with id ${args.id}. Use recall to list ids.`);
231
+ }
232
+ return `Forgot memory ${args.id}.`;
233
+ }, false),
234
+ tool('index_status', 'Report what the remimem index covers: files, chunks, last indexed commit, pending changes, embedding model.', {}, (ctx) => indexStatus(ctx)),
235
+ ];
236
+ /** The symbols of a file, nested ones indented under their parent. */
237
+ export function fileOutline(store, rawPath) {
238
+ const path = rawPath.replaceAll('\\', '/').replace(/^\.\//, '');
239
+ const language = store.fileLanguage(path);
240
+ if (language === undefined)
241
+ return `No file "${path}" in the index. Paths are relative to the project root.`;
242
+ const symbols = store.symbolsInFile(path);
243
+ if (symbols.length === 0) {
244
+ return `${path} has no symbols in the index (it is searchable as plain text).`;
245
+ }
246
+ const depth = new Map();
247
+ const out = [`${path} (${language ?? 'text'}, ${symbols.length} symbols)`];
248
+ for (const s of symbols) {
249
+ const level = s.parentId === null ? 0 : (depth.get(s.parentId) ?? 0) + 1;
250
+ depth.set(s.id, level);
251
+ const indent = ' '.repeat(level);
252
+ out.push(`${indent}${s.startLine}-${s.endLine} ${s.kind} ${s.name}`);
253
+ for (const line of s.signature.split('\n'))
254
+ out.push(`${indent} ${line}`);
255
+ }
256
+ return out.join('\n');
257
+ }
258
+ export async function indexStatus(ctx) {
259
+ const { store } = ctx;
260
+ const counts = store.counts();
261
+ if (counts.files === 0)
262
+ return new EmptyIndexError().message;
263
+ const pending = await pendingChanges(ctx.root, store, ctx.config);
264
+ const commit = store.getMeta('last_indexed_commit');
265
+ const model = store.embeddingModel();
266
+ return [
267
+ `Files: ${counts.files} | Symbols: ${counts.symbols} | Chunks: ${counts.chunks} | Edges: ${store.edgeCount()}`,
268
+ `Last indexed: ${store.getMeta('last_indexed_at') ?? 'unknown'}${commit ? ` at commit ${commit.slice(0, 12)}` : ' (no git commit)'}`,
269
+ `Pending changes: ${pending.changed} changed, ${pending.added} new, ${pending.deleted} deleted${pending.changed + pending.added + pending.deleted > 0 ? ' (run `remimem index`)' : ''}`,
270
+ `Embedding model: ${model ? `${model} (${store.vectorCount()} of ${counts.chunks} chunks embedded)` : 'none (keyword search only)'}`,
271
+ ].join('\n');
272
+ }
@@ -0,0 +1,259 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { CONFIG_DIR } from '../config/index.js';
6
+ import { RemimemError } from '../errors.js';
7
+ import { ftsQuery, fuse, queryTokens } from '../retriever/index.js';
8
+ import { expandTerms } from '../store/fts.js';
9
+ export class MemoryError extends RemimemError {
10
+ }
11
+ export const MEMORY_KINDS = ['decision', 'convention', 'gotcha', 'todo'];
12
+ /** The committable mirror of the memory tables: `.remimem/memory.json`. */
13
+ const FileSchema = z.object({
14
+ version: z.literal(1),
15
+ memories: z.array(z.object({
16
+ id: z.string().min(1),
17
+ kind: z.enum(MEMORY_KINDS),
18
+ text: z.string().min(1),
19
+ tags: z.array(z.string()).default([]),
20
+ createdAt: z.string(),
21
+ updatedAt: z.string(),
22
+ links: z
23
+ .array(z.object({
24
+ path: z.string(),
25
+ symbol: z.string().nullable().default(null),
26
+ contentHash: z.string(),
27
+ }))
28
+ .default([]),
29
+ })),
30
+ });
31
+ const mirrorPath = (root) => join(root, CONFIG_DIR, 'memory.json');
32
+ const hashOf = (text) => createHash('sha256').update(text).digest('hex');
33
+ /**
34
+ * Brings the database in line with `.remimem/memory.json` when the file has changed since
35
+ * the last look: after a `git pull`, a hand edit, or a deleted index. The file is the
36
+ * source of truth, so a team shares memories by committing it.
37
+ */
38
+ export function syncMemories(root, store) {
39
+ const path = mirrorPath(root);
40
+ if (!existsSync(path))
41
+ return;
42
+ const text = readFileSync(path, 'utf8');
43
+ const hash = hashOf(text);
44
+ if (store.getMeta('memory_json_hash') === hash)
45
+ return;
46
+ let parsed;
47
+ try {
48
+ parsed = FileSchema.parse(JSON.parse(text));
49
+ }
50
+ catch (cause) {
51
+ // Leave the database as it is rather than lose memories to a bad merge.
52
+ throw new MemoryError(`${CONFIG_DIR}/memory.json is not valid (${cause instanceof z.ZodError ? z.prettifyError(cause) : String(cause)}). Fix the file, or restore it with git.`);
53
+ }
54
+ store.transaction(() => {
55
+ const keep = new Set(parsed.memories.map((m) => m.id));
56
+ for (const existing of store.listMemories()) {
57
+ if (!keep.has(existing.id))
58
+ store.deleteMemory(existing.id);
59
+ }
60
+ const current = new Map(store.listMemories().map((m) => [m.id, m]));
61
+ for (const memory of parsed.memories) {
62
+ const known = current.get(memory.id);
63
+ // Untouched memories keep their stored vector.
64
+ if (!known || JSON.stringify(toFile(known)) !== JSON.stringify(memory))
65
+ store.putMemory(memory);
66
+ }
67
+ store.setMeta('memory_json_hash', hash);
68
+ });
69
+ refreshStaleness(store);
70
+ }
71
+ const toFile = (m) => ({
72
+ id: m.id,
73
+ kind: m.kind,
74
+ text: m.text,
75
+ tags: m.tags,
76
+ createdAt: m.createdAt,
77
+ updatedAt: m.updatedAt,
78
+ links: m.links,
79
+ });
80
+ function writeMirror(root, store) {
81
+ // Sorted by id with one memory per line: two people adding memories touch different
82
+ // lines, so git can merge the file without conflicts in most cases.
83
+ const lines = store
84
+ .listMemories()
85
+ .map(toFile)
86
+ .sort((a, b) => (a.id < b.id ? -1 : 1))
87
+ .map((memory) => ` ${JSON.stringify(memory)}`);
88
+ const text = `{\n "version": 1,\n "memories": [\n${lines.join(',\n')}\n ]\n}\n`;
89
+ mkdirSync(join(root, CONFIG_DIR), { recursive: true });
90
+ // Write then rename, so a crash cannot leave half a file.
91
+ const temp = `${mirrorPath(root)}.tmp`;
92
+ writeFileSync(temp, text);
93
+ renameSync(temp, mirrorPath(root));
94
+ store.setMeta('memory_json_hash', hashOf(text));
95
+ }
96
+ /** The hash of what a link points at now, or null when the file or symbol is gone. */
97
+ function currentHash(store, files, link) {
98
+ if (link.symbol === null)
99
+ return files.get(link.path) ?? null;
100
+ const symbol = store.symbolAt(link.path, link.symbol);
101
+ if (!symbol)
102
+ return null;
103
+ return hashOf(store
104
+ .chunksOfSymbol(symbol.id)
105
+ .map((chunk) => chunk.content)
106
+ .join('\n'));
107
+ }
108
+ /**
109
+ * Marks a memory stale when any code it is linked to has changed or disappeared since the
110
+ * link was made. Run after every index. Returns how many memories are stale.
111
+ */
112
+ export function refreshStaleness(store) {
113
+ const files = store.fileHashes();
114
+ let staleCount = 0;
115
+ store.transaction(() => {
116
+ for (const memory of store.listMemories()) {
117
+ const stale = memory.links.some((link) => currentHash(store, files, link) !== link.contentHash);
118
+ if (stale)
119
+ staleCount++;
120
+ if (stale !== memory.stale)
121
+ store.setMemoryStale(memory.id, stale);
122
+ }
123
+ });
124
+ return staleCount;
125
+ }
126
+ /** Stores a memory and links it to code. Names that cannot be linked are reported back. */
127
+ export function remember(root, store, input) {
128
+ syncMemories(root, store);
129
+ const files = store.fileHashes();
130
+ const links = [];
131
+ const unlinked = [];
132
+ for (const raw of input.paths ?? []) {
133
+ const path = raw.replaceAll('\\', '/').replace(/^\.\//, '');
134
+ const contentHash = files.get(path);
135
+ if (contentHash)
136
+ links.push({ path, symbol: null, contentHash });
137
+ else
138
+ unlinked.push(`${raw} (no such file in the index)`);
139
+ }
140
+ for (const name of input.symbols ?? []) {
141
+ const matches = store.symbolsNamed(name);
142
+ const exact = matches.filter((s) => s.qualifiedName === name);
143
+ const candidates = exact.length > 0 ? exact : matches;
144
+ const symbol = candidates[0];
145
+ if (!symbol || candidates.length > 1) {
146
+ unlinked.push(`${name} (${symbol ? `${candidates.length} symbols have this name; use a qualified name` : 'no such symbol in the index'})`);
147
+ continue;
148
+ }
149
+ const link = { path: symbol.path, symbol: symbol.qualifiedName };
150
+ links.push({ ...link, contentHash: currentHash(store, files, link) ?? '' });
151
+ }
152
+ const now = new Date().toISOString();
153
+ const memory = {
154
+ id: `m_${randomBytes(4).toString('hex')}`,
155
+ kind: input.kind,
156
+ text: input.text.trim(),
157
+ tags: [...new Set(input.tags ?? [])],
158
+ createdAt: now,
159
+ updatedAt: now,
160
+ links,
161
+ };
162
+ if (!memory.text)
163
+ throw new MemoryError('A memory needs some text.');
164
+ store.transaction(() => store.putMemory(memory));
165
+ writeMirror(root, store);
166
+ return { memory: { ...memory, stale: false }, unlinked };
167
+ }
168
+ /** Deletes a memory. Returns false when there is none with that id. */
169
+ export function forget(root, store, id) {
170
+ syncMemories(root, store);
171
+ const removed = store.transaction(() => store.deleteMemory(id));
172
+ if (removed)
173
+ writeMirror(root, store);
174
+ return removed;
175
+ }
176
+ /** The share of the query's terms that occur in a memory, with the same prefix rule as search. */
177
+ function keywordMatch(terms, memory) {
178
+ if (terms.length === 0)
179
+ return 0;
180
+ const words = [...new Set(expandTerms(`${memory.text} ${memory.tags.join(' ')}`))];
181
+ const found = terms.filter((term) => words.some((word) => (term.length >= 3 ? word.startsWith(term) : word === term)));
182
+ return found.length / terms.length;
183
+ }
184
+ /**
185
+ * Memories matching a query, best first: keyword and vector ranks fused the same way as
186
+ * code search. A memory must clear a minimum on at least one side: enough of the query's
187
+ * terms, or enough vector similarity. One shared word is not a match. An empty query
188
+ * lists everything.
189
+ */
190
+ export async function recall(root, store, provider, query, thresholds, options = {}) {
191
+ syncMemories(root, store);
192
+ const all = store.listMemories(options.kind);
193
+ const limit = options.limit ?? 10;
194
+ if (!query.trim())
195
+ return all.slice(0, limit);
196
+ const byId = new Map(all.map((m) => [m.id, m]));
197
+ const terms = [...new Set(queryTokens(query).flatMap((token) => expandTerms(token)))];
198
+ const match = ftsQuery(query);
199
+ const keyword = (match ? store.memoryKeywordSearch(match, 50) : []).filter((id) => {
200
+ const memory = byId.get(id);
201
+ return memory && keywordMatch(terms, memory) >= thresholds.memoryMinKeywordMatch;
202
+ });
203
+ let vector = [];
204
+ if (provider && all.length > 0) {
205
+ const stored = store.memoryEmbeddings(provider.id);
206
+ // Memories that arrived through memory.json have no vector yet.
207
+ const missing = stored.filter((m) => !m.embedding);
208
+ const fresh = await provider.embed(missing.map((m) => m.text), 'document');
209
+ for (const [i, m] of missing.entries()) {
210
+ m.embedding = fresh[i] ?? null;
211
+ if (m.embedding)
212
+ store.setMemoryEmbedding(m.id, provider.id, m.embedding);
213
+ }
214
+ const [target] = await provider.embed([query], 'query');
215
+ if (target) {
216
+ vector = stored
217
+ .flatMap((m) => {
218
+ if (!m.embedding)
219
+ return [];
220
+ let similarity = 0;
221
+ for (let i = 0; i < target.length; i++)
222
+ similarity += (target[i] ?? 0) * (m.embedding[i] ?? 0);
223
+ return similarity >= thresholds.memoryMinSimilarity ? [{ id: m.id, similarity }] : [];
224
+ })
225
+ .sort((a, b) => b.similarity - a.similarity)
226
+ .map((m) => m.id);
227
+ }
228
+ }
229
+ // Ranks are positions in each list; `fuse` works on numbers, so map ids to indexes.
230
+ const ids = [...new Set([...keyword, ...vector])];
231
+ const index = new Map(ids.map((id, i) => [id, i]));
232
+ const scores = fuse([keyword, vector].map((list) => list.map((id) => index.get(id))), 60);
233
+ return [...scores.entries()]
234
+ .sort((a, b) => b[1] - a[1])
235
+ .flatMap(([i]) => byId.get(ids[i]) ?? [])
236
+ .slice(0, limit);
237
+ }
238
+ /**
239
+ * Memories that belong with a set of results whatever their wording: those linked to a
240
+ * result's file as a whole, or to a symbol that is itself in the results. A memory linked
241
+ * to some other symbol of the same file has to earn its place through `recall`.
242
+ */
243
+ export function linkedMemories(store, results) {
244
+ const paths = new Set(results.map((r) => r.path));
245
+ const symbols = new Set(results.map((r) => `${r.path} ${r.symbol}`));
246
+ return store
247
+ .listMemories()
248
+ .filter((memory) => memory.links.some((link) => link.symbol === null ? paths.has(link.path) : symbols.has(`${link.path} ${link.symbol}`)));
249
+ }
250
+ /** One memory as text for an agent: kind, id, staleness, text, links, and tags. */
251
+ export function formatMemory(memory) {
252
+ const stale = memory.stale ? ' STALE: linked code has changed since this was written' : '';
253
+ const links = memory.links.map((l) => (l.symbol ? `${l.path} ${l.symbol}` : l.path));
254
+ const details = [
255
+ ...(links.length > 0 ? [`linked: ${links.join(', ')}`] : []),
256
+ ...(memory.tags.length > 0 ? [`tags: ${memory.tags.join(', ')}`] : []),
257
+ ];
258
+ return `[${memory.kind}] ${memory.id}${stale}\n ${memory.text.replaceAll('\n', '\n ')}${details.length > 0 ? `\n (${details.join('; ')})` : ''}`;
259
+ }
@@ -0,0 +1,149 @@
1
+ import { countTokens } from '../tokens.js';
2
+ /** Tokens set aside for the footer line so that adding it cannot break the budget. */
3
+ const FOOTER_RESERVE = 24;
4
+ const label = (chunk) => chunk.symbol ? `${chunk.kind} ${chunk.symbol}` : 'lines';
5
+ /**
6
+ * The source lines of a chunk. A later part of a split function carries its signature as
7
+ * extra leading lines, which are dropped here so parts can be joined back together.
8
+ */
9
+ function rawLines(chunk) {
10
+ const lines = chunk.content.split('\n');
11
+ const extra = lines.length - (chunk.endLine - chunk.startLine + 1);
12
+ return extra > 0 ? lines.slice(extra) : lines;
13
+ }
14
+ function toBlock(item) {
15
+ const { chunk } = item;
16
+ const signatureOnly = item.detail === 'signature' && chunk.signature !== '';
17
+ const doc = chunk.docstring ? `\n${chunk.docstring.replace(/^/gm, ' ')}` : '';
18
+ return {
19
+ path: chunk.path,
20
+ startLine: chunk.startLine,
21
+ endLine: chunk.endLine,
22
+ labels: [label(chunk)],
23
+ reasons: [...item.reasons],
24
+ body: signatureOnly ? `${chunk.signature}${doc}` : chunk.content,
25
+ score: item.score,
26
+ signatureOnly,
27
+ };
28
+ }
29
+ /**
30
+ * Blocks for the chosen items: grouped by file, in line order, with overlapping or adjacent
31
+ * chunks of a file joined into one block. Class headers and signature-only blocks stand
32
+ * alone because their text is not a plain slice of the file.
33
+ */
34
+ function buildBlocks(items) {
35
+ const byPath = new Map();
36
+ for (const item of items) {
37
+ byPath.set(item.chunk.path, [...(byPath.get(item.chunk.path) ?? []), item]);
38
+ }
39
+ const files = [...byPath.values()].sort((a, b) => Math.max(...b.map((i) => i.score)) - Math.max(...a.map((i) => i.score)));
40
+ const blocks = [];
41
+ for (const fileItems of files) {
42
+ const fileBlocks = [];
43
+ let open = null;
44
+ const sorted = [...fileItems].sort((a, b) => a.chunk.startLine - b.chunk.startLine || b.chunk.endLine - a.chunk.endLine);
45
+ for (const item of sorted) {
46
+ const { chunk } = item;
47
+ const mergeable = chunk.kind !== 'class' && !(item.detail === 'signature' && chunk.signature !== '');
48
+ if (!mergeable) {
49
+ fileBlocks.push(toBlock(item));
50
+ continue;
51
+ }
52
+ if (open && chunk.startLine <= open.endLine + 1) {
53
+ // Keep only the lines the open block does not already have.
54
+ open.lines.push(...rawLines(chunk).slice(Math.max(0, open.endLine + 1 - chunk.startLine)));
55
+ open.endLine = Math.max(open.endLine, chunk.endLine);
56
+ if (!open.labels.includes(label(chunk)))
57
+ open.labels.push(label(chunk));
58
+ open.reasons = [...new Set([...open.reasons, ...item.reasons])];
59
+ open.score = Math.max(open.score, item.score);
60
+ }
61
+ else {
62
+ // The first chunk of a block keeps its content as stored, signature prefix included.
63
+ open = { ...toBlock(item), lines: chunk.content.split('\n') };
64
+ fileBlocks.push(open);
65
+ }
66
+ }
67
+ for (const block of fileBlocks) {
68
+ if ('lines' in block)
69
+ block.body = block.lines.join('\n');
70
+ }
71
+ blocks.push(...fileBlocks.sort((a, b) => a.startLine - b.startLine || b.endLine - a.endLine));
72
+ }
73
+ return blocks;
74
+ }
75
+ function renderBlock(block) {
76
+ const note = block.signatureOnly ? ' (signature only)' : '';
77
+ return `--- ${block.path}:${block.startLine}-${block.endLine} ${block.labels.join(', ')} [${block.reasons.join(', ')}]${note}\n${block.body}`;
78
+ }
79
+ /** The items as blocks of text, without a budget or footer. */
80
+ export const render = (items) => buildBlocks(items).map(renderBlock).join('\n\n');
81
+ function footer(tokens, results, dropped) {
82
+ const drop = dropped > 0 ? ` | ${dropped} dropped for budget` : '';
83
+ return `~${tokens.toLocaleString('en-US')} tokens | ${results} result${results === 1 ? '' : 's'}${drop}`;
84
+ }
85
+ /**
86
+ * Fits ranked items into `budget` tokens. Items are taken in score order; one that does not
87
+ * fit in full is tried as signature-only before it is dropped. `preamble` (project memory)
88
+ * goes first and counts toward the budget; it is left out if it cannot fit. The returned
89
+ * text never exceeds the budget.
90
+ *
91
+ * `neighborShare` keeps that share of the budget free for signature-only items (graph
92
+ * neighbors). They score below every full result, so without it the full results use up
93
+ * the budget and the cheap pointers to related code are the first thing lost.
94
+ */
95
+ export function pack(candidates, budget, preamble = '', neighborShare = 0) {
96
+ const seen = new Set();
97
+ const items = [...candidates]
98
+ .sort((a, b) => b.score - a.score)
99
+ .filter((item) => !seen.has(item.chunk.id) && seen.add(item.chunk.id));
100
+ // Per-item cost is an estimate (joining blocks changes it slightly); the loop further
101
+ // down measures the real text.
102
+ const costOf = (item) => countTokens(renderBlock(toBlock(item))) + 2;
103
+ const bodyBudget = budget - FOOTER_RESERVE;
104
+ const head = preamble && countTokens(preamble) + 2 <= bodyBudget ? `${preamble}\n\n` : '';
105
+ const included = [];
106
+ const dropped = [];
107
+ let estimate = head ? countTokens(head) : 0;
108
+ const neighborCosts = new Map(items.filter((item) => item.detail === 'signature').map((item) => [item, costOf(item)]));
109
+ let reserve = Math.min(Math.floor(Math.max(0, neighborShare) * bodyBudget), [...neighborCosts.values()].reduce((sum, cost) => sum + cost, 0));
110
+ for (const item of items) {
111
+ const neighborCost = neighborCosts.get(item);
112
+ const limit = bodyBudget - (neighborCost === undefined ? reserve : 0);
113
+ const forms = item.detail === 'full' && item.chunk.signature
114
+ ? [item, { ...item, detail: 'signature' }]
115
+ : [item];
116
+ const fitting = forms
117
+ .map((form) => ({ form, cost: neighborCost ?? costOf(form) }))
118
+ .find(({ cost }) => estimate + cost <= limit);
119
+ if (neighborCost !== undefined)
120
+ reserve = Math.max(0, reserve - neighborCost);
121
+ if (fitting) {
122
+ included.push(fitting.form);
123
+ estimate += fitting.cost;
124
+ }
125
+ else {
126
+ dropped.push(item);
127
+ }
128
+ }
129
+ let body = `${head}${render(included)}`.trimEnd();
130
+ let tokens = countTokens(body);
131
+ while (included.length > 0 && tokens > bodyBudget) {
132
+ dropped.push(included.pop());
133
+ body = `${head}${render(included)}`.trimEnd();
134
+ tokens = countTokens(body);
135
+ }
136
+ // The footer states the size of the whole text, itself included.
137
+ let text = '';
138
+ let total = tokens + FOOTER_RESERVE;
139
+ for (let i = 0; i < 4; i++) {
140
+ text = `${body}${body ? '\n\n' : ''}${footer(total, included.length, dropped.length)}`;
141
+ const actual = countTokens(text);
142
+ if (actual === total)
143
+ break;
144
+ total = actual;
145
+ }
146
+ if (countTokens(text) > budget)
147
+ return { text: '', tokens: 0, included: [], dropped: items };
148
+ return { text, tokens: countTokens(text), included, dropped };
149
+ }