remimem 0.1.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.
@@ -0,0 +1,18 @@
1
+ Bundled license information:
2
+
3
+ cytoscape/dist/cytoscape.esm.mjs:
4
+ /*!
5
+ Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
6
+ Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
7
+ Licensed under The MIT License (http://opensource.org/licenses/MIT)
8
+ */
9
+ /*!
10
+ Event object based on jQuery events, MIT license
11
+
12
+ https://jquery.org/license/
13
+ https://tldrlegal.com/license/mit-license
14
+ https://github.com/jquery/jquery/blob/master/src/event.js
15
+ */
16
+ /*! Bezier curve function generator. Copyright 2014-2026 Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License
17
+ * https://github.com/gre/bezier-easing */
18
+ /*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
@@ -0,0 +1,37 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="referrer" content="no-referrer" />
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
+ />
12
+ <link rel="stylesheet" href="/app.css" />
13
+ </head>
14
+ <body>
15
+ <div class="shell">
16
+ <aside class="side">
17
+ <div class="brand">
18
+ <span class="mark" aria-hidden="true">μ</span>
19
+ <span class="name">remimem</span>
20
+ </div>
21
+ <p class="root" id="root" title=""></p>
22
+ <nav class="tabs" aria-label="Views">
23
+ <a href="#health" data-view="health">Health</a>
24
+ <a href="#activity" data-view="activity">Activity</a>
25
+ <a href="#graph" data-view="graph">Graph</a>
26
+ <a href="#search" data-view="search">Search</a>
27
+ <a href="#memory" data-view="memory">Memory</a>
28
+ <a href="#settings" data-view="settings">Settings</a>
29
+ </nav>
30
+ <p class="version" id="version"></p>
31
+ </aside>
32
+ <main id="main" tabindex="-1"></main>
33
+ </div>
34
+ <div class="toast" id="toast" role="status" aria-live="polite"></div>
35
+ <script type="module" src="/app.js"></script>
36
+ </body>
37
+ </html>
@@ -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';
@@ -24,14 +25,47 @@ function normalize(vector) {
24
25
  const norm = Math.sqrt(sum) || 1;
25
26
  return vector.map((x) => x / norm);
26
27
  }
28
+ let downloadListener;
29
+ /**
30
+ * Lets the CLI draw the first download of a local model. The MCP server never sets it, so
31
+ * nothing extra is ever written while it serves.
32
+ */
33
+ export function onModelDownload(listener) {
34
+ downloadListener = listener;
35
+ }
36
+ /** Sums byte progress across a model's files, and reports it only while files download. */
37
+ function progressReporter(model) {
38
+ const files = new Map();
39
+ let downloading = false;
40
+ return (info) => {
41
+ const event = info;
42
+ // Files read from the cache also report progress; only a real download is shown.
43
+ if (event.status === 'download')
44
+ downloading = true;
45
+ if (!downloading || !downloadListener || event.status !== 'progress' || !event.file)
46
+ return;
47
+ files.set(event.file, { loaded: event.loaded ?? 0, total: event.total ?? 0 });
48
+ let loaded = 0;
49
+ let total = 0;
50
+ for (const f of files.values()) {
51
+ loaded += f.loaded;
52
+ total += f.total;
53
+ }
54
+ downloadListener(model, loaded, total);
55
+ };
56
+ }
27
57
  function localProvider(model, maxTokens) {
28
58
  // Loaded on first use: importing the runtime and reading the model takes a while.
29
59
  let ready;
30
60
  const load = async () => {
31
61
  const { AutoModel, AutoTokenizer, env, mean_pooling } = await import('@huggingface/transformers');
32
62
  env.cacheDir = modelCacheDir();
33
- const tokenizer = await AutoTokenizer.from_pretrained(model);
34
- const network = await AutoModel.from_pretrained(model, { dtype: 'q8' });
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);
67
+ const tokenizer = await AutoTokenizer.from_pretrained(model, { progress_callback });
68
+ const network = await AutoModel.from_pretrained(model, { dtype: 'q8', progress_callback });
35
69
  return async (texts) => {
36
70
  const inputs = tokenizer(texts, { padding: true, truncation: true, max_length: maxTokens });
37
71
  const output = await network(inputs);
@@ -49,7 +83,7 @@ function localProvider(model, maxTokens) {
49
83
  return [];
50
84
  ready ??= load().catch((cause) => {
51
85
  ready = undefined;
52
- throw new EmbeddingError(`Embedding model ${model} failed to load (the first run downloads it); run \`remimem doctor\``, { cause });
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 });
53
87
  });
54
88
  return (await ready)(texts);
55
89
  },
@@ -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
- export function resolveReferences(input) {
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 key = `${family}|${source.startsWith('.') ? file.dir : ''}|${source}`;
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
- return source.startsWith('.')
86
- ? existing(endings(posix.normalize(posix.join(dir, bare))))
87
- : bySuffix(family, endings(bare.replace(/^[@~]\//, '')));
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 { refs, imports } = resolveReferences(store.graphInput());
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
+ }
@@ -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
  }
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
6
  import { CONFIG_DIR, loadConfig } from '../config/index.js';
7
+ import { startDashboard } from '../dashboard/server.js';
7
8
  import { createProvider } from '../embedder/index.js';
8
9
  import { RemimemError } from '../errors.js';
9
10
  import { log } from '../log.js';
@@ -60,9 +61,22 @@ export async function serve(root) {
60
61
  mkdirSync(join(root, CONFIG_DIR), { recursive: true });
61
62
  const store = new Store(join(root, CONFIG_DIR, 'index.db'));
62
63
  const ctx = { root, config, store, provider: createProvider(config.embedding) };
64
+ // The dashboard is a convenience: if its port cannot be opened, the tools still work.
65
+ const dashboard = config.dashboard.enabled
66
+ ? await startDashboard(ctx, config.dashboard.port).catch((error) => {
67
+ log.warn(`dashboard not started: ${String(error)}`);
68
+ return undefined;
69
+ })
70
+ : undefined;
71
+ // The dashboard lives as long as the agent's session: it never keeps the process alive.
72
+ dashboard?.unref();
73
+ ctx.dashboardUrl = dashboard?.url;
63
74
  const server = createServer(ctx);
64
75
  const transport = new StdioServerTransport();
65
- transport.onclose = () => store.close();
76
+ transport.onclose = () => {
77
+ void dashboard?.close();
78
+ store.close();
79
+ };
66
80
  await server.connect(transport);
67
81
  log.info(`serving ${root} over stdio`);
68
82
  }
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 about this codebase so future sessions see it. Link it to files or symbols so it is shown with them and flagged when they change. Example: remember({ text: "Passwords are hashed with argon2, never bcrypt", kind: "decision", symbols: ["hash"] }).', {
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 { memory, unlinked } = remember(ctx.root, ctx.store, args);
213
- const links = memory.links.map((l) => (l.symbol ? `${l.path} ${l.symbol}` : l.path));
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
- `Stored memory ${memory.id} (${memory.kind})${links.length > 0 ? `, linked to ${links.join(', ')}` : ''}.`,
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
- return withTokens(memories.map(formatMemory).join('\n'));
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)) {
@@ -268,5 +301,6 @@ export async function indexStatus(ctx) {
268
301
  `Last indexed: ${store.getMeta('last_indexed_at') ?? 'unknown'}${commit ? ` at commit ${commit.slice(0, 12)}` : ' (no git commit)'}`,
269
302
  `Pending changes: ${pending.changed} changed, ${pending.added} new, ${pending.deleted} deleted${pending.changed + pending.added + pending.deleted > 0 ? ' (run `remimem index`)' : ''}`,
270
303
  `Embedding model: ${model ? `${model} (${store.vectorCount()} of ${counts.chunks} chunks embedded)` : 'none (keyword search only)'}`,
304
+ ...(ctx.dashboardUrl ? [`Dashboard: ${ctx.dashboardUrl}`] : []),
271
305
  ].join('\n');
272
306
  }
@@ -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
+ }
@@ -150,12 +150,15 @@ export function remember(root, store, input) {
150
150
  links.push({ ...link, contentHash: currentHash(store, files, link) ?? '' });
151
151
  }
152
152
  const now = new Date().toISOString();
153
+ const existing = input.id === undefined ? undefined : store.listMemories().find((m) => m.id === input.id);
154
+ if (input.id !== undefined && !existing)
155
+ throw new MemoryError(`No memory with id ${input.id}.`);
153
156
  const memory = {
154
- id: `m_${randomBytes(4).toString('hex')}`,
157
+ id: existing?.id ?? `m_${randomBytes(4).toString('hex')}`,
155
158
  kind: input.kind,
156
159
  text: input.text.trim(),
157
160
  tags: [...new Set(input.tags ?? [])],
158
- createdAt: now,
161
+ createdAt: existing?.createdAt ?? now,
159
162
  updatedAt: now,
160
163
  links,
161
164
  };
@@ -165,6 +168,32 @@ export function remember(root, store, input) {
165
168
  writeMirror(root, store);
166
169
  return { memory: { ...memory, stale: false }, unlinked };
167
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
+ }
168
197
  /** Deletes a memory. Returns false when there is none with that id. */
169
198
  export function forget(root, store, id) {
170
199
  syncMemories(root, store);