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,224 @@
1
+ import { posix } from 'node:path';
2
+ /** Languages that can refer to each other's symbols. */
3
+ const FAMILY = {
4
+ typescript: 'ecma',
5
+ tsx: 'ecma',
6
+ javascript: 'ecma',
7
+ python: 'python',
8
+ go: 'go',
9
+ };
10
+ const ECMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
11
+ const TYPE_KINDS = new Set(['class', 'interface', 'type', 'enum']);
12
+ const SELF = new Set(['this', 'self', 'cls']);
13
+ const dirOf = (path) => {
14
+ const dir = posix.dirname(path);
15
+ return dir === '.' ? '' : dir;
16
+ };
17
+ function push(map, key, value) {
18
+ const list = map.get(key);
19
+ if (list)
20
+ list.push(value);
21
+ else
22
+ map.set(key, [value]);
23
+ }
24
+ /**
25
+ * Resolves every reference and import to the symbol it most likely means. Best effort, in
26
+ * this order: the same file (`exact`), a name the file imports (`import`), then a name that
27
+ * is unique in the repo (`name-match`). A call through an import that leads outside the
28
+ * repo, such as `fmt.Println`, is left unresolved instead of guessed.
29
+ */
30
+ export function resolveReferences(input) {
31
+ const files = new Map(input.files.map((f) => [f.id, { ...f, dir: dirOf(f.path) }]));
32
+ const fileIdByPath = new Map(input.files.map((f) => [f.path, f.id]));
33
+ const filesByDir = new Map();
34
+ for (const f of files.values())
35
+ push(filesByDir, f.dir, f.id);
36
+ const familyOf = (fileId) => FAMILY[files.get(fileId)?.language ?? ''] ?? '';
37
+ const symbols = new Map(input.symbols.map((s) => [s.id, s]));
38
+ const inFile = new Map(); // "fileId:name", every symbol
39
+ const topLevel = new Map(); // "fileId:name", symbols without a parent
40
+ const children = new Map();
41
+ const byName = new Map();
42
+ const byQualified = new Map(); // "dir:qualifiedName"
43
+ for (const s of input.symbols) {
44
+ push(inFile, `${s.fileId}:${s.name}`, s);
45
+ if (s.parentId === null)
46
+ push(topLevel, `${s.fileId}:${s.name}`, s);
47
+ else
48
+ push(children, s.parentId, s);
49
+ push(byName, s.name, s);
50
+ byQualified.set(`${files.get(s.fileId)?.dir}:${s.qualifiedName}`, s);
51
+ }
52
+ const locals = new Map(); // "fileId:localName"
53
+ for (const i of input.imports)
54
+ if (i.local)
55
+ locals.set(`${i.fileId}:${i.local}`, i);
56
+ const moduleCache = new Map();
57
+ /** The repo files an import source refers to; empty when it leads outside the repo. */
58
+ const moduleFiles = (fileId, source) => {
59
+ const file = files.get(fileId);
60
+ if (!file || !source)
61
+ return [];
62
+ const family = familyOf(fileId);
63
+ const key = `${family}|${source.startsWith('.') ? file.dir : ''}|${source}`;
64
+ let found = moduleCache.get(key);
65
+ if (!found) {
66
+ found = findModule(family, file.dir, source);
67
+ moduleCache.set(key, found);
68
+ }
69
+ return found;
70
+ };
71
+ const existing = (paths) => {
72
+ const id = paths.map((p) => fileIdByPath.get(p)).find((x) => x !== undefined);
73
+ return id === undefined ? [] : [id];
74
+ };
75
+ /** The one file of a family whose path ends with one of the given paths. */
76
+ const bySuffix = (family, endings) => {
77
+ const hits = input.files.filter((f) => FAMILY[f.language ?? ''] === family &&
78
+ endings.some((end) => f.path === end || f.path.endsWith(`/${end}`)));
79
+ return hits.length === 1 ? [hits[0].id] : [];
80
+ };
81
+ function findModule(family, dir, source) {
82
+ if (family === 'ecma') {
83
+ const bare = source.replace(/\.(js|jsx|mjs|cjs|ts|tsx)$/, '');
84
+ const endings = (base) => ECMA_EXTENSIONS.flatMap((ext) => [`${base}${ext}`, `${base}/index${ext}`]);
85
+ return source.startsWith('.')
86
+ ? existing(endings(posix.normalize(posix.join(dir, bare))))
87
+ : bySuffix(family, endings(bare.replace(/^[@~]\//, '')));
88
+ }
89
+ if (family === 'python') {
90
+ const dots = /^\.*/.exec(source)?.[0].length ?? 0;
91
+ const rest = source.slice(dots).split('.').filter(Boolean).join('/');
92
+ if (dots === 0)
93
+ return bySuffix(family, [`${rest}.py`, `${rest}/__init__.py`]);
94
+ let base = dir;
95
+ for (let i = 1; i < dots; i++)
96
+ base = dirOf(base);
97
+ const target = posix.join(base, rest);
98
+ return existing(rest ? [`${target}.py`, `${target}/__init__.py`] : [`${target}/__init__.py`]);
99
+ }
100
+ if (family === 'go') {
101
+ for (const { dir: root, module } of input.goModules) {
102
+ if (source !== module && !source.startsWith(`${module}/`))
103
+ continue;
104
+ const packageDir = posix.join(root, source.slice(module.length + 1));
105
+ return (filesByDir.get(packageDir === '.' ? '' : packageDir) ?? []).filter((id) => familyOf(id) === 'go');
106
+ }
107
+ }
108
+ return [];
109
+ }
110
+ const kindOk = (s, refKind) => refKind === 'call' || TYPE_KINDS.has(s.kind);
111
+ const topIn = (fileIds, name, refKind = 'call') => {
112
+ for (const id of fileIds) {
113
+ const hit = topLevel.get(`${id}:${name}`)?.find((s) => kindOk(s, refKind));
114
+ if (hit)
115
+ return hit;
116
+ }
117
+ return undefined;
118
+ };
119
+ /** A member of a class or struct. Go methods can live in another file of the package. */
120
+ const member = (owner, name) => children.get(owner.id)?.find((s) => s.name === name) ??
121
+ byQualified.get(`${files.get(owner.fileId)?.dir}:${owner.qualifiedName}.${name}`);
122
+ const hit = (s, confidence) => s ? { target: s.id, confidence } : null;
123
+ function resolve(ref) {
124
+ const { fileId, name, receiver, kind } = ref;
125
+ const caller = ref.symbolId === null ? undefined : symbols.get(ref.symbolId);
126
+ const family = familyOf(fileId);
127
+ if (receiver === null) {
128
+ // Enclosing functions, innermost first, then the top level of the file.
129
+ for (let s = caller; s; s = s.parentId === null ? undefined : symbols.get(s.parentId)) {
130
+ if (s.kind === 'class')
131
+ continue;
132
+ const nested = children.get(s.id)?.find((c) => c.name === name && kindOk(c, kind));
133
+ if (nested)
134
+ return hit(nested, 'exact');
135
+ }
136
+ const sameFile = topIn([fileId], name, kind);
137
+ if (sameFile)
138
+ return hit(sameFile, 'exact');
139
+ if (family === 'go') {
140
+ // A Go package is a directory: its files share one scope.
141
+ const samePackage = topIn(filesByDir.get(files.get(fileId)?.dir ?? '') ?? [], name, kind);
142
+ if (samePackage)
143
+ return hit(samePackage, 'exact');
144
+ }
145
+ const imported = locals.get(`${fileId}:${name}`);
146
+ if (imported) {
147
+ if (imported.name === '*')
148
+ return null;
149
+ const original = imported.name === 'default' ? name : imported.name;
150
+ return hit(topIn(moduleFiles(fileId, imported.source), original, kind), 'import');
151
+ }
152
+ }
153
+ else if (SELF.has(receiver)) {
154
+ let owner = caller;
155
+ while (owner && owner.kind !== 'class') {
156
+ owner = owner.parentId === null ? undefined : symbols.get(owner.parentId);
157
+ }
158
+ const own = owner && member(owner, name);
159
+ if (own)
160
+ return hit(own, 'exact');
161
+ }
162
+ else if (receiver !== '') {
163
+ const imported = locals.get(`${fileId}:${receiver}`) ?? locals.get(`${fileId}:${receiver.split('.')[0]}`);
164
+ if (imported) {
165
+ const targets = moduleFiles(fileId, imported.source);
166
+ if (imported.name === '*')
167
+ return hit(topIn(targets, name), 'import');
168
+ // The receiver is an imported class, or (Python) an imported submodule.
169
+ const owner = topIn(targets, imported.name === 'default' ? imported.local : imported.name);
170
+ if (owner)
171
+ return hit(member(owner, name), 'import');
172
+ const separator = imported.source.endsWith('.') ? '' : '.';
173
+ const submodule = family === 'python'
174
+ ? moduleFiles(fileId, `${imported.source}${separator}${imported.name}`)
175
+ : [];
176
+ return hit(topIn(submodule, name), 'import');
177
+ }
178
+ const owner = topIn([fileId], receiver);
179
+ const own = owner && TYPE_KINDS.has(owner.kind) ? member(owner, name) : undefined;
180
+ if (own)
181
+ return hit(own, 'exact');
182
+ // A capitalized receiver names a class or namespace. One that is neither in this file
183
+ // nor imported is a global such as `Object` or `Math`, so the call is not ours.
184
+ if (/^\p{Lu}[\p{L}\p{N}_$]*$/u.test(receiver))
185
+ return null;
186
+ }
187
+ if (receiver !== null) {
188
+ // The receiver is a value of unknown type: one symbol of that name in this file.
189
+ const sameFile = (inFile.get(`${fileId}:${name}`) ?? []).filter((s) => kindOk(s, kind));
190
+ if (sameFile.length === 1)
191
+ return hit(sameFile[0], 'exact');
192
+ }
193
+ const candidates = (byName.get(name) ?? []).filter((s) => {
194
+ const parent = s.parentId === null ? undefined : symbols.get(s.parentId);
195
+ return (familyOf(s.fileId) === family &&
196
+ kindOk(s, kind) &&
197
+ s.kind !== 'constant' &&
198
+ // A function nested in another function cannot be reached from elsewhere.
199
+ (!parent || parent.kind === 'class'));
200
+ });
201
+ return candidates.length === 1 ? hit(candidates[0], 'name-match') : null;
202
+ }
203
+ const refs = [];
204
+ for (const ref of input.refs) {
205
+ const resolved = resolve(ref);
206
+ if (resolved)
207
+ refs.push({ id: ref.id, ...resolved });
208
+ }
209
+ const imports = [];
210
+ for (const i of input.imports) {
211
+ if (i.name === '' || i.name === '*')
212
+ continue;
213
+ const target = topIn(moduleFiles(i.fileId, i.source), i.name === 'default' ? i.local : i.name);
214
+ if (target)
215
+ imports.push({ id: i.id, target: target.id });
216
+ }
217
+ return { refs, imports };
218
+ }
219
+ /** Resolves every reference in the store again and rebuilds the edges. */
220
+ export function updateGraph(store) {
221
+ const { refs, imports } = resolveReferences(store.graphInput());
222
+ store.saveResolution(refs, imports);
223
+ return { edges: store.edgeCount() };
224
+ }
@@ -0,0 +1,183 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { chunkFile } from '../chunker/index.js';
4
+ import { embedMissing, modelChanged } from '../embedder/index.js';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { updateGraph } from '../graph/index.js';
7
+ import { log } from '../log.js';
8
+ import { refreshStaleness, syncMemories } from '../memory/index.js';
9
+ import { buildOverview } from './overview.js';
10
+ import { languageOf, parseSource } from '../parser/index.js';
11
+ import { hasExcludedContent, listCandidates, resolveInRoot, scan } from '../scanner/index.js';
12
+ import { countTokens } from '../tokens.js';
13
+ /**
14
+ * Bump when the parser or chunker changes what gets stored for an unchanged file, so
15
+ * existing indexes are rebuilt instead of silently keeping the old shape.
16
+ */
17
+ const INDEX_FORMAT = '3';
18
+ const BATCH_FILES = 100;
19
+ async function readSource(root, path) {
20
+ // Normalize line endings so line numbers and offsets agree on every platform.
21
+ return (await readFile(resolveInRoot(root, path), 'utf8')).replace(/\r\n?/g, '\n');
22
+ }
23
+ const hashOf = (source) => createHash('sha256').update(source).digest('hex');
24
+ async function processSource(path, source, opts) {
25
+ const language = languageOf(path);
26
+ const parsed = language ? await parseSource(language, source) : null;
27
+ const chunks = chunkFile(path, language, source, parsed, opts);
28
+ const lineCount = source.split('\n').length - (source.endsWith('\n') ? 1 : 0);
29
+ return { path, language, contentHash: hashOf(source), lineCount, parsed, chunks };
30
+ }
31
+ /** Reads, parses, and chunks one file. `path` is relative to `root`. */
32
+ export async function processFile(root, path, opts) {
33
+ return processSource(path, await readSource(root, path), opts);
34
+ }
35
+ /** The current git commit of `root`, or an empty string outside a git repo. */
36
+ function headCommit(root) {
37
+ try {
38
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
39
+ cwd: root,
40
+ encoding: 'utf8',
41
+ stdio: ['ignore', 'pipe', 'ignore'],
42
+ }).trim();
43
+ }
44
+ catch {
45
+ return '';
46
+ }
47
+ }
48
+ /** How the files under `root` differ from the index, without changing anything. */
49
+ export async function pendingChanges(root, store, config) {
50
+ const known = store.fileHashes();
51
+ const result = { changed: 0, added: 0, deleted: 0 };
52
+ const present = new Set();
53
+ for (const { path } of scan(root, config)) {
54
+ present.add(path);
55
+ const stored = known.get(path);
56
+ if (stored === undefined)
57
+ result.added++;
58
+ else if (stored !== hashOf(await readSource(root, path)))
59
+ result.changed++;
60
+ }
61
+ for (const path of known.keys())
62
+ if (!present.has(path))
63
+ result.deleted++;
64
+ return result;
65
+ }
66
+ /**
67
+ * A file modified less than this long before the last look (or any time after it) is always
68
+ * hashed, never trusted: an edit in the same second as a scan can leave the size and, on a
69
+ * file system with coarse timestamps, the modification time looking untouched.
70
+ */
71
+ const MTIME_MARGIN_MS = 2000;
72
+ /**
73
+ * Brings the store in line with the files under `root`: changed files are re-read, files
74
+ * that disappeared are removed, and the graph, overview, memories, and vectors follow.
75
+ *
76
+ * - default: every file is read and hashed, and only files whose hash changed are indexed.
77
+ * - `quick`: a file whose size is unchanged and whose modification time is older than the
78
+ * last look is taken as unchanged without reading it. Used before tool calls and by
79
+ * `watch`, where the check runs often and must cost a few milliseconds.
80
+ * - `full`: every file is indexed again.
81
+ */
82
+ export async function indexRepo(root, store, config, options = {}) {
83
+ const started = performance.now();
84
+ const formatChanged = store.getMeta('index_format') !== INDEX_FORMAT;
85
+ const full = options.full === true || formatChanged;
86
+ const quick = options.quick === true && !full;
87
+ const known = store.fileStates();
88
+ const candidates = listCandidates(root, config);
89
+ const stats = {
90
+ scanned: 0,
91
+ indexed: 0,
92
+ unchanged: 0,
93
+ deleted: 0,
94
+ chunks: 0,
95
+ embedded: 0,
96
+ embeddingsCached: 0,
97
+ seconds: 0,
98
+ };
99
+ let batch = [];
100
+ const flush = () => {
101
+ store.transaction(() => {
102
+ for (const { file, sizeBytes, readAt } of batch) {
103
+ store.replaceFile({ ...file, sizeBytes, readAt }, file.parsed, file.chunks.map((chunk) => ({ ...chunk, tokenCount: countTokens(chunk.content) })));
104
+ }
105
+ });
106
+ batch = [];
107
+ };
108
+ const present = new Set();
109
+ for (const { path, sizeBytes, mtimeMs } of candidates) {
110
+ const state = known.get(path);
111
+ if (quick &&
112
+ state &&
113
+ state.sizeBytes === sizeBytes &&
114
+ mtimeMs < state.indexedAt - MTIME_MARGIN_MS) {
115
+ present.add(path);
116
+ stats.scanned++;
117
+ stats.unchanged++;
118
+ continue;
119
+ }
120
+ // Only now is the content looked at: binary, minified, and generated files drop out.
121
+ if (hasExcludedContent(resolveInRoot(root, path)))
122
+ continue;
123
+ present.add(path);
124
+ stats.scanned++;
125
+ const readAt = Date.now();
126
+ const source = await readSource(root, path);
127
+ if (!full && state?.hash === hashOf(source)) {
128
+ stats.unchanged++;
129
+ // Remember the look, so a recently touched file is not hashed on every quick check.
130
+ if (quick)
131
+ store.touchFile(path, readAt);
132
+ continue;
133
+ }
134
+ const file = await processSource(path, source);
135
+ batch.push({ file, sizeBytes, readAt });
136
+ stats.indexed++;
137
+ stats.chunks += file.chunks.length;
138
+ if (batch.length >= BATCH_FILES)
139
+ flush();
140
+ }
141
+ flush();
142
+ store.transaction(() => {
143
+ for (const path of known.keys()) {
144
+ if (!present.has(path) && store.deleteFile(path))
145
+ stats.deleted++;
146
+ }
147
+ if (formatChanged)
148
+ store.setMeta('index_format', INDEX_FORMAT);
149
+ });
150
+ const changed = stats.indexed > 0 || stats.deleted > 0;
151
+ log.debug(`files: ${stats.indexed} indexed, ${stats.deleted} removed in ${Math.round(performance.now() - started)} ms`);
152
+ // Memories follow the code: pick up a changed memory.json, then re-check every link.
153
+ syncMemories(root, store);
154
+ if (quick && !changed) {
155
+ stats.seconds = (performance.now() - started) / 1000;
156
+ return stats;
157
+ }
158
+ // Name resolution depends on every file, so the graph is rebuilt whenever anything changed.
159
+ if (changed || store.getMeta('overview') === undefined) {
160
+ const graphStarted = performance.now();
161
+ updateGraph(store);
162
+ store.setMeta('overview', buildOverview(store));
163
+ log.debug(`graph and overview rebuilt in ${Math.round(performance.now() - graphStarted)} ms`);
164
+ }
165
+ refreshStaleness(store);
166
+ store.setMeta('last_indexed_at', new Date().toISOString());
167
+ store.setMeta('last_indexed_commit', headCommit(root));
168
+ const provider = options.provider;
169
+ if (provider) {
170
+ const embedStarted = performance.now();
171
+ // A full rebuild is the way to switch models; anything else refuses to mix them.
172
+ if (options.full && modelChanged(store, provider))
173
+ store.clearVectors();
174
+ const embed = await embedMissing(store, provider, config.embedding.batchSize, options.onEmbedProgress);
175
+ stats.embedded = embed.embedded;
176
+ stats.embeddingsCached = embed.cached;
177
+ // A full run embeds every chunk, so it knows exactly which cached vectors are in use.
178
+ store.pruneEmbeddingCache(provider.id, options.full ? embed.hashes : undefined);
179
+ log.debug(`embedded ${embed.embedded} chunks in ${Math.round(performance.now() - embedStarted)} ms`);
180
+ }
181
+ stats.seconds = (performance.now() - started) / 1000;
182
+ return stats;
183
+ }
@@ -0,0 +1,75 @@
1
+ import { countTokens } from '../tokens.js';
2
+ const MAX_TOKENS = 1500;
3
+ function render(root, depth, perDir, totals) {
4
+ const out = [totals];
5
+ const walk = (dir, name, level) => {
6
+ if (level > 0) {
7
+ const top = dir.symbols
8
+ .sort((a, b) => b.references - a.references || a.name.localeCompare(b.name))
9
+ .slice(0, perDir)
10
+ .map((s) => s.name);
11
+ const names = top.length > 0 ? `: ${top.join(', ')}` : '';
12
+ out.push(`${' '.repeat(level - 1)}${name}/ (${dir.files} files)${names}`);
13
+ }
14
+ if (level >= depth)
15
+ return;
16
+ for (const [child, sub] of [...dir.children].sort((a, b) => a[0].localeCompare(b[0]))) {
17
+ walk(sub, child, level + 1);
18
+ }
19
+ };
20
+ walk(root, '', 0);
21
+ return out.join('\n');
22
+ }
23
+ /**
24
+ * A compact map of the repo for agents: the directory tree to depth 3, each directory with
25
+ * its file count (including subdirectories) and its most-referenced symbols. At most
26
+ * 1,500 tokens: detail is reduced until it fits.
27
+ */
28
+ export function buildOverview(store) {
29
+ const root = { files: 0, symbols: [], children: new Map() };
30
+ const dirFor = (path, count) => {
31
+ let dir = root;
32
+ if (count)
33
+ dir.files++;
34
+ for (const part of path.split('/').slice(0, -1)) {
35
+ let next = dir.children.get(part);
36
+ if (!next) {
37
+ next = { files: 0, symbols: [], children: new Map() };
38
+ dir.children.set(part, next);
39
+ }
40
+ dir = next;
41
+ if (count)
42
+ dir.files++;
43
+ }
44
+ return dir;
45
+ };
46
+ const { files, symbols } = store.overviewInput();
47
+ for (const path of files)
48
+ dirFor(path, true);
49
+ for (const s of symbols)
50
+ dirFor(s.path, false).symbols.push(s);
51
+ const counts = store.counts();
52
+ const totals = `${counts.files} files, ${counts.symbols} symbols. Directories show their file count and most-referenced symbols.`;
53
+ const top = root.symbols
54
+ .sort((a, b) => b.references - a.references)
55
+ .slice(0, 5)
56
+ .map((s) => s.name);
57
+ const header = top.length > 0 ? `${totals}\n(top level): ${top.join(', ')}` : totals;
58
+ for (const [depth, perDir] of [
59
+ [3, 5],
60
+ [3, 3],
61
+ [2, 3],
62
+ [2, 1],
63
+ [1, 1],
64
+ [1, 0],
65
+ ]) {
66
+ const text = render(root, depth, perDir, header);
67
+ if (countTokens(text) <= MAX_TOKENS)
68
+ return text;
69
+ }
70
+ // A repo with a very wide top level: keep as many lines as fit.
71
+ const lines = render(root, 1, 0, header).split('\n');
72
+ while (lines.length > 1 && countTokens(lines.join('\n')) > MAX_TOKENS)
73
+ lines.pop();
74
+ return lines.join('\n');
75
+ }
@@ -0,0 +1,55 @@
1
+ import { relative, sep } from 'node:path';
2
+ import { watch } from 'chokidar';
3
+ import { log } from '../log.js';
4
+ import { isExcludedPath } from '../scanner/index.js';
5
+ import { indexRepo } from './index.js';
6
+ /**
7
+ * Keeps the index fresh while files change: after `watch.debounceMs` without further
8
+ * changes, a quick re-index runs. `onRun` is called after each run that changed something.
9
+ */
10
+ export function startWatch(root, store, config, provider, onRun) {
11
+ let timer;
12
+ let running = false;
13
+ let again = false;
14
+ const run = async () => {
15
+ if (running) {
16
+ again = true; // changes arrived mid-run: go once more when it finishes
17
+ return;
18
+ }
19
+ running = true;
20
+ try {
21
+ const stats = await indexRepo(root, store, config, { quick: true, provider });
22
+ if (stats.indexed > 0 || stats.deleted > 0)
23
+ onRun(stats);
24
+ }
25
+ catch (error) {
26
+ log.error(`re-index failed: ${String(error)}`);
27
+ }
28
+ finally {
29
+ running = false;
30
+ if (again) {
31
+ again = false;
32
+ void run();
33
+ }
34
+ }
35
+ };
36
+ const watcher = watch(root, {
37
+ ignoreInitial: true,
38
+ // Skip vendored and generated directories; the dummy name makes every segment count as one.
39
+ ignored: (path) => {
40
+ const rel = relative(root, path).split(sep).join('/');
41
+ return rel !== '' && isExcludedPath(`${rel}/_`);
42
+ },
43
+ });
44
+ watcher.on('all', () => {
45
+ clearTimeout(timer);
46
+ timer = setTimeout(() => void run(), config.watch.debounceMs);
47
+ });
48
+ watcher.on('error', (error) => log.error(`watcher error: ${String(error)}`));
49
+ return {
50
+ close: async () => {
51
+ clearTimeout(timer);
52
+ await watcher.close();
53
+ },
54
+ };
55
+ }
package/dist/log.js ADDED
@@ -0,0 +1,16 @@
1
+ // All diagnostics go to stderr: stdout belongs to the MCP protocol when `serve` is running.
2
+ const LEVELS = ['error', 'warn', 'info', 'debug'];
3
+ function enabled(level) {
4
+ const wanted = LEVELS.indexOf((process.env['REMIMEM_LOG_LEVEL'] ?? 'warn'));
5
+ return LEVELS.indexOf(level) <= (wanted === -1 ? 1 : wanted);
6
+ }
7
+ function write(level, message) {
8
+ if (enabled(level))
9
+ process.stderr.write(`remimem ${level}: ${message}\n`);
10
+ }
11
+ export const log = {
12
+ error: (message) => write('error', message),
13
+ warn: (message) => write('warn', message),
14
+ info: (message) => write('info', message),
15
+ debug: (message) => write('debug', message),
16
+ };
@@ -0,0 +1,68 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join } from 'node:path';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { CONFIG_DIR, loadConfig } from '../config/index.js';
7
+ import { createProvider } from '../embedder/index.js';
8
+ import { RemimemError } from '../errors.js';
9
+ import { log } from '../log.js';
10
+ import { Store } from '../store/index.js';
11
+ import { runTool, TOOLS } from './tools.js';
12
+ const pkg = createRequire(import.meta.url)('../../package.json');
13
+ export const OVERVIEW_URI = 'remimem://overview';
14
+ const INSTRUCTIONS = 'remimem serves code from a local index of this repository. Start a task with get_context; ' +
15
+ 'use search_code for a specific lookup, get_symbol to read a body or see callers and callees, ' +
16
+ 'and find_references before changing a symbol. Results cite path:start-end. Save lasting ' +
17
+ 'decisions and conventions with remember; get_context shows them again in later sessions.';
18
+ /** An MCP server with every remimem tool and the overview resource. */
19
+ export function createServer(ctx) {
20
+ const server = new McpServer({ name: 'remimem', version: pkg.version }, { instructions: INSTRUCTIONS });
21
+ for (const tool of TOOLS) {
22
+ server.registerTool(tool.name, {
23
+ description: tool.description,
24
+ inputSchema: tool.shape,
25
+ annotations: { readOnlyHint: tool.readOnly, openWorldHint: false },
26
+ }, async (args) => {
27
+ const started = performance.now();
28
+ try {
29
+ const text = await runTool(ctx, tool, (args ?? {}));
30
+ log.debug(`${tool.name} answered in ${Math.round(performance.now() - started)} ms`);
31
+ return { content: [{ type: 'text', text }] };
32
+ }
33
+ catch (error) {
34
+ // A tool failure is an answer for the agent, never a crash of the server.
35
+ if (!(error instanceof RemimemError))
36
+ log.error(`${tool.name} failed: ${String(error)}`);
37
+ const message = error instanceof Error ? error.message : String(error);
38
+ return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
39
+ }
40
+ });
41
+ }
42
+ server.registerResource('overview', OVERVIEW_URI, {
43
+ title: 'Repository overview',
44
+ description: 'Directory tree with the most-referenced symbols per directory.',
45
+ mimeType: 'text/plain',
46
+ }, (uri) => ({
47
+ contents: [
48
+ {
49
+ uri: uri.href,
50
+ mimeType: 'text/plain',
51
+ text: ctx.store.getMeta('overview') ?? 'No overview yet. Run `remimem index` first.',
52
+ },
53
+ ],
54
+ }));
55
+ return server;
56
+ }
57
+ /** `remimem serve`: runs the server on stdio until the client disconnects. */
58
+ export async function serve(root) {
59
+ const config = loadConfig(root);
60
+ mkdirSync(join(root, CONFIG_DIR), { recursive: true });
61
+ const store = new Store(join(root, CONFIG_DIR, 'index.db'));
62
+ const ctx = { root, config, store, provider: createProvider(config.embedding) };
63
+ const server = createServer(ctx);
64
+ const transport = new StdioServerTransport();
65
+ transport.onclose = () => store.close();
66
+ await server.connect(transport);
67
+ log.info(`serving ${root} over stdio`);
68
+ }