remimem 0.2.0 → 0.3.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/README.md +13 -13
- package/dist/cli/commands.js +16 -1
- package/dist/cli/index.js +47 -6
- package/dist/cli/program.js +21 -1
- package/dist/cli/ui.js +18 -2
- package/dist/dashboard/api.js +12 -1
- package/dist/dashboard/server.js +16 -1
- package/dist/dashboard/ui/app.css +1 -1
- package/dist/dashboard/ui/app.js +22 -22
- package/dist/dashboard/ui/geist-pixel-latin-400-normal-ODEFW7VT.woff2 +0 -0
- package/dist/dashboard/ui/index.html +5 -0
- package/dist/dashboard/ui/inter-latin-400-normal-55WT6UWF.woff2 +0 -0
- package/dist/dashboard/ui/inter-latin-500-normal-W62DVTXI.woff2 +0 -0
- package/dist/dashboard/ui/inter-latin-600-normal-R6Y2SZCR.woff2 +0 -0
- package/dist/dashboard/ui/jetbrains-mono-latin-400-normal-3OOWLGQ2.woff2 +0 -0
- package/dist/dashboard/ui/jetbrains-mono-latin-500-normal-V4XIP5OW.woff2 +0 -0
- package/dist/embedder/index.js +6 -2
- package/dist/graph/index.js +30 -9
- package/dist/graph/tsconfig.js +100 -0
- package/dist/indexer/index.js +1 -1
- package/dist/mcp/tools.js +41 -8
- package/dist/memory/import.js +136 -0
- package/dist/memory/index.js +26 -0
- package/dist/store/index.js +9 -0
- package/dist/store/probe.js +113 -0
- package/package.json +4 -1
|
Binary file
|
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
6
|
<meta name="referrer" content="no-referrer" />
|
|
7
7
|
<title>remimem dashboard</title>
|
|
8
|
+
<link
|
|
9
|
+
rel="icon"
|
|
10
|
+
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%231f2bff'/%3E%3Cpath d='M23.5 17v33M23.5 30.5a8.25 8.25 0 0 0 16.5 0V17M40 30.5v5.5q0 4.5 4.5 4.5' fill='none' stroke='%23ffffff' stroke-width='5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"
|
|
11
|
+
/>
|
|
8
12
|
<link rel="stylesheet" href="/app.css" />
|
|
9
13
|
</head>
|
|
10
14
|
<body>
|
|
@@ -17,6 +21,7 @@
|
|
|
17
21
|
<p class="root" id="root" title=""></p>
|
|
18
22
|
<nav class="tabs" aria-label="Views">
|
|
19
23
|
<a href="#health" data-view="health">Health</a>
|
|
24
|
+
<a href="#activity" data-view="activity">Activity</a>
|
|
20
25
|
<a href="#graph" data-view="graph">Graph</a>
|
|
21
26
|
<a href="#search" data-view="search">Search</a>
|
|
22
27
|
<a href="#memory" data-view="memory">Memory</a>
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/dist/embedder/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { join } from 'node:path';
|
|
4
5
|
import { RemimemError, ConfigError } from '../errors.js';
|
|
@@ -59,7 +60,10 @@ function localProvider(model, maxTokens) {
|
|
|
59
60
|
const load = async () => {
|
|
60
61
|
const { AutoModel, AutoTokenizer, env, mean_pooling } = await import('@huggingface/transformers');
|
|
61
62
|
env.cacheDir = modelCacheDir();
|
|
62
|
-
|
|
63
|
+
// The library reports progress for files read from the cache too, so a model already on disk
|
|
64
|
+
// is never shown as downloading. q8 weights are stored as onnx/model_quantized.onnx.
|
|
65
|
+
const cached = existsSync(join(env.cacheDir, model, 'onnx', 'model_quantized.onnx'));
|
|
66
|
+
const progress_callback = cached ? undefined : progressReporter(model);
|
|
63
67
|
const tokenizer = await AutoTokenizer.from_pretrained(model, { progress_callback });
|
|
64
68
|
const network = await AutoModel.from_pretrained(model, { dtype: 'q8', progress_callback });
|
|
65
69
|
return async (texts) => {
|
|
@@ -79,7 +83,7 @@ function localProvider(model, maxTokens) {
|
|
|
79
83
|
return [];
|
|
80
84
|
ready ??= load().catch((cause) => {
|
|
81
85
|
ready = undefined;
|
|
82
|
-
throw new EmbeddingError(`Embedding model ${model} failed to load
|
|
86
|
+
throw new EmbeddingError(`Embedding model ${model} failed to load. The first run downloads it from huggingface.co: check the network or proxy, or set "embedding": { "provider": "none" } in .remimem/config.json to work without it`, { cause });
|
|
83
87
|
});
|
|
84
88
|
return (await ready)(texts);
|
|
85
89
|
},
|
package/dist/graph/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { posix } from 'node:path';
|
|
2
|
+
import { aliasCandidates, readTsPaths } from './tsconfig.js';
|
|
2
3
|
/** Languages that can refer to each other's symbols. */
|
|
3
4
|
const FAMILY = {
|
|
4
5
|
typescript: 'ecma',
|
|
@@ -27,7 +28,11 @@ function push(map, key, value) {
|
|
|
27
28
|
* is unique in the repo (`name-match`). A call through an import that leads outside the
|
|
28
29
|
* repo, such as `fmt.Println`, is left unresolved instead of guessed.
|
|
29
30
|
*/
|
|
30
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Resolves every reference. `tsPaths` are the path aliases from the repo's tsconfig and jsconfig
|
|
33
|
+
* files; the nearest config above an importing file applies.
|
|
34
|
+
*/
|
|
35
|
+
export function resolveReferences(input, tsPaths = []) {
|
|
31
36
|
const files = new Map(input.files.map((f) => [f.id, { ...f, dir: dirOf(f.path) }]));
|
|
32
37
|
const fileIdByPath = new Map(input.files.map((f) => [f.path, f.id]));
|
|
33
38
|
const filesByDir = new Map();
|
|
@@ -55,15 +60,20 @@ export function resolveReferences(input) {
|
|
|
55
60
|
locals.set(`${i.fileId}:${i.local}`, i);
|
|
56
61
|
const moduleCache = new Map();
|
|
57
62
|
/** The repo files an import source refers to; empty when it leads outside the repo. */
|
|
63
|
+
// The nearest config above a folder: the deepest one whose folder contains it.
|
|
64
|
+
const configFor = (dir) => tsPaths
|
|
65
|
+
.filter((c) => c.dir === '' || dir === c.dir || dir.startsWith(`${c.dir}/`))
|
|
66
|
+
.sort((a, b) => b.dir.length - a.dir.length)[0];
|
|
58
67
|
const moduleFiles = (fileId, source) => {
|
|
59
68
|
const file = files.get(fileId);
|
|
60
69
|
if (!file || !source)
|
|
61
70
|
return [];
|
|
62
71
|
const family = familyOf(fileId);
|
|
63
|
-
const
|
|
72
|
+
const config = family === 'ecma' && !source.startsWith('.') ? configFor(file.dir) : undefined;
|
|
73
|
+
const key = `${family}|${source.startsWith('.') ? file.dir : (config?.dir ?? '')}|${source}`;
|
|
64
74
|
let found = moduleCache.get(key);
|
|
65
75
|
if (!found) {
|
|
66
|
-
found = findModule(family, file.dir, source);
|
|
76
|
+
found = findModule(family, file.dir, source, config);
|
|
67
77
|
moduleCache.set(key, found);
|
|
68
78
|
}
|
|
69
79
|
return found;
|
|
@@ -78,13 +88,19 @@ export function resolveReferences(input) {
|
|
|
78
88
|
endings.some((end) => f.path === end || f.path.endsWith(`/${end}`)));
|
|
79
89
|
return hits.length === 1 ? [hits[0].id] : [];
|
|
80
90
|
};
|
|
81
|
-
function findModule(family, dir, source) {
|
|
91
|
+
function findModule(family, dir, source, config) {
|
|
82
92
|
if (family === 'ecma') {
|
|
83
93
|
const bare = source.replace(/\.(js|jsx|mjs|cjs|ts|tsx)$/, '');
|
|
84
94
|
const endings = (base) => ECMA_EXTENSIONS.flatMap((ext) => [`${base}${ext}`, `${base}/index${ext}`]);
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
95
|
+
if (source.startsWith('.'))
|
|
96
|
+
return existing(endings(posix.normalize(posix.join(dir, bare))));
|
|
97
|
+
// An alias from tsconfig names the file exactly; without one, match by file name.
|
|
98
|
+
for (const candidate of config ? aliasCandidates(config, bare) : []) {
|
|
99
|
+
const hit = existing(endings(candidate));
|
|
100
|
+
if (hit.length > 0)
|
|
101
|
+
return hit;
|
|
102
|
+
}
|
|
103
|
+
return bySuffix(family, endings(bare.replace(/^[@~]\//, '')));
|
|
88
104
|
}
|
|
89
105
|
if (family === 'python') {
|
|
90
106
|
const dots = /^\.*/.exec(source)?.[0].length ?? 0;
|
|
@@ -217,8 +233,13 @@ export function resolveReferences(input) {
|
|
|
217
233
|
return { refs, imports };
|
|
218
234
|
}
|
|
219
235
|
/** Resolves every reference in the store again and rebuilds the edges. */
|
|
220
|
-
export function updateGraph(store) {
|
|
221
|
-
const
|
|
236
|
+
export function updateGraph(store, root) {
|
|
237
|
+
const input = store.graphInput();
|
|
238
|
+
const configs = input.files
|
|
239
|
+
.map((f) => f.path)
|
|
240
|
+
.filter((p) => /(^|\/)(tsconfig|jsconfig)\.json$/.test(p));
|
|
241
|
+
const tsPaths = root ? readTsPaths(root, configs) : [];
|
|
242
|
+
const { refs, imports } = resolveReferences(input, tsPaths);
|
|
222
243
|
store.saveResolution(refs, imports);
|
|
223
244
|
return { edges: store.edgeCount() };
|
|
224
245
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Path aliases from tsconfig.json and jsconfig.json (`compilerOptions.baseUrl` and `paths`), so
|
|
2
|
+
// an import such as `@/lib/db` resolves to the file it names instead of a guess by file name.
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { join, posix } from 'node:path';
|
|
5
|
+
/** JSON with comments and trailing commas, as TypeScript accepts it. */
|
|
6
|
+
export function parseJsonc(text) {
|
|
7
|
+
let out = '';
|
|
8
|
+
let inString = false;
|
|
9
|
+
for (let i = 0; i < text.length; i++) {
|
|
10
|
+
const c = text[i];
|
|
11
|
+
if (inString) {
|
|
12
|
+
out += c;
|
|
13
|
+
if (c === '\\')
|
|
14
|
+
out += text[++i] ?? '';
|
|
15
|
+
else if (c === '"')
|
|
16
|
+
inString = false;
|
|
17
|
+
}
|
|
18
|
+
else if (c === '"') {
|
|
19
|
+
inString = true;
|
|
20
|
+
out += c;
|
|
21
|
+
}
|
|
22
|
+
else if (c === '/' && text[i + 1] === '/') {
|
|
23
|
+
while (i < text.length && text[i] !== '\n')
|
|
24
|
+
i++;
|
|
25
|
+
out += '\n';
|
|
26
|
+
}
|
|
27
|
+
else if (c === '/' && text[i + 1] === '*') {
|
|
28
|
+
i = text.indexOf('*/', i + 2);
|
|
29
|
+
if (i === -1)
|
|
30
|
+
break;
|
|
31
|
+
i++;
|
|
32
|
+
}
|
|
33
|
+
else
|
|
34
|
+
out += c;
|
|
35
|
+
}
|
|
36
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads the alias settings of the given config files (paths from the project root). Files that
|
|
40
|
+
* are missing, unreadable, or have no aliases are skipped.
|
|
41
|
+
* shortcut: `extends` is not followed, so aliases defined only in a base config are missed; follow
|
|
42
|
+
* it when someone reports a monorepo that keeps them there.
|
|
43
|
+
*/
|
|
44
|
+
export function readTsPaths(root, configPaths) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const path of configPaths) {
|
|
47
|
+
let options;
|
|
48
|
+
try {
|
|
49
|
+
const config = parseJsonc(readFileSync(join(root, path), 'utf8'));
|
|
50
|
+
options = config.compilerOptions;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!options)
|
|
56
|
+
continue;
|
|
57
|
+
const dir = posix.dirname(path) === '.' ? '' : posix.dirname(path);
|
|
58
|
+
const hasBaseUrl = typeof options.baseUrl === 'string';
|
|
59
|
+
const base = posix.normalize(posix.join(dir, hasBaseUrl ? options.baseUrl : '.'));
|
|
60
|
+
const paths = Object.entries(typeof options.paths === 'object' && options.paths !== null ? options.paths : {}).flatMap(([pattern, targets]) => Array.isArray(targets)
|
|
61
|
+
? [[pattern, targets.filter((t) => typeof t === 'string')]]
|
|
62
|
+
: []);
|
|
63
|
+
if (paths.length > 0 || hasBaseUrl) {
|
|
64
|
+
out.push({ dir, base: base === '.' ? '' : base, paths, hasBaseUrl });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The candidate paths (from the project root, without extension) an import source maps to under
|
|
71
|
+
* one config, in the order TypeScript tries them: the most specific matching alias first, then
|
|
72
|
+
* `baseUrl`.
|
|
73
|
+
*/
|
|
74
|
+
export function aliasCandidates(config, source) {
|
|
75
|
+
let best;
|
|
76
|
+
for (const [pattern, targets] of config.paths) {
|
|
77
|
+
const star = pattern.indexOf('*');
|
|
78
|
+
if (star === -1) {
|
|
79
|
+
if (pattern === source)
|
|
80
|
+
best = { prefixLength: Infinity, targets, star: '' };
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const prefix = pattern.slice(0, star);
|
|
84
|
+
const suffix = pattern.slice(star + 1);
|
|
85
|
+
if (source.startsWith(prefix) &&
|
|
86
|
+
source.endsWith(suffix) &&
|
|
87
|
+
source.length >= prefix.length + suffix.length &&
|
|
88
|
+
(!best || prefix.length > best.prefixLength)) {
|
|
89
|
+
best = {
|
|
90
|
+
prefixLength: prefix.length,
|
|
91
|
+
targets,
|
|
92
|
+
star: source.slice(prefix.length, source.length - suffix.length),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const out = (best?.targets ?? []).map((target) => posix.normalize(posix.join(config.base, target.replace('*', best?.star ?? ''))));
|
|
97
|
+
if (config.hasBaseUrl)
|
|
98
|
+
out.push(posix.normalize(posix.join(config.base, source)));
|
|
99
|
+
return out.map((p) => (p === '.' ? '' : p.replace(/^\.\//, '')));
|
|
100
|
+
}
|
package/dist/indexer/index.js
CHANGED
|
@@ -158,7 +158,7 @@ export async function indexRepo(root, store, config, options = {}) {
|
|
|
158
158
|
// Name resolution depends on every file, so the graph is rebuilt whenever anything changed.
|
|
159
159
|
if (changed || store.getMeta('overview') === undefined) {
|
|
160
160
|
const graphStarted = performance.now();
|
|
161
|
-
updateGraph(store);
|
|
161
|
+
updateGraph(store, root);
|
|
162
162
|
store.setMeta('overview', buildOverview(store));
|
|
163
163
|
log.debug(`graph and overview rebuilt in ${Math.round(performance.now() - graphStarted)} ms`);
|
|
164
164
|
}
|
package/dist/mcp/tools.js
CHANGED
|
@@ -4,7 +4,7 @@ import { RemimemError } from '../errors.js';
|
|
|
4
4
|
import { describeSymbol, findReferences } from '../graph/describe.js';
|
|
5
5
|
import { indexRepo, pendingChanges } from '../indexer/index.js';
|
|
6
6
|
import { log } from '../log.js';
|
|
7
|
-
import { forget, formatMemory, linkedMemories, MEMORY_KINDS, recall, remember, } from '../memory/index.js';
|
|
7
|
+
import { confirmMemory, forget, formatMemory, linkedMemories, MEMORY_KINDS, MemoryError, recall, remember, } from '../memory/index.js';
|
|
8
8
|
import { pack } from '../packer/index.js';
|
|
9
9
|
import { LANGS, languageOf } from '../parser/index.js';
|
|
10
10
|
import { search } from '../retriever/index.js';
|
|
@@ -202,17 +202,47 @@ export const TOOLS = [
|
|
|
202
202
|
requireIndex(ctx);
|
|
203
203
|
return withTokens(findReferences(ctx.store, args.name));
|
|
204
204
|
}),
|
|
205
|
-
tool('remember', 'Save a decision, convention, gotcha, or todo
|
|
206
|
-
text: z.string().min(1).describe('The fact to keep, in one or two sentences.'),
|
|
207
|
-
kind: z.enum(MEMORY_KINDS),
|
|
205
|
+
tool('remember', 'Save a decision, convention, gotcha, or todo for future sessions, linked to files or symbols so it is flagged when they change. Example: remember({ text: "Passwords use argon2", kind: "decision", symbols: ["hash"] }). remember({ id }) confirms a stale memory is still true; id plus fields updates it.', {
|
|
206
|
+
text: z.string().min(1).optional().describe('The fact to keep, in one or two sentences.'),
|
|
207
|
+
kind: z.enum(MEMORY_KINDS).optional().describe('Required for a new memory.'),
|
|
208
208
|
paths: z.array(z.string()).optional().describe('Files this is about.'),
|
|
209
209
|
symbols: z.array(z.string()).optional().describe('Symbols this is about.'),
|
|
210
210
|
tags: z.array(z.string()).optional(),
|
|
211
|
+
id: z
|
|
212
|
+
.string()
|
|
213
|
+
.optional()
|
|
214
|
+
.describe('An existing memory to update or, given alone, to confirm as still true.'),
|
|
211
215
|
}, (ctx, args) => {
|
|
212
|
-
const
|
|
213
|
-
const
|
|
216
|
+
const describe = (memory) => memory.links.map((l) => (l.symbol ? `${l.path} ${l.symbol}` : l.path));
|
|
217
|
+
const { id, text, kind, paths, symbols, tags } = args;
|
|
218
|
+
if (id !== undefined && [text, kind, paths, symbols, tags].every((v) => v === undefined)) {
|
|
219
|
+
const { memory, dropped } = confirmMemory(ctx.root, ctx.store, id);
|
|
220
|
+
const links = describe(memory);
|
|
221
|
+
return [
|
|
222
|
+
`Confirmed memory ${memory.id}: still true${links.length > 0 ? `, now linked to the current ${links.join(', ')}` : ''}.`,
|
|
223
|
+
...dropped.map((name) => `Unlinked: ${name} (no longer in the index).`),
|
|
224
|
+
].join('\n');
|
|
225
|
+
}
|
|
226
|
+
const existing = id === undefined ? undefined : ctx.store.listMemories().find((m) => m.id === id);
|
|
227
|
+
if (id !== undefined && !existing)
|
|
228
|
+
throw new MemoryError(`No memory with id ${id}.`);
|
|
229
|
+
const finalText = text ?? existing?.text;
|
|
230
|
+
const finalKind = kind ?? existing?.kind;
|
|
231
|
+
if (!finalText || !finalKind) {
|
|
232
|
+
throw new MemoryError('A new memory needs text and a kind.');
|
|
233
|
+
}
|
|
234
|
+
const { memory, unlinked } = remember(ctx.root, ctx.store, {
|
|
235
|
+
id,
|
|
236
|
+
text: finalText,
|
|
237
|
+
kind: finalKind,
|
|
238
|
+
// Links not given again are kept, refreshed to the current code.
|
|
239
|
+
paths: paths ?? existing?.links.filter((l) => !l.symbol).map((l) => l.path),
|
|
240
|
+
symbols: symbols ?? existing?.links.flatMap((l) => (l.symbol ? [l.symbol] : [])),
|
|
241
|
+
tags: tags ?? existing?.tags,
|
|
242
|
+
});
|
|
243
|
+
const links = describe(memory);
|
|
214
244
|
return [
|
|
215
|
-
|
|
245
|
+
`${existing ? 'Updated' : 'Stored'} memory ${memory.id} (${memory.kind})${links.length > 0 ? `, linked to ${links.join(', ')}` : ''}.`,
|
|
216
246
|
...unlinked.map((name) => `Not linked: ${name}.`),
|
|
217
247
|
].join('\n');
|
|
218
248
|
}, false),
|
|
@@ -223,7 +253,10 @@ export const TOOLS = [
|
|
|
223
253
|
const memories = await recall(ctx.root, ctx.store, ctx.provider, args.query, ctx.config.retrieval, { kind: args.kind });
|
|
224
254
|
if (memories.length === 0)
|
|
225
255
|
return 'No memories match.';
|
|
226
|
-
|
|
256
|
+
const hint = memories.some((m) => m.stale)
|
|
257
|
+
? '\n(For a stale memory: remember({ id }) confirms it is still true; forget({ id }) deletes it.)'
|
|
258
|
+
: '';
|
|
259
|
+
return withTokens(memories.map(formatMemory).join('\n') + hint);
|
|
227
260
|
}),
|
|
228
261
|
tool('forget', 'Delete a saved memory by id, e.g. one that recall marked stale and is no longer true. Example: forget({ id: "m_3f9a2c1b" }).', { id: z.string().min(1).describe('The memory id, as shown by recall.') }, (ctx, args) => {
|
|
229
262
|
if (!forget(ctx.root, ctx.store, args.id)) {
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Turns decision records a project already has into memories: architecture decision records
|
|
2
|
+
// (one decision per file, with a "Decision" or "Decision Outcome" section) and decision logs
|
|
3
|
+
// (one decision per "##" section, as in a DECISIONS.md).
|
|
4
|
+
import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
5
|
+
import { join, relative } from 'node:path';
|
|
6
|
+
import { resolveInRoot } from '../scanner/index.js';
|
|
7
|
+
import { MemoryError, remember } from './index.js';
|
|
8
|
+
/** The longest memory an import makes; longer decisions are cut at a sentence. */
|
|
9
|
+
const MAX_TEXT = 500;
|
|
10
|
+
function sections(markdown) {
|
|
11
|
+
const out = [];
|
|
12
|
+
let current;
|
|
13
|
+
let fence = false;
|
|
14
|
+
for (const line of markdown.split(/\r?\n/)) {
|
|
15
|
+
if (/^\s*(```|~~~)/.test(line))
|
|
16
|
+
fence = !fence;
|
|
17
|
+
const heading = fence ? null : /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(line);
|
|
18
|
+
if (heading) {
|
|
19
|
+
current = { level: heading[1].length, title: heading[2], body: '' };
|
|
20
|
+
out.push(current);
|
|
21
|
+
}
|
|
22
|
+
else if (current)
|
|
23
|
+
current.body += `${line}\n`;
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
/** Plain text from Markdown: no list markers, emphasis, links, or code fences. */
|
|
28
|
+
function plain(markdown) {
|
|
29
|
+
return markdown
|
|
30
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
31
|
+
.replace(/^\s*[-*+]\s+/gm, '')
|
|
32
|
+
.replace(/^\s*\d+\.\s+/gm, '')
|
|
33
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
|
34
|
+
.replace(/(\*\*|__|\*|_)(\S.*?\S|\S)\1/g, '$2')
|
|
35
|
+
.replace(/`([^`]+)`/g, '$1')
|
|
36
|
+
.replace(/\s+/g, ' ')
|
|
37
|
+
.trim();
|
|
38
|
+
}
|
|
39
|
+
/** Cuts text at the last full sentence that fits. */
|
|
40
|
+
function clip(text) {
|
|
41
|
+
if (text.length <= MAX_TEXT)
|
|
42
|
+
return text;
|
|
43
|
+
const cut = text.slice(0, MAX_TEXT);
|
|
44
|
+
const end = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf('; '));
|
|
45
|
+
return end > MAX_TEXT / 3 ? cut.slice(0, end + 1) : `${cut.trimEnd()}...`;
|
|
46
|
+
}
|
|
47
|
+
/** What a section decided: its "Decision:" item or subsection if it has one, else its opening. */
|
|
48
|
+
function decisionOf(body) {
|
|
49
|
+
// A labelled item, as in "- **Decision:** ...", with the items nested under it.
|
|
50
|
+
const labelled = /^[ \t]*[-*]?\s*\*\*Decision:?\*\*:?\s*(.*(?:\n(?:[ \t]+.*|\s*))*)/im.exec(body);
|
|
51
|
+
if (labelled?.[1]?.trim()) {
|
|
52
|
+
const lines = labelled[1].split('\n');
|
|
53
|
+
const kept = [lines[0]];
|
|
54
|
+
for (const line of lines.slice(1)) {
|
|
55
|
+
if (/^\S/.test(line) || /^[ \t]*[-*]\s*\*\*\w[^*]*:\*\*/.test(line))
|
|
56
|
+
break;
|
|
57
|
+
kept.push(line);
|
|
58
|
+
}
|
|
59
|
+
return plain(kept.join('\n'));
|
|
60
|
+
}
|
|
61
|
+
const paragraph = body
|
|
62
|
+
.split(/\n\s*\n/)
|
|
63
|
+
.map((p) => p.trim())
|
|
64
|
+
.find((p) => p && !/^(status|date|deciders?)\s*:/i.test(p));
|
|
65
|
+
return plain(paragraph ?? '');
|
|
66
|
+
}
|
|
67
|
+
const DECISION = /^decision( outcome)?$/i;
|
|
68
|
+
/** The decisions in one Markdown document. */
|
|
69
|
+
export function findDecisions(markdown, path) {
|
|
70
|
+
const all = sections(markdown);
|
|
71
|
+
const decision = all.find((s) => DECISION.test(plain(s.title)));
|
|
72
|
+
// One ADR per file: the title is the top heading, the text is its Decision section.
|
|
73
|
+
if (decision || all.filter((s) => s.level === 2).length < 2) {
|
|
74
|
+
const top = all.find((s) => s.level === 1) ?? all[0];
|
|
75
|
+
const text = decision ? decisionOf(decision.body) : decisionOf(top?.body ?? markdown);
|
|
76
|
+
const title = plain(top?.title ?? path).replace(/^(ADR[- ]?)?\d+[.:)]?\s*/i, '');
|
|
77
|
+
return text ? [{ path, title, text: clip(`${title}: ${text}`) }] : [];
|
|
78
|
+
}
|
|
79
|
+
// A decision log: every "##" section is one decision.
|
|
80
|
+
return all
|
|
81
|
+
.filter((s) => s.level === 2)
|
|
82
|
+
.flatMap((s) => {
|
|
83
|
+
const title = plain(s.title).replace(/^\d+[.:)]?\s*/, '');
|
|
84
|
+
const text = decisionOf(s.body);
|
|
85
|
+
return text ? [{ path, title, text: clip(`${title}: ${text}`) }] : [];
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** The Markdown files a path names: the file itself, or every .md file under a folder. */
|
|
89
|
+
function markdownFiles(path) {
|
|
90
|
+
if (!statSync(path).isDirectory())
|
|
91
|
+
return [path];
|
|
92
|
+
return readdirSync(path, { recursive: true, encoding: 'utf8' })
|
|
93
|
+
.filter((name) => /\.(md|markdown)$/i.test(name))
|
|
94
|
+
.sort()
|
|
95
|
+
.map((name) => join(path, name));
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Imports the decisions found in files or folders under `root`. Each memory is linked to the
|
|
99
|
+
* document it came from (when that document is indexed) and tagged `imported`. Running it again
|
|
100
|
+
* adds only what is new. With `dryRun`, nothing is saved.
|
|
101
|
+
*/
|
|
102
|
+
export function importDecisions(root, store, paths, options = {}) {
|
|
103
|
+
const found = [];
|
|
104
|
+
// resolveInRoot returns real paths, so compare against the real root (macOS /var is a link).
|
|
105
|
+
const realRoot = realpathSync(root);
|
|
106
|
+
for (const raw of paths) {
|
|
107
|
+
const target = resolveInRoot(root, raw);
|
|
108
|
+
for (const file of markdownFiles(target)) {
|
|
109
|
+
const path = relative(realRoot, file).replaceAll('\\', '/');
|
|
110
|
+
found.push(...findDecisions(readFileSync(file, 'utf8'), path));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (found.length === 0) {
|
|
114
|
+
throw new MemoryError('No decisions found. Point it at ADR files (with a "Decision" section) or a log with one "##" section per decision.');
|
|
115
|
+
}
|
|
116
|
+
const known = new Set(store.listMemories().map((m) => m.text));
|
|
117
|
+
const result = { added: [], skipped: [] };
|
|
118
|
+
const indexed = store.fileHashes();
|
|
119
|
+
for (const decision of found) {
|
|
120
|
+
if (known.has(decision.text)) {
|
|
121
|
+
result.skipped.push(decision);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
known.add(decision.text);
|
|
125
|
+
result.added.push(decision);
|
|
126
|
+
if (options.dryRun)
|
|
127
|
+
continue;
|
|
128
|
+
remember(root, store, {
|
|
129
|
+
text: decision.text,
|
|
130
|
+
kind: options.kind ?? 'decision',
|
|
131
|
+
paths: indexed.has(decision.path) ? [decision.path] : [],
|
|
132
|
+
tags: ['imported'],
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
}
|
package/dist/memory/index.js
CHANGED
|
@@ -168,6 +168,32 @@ export function remember(root, store, input) {
|
|
|
168
168
|
writeMirror(root, store);
|
|
169
169
|
return { memory: { ...memory, stale: false }, unlinked };
|
|
170
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Confirms that a memory is still true after its code changed: its links are pointed at the code
|
|
173
|
+
* as it is now, so it is no longer stale. Links to files or symbols that no longer exist are
|
|
174
|
+
* dropped and reported.
|
|
175
|
+
*/
|
|
176
|
+
export function confirmMemory(root, store, id) {
|
|
177
|
+
syncMemories(root, store);
|
|
178
|
+
const existing = store.listMemories().find((m) => m.id === id);
|
|
179
|
+
if (!existing)
|
|
180
|
+
throw new MemoryError(`No memory with id ${id}.`);
|
|
181
|
+
const files = store.fileHashes();
|
|
182
|
+
const links = [];
|
|
183
|
+
const dropped = [];
|
|
184
|
+
for (const link of existing.links) {
|
|
185
|
+
const contentHash = currentHash(store, files, link);
|
|
186
|
+
if (contentHash === null)
|
|
187
|
+
dropped.push(link.symbol ? `${link.path} ${link.symbol}` : link.path);
|
|
188
|
+
else
|
|
189
|
+
links.push({ ...link, contentHash });
|
|
190
|
+
}
|
|
191
|
+
const { kind, text, tags, createdAt } = existing;
|
|
192
|
+
const memory = { id, kind, text, tags, createdAt, links, updatedAt: new Date().toISOString() };
|
|
193
|
+
store.transaction(() => store.putMemory(memory));
|
|
194
|
+
writeMirror(root, store);
|
|
195
|
+
return { memory: { ...memory, stale: false }, dropped };
|
|
196
|
+
}
|
|
171
197
|
/** Deletes a memory. Returns false when there is none with that id. */
|
|
172
198
|
export function forget(root, store, id) {
|
|
173
199
|
syncMemories(root, store);
|
package/dist/store/index.js
CHANGED
|
@@ -219,6 +219,15 @@ export class Store {
|
|
|
219
219
|
.prepare('INSERT INTO query_log (tool, query, tokens_returned, baseline_tokens_estimate, latency_ms, created_at) VALUES (?, ?, ?, ?, ?, ?)')
|
|
220
220
|
.run(entry.tool, entry.query, entry.tokensReturned, entry.baselineTokens, entry.latencyMs, new Date().toISOString());
|
|
221
221
|
}
|
|
222
|
+
/** Tool calls logged after the given id, newest first, for the dashboard's live activity. */
|
|
223
|
+
queryLogAfter(afterId, limit) {
|
|
224
|
+
return this.db
|
|
225
|
+
.prepare(`SELECT id, tool, query, tokens_returned AS tokensReturned,
|
|
226
|
+
baseline_tokens_estimate AS baselineTokens, latency_ms AS latencyMs,
|
|
227
|
+
created_at AS createdAt
|
|
228
|
+
FROM query_log WHERE id > ? ORDER BY id DESC LIMIT ?`)
|
|
229
|
+
.all(afterId, limit);
|
|
230
|
+
}
|
|
222
231
|
/** Queries and tokens per day, oldest first, for the dashboard's savings chart. */
|
|
223
232
|
queryLogDaily() {
|
|
224
233
|
return this.db
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// A check of the native SQLite modules, run in a child process. better-sqlite3 and sqlite-vec are
|
|
2
|
+
// compiled code: a binary built for another Node.js version, or a broken one, can kill the whole
|
|
3
|
+
// process with an access violation before any JavaScript error handling runs, so the CLI would
|
|
4
|
+
// exit with no message. A child that crashes instead lets the parent explain what happened.
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { dirname, join } from 'node:path';
|
|
10
|
+
const require = createRequire(import.meta.url);
|
|
11
|
+
const DOCS = 'https://github.com/JaswanthRemiel/remimem/blob/main/SETUP.md#troubleshooting';
|
|
12
|
+
/** Windows reports a native crash as an NTSTATUS exit code, such as 0xC0000005. */
|
|
13
|
+
function describeExit({ status, signal }) {
|
|
14
|
+
if (signal)
|
|
15
|
+
return `killed by ${signal}`;
|
|
16
|
+
if (status === null)
|
|
17
|
+
return 'no exit code';
|
|
18
|
+
if (status > 255) {
|
|
19
|
+
const hex = `0x${(status >>> 0).toString(16).toUpperCase()}`;
|
|
20
|
+
return hex === '0xC0000005' ? `exit ${hex}, access violation` : `exit ${hex}`;
|
|
21
|
+
}
|
|
22
|
+
return `exit ${status}`;
|
|
23
|
+
}
|
|
24
|
+
/** Turns what the child did into a message that says what is wrong and how to fix it. */
|
|
25
|
+
export function classifyProbe(outcome, versions) {
|
|
26
|
+
if (outcome.status === 0)
|
|
27
|
+
return { ok: true };
|
|
28
|
+
const stderr = outcome.stderr.trim();
|
|
29
|
+
// The line that names the error; Node's last line is only its version footer.
|
|
30
|
+
const lines = stderr
|
|
31
|
+
.split('\n')
|
|
32
|
+
.map((l) => l.trim())
|
|
33
|
+
.filter(Boolean);
|
|
34
|
+
const last = lines.find((l) => /error/i.test(l)) ?? lines.filter((l) => !/^Node\.js v/.test(l)).at(-1) ?? '';
|
|
35
|
+
const missing = /bindings file|NODE_MODULE_VERSION|was compiled against a different Node\.js version|Cannot find module|invalid ELF|not a valid Win32 application|image not found|dlopen|mach-o|slice is not valid/i.test(stderr);
|
|
36
|
+
const crashed = outcome.signal !== null || outcome.status === null || outcome.status > 255;
|
|
37
|
+
const steps = [
|
|
38
|
+
'Update Node.js to the latest 22.x or 24.x release, then reinstall: npm install -g remimem',
|
|
39
|
+
'Or build the SQLite module on this machine: npm rebuild -g better-sqlite3 --build-from-source (needs C++ build tools; on Windows, Visual Studio Build Tools with "Desktop development with C++")',
|
|
40
|
+
'If you run remimem through npx, clear its cache first: npx clear-npx-cache',
|
|
41
|
+
`More help: ${DOCS}`,
|
|
42
|
+
];
|
|
43
|
+
const fix = steps.map((step, i) => ` ${i + 1}. ${step}`).join('\n');
|
|
44
|
+
if (missing) {
|
|
45
|
+
return {
|
|
46
|
+
ok: false,
|
|
47
|
+
kind: 'missing',
|
|
48
|
+
message: `The SQLite module is missing or was built for a different Node.js (${versions}).\n${last}\nTo fix it:\n${fix}`,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (crashed) {
|
|
52
|
+
return {
|
|
53
|
+
ok: false,
|
|
54
|
+
kind: 'crash',
|
|
55
|
+
message: `SQLite crashed on this machine (${describeExit(outcome)}; ${versions}). remimem stores its index in SQLite, so it cannot run until this is fixed.\nTo fix it:\n${fix}`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
kind: 'failed',
|
|
61
|
+
message: `SQLite failed to start (${describeExit(outcome)}; ${versions}).\n${last}\nTo fix it:\n${fix}`,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function versionOf(name) {
|
|
65
|
+
try {
|
|
66
|
+
return require(`${name}/package.json`).version;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return 'unknown';
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Opens an in-memory database with the vector extension in a child process. A success is
|
|
74
|
+
* remembered per platform, Node.js ABI and module version, so the check runs once per setup.
|
|
75
|
+
*/
|
|
76
|
+
export function probeSqlite() {
|
|
77
|
+
const sqlite = versionOf('better-sqlite3');
|
|
78
|
+
const versions = `Node.js ${process.version}, ${process.platform}-${process.arch}, better-sqlite3 ${sqlite}`;
|
|
79
|
+
const marker = join(process.env['REMIMEM_CACHE_DIR'] ?? join(homedir(), '.cache', 'remimem'), 'checks', `sqlite-${process.platform}-${process.arch}-abi${process.versions.modules}-${sqlite}-${versionOf('sqlite-vec')}`);
|
|
80
|
+
if (existsSync(marker))
|
|
81
|
+
return { ok: true };
|
|
82
|
+
let script;
|
|
83
|
+
try {
|
|
84
|
+
script = [
|
|
85
|
+
`const Database = require(${JSON.stringify(require.resolve('better-sqlite3'))});`,
|
|
86
|
+
`const vec = require(${JSON.stringify(require.resolve('sqlite-vec'))});`,
|
|
87
|
+
`const db = new Database(':memory:');`,
|
|
88
|
+
`vec.load(db);`,
|
|
89
|
+
`db.prepare('select vec_version() as v').get();`,
|
|
90
|
+
`db.close();`,
|
|
91
|
+
].join('\n');
|
|
92
|
+
}
|
|
93
|
+
catch (cause) {
|
|
94
|
+
const outcome = { status: 1, signal: null, stderr: `Cannot find module: ${String(cause)}` };
|
|
95
|
+
return classifyProbe(outcome, versions);
|
|
96
|
+
}
|
|
97
|
+
const child = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', timeout: 30_000 });
|
|
98
|
+
const result = classifyProbe({
|
|
99
|
+
status: child.status,
|
|
100
|
+
signal: child.signal,
|
|
101
|
+
stderr: child.stderr ?? String(child.error ?? ''),
|
|
102
|
+
}, versions);
|
|
103
|
+
if (result.ok) {
|
|
104
|
+
try {
|
|
105
|
+
mkdirSync(dirname(marker), { recursive: true });
|
|
106
|
+
writeFileSync(marker, `${new Date().toISOString()}\n`);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// Not being able to cache the result only means the check runs again next time.
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remimem",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Codebase memory for coding agents: a local-first MCP server and CLI that serves only the code context an agent needs",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jaswanth Remiel AG",
|
|
@@ -46,6 +46,9 @@
|
|
|
46
46
|
"zod": "^4.6.7"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
+
"@fontsource/geist-pixel": "^5.3.0",
|
|
50
|
+
"@fontsource/inter": "^5.3.0",
|
|
51
|
+
"@fontsource/jetbrains-mono": "^5.3.0",
|
|
49
52
|
"@types/better-sqlite3": "^9.6.0",
|
|
50
53
|
"@types/node": "^22.20.5",
|
|
51
54
|
"@vitest/coverage-v8": "^5.1.0",
|