remimem 0.0.0-stage → 0.2.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/dist/chunker/index.js +129 -0
  4. package/dist/cli/commands.js +256 -0
  5. package/dist/cli/index.js +39 -0
  6. package/dist/cli/program.js +328 -0
  7. package/dist/cli/ui.js +138 -0
  8. package/dist/config/index.js +116 -0
  9. package/dist/dashboard/api.js +196 -0
  10. package/dist/dashboard/graph.js +58 -0
  11. package/dist/dashboard/server.js +164 -0
  12. package/dist/dashboard/ui/app.css +1 -0
  13. package/dist/dashboard/ui/app.js +324 -0
  14. package/dist/dashboard/ui/app.js.LEGAL.txt +18 -0
  15. package/dist/dashboard/ui/index.html +32 -0
  16. package/dist/embedder/index.js +226 -0
  17. package/dist/errors.js +15 -0
  18. package/dist/graph/describe.js +90 -0
  19. package/dist/graph/index.js +224 -0
  20. package/dist/indexer/index.js +183 -0
  21. package/dist/indexer/overview.js +75 -0
  22. package/dist/indexer/watch.js +55 -0
  23. package/dist/log.js +16 -0
  24. package/dist/mcp/server.js +82 -0
  25. package/dist/mcp/tools.js +273 -0
  26. package/dist/memory/index.js +262 -0
  27. package/dist/packer/index.js +149 -0
  28. package/dist/parser/index.js +294 -0
  29. package/dist/retriever/index.js +186 -0
  30. package/dist/scanner/index.js +129 -0
  31. package/dist/stats/index.js +32 -0
  32. package/dist/store/fts.js +26 -0
  33. package/dist/store/index.js +658 -0
  34. package/dist/tokens.js +8 -0
  35. package/grammars/README.md +15 -0
  36. package/grammars/ecma.scm +42 -0
  37. package/grammars/go.scm +37 -0
  38. package/grammars/go.wasm +0 -0
  39. package/grammars/javascript.scm +6 -0
  40. package/grammars/javascript.wasm +0 -0
  41. package/grammars/python.scm +21 -0
  42. package/grammars/python.wasm +0 -0
  43. package/grammars/tsx.wasm +0 -0
  44. package/grammars/typescript.scm +20 -0
  45. package/grammars/typescript.wasm +0 -0
  46. package/package.json +71 -4
@@ -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
+ }
@@ -0,0 +1,294 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { Language, Parser, Query } from 'web-tree-sitter';
5
+ import { GrammarError } from '../errors.js';
6
+ const EXTENSIONS = {
7
+ '.ts': 'typescript',
8
+ '.mts': 'typescript',
9
+ '.cts': 'typescript',
10
+ '.tsx': 'tsx',
11
+ '.js': 'javascript',
12
+ '.mjs': 'javascript',
13
+ '.cjs': 'javascript',
14
+ '.jsx': 'javascript',
15
+ '.py': 'python',
16
+ '.go': 'go',
17
+ };
18
+ const QUERY_FILES = {
19
+ javascript: ['ecma', 'javascript'],
20
+ typescript: ['ecma', 'typescript'],
21
+ tsx: ['ecma', 'typescript'],
22
+ python: ['python'],
23
+ go: ['go'],
24
+ };
25
+ export const LANGS = Object.keys(QUERY_FILES);
26
+ const GRAMMAR_DIR = new URL('../../grammars/', import.meta.url);
27
+ /** Node types that wrap a definition and belong to it. */
28
+ const WRAPPERS = new Set(['export_statement', 'decorated_definition']);
29
+ /** The structural language for a path, or null when the file gets line windows. */
30
+ export function languageOf(path) {
31
+ return EXTENSIONS[extname(path).toLowerCase()] ?? null;
32
+ }
33
+ let init;
34
+ const loaded = new Map();
35
+ function load(lang) {
36
+ let entry = loaded.get(lang);
37
+ if (!entry) {
38
+ entry = (async () => {
39
+ try {
40
+ await (init ??= Parser.init());
41
+ const language = await Language.load(fileURLToPath(new URL(`${lang}.wasm`, GRAMMAR_DIR)));
42
+ const scm = await Promise.all(QUERY_FILES[lang].map((name) => readFile(new URL(`${name}.scm`, GRAMMAR_DIR), 'utf8')));
43
+ const parser = new Parser();
44
+ parser.setLanguage(language);
45
+ return { parser, query: new Query(language, scm.join('\n')) };
46
+ }
47
+ catch (cause) {
48
+ throw new GrammarError(`Grammar for ${lang} failed to load; run \`remimem doctor\``, {
49
+ cause,
50
+ });
51
+ }
52
+ })();
53
+ loaded.set(lang, entry);
54
+ }
55
+ return entry;
56
+ }
57
+ /** Parses one file and extracts its symbols, call sites, and imports. */
58
+ export async function parseSource(lang, source) {
59
+ const { parser, query } = await load(lang);
60
+ const tree = parser.parse(source);
61
+ if (!tree)
62
+ return null;
63
+ try {
64
+ return extract(lang, source, tree.rootNode, query);
65
+ }
66
+ finally {
67
+ tree.delete(); // WASM memory is not garbage collected
68
+ }
69
+ }
70
+ const collapse = (text) => text.replace(/\s+/g, ' ').trim().slice(0, 300);
71
+ function cleanComment(text) {
72
+ return text
73
+ .split('\n')
74
+ .map((line) => line.replace(/^\s*(\/\*+|\/\/+|#+|\*(?!\/))\s?/, '').replace(/\s*\*+\/\s*$/, ''))
75
+ .join('\n')
76
+ .trim();
77
+ }
78
+ function buildDraft(lang, source, lines, kind, node, name, body, receiver, pattern) {
79
+ let outer = node;
80
+ while (outer.parent && WRAPPERS.has(outer.parent.type))
81
+ outer = outer.parent;
82
+ // TypeScript method decorators are siblings that come before the method.
83
+ let start = outer;
84
+ for (let p = start.previousNamedSibling; p?.type === 'decorator'; p = p.previousNamedSibling) {
85
+ start = p;
86
+ }
87
+ const comments = [];
88
+ let docStartRow = start.startPosition.row;
89
+ for (let p = start.previousNamedSibling; p?.type === 'comment' &&
90
+ p.endPosition.row >= docStartRow - 1 &&
91
+ (lines[p.startPosition.row] ?? '').slice(0, p.startPosition.column).trim() === ''; p = p.previousNamedSibling) {
92
+ comments.unshift(p.text);
93
+ docStartRow = p.startPosition.row;
94
+ }
95
+ let docstring = cleanComment(comments.join('\n'));
96
+ if (lang === 'python' && body) {
97
+ const first = body.namedChild(0);
98
+ const str = first?.type === 'expression_statement' ? first.namedChild(0) : null;
99
+ if (str?.type === 'string') {
100
+ docstring = str.text
101
+ .replace(/^[a-zA-Z]*("""|'''|"|')/, '')
102
+ .replace(/("""|'''|"|')$/, '')
103
+ .trim();
104
+ }
105
+ }
106
+ let block = body;
107
+ const only = block?.namedChildCount === 1 ? block.namedChild(0) : null;
108
+ if (only?.type === 'statement_list')
109
+ block = only; // Go wraps statements in a list node
110
+ const isCallable = kind === 'function' || kind === 'method';
111
+ return {
112
+ name,
113
+ qualifiedName: name,
114
+ kind: (kind === 'overload' ? 'function' : kind),
115
+ signature: body
116
+ ? collapse(source
117
+ .slice(start.startIndex, body.startIndex)
118
+ .split('\n')
119
+ .filter((line) => !line.trimStart().startsWith(lang === 'python' ? '#' : '//'))
120
+ .join('\n'))
121
+ : collapse(lines[start.startPosition.row] ?? ''),
122
+ docstring,
123
+ startLine: start.startPosition.row + 1,
124
+ endLine: outer.endPosition.row + 1,
125
+ docStartLine: docStartRow + 1,
126
+ parent: null,
127
+ body: body ? [body.startIndex, body.endIndex] : null,
128
+ stmtLines: isCallable && block ? block.namedChildren.map((n) => n.startPosition.row + 1) : [],
129
+ from: start.startIndex,
130
+ to: outer.endIndex,
131
+ pattern,
132
+ overload: kind === 'overload',
133
+ receiver,
134
+ parentRef: null,
135
+ };
136
+ }
137
+ function extract(lang, source, root, query) {
138
+ const lines = source.split('\n');
139
+ const drafts = new Map();
140
+ const rawRefs = new Map();
141
+ const importSources = new Map();
142
+ const bindings = [];
143
+ for (const match of query.matches(root)) {
144
+ const caps = new Map(match.captures.map((c) => [c.name, c.node]));
145
+ const defKey = [...caps.keys()].find((key) => key.startsWith('def.'));
146
+ const nameNode = caps.get('name');
147
+ const imp = caps.get('import');
148
+ if (defKey && nameNode) {
149
+ const existing = drafts.get(nameNode.id);
150
+ if (existing && existing.pattern <= match.patternIndex)
151
+ continue;
152
+ const node = caps.get(defKey);
153
+ drafts.set(nameNode.id, buildDraft(lang, source, lines, defKey.slice(4), node, nameNode.text, caps.get('body'), caps.get('receiver')?.text ?? null, match.patternIndex));
154
+ }
155
+ else if (imp) {
156
+ const src = caps.get('source')?.text;
157
+ const alias = caps.get('ialias')?.text;
158
+ const module = caps.get('imodule')?.text;
159
+ const named = caps.get('iname')?.text;
160
+ const fallback = caps.get('idefault') ?? caps.get('inamespace');
161
+ if (src)
162
+ importSources.set(imp.id, { source: src, line: imp.startPosition.row + 1 });
163
+ if (module) {
164
+ const local = alias ?? (lang === 'go' ? (module.split('/').at(-1) ?? module) : module);
165
+ bindings.push({ node: imp.id, source: module, name: '*', local });
166
+ }
167
+ else if (named) {
168
+ bindings.push({ node: imp.id, source: src, name: named, local: alias ?? named });
169
+ }
170
+ else if (fallback) {
171
+ const name = caps.has('idefault') ? 'default' : '*';
172
+ bindings.push({ node: imp.id, source: src, name, local: fallback.text });
173
+ }
174
+ if (!importSources.has(imp.id)) {
175
+ importSources.set(imp.id, { source: module ?? '', line: imp.startPosition.row + 1 });
176
+ }
177
+ }
178
+ else {
179
+ const refKey = [...caps.keys()].find((key) => key.startsWith('ref.'));
180
+ const node = caps.get('callee') ?? (refKey ? caps.get(refKey) : undefined);
181
+ if (!node || rawRefs.has(node.id))
182
+ continue; // earlier patterns win
183
+ const recv = caps.get('recv')?.text;
184
+ rawRefs.set(node.id, {
185
+ kind: refKey ? refKey.slice(4) : 'call',
186
+ name: node.text,
187
+ receiver: recv === undefined ? null : /^[\w.$]+$/.test(recv) ? recv : '',
188
+ line: node.startPosition.row + 1,
189
+ index: node.startIndex,
190
+ });
191
+ }
192
+ }
193
+ // A definition's own name is not a reference to it.
194
+ for (const id of drafts.keys())
195
+ rawRefs.delete(id);
196
+ const sorted = [...drafts.values()].sort((a, b) => a.from - b.from || b.to - a.to);
197
+ const stack = [];
198
+ for (const d of sorted) {
199
+ while (stack.length > 0 && stack.at(-1).to <= d.from)
200
+ stack.pop();
201
+ d.parentRef = stack.at(-1) ?? null;
202
+ stack.push(d);
203
+ }
204
+ for (const d of sorted) {
205
+ if (d.receiver) {
206
+ // Go methods live outside their type; attach them when the type is in this file.
207
+ d.parentRef = sorted.find((s) => s !== d && !s.parentRef && s.name === d.receiver) ?? null;
208
+ d.qualifiedName = `${d.receiver}.${d.name}`;
209
+ }
210
+ else if (d.parentRef) {
211
+ d.qualifiedName = `${d.parentRef.qualifiedName}.${d.name}`;
212
+ }
213
+ if (d.kind === 'function' && d.parentRef?.kind === 'class')
214
+ d.kind = 'method';
215
+ }
216
+ // Fold overload signatures into the implementation that follows; drop the rest.
217
+ const symbols = [];
218
+ let pending = [];
219
+ for (const d of sorted) {
220
+ if (d.overload) {
221
+ pending.push(d);
222
+ continue;
223
+ }
224
+ const mine = pending.filter((o) => o.name === d.name && o.parentRef === d.parentRef);
225
+ const first = mine[0];
226
+ if (first && d.body) {
227
+ d.signature = [...mine.map((o) => o.signature), d.signature].join('\n');
228
+ d.docstring ||= first.docstring;
229
+ d.startLine = first.startLine;
230
+ d.docStartLine = first.docStartLine;
231
+ d.from = first.from;
232
+ }
233
+ pending = [];
234
+ symbols.push(d);
235
+ }
236
+ const indexOf = new Map(symbols.map((s, i) => [s, i]));
237
+ const callerOf = (index) => {
238
+ let found = null;
239
+ for (let i = 0; i < symbols.length; i++) {
240
+ const s = symbols[i];
241
+ if (s.from > index)
242
+ break;
243
+ if (index < s.to)
244
+ found = i; // later matches are nested deeper
245
+ }
246
+ return found;
247
+ };
248
+ const imports = [];
249
+ const bound = new Set();
250
+ for (const b of bindings) {
251
+ const statement = importSources.get(b.node);
252
+ bound.add(b.node);
253
+ imports.push({
254
+ source: b.source ?? statement?.source ?? '',
255
+ name: b.name,
256
+ local: b.local,
257
+ line: statement?.line ?? 0,
258
+ });
259
+ }
260
+ for (const [node, { source: module, line }] of importSources) {
261
+ if (!bound.has(node))
262
+ imports.push({ source: module, name: '', local: '', line });
263
+ }
264
+ // One type reference per symbol and name is enough.
265
+ const seenTypes = new Set();
266
+ const refs = [];
267
+ for (const { index, ...ref } of [...rawRefs.values()].sort((a, b) => a.index - b.index)) {
268
+ const from = callerOf(index);
269
+ if (ref.kind === 'type') {
270
+ const key = `${from}:${ref.name}`;
271
+ if (seenTypes.has(key))
272
+ continue;
273
+ seenTypes.add(key);
274
+ }
275
+ refs.push({ ...ref, from });
276
+ }
277
+ return {
278
+ symbols: symbols.map((d) => ({
279
+ name: d.name,
280
+ qualifiedName: d.qualifiedName,
281
+ kind: d.kind,
282
+ signature: d.signature,
283
+ docstring: d.docstring,
284
+ startLine: d.startLine,
285
+ endLine: d.endLine,
286
+ docStartLine: d.docStartLine,
287
+ parent: d.parentRef ? (indexOf.get(d.parentRef) ?? null) : null,
288
+ body: d.body,
289
+ stmtLines: d.stmtLines,
290
+ })),
291
+ refs,
292
+ imports: imports.sort((a, b) => a.line - b.line),
293
+ };
294
+ }
@@ -0,0 +1,186 @@
1
+ import { EmbeddingError, modelChanged } from '../embedder/index.js';
2
+ import { expandTerms } from '../store/fts.js';
3
+ /** How a neighbor relates to the result it was reached from, as a reason for the agent. */
4
+ const NEIGHBOR_REASONS = {
5
+ calls: 'called by',
6
+ 'calls by': 'calls',
7
+ extends: 'extended by',
8
+ 'extends by': 'extends',
9
+ implements: 'implemented by',
10
+ 'implements by': 'implements',
11
+ 'uses-type': 'type used by',
12
+ };
13
+ /** Words that say nothing about code and would match almost every chunk. */
14
+ const STOPWORDS = new Set('a an and are as at be by do does for from how in is it of on or that the this to what when where which with'.split(' '));
15
+ /** Identifier-like tokens of a query, including dotted paths such as `UserService.login`. */
16
+ export function queryTokens(query) {
17
+ const tokens = query.match(/[\p{L}\p{N}_$]+(\.[\p{L}\p{N}_$]+)*/gu) ?? [];
18
+ return [...new Set(tokens)].filter((token) => !STOPWORDS.has(token.toLowerCase()));
19
+ }
20
+ /**
21
+ * The FTS5 query for a search: any term may match, and terms of three or more characters
22
+ * also match as a prefix, so `auth` finds `authenticate`.
23
+ */
24
+ export function ftsQuery(query) {
25
+ const terms = new Set(queryTokens(query).flatMap((token) => expandTerms(token)));
26
+ return [...terms].map((term) => (term.length >= 3 ? `"${term}"*` : `"${term}"`)).join(' OR ');
27
+ }
28
+ /**
29
+ * Names worth an exact symbol lookup: tokens shaped like identifiers (camelCase, snake_case,
30
+ * dotted paths), plus the last segment of a dotted path. A plain word such as `resolve` only
31
+ * counts when it is the whole query; otherwise ordinary words in a sentence would pull in
32
+ * every symbol that happens to share their name.
33
+ */
34
+ export function symbolCandidates(query) {
35
+ const tokens = queryTokens(query);
36
+ const names = tokens.filter((t) => tokens.length === 1 || /[._$\p{N}]|\p{Ll}\p{Lu}/u.test(t));
37
+ const lastSegments = names.filter((t) => t.includes('.')).map((t) => t.split('.').at(-1) ?? t);
38
+ return [...new Set([...names, ...lastSegments])];
39
+ }
40
+ /**
41
+ * Reciprocal rank fusion: each list adds 1 / (k + rank) to the items it contains, so an item
42
+ * ranked well by several lists beats one ranked first by a single list.
43
+ */
44
+ export function fuse(lists, k) {
45
+ const scores = new Map();
46
+ for (const list of lists) {
47
+ for (const [index, id] of list.entries()) {
48
+ scores.set(id, (scores.get(id) ?? 0) + 1 / (k + index + 1));
49
+ }
50
+ }
51
+ return scores;
52
+ }
53
+ /**
54
+ * Hybrid search: keyword (BM25) and vector results fused by rank, with exact symbol-name
55
+ * matches on top. Without a provider the search is keyword-only.
56
+ */
57
+ export async function search(store, query, config, provider, k = config.defaultK) {
58
+ const match = ftsQuery(query);
59
+ const keyword = match && config.keywordLimit > 0
60
+ ? store.keywordSearch(match, config.keywordLimit, config.keywordWeights).map((hit) => hit.id)
61
+ : [];
62
+ let vector = [];
63
+ if (provider && config.vectorLimit > 0 && query.trim() && store.embeddingModel() !== undefined) {
64
+ if (modelChanged(store, provider)) {
65
+ throw new EmbeddingError(`The index holds vectors from ${store.embeddingModel()} but the configured model is ${provider.id}; run \`remimem index --full\` to rebuild them`);
66
+ }
67
+ const [embedding] = await provider.embed([query], 'query');
68
+ if (embedding)
69
+ vector = store.vectorSearch(embedding, config.vectorLimit).map((hit) => hit.id);
70
+ }
71
+ const scores = fuse([keyword, vector], config.rrfK);
72
+ // An exact symbol name in the query outranks anything fusion can produce (at most 2 / k).
73
+ // The exact-name lookup is a keyword signal, so it is off when keyword search is.
74
+ const exact = new Set(config.keywordLimit > 0 ? store.chunkIdsForSymbols(symbolCandidates(query)) : []);
75
+ for (const id of exact)
76
+ scores.set(id, 1 + (scores.get(id) ?? 0));
77
+ // Chunks are loaded for every candidate (at most the two limits), so that text files can
78
+ // be down-weighted and one file cannot take every slot.
79
+ const chunks = new Map(store.getChunks([...scores.keys()]).map((c) => [c.id, c]));
80
+ if (config.textFileWeight !== 1) {
81
+ for (const [id, score] of scores) {
82
+ if (chunks.get(id)?.language === null)
83
+ scores.set(id, score * config.textFileWeight);
84
+ }
85
+ }
86
+ const perFile = new Map();
87
+ const ranked = [...scores.entries()]
88
+ .sort((a, b) => b[1] - a[1])
89
+ .filter(([id]) => {
90
+ if (config.maxChunksPerFile === 0)
91
+ return true;
92
+ const path = chunks.get(id)?.path ?? '';
93
+ const count = (perFile.get(path) ?? 0) + 1;
94
+ perFile.set(path, count);
95
+ return count <= config.maxChunksPerFile;
96
+ })
97
+ .slice(0, k);
98
+ const results = ranked.flatMap(([id, score]) => {
99
+ const chunk = chunks.get(id);
100
+ if (!chunk)
101
+ return [];
102
+ const keywordRank = keyword.indexOf(id) + 1;
103
+ const vectorRank = vector.indexOf(id) + 1;
104
+ return [
105
+ {
106
+ chunk,
107
+ score,
108
+ reasons: [
109
+ ...(exact.has(id) ? ['exact-symbol'] : []),
110
+ ...(keywordRank ? ['keyword'] : []),
111
+ ...(vectorRank ? ['vector'] : []),
112
+ ],
113
+ ranks: {
114
+ ...(keywordRank ? { keyword: keywordRank } : {}),
115
+ ...(vectorRank ? { vector: vectorRank } : {}),
116
+ },
117
+ detail: 'full',
118
+ },
119
+ ];
120
+ });
121
+ return [...results, ...expand(store, results, config)];
122
+ }
123
+ /**
124
+ * Graph expansion: the direct neighbors of the top results (callers, callees, base and
125
+ * derived classes, referenced types, the enclosing class), scored as the result's score
126
+ * times the weight of the edge's confidence. A neighbor that is already a result only
127
+ * gains a reason.
128
+ */
129
+ function expand(store, results, config) {
130
+ const bySymbol = new Map();
131
+ for (const result of results) {
132
+ const id = result.chunk.symbolId;
133
+ if (id !== null && !bySymbol.has(id))
134
+ bySymbol.set(id, result);
135
+ }
136
+ const seeds = [...bySymbol.keys()].slice(0, config.graphTopN);
137
+ const added = new Map();
138
+ for (const n of store.neighbors(seeds)) {
139
+ const parent = bySymbol.get(n.of);
140
+ const relation = n.relation === 'inside' && n.kind === 'class' ? 'contains' : NEIGHBOR_REASONS[n.relation];
141
+ if (!relation)
142
+ continue;
143
+ // A function nested in the result is already part of the result's text.
144
+ const inside = n.path === parent.chunk.path &&
145
+ n.startLine >= parent.chunk.startLine &&
146
+ n.endLine <= parent.chunk.endLine;
147
+ if (inside && n.relation !== 'inside')
148
+ continue;
149
+ const reason = `${relation} ${parent.chunk.symbol}`;
150
+ const existing = bySymbol.get(n.id) ?? added.get(n.id);
151
+ const weight = config.edgeWeights[n.confidence] ?? 0;
152
+ if (weight === 0)
153
+ continue;
154
+ const score = parent.score * weight;
155
+ if (existing) {
156
+ if (!existing.reasons.includes(reason))
157
+ existing.reasons.push(reason);
158
+ if (added.has(n.id))
159
+ existing.score = Math.max(existing.score, score);
160
+ continue;
161
+ }
162
+ const body = config.compressNeighbors ? undefined : store.chunksOfSymbol(n.id)[0];
163
+ added.set(n.id, {
164
+ // Not a stored chunk: the neighbor's own signature, under a negative id.
165
+ chunk: body ?? {
166
+ id: -n.id,
167
+ symbolId: n.id,
168
+ path: n.path,
169
+ language: null,
170
+ startLine: n.startLine,
171
+ endLine: n.endLine,
172
+ content: n.signature,
173
+ tokenCount: 0,
174
+ symbol: n.qualifiedName,
175
+ kind: n.kind,
176
+ signature: n.signature,
177
+ docstring: n.docstring,
178
+ },
179
+ score,
180
+ reasons: [reason],
181
+ ranks: {},
182
+ detail: body ? 'full' : 'signature',
183
+ });
184
+ }
185
+ return [...added.values()].sort((a, b) => b.score - a.score).slice(0, config.graphMaxNeighbors);
186
+ }