@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.
Files changed (4) hide show
  1. package/README.md +42 -22
  2. package/index.js +1437 -75
  3. package/package.json +1 -1
  4. package/tui.ts +192 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nandoblanco/opencode-local-memory",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/tui.ts CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
+ import { execFile } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
5
7
  import type { TuiPluginContext } from "@opencode-ai/plugin/tui";
6
8
  import { TextAttributes } from "@opentui/core";
7
9
  import {
@@ -24,8 +26,11 @@ import {
24
26
  Show,
25
27
  } from "solid-js";
26
28
  import {
29
+ deleteMemoryEntry,
27
30
  getTopicSlugs,
31
+ importExistingMemory,
28
32
  loadCachedVectors,
33
+ matchesProjectScope,
29
34
  resolveMemoryDir,
30
35
  searchMemory,
31
36
  storeMemoryFact,
@@ -38,6 +43,8 @@ interface MemoryEntry {
38
43
  file: string;
39
44
  tags: string;
40
45
  fact: string;
46
+ project?: string;
47
+ core?: boolean;
41
48
  vector?: number[];
42
49
  _haystack?: string;
43
50
  }
@@ -53,6 +60,43 @@ type ModeFilter = "hybrid" | "keyword" | "regex";
53
60
 
54
61
  const TYPE_CYCLE: TypeFilter[] = ["all", "topics", "sessions"];
55
62
  const MODE_CYCLE: ModeFilter[] = ["hybrid", "keyword", "regex"];
63
+ const CLI_SCRIPT_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "index.js");
64
+
65
+ function runCliSubprocess(args: string[]): Promise<string> {
66
+ return new Promise((resolve, reject) => {
67
+ const baseEnv = { ...process.env, OPENCODE_MEMORY_SUBPROCESS: "1" };
68
+ execFile("node", [CLI_SCRIPT_PATH, ...args], { env: baseEnv, windowsHide: true, timeout: 120000 }, (err, stdout) => {
69
+ if (!err) return resolve(String(stdout || ""));
70
+ const bunEnv = { ...baseEnv, BUN_BE_BUN: "1" };
71
+ execFile(process.execPath, [CLI_SCRIPT_PATH, ...args], { env: bunEnv, windowsHide: true, timeout: 120000 }, (err2, stdout2) => {
72
+ if (err2) return reject(err);
73
+ resolve(String(stdout2 || ""));
74
+ });
75
+ });
76
+ });
77
+ }
78
+
79
+ async function safeSyncVectors(rootDir: string) {
80
+ try {
81
+ return await syncVectors(rootDir);
82
+ } catch {
83
+ await runCliSubprocess(["sync", "--dir", rootDir]);
84
+ const loaded = (loadCachedVectors(rootDir) || []) as MemoryEntry[];
85
+ return { total: loaded.length, embedded: 0, reused: loaded.length, vecFile: path.join(rootDir, "vectors.json") };
86
+ }
87
+ }
88
+
89
+ async function safeImportMemory(rootDir: string, limit?: number) {
90
+ try {
91
+ return await importExistingMemory(rootDir, { limit });
92
+ } catch {
93
+ const args = ["import", "--dir", rootDir, "--json"];
94
+ if (limit) args.push("--limit", String(limit));
95
+ const stdout = await runCliSubprocess(args);
96
+ const lines = stdout.trim().split(/\r?\n/).filter(Boolean);
97
+ return JSON.parse(lines[lines.length - 1]);
98
+ }
99
+ }
56
100
 
57
101
  function splitHighlightedText(
58
102
  text: string,
@@ -249,6 +293,8 @@ function createTuiRenderer() {
249
293
  let effType = tFilter;
250
294
  let effTopic = topFilter;
251
295
  let effMode = mFilter;
296
+ let effProject = "all";
297
+ let effCoreOnly = false;
252
298
  const tokens = rawQ.trim().split(/\s+/).filter(Boolean);
253
299
  const cleanTokens: string[] = [];
254
300
 
@@ -260,6 +306,11 @@ function createTuiRenderer() {
260
306
  effType = "sessions";
261
307
  } else if (lower === "type:all") {
262
308
  effType = "all";
309
+ } else if (lower === "core:true" || lower === "is:core") {
310
+ effCoreOnly = true;
311
+ } else if (lower.startsWith("project:")) {
312
+ const val = lower.slice(8).trim();
313
+ if (val) effProject = val;
263
314
  } else if (lower.startsWith("topic:")) {
264
315
  const val = lower.slice(6).trim();
265
316
  if (val) effTopic = val;
@@ -276,6 +327,8 @@ function createTuiRenderer() {
276
327
  effType,
277
328
  effTopic,
278
329
  effMode,
330
+ effProject,
331
+ effCoreOnly,
279
332
  };
280
333
  };
281
334
 
@@ -286,7 +339,7 @@ function createTuiRenderer() {
286
339
  topFilter: string,
287
340
  mFilter: ModeFilter
288
341
  ): MemoryHit[] => {
289
- const { cleanQ: q, effType, effTopic, effMode } = parseInlineFilters(
342
+ const { cleanQ: q, effType, effTopic, effMode, effProject, effCoreOnly } = parseInlineFilters(
290
343
  rawQ,
291
344
  tFilter,
292
345
  topFilter,
@@ -297,6 +350,8 @@ function createTuiRenderer() {
297
350
  if (effType === "topics" && !e.file.startsWith("topics/")) return false;
298
351
  if (effType === "sessions" && !e.file.startsWith("sessions/")) return false;
299
352
  if (effTopic !== "all" && e.file !== `topics/${effTopic}.md`) return false;
353
+ if (effCoreOnly && !e.core) return false;
354
+ if (effProject !== "all" && !matchesProjectScope(e.project, effProject, false)) return false;
300
355
  return true;
301
356
  });
302
357
 
@@ -356,7 +411,7 @@ function createTuiRenderer() {
356
411
  const tFilter = typeFilter();
357
412
  const topFilter = topicFilter();
358
413
  const mFilter = mode();
359
- const { cleanQ: q, effType, effTopic, effMode } = parseInlineFilters(
414
+ const { cleanQ: q, effType, effTopic, effMode, effProject, effCoreOnly } = parseInlineFilters(
360
415
  rawQ,
361
416
  tFilter,
362
417
  topFilter,
@@ -370,7 +425,11 @@ function createTuiRenderer() {
370
425
  // If hybrid mode and non-empty query, refine with local vector similarity (0 LLM tokens)
371
426
  if (effMode === "hybrid" && q.length >= 2) {
372
427
  try {
373
- const semHits: MemoryHit[] = await searchMemory(props.rootDir, q, "hybrid", 50);
428
+ const semHits: MemoryHit[] = await searchMemory(props.rootDir, q, "hybrid", 50, {
429
+ project: effProject,
430
+ includeGlobal: effProject === "all",
431
+ coreOnly: effCoreOnly,
432
+ });
374
433
  if (currentSeq !== searchSeq) return;
375
434
  const filtered = semHits.filter((h) => {
376
435
  if (effType === "topics" && !h.entry.file.startsWith("topics/")) return false;
@@ -388,7 +447,7 @@ function createTuiRenderer() {
388
447
  const reloadVectors = async (forceSync = false) => {
389
448
  if (forceSync) {
390
449
  setStatusMsg("syncing markdown -> vectors.json...");
391
- await syncVectors(props.rootDir).catch(() => {});
450
+ await safeSyncVectors(props.rootDir).catch(() => {});
392
451
  setStatusMsg("");
393
452
  }
394
453
  const loaded = (loadCachedVectors(props.rootDir) || []) as MemoryEntry[];
@@ -396,6 +455,29 @@ function createTuiRenderer() {
396
455
  await runSearch();
397
456
  };
398
457
 
458
+ const runImportInDialog = async () => {
459
+ setStatusMsg("importing AGENTS.md & opencode.db...");
460
+ try {
461
+ const res = await safeImportMemory(props.rootDir);
462
+ setStatusMsg("");
463
+ const loaded = (loadCachedVectors(props.rootDir) || []) as MemoryEntry[];
464
+ setAllEntries(loaded);
465
+ await runSearch();
466
+ props.context.ui.toast.show({
467
+ title: "Memory Import Complete (0 tokens)",
468
+ message: `Imported ${res.importedFacts.length} rules & ${res.importedSessions.length} sessions (${res.syncResult.total} total)`,
469
+ variant: "success",
470
+ });
471
+ } catch (err) {
472
+ setStatusMsg("");
473
+ props.context.ui.toast.show({
474
+ title: "Memory Import Error",
475
+ message: err instanceof Error ? err.message : String(err),
476
+ variant: "error",
477
+ });
478
+ }
479
+ };
480
+
399
481
  createEffect(() => {
400
482
  query();
401
483
  typeFilter();
@@ -488,6 +570,12 @@ function createTuiRenderer() {
488
570
  void reloadVectors(true);
489
571
  return;
490
572
  }
573
+ if (event.ctrl && name === "b") {
574
+ event.preventDefault();
575
+ event.stopPropagation();
576
+ void runImportInDialog();
577
+ return;
578
+ }
491
579
 
492
580
  if (name === "return" || name === "enter") {
493
581
  const current = selectedHit();
@@ -742,6 +830,12 @@ function createTuiRenderer() {
742
830
  shortcut: "^r",
743
831
  active: () => mode() !== "hybrid",
744
832
  onClick: cycleMode,
833
+ }),
834
+ Pill({
835
+ label: () => "import",
836
+ shortcut: "^b",
837
+ active: () => false,
838
+ onClick: () => void runImportInDialog(),
745
839
  })
746
840
  )
747
841
  ),
@@ -903,7 +997,9 @@ function createTuiRenderer() {
903
997
  () => {
904
998
  const h = selectedHit();
905
999
  if (!h) return "";
906
- return `File: ${h.entry.file} · Date: ${h.entry.date || "N/A"} · Score: ${h.score.toFixed(3)}`;
1000
+ const scope = h.entry.project || "global";
1001
+ const coreLabel = h.entry.core ? " · Core: pinned" : "";
1002
+ return `File: ${h.entry.file} · Date: ${h.entry.date || "N/A"} · Scope: ${scope}${coreLabel} · Score: ${h.score.toFixed(3)}`;
907
1003
  }
908
1004
  ),
909
1005
  el(
@@ -991,7 +1087,7 @@ function createTuiRenderer() {
991
1087
  el(
992
1088
  "text",
993
1089
  { fg: () => theme().text.muted },
994
- "enter select · ↑/↓ or ^n/^k move · ^t type · ^g topic · ^r mode · ^l resync · tab pane · esc"
1090
+ "enter select · ↑/↓ or ^n/^k move · ^t type · ^g topic · ^r mode · ^b import · ^l resync · tab pane · esc"
995
1091
  ),
996
1092
  el(
997
1093
  "text",
@@ -1102,6 +1198,64 @@ export default {
1102
1198
  }
1103
1199
  };
1104
1200
 
1201
+ const quickDeleteFromSlash = async (rawArgs?: string) => {
1202
+ const id = typeof rawArgs === "string" ? rawArgs.trim() : "";
1203
+ if (!id) {
1204
+ context.ui.toast.show({
1205
+ title: "Local Memory Delete (0 tokens)",
1206
+ message: "Usage: /memory-delete <id>",
1207
+ variant: "warning",
1208
+ });
1209
+ return;
1210
+ }
1211
+ try {
1212
+ const res = await deleteMemoryEntry(rootDir, id);
1213
+ if (res.deleted.length === 0) {
1214
+ context.ui.toast.show({
1215
+ title: "Not Found",
1216
+ message: `No memory entry matched ID: ${id}`,
1217
+ variant: "warning",
1218
+ });
1219
+ return;
1220
+ }
1221
+ context.ui.toast.show({
1222
+ title: `Deleted ${res.deleted.map((d: { id: string }) => `[${d.id}]`).join(", ")} (0 tokens)`,
1223
+ message: `${res.total} entries remaining in vectors.json`,
1224
+ variant: "success",
1225
+ });
1226
+ } catch (err) {
1227
+ context.ui.toast.show({
1228
+ title: "Local Memory Error",
1229
+ message: err instanceof Error ? err.message : String(err),
1230
+ variant: "error",
1231
+ });
1232
+ }
1233
+ };
1234
+
1235
+ const quickImportFromSlash = async (rawArgs?: string) => {
1236
+ const arg = typeof rawArgs === "string" ? rawArgs.trim() : "";
1237
+ const limit = arg && /^\d+$/.test(arg) ? parseInt(arg, 10) : undefined;
1238
+ context.ui.toast.show({
1239
+ title: "Importing Local Memory (0 tokens)...",
1240
+ message: "Scanning AGENTS.md rules and opencode.db session history...",
1241
+ variant: "info",
1242
+ });
1243
+ try {
1244
+ const res = await safeImportMemory(rootDir, limit);
1245
+ context.ui.toast.show({
1246
+ title: "Local Memory Import Complete (0 tokens)",
1247
+ message: `Added ${res.importedFacts.length} rules & ${res.importedSessions.length} sessions (${res.syncResult.total} total indexed)`,
1248
+ variant: "success",
1249
+ });
1250
+ } catch (err) {
1251
+ context.ui.toast.show({
1252
+ title: "Local Memory Import Error",
1253
+ message: err instanceof Error ? err.message : String(err),
1254
+ variant: "error",
1255
+ });
1256
+ }
1257
+ };
1258
+
1105
1259
  let layerRegistered = false;
1106
1260
  context.ui.slot({
1107
1261
  append: "app",
@@ -1143,6 +1297,38 @@ export default {
1143
1297
  void quickStoreFromSlash(rawArgs);
1144
1298
  },
1145
1299
  },
1300
+ {
1301
+ id: "local.memory.delete",
1302
+ title: "Delete local memory entry by ID (0 tokens)...",
1303
+ description:
1304
+ "Zero-token slash command to delete a memory entry by ID: /memory-delete <id>",
1305
+ category: "Memory",
1306
+ palette: false,
1307
+ slash: {
1308
+ name: "memory-delete",
1309
+ arguments: true,
1310
+ },
1311
+ run: (input) => {
1312
+ const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
1313
+ void quickDeleteFromSlash(rawArgs);
1314
+ },
1315
+ },
1316
+ {
1317
+ id: "local.memory.import",
1318
+ title: "Import existing AGENTS.md & session history (0 tokens)...",
1319
+ description:
1320
+ "Zero-token command to import existing AGENTS.md/CLAUDE.md rules and compacted session summaries from opencode.db: /memory-import [limit]",
1321
+ category: "Memory",
1322
+ palette: true,
1323
+ slash: {
1324
+ name: "memory-import",
1325
+ arguments: true,
1326
+ },
1327
+ run: (input) => {
1328
+ const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
1329
+ void quickImportFromSlash(rawArgs);
1330
+ },
1331
+ },
1146
1332
  ],
1147
1333
  }));
1148
1334
  }