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,39 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { join } from 'node:path';
5
+ import { CONFIG_DIR } from '../config/index.js';
6
+ import { onModelDownload } from '../embedder/index.js';
7
+ import { RemimemError } from '../errors.js';
8
+ import { buildProgram } from './program.js';
9
+ import { downloadDisplay, paint, welcome } from './ui.js';
10
+ const pkg = createRequire(import.meta.url)('../../package.json');
11
+ // Exit quietly when the reader goes away, as in `remimem search x | head`.
12
+ process.stdout.on('error', (error) => {
13
+ if (error.code !== 'EPIPE')
14
+ throw error;
15
+ process.exit(0);
16
+ });
17
+ const command = process.argv[2];
18
+ // A bare `remimem` greets the user instead of printing an error and the full help.
19
+ if (command === undefined) {
20
+ console.log(welcome(pkg.version, existsSync(join(process.cwd(), CONFIG_DIR, 'index.db'))));
21
+ process.exit(0);
22
+ }
23
+ // The MCP server talks over stdio, so it never draws anything.
24
+ if (command !== 'serve') {
25
+ let display;
26
+ onModelDownload((model, loaded, total) => {
27
+ display ??= downloadDisplay(model);
28
+ display.update(loaded, total);
29
+ });
30
+ }
31
+ try {
32
+ await buildProgram().parseAsync();
33
+ }
34
+ catch (error) {
35
+ if (!(error instanceof RemimemError))
36
+ throw error;
37
+ console.error(`${paint('red', 'error:', process.stderr)} ${error.message}`);
38
+ process.exitCode = 1;
39
+ }
@@ -0,0 +1,328 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createRequire } from 'node:module';
3
+ import { existsSync, statSync } from 'node:fs';
4
+ import { join, resolve } from 'node:path';
5
+ import { Command } from 'commander';
6
+ import { CONFIG_DIR, loadConfig } from '../config/index.js';
7
+ import { findDashboard, startDashboard } from '../dashboard/server.js';
8
+ import { createProvider } from '../embedder/index.js';
9
+ import { processFile } from '../indexer/index.js';
10
+ import { Store } from '../store/index.js';
11
+ import { RemimemError } from '../errors.js';
12
+ import { MEMORY_KINDS, MemoryError } from '../memory/index.js';
13
+ import { serve } from '../mcp/server.js';
14
+ import { runContext, runDoctor, runIndex, runInit, runMemory, runRefs, runSearch, runStats, runWatch, runSymbol, } from './commands.js';
15
+ import { resolveInRoot, scan } from '../scanner/index.js';
16
+ import { banner, clearLine, embedProgress, paint } from './ui.js';
17
+ const pkg = createRequire(import.meta.url)('../../package.json');
18
+ const HELP_ORDER = [
19
+ 'init',
20
+ 'search',
21
+ 'context',
22
+ 'memory',
23
+ 'index',
24
+ 'watch',
25
+ 'dashboard',
26
+ 'stats',
27
+ 'doctor',
28
+ 'serve',
29
+ 'bench',
30
+ ];
31
+ /** True when a dashboard answers at `url`; a stale discovery file can outlive its server. */
32
+ async function reachable(url) {
33
+ const { origin, searchParams } = new URL(url);
34
+ try {
35
+ const res = await fetch(`${origin}/api/overview`, {
36
+ headers: { 'x-remimem-token': searchParams.get('token') ?? '' },
37
+ signal: AbortSignal.timeout(1500),
38
+ });
39
+ return res.ok;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ /** Opens a URL in the default browser; failures are ignored, the URL is printed anyway. */
46
+ function openBrowser(url) {
47
+ const [command, args] = process.platform === 'darwin'
48
+ ? ['open', [url]]
49
+ : process.platform === 'win32'
50
+ ? ['cmd', ['/c', 'start', '""', url]]
51
+ : ['xdg-open', [url]];
52
+ try {
53
+ spawn(command, args, { stdio: 'ignore', detached: true })
54
+ .on('error', () => undefined)
55
+ .unref();
56
+ }
57
+ catch {
58
+ // No browser available (a server or container): the printed URL is enough.
59
+ }
60
+ }
61
+ export function buildProgram() {
62
+ const program = new Command('remimem')
63
+ .description('Gives coding agents only the code they need, within a token budget, and remembers your project.')
64
+ .version(pkg.version, '-v, --version', 'print the version')
65
+ .helpOption('-h, --help', 'show help for a command')
66
+ .helpCommand(false)
67
+ .showSuggestionAfterError(true)
68
+ // The logo above help, only when a person is reading it in a terminal.
69
+ .addHelpText('beforeAll', () => (process.stdout.isTTY ? banner(pkg.version) : ''))
70
+ .addHelpText('after', () => `
71
+ ${paint('bold', 'Examples:')}
72
+ ${paint('cyan', 'remimem init')} set up this project, print client configs
73
+ ${paint('cyan', 'remimem search "how are passwords hashed"')} find code by meaning or by name
74
+ ${paint('cyan', 'remimem context "add rate limiting to login"')} everything an agent needs for a task
75
+ ${paint('cyan', 'remimem memory add "Money is stored in cents" --kind convention')}
76
+
77
+ Help for one command: ${paint('cyan', 'remimem <command> --help')}
78
+ Docs: https://github.com/JaswanthRemiel/remimem`);
79
+ program
80
+ .command('doctor')
81
+ .helpGroup('Check:')
82
+ .description('Check that everything is installed and working')
83
+ .action(async () => {
84
+ const { lines, ok } = await runDoctor(process.cwd());
85
+ console.log(lines.join('\n'));
86
+ if (!ok)
87
+ process.exitCode = 1;
88
+ });
89
+ program
90
+ .command('init')
91
+ .helpGroup('Get started:')
92
+ .description('Set up this project: index the code and print the config for your agent')
93
+ .action(async () => {
94
+ const root = process.cwd();
95
+ if (process.stdout.isTTY) {
96
+ console.log(banner(pkg.version));
97
+ console.log(`Setting up remimem in ${paint('bold', root)}\n`);
98
+ }
99
+ const report = await runInit(root, { onEmbedProgress: embedProgress });
100
+ clearLine();
101
+ // The status lines come first, before the blank line that starts the client configs.
102
+ const split = report.indexOf('\n\n');
103
+ const status = split === -1 ? report : report.slice(0, split);
104
+ const rest = split === -1 ? '' : report.slice(split);
105
+ const check = paint('green', '✓');
106
+ console.log(process.stdout.isTTY
107
+ ? status
108
+ .split('\n')
109
+ .map((line) => `${check} ${line}`)
110
+ .join('\n') + rest
111
+ : report);
112
+ });
113
+ program
114
+ .command('serve')
115
+ .helpGroup('For MCP clients:')
116
+ .description('Start the MCP server (your agent runs this, not you)')
117
+ .option('--root <dir>', 'project directory, default the current directory')
118
+ .action(async (options) => {
119
+ await serve(resolve(options.root ?? process.cwd()));
120
+ });
121
+ program
122
+ .command('context <task>')
123
+ .helpGroup('Find code:')
124
+ .description('Everything an agent needs for a task, ready to paste into any chat')
125
+ .option('--budget <tokens>', 'token budget for the output')
126
+ .action(async (task, options) => {
127
+ const budget = Number(options.budget);
128
+ console.log(await runContext(process.cwd(), task, Number.isFinite(budget) ? { budget } : {}));
129
+ });
130
+ const memory = program
131
+ .command('memory')
132
+ .helpGroup('Project memory:')
133
+ .description('Save, list, and delete decisions and conventions by hand');
134
+ const collect = (value, all) => [...all, value];
135
+ memory
136
+ .command('list')
137
+ .description('List memories, or search them with a query')
138
+ .argument('[query]', 'what to look for', '')
139
+ .option('--kind <kind>', 'decision, convention, gotcha, or todo')
140
+ .action(async (query, options) => {
141
+ console.log(await runMemory(process.cwd(), 'list', { query, kind: options.kind }));
142
+ });
143
+ memory
144
+ .command('add <text>')
145
+ .description('Save a memory')
146
+ .option('--kind <kind>', 'decision, convention, gotcha, or todo', 'decision')
147
+ .option('--path <path>', 'file this is about (repeatable)', collect, [])
148
+ .option('--symbol <name>', 'symbol this is about (repeatable)', collect, [])
149
+ .option('--tag <tag>', 'tag (repeatable)', collect, [])
150
+ .action(async (text, options) => {
151
+ if (!MEMORY_KINDS.includes(options.kind)) {
152
+ throw new MemoryError(`Unknown kind "${options.kind}". Use one of: ${MEMORY_KINDS.join(', ')}.`);
153
+ }
154
+ console.log(await runMemory(process.cwd(), 'add', {
155
+ text,
156
+ kind: options.kind,
157
+ paths: options.path,
158
+ symbols: options.symbol,
159
+ tags: options.tag,
160
+ }));
161
+ });
162
+ memory
163
+ .command('rm <id>')
164
+ .description('Delete a memory')
165
+ .action(async (id) => {
166
+ console.log(await runMemory(process.cwd(), 'rm', { id }));
167
+ });
168
+ program
169
+ .command('index')
170
+ .helpGroup('Keep the index fresh:')
171
+ .description('Bring the index up to date (only changed files are re-read)')
172
+ .option('--full', 'reindex every file and rebuild vectors')
173
+ .action(async (options) => {
174
+ const summary = await runIndex(process.cwd(), { ...options, onEmbedProgress: embedProgress });
175
+ clearLine();
176
+ console.log(summary);
177
+ });
178
+ program
179
+ .command('watch')
180
+ .helpGroup('Keep the index fresh:')
181
+ .description('Re-index automatically while you edit')
182
+ .action(async () => {
183
+ const stop = await runWatch(process.cwd(), (line) => console.log(line));
184
+ process.once('SIGINT', () => void stop().then(() => process.exit(0)));
185
+ });
186
+ program
187
+ .command('dashboard')
188
+ .helpGroup('Check:')
189
+ .description('Open the local dashboard: code graph, search, memories, savings, and settings')
190
+ .option('--port <n>', 'port on 127.0.0.1 when starting a new dashboard (default: any free port)')
191
+ .option('--no-open', 'print the address without opening a browser')
192
+ .action(async (options) => {
193
+ const root = process.cwd();
194
+ // An agent's `remimem serve` already runs one for this project: use that.
195
+ const running = findDashboard(root);
196
+ if (running && (await reachable(running.url))) {
197
+ console.log(`Dashboard (served by a running remimem server): ${running.url}`);
198
+ if (options.open)
199
+ openBrowser(running.url);
200
+ return;
201
+ }
202
+ if (!existsSync(join(root, CONFIG_DIR, 'index.db'))) {
203
+ throw new RemimemError('No index here yet. Run `remimem init` in the project first.');
204
+ }
205
+ const config = loadConfig(root);
206
+ const store = new Store(join(root, CONFIG_DIR, 'index.db'));
207
+ const ctx = { root, config, store, provider: createProvider(config.embedding) };
208
+ const port = options.port === undefined ? config.dashboard.port : Number(options.port);
209
+ const dashboard = await startDashboard(ctx, port);
210
+ console.log(`Dashboard: ${paint('cyan', dashboard.url)}\nPress Ctrl+C to stop.`);
211
+ if (options.open)
212
+ openBrowser(dashboard.url);
213
+ // Ctrl+C, or a kill: close cleanly so the discovery file goes away with the server.
214
+ const stop = () => {
215
+ void dashboard.close().then(() => {
216
+ store.close();
217
+ process.exit(0);
218
+ });
219
+ };
220
+ process.once('SIGINT', stop);
221
+ process.once('SIGTERM', stop);
222
+ });
223
+ program
224
+ .command('stats')
225
+ .helpGroup('Check:')
226
+ .description('Show how many tokens remimem saved your agent')
227
+ .action(() => {
228
+ console.log(runStats(process.cwd()));
229
+ });
230
+ program
231
+ .command('bench')
232
+ .helpGroup('Contributors:')
233
+ .description('Run the benchmark (from a source checkout of remimem)')
234
+ .option('--mine', 'rebuild the task files from the pinned repositories instead of running')
235
+ .option('--repo <name>', 'run one repository only (repeatable)', (v, all) => [...all, v], [])
236
+ .option('--limit <n>', 'run only the first n tasks of each repository')
237
+ .option('--model <name>', 'embedding model to index with')
238
+ .option('--tune', 'also try the tuning configurations on the training split')
239
+ .option('--update-readme', 'paste the summary table into README.md')
240
+ .option('--compare <file>', 'check the run against an earlier results file, within a tolerance')
241
+ .option('--e2e', 'print the cost estimate for the end-to-end agent run (add --yes to run it)')
242
+ .option('--yes', 'with --e2e: actually run it, which costs money')
243
+ .option('--price-per-mtok <usd>', 'with --e2e: price per million input tokens for the estimate')
244
+ .action(async (options) => {
245
+ // Loaded on demand: the benchmark is not part of the published package.
246
+ const { runBenchCommand } = await import('../bench/command.js').catch(() => {
247
+ throw new RemimemError('The benchmark runs from a source checkout of remimem.');
248
+ });
249
+ const ok = await runBenchCommand(options, (line) => console.log(line));
250
+ if (!ok)
251
+ process.exitCode = 1;
252
+ });
253
+ program
254
+ .command('search <query>')
255
+ .helpGroup('Find code:')
256
+ .description('Find code by meaning or by name, packed into a token budget')
257
+ .option('-k, --limit <n>', 'number of results to consider')
258
+ .option('--budget <tokens>', 'token budget for the output')
259
+ .option('--debug', 'print every score before the results')
260
+ .action(async (query, options) => {
261
+ const number = (value) => value === undefined || !Number.isFinite(Number(value)) ? undefined : Number(value);
262
+ console.log(await runSearch(process.cwd(), query, {
263
+ k: number(options.limit),
264
+ budget: number(options.budget),
265
+ debug: options.debug,
266
+ }));
267
+ });
268
+ // Hidden developer commands, not part of the public interface.
269
+ const debug = program.command('debug', { hidden: true });
270
+ debug
271
+ .command('symbol <name>')
272
+ .description('Print a symbol with its callers, callees, and other neighbors')
273
+ .option('--depth <n>', 'hops of callers and callees to show, 0 to 2', '1')
274
+ .option('--signature', 'print the signature instead of the body')
275
+ .action((name, options) => {
276
+ console.log(runSymbol(process.cwd(), name, {
277
+ depth: Number(options.depth),
278
+ include: options.signature ? 'signature' : 'body',
279
+ }));
280
+ });
281
+ debug
282
+ .command('refs <name>')
283
+ .description('Print every reference to a symbol, grouped by file')
284
+ .action((name) => {
285
+ console.log(runRefs(process.cwd(), name));
286
+ });
287
+ debug
288
+ .command('chunks <path>')
289
+ .description('Print the chunks of a file, or scan and chunk a directory and print totals')
290
+ .option('--content', 'print chunk bodies')
291
+ .action(async (path, options) => {
292
+ const root = process.cwd();
293
+ const target = resolveInRoot(root, path);
294
+ if (statSync(target).isDirectory()) {
295
+ const started = performance.now();
296
+ const files = scan(target);
297
+ let lines = 0;
298
+ let symbols = 0;
299
+ let chunks = 0;
300
+ for (const file of files) {
301
+ const result = await processFile(target, file.path);
302
+ lines += result.lineCount;
303
+ symbols += result.parsed?.symbols.length ?? 0;
304
+ chunks += result.chunks.length;
305
+ }
306
+ const seconds = ((performance.now() - started) / 1000).toFixed(2);
307
+ console.log(`${files.length} files, ${lines} lines, ${symbols} symbols, ${chunks} chunks in ${seconds}s`);
308
+ return;
309
+ }
310
+ const { chunks } = await processFile(root, path);
311
+ for (const chunk of chunks) {
312
+ const label = chunk.symbol ? `${chunk.kind} ${chunk.symbol}` : chunk.kind;
313
+ console.log(`${chunk.path}:${chunk.startLine}-${chunk.endLine} ${label}`);
314
+ if (chunk.signature)
315
+ console.log(` ${chunk.signature.replaceAll('\n', '\n ')}`);
316
+ if (options.content)
317
+ console.log(`${chunk.content}\n`);
318
+ }
319
+ });
320
+ // Help lists groups and commands in the order a new user needs them.
321
+ const rank = (c) => {
322
+ const i = HELP_ORDER.indexOf(c.name());
323
+ return i === -1 ? HELP_ORDER.length : i;
324
+ };
325
+ // `commands` is typed read-only but is the list help reads, so sorting it in place is the hook.
326
+ program.commands.sort((a, b) => rank(a) - rank(b));
327
+ return program;
328
+ }
package/dist/cli/ui.js ADDED
@@ -0,0 +1,138 @@
1
+ // Presentation for people at a terminal: the banner, colors, and progress drawings.
2
+ // Everything here writes nothing on its own; callers decide where text goes, and the MCP
3
+ // server never uses this module, because its stdout belongs to the protocol.
4
+ import { styleText } from 'node:util';
5
+ /** Colors only when the stream is a terminal; honors NO_COLOR and FORCE_COLOR. */
6
+ export function paint(style, text, stream = process.stdout) {
7
+ return styleText(style, text, { validateStream: true, stream });
8
+ }
9
+ const LOGO = [
10
+ '██████╗ ███████╗███╗ ███╗██╗███╗ ███╗███████╗███╗ ███╗',
11
+ '██╔══██╗██╔════╝████╗ ████║██║████╗ ████║██╔════╝████╗ ████║',
12
+ '██████╔╝█████╗ ██╔████╔██║██║██╔████╔██║█████╗ ██╔████╔██║',
13
+ '██╔══██╗██╔══╝ ██║╚██╔╝██║██║██║╚██╔╝██║██╔══╝ ██║╚██╔╝██║',
14
+ '██║ ██║███████╗██║ ╚═╝ ██║██║██║ ╚═╝ ██║███████╗██║ ╚═╝ ██║',
15
+ '╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝',
16
+ ];
17
+ /** For terminals narrower than the full logo. */
18
+ const LOGO_SMALL = [
19
+ ' _ ',
20
+ ' _ _ ___ _ __ (_)_ __ ___ _ __ ',
21
+ " | '_/ -_) ' \\| | ' \\/ -_) ' \\ ",
22
+ ' |_| \\___|_|_|_|_|_|_|_\\___|_|_|_|',
23
+ ];
24
+ /** The remimem logo, the tagline, and the version, sized to the terminal. */
25
+ export function banner(version, stream = process.stdout) {
26
+ const logo = (stream.columns ?? 80) >= 64 ? LOGO : LOGO_SMALL;
27
+ return [
28
+ '',
29
+ ...logo.map((line) => paint('yellow', line, stream)),
30
+ '',
31
+ `${paint('bold', 'codebase memory for coding agents', stream)} ${paint('dim', `v${version}`, stream)}`,
32
+ '',
33
+ ].join('\n');
34
+ }
35
+ /** A horizontal bar such as `██████████░░░░░░░░░░`, for a fraction from 0 to 1. */
36
+ export function bar(fraction, width = 24) {
37
+ const filled = Math.round(Math.min(1, Math.max(0, fraction)) * width);
38
+ return '█'.repeat(filled) + '░'.repeat(width - filled);
39
+ }
40
+ // An amphora, Mnemosyne's vessel, that fills from the bottom as the model downloads.
41
+ // `#` marks the cells inside it that fill up.
42
+ const AMPHORA = [
43
+ ' .-"""-. ',
44
+ ' (_______) ',
45
+ ' )#####( ',
46
+ ' /#######\\ ',
47
+ ' |#########| ',
48
+ ' |#########| ',
49
+ ' \\#######/ ',
50
+ " `-----' ",
51
+ ];
52
+ const AMPHORA_CELLS = AMPHORA.join('').split('#').length - 1;
53
+ /** The amphora filled to `fraction`, bottom row first, left to right. */
54
+ export function amphora(fraction) {
55
+ let toFill = Math.round(Math.min(1, Math.max(0, fraction)) * AMPHORA_CELLS);
56
+ const rows = [...AMPHORA];
57
+ for (let r = rows.length - 1; r >= 0; r--) {
58
+ rows[r] = rows[r].replace(/#/g, () => (toFill-- > 0 ? '▓' : ' '));
59
+ }
60
+ return rows;
61
+ }
62
+ const mb = (bytes) => (bytes / 1_048_576).toFixed(1);
63
+ const MIN_DRAW_BYTES = 2 * 1_048_576;
64
+ /**
65
+ * Draws the download of the embedding model on stderr: the amphora on the left, the model
66
+ * name and byte counts beside it, redrawn in place. Does nothing when stderr is not a
67
+ * terminal. Returns `finish`, which leaves the full drawing on screen.
68
+ */
69
+ export function downloadDisplay(model) {
70
+ const out = process.stderr;
71
+ if (!out.isTTY)
72
+ return { update: () => undefined, finish: () => undefined };
73
+ let drawn = false;
74
+ let lastDraw = 0;
75
+ let last = { loaded: 0, total: 0 };
76
+ const draw = (loaded, total) => {
77
+ const fraction = total > 0 ? loaded / total : 0;
78
+ const side = [
79
+ '',
80
+ '',
81
+ paint('bold', 'Downloading the embedding model', out),
82
+ paint('dim', `${model}, downloaded once, then cached`, out),
83
+ '',
84
+ `${paint('yellow', bar(fraction, 28), out)} ${Math.round(fraction * 100)}%`,
85
+ paint('dim', `${mb(loaded)} of ${mb(total)} MB`, out),
86
+ '',
87
+ ];
88
+ const lines = amphora(fraction).map((row, i) => ` ${paint('yellow', row, out)} ${side[i] ?? ''}`);
89
+ // Move back up over the previous drawing, then redraw every line.
90
+ if (drawn)
91
+ out.write(`\x1b[${lines.length}A`);
92
+ out.write(`${lines.map((line) => `\r\x1b[K${line}`).join('\n')}\n`);
93
+ drawn = true;
94
+ };
95
+ return {
96
+ update(loaded, total) {
97
+ last = { loaded, total };
98
+ // Small files (tokenizer, config) come first and would read as 100% at once; the
99
+ // drawing starts with the model weights. Redraws are capped at about ten a second.
100
+ const now = Date.now();
101
+ if (total < MIN_DRAW_BYTES || (now - lastDraw < 100 && loaded < total))
102
+ return;
103
+ lastDraw = now;
104
+ draw(loaded, total);
105
+ },
106
+ finish() {
107
+ if (drawn)
108
+ draw(last.total, last.total);
109
+ },
110
+ };
111
+ }
112
+ /** A one-line bar for embedding progress, redrawn in place on stderr. */
113
+ export function embedProgress(done, total) {
114
+ const out = process.stderr;
115
+ if (!out.isTTY)
116
+ return;
117
+ const fraction = done / Math.max(total, 1);
118
+ out.write(`\r\x1b[K ${paint('dim', 'Embedding', out)} ${paint('yellow', bar(fraction), out)} ${done}/${total} chunks`);
119
+ }
120
+ /** Clears the current line on stderr, after a progress bar. */
121
+ export function clearLine() {
122
+ if (process.stderr.isTTY)
123
+ process.stderr.write('\r\x1b[K');
124
+ }
125
+ /** What a bare `remimem` prints: the banner and the few commands that matter first. */
126
+ export function welcome(version, initialized) {
127
+ const cmd = (text) => paint('cyan', text);
128
+ const step = (n, text, command) => ` ${paint('dim', `${n}.`)} ${text}\n ${cmd(command)}`;
129
+ const lines = [banner(version)];
130
+ if (initialized) {
131
+ lines.push(`${paint('green', '✓')} This project is set up. A few things to try:`, '', ` ${cmd('remimem search "how are requests authenticated"')} find code`, ` ${cmd('remimem context "add rate limiting to login"')} context for a task`, ` ${cmd('remimem stats')} what it saved`, ` ${cmd('remimem doctor')} check the setup`);
132
+ }
133
+ else {
134
+ lines.push('Get started in this project:', '', step(1, 'Index the code and get your client configuration', 'remimem init'), '', step(2, 'Connect your agent (Claude Code shown)', 'claude mcp add remimem -- npx -y remimem serve'), '', step(3, 'Ask it something', 'remimem search "where is the config loaded"'));
135
+ }
136
+ lines.push('', `${paint('dim', 'All commands:')} ${cmd('remimem --help')} ${paint('dim', 'Docs:')} ${paint('underline', 'https://github.com/JaswanthRemiel/remimem')}`, '');
137
+ return lines.join('\n');
138
+ }
@@ -0,0 +1,116 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { ConfigError } from '../errors.js';
5
+ export const CONFIG_DIR = '.remimem';
6
+ const EmbeddingSchema = z.strictObject({
7
+ /** `local` runs on this machine. `openai` and `voyage` send code to that service. `none` disables vectors. */
8
+ provider: z.enum(['local', 'openai', 'voyage', 'none']).default('local'),
9
+ /** Model name. Empty means the provider's default. */
10
+ model: z.string().default(''),
11
+ batchSize: z.number().int().positive().default(8),
12
+ /** Local models only: inputs are cut to this many model tokens. */
13
+ maxTokens: z.number().int().positive().default(256),
14
+ });
15
+ const RetrievalSchema = z.strictObject({
16
+ /** Reciprocal rank fusion constant: larger values flatten the difference between ranks. */
17
+ rrfK: z.number().positive().default(60),
18
+ /** Candidates taken from keyword search before fusion. 0 turns keyword search off. */
19
+ keywordLimit: z.number().int().nonnegative().default(50),
20
+ /** Candidates taken from vector search before fusion. 0 turns vector search off. */
21
+ vectorLimit: z.number().int().nonnegative().default(50),
22
+ /** BM25 column weights. */
23
+ keywordWeights: z
24
+ .strictObject({
25
+ content: z.number().nonnegative().default(1),
26
+ symbol: z.number().nonnegative().default(5),
27
+ path: z.number().nonnegative().default(2),
28
+ })
29
+ .prefault({}),
30
+ /** The most chunks one file may contribute to the results. 0 means no limit. */
31
+ maxChunksPerFile: z.number().int().nonnegative().default(0),
32
+ /** Score multiplier for chunks of files that are not parsed as code (docs, config, data). */
33
+ textFileWeight: z.number().positive().max(1).default(0.25),
34
+ /** Share of the token budget kept free for the signature-only neighbors of the results. */
35
+ neighborBudgetShare: z.number().min(0).max(0.9).default(0),
36
+ /** Results returned when the caller does not say how many. */
37
+ defaultK: z.number().int().positive().default(10),
38
+ defaultBudgetTokens: z.number().int().positive().default(4000),
39
+ /** Results `get_context` considers before packing; the budget decides how many are shown. */
40
+ contextK: z.number().int().positive().default(20),
41
+ /** The most project memories `get_context` adds from a search of the task text. 0 turns memories off. */
42
+ memoryLimit: z.number().int().nonnegative().default(5),
43
+ /** A memory found only by vector search needs at least this cosine similarity to the task. */
44
+ memoryMinSimilarity: z.number().min(0).max(1).default(0.4),
45
+ /** A memory found only by keyword search must contain at least this share of the task's terms. */
46
+ memoryMinKeywordMatch: z.number().min(0).max(1).default(0.5),
47
+ /** Graph expansion: how many top results get their neighbors added. */
48
+ graphTopN: z.number().int().nonnegative().default(10),
49
+ /** Graph expansion: show neighbors as signature and docstring only, not their full body. */
50
+ compressNeighbors: z.boolean().default(true),
51
+ /** Graph expansion: the most neighbors added in total. */
52
+ graphMaxNeighbors: z.number().int().nonnegative().default(20),
53
+ /**
54
+ * Graph expansion: neighbor score = parent score x the weight of the edge's confidence.
55
+ * A weight of 0 leaves edges of that confidence out.
56
+ */
57
+ edgeWeights: z
58
+ .strictObject({
59
+ exact: z.number().nonnegative().default(0.5),
60
+ import: z.number().nonnegative().default(0.4),
61
+ 'name-match': z.number().nonnegative().default(0.2),
62
+ })
63
+ .prefault({}),
64
+ });
65
+ // Unknown keys are rejected so a typo does not silently fall back to a default.
66
+ const ConfigSchema = z.strictObject({
67
+ /** Globs a file must match to be indexed. Empty means every file. */
68
+ include: z.array(z.string()).default([]),
69
+ /** Globs that remove files from the index, on top of the built-in excludes. */
70
+ exclude: z.array(z.string()).default([]),
71
+ maxFileSizeKb: z.number().int().positive().default(512),
72
+ embedding: EmbeddingSchema.prefault({}),
73
+ retrieval: RetrievalSchema.prefault({}),
74
+ watch: z
75
+ .strictObject({
76
+ /** `remimem watch` waits this long after the last file change before re-indexing. */
77
+ debounceMs: z.number().int().nonnegative().default(500),
78
+ })
79
+ .prefault({}),
80
+ dashboard: z
81
+ .strictObject({
82
+ /** `remimem serve` also serves the local dashboard. */
83
+ enabled: z.boolean().default(true),
84
+ /** Port on 127.0.0.1. 0 picks a free one, so several agent sessions do not collide. */
85
+ port: z.number().int().min(0).max(65535).default(0),
86
+ })
87
+ .prefault({}),
88
+ /** There is no telemetry. The field exists so that fact is visible in the config. */
89
+ telemetry: z.literal(false).default(false),
90
+ });
91
+ /** Validates a raw config object and fills in defaults. */
92
+ export function parseConfig(raw) {
93
+ const result = ConfigSchema.safeParse(raw);
94
+ if (!result.success) {
95
+ throw new ConfigError(`Invalid ${CONFIG_DIR}/config.json:\n${z.prettifyError(result.error)}`);
96
+ }
97
+ return result.data;
98
+ }
99
+ /** Loads `.remimem/config.json` under `root`, or the defaults when it does not exist. */
100
+ export function loadConfig(root) {
101
+ let text;
102
+ try {
103
+ text = readFileSync(join(root, CONFIG_DIR, 'config.json'), 'utf8');
104
+ }
105
+ catch {
106
+ return parseConfig({});
107
+ }
108
+ let raw;
109
+ try {
110
+ raw = JSON.parse(text);
111
+ }
112
+ catch (cause) {
113
+ throw new ConfigError(`${CONFIG_DIR}/config.json is not valid JSON: ${String(cause)}`);
114
+ }
115
+ return parseConfig(raw);
116
+ }