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.
- package/LICENSE +21 -0
- package/README.md +213 -2
- package/dist/chunker/index.js +129 -0
- package/dist/cli/commands.js +256 -0
- package/dist/cli/index.js +18 -0
- package/dist/cli/program.js +206 -0
- package/dist/config/index.js +108 -0
- package/dist/embedder/index.js +196 -0
- package/dist/errors.js +15 -0
- package/dist/graph/describe.js +90 -0
- package/dist/graph/index.js +224 -0
- package/dist/indexer/index.js +183 -0
- package/dist/indexer/overview.js +75 -0
- package/dist/indexer/watch.js +55 -0
- package/dist/log.js +16 -0
- package/dist/mcp/server.js +68 -0
- package/dist/mcp/tools.js +272 -0
- package/dist/memory/index.js +259 -0
- package/dist/packer/index.js +149 -0
- package/dist/parser/index.js +294 -0
- package/dist/retriever/index.js +186 -0
- package/dist/scanner/index.js +129 -0
- package/dist/stats/index.js +32 -0
- package/dist/store/fts.js +26 -0
- package/dist/store/index.js +633 -0
- package/dist/tokens.js +8 -0
- package/grammars/README.md +15 -0
- package/grammars/ecma.scm +42 -0
- package/grammars/go.scm +37 -0
- package/grammars/go.wasm +0 -0
- package/grammars/javascript.scm +6 -0
- package/grammars/javascript.wasm +0 -0
- package/grammars/python.scm +21 -0
- package/grammars/python.wasm +0 -0
- package/grammars/tsx.wasm +0 -0
- package/grammars/typescript.scm +20 -0
- package/grammars/typescript.wasm +0 -0
- package/package.json +69 -4
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { statSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { Command } from 'commander';
|
|
5
|
+
import { processFile } from '../indexer/index.js';
|
|
6
|
+
import { RemimemError } from '../errors.js';
|
|
7
|
+
import { MEMORY_KINDS, MemoryError } from '../memory/index.js';
|
|
8
|
+
import { serve } from '../mcp/server.js';
|
|
9
|
+
import { runContext, runDoctor, runIndex, runInit, runMemory, runRefs, runSearch, runStats, runWatch, runSymbol, } from './commands.js';
|
|
10
|
+
import { resolveInRoot, scan } from '../scanner/index.js';
|
|
11
|
+
const pkg = createRequire(import.meta.url)('../../package.json');
|
|
12
|
+
export function buildProgram() {
|
|
13
|
+
const program = new Command('remimem')
|
|
14
|
+
.description('Local-first code context and project memory for coding agents')
|
|
15
|
+
.version(pkg.version);
|
|
16
|
+
program
|
|
17
|
+
.command('doctor')
|
|
18
|
+
.description('Check that this machine can run remimem')
|
|
19
|
+
.action(async () => {
|
|
20
|
+
const { lines, ok } = await runDoctor(process.cwd());
|
|
21
|
+
console.log(lines.join('\n'));
|
|
22
|
+
if (!ok)
|
|
23
|
+
process.exitCode = 1;
|
|
24
|
+
});
|
|
25
|
+
const tty = process.stderr.isTTY;
|
|
26
|
+
/** A progress bar on stderr while chunks are embedded. Silent when not a terminal. */
|
|
27
|
+
const onEmbedProgress = (done, total) => {
|
|
28
|
+
if (!tty)
|
|
29
|
+
return;
|
|
30
|
+
const filled = Math.round((done / Math.max(total, 1)) * 24);
|
|
31
|
+
process.stderr.write(`\rEmbedding [${'#'.repeat(filled)}${'.'.repeat(24 - filled)}] ${done}/${total}`);
|
|
32
|
+
};
|
|
33
|
+
const clearProgress = () => {
|
|
34
|
+
if (tty)
|
|
35
|
+
process.stderr.write('\r\x1b[K');
|
|
36
|
+
};
|
|
37
|
+
program
|
|
38
|
+
.command('init')
|
|
39
|
+
.description('Set up remimem in the current directory and print MCP client configuration')
|
|
40
|
+
.action(async () => {
|
|
41
|
+
const report = await runInit(process.cwd(), { onEmbedProgress });
|
|
42
|
+
clearProgress();
|
|
43
|
+
console.log(report);
|
|
44
|
+
});
|
|
45
|
+
program
|
|
46
|
+
.command('serve')
|
|
47
|
+
.description('Start the MCP server on stdio (this is what MCP clients run)')
|
|
48
|
+
.option('--root <dir>', 'project directory, default the current directory')
|
|
49
|
+
.action(async (options) => {
|
|
50
|
+
await serve(resolve(options.root ?? process.cwd()));
|
|
51
|
+
});
|
|
52
|
+
program
|
|
53
|
+
.command('context <task>')
|
|
54
|
+
.description('Print the context an agent would get for a task, to paste into any chat')
|
|
55
|
+
.option('--budget <tokens>', 'token budget for the output')
|
|
56
|
+
.action(async (task, options) => {
|
|
57
|
+
const budget = Number(options.budget);
|
|
58
|
+
console.log(await runContext(process.cwd(), task, Number.isFinite(budget) ? { budget } : {}));
|
|
59
|
+
});
|
|
60
|
+
const memory = program.command('memory').description('Manage project memory by hand');
|
|
61
|
+
const collect = (value, all) => [...all, value];
|
|
62
|
+
memory
|
|
63
|
+
.command('list')
|
|
64
|
+
.description('List memories, or search them with a query')
|
|
65
|
+
.argument('[query]', 'what to look for', '')
|
|
66
|
+
.option('--kind <kind>', 'decision, convention, gotcha, or todo')
|
|
67
|
+
.action(async (query, options) => {
|
|
68
|
+
console.log(await runMemory(process.cwd(), 'list', { query, kind: options.kind }));
|
|
69
|
+
});
|
|
70
|
+
memory
|
|
71
|
+
.command('add <text>')
|
|
72
|
+
.description('Save a memory')
|
|
73
|
+
.option('--kind <kind>', 'decision, convention, gotcha, or todo', 'decision')
|
|
74
|
+
.option('--path <path>', 'file this is about (repeatable)', collect, [])
|
|
75
|
+
.option('--symbol <name>', 'symbol this is about (repeatable)', collect, [])
|
|
76
|
+
.option('--tag <tag>', 'tag (repeatable)', collect, [])
|
|
77
|
+
.action(async (text, options) => {
|
|
78
|
+
if (!MEMORY_KINDS.includes(options.kind)) {
|
|
79
|
+
throw new MemoryError(`Unknown kind "${options.kind}". Use one of: ${MEMORY_KINDS.join(', ')}.`);
|
|
80
|
+
}
|
|
81
|
+
console.log(await runMemory(process.cwd(), 'add', {
|
|
82
|
+
text,
|
|
83
|
+
kind: options.kind,
|
|
84
|
+
paths: options.path,
|
|
85
|
+
symbols: options.symbol,
|
|
86
|
+
tags: options.tag,
|
|
87
|
+
}));
|
|
88
|
+
});
|
|
89
|
+
memory
|
|
90
|
+
.command('rm <id>')
|
|
91
|
+
.description('Delete a memory')
|
|
92
|
+
.action(async (id) => {
|
|
93
|
+
console.log(await runMemory(process.cwd(), 'rm', { id }));
|
|
94
|
+
});
|
|
95
|
+
program
|
|
96
|
+
.command('index')
|
|
97
|
+
.description('Index the current directory, skipping files that have not changed')
|
|
98
|
+
.option('--full', 'reindex every file and rebuild vectors')
|
|
99
|
+
.action(async (options) => {
|
|
100
|
+
const summary = await runIndex(process.cwd(), { ...options, onEmbedProgress });
|
|
101
|
+
clearProgress();
|
|
102
|
+
console.log(summary);
|
|
103
|
+
});
|
|
104
|
+
program
|
|
105
|
+
.command('watch')
|
|
106
|
+
.description('Keep the index fresh while you work')
|
|
107
|
+
.action(async () => {
|
|
108
|
+
const stop = await runWatch(process.cwd(), (line) => console.log(line));
|
|
109
|
+
process.once('SIGINT', () => void stop().then(() => process.exit(0)));
|
|
110
|
+
});
|
|
111
|
+
program
|
|
112
|
+
.command('stats')
|
|
113
|
+
.description('Show queries served and tokens served against an estimated baseline')
|
|
114
|
+
.action(() => {
|
|
115
|
+
console.log(runStats(process.cwd()));
|
|
116
|
+
});
|
|
117
|
+
program
|
|
118
|
+
.command('bench')
|
|
119
|
+
.description('Run the benchmark (from a source checkout of remimem)')
|
|
120
|
+
.option('--mine', 'rebuild the task files from the pinned repositories instead of running')
|
|
121
|
+
.option('--repo <name>', 'run one repository only (repeatable)', (v, all) => [...all, v], [])
|
|
122
|
+
.option('--limit <n>', 'run only the first n tasks of each repository')
|
|
123
|
+
.option('--model <name>', 'embedding model to index with')
|
|
124
|
+
.option('--tune', 'also try the tuning configurations on the training split')
|
|
125
|
+
.option('--update-readme', 'paste the summary table into README.md')
|
|
126
|
+
.option('--compare <file>', 'check the run against an earlier results file, within a tolerance')
|
|
127
|
+
.option('--e2e', 'print the cost estimate for the end-to-end agent run (add --yes to run it)')
|
|
128
|
+
.option('--yes', 'with --e2e: actually run it, which costs money')
|
|
129
|
+
.option('--price-per-mtok <usd>', 'with --e2e: price per million input tokens for the estimate')
|
|
130
|
+
.action(async (options) => {
|
|
131
|
+
// Loaded on demand: the benchmark is not part of the published package.
|
|
132
|
+
const { runBenchCommand } = await import('../bench/command.js').catch(() => {
|
|
133
|
+
throw new RemimemError('The benchmark runs from a source checkout of remimem.');
|
|
134
|
+
});
|
|
135
|
+
const ok = await runBenchCommand(options, (line) => console.log(line));
|
|
136
|
+
if (!ok)
|
|
137
|
+
process.exitCode = 1;
|
|
138
|
+
});
|
|
139
|
+
program
|
|
140
|
+
.command('search <query>')
|
|
141
|
+
.description('Search the index and print the best matching code within a token budget')
|
|
142
|
+
.option('-k, --limit <n>', 'number of results to consider')
|
|
143
|
+
.option('--budget <tokens>', 'token budget for the output')
|
|
144
|
+
.option('--debug', 'print every score before the results')
|
|
145
|
+
.action(async (query, options) => {
|
|
146
|
+
const number = (value) => value === undefined || !Number.isFinite(Number(value)) ? undefined : Number(value);
|
|
147
|
+
console.log(await runSearch(process.cwd(), query, {
|
|
148
|
+
k: number(options.limit),
|
|
149
|
+
budget: number(options.budget),
|
|
150
|
+
debug: options.debug,
|
|
151
|
+
}));
|
|
152
|
+
});
|
|
153
|
+
// Hidden developer commands, not part of the public interface.
|
|
154
|
+
const debug = program.command('debug', { hidden: true });
|
|
155
|
+
debug
|
|
156
|
+
.command('symbol <name>')
|
|
157
|
+
.description('Print a symbol with its callers, callees, and other neighbors')
|
|
158
|
+
.option('--depth <n>', 'hops of callers and callees to show, 0 to 2', '1')
|
|
159
|
+
.option('--signature', 'print the signature instead of the body')
|
|
160
|
+
.action((name, options) => {
|
|
161
|
+
console.log(runSymbol(process.cwd(), name, {
|
|
162
|
+
depth: Number(options.depth),
|
|
163
|
+
include: options.signature ? 'signature' : 'body',
|
|
164
|
+
}));
|
|
165
|
+
});
|
|
166
|
+
debug
|
|
167
|
+
.command('refs <name>')
|
|
168
|
+
.description('Print every reference to a symbol, grouped by file')
|
|
169
|
+
.action((name) => {
|
|
170
|
+
console.log(runRefs(process.cwd(), name));
|
|
171
|
+
});
|
|
172
|
+
debug
|
|
173
|
+
.command('chunks <path>')
|
|
174
|
+
.description('Print the chunks of a file, or scan and chunk a directory and print totals')
|
|
175
|
+
.option('--content', 'print chunk bodies')
|
|
176
|
+
.action(async (path, options) => {
|
|
177
|
+
const root = process.cwd();
|
|
178
|
+
const target = resolveInRoot(root, path);
|
|
179
|
+
if (statSync(target).isDirectory()) {
|
|
180
|
+
const started = performance.now();
|
|
181
|
+
const files = scan(target);
|
|
182
|
+
let lines = 0;
|
|
183
|
+
let symbols = 0;
|
|
184
|
+
let chunks = 0;
|
|
185
|
+
for (const file of files) {
|
|
186
|
+
const result = await processFile(target, file.path);
|
|
187
|
+
lines += result.lineCount;
|
|
188
|
+
symbols += result.parsed?.symbols.length ?? 0;
|
|
189
|
+
chunks += result.chunks.length;
|
|
190
|
+
}
|
|
191
|
+
const seconds = ((performance.now() - started) / 1000).toFixed(2);
|
|
192
|
+
console.log(`${files.length} files, ${lines} lines, ${symbols} symbols, ${chunks} chunks in ${seconds}s`);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const { chunks } = await processFile(root, path);
|
|
196
|
+
for (const chunk of chunks) {
|
|
197
|
+
const label = chunk.symbol ? `${chunk.kind} ${chunk.symbol}` : chunk.kind;
|
|
198
|
+
console.log(`${chunk.path}:${chunk.startLine}-${chunk.endLine} ${label}`);
|
|
199
|
+
if (chunk.signature)
|
|
200
|
+
console.log(` ${chunk.signature.replaceAll('\n', '\n ')}`);
|
|
201
|
+
if (options.content)
|
|
202
|
+
console.log(`${chunk.content}\n`);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
return program;
|
|
206
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
/** There is no telemetry. The field exists so that fact is visible in the config. */
|
|
81
|
+
telemetry: z.literal(false).default(false),
|
|
82
|
+
});
|
|
83
|
+
/** Validates a raw config object and fills in defaults. */
|
|
84
|
+
export function parseConfig(raw) {
|
|
85
|
+
const result = ConfigSchema.safeParse(raw);
|
|
86
|
+
if (!result.success) {
|
|
87
|
+
throw new ConfigError(`Invalid ${CONFIG_DIR}/config.json:\n${z.prettifyError(result.error)}`);
|
|
88
|
+
}
|
|
89
|
+
return result.data;
|
|
90
|
+
}
|
|
91
|
+
/** Loads `.remimem/config.json` under `root`, or the defaults when it does not exist. */
|
|
92
|
+
export function loadConfig(root) {
|
|
93
|
+
let text;
|
|
94
|
+
try {
|
|
95
|
+
text = readFileSync(join(root, CONFIG_DIR, 'config.json'), 'utf8');
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return parseConfig({});
|
|
99
|
+
}
|
|
100
|
+
let raw;
|
|
101
|
+
try {
|
|
102
|
+
raw = JSON.parse(text);
|
|
103
|
+
}
|
|
104
|
+
catch (cause) {
|
|
105
|
+
throw new ConfigError(`${CONFIG_DIR}/config.json is not valid JSON: ${String(cause)}`);
|
|
106
|
+
}
|
|
107
|
+
return parseConfig(raw);
|
|
108
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { RemimemError, ConfigError } from '../errors.js';
|
|
5
|
+
export class EmbeddingError extends RemimemError {
|
|
6
|
+
}
|
|
7
|
+
const DEFAULT_MODELS = {
|
|
8
|
+
local: 'Xenova/all-MiniLM-L6-v2',
|
|
9
|
+
openai: 'text-embedding-3-small',
|
|
10
|
+
voyage: 'voyage-code-3',
|
|
11
|
+
};
|
|
12
|
+
const REMOTE = {
|
|
13
|
+
openai: { url: 'https://api.openai.com/v1/embeddings', keyEnv: 'OPENAI_API_KEY' },
|
|
14
|
+
voyage: { url: 'https://api.voyageai.com/v1/embeddings', keyEnv: 'VOYAGE_API_KEY' },
|
|
15
|
+
};
|
|
16
|
+
/** Where downloaded models are kept. Override with REMIMEM_CACHE_DIR. */
|
|
17
|
+
export function modelCacheDir() {
|
|
18
|
+
return join(process.env['REMIMEM_CACHE_DIR'] ?? join(homedir(), '.cache', 'remimem'), 'models');
|
|
19
|
+
}
|
|
20
|
+
function normalize(vector) {
|
|
21
|
+
let sum = 0;
|
|
22
|
+
for (const x of vector)
|
|
23
|
+
sum += x * x;
|
|
24
|
+
const norm = Math.sqrt(sum) || 1;
|
|
25
|
+
return vector.map((x) => x / norm);
|
|
26
|
+
}
|
|
27
|
+
function localProvider(model, maxTokens) {
|
|
28
|
+
// Loaded on first use: importing the runtime and reading the model takes a while.
|
|
29
|
+
let ready;
|
|
30
|
+
const load = async () => {
|
|
31
|
+
const { AutoModel, AutoTokenizer, env, mean_pooling } = await import('@huggingface/transformers');
|
|
32
|
+
env.cacheDir = modelCacheDir();
|
|
33
|
+
const tokenizer = await AutoTokenizer.from_pretrained(model);
|
|
34
|
+
const network = await AutoModel.from_pretrained(model, { dtype: 'q8' });
|
|
35
|
+
return async (texts) => {
|
|
36
|
+
const inputs = tokenizer(texts, { padding: true, truncation: true, max_length: maxTokens });
|
|
37
|
+
const output = await network(inputs);
|
|
38
|
+
const pooled = mean_pooling(output.last_hidden_state, inputs.attention_mask);
|
|
39
|
+
const [rows = 0, dim = 0] = pooled.dims;
|
|
40
|
+
const data = pooled.data;
|
|
41
|
+
return Array.from({ length: rows }, (_, i) => normalize(data.slice(i * dim, (i + 1) * dim)));
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
id: `local:${model}`,
|
|
46
|
+
local: true,
|
|
47
|
+
async embed(texts) {
|
|
48
|
+
if (texts.length === 0)
|
|
49
|
+
return [];
|
|
50
|
+
ready ??= load().catch((cause) => {
|
|
51
|
+
ready = undefined;
|
|
52
|
+
throw new EmbeddingError(`Embedding model ${model} failed to load (the first run downloads it); run \`remimem doctor\``, { cause });
|
|
53
|
+
});
|
|
54
|
+
return (await ready)(texts);
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function remoteProvider(provider, model) {
|
|
59
|
+
const { url, keyEnv } = REMOTE[provider];
|
|
60
|
+
return {
|
|
61
|
+
id: `${provider}:${model}`,
|
|
62
|
+
local: false,
|
|
63
|
+
async embed(texts, kind) {
|
|
64
|
+
if (texts.length === 0)
|
|
65
|
+
return [];
|
|
66
|
+
// Keys come from the environment only, never from the config file.
|
|
67
|
+
const key = process.env[keyEnv];
|
|
68
|
+
if (!key)
|
|
69
|
+
throw new ConfigError(`Set ${keyEnv} to use the ${provider} embedding provider`);
|
|
70
|
+
const body = JSON.stringify({
|
|
71
|
+
model,
|
|
72
|
+
input: texts,
|
|
73
|
+
...(provider === 'voyage' ? { input_type: kind } : {}),
|
|
74
|
+
});
|
|
75
|
+
let lastError = '';
|
|
76
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
77
|
+
if (attempt > 0)
|
|
78
|
+
await new Promise((done) => setTimeout(done, 500 * 2 ** attempt));
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await fetch(url, {
|
|
82
|
+
method: 'POST',
|
|
83
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
84
|
+
body,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
lastError = String(error);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (response.ok) {
|
|
92
|
+
const json = (await response.json());
|
|
93
|
+
return [...json.data]
|
|
94
|
+
.sort((a, b) => a.index - b.index)
|
|
95
|
+
.map((item) => normalize(Float32Array.from(item.embedding)));
|
|
96
|
+
}
|
|
97
|
+
lastError = `HTTP ${response.status}: ${(await response.text()).slice(0, 200)}`;
|
|
98
|
+
// Only rate limits and server errors are worth another try.
|
|
99
|
+
if (response.status !== 429 && response.status < 500)
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
throw new EmbeddingError(`${provider} embedding request failed: ${lastError}`);
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** The provider the config asks for, or null when embeddings are turned off. */
|
|
107
|
+
export function createProvider(config) {
|
|
108
|
+
if (config.provider === 'none')
|
|
109
|
+
return null;
|
|
110
|
+
const model = config.model || DEFAULT_MODELS[config.provider];
|
|
111
|
+
return config.provider === 'local'
|
|
112
|
+
? localProvider(model, config.maxTokens)
|
|
113
|
+
: remoteProvider(config.provider, model);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The text that is embedded for a chunk: path, signature, docstring, then the body. Local
|
|
117
|
+
* models cut their input after a few hundred tokens, and this order means the cut only ever
|
|
118
|
+
* removes the end of the body.
|
|
119
|
+
*/
|
|
120
|
+
export function embeddingText(chunk) {
|
|
121
|
+
const { path, content, signature, docstring } = chunk;
|
|
122
|
+
if (!signature)
|
|
123
|
+
return `${path}\n${content}`;
|
|
124
|
+
// Drop the doc comment above the symbol, then the signature the code starts with, so
|
|
125
|
+
// neither appears twice. A later part of a split function also starts with the signature.
|
|
126
|
+
let body = content.split('\n').slice(chunk.docLines).join('\n');
|
|
127
|
+
const wanted = signature.replace(/\s+/g, '');
|
|
128
|
+
let end = 0;
|
|
129
|
+
for (let matched = 0; end < body.length && matched < wanted.length; end++) {
|
|
130
|
+
const ch = body[end];
|
|
131
|
+
if (/\s/.test(ch))
|
|
132
|
+
continue;
|
|
133
|
+
if (ch !== wanted[matched])
|
|
134
|
+
break;
|
|
135
|
+
matched++;
|
|
136
|
+
if (matched === wanted.length) {
|
|
137
|
+
body = body.slice(end + 1);
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// shortcut: a Python docstring stays in the body as well, since it is part of the code.
|
|
142
|
+
// Strip it there if the repeated text turns out to cost recall.
|
|
143
|
+
return [path, signature, docstring, body.trim()].filter(Boolean).join('\n');
|
|
144
|
+
}
|
|
145
|
+
const hashOf = (text) => createHash('sha256').update(text).digest('hex');
|
|
146
|
+
/** True when the stored vectors came from a different model than `provider`. */
|
|
147
|
+
export function modelChanged(store, provider) {
|
|
148
|
+
const stored = store.embeddingModel();
|
|
149
|
+
return stored !== undefined && stored !== provider.id;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Gives every chunk that lacks a vector one, reusing cached vectors for text that was
|
|
153
|
+
* embedded before. Safe to interrupt: the next run continues with what is still missing.
|
|
154
|
+
*/
|
|
155
|
+
export async function embedMissing(store, provider, batchSize, onProgress) {
|
|
156
|
+
if (modelChanged(store, provider)) {
|
|
157
|
+
throw new EmbeddingError(`The index holds vectors from ${store.embeddingModel()} but the configured model is ${provider.id}; run \`remimem index --full\` to rebuild them`);
|
|
158
|
+
}
|
|
159
|
+
const stats = { embedded: 0, cached: 0, hashes: new Set() };
|
|
160
|
+
// Cheap check first: finding the chunks that lack a vector scans the whole table.
|
|
161
|
+
if (store.embeddingModel() !== undefined && store.vectorCount() === store.counts().chunks) {
|
|
162
|
+
return stats;
|
|
163
|
+
}
|
|
164
|
+
const pending = store.chunksWithoutVectors();
|
|
165
|
+
for (let start = 0; start < pending.length; start += batchSize) {
|
|
166
|
+
const batch = pending.slice(start, start + batchSize).map((chunk) => {
|
|
167
|
+
const text = embeddingText(chunk);
|
|
168
|
+
const hash = hashOf(text);
|
|
169
|
+
return { id: chunk.id, text, hash, vector: store.cachedEmbedding(hash, provider.id) };
|
|
170
|
+
});
|
|
171
|
+
const misses = batch.filter((item) => !item.vector);
|
|
172
|
+
const fresh = await provider.embed(misses.map((item) => item.text), 'document');
|
|
173
|
+
if (fresh.length !== misses.length) {
|
|
174
|
+
throw new EmbeddingError(`${provider.id} returned ${fresh.length} vectors for ${misses.length} texts`);
|
|
175
|
+
}
|
|
176
|
+
for (const [i, item] of misses.entries())
|
|
177
|
+
item.vector = fresh[i];
|
|
178
|
+
const first = batch[0]?.vector;
|
|
179
|
+
if (first && store.embeddingModel() === undefined)
|
|
180
|
+
store.resetVectors(provider.id, first.length);
|
|
181
|
+
store.transaction(() => {
|
|
182
|
+
for (const item of batch) {
|
|
183
|
+
const vector = item.vector;
|
|
184
|
+
store.setVector(item.id, vector);
|
|
185
|
+
if (misses.includes(item))
|
|
186
|
+
store.cacheEmbedding(item.hash, provider.id, vector);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
for (const item of batch)
|
|
190
|
+
stats.hashes.add(item.hash);
|
|
191
|
+
stats.embedded += batch.length;
|
|
192
|
+
stats.cached += batch.length - misses.length;
|
|
193
|
+
onProgress?.(stats.embedded, pending.length);
|
|
194
|
+
}
|
|
195
|
+
return stats;
|
|
196
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Base class for errors whose message is safe and useful to show to the user. */
|
|
2
|
+
export class RemimemError extends Error {
|
|
3
|
+
constructor(message, options) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export class GrammarError extends RemimemError {
|
|
9
|
+
}
|
|
10
|
+
export class PathError extends RemimemError {
|
|
11
|
+
}
|
|
12
|
+
export class ConfigError extends RemimemError {
|
|
13
|
+
}
|
|
14
|
+
export class StoreError extends RemimemError {
|
|
15
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { render } from '../packer/index.js';
|
|
2
|
+
/** Section titles for each relation, in display order. */
|
|
3
|
+
const SECTIONS = [
|
|
4
|
+
['calls', 'Calls'],
|
|
5
|
+
['calls by', 'Called by'],
|
|
6
|
+
['extends', 'Extends'],
|
|
7
|
+
['extends by', 'Extended by'],
|
|
8
|
+
['implements', 'Implements'],
|
|
9
|
+
['implements by', 'Implemented by'],
|
|
10
|
+
['uses-type', 'Uses types'],
|
|
11
|
+
['uses-type by', 'Used as a type by'],
|
|
12
|
+
['inside', 'Inside'],
|
|
13
|
+
['contains', 'Contains'],
|
|
14
|
+
];
|
|
15
|
+
const location = (s) => `${s.path}:${s.startLine}-${s.endLine}`;
|
|
16
|
+
/** The symbols a name refers to: an exact qualified name wins over plain name matches. */
|
|
17
|
+
function lookup(store, name) {
|
|
18
|
+
const matches = store.symbolsNamed(name);
|
|
19
|
+
const qualified = matches.filter((s) => s.qualifiedName === name);
|
|
20
|
+
return qualified.length > 0 ? qualified : matches;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A symbol with its neighbors, as text for an agent. `depth` is how many hops of callers
|
|
24
|
+
* and callees to follow (0 to 2); other relations are listed for the symbol itself.
|
|
25
|
+
*/
|
|
26
|
+
export function describeSymbol(store, name, options = {}) {
|
|
27
|
+
const matches = lookup(store, name);
|
|
28
|
+
const symbol = matches[0];
|
|
29
|
+
if (!symbol)
|
|
30
|
+
return `No symbol named "${name}" in the index.`;
|
|
31
|
+
if (matches.length > 1) {
|
|
32
|
+
const list = matches.map((s) => ` ${s.kind} ${s.qualifiedName} ${location(s)}`);
|
|
33
|
+
return `${matches.length} symbols are named "${name}". Ask again with a qualified name:\n${list.join('\n')}`;
|
|
34
|
+
}
|
|
35
|
+
const depth = Math.max(0, Math.min(2, Math.trunc(options.depth ?? 1)));
|
|
36
|
+
const chunks = store.chunksOfSymbol(symbol.id);
|
|
37
|
+
const body = options.include === 'signature' || chunks.length === 0
|
|
38
|
+
? `--- ${location(symbol)} ${symbol.kind} ${symbol.qualifiedName}\n${symbol.signature}${symbol.docstring ? `\n${symbol.docstring.replace(/^/gm, ' ')}` : ''}`
|
|
39
|
+
: render(chunks.map((chunk) => ({ chunk, score: 0, reasons: [], detail: 'full' }))).replaceAll(' []', '');
|
|
40
|
+
if (depth === 0)
|
|
41
|
+
return body;
|
|
42
|
+
const out = [body];
|
|
43
|
+
const direct = store.neighbors([symbol.id]);
|
|
44
|
+
for (const [relation, title] of SECTIONS) {
|
|
45
|
+
const rows = direct.filter((n) => n.relation === relation);
|
|
46
|
+
if (rows.length === 0)
|
|
47
|
+
continue;
|
|
48
|
+
out.push('', `${title}:`);
|
|
49
|
+
const follow = relation === 'calls' || relation === 'calls by';
|
|
50
|
+
const seen = new Set([symbol.id]);
|
|
51
|
+
const walk = (level, hop) => {
|
|
52
|
+
for (const n of level) {
|
|
53
|
+
const again = seen.has(n.id);
|
|
54
|
+
seen.add(n.id);
|
|
55
|
+
out.push(`${' '.repeat(hop)}${n.qualifiedName} ${location(n)} [${n.confidence}]${again ? ' (shown above)' : ''}`);
|
|
56
|
+
if (follow && !again && hop < depth) {
|
|
57
|
+
walk(store.neighbors([n.id]).filter((next) => next.relation === relation), hop + 1);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
walk(rows, 1);
|
|
62
|
+
}
|
|
63
|
+
return out.join('\n');
|
|
64
|
+
}
|
|
65
|
+
/** Every place a symbol is called, extended, used as a type, or imported, grouped by file. */
|
|
66
|
+
export function findReferences(store, name) {
|
|
67
|
+
const matches = lookup(store, name);
|
|
68
|
+
if (matches.length === 0)
|
|
69
|
+
return `No symbol named "${name}" in the index.`;
|
|
70
|
+
const references = store.referencesTo(matches.map((s) => s.id));
|
|
71
|
+
const defined = matches.map((s) => `${s.kind} ${s.qualifiedName} at ${location(s)}`).join('; ');
|
|
72
|
+
if (references.length === 0)
|
|
73
|
+
return `No references found to ${defined}.`;
|
|
74
|
+
const paths = new Set(references.map((r) => r.path));
|
|
75
|
+
const out = [
|
|
76
|
+
`${references.length} reference${references.length === 1 ? '' : 's'} in ${paths.size} file${paths.size === 1 ? '' : 's'} to ${defined}`,
|
|
77
|
+
];
|
|
78
|
+
let current = '';
|
|
79
|
+
for (const r of references) {
|
|
80
|
+
if (r.path !== current) {
|
|
81
|
+
current = r.path;
|
|
82
|
+
out.push('', r.path);
|
|
83
|
+
}
|
|
84
|
+
const what = r.kind === 'import'
|
|
85
|
+
? 'import'
|
|
86
|
+
: `${r.kind} in ${r.fromSymbol ?? 'file scope'} [${r.confidence}]`;
|
|
87
|
+
out.push(` ${r.path}:${r.line} ${what}`);
|
|
88
|
+
}
|
|
89
|
+
return out.join('\n');
|
|
90
|
+
}
|