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,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
+ }
@@ -0,0 +1,129 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { closeSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from 'node:fs';
3
+ import { isAbsolute, join, matchesGlob, relative, resolve, sep } from 'node:path';
4
+ import { PathError } from '../errors.js';
5
+ export const DEFAULT_SCAN_OPTIONS = { maxFileSizeKb: 512, include: [], exclude: [] };
6
+ const EXCLUDED_DIRS = new Set([
7
+ '.git',
8
+ '.remimem',
9
+ 'node_modules',
10
+ 'dist',
11
+ 'vendor',
12
+ '__pycache__',
13
+ '.venv',
14
+ 'venv',
15
+ '.next',
16
+ 'coverage',
17
+ ]);
18
+ const LOCKFILES = /^(package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|bun\.lockb|go\.sum|.*\.lock)$/;
19
+ const GENERATED_NAME = /(\.min\.(js|css)|\.map|\.pb\.go|_pb2(_grpc)?\.pyi?)$|\.generated\./;
20
+ const SECRETS = /^(\.env.*|\.npmrc|\.netrc|\.pypirc|id_(rsa|dsa|ecdsa|ed25519).*|.*\.(pem|key|p12|pfx|jks|keystore))$/;
21
+ const GENERATED_HEADER = /Code generated .* DO NOT EDIT|@generated/;
22
+ const HEAD_BYTES = 8192;
23
+ /** True when the path is vendored, generated, a lockfile, or looks like a secret. */
24
+ export function isExcludedPath(path) {
25
+ const parts = path.split('/');
26
+ const base = parts.pop();
27
+ return (parts.some((dir) => EXCLUDED_DIRS.has(dir)) ||
28
+ LOCKFILES.test(base) ||
29
+ GENERATED_NAME.test(base) ||
30
+ SECRETS.test(base));
31
+ }
32
+ /** Resolves `path` against `root` and rejects anything outside it, following symlinks. */
33
+ export function resolveInRoot(root, path) {
34
+ const realRoot = realpathSync(root);
35
+ let target = resolve(realRoot, path);
36
+ try {
37
+ target = realpathSync(target);
38
+ }
39
+ catch {
40
+ // The file does not exist; the lexical check below still applies.
41
+ }
42
+ const rel = relative(realRoot, target);
43
+ if (rel.startsWith('..') || isAbsolute(rel)) {
44
+ throw new PathError(`Path is outside the repository root: ${path}`);
45
+ }
46
+ return target;
47
+ }
48
+ function listFiles(root) {
49
+ try {
50
+ // Tracked files plus untracked files that .gitignore does not exclude.
51
+ return execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
52
+ cwd: root,
53
+ encoding: 'utf8',
54
+ maxBuffer: 1 << 30,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ })
57
+ .split('\0')
58
+ .filter(Boolean);
59
+ }
60
+ catch {
61
+ // shortcut: without git, .gitignore is not read, only the built-in excludes apply.
62
+ // Add a .gitignore parser if non-git folders turn out to matter.
63
+ const out = [];
64
+ const walk = (dir) => {
65
+ for (const entry of readdirSync(join(root, dir), { withFileTypes: true })) {
66
+ const rel = dir ? `${dir}/${entry.name}` : entry.name;
67
+ if (entry.isDirectory()) {
68
+ if (!EXCLUDED_DIRS.has(entry.name))
69
+ walk(rel);
70
+ }
71
+ else if (entry.isFile()) {
72
+ out.push(rel);
73
+ }
74
+ }
75
+ };
76
+ walk('');
77
+ return out;
78
+ }
79
+ }
80
+ /** True for binary, minified, or generated content, judged from the first bytes of the file. */
81
+ export function hasExcludedContent(file) {
82
+ const buffer = Buffer.alloc(HEAD_BYTES);
83
+ const fd = openSync(file, 'r');
84
+ let length;
85
+ try {
86
+ length = readSync(fd, buffer, 0, HEAD_BYTES, 0);
87
+ }
88
+ finally {
89
+ closeSync(fd);
90
+ }
91
+ const head = buffer.subarray(0, length);
92
+ if (head.includes(0))
93
+ return true;
94
+ const text = head.toString('utf8');
95
+ const minified = text.length >= 2000 && !text.slice(0, 2000).includes('\n');
96
+ return minified || GENERATED_HEADER.test(text.slice(0, 1000));
97
+ }
98
+ /**
99
+ * Files under `root` that pass every check on name, type, and size, sorted by path. Their
100
+ * content has not been looked at yet: see `hasExcludedContent`.
101
+ */
102
+ export function listCandidates(root, options = {}) {
103
+ const opts = { ...DEFAULT_SCAN_OPTIONS, ...options };
104
+ const matches = (globs, path) => globs.some((glob) => matchesGlob(path, glob));
105
+ const files = [];
106
+ for (const listed of new Set(listFiles(root))) {
107
+ const path = listed.split(sep).join('/');
108
+ if (isExcludedPath(path) || matches(opts.exclude, path))
109
+ continue;
110
+ if (opts.include.length > 0 && !matches(opts.include, path))
111
+ continue;
112
+ try {
113
+ const stat = lstatSync(join(root, path));
114
+ if (!stat.isFile())
115
+ continue; // symlinks, submodules, deleted files
116
+ if (stat.size === 0 || stat.size > opts.maxFileSizeKb * 1024)
117
+ continue;
118
+ files.push({ path, sizeBytes: stat.size, mtimeMs: stat.mtimeMs });
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ }
124
+ return files.sort((a, b) => (a.path < b.path ? -1 : 1));
125
+ }
126
+ /** Lists the files worth indexing under `root`, sorted by path. */
127
+ export function scan(root, options = {}) {
128
+ return listCandidates(root, options).filter((file) => !hasExcludedContent(join(root, file.path)));
129
+ }
@@ -0,0 +1,32 @@
1
+ const number = (n) => n.toLocaleString('en-US');
2
+ /**
3
+ * `remimem stats`: what the tools served, against an estimated baseline. The baseline of a
4
+ * query is the size of every whole file that a full result came from, which is what an agent
5
+ * reading files would have loaded to see the same code. Files that only contributed a
6
+ * signature are not counted. Tools that do not return code
7
+ * (references, memory, status) count the same on both sides, so they claim no saving.
8
+ */
9
+ export function formatStats(store) {
10
+ const rows = store.queryLogSummary();
11
+ if (rows.length === 0) {
12
+ return 'No queries logged yet. Queries are logged when an MCP client or `remimem context` uses the index.';
13
+ }
14
+ const total = (pick) => rows.reduce((sum, row) => sum + pick(row), 0);
15
+ const queries = total((r) => r.queries);
16
+ const served = total((r) => r.tokensReturned);
17
+ const baseline = total((r) => r.baselineTokens);
18
+ const saved = baseline - served;
19
+ const since = rows.map((r) => r.since).sort()[0] ?? '';
20
+ const width = Math.max(...rows.map((r) => r.tool.length));
21
+ return [
22
+ `Queries served: ${number(queries)} since ${since.slice(0, 10)}`,
23
+ `Tokens served: ~${number(served)}`,
24
+ `Estimated baseline: ~${number(baseline)} tokens (reading in full every file a result body came from)`,
25
+ `Estimated saving: up to ~${number(saved)} tokens (${baseline > 0 ? Math.round((saved / baseline) * 100) : 0}%)`,
26
+ '',
27
+ 'By tool (queries, tokens served, estimated baseline, mean latency):',
28
+ ...rows.map((r) => ` ${r.tool.padEnd(width)} ${number(r.queries)} ~${number(r.tokensReturned)} ~${number(r.baselineTokens)} ${r.meanLatencyMs} ms`),
29
+ '',
30
+ 'Token counts are approximate, and the baseline is an estimate, not a measurement: it assumes an agent would have read each of those files in full, so treat the saving as an upper bound. `remimem bench` measures savings against a simulated grep-and-read agent.',
31
+ ].join('\n');
32
+ }
@@ -0,0 +1,26 @@
1
+ // Code-friendly tokenization for FTS5. SQLite cannot load a custom tokenizer through
2
+ // better-sqlite3, so text is expanded here before it is indexed or queried: every identifier
3
+ // is kept whole and also split into its camelCase and snake_case parts.
4
+ const WORD = /[\p{L}\p{N}_$]+/gu;
5
+ /** `parseHTTPResponse` gives `['parse', 'http', 'response']`; `find_user` gives `['find', 'user']`. */
6
+ export function identifierParts(identifier) {
7
+ return identifier
8
+ .replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, '$1 $2')
9
+ .replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu, '$1 $2')
10
+ .split(/[\s_$]+/)
11
+ .filter(Boolean)
12
+ .map((part) => part.toLowerCase());
13
+ }
14
+ /** Every identifier in lower case, followed by its parts when it has more than one. */
15
+ export function expandTerms(text) {
16
+ const out = [];
17
+ for (const word of text.match(WORD) ?? []) {
18
+ const parts = identifierParts(word);
19
+ out.push(word.toLowerCase());
20
+ if (parts.length > 1)
21
+ out.push(...parts);
22
+ }
23
+ return out;
24
+ }
25
+ /** The text stored in the FTS index for a piece of code, a symbol name, or a path. */
26
+ export const expandForIndex = (text) => expandTerms(text).join(' ');