@nandoblanco/opencode-local-memory 1.0.0 → 1.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.
Files changed (4) hide show
  1. package/README.md +42 -22
  2. package/index.js +1637 -101
  3. package/package.json +1 -1
  4. package/tui.ts +285 -67
package/index.js CHANGED
@@ -4,12 +4,15 @@
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import os from "node:os";
7
+ import { execFile } from "node:child_process";
7
8
  import { fileURLToPath } from "node:url";
8
9
 
9
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
10
12
  const cliName = "open" + "code";
11
13
 
12
14
  let embedderPromise = null;
15
+ let activeSyncPromise = null;
13
16
  let cachedEntries = null;
14
17
  let cachedRootDir = "";
15
18
  let cachedMtime = 0;
@@ -18,7 +21,176 @@ let cachedTopicSlugs = null;
18
21
  let cachedTopicsRootDir = "";
19
22
  let lastContextKey = "";
20
23
  let lastContextText = "";
24
+ let cachedCorpusStats = null;
21
25
  const queryVecCache = new Map();
26
+ const parsedFileCache = new Map();
27
+
28
+ const STOPWORDS = new Set([
29
+ "a", "an", "and", "are", "as", "at", "be", "by", "can", "do", "for",
30
+ "from", "had", "has", "have", "how", "if", "in", "into", "is", "it",
31
+ "its", "not", "of", "on", "or", "our", "out", "so", "that", "the",
32
+ "their", "then", "there", "these", "they", "this", "to", "use", "used",
33
+ "using", "was", "we", "were", "what", "when", "where", "which", "who",
34
+ "why", "will", "with", "you", "your"
35
+ ]);
36
+
37
+ function tokenizeText(text) {
38
+ if (!text) return [];
39
+ return String(text)
40
+ .toLowerCase()
41
+ .split(/[^a-z0-9_.-]+/)
42
+ .map(function (t) { return t.replace(/^[._-]+|[._-]+$/g, ""); })
43
+ .filter(function (t) { return t.length >= 2; });
44
+ }
45
+
46
+ const UMBRELLA_DIRS = new Set([
47
+ "mampfiles", "git", "hannon-hill", "_clients", "_cms", "_modules",
48
+ "z-old-clients", "client-code-cms", "client-code", "projects",
49
+ "opencode-plugins", "repos", "workspace", "users", "home"
50
+ ]);
51
+
52
+ function slugifyScopePart(str) {
53
+ return String(str || "")
54
+ .trim()
55
+ .toLowerCase()
56
+ .replace(/[^a-z0-9-_]/g, "-")
57
+ .replace(/-+/g, "-")
58
+ .replace(/^-|-$/g, "");
59
+ }
60
+
61
+ function isUmbrellaProject(raw) {
62
+ const val = String(raw || "").trim();
63
+ if (!val || val.toLowerCase() === "global" || val.toLowerCase() === "all" || val === "*") return true;
64
+ const norm = val.replace(/\\/g, "/").replace(/\/+$/, "");
65
+ if (/(?:^|\/)(?:_clients|client-code-cms|client-code|projects)\/([a-z0-9._-]+)/i.test(norm)) {
66
+ return false;
67
+ }
68
+ const gitSub = norm.match(/(?:^|\/)git\/(?:hannon-hill|opencode-plugins)\/([a-z0-9._-]+)/i);
69
+ if (gitSub && !UMBRELLA_DIRS.has(gitSub[1].toLowerCase())) return false;
70
+ const gitDirect = norm.match(/(?:^|\/)git\/([a-z0-9._-]+)/i);
71
+ if (gitDirect && !UMBRELLA_DIRS.has(gitDirect[1].toLowerCase())) return false;
72
+ const base = slugifyScopePart(path.posix.basename(norm) || norm);
73
+ return !base || UMBRELLA_DIRS.has(base);
74
+ }
75
+
76
+ function normalizeProjectScope(raw) {
77
+ const val = String(raw || "").trim();
78
+ if (!val || val.toLowerCase() === "global" || val === "*") return "global";
79
+ if (val.toLowerCase() === "all") return "all";
80
+ const norm = val.replace(/\\/g, "/").replace(/\/+$/, "");
81
+
82
+ if (/^(cms|git)\/[a-z0-9-_]+$/i.test(norm)) {
83
+ const parts = norm.split("/");
84
+ return parts[0].toLowerCase() + "/" + slugifyScopePart(parts[1]);
85
+ }
86
+
87
+ const cmsMatch = norm.match(/(?:^|\/)(?:_clients|client-code-cms|client-code|projects)\/([a-z0-9._-]+)/i);
88
+ if (cmsMatch && !UMBRELLA_DIRS.has(cmsMatch[1].toLowerCase())) {
89
+ return "cms/" + slugifyScopePart(cmsMatch[1]);
90
+ }
91
+
92
+ const gitNested = norm.match(/(?:^|\/)git\/(?:hannon-hill|opencode-plugins)\/([a-z0-9._-]+)/i);
93
+ if (gitNested && !UMBRELLA_DIRS.has(gitNested[1].toLowerCase())) {
94
+ return "git/" + slugifyScopePart(gitNested[1]);
95
+ }
96
+
97
+ const gitRepo = norm.match(/(?:^|\/)git\/([a-z0-9._-]+)/i);
98
+ if (gitRepo && !UMBRELLA_DIRS.has(gitRepo[1].toLowerCase())) {
99
+ return "git/" + slugifyScopePart(gitRepo[1]);
100
+ }
101
+
102
+ const mampChild = norm.match(/(?:^|\/)mampfiles\/([a-z0-9._-]+)/i);
103
+ if (mampChild) {
104
+ const child = slugifyScopePart(mampChild[1]);
105
+ if (child && child !== "agent" && !UMBRELLA_DIRS.has(child)) {
106
+ return child;
107
+ }
108
+ }
109
+
110
+ const base = slugifyScopePart(path.posix.basename(norm) || norm);
111
+ if (!base || UMBRELLA_DIRS.has(base)) return "global";
112
+ return base;
113
+ }
114
+
115
+ function getProjectLeaf(scope) {
116
+ const norm = normalizeProjectScope(scope);
117
+ const idx = norm.lastIndexOf("/");
118
+ return idx !== -1 ? norm.slice(idx + 1) : norm;
119
+ }
120
+
121
+ function projectSlugsEquivalent(a, b) {
122
+ if (!a || !b) return false;
123
+ if (a === b) return true;
124
+ const leafA = getProjectLeaf(a);
125
+ const leafB = getProjectLeaf(b);
126
+ if (leafA === leafB) return true;
127
+ if (("u" + leafA === leafB || "u" + leafB === leafA) && Math.min(leafA.length, leafB.length) >= 4) {
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+
133
+ function matchesProjectScope(entryProject, targetProject, includeGlobal) {
134
+ const eProj = normalizeProjectScope(entryProject);
135
+ if (Array.isArray(targetProject)) {
136
+ if (targetProject.length === 0) return true;
137
+ if (includeGlobal !== false && eProj === "global") return true;
138
+ return targetProject.some(function (t) { return projectSlugsEquivalent(eProj, normalizeProjectScope(t)); });
139
+ }
140
+ const tProj = normalizeProjectScope(targetProject);
141
+ if (tProj === "all" || tProj === "global") {
142
+ if (includeGlobal === false && tProj === "global") return eProj === "global";
143
+ return true;
144
+ }
145
+ if (projectSlugsEquivalent(eProj, tProj)) return true;
146
+ if (includeGlobal !== false && eProj === "global") return true;
147
+ return false;
148
+ }
149
+
150
+ function detectProjectsFromText(text, entries) {
151
+ if (!text) return [];
152
+ const raw = String(text);
153
+ const norm = raw.replace(/\\/g, "/");
154
+ const detected = new Set();
155
+
156
+ const pathPatterns = [
157
+ /(?:^|[\s"'`(])(?:[a-z]:)?[^\s"'`)]*?\/(?:_clients|client-code-cms|client-code)\/([a-z0-9._-]+)/gi,
158
+ /(?:^|[\s"'`(])(?:[a-z]:)?[^\s"'`)]*?\/git\/(?:hannon-hill|opencode-plugins)\/([a-z0-9._-]+)/gi,
159
+ /(?:^|[\s"'`(])(?:[a-z]:)?[^\s"'`)]*?\/git\/([a-z0-9._-]+)/gi,
160
+ /\b(?:cms|git)\/([a-z0-9._-]+)\b/gi
161
+ ];
162
+
163
+ for (const re of pathPatterns) {
164
+ let m;
165
+ while ((m = re.exec(norm)) !== null) {
166
+ const slug = slugifyScopePart(m[1]);
167
+ if (slug && !UMBRELLA_DIRS.has(slug)) {
168
+ detected.add(slug);
169
+ }
170
+ }
171
+ }
172
+
173
+ const tokens = new Set(tokenizeText(raw));
174
+ if (Array.isArray(entries)) {
175
+ const knownProjects = new Set();
176
+ for (const e of entries) {
177
+ if (e.project && e.project !== "global") {
178
+ knownProjects.add(getProjectLeaf(e.project));
179
+ }
180
+ }
181
+ for (const proj of knownProjects) {
182
+ if (tokens.has(proj)) {
183
+ detected.add(proj);
184
+ } else if (proj.length >= 4 && tokens.has("u" + proj)) {
185
+ detected.add(proj);
186
+ } else if (proj.startsWith("u") && proj.length >= 5 && tokens.has(proj.slice(1))) {
187
+ detected.add(proj);
188
+ }
189
+ }
190
+ }
191
+
192
+ return Array.from(detected);
193
+ }
22
194
 
23
195
  function resolveMemoryDir(customDir) {
24
196
  if (customDir) {
@@ -47,12 +219,108 @@ function resolveConfigDir(customConfigDir) {
47
219
  }
48
220
  return path.resolve(customConfigDir);
49
221
  }
222
+ if (process.env.OPENCODE_CONFIG_DIR) {
223
+ return path.resolve(process.env.OPENCODE_CONFIG_DIR);
224
+ }
50
225
  const configBase = process.env.XDG_CONFIG_HOME
51
226
  ? path.resolve(process.env.XDG_CONFIG_HOME)
52
227
  : path.join(os.homedir(), ".config");
53
228
  return path.join(configBase, cliName);
54
229
  }
55
230
 
231
+ function findPluginsArraySpan(raw) {
232
+ const keyRe = /"plugins"\s*:\s*\[/g;
233
+ const match = keyRe.exec(raw);
234
+ if (!match) return null;
235
+ const openBracketIdx = match.index + match[0].length - 1;
236
+ let depth = 0;
237
+ let inString = false;
238
+ let escaped = false;
239
+ for (let i = openBracketIdx; i < raw.length; i++) {
240
+ const ch = raw[i];
241
+ if (inString) {
242
+ if (escaped) {
243
+ escaped = false;
244
+ } else if (ch === "\\") {
245
+ escaped = true;
246
+ } else if (ch === '"') {
247
+ inString = false;
248
+ }
249
+ continue;
250
+ }
251
+ if (ch === "/" && raw[i + 1] === "/") {
252
+ const nl = raw.indexOf("\n", i + 2);
253
+ if (nl === -1) break;
254
+ i = nl;
255
+ continue;
256
+ }
257
+ if (ch === "/" && raw[i + 1] === "*") {
258
+ const endComment = raw.indexOf("*/", i + 2);
259
+ if (endComment === -1) break;
260
+ i = endComment + 1;
261
+ continue;
262
+ }
263
+ if (ch === '"') {
264
+ inString = true;
265
+ continue;
266
+ }
267
+ if (ch === "[") depth++;
268
+ else if (ch === "]") {
269
+ depth--;
270
+ if (depth === 0) {
271
+ return {
272
+ start: match.index,
273
+ openEnd: openBracketIdx + 1,
274
+ closeStart: i,
275
+ end: i + 1
276
+ };
277
+ }
278
+ }
279
+ }
280
+ return null;
281
+ }
282
+
283
+ function findLastCodeCharIndex(str) {
284
+ let lastIdx = -1;
285
+ let inString = false;
286
+ let escaped = false;
287
+ for (let i = 0; i < str.length; i++) {
288
+ const ch = str[i];
289
+ if (inString) {
290
+ lastIdx = i;
291
+ if (escaped) {
292
+ escaped = false;
293
+ } else if (ch === "\\") {
294
+ escaped = true;
295
+ } else if (ch === '"') {
296
+ inString = false;
297
+ }
298
+ continue;
299
+ }
300
+ if (ch === "/" && str[i + 1] === "/") {
301
+ const nl = str.indexOf("\n", i + 2);
302
+ if (nl === -1) break;
303
+ i = nl;
304
+ continue;
305
+ }
306
+ if (ch === "/" && str[i + 1] === "*") {
307
+ const endComment = str.indexOf("*/", i + 2);
308
+ if (endComment === -1) break;
309
+ i = endComment + 1;
310
+ continue;
311
+ }
312
+ if (ch === '"') {
313
+ inString = true;
314
+ lastIdx = i;
315
+ continue;
316
+ }
317
+ if (!/\s/.test(ch)) {
318
+ lastIdx = i;
319
+ }
320
+ }
321
+ return lastIdx;
322
+ }
323
+
56
324
  function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
57
325
  if (!fs.existsSync(filePath)) {
58
326
  const content = [
@@ -73,28 +341,39 @@ function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
73
341
  return "already-present";
74
342
  }
75
343
 
76
- const pluginsArrRe = /("plugins"\s*:\s*\[)([\s\S]*?)(\])/;
77
- const match = raw.match(pluginsArrRe);
78
- if (match) {
79
- const inner = match[2].trim();
80
- const updated = raw.replace(pluginsArrRe, function (_, open, body, close) {
81
- if (!inner) {
82
- return open + "\n " + pluginEntryStr + "\n " + close;
83
- }
84
- const trimmedBody = body.replace(/\s*$/, "");
85
- const needsComma = !trimmedBody.endsWith(",");
86
- return open + trimmedBody + (needsComma ? "," : "") + "\n " + pluginEntryStr + "\n " + close;
87
- });
344
+ const span = findPluginsArraySpan(raw);
345
+ if (span) {
346
+ const open = raw.slice(span.start, span.openEnd);
347
+ const body = raw.slice(span.openEnd, span.closeStart);
348
+ const close = raw.slice(span.closeStart, span.end);
349
+ const lastCodeIdx = findLastCodeCharIndex(body);
350
+ let replacement;
351
+ if (lastCodeIdx === -1) {
352
+ replacement = open + "\n " + pluginEntryStr + "\n " + close;
353
+ } else {
354
+ const needsComma = body[lastCodeIdx] !== ",";
355
+ const withComma = needsComma
356
+ ? body.slice(0, lastCodeIdx + 1) + "," + body.slice(lastCodeIdx + 1)
357
+ : body;
358
+ const trimmedBody = withComma.replace(/\s*$/, "");
359
+ replacement = open + trimmedBody + "\n " + pluginEntryStr + "\n " + close;
360
+ }
361
+ const updated = raw.slice(0, span.start) + replacement + raw.slice(span.end);
88
362
  fs.writeFileSync(filePath, updated, "utf8");
89
363
  return "updated";
90
364
  }
91
365
 
92
366
  const lastBrace = raw.lastIndexOf("}");
93
367
  if (lastBrace !== -1) {
94
- const before = raw.slice(0, lastBrace).replace(/\s*$/, "");
95
- const trimmedObj = before.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim();
96
- const needsComma = trimmedObj.length > 1 && !trimmedObj.endsWith("{") && !trimmedObj.endsWith(",");
97
- const updated = before + (needsComma ? "," : "") + '\n "plugins": [\n ' + pluginEntryStr + "\n ]\n}\n";
368
+ const beforeSlice = raw.slice(0, lastBrace);
369
+ const lastCodeIdx = findLastCodeCharIndex(beforeSlice);
370
+ const lastChar = lastCodeIdx !== -1 ? beforeSlice[lastCodeIdx] : "{";
371
+ const needsComma = lastChar !== "{" && lastChar !== ",";
372
+ const withComma = (needsComma && lastCodeIdx !== -1)
373
+ ? beforeSlice.slice(0, lastCodeIdx + 1) + "," + beforeSlice.slice(lastCodeIdx + 1)
374
+ : beforeSlice;
375
+ const before = withComma.replace(/\s*$/, "");
376
+ const updated = before + '\n "plugins": [\n ' + pluginEntryStr + "\n ]\n}\n";
98
377
  fs.writeFileSync(filePath, updated, "utf8");
99
378
  return "updated";
100
379
  }
@@ -119,14 +398,25 @@ async function installPlugin(options) {
119
398
  const cliConfigFile = path.join(configDir, "cli.json");
120
399
 
121
400
  const serverEntryStr = opts.directory
122
- ? JSON.stringify({ package: pkgName, options: { directory: opts.directory } })
401
+ ? JSON.stringify([pkgName, { directory: opts.directory }])
402
+ : JSON.stringify(pkgName);
403
+ const cliEntryStr = opts.directory
404
+ ? JSON.stringify([pkgName, { directory: opts.directory }])
123
405
  : JSON.stringify(pkgName);
124
- const cliEntryStr = JSON.stringify(pkgName);
125
406
 
126
407
  const serverStatus = addPluginToJsoncFile(serverConfigFile, "https://" + cliName + ".ai/config.json", serverEntryStr, matchKey);
127
408
  const cliStatus = addPluginToJsoncFile(cliConfigFile, "https://" + cliName + ".ai/v2/cli.json", cliEntryStr, matchKey);
128
409
 
129
410
  ensureMemoryLayout(rootDir);
411
+ const importResult = opts.importExisting
412
+ ? await importExistingMemory(rootDir, {
413
+ dbPath: opts.dbPath,
414
+ agentsFiles: opts.agentsFiles,
415
+ projectDir: opts.projectDir,
416
+ limit: opts.limit,
417
+ skipSync: true
418
+ })
419
+ : null;
130
420
  const syncResult = opts.skipSync ? { total: 0, embedded: 0, reused: 0, vecFile: path.join(rootDir, "vectors.json") } : await syncVectors(rootDir);
131
421
 
132
422
  return {
@@ -136,6 +426,7 @@ async function installPlugin(options) {
136
426
  cliConfigFile: cliConfigFile,
137
427
  cliStatus: cliStatus,
138
428
  memoryDir: rootDir,
429
+ importResult: importResult,
139
430
  syncResult: syncResult
140
431
  };
141
432
  }
@@ -201,10 +492,27 @@ async function getEmbedder() {
201
492
  pipelineFn = mod.pipeline;
202
493
  }
203
494
  return pipelineFn("feature-extraction", "Xenova/all-MiniLM-L6-v2");
204
- })();
495
+ })().catch(function (err) {
496
+ embedderPromise = null;
497
+ throw err;
498
+ });
205
499
  return embedderPromise;
206
500
  }
207
501
 
502
+ function runSubprocessCli(args) {
503
+ return new Promise(function (resolve, reject) {
504
+ const baseEnv = Object.assign({}, process.env, { OPENCODE_MEMORY_SUBPROCESS: "1" });
505
+ execFile("node", [__filename].concat(args), { env: baseEnv, windowsHide: true, timeout: 120000 }, function (err, stdout) {
506
+ if (!err) return resolve(String(stdout || ""));
507
+ const bunEnv = Object.assign({}, baseEnv, { BUN_BE_BUN: "1" });
508
+ execFile(process.execPath, [__filename].concat(args), { env: bunEnv, windowsHide: true, timeout: 120000 }, function (err2, stdout2) {
509
+ if (err2) return reject(err);
510
+ resolve(String(stdout2 || ""));
511
+ });
512
+ });
513
+ });
514
+ }
515
+
208
516
  async function embedText(text) {
209
517
  const key = String(text || "").trim().toLowerCase();
210
518
  if (queryVecCache.has(key)) {
@@ -212,7 +520,16 @@ async function embedText(text) {
212
520
  }
213
521
  const embed = await getEmbedder();
214
522
  const out = await embed(text, { pooling: "mean", normalize: true });
215
- const vec = Array.from(out.data);
523
+ const vec = Array.from(out.data, function (v) {
524
+ return Math.round(v * 1e6) / 1e6;
525
+ });
526
+ if (out && typeof out.dispose === "function") {
527
+ try {
528
+ out.dispose();
529
+ } catch {
530
+ // ignore dispose errors
531
+ }
532
+ }
216
533
  if (queryVecCache.size >= 128) {
217
534
  const firstKey = queryVecCache.keys().next().value;
218
535
  queryVecCache.delete(firstKey);
@@ -228,23 +545,50 @@ function parseTopicEntries(rootDir) {
228
545
  const entries = [];
229
546
 
230
547
  for (const file of files) {
231
- const text = fs.readFileSync(path.join(topicDir, file), "utf8").replace(/\r\n/g, "\n");
548
+ const fullPath = path.join(topicDir, file);
549
+ let stat;
550
+ try {
551
+ stat = fs.statSync(fullPath);
552
+ } catch {
553
+ continue;
554
+ }
555
+ const cached = parsedFileCache.get(fullPath);
556
+ if (cached && cached.mtimeMs === stat.mtimeMs) {
557
+ for (const item of cached.entries) {
558
+ entries.push(Object.assign({}, item));
559
+ }
560
+ continue;
561
+ }
562
+
563
+ const text = fs.readFileSync(fullPath, "utf8").replace(/\r\n/g, "\n");
232
564
  const blocks = text.split(/\n(?=- id: )/).filter(function (b) { return b.trim().startsWith("- id: "); });
565
+ const fileEntries = [];
233
566
  for (const block of blocks) {
234
567
  const idMatch = block.match(/- id:\s*(\S+)/);
235
568
  const dateMatch = block.match(/date:\s*(\S+)/);
236
569
  const tagsMatch = block.match(/tags:\s*\[([^\]]*)\]/);
570
+ const projectMatch = block.match(/^\s*project:\s*(.+)$/m);
571
+ const coreMatch = block.match(/^\s*core:\s*(true|false)\s*$/mi);
237
572
  const factMatch = block.match(/fact:\s*(.+)/);
238
573
  if (idMatch && factMatch) {
239
- entries.push({
574
+ const tagsStr = tagsMatch ? tagsMatch[1].trim() : "";
575
+ const hasCoreTag = /(?:^|,)\s*core\s*(?:,|$)/i.test(tagsStr);
576
+ const isCore = coreMatch ? coreMatch[1].toLowerCase() === "true" : hasCoreTag;
577
+ const proj = projectMatch ? normalizeProjectScope(projectMatch[1].trim()) : "global";
578
+ const entry = {
240
579
  id: idMatch[1].trim(),
241
580
  date: dateMatch ? dateMatch[1].trim() : "",
242
581
  file: "topics/" + file,
243
- tags: tagsMatch ? tagsMatch[1].trim() : "",
582
+ tags: tagsStr,
244
583
  fact: factMatch[1].trim()
245
- });
584
+ };
585
+ if (proj !== "global") entry.project = proj;
586
+ if (isCore) entry.core = true;
587
+ fileEntries.push(entry);
588
+ entries.push(Object.assign({}, entry));
246
589
  }
247
590
  }
591
+ parsedFileCache.set(fullPath, { mtimeMs: stat.mtimeMs, entries: fileEntries });
248
592
  }
249
593
  return entries;
250
594
  }
@@ -258,7 +602,22 @@ function parseSessionEntries(rootDir) {
258
602
  const entries = [];
259
603
 
260
604
  for (const file of files) {
261
- const raw = fs.readFileSync(path.join(sessionDir, file), "utf8").replace(/\r\n/g, "\n");
605
+ const fullPath = path.join(sessionDir, file);
606
+ let stat;
607
+ try {
608
+ stat = fs.statSync(fullPath);
609
+ } catch {
610
+ continue;
611
+ }
612
+ const cached = parsedFileCache.get(fullPath);
613
+ if (cached && cached.mtimeMs === stat.mtimeMs) {
614
+ for (const item of cached.entries) {
615
+ entries.push(Object.assign({}, item));
616
+ }
617
+ continue;
618
+ }
619
+
620
+ const raw = fs.readFileSync(fullPath, "utf8").replace(/\r\n/g, "\n");
262
621
  const base = file.replace(/\.md$/, "");
263
622
  const titleMatch = raw.match(/^#\s+(.+)$/m);
264
623
  const title = titleMatch ? titleMatch[1].trim() : base;
@@ -266,6 +625,8 @@ function parseSessionEntries(rootDir) {
266
625
  const date = dateMatch ? dateMatch[1] : "";
267
626
  const slug = dateMatch ? dateMatch[2] : base;
268
627
  const tags = slug.replace(/-\d+$/, "").split(/[-_]+/).filter(Boolean).join(", ");
628
+ const projMatch = raw.match(/^\*\*Project\*\*:\s*(.+)$/m);
629
+ const proj = projMatch ? normalizeProjectScope(projMatch[1].trim()) : "global";
269
630
 
270
631
  const sections = [];
271
632
  const targetHeadings = [
@@ -287,28 +648,195 @@ function parseSessionEntries(rootDir) {
287
648
  }
288
649
 
289
650
  const factText = title + " — " + (sections.join(" | ").slice(0, 700) || raw.replace(/\s+/g, " ").slice(0, 500));
290
- entries.push({
651
+ const entry = {
291
652
  id: "session:" + base,
292
653
  date: date,
293
654
  file: "sessions/" + file,
294
655
  tags: tags,
295
656
  fact: factText
296
- });
657
+ };
658
+ if (proj !== "global") entry.project = proj;
659
+ parsedFileCache.set(fullPath, { mtimeMs: stat.mtimeMs, entries: [entry] });
660
+ entries.push(Object.assign({}, entry));
297
661
  }
298
662
  return entries;
299
663
  }
300
664
 
301
- async function syncVectors(rootDir) {
665
+ function serializeEntryLine(e) {
666
+ if (e._jsonLine) return e._jsonLine;
667
+ const obj = {
668
+ id: e.id,
669
+ date: e.date,
670
+ file: e.file,
671
+ tags: e.tags,
672
+ fact: e.fact
673
+ };
674
+ if (e.project && e.project !== "global") obj.project = e.project;
675
+ if (e.core === true) obj.core = true;
676
+ obj.vector = e.vector;
677
+ e._jsonLine = " " + JSON.stringify(obj);
678
+ return e._jsonLine;
679
+ }
680
+
681
+ function serializeVectorsJson(entries) {
682
+ if (!entries || entries.length === 0) return "[]\n";
683
+ const lines = entries.map(serializeEntryLine);
684
+ return "[\n" + lines.join(",\n") + "\n]\n";
685
+ }
686
+
687
+ function writeVectorsAtomic(vecFile, content) {
688
+ const tmpFile = vecFile + ".tmp." + process.pid;
689
+ try {
690
+ fs.writeFileSync(tmpFile, content, "utf8");
691
+ fs.renameSync(tmpFile, vecFile);
692
+ } catch {
693
+ try {
694
+ if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile);
695
+ } catch {
696
+ // ignore cleanup error
697
+ }
698
+ fs.writeFileSync(vecFile, content, "utf8");
699
+ }
700
+ }
701
+
702
+ function prepareEntryCacheFields(item) {
703
+ if (!item) return;
704
+ if (!item._haystack) {
705
+ item._haystack = (
706
+ item.id + " " +
707
+ item.tags + " " +
708
+ item.fact + " " +
709
+ item.file +
710
+ (item.project ? " " + item.project : "")
711
+ ).toLowerCase();
712
+ }
713
+ if (!item._idTokens) {
714
+ item._idTokens = new Set(tokenizeText(item.id));
715
+ item._tagTokens = new Set(tokenizeText(item.tags));
716
+ item._fileTokens = new Set(tokenizeText(item.file));
717
+ const factToks = tokenizeText(item.fact);
718
+ const tf = new Map();
719
+ for (const t of factToks) {
720
+ tf.set(t, (tf.get(t) || 0) + 1);
721
+ }
722
+ item._factTf = tf;
723
+ item._docLen = factToks.length + item._tagTokens.size * 2 + item._idTokens.size;
724
+ const allToks = new Set(factToks);
725
+ for (const t of item._idTokens) allToks.add(t);
726
+ for (const t of item._tagTokens) allToks.add(t);
727
+ for (const t of item._fileTokens) allToks.add(t);
728
+ item._allTokens = allToks;
729
+ }
730
+ if (Array.isArray(item.vector) && !(item._vec instanceof Float32Array)) {
731
+ item._vec = new Float32Array(item.vector);
732
+ }
733
+ }
734
+
735
+ function buildCorpusStats(entries) {
736
+ const df = new Map();
737
+ let totalLen = 0;
738
+ const count = entries ? entries.length : 0;
739
+ if (!count) {
740
+ return { N: 0, avgDocLen: 1, df: df };
741
+ }
742
+ for (const entry of entries) {
743
+ prepareEntryCacheFields(entry);
744
+ totalLen += entry._docLen || 1;
745
+ if (entry._allTokens) {
746
+ for (const tok of entry._allTokens) {
747
+ df.set(tok, (df.get(tok) || 0) + 1);
748
+ }
749
+ }
750
+ }
751
+ return {
752
+ N: count,
753
+ avgDocLen: Math.max(1, totalLen / count),
754
+ df: df
755
+ };
756
+ }
757
+
758
+ function computeLexicalScore(entry, cleanQuery, queryTokens, stats) {
759
+ prepareEntryCacheFields(entry);
760
+ const lowerQ = cleanQuery.toLowerCase();
761
+ const idLower = String(entry.id || "").toLowerCase();
762
+
763
+ let exactBoost = 0;
764
+ if (lowerQ === idLower || entry._idTokens.has(lowerQ)) {
765
+ exactBoost += 0.55;
766
+ } else if (lowerQ.length >= 4 && entry._haystack.includes(lowerQ)) {
767
+ const escaped = lowerQ.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
768
+ const boundaryRe = new RegExp("(^|[^a-z0-9])" + escaped + "($|[^a-z0-9])");
769
+ exactBoost += boundaryRe.test(entry._haystack) ? 0.22 : 0.14;
770
+ }
771
+
772
+ if (!queryTokens.length) {
773
+ return Math.min(0.6, exactBoost);
774
+ }
775
+
776
+ const N = Math.max(1, stats ? stats.N : 1);
777
+ const avgDocLen = stats ? stats.avgDocLen : 20;
778
+ const dfMap = stats ? stats.df : null;
779
+ const k1 = 1.2;
780
+ const b = 0.75;
781
+ const docLen = entry._docLen || 10;
782
+
783
+ let bm25Raw = 0;
784
+ let maxPossible = 0;
785
+ let matchedTokens = 0;
786
+
787
+ for (const qTok of queryTokens) {
788
+ const df = dfMap ? (dfMap.get(qTok) || 0) : 0;
789
+ const idf = Math.log(1 + (N - df + 0.5) / (df + 0.5));
790
+ const maxIdf = Math.log(1 + (N + 0.5) / 0.5);
791
+ maxPossible += Math.max(0.5, idf) * (k1 + 1);
792
+
793
+ let weightedTf = 0;
794
+ if (entry._idTokens.has(qTok)) weightedTf += 3.0;
795
+ if (entry._tagTokens.has(qTok)) weightedTf += 2.2;
796
+ if (entry._fileTokens.has(qTok)) weightedTf += 1.2;
797
+ if (entry._factTf.has(qTok)) weightedTf += entry._factTf.get(qTok);
798
+
799
+ if (weightedTf === 0 && qTok.length >= 4 && entry._allTokens) {
800
+ for (const cand of entry._allTokens) {
801
+ if (cand.startsWith(qTok) || (qTok.length >= 5 && cand.includes(qTok))) {
802
+ weightedTf += 0.55;
803
+ break;
804
+ }
805
+ }
806
+ }
807
+
808
+ if (weightedTf > 0) {
809
+ matchedTokens++;
810
+ const effectiveIdf = df > 0 ? idf : maxIdf * 0.85;
811
+ const tfNorm = (weightedTf * (k1 + 1)) / (weightedTf + k1 * (1 - b + b * (docLen / avgDocLen)));
812
+ bm25Raw += effectiveIdf * tfNorm;
813
+ }
814
+ }
815
+
816
+ if (matchedTokens === 0 && exactBoost === 0) return 0;
817
+
818
+ const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
819
+ const normalizedBm25 = maxPossible > 0 ? Math.min(1, bm25Raw / maxPossible) : 0;
820
+ const combined = normalizedBm25 * 0.28 + coverage * 0.12 + exactBoost;
821
+ return Math.min(exactBoost >= 0.5 ? 0.85 : 0.65, combined);
822
+ }
823
+
824
+ async function runSyncVectors(rootDir) {
302
825
  ensureMemoryLayout(rootDir);
303
826
  const vecFile = path.join(rootDir, "vectors.json");
304
827
  const existingMap = new Map();
828
+ let prevCount = 0;
305
829
 
306
830
  if (fs.existsSync(vecFile)) {
307
831
  try {
308
832
  const prev = JSON.parse(fs.readFileSync(vecFile, "utf8"));
833
+ prevCount = Array.isArray(prev) ? prev.length : 0;
309
834
  for (const item of prev) {
310
835
  if (item && item.id && Array.isArray(item.vector)) {
311
- existingMap.set(item.id, item);
836
+ existingMap.set(item.id + "::" + (item.fact || ""), item);
837
+ if (!existingMap.has(item.id)) {
838
+ existingMap.set(item.id, item);
839
+ }
312
840
  }
313
841
  }
314
842
  } catch {
@@ -319,27 +847,41 @@ async function syncVectors(rootDir) {
319
847
  const parsed = parseTopicEntries(rootDir).concat(parseSessionEntries(rootDir));
320
848
  let embeddedCount = 0;
321
849
  let reusedCount = 0;
850
+ let metadataChanged = false;
322
851
 
323
852
  for (const entry of parsed) {
324
- const prev = existingMap.get(entry.id);
853
+ const prev = existingMap.get(entry.id + "::" + (entry.fact || "")) || existingMap.get(entry.id);
325
854
  if (prev && prev.fact === entry.fact && prev.tags === entry.tags && Array.isArray(prev.vector)) {
326
855
  entry.vector = prev.vector;
327
856
  reusedCount++;
857
+ if ((prev.project || "global") !== (entry.project || "global") || Boolean(prev.core) !== Boolean(entry.core)) {
858
+ metadataChanged = true;
859
+ } else if (prev._jsonLine) {
860
+ entry._jsonLine = prev._jsonLine;
861
+ }
328
862
  } else {
329
- entry.vector = await embedText(entry.fact + " " + entry.tags);
330
- embeddedCount++;
863
+ try {
864
+ entry.vector = await embedText(entry.fact + " " + entry.tags);
865
+ embeddedCount++;
866
+ } catch (embedErr) {
867
+ if (process.env.OPENCODE_MEMORY_SUBPROCESS === "1") throw embedErr;
868
+ await runSubprocessCli(["sync", "--dir", rootDir]);
869
+ cachedMtime = 0;
870
+ const reloaded = loadCachedVectors(rootDir) || [];
871
+ return { total: reloaded.length, embedded: parsed.length - reusedCount, reused: reusedCount, vecFile: vecFile };
872
+ }
331
873
  }
874
+ prepareEntryCacheFields(entry);
875
+ serializeEntryLine(entry);
332
876
  }
333
877
 
334
- const changed = embeddedCount > 0 || parsed.length !== existingMap.size;
878
+ const changed = embeddedCount > 0 || metadataChanged || parsed.length !== prevCount;
335
879
  if (changed || !fs.existsSync(vecFile)) {
336
- fs.writeFileSync(vecFile, JSON.stringify(parsed, null, 1), "utf8");
880
+ writeVectorsAtomic(vecFile, serializeVectorsJson(parsed));
337
881
  }
338
882
 
339
- for (const item of parsed) {
340
- item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
341
- }
342
883
  cachedEntries = parsed;
884
+ cachedCorpusStats = buildCorpusStats(parsed);
343
885
  cachedRootDir = path.resolve(rootDir);
344
886
  cachedMtime = fs.existsSync(vecFile) ? fs.statSync(vecFile).mtimeMs : Date.now();
345
887
  cachedVersion++;
@@ -348,27 +890,77 @@ async function syncVectors(rootDir) {
348
890
  return { total: parsed.length, embedded: embeddedCount, reused: reusedCount, vecFile: vecFile };
349
891
  }
350
892
 
893
+ async function syncVectors(rootDir) {
894
+ if (activeSyncPromise) {
895
+ try {
896
+ await activeSyncPromise;
897
+ } catch {
898
+ // Proceed with fresh sync
899
+ }
900
+ }
901
+ const p = runSyncVectors(rootDir);
902
+ activeSyncPromise = p;
903
+ try {
904
+ return await p;
905
+ } finally {
906
+ if (activeSyncPromise === p) {
907
+ activeSyncPromise = null;
908
+ }
909
+ }
910
+ }
911
+
351
912
  function loadCachedVectors(rootDir) {
352
913
  const resolved = path.resolve(rootDir);
353
914
  const vecFile = path.join(resolved, "vectors.json");
354
- if (!fs.existsSync(vecFile)) return [];
355
- const stat = fs.statSync(vecFile);
915
+ let stat;
916
+ try {
917
+ stat = fs.statSync(vecFile);
918
+ } catch {
919
+ return [];
920
+ }
356
921
  if (cachedEntries && cachedRootDir === resolved && cachedMtime === stat.mtimeMs) {
357
922
  return cachedEntries;
358
923
  }
359
924
  const parsed = JSON.parse(fs.readFileSync(vecFile, "utf8"));
360
925
  for (const item of parsed) {
361
- if (item && !item._haystack) {
362
- item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
363
- }
926
+ prepareEntryCacheFields(item);
927
+ serializeEntryLine(item);
364
928
  }
365
929
  cachedEntries = parsed;
930
+ cachedCorpusStats = buildCorpusStats(parsed);
366
931
  cachedRootDir = resolved;
367
932
  cachedMtime = stat.mtimeMs;
368
933
  cachedVersion++;
369
934
  return cachedEntries;
370
935
  }
371
936
 
937
+ function getCoreMemories(rootDir, project, queryText) {
938
+ const entries = loadCachedVectors(rootDir);
939
+ const rawProj = String(project || "").trim();
940
+ let targetFilter = "global";
941
+ let includeGlobal = true;
942
+
943
+ if (rawProj && rawProj.toLowerCase() === "all") {
944
+ targetFilter = "all";
945
+ } else if (isUmbrellaProject(rawProj)) {
946
+ const detected = queryText ? detectProjectsFromText(queryText, entries) : [];
947
+ if (detected.length > 0) {
948
+ targetFilter = detected;
949
+ } else {
950
+ targetFilter = "global";
951
+ includeGlobal = false;
952
+ }
953
+ } else {
954
+ targetFilter = normalizeProjectScope(rawProj);
955
+ }
956
+
957
+ return entries.filter(function (e) {
958
+ const isCore = e.core === true || /(?:^|,)\s*core\s*(?:,|$)/i.test(e.tags || "");
959
+ if (!isCore) return false;
960
+ return matchesProjectScope(e.project, targetFilter, includeGlobal);
961
+ });
962
+ }
963
+
372
964
  function getTopicSlugs(rootDir) {
373
965
  const resolved = path.resolve(rootDir);
374
966
  if (cachedTopicSlugs && cachedTopicsRootDir === resolved) return cachedTopicSlugs;
@@ -389,50 +981,80 @@ function dotProduct(a, b) {
389
981
  return sum;
390
982
  }
391
983
 
392
- async function searchMemory(rootDir, query, mode, topN) {
984
+ async function searchMemory(rootDir, query, mode, topN, options) {
393
985
  const cleanQuery = String(query || "").trim();
394
986
  if (!cleanQuery) return [];
395
987
  const limit = Number(topN) || 8;
396
988
  const searchMode = mode || "hybrid";
989
+ const opts = options || {};
990
+ const rawProject = String(opts.project || "").trim();
991
+ const includeGlobal = opts.includeGlobal !== false;
397
992
 
398
993
  let entries = loadCachedVectors(rootDir);
399
994
  if (entries.length === 0) {
400
995
  await syncVectors(rootDir);
401
996
  entries = loadCachedVectors(rootDir);
402
997
  }
998
+ const stats = cachedCorpusStats || buildCorpusStats(entries);
999
+
1000
+ let effectiveFilter = null;
1001
+ let boostTargets = [];
1002
+ if (!rawProject || rawProject.toLowerCase() === "all") {
1003
+ effectiveFilter = null;
1004
+ boostTargets = detectProjectsFromText(cleanQuery, entries);
1005
+ } else if (rawProject.toLowerCase() === "global" && !includeGlobal) {
1006
+ effectiveFilter = "global";
1007
+ } else if (isUmbrellaProject(rawProject)) {
1008
+ const detected = detectProjectsFromText(cleanQuery, entries);
1009
+ if (detected.length > 0) {
1010
+ effectiveFilter = detected;
1011
+ boostTargets = detected;
1012
+ } else {
1013
+ effectiveFilter = null;
1014
+ }
1015
+ } else {
1016
+ const normProj = normalizeProjectScope(rawProject);
1017
+ effectiveFilter = normProj;
1018
+ boostTargets = [normProj];
1019
+ }
403
1020
 
404
- const results = [];
405
- const words = cleanQuery.toLowerCase().split(/\s+/).filter(function (w) { return w.length >= 2; });
1021
+ const rawTokens = tokenizeText(cleanQuery);
1022
+ const nonStopTokens = rawTokens.filter(function (t) { return !STOPWORDS.has(t); });
1023
+ const queryTokens = nonStopTokens.length > 0 ? nonStopTokens : rawTokens;
406
1024
 
407
1025
  let queryVec = null;
408
1026
  if (searchMode === "semantic" || searchMode === "hybrid") {
409
- queryVec = await embedText(cleanQuery);
1027
+ const rawQueryVec = await embedText(cleanQuery);
1028
+ queryVec = rawQueryVec instanceof Float32Array ? rawQueryVec : new Float32Array(rawQueryVec);
410
1029
  }
411
1030
 
1031
+ const results = [];
412
1032
  for (const entry of entries) {
1033
+ if (opts.coreOnly && !entry.core) {
1034
+ continue;
1035
+ }
1036
+ if (effectiveFilter && !matchesProjectScope(entry.project, effectiveFilter, includeGlobal)) {
1037
+ continue;
1038
+ }
1039
+
413
1040
  let semanticScore = 0;
414
- if (queryVec && Array.isArray(entry.vector)) {
415
- semanticScore = dotProduct(queryVec, entry.vector);
416
- }
417
-
418
- let lexicalScore = 0;
419
- const haystack = entry._haystack || (entry._haystack = (entry.id + " " + entry.tags + " " + entry.fact + " " + entry.file).toLowerCase());
420
- if (haystack.includes(cleanQuery.toLowerCase())) {
421
- lexicalScore = 0.35;
422
- } else if (words.length > 0) {
423
- let matched = 0;
424
- for (const w of words) {
425
- if (haystack.includes(w)) matched++;
426
- }
427
- lexicalScore = (matched / words.length) * 0.25;
1041
+ if (queryVec && (entry._vec || Array.isArray(entry.vector))) {
1042
+ semanticScore = dotProduct(queryVec, entry._vec || entry.vector);
428
1043
  }
429
1044
 
1045
+ const lexicalScore = computeLexicalScore(entry, cleanQuery, queryTokens, stats);
1046
+ const entryProj = normalizeProjectScope(entry.project);
1047
+ const isBoostedProject = entryProj !== "global" && boostTargets.some(function (t) {
1048
+ return projectSlugsEquivalent(entryProj, normalizeProjectScope(t));
1049
+ });
1050
+ const projectBoost = isBoostedProject ? 0.08 : 0;
1051
+
430
1052
  const score = searchMode === "grep"
431
1053
  ? lexicalScore
432
- : (searchMode === "semantic" ? semanticScore : semanticScore + lexicalScore);
1054
+ : (searchMode === "semantic" ? semanticScore + projectBoost : semanticScore + lexicalScore + projectBoost);
433
1055
 
434
1056
  if (searchMode === "grep" && lexicalScore === 0) continue;
435
- results.push({ score: score, semanticScore: semanticScore, entry: entry });
1057
+ results.push({ score: score, semanticScore: semanticScore, lexicalScore: lexicalScore, entry: entry });
436
1058
  }
437
1059
 
438
1060
  results.sort(function (a, b) { return b.score - a.score; });
@@ -440,26 +1062,187 @@ async function searchMemory(rootDir, query, mode, topN) {
440
1062
  }
441
1063
 
442
1064
  function nextTopicId(topicText, topicSlug) {
1065
+ const normalized = String(topicText || "").replace(/\r\n/g, "\n");
443
1066
  const re = /- id:\s*([a-z0-9-]+?)-(\d+)\s*$/gm;
1067
+ const existingIds = new Set();
444
1068
  let maxNum = 0;
445
1069
  let detectedPrefix = topicSlug;
446
1070
  let m;
447
- while ((m = re.exec(topicText)) !== null) {
1071
+ while ((m = re.exec(normalized)) !== null) {
1072
+ existingIds.add(m[1] + "-" + m[2]);
448
1073
  const n = parseInt(m[2], 10);
449
1074
  if (n > maxNum) {
450
1075
  maxNum = n;
451
1076
  detectedPrefix = m[1];
452
1077
  }
453
1078
  }
454
- return detectedPrefix + "-" + String(maxNum + 1).padStart(3, "0");
1079
+ let nextNum = maxNum + 1;
1080
+ let candidate = detectedPrefix + "-" + String(nextNum).padStart(3, "0");
1081
+ while (existingIds.has(candidate)) {
1082
+ nextNum++;
1083
+ candidate = detectedPrefix + "-" + String(nextNum).padStart(3, "0");
1084
+ }
1085
+ return candidate;
1086
+ }
1087
+
1088
+ function removeTopicBlockFromFile(filePath, targetId) {
1089
+ if (!fs.existsSync(filePath)) return null;
1090
+ const raw = fs.readFileSync(filePath, "utf8").replace(/\r\n/g, "\n");
1091
+ const lines = raw.split("\n");
1092
+ const out = [];
1093
+ let removedBlock = null;
1094
+ let i = 0;
1095
+
1096
+ while (i < lines.length) {
1097
+ const m = lines[i].match(/^- id:\s*(\S+)\s*$/);
1098
+ if (m && m[1].trim() === targetId) {
1099
+ const blockLines = [lines[i]];
1100
+ i++;
1101
+ while (i < lines.length && (/^\s+[a-zA-Z0-9_-]+:/.test(lines[i]) || lines[i].trim() === "")) {
1102
+ if (lines[i].trim() === "" && i + 1 < lines.length && !/^\s+[a-zA-Z0-9_-]+:/.test(lines[i + 1])) {
1103
+ i++;
1104
+ break;
1105
+ }
1106
+ blockLines.push(lines[i]);
1107
+ i++;
1108
+ }
1109
+ removedBlock = blockLines.join("\n").trim();
1110
+ continue;
1111
+ }
1112
+ out.push(lines[i]);
1113
+ i++;
1114
+ }
1115
+
1116
+ if (removedBlock !== null) {
1117
+ const cleaned = out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
1118
+ fs.writeFileSync(filePath, cleaned, "utf8");
1119
+ parsedFileCache.delete(filePath);
1120
+ }
1121
+ return removedBlock;
1122
+ }
1123
+
1124
+ async function deleteMemoryEntry(rootDir, idInput) {
1125
+ if (activeSyncPromise) {
1126
+ try {
1127
+ await activeSyncPromise;
1128
+ } catch {
1129
+ // Ignore background sync error
1130
+ }
1131
+ }
1132
+ const rawIds = Array.isArray(idInput)
1133
+ ? idInput
1134
+ : String(idInput || "").split(",");
1135
+ const targetIds = rawIds
1136
+ .map(function (s) { return String(s || "").replace(/[\[\]]+/g, "").trim(); })
1137
+ .filter(Boolean);
1138
+
1139
+ if (targetIds.length === 0) {
1140
+ return { deleted: [], notFound: [], total: loadCachedVectors(rootDir).length };
1141
+ }
1142
+
1143
+ const topicDir = path.join(rootDir, "topics");
1144
+ const sessionDir = path.join(rootDir, "sessions");
1145
+ const prevEntries = loadCachedVectors(rootDir);
1146
+ const deleted = [];
1147
+ const notFound = [];
1148
+ const removedSet = new Set();
1149
+
1150
+ for (const targetId of targetIds) {
1151
+ let foundFile = "";
1152
+ if (fs.existsSync(topicDir)) {
1153
+ const files = fs.readdirSync(topicDir).filter(function (f) { return f.endsWith(".md"); });
1154
+ for (const file of files) {
1155
+ const fullPath = path.join(topicDir, file);
1156
+ const removed = removeTopicBlockFromFile(fullPath, targetId);
1157
+ if (removed !== null) {
1158
+ foundFile = "topics/" + file;
1159
+ break;
1160
+ }
1161
+ }
1162
+ }
1163
+ if (!foundFile && targetId.startsWith("session:") && fs.existsSync(sessionDir)) {
1164
+ const base = targetId.slice("session:".length) + ".md";
1165
+ const fullPath = path.join(sessionDir, base);
1166
+ if (fs.existsSync(fullPath)) {
1167
+ fs.unlinkSync(fullPath);
1168
+ parsedFileCache.delete(fullPath);
1169
+ foundFile = "sessions/" + base;
1170
+ }
1171
+ }
1172
+ const matchedEntry = prevEntries.find(function (e) { return e.id === targetId; });
1173
+ if (foundFile || matchedEntry) {
1174
+ removedSet.add(targetId);
1175
+ deleted.push({
1176
+ id: targetId,
1177
+ file: foundFile || (matchedEntry ? matchedEntry.file : "")
1178
+ });
1179
+ } else {
1180
+ notFound.push(targetId);
1181
+ }
1182
+ }
1183
+
1184
+ const vecFile = path.join(rootDir, "vectors.json");
1185
+ const nextEntries = prevEntries.filter(function (e) { return !removedSet.has(e.id); });
1186
+
1187
+ if (removedSet.size > 0 && (nextEntries.length !== prevEntries.length || fs.existsSync(vecFile))) {
1188
+ writeVectorsAtomic(vecFile, serializeVectorsJson(nextEntries));
1189
+ }
1190
+ cachedEntries = nextEntries;
1191
+ cachedCorpusStats = buildCorpusStats(nextEntries);
1192
+ cachedRootDir = path.resolve(rootDir);
1193
+ cachedMtime = fs.existsSync(vecFile) ? fs.statSync(vecFile).mtimeMs : Date.now();
1194
+ cachedVersion++;
1195
+
1196
+ return {
1197
+ deleted: deleted,
1198
+ notFound: notFound,
1199
+ total: nextEntries.length
1200
+ };
455
1201
  }
456
1202
 
457
1203
  async function storeMemoryFact(rootDir, input) {
1204
+ if (activeSyncPromise) {
1205
+ try {
1206
+ await activeSyncPromise;
1207
+ } catch {
1208
+ // Ignore background sync error
1209
+ }
1210
+ }
458
1211
  ensureMemoryLayout(rootDir);
459
1212
  const rawTopic = String(input.topic || "decisions").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
460
- const topicFile = path.join(rootDir, "topics", rawTopic + ".md");
1213
+ const topicDir = path.join(rootDir, "topics");
1214
+ const topicFile = path.join(topicDir, rawTopic + ".md");
461
1215
  const indexFile = path.join(rootDir, "memory.md");
462
1216
 
1217
+ const rawId = input.id
1218
+ ? String(input.id).replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "")
1219
+ : "";
1220
+ const supersedesList = input.supersedes
1221
+ ? (Array.isArray(input.supersedes) ? input.supersedes : String(input.supersedes).split(","))
1222
+ .map(function (s) { return String(s || "").replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); })
1223
+ .filter(Boolean)
1224
+ : [];
1225
+
1226
+ let wasUpdated = false;
1227
+ const supersededIds = [];
1228
+ const idsToRemove = new Set([rawId].concat(supersedesList).filter(Boolean));
1229
+ if (idsToRemove.size > 0 && fs.existsSync(topicDir)) {
1230
+ const files = fs.readdirSync(topicDir).filter(function (f) { return f.endsWith(".md"); });
1231
+ for (const file of files) {
1232
+ const fullPath = path.join(topicDir, file);
1233
+ for (const targetId of idsToRemove) {
1234
+ const removed = removeTopicBlockFromFile(fullPath, targetId);
1235
+ if (removed !== null) {
1236
+ if (targetId === rawId) {
1237
+ wasUpdated = true;
1238
+ } else if (!supersededIds.includes(targetId)) {
1239
+ supersededIds.push(targetId);
1240
+ }
1241
+ }
1242
+ }
1243
+ }
1244
+ }
1245
+
463
1246
  let existingText = "";
464
1247
  if (fs.existsSync(topicFile)) {
465
1248
  existingText = fs.readFileSync(topicFile, "utf8");
@@ -475,27 +1258,39 @@ async function storeMemoryFact(rootDir, input) {
475
1258
  }
476
1259
  }
477
1260
 
478
- const id = input.id ? String(input.id).trim() : nextTopicId(existingText, rawTopic);
1261
+ const id = rawId || nextTopicId(existingText, rawTopic);
479
1262
  const today = new Date().toISOString().split("T")[0];
480
- const tagsList = Array.isArray(input.tags)
1263
+ const rawTags = Array.isArray(input.tags)
481
1264
  ? input.tags.map(function (t) { return String(t).trim(); }).filter(Boolean).join(", ")
482
1265
  : String(input.tags || rawTopic).trim();
1266
+ const tagsList = rawTags.replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, " ").trim() || rawTopic;
483
1267
  const cleanFact = String(input.fact || "").replace(/\s+/g, " ").trim();
1268
+ const projectScope = normalizeProjectScope(input.project);
1269
+ const isCore = input.core === true || /(?:^|,)\s*core\s*(?:,|$)/i.test(tagsList);
484
1270
 
485
- const block = [
1271
+ const blockLines = [
486
1272
  "",
487
1273
  "- id: " + id,
488
1274
  " date: " + today,
489
- " tags: [" + tagsList + "]",
490
- " fact: " + cleanFact,
491
- ""
492
- ].join("\n");
1275
+ " tags: [" + tagsList + "]"
1276
+ ];
1277
+ if (projectScope !== "global") {
1278
+ blockLines.push(" project: " + projectScope);
1279
+ }
1280
+ if (isCore) {
1281
+ blockLines.push(" core: true");
1282
+ }
1283
+ blockLines.push(" fact: " + cleanFact, "");
493
1284
 
494
- fs.writeFileSync(topicFile, existingText.trimEnd() + "\n" + block, "utf8");
1285
+ fs.writeFileSync(topicFile, existingText.trimEnd() + "\n" + blockLines.join("\n"), "utf8");
1286
+ parsedFileCache.delete(topicFile);
495
1287
 
496
1288
  const vec = await embedText(cleanFact + " " + tagsList);
497
1289
  const vecFile = path.join(rootDir, "vectors.json");
498
- const entries = loadCachedVectors(rootDir).filter(function (e) { return e.id !== id; });
1290
+ const removeVecIds = new Set([id].concat(supersedesList));
1291
+ const entries = loadCachedVectors(rootDir).filter(function (e) {
1292
+ return !removeVecIds.has(e.id);
1293
+ });
499
1294
  const newEntry = {
500
1295
  id: id,
501
1296
  date: today,
@@ -504,20 +1299,26 @@ async function storeMemoryFact(rootDir, input) {
504
1299
  fact: cleanFact,
505
1300
  vector: vec
506
1301
  };
1302
+ if (projectScope !== "global") newEntry.project = projectScope;
1303
+ if (isCore) newEntry.core = true;
1304
+ prepareEntryCacheFields(newEntry);
1305
+ serializeEntryLine(newEntry);
507
1306
  entries.push(newEntry);
508
- const serializable = entries.map(function (e) {
509
- return { id: e.id, date: e.date, file: e.file, tags: e.tags, fact: e.fact, vector: e.vector };
510
- });
511
- fs.writeFileSync(vecFile, JSON.stringify(serializable, null, 1), "utf8");
512
- newEntry._haystack = (newEntry.id + " " + newEntry.tags + " " + newEntry.fact + " " + newEntry.file).toLowerCase();
1307
+ writeVectorsAtomic(vecFile, serializeVectorsJson(entries));
513
1308
  cachedEntries = entries;
1309
+ cachedCorpusStats = buildCorpusStats(entries);
514
1310
  cachedRootDir = path.resolve(rootDir);
515
1311
  cachedMtime = fs.statSync(vecFile).mtimeMs;
516
1312
  cachedVersion++;
517
1313
  cachedTopicSlugs = null;
518
1314
  cachedTopicsRootDir = "";
519
1315
 
520
- return newEntry;
1316
+ return Object.assign({}, newEntry, {
1317
+ project: projectScope,
1318
+ core: isCore,
1319
+ updated: wasUpdated,
1320
+ superseded: supersededIds
1321
+ });
521
1322
  }
522
1323
 
523
1324
  async function storeSessionCheckpoint(rootDir, input) {
@@ -564,6 +1365,603 @@ async function storeSessionCheckpoint(rootDir, input) {
564
1365
  return { filename: filename, filepath: filepath, checkpoint: numStr };
565
1366
  }
566
1367
 
1368
+ function resolveDbPath(customPath) {
1369
+ if (customPath) {
1370
+ const resolved = customPath.startsWith("~")
1371
+ ? path.join(os.homedir(), customPath.slice(1))
1372
+ : path.resolve(customPath);
1373
+ if (fs.existsSync(resolved)) return resolved;
1374
+ }
1375
+ if (process.env.OPENCODE_DB_PATH && fs.existsSync(process.env.OPENCODE_DB_PATH)) {
1376
+ return path.resolve(process.env.OPENCODE_DB_PATH);
1377
+ }
1378
+ const home = os.homedir();
1379
+ const candidates = [];
1380
+ if (process.env.XDG_DATA_HOME) {
1381
+ candidates.push(path.join(process.env.XDG_DATA_HOME, cliName, cliName + ".db"));
1382
+ }
1383
+ candidates.push(path.join(home, ".local", "share", cliName, cliName + ".db"));
1384
+ if (process.env.LOCALAPPDATA) {
1385
+ candidates.push(path.join(process.env.LOCALAPPDATA, cliName, cliName + ".db"));
1386
+ }
1387
+ for (const cand of candidates) {
1388
+ if (fs.existsSync(cand)) return cand;
1389
+ }
1390
+ return candidates[0];
1391
+ }
1392
+
1393
+ async function openReadOnlySqlite(dbPath) {
1394
+ const isBun = typeof globalThis.Bun !== "undefined";
1395
+ async function openBun() {
1396
+ const mod = await import("bun:sqlite");
1397
+ let db;
1398
+ try {
1399
+ db = new mod.Database(dbPath, { readonly: true });
1400
+ } catch {
1401
+ db = new mod.Database(dbPath);
1402
+ }
1403
+ return {
1404
+ all: function (sql) {
1405
+ const params = Array.prototype.slice.call(arguments, 1);
1406
+ return db.query(sql).all.apply(db.query(sql), params);
1407
+ },
1408
+ close: function () { db.close(); }
1409
+ };
1410
+ }
1411
+ async function openNode() {
1412
+ const mod = await import("node:sqlite");
1413
+ let db;
1414
+ try {
1415
+ db = new mod.DatabaseSync(dbPath, { readOnly: true });
1416
+ } catch {
1417
+ db = new mod.DatabaseSync(dbPath);
1418
+ }
1419
+ return {
1420
+ all: function (sql) {
1421
+ const params = Array.prototype.slice.call(arguments, 1);
1422
+ return db.prepare(sql).all.apply(db.prepare(sql), params);
1423
+ },
1424
+ close: function () { db.close(); }
1425
+ };
1426
+ }
1427
+ if (isBun) {
1428
+ try {
1429
+ return await openBun();
1430
+ } catch {
1431
+ return await openNode();
1432
+ }
1433
+ }
1434
+ try {
1435
+ return await openNode();
1436
+ } catch {
1437
+ return await openBun();
1438
+ }
1439
+ }
1440
+
1441
+ function classifyRuleTopic(heading, text) {
1442
+ const h = String(heading || "").toLowerCase();
1443
+ const t = String(text || "").toLowerCase();
1444
+ if (/(environment|url|xampp|apache|localhost|port|path|workspace|server|database|sqlite|directory|folder)/i.test(h)) {
1445
+ return "environment";
1446
+ }
1447
+ if (/(style|format|output|code|css|js|javascript|html|php|python|sql|naming|indent|comment|preference)/i.test(h)) {
1448
+ return "preferences";
1449
+ }
1450
+ if (/(mentor|persona|confirm|delete|deletion|boundary|shell|accuracy|outbound|untrusted|protocol|behavior|backup|screenshot|verify|playwright)/i.test(h)) {
1451
+ return "agent-behavior";
1452
+ }
1453
+ if (/(decision|architecture|schema|stack|plugin)/i.test(h)) {
1454
+ return "decisions";
1455
+ }
1456
+ if (/\b(never|always|must not|do not|ask first|before editing)\b/i.test(t)) {
1457
+ return "agent-behavior";
1458
+ }
1459
+ if (/\b(localhost|http:\/\/|c:\\|\/users\/|port \d+|xampp|apache)\b/i.test(t)) {
1460
+ return "environment";
1461
+ }
1462
+ return "preferences";
1463
+ }
1464
+
1465
+ function parseAgentsMarkdownRules(filePath, projectScope, visited) {
1466
+ const seenFiles = visited || new Set();
1467
+ if (!filePath || !fs.existsSync(filePath)) return [];
1468
+ const resolved = path.resolve(filePath);
1469
+ if (seenFiles.has(resolved)) return [];
1470
+ seenFiles.add(resolved);
1471
+
1472
+ const raw = fs.readFileSync(resolved, "utf8").replace(/\r\n/g, "\n");
1473
+ const lines = raw.split("\n");
1474
+ const rules = [];
1475
+
1476
+ for (const line of lines) {
1477
+ const importMatch = line.trim().match(/^@([a-zA-Z]:[^\s]+|~\/[^\s]+|\/[^\s]+)$/);
1478
+ if (importMatch) {
1479
+ const targetRaw = importMatch[1];
1480
+ const targetPath = targetRaw.startsWith("~")
1481
+ ? path.join(os.homedir(), targetRaw.slice(1))
1482
+ : path.resolve(path.dirname(resolved), targetRaw);
1483
+ if (fs.existsSync(targetPath)) {
1484
+ const imported = parseAgentsMarkdownRules(targetPath, projectScope, seenFiles);
1485
+ for (const r of imported) rules.push(r);
1486
+ }
1487
+ }
1488
+ }
1489
+
1490
+ let currentHeading = "";
1491
+ let currentSubHeading = "";
1492
+ let inCodeBlock = false;
1493
+
1494
+ for (let i = 0; i < lines.length; i++) {
1495
+ const line = lines[i];
1496
+ const trimmed = line.trim();
1497
+ if (trimmed.startsWith("```")) {
1498
+ inCodeBlock = !inCodeBlock;
1499
+ continue;
1500
+ }
1501
+ if (inCodeBlock) continue;
1502
+
1503
+ const h2 = trimmed.match(/^##\s+(.+)$/);
1504
+ if (h2) {
1505
+ currentHeading = h2[1].replace(/[*_`]/g, "").trim();
1506
+ currentSubHeading = "";
1507
+ continue;
1508
+ }
1509
+ const h3 = trimmed.match(/^###\s+(.+)$/);
1510
+ if (h3) {
1511
+ currentSubHeading = h3[1].replace(/[*_`]/g, "").trim();
1512
+ continue;
1513
+ }
1514
+ const boldHeader = trimmed.match(/^\*\*([^*]+?)(?::)?\*\*\s*$/);
1515
+ if (boldHeader) {
1516
+ currentSubHeading = boldHeader[1].trim();
1517
+ continue;
1518
+ }
1519
+
1520
+ const bullet = line.match(/^\s*[-*]\s+(.+)$/);
1521
+ if (!bullet) continue;
1522
+ let body = bullet[1].trim();
1523
+ while (i + 1 < lines.length && /^\s{2,}[^-*\s]/.test(lines[i + 1]) && !lines[i + 1].trim().startsWith("```")) {
1524
+ i++;
1525
+ body += " " + lines[i].trim();
1526
+ }
1527
+
1528
+ const cleanBody = body.replace(/\s+/g, " ").trim();
1529
+ if (cleanBody.length < 24 || cleanBody.length > 550) continue;
1530
+ if (/^`topics\/|^`sessions\//.test(cleanBody)) continue;
1531
+
1532
+ let leadLabel = "";
1533
+ const leadMatch = cleanBody.match(/^\*\*([^*]{2,40}?)\*\*[:\s-]*(.+)$/);
1534
+ let factText = cleanBody;
1535
+ if (leadMatch) {
1536
+ leadLabel = leadMatch[1].replace(/:$/, "").trim();
1537
+ factText = (leadLabel + ": " + leadMatch[2].trim()).replace(/\*\*/g, "");
1538
+ } else {
1539
+ factText = cleanBody.replace(/\*\*/g, "");
1540
+ }
1541
+
1542
+ const sectionContext = [currentHeading, currentSubHeading].filter(Boolean).join(" / ");
1543
+ const topic = classifyRuleTopic(sectionContext + " " + leadLabel, factText);
1544
+ const tagTokens = tokenizeText(sectionContext + " " + leadLabel)
1545
+ .filter(function (t) { return !STOPWORDS.has(t) && t.length >= 3; })
1546
+ .slice(0, 5);
1547
+ if (tagTokens.indexOf("imported") === -1) tagTokens.push("imported");
1548
+ const tags = Array.from(new Set(tagTokens)).join(", ") || topic;
1549
+
1550
+ const fullFact = currentSubHeading && !factText.toLowerCase().startsWith(currentSubHeading.toLowerCase())
1551
+ ? currentSubHeading + ": " + factText
1552
+ : factText;
1553
+
1554
+ rules.push({
1555
+ topic: topic,
1556
+ tags: tags,
1557
+ fact: fullFact,
1558
+ project: projectScope || "global",
1559
+ sourceFile: resolved
1560
+ });
1561
+ }
1562
+
1563
+ return rules;
1564
+ }
1565
+
1566
+ function appendTopicFactBatch(rootDir, items) {
1567
+ if (!Array.isArray(items) || items.length === 0) return { added: [], skipped: 0 };
1568
+ ensureMemoryLayout(rootDir);
1569
+ const existing = parseTopicEntries(rootDir);
1570
+ const existingFacts = new Set(
1571
+ existing.map(function (e) {
1572
+ return String(e.fact || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
1573
+ })
1574
+ );
1575
+
1576
+ const byTopic = new Map();
1577
+ let skipped = 0;
1578
+ for (const item of items) {
1579
+ const cleanFact = String(item.fact || "").replace(/\s+/g, " ").trim();
1580
+ const normFact = cleanFact.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
1581
+ if (!normFact || existingFacts.has(normFact)) {
1582
+ skipped++;
1583
+ continue;
1584
+ }
1585
+ existingFacts.add(normFact);
1586
+ const rawTopic = String(item.topic || "preferences").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
1587
+ if (!byTopic.has(rawTopic)) byTopic.set(rawTopic, []);
1588
+ byTopic.get(rawTopic).push(Object.assign({}, item, { topic: rawTopic, fact: cleanFact }));
1589
+ }
1590
+
1591
+ const topicDir = path.join(rootDir, "topics");
1592
+ const indexFile = path.join(rootDir, "memory.md");
1593
+ const today = new Date().toISOString().split("T")[0];
1594
+ const added = [];
1595
+
1596
+ for (const [rawTopic, list] of byTopic.entries()) {
1597
+ const topicFile = path.join(topicDir, rawTopic + ".md");
1598
+ let text = "";
1599
+ if (fs.existsSync(topicFile)) {
1600
+ text = fs.readFileSync(topicFile, "utf8");
1601
+ } else {
1602
+ text = "# " + rawTopic.charAt(0).toUpperCase() + rawTopic.slice(1) + "\n";
1603
+ if (fs.existsSync(indexFile)) {
1604
+ const idxContent = fs.readFileSync(indexFile, "utf8");
1605
+ if (!idxContent.includes("topics/" + rawTopic + ".md")) {
1606
+ fs.writeFileSync(indexFile, idxContent.trimEnd() + "\n- `topics/" + rawTopic + ".md` - " + rawTopic + " entries\n", "utf8");
1607
+ }
1608
+ }
1609
+ }
1610
+
1611
+ for (const item of list) {
1612
+ const id = nextTopicId(text, rawTopic);
1613
+ const tagsList = String(item.tags || rawTopic).replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, " ").trim() || rawTopic;
1614
+ const proj = normalizeProjectScope(item.project);
1615
+ const blockLines = [
1616
+ "",
1617
+ "- id: " + id,
1618
+ " date: " + (item.date || today),
1619
+ " tags: [" + tagsList + "]"
1620
+ ];
1621
+ if (proj !== "global") blockLines.push(" project: " + proj);
1622
+ if (item.core) blockLines.push(" core: true");
1623
+ blockLines.push(" fact: " + item.fact, "");
1624
+ text = text.trimEnd() + "\n" + blockLines.join("\n");
1625
+ added.push({ id: id, topic: rawTopic, file: "topics/" + rawTopic + ".md", fact: item.fact, project: proj });
1626
+ }
1627
+
1628
+ fs.writeFileSync(topicFile, text, "utf8");
1629
+ parsedFileCache.delete(topicFile);
1630
+ }
1631
+
1632
+ cachedTopicSlugs = null;
1633
+ cachedTopicsRootDir = "";
1634
+ return { added: added, skipped: skipped };
1635
+ }
1636
+
1637
+ function getImportedSessionIds(rootDir) {
1638
+ const sessionDir = path.join(rootDir, "sessions");
1639
+ const importedIds = new Set();
1640
+ if (!fs.existsSync(sessionDir)) return importedIds;
1641
+ const files = fs.readdirSync(sessionDir).filter(function (f) { return f.endsWith(".md") && f.toLowerCase() !== "readme.md"; });
1642
+ for (const file of files) {
1643
+ try {
1644
+ const raw = fs.readFileSync(path.join(sessionDir, file), "utf8");
1645
+ const m = raw.match(/^\*\*Session ID\*\*:\s*(\S+)\s*$/m);
1646
+ if (m && m[1]) importedIds.add(m[1].trim());
1647
+ } catch {
1648
+ // ignore unreadable file
1649
+ }
1650
+ }
1651
+ return importedIds;
1652
+ }
1653
+
1654
+ function writeImportedSessionFile(rootDir, sessionData) {
1655
+ ensureMemoryLayout(rootDir);
1656
+ const sessionDir = path.join(rootDir, "sessions");
1657
+ const dateStr = sessionData.date || new Date().toISOString().split("T")[0];
1658
+ const rawSlug = String(sessionData.slug || sessionData.title || "session")
1659
+ .toLowerCase()
1660
+ .replace(/[^a-z0-9\s-_]/g, "")
1661
+ .trim()
1662
+ .split(/[\s-_]+/)
1663
+ .filter(function (w) { return w && !STOPWORDS.has(w); })
1664
+ .slice(0, 4)
1665
+ .join("-") || "session";
1666
+ const prefix = dateStr + "_" + rawSlug + "-";
1667
+
1668
+ const existingNums = fs.readdirSync(sessionDir)
1669
+ .filter(function (f) { return f.startsWith(prefix) && f.endsWith(".md"); })
1670
+ .map(function (f) {
1671
+ const m = f.match(/-(\d+)\.md$/);
1672
+ return m ? parseInt(m[1], 10) : 0;
1673
+ });
1674
+ const nextNum = existingNums.length > 0 ? Math.max.apply(null, existingNums) + 1 : 1;
1675
+ const numStr = String(nextNum).padStart(2, "0");
1676
+ const filename = prefix + numStr + ".md";
1677
+ const filepath = path.join(sessionDir, filename);
1678
+
1679
+ const md = [
1680
+ "# " + String(sessionData.title || rawSlug).trim(),
1681
+ "",
1682
+ "**Date**: " + dateStr,
1683
+ "**Checkpoint**: " + numStr,
1684
+ "**Context**: imported from opencode.db",
1685
+ "**Project**: " + (sessionData.project || "global"),
1686
+ "**Session ID**: " + sessionData.sessionId,
1687
+ "",
1688
+ sessionData.summary,
1689
+ ""
1690
+ ].join("\n");
1691
+
1692
+ fs.writeFileSync(filepath, md, "utf8");
1693
+ parsedFileCache.delete(filepath);
1694
+ return { filename: filename, filepath: filepath, sessionId: sessionData.sessionId };
1695
+ }
1696
+
1697
+ async function importFromOpenCodeDb(rootDir, options) {
1698
+ const opts = options || {};
1699
+ const dbPath = resolveDbPath(opts.dbPath);
1700
+ const maxSessions = Number(opts.limit) || 40;
1701
+ if (!dbPath || !fs.existsSync(dbPath)) {
1702
+ return { dbPath: dbPath || "", imported: [], skipped: 0 };
1703
+ }
1704
+
1705
+ const existingSessionIds = getImportedSessionIds(rootDir);
1706
+ let db;
1707
+ try {
1708
+ db = await openReadOnlySqlite(dbPath);
1709
+ } catch {
1710
+ return { dbPath: dbPath, imported: [], skipped: 0 };
1711
+ }
1712
+
1713
+ const imported = [];
1714
+ let skipped = 0;
1715
+
1716
+ try {
1717
+ const tables = new Set(
1718
+ db.all("SELECT name FROM sqlite_master WHERE type = 'table'").map(function (r) { return String(r.name || ""); })
1719
+ );
1720
+
1721
+ const candidates = [];
1722
+
1723
+ if (tables.has("session_v2") && tables.has("session_message")) {
1724
+ const v2Cols = new Set(
1725
+ db.all("PRAGMA table_info(session_v2)").map(function (c) { return String(c.name || ""); })
1726
+ );
1727
+ const dirExpr = v2Cols.has("directory")
1728
+ ? "directory"
1729
+ : (v2Cols.has("workspace_directory") ? "COALESCE(workspace_directory, root_directory, '')" : "''");
1730
+ const whereClause = v2Cols.has("time_archived") ? "WHERE time_archived IS NULL" : "";
1731
+ const rows = db.all(
1732
+ "SELECT id, title, " + dirExpr + " AS directory, time_created, time_updated FROM session_v2 " +
1733
+ whereClause + " ORDER BY time_updated DESC LIMIT " + Math.max(100, maxSessions * 3)
1734
+ );
1735
+
1736
+ for (const row of rows) {
1737
+ const sid = String(row.id || "");
1738
+ if (!sid) continue;
1739
+ if (existingSessionIds.has(sid)) {
1740
+ skipped++;
1741
+ continue;
1742
+ }
1743
+ const msgs = db.all(
1744
+ "SELECT type, time_created, data FROM session_message WHERE session_id = ? ORDER BY time_created ASC LIMIT 120",
1745
+ sid
1746
+ );
1747
+ if (!msgs || msgs.length < 2) continue;
1748
+
1749
+ let firstUser = "";
1750
+ let lastUser = "";
1751
+ let lastAssistant = "";
1752
+ const compressSummaries = [];
1753
+
1754
+ for (const m of msgs) {
1755
+ let parsed;
1756
+ try {
1757
+ parsed = JSON.parse(String(m.data || ""));
1758
+ } catch {
1759
+ continue;
1760
+ }
1761
+ const t = String(m.type || parsed.type || "");
1762
+ if (t === "user" && typeof parsed.text === "string" && parsed.text.trim()) {
1763
+ const txt = parsed.text.trim();
1764
+ if (!firstUser) firstUser = txt;
1765
+ lastUser = txt;
1766
+ } else if (t === "assistant" && Array.isArray(parsed.content)) {
1767
+ for (const part of parsed.content) {
1768
+ if (!part || typeof part !== "object") continue;
1769
+ if (part.type === "text" && typeof part.text === "string" && part.text.trim()) {
1770
+ lastAssistant = part.text.trim();
1771
+ } else if (part.type === "tool" && part.name === "compress" && part.state && part.state.input) {
1772
+ const inp = part.state.input;
1773
+ if (Array.isArray(inp.content)) {
1774
+ for (const c of inp.content) {
1775
+ if (c && typeof c.summary === "string" && c.summary.trim()) {
1776
+ compressSummaries.push(c.summary.trim());
1777
+ }
1778
+ }
1779
+ }
1780
+ }
1781
+ }
1782
+ } else if ((t === "compaction" || t === "summary") && typeof parsed.text === "string" && parsed.text.trim()) {
1783
+ compressSummaries.push(parsed.text.trim());
1784
+ }
1785
+ }
1786
+
1787
+ if (!compressSummaries.length && (!firstUser || !lastAssistant || (firstUser.length + lastAssistant.length) < 120)) {
1788
+ continue;
1789
+ }
1790
+ const rawTitle = String(row.title || "").trim();
1791
+ const isGenericTitle = !rawTitle || /^(\(untitled|new session|greeting|hi|hello|test)/i.test(rawTitle);
1792
+ if (isGenericTitle && !compressSummaries.length && msgs.length < 4) {
1793
+ continue;
1794
+ }
1795
+
1796
+ const ts = Number(row.time_updated || row.time_created || Date.now());
1797
+ const dateStr = new Date(ts > 1e11 ? ts : ts * 1000).toISOString().split("T")[0];
1798
+ const title = (!isGenericTitle ? rawTitle : firstUser.split("\n")[0].slice(0, 72)).trim() || "Imported Session";
1799
+ const bodyParts = [];
1800
+ if (compressSummaries.length > 0) {
1801
+ bodyParts.push("## What was built/fixed/decided\n\n" + compressSummaries.join("\n\n").slice(0, 1800));
1802
+ } else {
1803
+ bodyParts.push("## What was built/fixed/decided\n\n" + firstUser.replace(/\s+/g, " ").slice(0, 500));
1804
+ }
1805
+ if (lastAssistant) {
1806
+ bodyParts.push("## Outcome\n\n" + lastAssistant.replace(/\s+/g, " ").slice(0, 900));
1807
+ }
1808
+ if (lastUser && lastUser !== firstUser) {
1809
+ bodyParts.push("## Key decisions\n\nFollow-up focus: " + lastUser.replace(/\s+/g, " ").slice(0, 350));
1810
+ }
1811
+
1812
+ candidates.push({
1813
+ sessionId: sid,
1814
+ title: title,
1815
+ date: dateStr,
1816
+ project: row.directory ? normalizeProjectScope(String(row.directory)) : "global",
1817
+ summary: bodyParts.join("\n\n"),
1818
+ hasCompaction: compressSummaries.length > 0
1819
+ });
1820
+ if (candidates.length >= maxSessions) break;
1821
+ }
1822
+ }
1823
+
1824
+ if (candidates.length < maxSessions && tables.has("session") && tables.has("message") && tables.has("part")) {
1825
+ const v1Rows = db.all(
1826
+ "SELECT id, title, directory, time_created, time_updated FROM session ORDER BY time_updated DESC LIMIT " +
1827
+ Math.max(100, maxSessions * 3)
1828
+ );
1829
+ for (const row of v1Rows) {
1830
+ const sid = String(row.id || "");
1831
+ if (!sid) continue;
1832
+ if (existingSessionIds.has(sid) || candidates.some(function (c) { return c.sessionId === sid; })) {
1833
+ skipped++;
1834
+ continue;
1835
+ }
1836
+ const parts = db.all(
1837
+ "SELECT p.data AS part_data, json_extract(m.data, '$.role') AS role FROM part p JOIN message m ON m.id = p.message_id WHERE p.session_id = ? ORDER BY p.time_created ASC LIMIT 120",
1838
+ sid
1839
+ );
1840
+ if (!parts || parts.length < 2) continue;
1841
+
1842
+ let firstUser = "";
1843
+ let lastAssistant = "";
1844
+ const compressSummaries = [];
1845
+ for (const p of parts) {
1846
+ let parsed;
1847
+ try {
1848
+ parsed = JSON.parse(String(p.part_data || ""));
1849
+ } catch {
1850
+ continue;
1851
+ }
1852
+ if (parsed.type === "text" && typeof parsed.text === "string" && parsed.text.trim()) {
1853
+ if (p.role === "user") {
1854
+ if (!firstUser) firstUser = parsed.text.trim();
1855
+ } else {
1856
+ lastAssistant = parsed.text.trim();
1857
+ }
1858
+ } else if ((parsed.type === "compaction" || parsed.type === "summary") && typeof parsed.text === "string") {
1859
+ compressSummaries.push(parsed.text.trim());
1860
+ }
1861
+ }
1862
+
1863
+ if (!compressSummaries.length && (!firstUser || !lastAssistant || (firstUser.length + lastAssistant.length) < 120)) {
1864
+ continue;
1865
+ }
1866
+ const ts = Number(row.time_updated || row.time_created || Date.now());
1867
+ const dateStr = new Date(ts > 1e11 ? ts : ts * 1000).toISOString().split("T")[0];
1868
+ const rawTitle = String(row.title || "").trim();
1869
+ const title = (rawTitle && !/^(\(untitled|new session)/i.test(rawTitle) ? rawTitle : firstUser.split("\n")[0].slice(0, 72)).trim() || "Imported Session";
1870
+ const bodyParts = [
1871
+ "## What was built/fixed/decided\n\n" + (compressSummaries.length > 0 ? compressSummaries.join("\n\n").slice(0, 1800) : firstUser.replace(/\s+/g, " ").slice(0, 500))
1872
+ ];
1873
+ if (lastAssistant) {
1874
+ bodyParts.push("## Outcome\n\n" + lastAssistant.replace(/\s+/g, " ").slice(0, 900));
1875
+ }
1876
+
1877
+ candidates.push({
1878
+ sessionId: sid,
1879
+ title: title,
1880
+ date: dateStr,
1881
+ project: row.directory ? normalizeProjectScope(String(row.directory)) : "global",
1882
+ summary: bodyParts.join("\n\n"),
1883
+ hasCompaction: compressSummaries.length > 0
1884
+ });
1885
+ if (candidates.length >= maxSessions) break;
1886
+ }
1887
+ }
1888
+
1889
+ for (const cand of candidates.slice(0, maxSessions)) {
1890
+ const saved = writeImportedSessionFile(rootDir, cand);
1891
+ existingSessionIds.add(cand.sessionId);
1892
+ imported.push(saved);
1893
+ }
1894
+ } finally {
1895
+ try {
1896
+ db.close();
1897
+ } catch {
1898
+ // ignore close error
1899
+ }
1900
+ }
1901
+
1902
+ return { dbPath: dbPath, imported: imported, skipped: skipped };
1903
+ }
1904
+
1905
+ async function importExistingMemory(rootDir, options) {
1906
+ const opts = options || {};
1907
+ ensureMemoryLayout(rootDir);
1908
+
1909
+ const candidateAgentsFiles = [];
1910
+ if (Array.isArray(opts.agentsFiles) && opts.agentsFiles.length > 0) {
1911
+ for (const f of opts.agentsFiles) {
1912
+ if (f) candidateAgentsFiles.push({ path: f, project: opts.project || "global" });
1913
+ }
1914
+ } else if (typeof opts.agentsFiles === "string" && opts.agentsFiles.trim()) {
1915
+ candidateAgentsFiles.push({ path: opts.agentsFiles.trim(), project: opts.project || "global" });
1916
+ } else if (opts.includeAgents !== false) {
1917
+ const home = os.homedir();
1918
+ const configDir = resolveConfigDir(opts.configDir);
1919
+ candidateAgentsFiles.push({ path: path.join(configDir, "AGENTS.md"), project: "global" });
1920
+ candidateAgentsFiles.push({ path: path.join(home, ".claude", "CLAUDE.md"), project: "global" });
1921
+ const projDir = opts.projectDir || process.cwd();
1922
+ if (projDir) {
1923
+ const projAgents = path.join(path.resolve(projDir), "AGENTS.md");
1924
+ const projScope = isUmbrellaProject(projDir) ? "global" : normalizeProjectScope(projDir);
1925
+ candidateAgentsFiles.push({ path: projAgents, project: projScope });
1926
+ }
1927
+ }
1928
+
1929
+ const visitedFiles = new Set();
1930
+ const parsedRules = [];
1931
+ const agentsSources = [];
1932
+ for (const item of candidateAgentsFiles) {
1933
+ const resolved = item.path.startsWith("~")
1934
+ ? path.join(os.homedir(), item.path.slice(1))
1935
+ : path.resolve(item.path);
1936
+ if (!fs.existsSync(resolved)) continue;
1937
+ const beforeCount = parsedRules.length;
1938
+ const extracted = parseAgentsMarkdownRules(resolved, item.project, visitedFiles);
1939
+ for (const r of extracted) parsedRules.push(r);
1940
+ if (parsedRules.length > beforeCount) {
1941
+ agentsSources.push(resolved);
1942
+ }
1943
+ }
1944
+
1945
+ const factsResult = appendTopicFactBatch(rootDir, parsedRules);
1946
+ const sessionsResult = opts.includeSessions === false
1947
+ ? { dbPath: "", imported: [], skipped: 0 }
1948
+ : await importFromOpenCodeDb(rootDir, { dbPath: opts.dbPath, limit: opts.limit });
1949
+
1950
+ const syncResult = opts.skipSync
1951
+ ? { total: 0, embedded: 0, reused: 0, vecFile: path.join(rootDir, "vectors.json") }
1952
+ : await syncVectors(rootDir);
1953
+
1954
+ return {
1955
+ importedFacts: factsResult.added,
1956
+ skippedFacts: factsResult.skipped,
1957
+ importedSessions: sessionsResult.imported,
1958
+ skippedSessions: sessionsResult.skipped,
1959
+ agentsSources: agentsSources,
1960
+ dbPath: sessionsResult.dbPath,
1961
+ syncResult: syncResult
1962
+ };
1963
+ }
1964
+
567
1965
  function extractLastUserText(messages) {
568
1966
  if (!Array.isArray(messages)) return "";
569
1967
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -597,9 +1995,11 @@ function createPluginDefinition() {
597
1995
  const rootDir = resolveMemoryDir(options.directory);
598
1996
  const minScore = Number(options.minScore || 0.38);
599
1997
  const topK = Number(options.topK || 6);
1998
+ const defaultProject = (ctx && ctx.location && ctx.location.directory)
1999
+ ? ctx.location.directory
2000
+ : (options.project || "global");
600
2001
 
601
2002
  loadCachedVectors(rootDir);
602
- getEmbedder().catch(function () {});
603
2003
  syncVectors(rootDir).catch(function (err) {
604
2004
  console.error("local-memory sync error:", err);
605
2005
  });
@@ -610,7 +2010,7 @@ function createPluginDefinition() {
610
2010
  const toolReg = await ctx.tool.transform(function (editor) {
611
2011
  editor.add({
612
2012
  name: "memory_store",
613
- description: "Atomically store a persistent memory fact into a topic file and update semantic vectors immediately. Call this whenever the user states a preference/rule, corrects the agent, makes an architectural decision, or uncovers a non-obvious environment fact.",
2013
+ description: "Atomically store or update a persistent memory fact in a topic file and update semantic vectors immediately. Supports in-place updates via id, superseding outdated facts via supersedes, project scoping, and core pinning.",
614
2014
  input: {
615
2015
  type: "object",
616
2016
  properties: {
@@ -628,7 +2028,19 @@ function createPluginDefinition() {
628
2028
  },
629
2029
  id: {
630
2030
  type: "string",
631
- description: "Optional explicit ID (auto-generated as <topic>-<nnn> when omitted)"
2031
+ description: "Optional explicit ID (auto-generated as <topic>-<nnn> when omitted; updates in place if ID already exists)"
2032
+ },
2033
+ supersedes: {
2034
+ type: "string",
2035
+ description: "Optional ID (or comma-separated IDs) of outdated memory entries to delete when storing this replacement"
2036
+ },
2037
+ project: {
2038
+ type: "string",
2039
+ description: "Optional project scope slug/path or 'global' (default: 'global')"
2040
+ },
2041
+ core: {
2042
+ type: "boolean",
2043
+ description: "Optional flag to pin this fact as a core memory injected on every turn regardless of prompt query"
632
2044
  }
633
2045
  },
634
2046
  required: ["topic", "tags", "fact"],
@@ -636,15 +2048,52 @@ function createPluginDefinition() {
636
2048
  },
637
2049
  execute: async function (input) {
638
2050
  const saved = await storeMemoryFact(rootDir, input);
2051
+ const verb = saved.updated ? "Updated" : "Stored";
2052
+ const extra = [];
2053
+ if (saved.project && saved.project !== "global") extra.push("project=" + saved.project);
2054
+ if (saved.core) extra.push("core=true");
2055
+ if (saved.superseded && saved.superseded.length > 0) extra.push("superseded: " + saved.superseded.join(", "));
2056
+ const suffix = extra.length > 0 ? " (" + extra.join(", ") + ")" : "";
639
2057
  return {
640
- content: "Stored [" + saved.id + "] in " + saved.file + " and updated vectors.json:\n" + saved.fact
2058
+ content: verb + " [" + saved.id + "] in " + saved.file + suffix + " and updated vectors.json:\n" + saved.fact
2059
+ };
2060
+ }
2061
+ });
2062
+
2063
+ editor.add({
2064
+ name: "memory_delete",
2065
+ description: "Delete one or more outdated or incorrect memory entries by ID from their Markdown source files (topics/*.md or sessions/*.md) and vectors.json.",
2066
+ input: {
2067
+ type: "object",
2068
+ properties: {
2069
+ id: {
2070
+ type: "string",
2071
+ description: "Memory entry ID to delete (or comma-separated IDs, e.g. 'env-007' or 'env-007, dec-002')"
2072
+ }
2073
+ },
2074
+ required: ["id"],
2075
+ additionalProperties: false
2076
+ },
2077
+ execute: async function (input) {
2078
+ const res = await deleteMemoryEntry(rootDir, input.id);
2079
+ if (res.deleted.length === 0) {
2080
+ return {
2081
+ content: "No matching memory entry found for ID: " + res.notFound.join(", ")
2082
+ };
2083
+ }
2084
+ const summary = res.deleted.map(function (d) {
2085
+ return "[" + d.id + "] from " + d.file;
2086
+ }).join(", ");
2087
+ const missing = res.notFound.length > 0 ? " (not found: " + res.notFound.join(", ") + ")" : "";
2088
+ return {
2089
+ content: "Deleted " + summary + " and updated vectors.json" + missing + "."
641
2090
  };
642
2091
  }
643
2092
  });
644
2093
 
645
2094
  editor.add({
646
2095
  name: "memory_search",
647
- description: "Search persistent local memory (both atomic topic facts and session checkpoint summaries) using hybrid semantic + keyword matching.",
2096
+ description: "Search persistent local memory (both atomic topic facts and session checkpoint summaries) using hybrid semantic + BM25 keyword matching.",
648
2097
  input: {
649
2098
  type: "object",
650
2099
  properties: {
@@ -660,18 +2109,33 @@ function createPluginDefinition() {
660
2109
  topN: {
661
2110
  type: "number",
662
2111
  description: "Maximum results to return (default: 8)"
2112
+ },
2113
+ project: {
2114
+ type: "string",
2115
+ description: "Optional project scope filter ('all' for all projects, 'global' for global only, or a project name/path)"
2116
+ },
2117
+ coreOnly: {
2118
+ type: "boolean",
2119
+ description: "When true, only return pinned core memories"
663
2120
  }
664
2121
  },
665
2122
  required: ["query"],
666
2123
  additionalProperties: false
667
2124
  },
668
2125
  execute: async function (input) {
669
- const hits = await searchMemory(rootDir, input.query, input.mode || "hybrid", input.topN || 8);
2126
+ const hits = await searchMemory(rootDir, input.query, input.mode || "hybrid", input.topN || 8, {
2127
+ project: input.project || "all",
2128
+ coreOnly: Boolean(input.coreOnly)
2129
+ });
670
2130
  if (hits.length === 0) {
671
2131
  return { content: "No matching memory entries found." };
672
2132
  }
673
2133
  const formatted = hits.map(function (h) {
674
- return h.score.toFixed(3) + " [" + h.entry.id + "] " + h.entry.fact + " (" + h.entry.file + ")";
2134
+ const badges = [];
2135
+ if (h.entry.core) badges.push("core");
2136
+ if (h.entry.project && h.entry.project !== "global") badges.push("project:" + h.entry.project);
2137
+ const badgeStr = badges.length > 0 ? " [" + badges.join(",") + "]" : "";
2138
+ return h.score.toFixed(3) + " [" + h.entry.id + "]" + badgeStr + " " + h.entry.fact + " (" + h.entry.file + ")";
675
2139
  }).join("\n");
676
2140
  return { content: formatted };
677
2141
  }
@@ -720,8 +2184,9 @@ function createPluginDefinition() {
720
2184
 
721
2185
  if (ctx && ctx.session && typeof ctx.session.hook === "function") {
722
2186
  const ctxReg = await ctx.session.hook("context", async function (event) {
2187
+ const activeProject = (event && event.directory) || defaultProject || "global";
723
2188
  const userText = extractLastUserText(event.messages);
724
- const ctxKey = String(userText || "").trim() + "::" + cachedVersion;
2189
+ const ctxKey = String(userText || "").trim() + "::" + normalizeProjectScope(activeProject) + "::" + cachedVersion;
725
2190
  if (ctxKey === lastContextKey && lastContextText) {
726
2191
  if (Array.isArray(event.system)) {
727
2192
  event.system.push({ type: "text", text: lastContextText });
@@ -735,27 +2200,40 @@ function createPluginDefinition() {
735
2200
  "Persistent memory (`opencode-local-memory`) is active at: " + rootDir,
736
2201
  "Available topics: " + (topicSlugs.join(", ") || "preferences, decisions, environment, agent-behavior") + " (or pass any new topic slug to create a new file).",
737
2202
  "",
738
- "AUTOMATIC STORAGE (via `memory_store` tool — no prompting needed):",
2203
+ "AUTOMATIC STORAGE (via `memory_store` / `memory_delete` tools — no prompting needed):",
739
2204
  "Call `memory_store` immediately in the SAME turn before your final response whenever any of these happen:",
740
2205
  "- User states a preference, convention, or 'always/never do X' rule",
741
2206
  "- An architecture, workflow, or design decision is made (yours or theirs)",
742
2207
  "- A non-obvious environment, path, port, or tooling fact is discovered",
743
2208
  "- A recurring correction or pattern emerges",
744
2209
  "- The user has to correct you or repeat an instruction (store it so it never needs repeating)",
2210
+ "- When replacing an outdated fact, pass `id` to update in-place or `supersedes: '<old-id>'` (or call `memory_delete`) so stale facts never pollute recall.",
745
2211
  "Hard gate: before finishing every task, check if any trigger above fired. If it did, call `memory_store` NOW — never promise to remember later. Do NOT store trivial exchanges, transient debugging steps, duplicates, or secrets.",
746
2212
  "",
747
2213
  "WHERE TO STORE:",
748
- "- Global (`memory_store` tool): coding style, tooling preferences, agent behavior rules, cross-project decisions, and environment facts that remain true in a new project tomorrow.",
749
- "- Project (`AGENTS.md` in repo root): repo-specific architecture, asset IDs, endpoints, or conventions true only inside that repo.",
2214
+ "- Global (`memory_store` with default `project: 'global'`): coding style, tooling preferences, agent behavior rules, cross-project decisions, and environment facts that remain true in a new project tomorrow. Pass `core: true` for critical invariants that must be pinned on every turn.",
2215
+ "- Project-scoped (`memory_store` with `project: '<repo-or-path>'` or `AGENTS.md` in repo root): project-specific architecture, asset IDs, endpoints, or conventions that only apply to that project.",
750
2216
  "",
751
2217
  "AUTOMATIC RECALL & CHECKPOINTS:",
752
2218
  "- When the user references 'we discussed', 'last time', 'earlier', a settled decision, or when a topic needs deeper lookup than the auto-recalled hits below, call `memory_search` (`mode: 'hybrid' | 'semantic' | 'grep'`).",
753
2219
  "- Session compactions are checkpointed automatically. At the end of significant work sessions (architecture decisions, hard-won fixes, new patterns), call `memory_checkpoint` with `slug`, `title`, and a distilled `summary`."
754
2220
  ];
755
2221
 
2222
+ const coreMemories = getCoreMemories(rootDir, activeProject, userText);
2223
+ const coreIds = new Set();
2224
+ if (coreMemories.length > 0) {
2225
+ lines.push("Pinned core memories:");
2226
+ for (const entry of coreMemories) {
2227
+ coreIds.add(entry.id);
2228
+ lines.push("- [" + entry.id + "] (" + entry.file + "): " + entry.fact);
2229
+ }
2230
+ }
2231
+
756
2232
  if (userText && userText.trim().length >= 5) {
757
- const hits = await searchMemory(rootDir, userText, "hybrid", topK).catch(function () { return []; });
758
- const relevant = hits.filter(function (h) { return h.score >= minScore; });
2233
+ const hits = await searchMemory(rootDir, userText, "hybrid", topK, { project: activeProject }).catch(function () { return []; });
2234
+ const relevant = hits.filter(function (h) {
2235
+ return h.score >= minScore && !coreIds.has(h.entry.id);
2236
+ });
759
2237
  if (relevant.length > 0) {
760
2238
  lines.push("Auto-recalled memories for this prompt:");
761
2239
  for (const h of relevant) {
@@ -808,40 +2286,90 @@ export {
808
2286
  server,
809
2287
  resolveMemoryDir,
810
2288
  resolveConfigDir,
2289
+ resolveDbPath,
811
2290
  ensureMemoryLayout,
812
2291
  installPlugin,
2292
+ importExistingMemory,
2293
+ parseAgentsMarkdownRules,
813
2294
  parseTopicEntries,
814
2295
  parseSessionEntries,
815
2296
  nextTopicId,
816
2297
  getTopicSlugs,
2298
+ getCoreMemories,
2299
+ isUmbrellaProject,
2300
+ normalizeProjectScope,
2301
+ getProjectLeaf,
2302
+ matchesProjectScope,
2303
+ detectProjectsFromText,
2304
+ computeLexicalScore,
817
2305
  loadCachedVectors,
818
2306
  syncVectors,
819
2307
  searchMemory,
820
2308
  storeMemoryFact,
2309
+ deleteMemoryEntry,
821
2310
  storeSessionCheckpoint
822
2311
  };
823
2312
 
824
2313
  const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
825
2314
  if (isDirectRun) {
826
2315
  const cmd = process.argv[2] || "sync";
827
- const rootDir = resolveMemoryDir(process.env.OPENCODE_MEMORY_DIR);
2316
+ let customDir = process.env.OPENCODE_MEMORY_DIR || "";
2317
+ const dirFlagIdx = process.argv.indexOf("--dir");
2318
+ if (dirFlagIdx !== -1 && process.argv[dirFlagIdx + 1]) {
2319
+ customDir = process.argv[dirFlagIdx + 1];
2320
+ }
2321
+ const dbFlagIdx = process.argv.indexOf("--db");
2322
+ const customDb = (dbFlagIdx !== -1 && process.argv[dbFlagIdx + 1]) ? process.argv[dbFlagIdx + 1] : undefined;
2323
+ const agentsFlagIdx = process.argv.indexOf("--agents");
2324
+ const customAgents = (agentsFlagIdx !== -1 && process.argv[agentsFlagIdx + 1]) ? process.argv[agentsFlagIdx + 1] : undefined;
2325
+ const limitFlagIdx = process.argv.indexOf("--limit");
2326
+ const customLimit = (limitFlagIdx !== -1 && process.argv[limitFlagIdx + 1]) ? parseInt(process.argv[limitFlagIdx + 1], 10) : undefined;
2327
+ const withImport = process.argv.includes("--import");
2328
+ const rootDir = resolveMemoryDir(customDir || undefined);
828
2329
 
829
2330
  if (cmd === "install" || cmd === "init" || cmd === "setup") {
830
- let customDir = process.env.OPENCODE_MEMORY_DIR || "";
831
- const dirFlagIdx = process.argv.indexOf("--dir");
832
- if (dirFlagIdx !== -1 && process.argv[dirFlagIdx + 1]) {
833
- customDir = process.argv[dirFlagIdx + 1];
834
- }
835
- installPlugin({ directory: customDir || undefined }).then(function (res) {
2331
+ installPlugin({
2332
+ directory: customDir || undefined,
2333
+ importExisting: withImport,
2334
+ dbPath: customDb,
2335
+ agentsFiles: customAgents,
2336
+ limit: customLimit
2337
+ }).then(function (res) {
836
2338
  console.log("opencode-local-memory installed:");
837
2339
  console.log(" Server config: " + res.serverConfigFile + " (" + res.serverStatus + ")");
838
2340
  console.log(" TUI config: " + res.cliConfigFile + " (" + res.cliStatus + ")");
839
2341
  console.log(" Memory folder: " + res.memoryDir);
2342
+ if (res.importResult) {
2343
+ console.log(
2344
+ " Imported: " +
2345
+ res.importResult.importedFacts.length + " rules from AGENTS.md, " +
2346
+ res.importResult.importedSessions.length + " sessions from opencode.db"
2347
+ );
2348
+ }
840
2349
  console.log(" Vectors cache: " + res.syncResult.vecFile + " (" + res.syncResult.total + " entries ready)");
841
2350
  }).catch(function (err) {
842
2351
  console.error("Install failed:", err);
843
2352
  process.exit(1);
844
2353
  });
2354
+ } else if (cmd === "import" || cmd === "backfill") {
2355
+ const asJson = process.argv.includes("--json");
2356
+ importExistingMemory(rootDir, {
2357
+ dbPath: customDb,
2358
+ agentsFiles: customAgents,
2359
+ limit: customLimit
2360
+ }).then(function (res) {
2361
+ if (asJson) {
2362
+ console.log(JSON.stringify(res));
2363
+ return;
2364
+ }
2365
+ console.log("opencode-local-memory import complete:");
2366
+ console.log(" Rules imported: " + res.importedFacts.length + " (skipped " + res.skippedFacts + " existing)");
2367
+ console.log(" Sessions imported: " + res.importedSessions.length + " (skipped " + res.skippedSessions + " existing)");
2368
+ console.log(" Vectors cache: " + res.syncResult.vecFile + " (" + res.syncResult.total + " total entries)");
2369
+ }).catch(function (err) {
2370
+ console.error("Import failed:", err);
2371
+ process.exit(1);
2372
+ });
845
2373
  } else if (cmd === "sync" || cmd === "embed") {
846
2374
  syncVectors(rootDir).then(function (res) {
847
2375
  console.log("Synced " + res.total + " memory entries (" + res.embedded + " newly embedded, " + res.reused + " cached) -> " + res.vecFile);
@@ -871,5 +2399,13 @@ if (isDirectRun) {
871
2399
  console.error("Store failed:", err);
872
2400
  process.exit(1);
873
2401
  });
2402
+ } else if (cmd === "delete" || cmd === "rm") {
2403
+ const id = process.argv.slice(3).join(",");
2404
+ deleteMemoryEntry(rootDir, id).then(function (res) {
2405
+ console.log("Deleted " + res.deleted.length + " entries; remaining: " + res.total);
2406
+ }).catch(function (err) {
2407
+ console.error("Delete failed:", err);
2408
+ process.exit(1);
2409
+ });
874
2410
  }
875
2411
  }