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,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,82 @@
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 { startDashboard } from '../dashboard/server.js';
8
+ import { createProvider } from '../embedder/index.js';
9
+ import { RemimemError } from '../errors.js';
10
+ import { log } from '../log.js';
11
+ import { Store } from '../store/index.js';
12
+ import { runTool, TOOLS } from './tools.js';
13
+ const pkg = createRequire(import.meta.url)('../../package.json');
14
+ export const OVERVIEW_URI = 'remimem://overview';
15
+ const INSTRUCTIONS = 'remimem serves code from a local index of this repository. Start a task with get_context; ' +
16
+ 'use search_code for a specific lookup, get_symbol to read a body or see callers and callees, ' +
17
+ 'and find_references before changing a symbol. Results cite path:start-end. Save lasting ' +
18
+ 'decisions and conventions with remember; get_context shows them again in later sessions.';
19
+ /** An MCP server with every remimem tool and the overview resource. */
20
+ export function createServer(ctx) {
21
+ const server = new McpServer({ name: 'remimem', version: pkg.version }, { instructions: INSTRUCTIONS });
22
+ for (const tool of TOOLS) {
23
+ server.registerTool(tool.name, {
24
+ description: tool.description,
25
+ inputSchema: tool.shape,
26
+ annotations: { readOnlyHint: tool.readOnly, openWorldHint: false },
27
+ }, async (args) => {
28
+ const started = performance.now();
29
+ try {
30
+ const text = await runTool(ctx, tool, (args ?? {}));
31
+ log.debug(`${tool.name} answered in ${Math.round(performance.now() - started)} ms`);
32
+ return { content: [{ type: 'text', text }] };
33
+ }
34
+ catch (error) {
35
+ // A tool failure is an answer for the agent, never a crash of the server.
36
+ if (!(error instanceof RemimemError))
37
+ log.error(`${tool.name} failed: ${String(error)}`);
38
+ const message = error instanceof Error ? error.message : String(error);
39
+ return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
40
+ }
41
+ });
42
+ }
43
+ server.registerResource('overview', OVERVIEW_URI, {
44
+ title: 'Repository overview',
45
+ description: 'Directory tree with the most-referenced symbols per directory.',
46
+ mimeType: 'text/plain',
47
+ }, (uri) => ({
48
+ contents: [
49
+ {
50
+ uri: uri.href,
51
+ mimeType: 'text/plain',
52
+ text: ctx.store.getMeta('overview') ?? 'No overview yet. Run `remimem index` first.',
53
+ },
54
+ ],
55
+ }));
56
+ return server;
57
+ }
58
+ /** `remimem serve`: runs the server on stdio until the client disconnects. */
59
+ export async function serve(root) {
60
+ const config = loadConfig(root);
61
+ mkdirSync(join(root, CONFIG_DIR), { recursive: true });
62
+ const store = new Store(join(root, CONFIG_DIR, 'index.db'));
63
+ const ctx = { root, config, store, provider: createProvider(config.embedding) };
64
+ // The dashboard is a convenience: if its port cannot be opened, the tools still work.
65
+ const dashboard = config.dashboard.enabled
66
+ ? await startDashboard(ctx, config.dashboard.port).catch((error) => {
67
+ log.warn(`dashboard not started: ${String(error)}`);
68
+ return undefined;
69
+ })
70
+ : undefined;
71
+ // The dashboard lives as long as the agent's session: it never keeps the process alive.
72
+ dashboard?.unref();
73
+ ctx.dashboardUrl = dashboard?.url;
74
+ const server = createServer(ctx);
75
+ const transport = new StdioServerTransport();
76
+ transport.onclose = () => {
77
+ void dashboard?.close();
78
+ store.close();
79
+ };
80
+ await server.connect(transport);
81
+ log.info(`serving ${root} over stdio`);
82
+ }