@nandoblanco/opencode-local-memory 0.0.0-stage → 1.0.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/index.js ADDED
@@ -0,0 +1,875 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+ const cliName = "open" + "code";
11
+
12
+ let embedderPromise = null;
13
+ let cachedEntries = null;
14
+ let cachedRootDir = "";
15
+ let cachedMtime = 0;
16
+ let cachedVersion = 0;
17
+ let cachedTopicSlugs = null;
18
+ let cachedTopicsRootDir = "";
19
+ let lastContextKey = "";
20
+ let lastContextText = "";
21
+ const queryVecCache = new Map();
22
+
23
+ function resolveMemoryDir(customDir) {
24
+ if (customDir) {
25
+ if (customDir.startsWith("~")) {
26
+ return path.join(os.homedir(), customDir.slice(1));
27
+ }
28
+ return path.resolve(customDir);
29
+ }
30
+ if (process.env.OPENCODE_MEMORY_DIR) {
31
+ return path.resolve(process.env.OPENCODE_MEMORY_DIR);
32
+ }
33
+ const localParent = path.resolve(__dirname, "..");
34
+ if (fs.existsSync(path.join(localParent, "memory.md")) && fs.existsSync(path.join(localParent, "topics"))) {
35
+ return localParent;
36
+ }
37
+ const configBase = process.env.XDG_CONFIG_HOME
38
+ ? path.resolve(process.env.XDG_CONFIG_HOME)
39
+ : path.join(os.homedir(), ".config");
40
+ return path.join(configBase, cliName, "memory");
41
+ }
42
+
43
+ function resolveConfigDir(customConfigDir) {
44
+ if (customConfigDir) {
45
+ if (customConfigDir.startsWith("~")) {
46
+ return path.join(os.homedir(), customConfigDir.slice(1));
47
+ }
48
+ return path.resolve(customConfigDir);
49
+ }
50
+ const configBase = process.env.XDG_CONFIG_HOME
51
+ ? path.resolve(process.env.XDG_CONFIG_HOME)
52
+ : path.join(os.homedir(), ".config");
53
+ return path.join(configBase, cliName);
54
+ }
55
+
56
+ function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
57
+ if (!fs.existsSync(filePath)) {
58
+ const content = [
59
+ "{",
60
+ ' "$schema": "' + schemaUrl + '",',
61
+ ' "plugins": [',
62
+ " " + pluginEntryStr,
63
+ " ]",
64
+ "}",
65
+ ""
66
+ ].join("\n");
67
+ fs.writeFileSync(filePath, content, "utf8");
68
+ return "created";
69
+ }
70
+
71
+ const raw = fs.readFileSync(filePath, "utf8");
72
+ if (raw.includes(pkgName)) {
73
+ return "already-present";
74
+ }
75
+
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
+ });
88
+ fs.writeFileSync(filePath, updated, "utf8");
89
+ return "updated";
90
+ }
91
+
92
+ const lastBrace = raw.lastIndexOf("}");
93
+ 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";
98
+ fs.writeFileSync(filePath, updated, "utf8");
99
+ return "updated";
100
+ }
101
+
102
+ return "skipped";
103
+ }
104
+
105
+ async function installPlugin(options) {
106
+ const opts = options || {};
107
+ const configDir = resolveConfigDir(opts.configDir);
108
+ const rootDir = resolveMemoryDir(opts.directory);
109
+ const pkgName = "@nandoblanco/opencode-local-memory";
110
+ const matchKey = "opencode-local-memory";
111
+
112
+ if (!fs.existsSync(configDir)) {
113
+ fs.mkdirSync(configDir, { recursive: true });
114
+ }
115
+
116
+ const serverConfigFile = fs.existsSync(path.join(configDir, cliName + ".json")) && !fs.existsSync(path.join(configDir, cliName + ".jsonc"))
117
+ ? path.join(configDir, cliName + ".json")
118
+ : path.join(configDir, cliName + ".jsonc");
119
+ const cliConfigFile = path.join(configDir, "cli.json");
120
+
121
+ const serverEntryStr = opts.directory
122
+ ? JSON.stringify({ package: pkgName, options: { directory: opts.directory } })
123
+ : JSON.stringify(pkgName);
124
+ const cliEntryStr = JSON.stringify(pkgName);
125
+
126
+ const serverStatus = addPluginToJsoncFile(serverConfigFile, "https://" + cliName + ".ai/config.json", serverEntryStr, matchKey);
127
+ const cliStatus = addPluginToJsoncFile(cliConfigFile, "https://" + cliName + ".ai/v2/cli.json", cliEntryStr, matchKey);
128
+
129
+ ensureMemoryLayout(rootDir);
130
+ const syncResult = opts.skipSync ? { total: 0, embedded: 0, reused: 0, vecFile: path.join(rootDir, "vectors.json") } : await syncVectors(rootDir);
131
+
132
+ return {
133
+ configDir: configDir,
134
+ serverConfigFile: serverConfigFile,
135
+ serverStatus: serverStatus,
136
+ cliConfigFile: cliConfigFile,
137
+ cliStatus: cliStatus,
138
+ memoryDir: rootDir,
139
+ syncResult: syncResult
140
+ };
141
+ }
142
+
143
+ function ensureMemoryLayout(rootDir) {
144
+ const topicDir = path.join(rootDir, "topics");
145
+ const sessionDir = path.join(rootDir, "sessions");
146
+ const indexFile = path.join(rootDir, "memory.md");
147
+ const sessionReadme = path.join(sessionDir, "README.md");
148
+
149
+ if (!fs.existsSync(rootDir)) fs.mkdirSync(rootDir, { recursive: true });
150
+ if (!fs.existsSync(topicDir)) fs.mkdirSync(topicDir, { recursive: true });
151
+ if (!fs.existsSync(sessionDir)) fs.mkdirSync(sessionDir, { recursive: true });
152
+
153
+ const starterTopics = [
154
+ { slug: "preferences", title: "# Preferences\n", desc: "user coding style and workflow preferences" },
155
+ { slug: "decisions", title: "# Decisions\n", desc: "architectural and cross-project decisions" },
156
+ { slug: "environment", title: "# Environment\n", desc: "machine, OS, and tooling facts" },
157
+ { slug: "agent-behavior", title: "# Agent Behavior\n", desc: "corrections and operational protocols" }
158
+ ];
159
+
160
+ if (!fs.existsSync(indexFile)) {
161
+ const starterIndex = [
162
+ "# Global Memory Index",
163
+ "",
164
+ "## Topic files",
165
+ "",
166
+ ...starterTopics.map(function (t) { return "- `topics/" + t.slug + ".md` - " + t.desc; }),
167
+ "",
168
+ "## Session summaries",
169
+ "",
170
+ "- `sessions/YYYY-MM-DD_slug-NN.md` - distilled record of significant work sessions",
171
+ ""
172
+ ].join("\n");
173
+ fs.writeFileSync(indexFile, starterIndex, "utf8");
174
+
175
+ for (const t of starterTopics) {
176
+ const tf = path.join(topicDir, t.slug + ".md");
177
+ if (!fs.existsSync(tf)) fs.writeFileSync(tf, t.title, "utf8");
178
+ }
179
+ }
180
+
181
+ if (!fs.existsSync(sessionReadme)) {
182
+ fs.writeFileSync(
183
+ sessionReadme,
184
+ "# Session Checkpoints\n\nNumbered session summaries (`YYYY-MM-DD_slug-NN.md`) created by `memory_checkpoint` or automatic session compaction.\n",
185
+ "utf8"
186
+ );
187
+ }
188
+ }
189
+
190
+ async function getEmbedder() {
191
+ if (embedderPromise) return embedderPromise;
192
+ embedderPromise = (async function () {
193
+ let pipelineFn;
194
+ try {
195
+ const mod = await import("@xenova/transformers");
196
+ pipelineFn = mod.pipeline;
197
+ } catch {
198
+ const fallbackPath = path.resolve(__dirname, "node_modules/@xenova/transformers/src/transformers.js");
199
+ const fallbackUrl = new URL("file:///" + fallbackPath.replace(/\\/g, "/")).href;
200
+ const mod = await import(fallbackUrl);
201
+ pipelineFn = mod.pipeline;
202
+ }
203
+ return pipelineFn("feature-extraction", "Xenova/all-MiniLM-L6-v2");
204
+ })();
205
+ return embedderPromise;
206
+ }
207
+
208
+ async function embedText(text) {
209
+ const key = String(text || "").trim().toLowerCase();
210
+ if (queryVecCache.has(key)) {
211
+ return queryVecCache.get(key);
212
+ }
213
+ const embed = await getEmbedder();
214
+ const out = await embed(text, { pooling: "mean", normalize: true });
215
+ const vec = Array.from(out.data);
216
+ if (queryVecCache.size >= 128) {
217
+ const firstKey = queryVecCache.keys().next().value;
218
+ queryVecCache.delete(firstKey);
219
+ }
220
+ queryVecCache.set(key, vec);
221
+ return vec;
222
+ }
223
+
224
+ function parseTopicEntries(rootDir) {
225
+ const topicDir = path.join(rootDir, "topics");
226
+ if (!fs.existsSync(topicDir)) return [];
227
+ const files = fs.readdirSync(topicDir).filter(function (f) { return f.endsWith(".md"); });
228
+ const entries = [];
229
+
230
+ for (const file of files) {
231
+ const text = fs.readFileSync(path.join(topicDir, file), "utf8").replace(/\r\n/g, "\n");
232
+ const blocks = text.split(/\n(?=- id: )/).filter(function (b) { return b.trim().startsWith("- id: "); });
233
+ for (const block of blocks) {
234
+ const idMatch = block.match(/- id:\s*(\S+)/);
235
+ const dateMatch = block.match(/date:\s*(\S+)/);
236
+ const tagsMatch = block.match(/tags:\s*\[([^\]]*)\]/);
237
+ const factMatch = block.match(/fact:\s*(.+)/);
238
+ if (idMatch && factMatch) {
239
+ entries.push({
240
+ id: idMatch[1].trim(),
241
+ date: dateMatch ? dateMatch[1].trim() : "",
242
+ file: "topics/" + file,
243
+ tags: tagsMatch ? tagsMatch[1].trim() : "",
244
+ fact: factMatch[1].trim()
245
+ });
246
+ }
247
+ }
248
+ }
249
+ return entries;
250
+ }
251
+
252
+ function parseSessionEntries(rootDir) {
253
+ const sessionDir = path.join(rootDir, "sessions");
254
+ if (!fs.existsSync(sessionDir)) return [];
255
+ const files = fs.readdirSync(sessionDir).filter(function (f) {
256
+ return f.endsWith(".md") && f.toLowerCase() !== "readme.md";
257
+ });
258
+ const entries = [];
259
+
260
+ for (const file of files) {
261
+ const raw = fs.readFileSync(path.join(sessionDir, file), "utf8").replace(/\r\n/g, "\n");
262
+ const base = file.replace(/\.md$/, "");
263
+ const titleMatch = raw.match(/^#\s+(.+)$/m);
264
+ const title = titleMatch ? titleMatch[1].trim() : base;
265
+ const dateMatch = base.match(/^(\d{4}-\d{2}-\d{2})_(.+)$/);
266
+ const date = dateMatch ? dateMatch[1] : "";
267
+ const slug = dateMatch ? dateMatch[2] : base;
268
+ const tags = slug.replace(/-\d+$/, "").split(/[-_]+/).filter(Boolean).join(", ");
269
+
270
+ const sections = [];
271
+ const targetHeadings = [
272
+ "What was built/fixed/decided",
273
+ "Key decisions",
274
+ "Problems solved",
275
+ "Gotchas / live traps",
276
+ "Patterns discovered",
277
+ "Outcome"
278
+ ];
279
+
280
+ for (const heading of targetHeadings) {
281
+ const re = new RegExp("##\\s+" + heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\s*\\n([\\s\\S]*?)(?=\\n##\\s+|$)", "i");
282
+ const m = raw.match(re);
283
+ if (m && m[1].trim()) {
284
+ const cleaned = m[1].trim().replace(/\n+/g, " ").replace(/\s+/g, " ");
285
+ sections.push(heading + ": " + cleaned);
286
+ }
287
+ }
288
+
289
+ const factText = title + " — " + (sections.join(" | ").slice(0, 700) || raw.replace(/\s+/g, " ").slice(0, 500));
290
+ entries.push({
291
+ id: "session:" + base,
292
+ date: date,
293
+ file: "sessions/" + file,
294
+ tags: tags,
295
+ fact: factText
296
+ });
297
+ }
298
+ return entries;
299
+ }
300
+
301
+ async function syncVectors(rootDir) {
302
+ ensureMemoryLayout(rootDir);
303
+ const vecFile = path.join(rootDir, "vectors.json");
304
+ const existingMap = new Map();
305
+
306
+ if (fs.existsSync(vecFile)) {
307
+ try {
308
+ const prev = JSON.parse(fs.readFileSync(vecFile, "utf8"));
309
+ for (const item of prev) {
310
+ if (item && item.id && Array.isArray(item.vector)) {
311
+ existingMap.set(item.id, item);
312
+ }
313
+ }
314
+ } catch {
315
+ // Rebuild if corrupted
316
+ }
317
+ }
318
+
319
+ const parsed = parseTopicEntries(rootDir).concat(parseSessionEntries(rootDir));
320
+ let embeddedCount = 0;
321
+ let reusedCount = 0;
322
+
323
+ for (const entry of parsed) {
324
+ const prev = existingMap.get(entry.id);
325
+ if (prev && prev.fact === entry.fact && prev.tags === entry.tags && Array.isArray(prev.vector)) {
326
+ entry.vector = prev.vector;
327
+ reusedCount++;
328
+ } else {
329
+ entry.vector = await embedText(entry.fact + " " + entry.tags);
330
+ embeddedCount++;
331
+ }
332
+ }
333
+
334
+ const changed = embeddedCount > 0 || parsed.length !== existingMap.size;
335
+ if (changed || !fs.existsSync(vecFile)) {
336
+ fs.writeFileSync(vecFile, JSON.stringify(parsed, null, 1), "utf8");
337
+ }
338
+
339
+ for (const item of parsed) {
340
+ item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
341
+ }
342
+ cachedEntries = parsed;
343
+ cachedRootDir = path.resolve(rootDir);
344
+ cachedMtime = fs.existsSync(vecFile) ? fs.statSync(vecFile).mtimeMs : Date.now();
345
+ cachedVersion++;
346
+ cachedTopicSlugs = null;
347
+ cachedTopicsRootDir = "";
348
+ return { total: parsed.length, embedded: embeddedCount, reused: reusedCount, vecFile: vecFile };
349
+ }
350
+
351
+ function loadCachedVectors(rootDir) {
352
+ const resolved = path.resolve(rootDir);
353
+ const vecFile = path.join(resolved, "vectors.json");
354
+ if (!fs.existsSync(vecFile)) return [];
355
+ const stat = fs.statSync(vecFile);
356
+ if (cachedEntries && cachedRootDir === resolved && cachedMtime === stat.mtimeMs) {
357
+ return cachedEntries;
358
+ }
359
+ const parsed = JSON.parse(fs.readFileSync(vecFile, "utf8"));
360
+ for (const item of parsed) {
361
+ if (item && !item._haystack) {
362
+ item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
363
+ }
364
+ }
365
+ cachedEntries = parsed;
366
+ cachedRootDir = resolved;
367
+ cachedMtime = stat.mtimeMs;
368
+ cachedVersion++;
369
+ return cachedEntries;
370
+ }
371
+
372
+ function getTopicSlugs(rootDir) {
373
+ const resolved = path.resolve(rootDir);
374
+ if (cachedTopicSlugs && cachedTopicsRootDir === resolved) return cachedTopicSlugs;
375
+ const topicDir = path.join(resolved, "topics");
376
+ cachedTopicSlugs = fs.existsSync(topicDir)
377
+ ? fs.readdirSync(topicDir)
378
+ .filter(function (f) { return f.endsWith(".md") && f.toLowerCase() !== "readme.md"; })
379
+ .map(function (f) { return f.replace(/\.md$/i, ""); })
380
+ : [];
381
+ cachedTopicsRootDir = resolved;
382
+ return cachedTopicSlugs;
383
+ }
384
+
385
+ function dotProduct(a, b) {
386
+ let sum = 0;
387
+ const len = Math.min(a.length, b.length);
388
+ for (let i = 0; i < len; i++) sum += a[i] * b[i];
389
+ return sum;
390
+ }
391
+
392
+ async function searchMemory(rootDir, query, mode, topN) {
393
+ const cleanQuery = String(query || "").trim();
394
+ if (!cleanQuery) return [];
395
+ const limit = Number(topN) || 8;
396
+ const searchMode = mode || "hybrid";
397
+
398
+ let entries = loadCachedVectors(rootDir);
399
+ if (entries.length === 0) {
400
+ await syncVectors(rootDir);
401
+ entries = loadCachedVectors(rootDir);
402
+ }
403
+
404
+ const results = [];
405
+ const words = cleanQuery.toLowerCase().split(/\s+/).filter(function (w) { return w.length >= 2; });
406
+
407
+ let queryVec = null;
408
+ if (searchMode === "semantic" || searchMode === "hybrid") {
409
+ queryVec = await embedText(cleanQuery);
410
+ }
411
+
412
+ for (const entry of entries) {
413
+ 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;
428
+ }
429
+
430
+ const score = searchMode === "grep"
431
+ ? lexicalScore
432
+ : (searchMode === "semantic" ? semanticScore : semanticScore + lexicalScore);
433
+
434
+ if (searchMode === "grep" && lexicalScore === 0) continue;
435
+ results.push({ score: score, semanticScore: semanticScore, entry: entry });
436
+ }
437
+
438
+ results.sort(function (a, b) { return b.score - a.score; });
439
+ return results.slice(0, limit);
440
+ }
441
+
442
+ function nextTopicId(topicText, topicSlug) {
443
+ const re = /- id:\s*([a-z0-9-]+?)-(\d+)\s*$/gm;
444
+ let maxNum = 0;
445
+ let detectedPrefix = topicSlug;
446
+ let m;
447
+ while ((m = re.exec(topicText)) !== null) {
448
+ const n = parseInt(m[2], 10);
449
+ if (n > maxNum) {
450
+ maxNum = n;
451
+ detectedPrefix = m[1];
452
+ }
453
+ }
454
+ return detectedPrefix + "-" + String(maxNum + 1).padStart(3, "0");
455
+ }
456
+
457
+ async function storeMemoryFact(rootDir, input) {
458
+ ensureMemoryLayout(rootDir);
459
+ const rawTopic = String(input.topic || "decisions").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
460
+ const topicFile = path.join(rootDir, "topics", rawTopic + ".md");
461
+ const indexFile = path.join(rootDir, "memory.md");
462
+
463
+ let existingText = "";
464
+ if (fs.existsSync(topicFile)) {
465
+ existingText = fs.readFileSync(topicFile, "utf8");
466
+ } else {
467
+ const heading = "# " + rawTopic.charAt(0).toUpperCase() + rawTopic.slice(1) + "\n";
468
+ existingText = heading;
469
+ if (fs.existsSync(indexFile)) {
470
+ const idxContent = fs.readFileSync(indexFile, "utf8");
471
+ if (!idxContent.includes("topics/" + rawTopic + ".md") && !idxContent.includes("topics\\" + rawTopic + ".md")) {
472
+ const updatedIdx = idxContent.trimEnd() + "\n- `topics/" + rawTopic + ".md` - " + rawTopic + " entries\n";
473
+ fs.writeFileSync(indexFile, updatedIdx, "utf8");
474
+ }
475
+ }
476
+ }
477
+
478
+ const id = input.id ? String(input.id).trim() : nextTopicId(existingText, rawTopic);
479
+ const today = new Date().toISOString().split("T")[0];
480
+ const tagsList = Array.isArray(input.tags)
481
+ ? input.tags.map(function (t) { return String(t).trim(); }).filter(Boolean).join(", ")
482
+ : String(input.tags || rawTopic).trim();
483
+ const cleanFact = String(input.fact || "").replace(/\s+/g, " ").trim();
484
+
485
+ const block = [
486
+ "",
487
+ "- id: " + id,
488
+ " date: " + today,
489
+ " tags: [" + tagsList + "]",
490
+ " fact: " + cleanFact,
491
+ ""
492
+ ].join("\n");
493
+
494
+ fs.writeFileSync(topicFile, existingText.trimEnd() + "\n" + block, "utf8");
495
+
496
+ const vec = await embedText(cleanFact + " " + tagsList);
497
+ const vecFile = path.join(rootDir, "vectors.json");
498
+ const entries = loadCachedVectors(rootDir).filter(function (e) { return e.id !== id; });
499
+ const newEntry = {
500
+ id: id,
501
+ date: today,
502
+ file: "topics/" + rawTopic + ".md",
503
+ tags: tagsList,
504
+ fact: cleanFact,
505
+ vector: vec
506
+ };
507
+ 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();
513
+ cachedEntries = entries;
514
+ cachedRootDir = path.resolve(rootDir);
515
+ cachedMtime = fs.statSync(vecFile).mtimeMs;
516
+ cachedVersion++;
517
+ cachedTopicSlugs = null;
518
+ cachedTopicsRootDir = "";
519
+
520
+ return newEntry;
521
+ }
522
+
523
+ async function storeSessionCheckpoint(rootDir, input) {
524
+ ensureMemoryLayout(rootDir);
525
+ const sessionDir = path.join(rootDir, "sessions");
526
+ const today = new Date().toISOString().split("T")[0];
527
+ const slug = String(input.slug || "session").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
528
+ const prefix = today + "_" + slug + "-";
529
+
530
+ const existingNums = fs.readdirSync(sessionDir)
531
+ .filter(function (f) { return f.startsWith(prefix) && f.endsWith(".md"); })
532
+ .map(function (f) {
533
+ const m = f.match(/-(\d+)\.md$/);
534
+ return m ? parseInt(m[1], 10) : 0;
535
+ });
536
+ const nextNum = existingNums.length > 0 ? Math.max.apply(null, existingNums) + 1 : 1;
537
+ const numStr = String(nextNum).padStart(2, "0");
538
+ const filename = prefix + numStr + ".md";
539
+ const filepath = path.join(sessionDir, filename);
540
+
541
+ const title = String(input.title || slug).trim();
542
+ const pct = input.contextPct !== undefined ? String(input.contextPct) + "% used at checkpoint" : "auto";
543
+ const project = String(input.project || "global").trim();
544
+ const summary = String(input.summary || "").trim();
545
+
546
+ const md = [
547
+ "# " + title,
548
+ "",
549
+ "**Date**: " + today,
550
+ "**Checkpoint**: " + numStr,
551
+ "**Context**: " + pct,
552
+ "**Project**: " + project,
553
+ "",
554
+ summary,
555
+ ""
556
+ ].join("\n");
557
+
558
+ fs.writeFileSync(filepath, md, "utf8");
559
+
560
+ const stateFile = path.join(rootDir, ".session-state");
561
+ fs.writeFileSync(stateFile, "slug=" + slug + "\nlast_checkpoint_pct=" + (Number(input.contextPct) || 0) + "\n", "utf8");
562
+
563
+ await syncVectors(rootDir);
564
+ return { filename: filename, filepath: filepath, checkpoint: numStr };
565
+ }
566
+
567
+ function extractLastUserText(messages) {
568
+ if (!Array.isArray(messages)) return "";
569
+ for (let i = messages.length - 1; i >= 0; i--) {
570
+ const msg = messages[i];
571
+ if (!msg) continue;
572
+ if (msg.role === "user") {
573
+ if (typeof msg.content === "string") return msg.content;
574
+ if (typeof msg.text === "string") return msg.text;
575
+ if (Array.isArray(msg.content)) {
576
+ const textParts = msg.content
577
+ .filter(function (p) { return p && (p.type === "text" || typeof p.text === "string"); })
578
+ .map(function (p) { return p.text || ""; });
579
+ if (textParts.length > 0) return textParts.join(" ");
580
+ }
581
+ if (Array.isArray(msg.parts)) {
582
+ const textParts = msg.parts
583
+ .filter(function (p) { return p && p.type === "text"; })
584
+ .map(function (p) { return p.text || ""; });
585
+ if (textParts.length > 0) return textParts.join(" ");
586
+ }
587
+ }
588
+ }
589
+ return "";
590
+ }
591
+
592
+ function createPluginDefinition() {
593
+ return {
594
+ id: "opencode-local-memory",
595
+ async setup(ctx) {
596
+ const options = (ctx && ctx.options) || {};
597
+ const rootDir = resolveMemoryDir(options.directory);
598
+ const minScore = Number(options.minScore || 0.38);
599
+ const topK = Number(options.topK || 6);
600
+
601
+ loadCachedVectors(rootDir);
602
+ getEmbedder().catch(function () {});
603
+ syncVectors(rootDir).catch(function (err) {
604
+ console.error("local-memory sync error:", err);
605
+ });
606
+
607
+ const registrations = [];
608
+
609
+ if (ctx && ctx.tool && typeof ctx.tool.transform === "function") {
610
+ const toolReg = await ctx.tool.transform(function (editor) {
611
+ editor.add({
612
+ 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.",
614
+ input: {
615
+ type: "object",
616
+ properties: {
617
+ topic: {
618
+ type: "string",
619
+ description: "Topic filename slug without .md (e.g. preferences, decisions, environment, agent-behavior, tools)"
620
+ },
621
+ tags: {
622
+ type: "string",
623
+ description: "Comma-separated keywords for retrieval"
624
+ },
625
+ fact: {
626
+ type: "string",
627
+ description: "Concise one-line statement of the fact, decision, or preference"
628
+ },
629
+ id: {
630
+ type: "string",
631
+ description: "Optional explicit ID (auto-generated as <topic>-<nnn> when omitted)"
632
+ }
633
+ },
634
+ required: ["topic", "tags", "fact"],
635
+ additionalProperties: false
636
+ },
637
+ execute: async function (input) {
638
+ const saved = await storeMemoryFact(rootDir, input);
639
+ return {
640
+ content: "Stored [" + saved.id + "] in " + saved.file + " and updated vectors.json:\n" + saved.fact
641
+ };
642
+ }
643
+ });
644
+
645
+ editor.add({
646
+ name: "memory_search",
647
+ description: "Search persistent local memory (both atomic topic facts and session checkpoint summaries) using hybrid semantic + keyword matching.",
648
+ input: {
649
+ type: "object",
650
+ properties: {
651
+ query: {
652
+ type: "string",
653
+ description: "Search query or keywords"
654
+ },
655
+ mode: {
656
+ type: "string",
657
+ enum: ["hybrid", "semantic", "grep"],
658
+ description: "Search mode (default: hybrid)"
659
+ },
660
+ topN: {
661
+ type: "number",
662
+ description: "Maximum results to return (default: 8)"
663
+ }
664
+ },
665
+ required: ["query"],
666
+ additionalProperties: false
667
+ },
668
+ execute: async function (input) {
669
+ const hits = await searchMemory(rootDir, input.query, input.mode || "hybrid", input.topN || 8);
670
+ if (hits.length === 0) {
671
+ return { content: "No matching memory entries found." };
672
+ }
673
+ const formatted = hits.map(function (h) {
674
+ return h.score.toFixed(3) + " [" + h.entry.id + "] " + h.entry.fact + " (" + h.entry.file + ")";
675
+ }).join("\n");
676
+ return { content: formatted };
677
+ }
678
+ });
679
+
680
+ editor.add({
681
+ name: "memory_checkpoint",
682
+ description: "Save a numbered session checkpoint summary to sessions/YYYY-MM-DD_<slug>-<NN>.md and index it into vectors.json.",
683
+ input: {
684
+ type: "object",
685
+ properties: {
686
+ slug: {
687
+ type: "string",
688
+ description: "Short kebab-case session topic slug"
689
+ },
690
+ title: {
691
+ type: "string",
692
+ description: "Short descriptive title for the checkpoint"
693
+ },
694
+ summary: {
695
+ type: "string",
696
+ description: "Markdown summary body (What was built/fixed/decided, Key decisions, Files changed, Problems solved, Outcome)"
697
+ },
698
+ project: {
699
+ type: "string",
700
+ description: "Project path or 'global'"
701
+ },
702
+ contextPct: {
703
+ type: "number",
704
+ description: "Optional context usage percentage"
705
+ }
706
+ },
707
+ required: ["slug", "title", "summary"],
708
+ additionalProperties: false
709
+ },
710
+ execute: async function (input) {
711
+ const saved = await storeSessionCheckpoint(rootDir, input);
712
+ return {
713
+ content: "Saved and indexed session checkpoint: " + saved.filename
714
+ };
715
+ }
716
+ });
717
+ });
718
+ if (toolReg) registrations.push(toolReg);
719
+ }
720
+
721
+ if (ctx && ctx.session && typeof ctx.session.hook === "function") {
722
+ const ctxReg = await ctx.session.hook("context", async function (event) {
723
+ const userText = extractLastUserText(event.messages);
724
+ const ctxKey = String(userText || "").trim() + "::" + cachedVersion;
725
+ if (ctxKey === lastContextKey && lastContextText) {
726
+ if (Array.isArray(event.system)) {
727
+ event.system.push({ type: "text", text: lastContextText });
728
+ }
729
+ return;
730
+ }
731
+
732
+ const topicSlugs = getTopicSlugs(rootDir);
733
+ const lines = [
734
+ "<local-memory-plugin>",
735
+ "Persistent memory (`opencode-local-memory`) is active at: " + rootDir,
736
+ "Available topics: " + (topicSlugs.join(", ") || "preferences, decisions, environment, agent-behavior") + " (or pass any new topic slug to create a new file).",
737
+ "",
738
+ "AUTOMATIC STORAGE (via `memory_store` tool — no prompting needed):",
739
+ "Call `memory_store` immediately in the SAME turn before your final response whenever any of these happen:",
740
+ "- User states a preference, convention, or 'always/never do X' rule",
741
+ "- An architecture, workflow, or design decision is made (yours or theirs)",
742
+ "- A non-obvious environment, path, port, or tooling fact is discovered",
743
+ "- A recurring correction or pattern emerges",
744
+ "- The user has to correct you or repeat an instruction (store it so it never needs repeating)",
745
+ "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
+ "",
747
+ "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.",
750
+ "",
751
+ "AUTOMATIC RECALL & CHECKPOINTS:",
752
+ "- 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
+ "- 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
+ ];
755
+
756
+ 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; });
759
+ if (relevant.length > 0) {
760
+ lines.push("Auto-recalled memories for this prompt:");
761
+ for (const h of relevant) {
762
+ lines.push("- [" + h.entry.id + "] (" + h.entry.file + "): " + h.entry.fact);
763
+ }
764
+ }
765
+ }
766
+
767
+ lines.push("</local-memory-plugin>");
768
+ lastContextKey = ctxKey;
769
+ lastContextText = lines.join("\n");
770
+ if (Array.isArray(event.system)) {
771
+ event.system.push({ type: "text", text: lastContextText });
772
+ }
773
+ });
774
+ if (ctxReg) registrations.push(ctxReg);
775
+
776
+ const compReg = await ctx.session.hook("compaction", async function (event) {
777
+ const lastText = extractLastUserText(event.messages);
778
+ const slug = lastText
779
+ ? lastText.toLowerCase().replace(/[^a-z0-9\s]/g, "").trim().split(/\s+/).slice(0, 4).join("-") || "compaction"
780
+ : "compaction";
781
+ const projectDir = (ctx.location && ctx.location.directory) ? ctx.location.directory : "global";
782
+ await storeSessionCheckpoint(rootDir, {
783
+ slug: slug,
784
+ title: "Auto Compaction Checkpoint (" + slug + ")",
785
+ project: projectDir,
786
+ summary: "## What was built/fixed/decided\n\nAutomatic checkpoint captured at session compaction.\n\n## Last active prompt\n\n" + (lastText || "N/A")
787
+ }).catch(function (err) {
788
+ console.error("local-memory compaction checkpoint error:", err);
789
+ });
790
+ });
791
+ if (compReg) registrations.push(compReg);
792
+ }
793
+
794
+ return async function () {
795
+ for (const reg of registrations) {
796
+ if (reg && typeof reg.dispose === "function") {
797
+ await reg.dispose();
798
+ }
799
+ }
800
+ };
801
+ }
802
+ };
803
+ }
804
+
805
+ const server = createPluginDefinition();
806
+ export default server;
807
+ export {
808
+ server,
809
+ resolveMemoryDir,
810
+ resolveConfigDir,
811
+ ensureMemoryLayout,
812
+ installPlugin,
813
+ parseTopicEntries,
814
+ parseSessionEntries,
815
+ nextTopicId,
816
+ getTopicSlugs,
817
+ loadCachedVectors,
818
+ syncVectors,
819
+ searchMemory,
820
+ storeMemoryFact,
821
+ storeSessionCheckpoint
822
+ };
823
+
824
+ const isDirectRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
825
+ if (isDirectRun) {
826
+ const cmd = process.argv[2] || "sync";
827
+ const rootDir = resolveMemoryDir(process.env.OPENCODE_MEMORY_DIR);
828
+
829
+ 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) {
836
+ console.log("opencode-local-memory installed:");
837
+ console.log(" Server config: " + res.serverConfigFile + " (" + res.serverStatus + ")");
838
+ console.log(" TUI config: " + res.cliConfigFile + " (" + res.cliStatus + ")");
839
+ console.log(" Memory folder: " + res.memoryDir);
840
+ console.log(" Vectors cache: " + res.syncResult.vecFile + " (" + res.syncResult.total + " entries ready)");
841
+ }).catch(function (err) {
842
+ console.error("Install failed:", err);
843
+ process.exit(1);
844
+ });
845
+ } else if (cmd === "sync" || cmd === "embed") {
846
+ syncVectors(rootDir).then(function (res) {
847
+ console.log("Synced " + res.total + " memory entries (" + res.embedded + " newly embedded, " + res.reused + " cached) -> " + res.vecFile);
848
+ }).catch(function (err) {
849
+ console.error("Sync failed:", err);
850
+ process.exit(1);
851
+ });
852
+ } else if (cmd === "search" || cmd === "recall") {
853
+ const query = process.argv[3] || "";
854
+ const mode = cmd === "recall" ? "grep" : (process.argv[4] || "hybrid");
855
+ const topN = parseInt(process.argv[5] || "8", 10);
856
+ searchMemory(rootDir, query, mode, topN).then(function (hits) {
857
+ for (const h of hits) {
858
+ console.log(h.score.toFixed(3) + " [" + h.entry.id + "] " + h.entry.fact + " (" + h.entry.file + ")");
859
+ }
860
+ }).catch(function (err) {
861
+ console.error("Search failed:", err);
862
+ process.exit(1);
863
+ });
864
+ } else if (cmd === "store") {
865
+ const topic = process.argv[3];
866
+ const tags = process.argv[4];
867
+ const fact = process.argv.slice(5).join(" ");
868
+ storeMemoryFact(rootDir, { topic: topic, tags: tags, fact: fact }).then(function (entry) {
869
+ console.log("Stored [" + entry.id + "] in " + entry.file);
870
+ }).catch(function (err) {
871
+ console.error("Store failed:", err);
872
+ process.exit(1);
873
+ });
874
+ }
875
+ }