@nandoblanco/opencode-local-memory 1.0.1 → 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.
- package/README.md +42 -22
- package/index.js +1437 -75
- package/package.json +1 -1
- package/tui.ts +192 -6
package/index.js
CHANGED
|
@@ -4,9 +4,11 @@
|
|
|
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
|
|
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;
|
|
@@ -19,7 +21,176 @@ let cachedTopicSlugs = null;
|
|
|
19
21
|
let cachedTopicsRootDir = "";
|
|
20
22
|
let lastContextKey = "";
|
|
21
23
|
let lastContextText = "";
|
|
24
|
+
let cachedCorpusStats = null;
|
|
22
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
|
+
}
|
|
23
194
|
|
|
24
195
|
function resolveMemoryDir(customDir) {
|
|
25
196
|
if (customDir) {
|
|
@@ -237,6 +408,15 @@ async function installPlugin(options) {
|
|
|
237
408
|
const cliStatus = addPluginToJsoncFile(cliConfigFile, "https://" + cliName + ".ai/v2/cli.json", cliEntryStr, matchKey);
|
|
238
409
|
|
|
239
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;
|
|
240
420
|
const syncResult = opts.skipSync ? { total: 0, embedded: 0, reused: 0, vecFile: path.join(rootDir, "vectors.json") } : await syncVectors(rootDir);
|
|
241
421
|
|
|
242
422
|
return {
|
|
@@ -246,6 +426,7 @@ async function installPlugin(options) {
|
|
|
246
426
|
cliConfigFile: cliConfigFile,
|
|
247
427
|
cliStatus: cliStatus,
|
|
248
428
|
memoryDir: rootDir,
|
|
429
|
+
importResult: importResult,
|
|
249
430
|
syncResult: syncResult
|
|
250
431
|
};
|
|
251
432
|
}
|
|
@@ -318,6 +499,20 @@ async function getEmbedder() {
|
|
|
318
499
|
return embedderPromise;
|
|
319
500
|
}
|
|
320
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
|
+
|
|
321
516
|
async function embedText(text) {
|
|
322
517
|
const key = String(text || "").trim().toLowerCase();
|
|
323
518
|
if (queryVecCache.has(key)) {
|
|
@@ -350,23 +545,50 @@ function parseTopicEntries(rootDir) {
|
|
|
350
545
|
const entries = [];
|
|
351
546
|
|
|
352
547
|
for (const file of files) {
|
|
353
|
-
const
|
|
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");
|
|
354
564
|
const blocks = text.split(/\n(?=- id: )/).filter(function (b) { return b.trim().startsWith("- id: "); });
|
|
565
|
+
const fileEntries = [];
|
|
355
566
|
for (const block of blocks) {
|
|
356
567
|
const idMatch = block.match(/- id:\s*(\S+)/);
|
|
357
568
|
const dateMatch = block.match(/date:\s*(\S+)/);
|
|
358
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);
|
|
359
572
|
const factMatch = block.match(/fact:\s*(.+)/);
|
|
360
573
|
if (idMatch && factMatch) {
|
|
361
|
-
|
|
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 = {
|
|
362
579
|
id: idMatch[1].trim(),
|
|
363
580
|
date: dateMatch ? dateMatch[1].trim() : "",
|
|
364
581
|
file: "topics/" + file,
|
|
365
|
-
tags:
|
|
582
|
+
tags: tagsStr,
|
|
366
583
|
fact: factMatch[1].trim()
|
|
367
|
-
}
|
|
584
|
+
};
|
|
585
|
+
if (proj !== "global") entry.project = proj;
|
|
586
|
+
if (isCore) entry.core = true;
|
|
587
|
+
fileEntries.push(entry);
|
|
588
|
+
entries.push(Object.assign({}, entry));
|
|
368
589
|
}
|
|
369
590
|
}
|
|
591
|
+
parsedFileCache.set(fullPath, { mtimeMs: stat.mtimeMs, entries: fileEntries });
|
|
370
592
|
}
|
|
371
593
|
return entries;
|
|
372
594
|
}
|
|
@@ -380,7 +602,22 @@ function parseSessionEntries(rootDir) {
|
|
|
380
602
|
const entries = [];
|
|
381
603
|
|
|
382
604
|
for (const file of files) {
|
|
383
|
-
const
|
|
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");
|
|
384
621
|
const base = file.replace(/\.md$/, "");
|
|
385
622
|
const titleMatch = raw.match(/^#\s+(.+)$/m);
|
|
386
623
|
const title = titleMatch ? titleMatch[1].trim() : base;
|
|
@@ -388,6 +625,8 @@ function parseSessionEntries(rootDir) {
|
|
|
388
625
|
const date = dateMatch ? dateMatch[1] : "";
|
|
389
626
|
const slug = dateMatch ? dateMatch[2] : base;
|
|
390
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";
|
|
391
630
|
|
|
392
631
|
const sections = [];
|
|
393
632
|
const targetHeadings = [
|
|
@@ -409,53 +648,195 @@ function parseSessionEntries(rootDir) {
|
|
|
409
648
|
}
|
|
410
649
|
|
|
411
650
|
const factText = title + " — " + (sections.join(" | ").slice(0, 700) || raw.replace(/\s+/g, " ").slice(0, 500));
|
|
412
|
-
|
|
651
|
+
const entry = {
|
|
413
652
|
id: "session:" + base,
|
|
414
653
|
date: date,
|
|
415
654
|
file: "sessions/" + file,
|
|
416
655
|
tags: tags,
|
|
417
656
|
fact: factText
|
|
418
|
-
}
|
|
657
|
+
};
|
|
658
|
+
if (proj !== "global") entry.project = proj;
|
|
659
|
+
parsedFileCache.set(fullPath, { mtimeMs: stat.mtimeMs, entries: [entry] });
|
|
660
|
+
entries.push(Object.assign({}, entry));
|
|
419
661
|
}
|
|
420
662
|
return entries;
|
|
421
663
|
}
|
|
422
664
|
|
|
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
|
+
|
|
423
681
|
function serializeVectorsJson(entries) {
|
|
424
682
|
if (!entries || entries.length === 0) return "[]\n";
|
|
425
|
-
const lines = entries.map(
|
|
426
|
-
return " " + JSON.stringify({
|
|
427
|
-
id: e.id,
|
|
428
|
-
date: e.date,
|
|
429
|
-
file: e.file,
|
|
430
|
-
tags: e.tags,
|
|
431
|
-
fact: e.fact,
|
|
432
|
-
vector: e.vector
|
|
433
|
-
});
|
|
434
|
-
});
|
|
683
|
+
const lines = entries.map(serializeEntryLine);
|
|
435
684
|
return "[\n" + lines.join(",\n") + "\n]\n";
|
|
436
685
|
}
|
|
437
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
|
+
|
|
438
702
|
function prepareEntryCacheFields(item) {
|
|
439
703
|
if (!item) return;
|
|
440
704
|
if (!item._haystack) {
|
|
441
|
-
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;
|
|
442
729
|
}
|
|
443
730
|
if (Array.isArray(item.vector) && !(item._vec instanceof Float32Array)) {
|
|
444
731
|
item._vec = new Float32Array(item.vector);
|
|
445
732
|
}
|
|
446
733
|
}
|
|
447
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
|
+
|
|
448
824
|
async function runSyncVectors(rootDir) {
|
|
449
825
|
ensureMemoryLayout(rootDir);
|
|
450
826
|
const vecFile = path.join(rootDir, "vectors.json");
|
|
451
827
|
const existingMap = new Map();
|
|
828
|
+
let prevCount = 0;
|
|
452
829
|
|
|
453
830
|
if (fs.existsSync(vecFile)) {
|
|
454
831
|
try {
|
|
455
832
|
const prev = JSON.parse(fs.readFileSync(vecFile, "utf8"));
|
|
833
|
+
prevCount = Array.isArray(prev) ? prev.length : 0;
|
|
456
834
|
for (const item of prev) {
|
|
457
835
|
if (item && item.id && Array.isArray(item.vector)) {
|
|
458
|
-
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
|
+
}
|
|
459
840
|
}
|
|
460
841
|
}
|
|
461
842
|
} catch {
|
|
@@ -466,25 +847,41 @@ async function runSyncVectors(rootDir) {
|
|
|
466
847
|
const parsed = parseTopicEntries(rootDir).concat(parseSessionEntries(rootDir));
|
|
467
848
|
let embeddedCount = 0;
|
|
468
849
|
let reusedCount = 0;
|
|
850
|
+
let metadataChanged = false;
|
|
469
851
|
|
|
470
852
|
for (const entry of parsed) {
|
|
471
|
-
const prev = existingMap.get(entry.id);
|
|
853
|
+
const prev = existingMap.get(entry.id + "::" + (entry.fact || "")) || existingMap.get(entry.id);
|
|
472
854
|
if (prev && prev.fact === entry.fact && prev.tags === entry.tags && Array.isArray(prev.vector)) {
|
|
473
855
|
entry.vector = prev.vector;
|
|
474
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
|
+
}
|
|
475
862
|
} else {
|
|
476
|
-
|
|
477
|
-
|
|
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
|
+
}
|
|
478
873
|
}
|
|
479
874
|
prepareEntryCacheFields(entry);
|
|
875
|
+
serializeEntryLine(entry);
|
|
480
876
|
}
|
|
481
877
|
|
|
482
|
-
const changed = embeddedCount > 0 || parsed.length !==
|
|
878
|
+
const changed = embeddedCount > 0 || metadataChanged || parsed.length !== prevCount;
|
|
483
879
|
if (changed || !fs.existsSync(vecFile)) {
|
|
484
|
-
|
|
880
|
+
writeVectorsAtomic(vecFile, serializeVectorsJson(parsed));
|
|
485
881
|
}
|
|
486
882
|
|
|
487
883
|
cachedEntries = parsed;
|
|
884
|
+
cachedCorpusStats = buildCorpusStats(parsed);
|
|
488
885
|
cachedRootDir = path.resolve(rootDir);
|
|
489
886
|
cachedMtime = fs.existsSync(vecFile) ? fs.statSync(vecFile).mtimeMs : Date.now();
|
|
490
887
|
cachedVersion++;
|
|
@@ -527,14 +924,43 @@ function loadCachedVectors(rootDir) {
|
|
|
527
924
|
const parsed = JSON.parse(fs.readFileSync(vecFile, "utf8"));
|
|
528
925
|
for (const item of parsed) {
|
|
529
926
|
prepareEntryCacheFields(item);
|
|
927
|
+
serializeEntryLine(item);
|
|
530
928
|
}
|
|
531
929
|
cachedEntries = parsed;
|
|
930
|
+
cachedCorpusStats = buildCorpusStats(parsed);
|
|
532
931
|
cachedRootDir = resolved;
|
|
533
932
|
cachedMtime = stat.mtimeMs;
|
|
534
933
|
cachedVersion++;
|
|
535
934
|
return cachedEntries;
|
|
536
935
|
}
|
|
537
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
|
+
|
|
538
964
|
function getTopicSlugs(rootDir) {
|
|
539
965
|
const resolved = path.resolve(rootDir);
|
|
540
966
|
if (cachedTopicSlugs && cachedTopicsRootDir === resolved) return cachedTopicSlugs;
|
|
@@ -555,20 +981,46 @@ function dotProduct(a, b) {
|
|
|
555
981
|
return sum;
|
|
556
982
|
}
|
|
557
983
|
|
|
558
|
-
async function searchMemory(rootDir, query, mode, topN) {
|
|
984
|
+
async function searchMemory(rootDir, query, mode, topN, options) {
|
|
559
985
|
const cleanQuery = String(query || "").trim();
|
|
560
986
|
if (!cleanQuery) return [];
|
|
561
987
|
const limit = Number(topN) || 8;
|
|
562
988
|
const searchMode = mode || "hybrid";
|
|
989
|
+
const opts = options || {};
|
|
990
|
+
const rawProject = String(opts.project || "").trim();
|
|
991
|
+
const includeGlobal = opts.includeGlobal !== false;
|
|
563
992
|
|
|
564
993
|
let entries = loadCachedVectors(rootDir);
|
|
565
994
|
if (entries.length === 0) {
|
|
566
995
|
await syncVectors(rootDir);
|
|
567
996
|
entries = loadCachedVectors(rootDir);
|
|
568
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
|
+
}
|
|
569
1020
|
|
|
570
|
-
const
|
|
571
|
-
const
|
|
1021
|
+
const rawTokens = tokenizeText(cleanQuery);
|
|
1022
|
+
const nonStopTokens = rawTokens.filter(function (t) { return !STOPWORDS.has(t); });
|
|
1023
|
+
const queryTokens = nonStopTokens.length > 0 ? nonStopTokens : rawTokens;
|
|
572
1024
|
|
|
573
1025
|
let queryVec = null;
|
|
574
1026
|
if (searchMode === "semantic" || searchMode === "hybrid") {
|
|
@@ -576,30 +1028,33 @@ async function searchMemory(rootDir, query, mode, topN) {
|
|
|
576
1028
|
queryVec = rawQueryVec instanceof Float32Array ? rawQueryVec : new Float32Array(rawQueryVec);
|
|
577
1029
|
}
|
|
578
1030
|
|
|
1031
|
+
const results = [];
|
|
579
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
|
+
|
|
580
1040
|
let semanticScore = 0;
|
|
581
1041
|
if (queryVec && (entry._vec || Array.isArray(entry.vector))) {
|
|
582
1042
|
semanticScore = dotProduct(queryVec, entry._vec || entry.vector);
|
|
583
1043
|
}
|
|
584
1044
|
|
|
585
|
-
|
|
586
|
-
const
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
for (const w of words) {
|
|
592
|
-
if (haystack.includes(w)) matched++;
|
|
593
|
-
}
|
|
594
|
-
lexicalScore = (matched / words.length) * 0.25;
|
|
595
|
-
}
|
|
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;
|
|
596
1051
|
|
|
597
1052
|
const score = searchMode === "grep"
|
|
598
1053
|
? lexicalScore
|
|
599
|
-
: (searchMode === "semantic" ? semanticScore : semanticScore + lexicalScore);
|
|
1054
|
+
: (searchMode === "semantic" ? semanticScore + projectBoost : semanticScore + lexicalScore + projectBoost);
|
|
600
1055
|
|
|
601
1056
|
if (searchMode === "grep" && lexicalScore === 0) continue;
|
|
602
|
-
results.push({ score: score, semanticScore: semanticScore, entry: entry });
|
|
1057
|
+
results.push({ score: score, semanticScore: semanticScore, lexicalScore: lexicalScore, entry: entry });
|
|
603
1058
|
}
|
|
604
1059
|
|
|
605
1060
|
results.sort(function (a, b) { return b.score - a.score; });
|
|
@@ -607,18 +1062,142 @@ async function searchMemory(rootDir, query, mode, topN) {
|
|
|
607
1062
|
}
|
|
608
1063
|
|
|
609
1064
|
function nextTopicId(topicText, topicSlug) {
|
|
1065
|
+
const normalized = String(topicText || "").replace(/\r\n/g, "\n");
|
|
610
1066
|
const re = /- id:\s*([a-z0-9-]+?)-(\d+)\s*$/gm;
|
|
1067
|
+
const existingIds = new Set();
|
|
611
1068
|
let maxNum = 0;
|
|
612
1069
|
let detectedPrefix = topicSlug;
|
|
613
1070
|
let m;
|
|
614
|
-
while ((m = re.exec(
|
|
1071
|
+
while ((m = re.exec(normalized)) !== null) {
|
|
1072
|
+
existingIds.add(m[1] + "-" + m[2]);
|
|
615
1073
|
const n = parseInt(m[2], 10);
|
|
616
1074
|
if (n > maxNum) {
|
|
617
1075
|
maxNum = n;
|
|
618
1076
|
detectedPrefix = m[1];
|
|
619
1077
|
}
|
|
620
1078
|
}
|
|
621
|
-
|
|
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
|
+
};
|
|
622
1201
|
}
|
|
623
1202
|
|
|
624
1203
|
async function storeMemoryFact(rootDir, input) {
|
|
@@ -631,9 +1210,39 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
631
1210
|
}
|
|
632
1211
|
ensureMemoryLayout(rootDir);
|
|
633
1212
|
const rawTopic = String(input.topic || "decisions").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
|
|
634
|
-
const
|
|
1213
|
+
const topicDir = path.join(rootDir, "topics");
|
|
1214
|
+
const topicFile = path.join(topicDir, rawTopic + ".md");
|
|
635
1215
|
const indexFile = path.join(rootDir, "memory.md");
|
|
636
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
|
+
|
|
637
1246
|
let existingText = "";
|
|
638
1247
|
if (fs.existsSync(topicFile)) {
|
|
639
1248
|
existingText = fs.readFileSync(topicFile, "utf8");
|
|
@@ -649,9 +1258,6 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
649
1258
|
}
|
|
650
1259
|
}
|
|
651
1260
|
|
|
652
|
-
const rawId = input.id
|
|
653
|
-
? String(input.id).replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "")
|
|
654
|
-
: "";
|
|
655
1261
|
const id = rawId || nextTopicId(existingText, rawTopic);
|
|
656
1262
|
const today = new Date().toISOString().split("T")[0];
|
|
657
1263
|
const rawTags = Array.isArray(input.tags)
|
|
@@ -659,21 +1265,32 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
659
1265
|
: String(input.tags || rawTopic).trim();
|
|
660
1266
|
const tagsList = rawTags.replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, " ").trim() || rawTopic;
|
|
661
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);
|
|
662
1270
|
|
|
663
|
-
const
|
|
1271
|
+
const blockLines = [
|
|
664
1272
|
"",
|
|
665
1273
|
"- id: " + id,
|
|
666
1274
|
" date: " + today,
|
|
667
|
-
" tags: [" + tagsList + "]"
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
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, "");
|
|
671
1284
|
|
|
672
|
-
fs.writeFileSync(topicFile, existingText.trimEnd() + "\n" +
|
|
1285
|
+
fs.writeFileSync(topicFile, existingText.trimEnd() + "\n" + blockLines.join("\n"), "utf8");
|
|
1286
|
+
parsedFileCache.delete(topicFile);
|
|
673
1287
|
|
|
674
1288
|
const vec = await embedText(cleanFact + " " + tagsList);
|
|
675
1289
|
const vecFile = path.join(rootDir, "vectors.json");
|
|
676
|
-
const
|
|
1290
|
+
const removeVecIds = new Set([id].concat(supersedesList));
|
|
1291
|
+
const entries = loadCachedVectors(rootDir).filter(function (e) {
|
|
1292
|
+
return !removeVecIds.has(e.id);
|
|
1293
|
+
});
|
|
677
1294
|
const newEntry = {
|
|
678
1295
|
id: id,
|
|
679
1296
|
date: today,
|
|
@@ -682,17 +1299,26 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
682
1299
|
fact: cleanFact,
|
|
683
1300
|
vector: vec
|
|
684
1301
|
};
|
|
1302
|
+
if (projectScope !== "global") newEntry.project = projectScope;
|
|
1303
|
+
if (isCore) newEntry.core = true;
|
|
685
1304
|
prepareEntryCacheFields(newEntry);
|
|
1305
|
+
serializeEntryLine(newEntry);
|
|
686
1306
|
entries.push(newEntry);
|
|
687
|
-
|
|
1307
|
+
writeVectorsAtomic(vecFile, serializeVectorsJson(entries));
|
|
688
1308
|
cachedEntries = entries;
|
|
1309
|
+
cachedCorpusStats = buildCorpusStats(entries);
|
|
689
1310
|
cachedRootDir = path.resolve(rootDir);
|
|
690
1311
|
cachedMtime = fs.statSync(vecFile).mtimeMs;
|
|
691
1312
|
cachedVersion++;
|
|
692
1313
|
cachedTopicSlugs = null;
|
|
693
1314
|
cachedTopicsRootDir = "";
|
|
694
1315
|
|
|
695
|
-
return newEntry
|
|
1316
|
+
return Object.assign({}, newEntry, {
|
|
1317
|
+
project: projectScope,
|
|
1318
|
+
core: isCore,
|
|
1319
|
+
updated: wasUpdated,
|
|
1320
|
+
superseded: supersededIds
|
|
1321
|
+
});
|
|
696
1322
|
}
|
|
697
1323
|
|
|
698
1324
|
async function storeSessionCheckpoint(rootDir, input) {
|
|
@@ -739,6 +1365,603 @@ async function storeSessionCheckpoint(rootDir, input) {
|
|
|
739
1365
|
return { filename: filename, filepath: filepath, checkpoint: numStr };
|
|
740
1366
|
}
|
|
741
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
|
+
|
|
742
1965
|
function extractLastUserText(messages) {
|
|
743
1966
|
if (!Array.isArray(messages)) return "";
|
|
744
1967
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -772,6 +1995,9 @@ function createPluginDefinition() {
|
|
|
772
1995
|
const rootDir = resolveMemoryDir(options.directory);
|
|
773
1996
|
const minScore = Number(options.minScore || 0.38);
|
|
774
1997
|
const topK = Number(options.topK || 6);
|
|
1998
|
+
const defaultProject = (ctx && ctx.location && ctx.location.directory)
|
|
1999
|
+
? ctx.location.directory
|
|
2000
|
+
: (options.project || "global");
|
|
775
2001
|
|
|
776
2002
|
loadCachedVectors(rootDir);
|
|
777
2003
|
syncVectors(rootDir).catch(function (err) {
|
|
@@ -784,7 +2010,7 @@ function createPluginDefinition() {
|
|
|
784
2010
|
const toolReg = await ctx.tool.transform(function (editor) {
|
|
785
2011
|
editor.add({
|
|
786
2012
|
name: "memory_store",
|
|
787
|
-
description: "Atomically store a persistent memory 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.",
|
|
788
2014
|
input: {
|
|
789
2015
|
type: "object",
|
|
790
2016
|
properties: {
|
|
@@ -802,7 +2028,19 @@ function createPluginDefinition() {
|
|
|
802
2028
|
},
|
|
803
2029
|
id: {
|
|
804
2030
|
type: "string",
|
|
805
|
-
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"
|
|
806
2044
|
}
|
|
807
2045
|
},
|
|
808
2046
|
required: ["topic", "tags", "fact"],
|
|
@@ -810,15 +2048,52 @@ function createPluginDefinition() {
|
|
|
810
2048
|
},
|
|
811
2049
|
execute: async function (input) {
|
|
812
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(", ") + ")" : "";
|
|
2057
|
+
return {
|
|
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(", ") + ")" : "";
|
|
813
2088
|
return {
|
|
814
|
-
content: "
|
|
2089
|
+
content: "Deleted " + summary + " and updated vectors.json" + missing + "."
|
|
815
2090
|
};
|
|
816
2091
|
}
|
|
817
2092
|
});
|
|
818
2093
|
|
|
819
2094
|
editor.add({
|
|
820
2095
|
name: "memory_search",
|
|
821
|
-
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.",
|
|
822
2097
|
input: {
|
|
823
2098
|
type: "object",
|
|
824
2099
|
properties: {
|
|
@@ -834,18 +2109,33 @@ function createPluginDefinition() {
|
|
|
834
2109
|
topN: {
|
|
835
2110
|
type: "number",
|
|
836
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"
|
|
837
2120
|
}
|
|
838
2121
|
},
|
|
839
2122
|
required: ["query"],
|
|
840
2123
|
additionalProperties: false
|
|
841
2124
|
},
|
|
842
2125
|
execute: async function (input) {
|
|
843
|
-
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
|
+
});
|
|
844
2130
|
if (hits.length === 0) {
|
|
845
2131
|
return { content: "No matching memory entries found." };
|
|
846
2132
|
}
|
|
847
2133
|
const formatted = hits.map(function (h) {
|
|
848
|
-
|
|
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 + ")";
|
|
849
2139
|
}).join("\n");
|
|
850
2140
|
return { content: formatted };
|
|
851
2141
|
}
|
|
@@ -894,8 +2184,9 @@ function createPluginDefinition() {
|
|
|
894
2184
|
|
|
895
2185
|
if (ctx && ctx.session && typeof ctx.session.hook === "function") {
|
|
896
2186
|
const ctxReg = await ctx.session.hook("context", async function (event) {
|
|
2187
|
+
const activeProject = (event && event.directory) || defaultProject || "global";
|
|
897
2188
|
const userText = extractLastUserText(event.messages);
|
|
898
|
-
const ctxKey = String(userText || "").trim() + "::" + cachedVersion;
|
|
2189
|
+
const ctxKey = String(userText || "").trim() + "::" + normalizeProjectScope(activeProject) + "::" + cachedVersion;
|
|
899
2190
|
if (ctxKey === lastContextKey && lastContextText) {
|
|
900
2191
|
if (Array.isArray(event.system)) {
|
|
901
2192
|
event.system.push({ type: "text", text: lastContextText });
|
|
@@ -909,27 +2200,40 @@ function createPluginDefinition() {
|
|
|
909
2200
|
"Persistent memory (`opencode-local-memory`) is active at: " + rootDir,
|
|
910
2201
|
"Available topics: " + (topicSlugs.join(", ") || "preferences, decisions, environment, agent-behavior") + " (or pass any new topic slug to create a new file).",
|
|
911
2202
|
"",
|
|
912
|
-
"AUTOMATIC STORAGE (via `memory_store`
|
|
2203
|
+
"AUTOMATIC STORAGE (via `memory_store` / `memory_delete` tools — no prompting needed):",
|
|
913
2204
|
"Call `memory_store` immediately in the SAME turn before your final response whenever any of these happen:",
|
|
914
2205
|
"- User states a preference, convention, or 'always/never do X' rule",
|
|
915
2206
|
"- An architecture, workflow, or design decision is made (yours or theirs)",
|
|
916
2207
|
"- A non-obvious environment, path, port, or tooling fact is discovered",
|
|
917
2208
|
"- A recurring correction or pattern emerges",
|
|
918
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.",
|
|
919
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.",
|
|
920
2212
|
"",
|
|
921
2213
|
"WHERE TO STORE:",
|
|
922
|
-
"- Global (`memory_store`
|
|
923
|
-
"- Project (`AGENTS.md` in repo root):
|
|
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.",
|
|
924
2216
|
"",
|
|
925
2217
|
"AUTOMATIC RECALL & CHECKPOINTS:",
|
|
926
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'`).",
|
|
927
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`."
|
|
928
2220
|
];
|
|
929
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
|
+
|
|
930
2232
|
if (userText && userText.trim().length >= 5) {
|
|
931
|
-
const hits = await searchMemory(rootDir, userText, "hybrid", topK).catch(function () { return []; });
|
|
932
|
-
const relevant = hits.filter(function (h) {
|
|
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
|
+
});
|
|
933
2237
|
if (relevant.length > 0) {
|
|
934
2238
|
lines.push("Auto-recalled memories for this prompt:");
|
|
935
2239
|
for (const h of relevant) {
|
|
@@ -982,40 +2286,90 @@ export {
|
|
|
982
2286
|
server,
|
|
983
2287
|
resolveMemoryDir,
|
|
984
2288
|
resolveConfigDir,
|
|
2289
|
+
resolveDbPath,
|
|
985
2290
|
ensureMemoryLayout,
|
|
986
2291
|
installPlugin,
|
|
2292
|
+
importExistingMemory,
|
|
2293
|
+
parseAgentsMarkdownRules,
|
|
987
2294
|
parseTopicEntries,
|
|
988
2295
|
parseSessionEntries,
|
|
989
2296
|
nextTopicId,
|
|
990
2297
|
getTopicSlugs,
|
|
2298
|
+
getCoreMemories,
|
|
2299
|
+
isUmbrellaProject,
|
|
2300
|
+
normalizeProjectScope,
|
|
2301
|
+
getProjectLeaf,
|
|
2302
|
+
matchesProjectScope,
|
|
2303
|
+
detectProjectsFromText,
|
|
2304
|
+
computeLexicalScore,
|
|
991
2305
|
loadCachedVectors,
|
|
992
2306
|
syncVectors,
|
|
993
2307
|
searchMemory,
|
|
994
2308
|
storeMemoryFact,
|
|
2309
|
+
deleteMemoryEntry,
|
|
995
2310
|
storeSessionCheckpoint
|
|
996
2311
|
};
|
|
997
2312
|
|
|
998
2313
|
const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
|
|
999
2314
|
if (isDirectRun) {
|
|
1000
2315
|
const cmd = process.argv[2] || "sync";
|
|
1001
|
-
|
|
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);
|
|
1002
2329
|
|
|
1003
2330
|
if (cmd === "install" || cmd === "init" || cmd === "setup") {
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
2331
|
+
installPlugin({
|
|
2332
|
+
directory: customDir || undefined,
|
|
2333
|
+
importExisting: withImport,
|
|
2334
|
+
dbPath: customDb,
|
|
2335
|
+
agentsFiles: customAgents,
|
|
2336
|
+
limit: customLimit
|
|
2337
|
+
}).then(function (res) {
|
|
1010
2338
|
console.log("opencode-local-memory installed:");
|
|
1011
2339
|
console.log(" Server config: " + res.serverConfigFile + " (" + res.serverStatus + ")");
|
|
1012
2340
|
console.log(" TUI config: " + res.cliConfigFile + " (" + res.cliStatus + ")");
|
|
1013
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
|
+
}
|
|
1014
2349
|
console.log(" Vectors cache: " + res.syncResult.vecFile + " (" + res.syncResult.total + " entries ready)");
|
|
1015
2350
|
}).catch(function (err) {
|
|
1016
2351
|
console.error("Install failed:", err);
|
|
1017
2352
|
process.exit(1);
|
|
1018
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
|
+
});
|
|
1019
2373
|
} else if (cmd === "sync" || cmd === "embed") {
|
|
1020
2374
|
syncVectors(rootDir).then(function (res) {
|
|
1021
2375
|
console.log("Synced " + res.total + " memory entries (" + res.embedded + " newly embedded, " + res.reused + " cached) -> " + res.vecFile);
|
|
@@ -1045,5 +2399,13 @@ if (isDirectRun) {
|
|
|
1045
2399
|
console.error("Store failed:", err);
|
|
1046
2400
|
process.exit(1);
|
|
1047
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
|
+
});
|
|
1048
2410
|
}
|
|
1049
2411
|
}
|