@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/tui.ts ADDED
@@ -0,0 +1,1121 @@
1
+ "use strict";
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import type { TuiPluginContext } from "@opencode-ai/plugin/tui";
6
+ import { TextAttributes } from "@opentui/core";
7
+ import {
8
+ createComponent,
9
+ createElement,
10
+ createTextNode,
11
+ effect,
12
+ insert,
13
+ insertNode,
14
+ setProp,
15
+ use,
16
+ } from "@opentui/solid";
17
+ import {
18
+ createEffect,
19
+ createMemo,
20
+ createSignal,
21
+ For,
22
+ onCleanup,
23
+ onMount,
24
+ Show,
25
+ } from "solid-js";
26
+ import {
27
+ getTopicSlugs,
28
+ loadCachedVectors,
29
+ resolveMemoryDir,
30
+ searchMemory,
31
+ storeMemoryFact,
32
+ syncVectors,
33
+ } from "./index.js";
34
+
35
+ interface MemoryEntry {
36
+ id: string;
37
+ date: string;
38
+ file: string;
39
+ tags: string;
40
+ fact: string;
41
+ vector?: number[];
42
+ _haystack?: string;
43
+ }
44
+
45
+ interface MemoryHit {
46
+ score: number;
47
+ semanticScore: number;
48
+ entry: MemoryEntry;
49
+ }
50
+
51
+ type TypeFilter = "all" | "topics" | "sessions";
52
+ type ModeFilter = "hybrid" | "keyword" | "regex";
53
+
54
+ const TYPE_CYCLE: TypeFilter[] = ["all", "topics", "sessions"];
55
+ const MODE_CYCLE: ModeFilter[] = ["hybrid", "keyword", "regex"];
56
+
57
+ function splitHighlightedText(
58
+ text: string,
59
+ term: string
60
+ ): Array<{ text: string; match: boolean }> {
61
+ if (!term || !term.trim()) {
62
+ return [{ text, match: false }];
63
+ }
64
+ const firstWord =
65
+ term
66
+ .trim()
67
+ .toLowerCase()
68
+ .split(/\s+/)
69
+ .find((w) => w.length >= 2 && !w.includes(":")) || term.trim().toLowerCase();
70
+ if (!firstWord) return [{ text, match: false }];
71
+
72
+ const parts: Array<{ text: string; match: boolean }> = [];
73
+ const lower = text.toLowerCase();
74
+ let cursor = 0;
75
+
76
+ while (cursor < text.length) {
77
+ const idx = lower.indexOf(firstWord, cursor);
78
+ if (idx === -1) {
79
+ parts.push({ text: text.slice(cursor), match: false });
80
+ break;
81
+ }
82
+ if (idx > cursor) {
83
+ parts.push({ text: text.slice(cursor, idx), match: false });
84
+ }
85
+ parts.push({ text: text.slice(idx, idx + firstWord.length), match: true });
86
+ cursor = idx + firstWord.length;
87
+ }
88
+ return parts.length ? parts : [{ text, match: false }];
89
+ }
90
+
91
+ function readFullSessionMarkdown(rootDir: string, relFile: string): string {
92
+ try {
93
+ const fullPath = path.join(rootDir, relFile);
94
+ if (fs.existsSync(fullPath)) {
95
+ return fs.readFileSync(fullPath, "utf8").replace(/\r\n/g, "\n").trim();
96
+ }
97
+ } catch {
98
+ // ignore read error
99
+ }
100
+ return "";
101
+ }
102
+
103
+ interface DialogProps {
104
+ context: TuiPluginContext;
105
+ rootDir: string;
106
+ initialQuery: string;
107
+ close: () => void;
108
+ }
109
+
110
+ async function loadTuiRenderer() {
111
+ function el(
112
+ tag: string,
113
+ props?: Record<string, unknown> | null,
114
+ ...children: unknown[]
115
+ ) {
116
+ const node = createElement(tag);
117
+ if (props) {
118
+ for (const [key, val] of Object.entries(props)) {
119
+ if (val === undefined) continue;
120
+ if (key === "ref" && typeof val === "function") {
121
+ use(val as (e: unknown) => void, node, undefined);
122
+ } else if (
123
+ typeof val === "function" &&
124
+ !key.startsWith("on") &&
125
+ key !== "renderBefore"
126
+ ) {
127
+ effect((prev: unknown) => setProp(node, key, (val as () => unknown)(), prev));
128
+ } else {
129
+ setProp(node, key, val);
130
+ }
131
+ }
132
+ }
133
+ for (const child of children) {
134
+ if (child === undefined || child === null || child === false) continue;
135
+ if (typeof child === "string") {
136
+ insertNode(node, createTextNode(child));
137
+ } else {
138
+ insert(node, child);
139
+ }
140
+ }
141
+ return node;
142
+ }
143
+
144
+ function LocalMemoryDialog(props: DialogProps) {
145
+ const [query, setQuery] = createSignal(props.initialQuery);
146
+ const [typeFilter, setTypeFilter] = createSignal<TypeFilter>("all");
147
+ const [topicFilter, setTopicFilter] = createSignal<string>("all");
148
+ const [mode, setMode] = createSignal<ModeFilter>("hybrid");
149
+ const [focusPane, setFocusPane] = createSignal<"search" | "list" | "preview">("search");
150
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
151
+ const [allEntries, setAllEntries] = createSignal<MemoryEntry[]>([]);
152
+ const [hits, setHits] = createSignal<MemoryHit[]>([]);
153
+ const [statusMsg, setStatusMsg] = createSignal("");
154
+
155
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
+ let rootRef: any;
157
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
+ let listScrollRef: any;
159
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
160
+ let previewScrollRef: any;
161
+ let searchSeq = 0;
162
+
163
+ const resolveDialogWidth = (): string | number => {
164
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
165
+ const opts = (props.context as any)?.options;
166
+ const raw =
167
+ opts?.dialogWidth ??
168
+ opts?.width ??
169
+ process.env.OPENCODE_MEMORY_DIALOG_WIDTH ??
170
+ process.env.OPENCODE_DIALOG_WIDTH ??
171
+ "80%";
172
+ if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {
173
+ return raw <= 100 ? `${Math.round(raw)}%` : Math.round(raw);
174
+ }
175
+ if (typeof raw === "string") {
176
+ const trimmed = raw.trim();
177
+ if (/^\d+(\.\d+)?%$/.test(trimmed)) return trimmed;
178
+ const num = Number(trimmed);
179
+ if (Number.isFinite(num) && num > 0) {
180
+ return num <= 100 ? `${Math.round(num)}%` : Math.round(num);
181
+ }
182
+ }
183
+ return "80%";
184
+ };
185
+
186
+ const applyDialogWidth = () => {
187
+ if (!rootRef) return;
188
+ try {
189
+ const targetWidth = resolveDialogWidth();
190
+ let cursor = rootRef;
191
+ let dialogBox = rootRef;
192
+ while (cursor.parent && cursor.parent._positionType !== "absolute") {
193
+ cursor = cursor.parent;
194
+ dialogBox = cursor;
195
+ }
196
+ dialogBox.width = targetWidth;
197
+ dialogBox.maxWidth = targetWidth;
198
+ dialogBox.minWidth = 76;
199
+
200
+ let inner = rootRef;
201
+ while (inner && inner !== dialogBox) {
202
+ inner.width = "100%";
203
+ inner.maxWidth = "100%";
204
+ inner = inner.parent;
205
+ }
206
+ rootRef.requestRender?.();
207
+ } catch {
208
+ // ignore layout mutation errors
209
+ }
210
+ };
211
+
212
+ const theme = () => props.context.theme.surface("dialog");
213
+
214
+ const topicsList = createMemo<string[]>(() => {
215
+ const slugs = getTopicSlugs(props.rootDir) || [];
216
+ return ["all", ...slugs];
217
+ });
218
+
219
+ const parseInlineFilters = (
220
+ rawQ: string,
221
+ tFilter: TypeFilter,
222
+ topFilter: string,
223
+ mFilter: ModeFilter
224
+ ) => {
225
+ let effType = tFilter;
226
+ let effTopic = topFilter;
227
+ let effMode = mFilter;
228
+ const tokens = rawQ.trim().split(/\s+/).filter(Boolean);
229
+ const cleanTokens: string[] = [];
230
+
231
+ for (const tok of tokens) {
232
+ const lower = tok.toLowerCase();
233
+ if (lower === "type:topics" || lower === "type:facts" || lower === "in:topics") {
234
+ effType = "topics";
235
+ } else if (lower === "type:sessions" || lower === "in:sessions") {
236
+ effType = "sessions";
237
+ } else if (lower === "type:all") {
238
+ effType = "all";
239
+ } else if (lower.startsWith("topic:")) {
240
+ const val = lower.slice(6).trim();
241
+ if (val) effTopic = val;
242
+ } else if (lower.startsWith("re:") && tok.length > 3) {
243
+ effMode = "regex";
244
+ cleanTokens.push(tok.slice(3));
245
+ } else {
246
+ cleanTokens.push(tok);
247
+ }
248
+ }
249
+
250
+ return {
251
+ cleanQ: cleanTokens.join(" ").trim(),
252
+ effType,
253
+ effTopic,
254
+ effMode,
255
+ };
256
+ };
257
+
258
+ const filterEntriesSync = (
259
+ entries: MemoryEntry[],
260
+ rawQ: string,
261
+ tFilter: TypeFilter,
262
+ topFilter: string,
263
+ mFilter: ModeFilter
264
+ ): MemoryHit[] => {
265
+ const { cleanQ: q, effType, effTopic, effMode } = parseInlineFilters(
266
+ rawQ,
267
+ tFilter,
268
+ topFilter,
269
+ mFilter
270
+ );
271
+
272
+ const subset = entries.filter((e) => {
273
+ if (effType === "topics" && !e.file.startsWith("topics/")) return false;
274
+ if (effType === "sessions" && !e.file.startsWith("sessions/")) return false;
275
+ if (effTopic !== "all" && e.file !== `topics/${effTopic}.md`) return false;
276
+ return true;
277
+ });
278
+
279
+ if (!q) {
280
+ return subset
281
+ .slice()
282
+ .reverse()
283
+ .map((e) => ({ score: 1, semanticScore: 0, entry: e }));
284
+ }
285
+
286
+ if (effMode === "regex" || (q.startsWith("/") && q.lastIndexOf("/") > 0)) {
287
+ try {
288
+ const lastSlash = q.startsWith("/") ? q.lastIndexOf("/") : -1;
289
+ const pattern = lastSlash > 0 ? q.slice(1, lastSlash) : q;
290
+ const flags = lastSlash > 0 ? q.slice(lastSlash + 1) || "i" : "i";
291
+ const re = new RegExp(pattern, flags);
292
+ return subset
293
+ .filter((e) => re.test(`${e.id} ${e.tags} ${e.fact} ${e.file}`))
294
+ .map((e) => ({ score: 1, semanticScore: 0, entry: e }));
295
+ } catch {
296
+ return [];
297
+ }
298
+ }
299
+
300
+ const lowerQ = q.toLowerCase();
301
+ const words = lowerQ.split(/\s+/).filter((w) => w.length >= 2);
302
+ const scored: MemoryHit[] = [];
303
+
304
+ for (const e of subset) {
305
+ const hay = e._haystack || `${e.id} ${e.tags} ${e.fact} ${e.file}`.toLowerCase();
306
+ let lex = 0;
307
+ if (hay.includes(lowerQ)) {
308
+ lex = 0.9;
309
+ } else if (words.length > 0) {
310
+ let matched = 0;
311
+ for (const w of words) {
312
+ if (hay.includes(w)) matched++;
313
+ }
314
+ if (matched > 0) {
315
+ lex = (matched / words.length) * 0.75;
316
+ }
317
+ }
318
+ if (lex > 0) {
319
+ scored.push({ score: lex, semanticScore: 0, entry: e });
320
+ }
321
+ }
322
+
323
+ scored.sort((a, b) => b.score - a.score);
324
+ return scored;
325
+ };
326
+
327
+ const runSearch = async () => {
328
+ const currentSeq = ++searchSeq;
329
+ const entries = allEntries();
330
+ const rawQ = query().trim();
331
+ const tFilter = typeFilter();
332
+ const topFilter = topicFilter();
333
+ const mFilter = mode();
334
+ const { cleanQ: q, effType, effTopic, effMode } = parseInlineFilters(
335
+ rawQ,
336
+ tFilter,
337
+ topFilter,
338
+ mFilter
339
+ );
340
+
341
+ // Instant synchronous pass first (0ms)
342
+ const instant = filterEntriesSync(entries, rawQ, tFilter, topFilter, mFilter);
343
+ setHits(instant);
344
+
345
+ // If hybrid mode and non-empty query, refine with local vector similarity (0 LLM tokens)
346
+ if (effMode === "hybrid" && q.length >= 2) {
347
+ try {
348
+ const semHits: MemoryHit[] = await searchMemory(props.rootDir, q, "hybrid", 50);
349
+ if (currentSeq !== searchSeq) return;
350
+ const filtered = semHits.filter((h) => {
351
+ if (effType === "topics" && !h.entry.file.startsWith("topics/")) return false;
352
+ if (effType === "sessions" && !h.entry.file.startsWith("sessions/")) return false;
353
+ if (effTopic !== "all" && h.entry.file !== `topics/${effTopic}.md`) return false;
354
+ return h.score >= 0.22;
355
+ });
356
+ setHits(filtered);
357
+ } catch {
358
+ // Keep instant lexical results on error
359
+ }
360
+ }
361
+ };
362
+
363
+ const reloadVectors = async (forceSync = false) => {
364
+ if (forceSync) {
365
+ setStatusMsg("syncing markdown -> vectors.json...");
366
+ await syncVectors(props.rootDir).catch(() => {});
367
+ setStatusMsg("");
368
+ }
369
+ const loaded = (loadCachedVectors(props.rootDir) || []) as MemoryEntry[];
370
+ setAllEntries(loaded);
371
+ await runSearch();
372
+ };
373
+
374
+ createEffect(() => {
375
+ query();
376
+ typeFilter();
377
+ topicFilter();
378
+ mode();
379
+ setSelectedIndex(0);
380
+ queueMicrotask(() => listScrollRef?.scrollTo?.(0));
381
+ void runSearch();
382
+ });
383
+
384
+ const selectedHit = createMemo<MemoryHit | undefined>(() => {
385
+ const list = hits();
386
+ if (!list.length) return undefined;
387
+ const idx = Math.max(0, Math.min(list.length - 1, selectedIndex()));
388
+ return list[idx];
389
+ });
390
+
391
+ const selectedSessionBody = createMemo<string>(() => {
392
+ const h = selectedHit();
393
+ if (!h || !h.entry.file.startsWith("sessions/")) return "";
394
+ return readFullSessionMarkdown(props.rootDir, h.entry.file);
395
+ });
396
+
397
+ const moveSelection = (delta: number) => {
398
+ const list = hits();
399
+ if (!list.length) return;
400
+ const next = Math.max(0, Math.min(list.length - 1, selectedIndex() + delta));
401
+ setSelectedIndex(next);
402
+ queueMicrotask(() => {
403
+ listScrollRef?.scrollChildIntoView?.(`memory-row-${next}`);
404
+ previewScrollRef?.scrollTo?.(0);
405
+ });
406
+ };
407
+
408
+ const cycleType = () => {
409
+ setTypeFilter((prev: TypeFilter) => TYPE_CYCLE[(TYPE_CYCLE.indexOf(prev) + 1) % TYPE_CYCLE.length]);
410
+ };
411
+
412
+ const cycleTopic = () => {
413
+ const list = topicsList();
414
+ setTopicFilter((prev: string) => list[(list.indexOf(prev) + 1) % list.length]);
415
+ };
416
+
417
+ const cycleMode = () => {
418
+ setMode((prev: ModeFilter) => MODE_CYCLE[(MODE_CYCLE.indexOf(prev) + 1) % MODE_CYCLE.length]);
419
+ };
420
+
421
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
422
+ const handleKeyPress = (event: any) => {
423
+ const name = String(event.name || "").toLowerCase();
424
+
425
+ if (name === "escape") {
426
+ event.preventDefault();
427
+ event.stopPropagation();
428
+ props.close();
429
+ return;
430
+ }
431
+
432
+ if (name === "tab") {
433
+ event.preventDefault();
434
+ event.stopPropagation();
435
+ const order: Array<"search" | "list" | "preview"> = ["search", "list", "preview"];
436
+ const idx = order.indexOf(focusPane());
437
+ const next = order[(idx + (event.shift ? -1 : 1) + order.length) % order.length];
438
+ setFocusPane(next);
439
+ return;
440
+ }
441
+
442
+ if (event.ctrl && name === "t") {
443
+ event.preventDefault();
444
+ event.stopPropagation();
445
+ cycleType();
446
+ return;
447
+ }
448
+ if (event.ctrl && name === "g") {
449
+ event.preventDefault();
450
+ event.stopPropagation();
451
+ cycleTopic();
452
+ return;
453
+ }
454
+ if (event.ctrl && name === "r") {
455
+ event.preventDefault();
456
+ event.stopPropagation();
457
+ cycleMode();
458
+ return;
459
+ }
460
+ if (event.ctrl && name === "l") {
461
+ event.preventDefault();
462
+ event.stopPropagation();
463
+ void reloadVectors(true);
464
+ return;
465
+ }
466
+
467
+ if (name === "return" || name === "enter") {
468
+ const current = selectedHit();
469
+ if (current) {
470
+ event.preventDefault();
471
+ event.stopPropagation();
472
+ const formatted = `[${current.entry.id}] (${current.entry.file}): ${current.entry.fact}`;
473
+ try {
474
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
475
+ const uiAny = props.context.ui as any;
476
+ if (uiAny.clipboard?.writeText) {
477
+ void uiAny.clipboard.writeText(formatted);
478
+ } else if (uiAny.clipboard?.copy) {
479
+ void uiAny.clipboard.copy(formatted);
480
+ }
481
+ } catch {
482
+ // ignore clipboard errors
483
+ }
484
+ props.context.ui.toast.show({
485
+ title: `Selected [${current.entry.id}]`,
486
+ message: `${current.entry.file}: ${current.entry.fact.slice(0, 90)}`,
487
+ variant: "info",
488
+ });
489
+ props.close();
490
+ }
491
+ return;
492
+ }
493
+
494
+ if (
495
+ name === "down" ||
496
+ (event.ctrl && name === "n") ||
497
+ (focusPane() === "list" && !event.ctrl && name === "j")
498
+ ) {
499
+ event.preventDefault();
500
+ event.stopPropagation();
501
+ moveSelection(1);
502
+ return;
503
+ }
504
+ if (
505
+ name === "up" ||
506
+ (event.ctrl && name === "k") ||
507
+ (focusPane() === "list" && !event.ctrl && name === "k")
508
+ ) {
509
+ event.preventDefault();
510
+ event.stopPropagation();
511
+ moveSelection(-1);
512
+ return;
513
+ }
514
+ if (name === "pagedown" || (event.ctrl && name === "d")) {
515
+ event.preventDefault();
516
+ event.stopPropagation();
517
+ if (focusPane() === "preview") {
518
+ previewScrollRef?.scrollBy?.(8);
519
+ } else {
520
+ moveSelection(6);
521
+ }
522
+ return;
523
+ }
524
+ if (name === "pageup" || (event.ctrl && name === "u")) {
525
+ event.preventDefault();
526
+ event.stopPropagation();
527
+ if (focusPane() === "preview") {
528
+ previewScrollRef?.scrollBy?.(-8);
529
+ } else {
530
+ moveSelection(-6);
531
+ }
532
+ return;
533
+ }
534
+ };
535
+
536
+ onMount(() => {
537
+ applyDialogWidth();
538
+ queueMicrotask(applyDialogWidth);
539
+ props.context.renderer.keyInput.prependListener("keypress", handleKeyPress);
540
+ void reloadVectors(false);
541
+ });
542
+
543
+ onCleanup(() => {
544
+ props.context.renderer.keyInput.removeListener("keypress", handleKeyPress);
545
+ });
546
+
547
+ const Pill = (pillProps: {
548
+ label: () => string;
549
+ shortcut?: string;
550
+ active: () => boolean;
551
+ onClick: () => void;
552
+ }) =>
553
+ el(
554
+ "box",
555
+ {
556
+ flexDirection: "row",
557
+ flexShrink: 0,
558
+ paddingX: 1,
559
+ backgroundColor: () =>
560
+ pillProps.active()
561
+ ? theme().background.action.primary.focused
562
+ : theme().background.raised.base,
563
+ onMouseUp: pillProps.onClick,
564
+ },
565
+ el(
566
+ "text",
567
+ {
568
+ fg: () =>
569
+ pillProps.active()
570
+ ? theme().text.action.primary.focused
571
+ : theme().text.base,
572
+ attributes: () => (pillProps.active() ? TextAttributes.BOLD : undefined),
573
+ },
574
+ pillProps.label
575
+ ),
576
+ pillProps.shortcut
577
+ ? el(
578
+ "text",
579
+ {
580
+ fg: () =>
581
+ pillProps.active()
582
+ ? theme().text.action.primary.focused
583
+ : theme().text.muted,
584
+ },
585
+ ` ${pillProps.shortcut}`
586
+ )
587
+ : null
588
+ );
589
+
590
+ return el(
591
+ "box",
592
+ {
593
+ ref: (r: unknown) => {
594
+ rootRef = r;
595
+ queueMicrotask(applyDialogWidth);
596
+ },
597
+ width: "100%",
598
+ height: 28,
599
+ flexDirection: "column",
600
+ backgroundColor: () => theme().background.base,
601
+ },
602
+ // 1. Header Bar
603
+ el(
604
+ "box",
605
+ {
606
+ flexDirection: "row",
607
+ justifyContent: "space-between",
608
+ alignItems: "center",
609
+ paddingX: 2,
610
+ paddingTop: 1,
611
+ flexShrink: 0,
612
+ },
613
+ el(
614
+ "box",
615
+ { flexDirection: "row", gap: 2, alignItems: "center" },
616
+ el(
617
+ "text",
618
+ {
619
+ fg: () => theme().text.base,
620
+ attributes: TextAttributes.BOLD,
621
+ },
622
+ "Local Memory Search"
623
+ ),
624
+ el(
625
+ "text",
626
+ { fg: () => theme().text.muted },
627
+ () =>
628
+ statusMsg() ||
629
+ `${hits().length} of ${allEntries().length} entries`
630
+ )
631
+ ),
632
+ el(
633
+ "box",
634
+ { flexDirection: "row", gap: 2, alignItems: "center" },
635
+ el(
636
+ "text",
637
+ { fg: () => theme().text.muted },
638
+ () => props.context.ui.format.path(props.rootDir)
639
+ ),
640
+ el(
641
+ "box",
642
+ { paddingX: 1, onMouseUp: () => props.close() },
643
+ el("text", { fg: () => theme().text.muted }, "esc")
644
+ )
645
+ )
646
+ ),
647
+
648
+ // 2. Search Input + Filter Pills
649
+ el(
650
+ "box",
651
+ {
652
+ flexDirection: "column",
653
+ paddingX: 2,
654
+ paddingY: 1,
655
+ gap: 1,
656
+ flexShrink: 0,
657
+ border: ["bottom"],
658
+ borderColor: () => theme().border.base,
659
+ },
660
+ el(
661
+ "box",
662
+ { flexDirection: "row", alignItems: "center", gap: 1 },
663
+ el(
664
+ "text",
665
+ {
666
+ fg: () =>
667
+ focusPane() === "search"
668
+ ? theme().text.action.primary.base
669
+ : theme().text.muted,
670
+ attributes: TextAttributes.BOLD,
671
+ },
672
+ "›"
673
+ ),
674
+ el("input", {
675
+ id: "local-memory-search-input",
676
+ flexGrow: 1,
677
+ value: () => query(),
678
+ focused: () => focusPane() === "search",
679
+ maxLength: Number.POSITIVE_INFINITY,
680
+ placeholder:
681
+ "Search local memories (semantic + keyword, or /regex/i)... 0 tokens",
682
+ placeholderColor: () => theme().text.muted,
683
+ textColor: () => theme().text.base,
684
+ focusedTextColor: () => theme().text.formfield.focused,
685
+ cursorColor: () => theme().text.formfield.focused,
686
+ backgroundColor: () => theme().background.base,
687
+ focusedBackgroundColor: () => theme().background.formfield.focused,
688
+ onMouseDown: () => setFocusPane("search"),
689
+ onInput: (val: string) => setQuery(val),
690
+ })
691
+ ),
692
+ el(
693
+ "box",
694
+ { flexDirection: "row", flexWrap: "wrap", gap: 1, alignItems: "center" },
695
+ Pill({
696
+ label: () => `type:${typeFilter()}`,
697
+ shortcut: "^t",
698
+ active: () => typeFilter() !== "all",
699
+ onClick: cycleType,
700
+ }),
701
+ Pill({
702
+ label: () => `topic:${topicFilter()}`,
703
+ shortcut: "^g",
704
+ active: () => topicFilter() !== "all",
705
+ onClick: cycleTopic,
706
+ }),
707
+ Pill({
708
+ label: () => `mode:${mode()}`,
709
+ shortcut: "^r",
710
+ active: () => mode() !== "hybrid",
711
+ onClick: cycleMode,
712
+ })
713
+ )
714
+ ),
715
+
716
+ // 3. Split-Pane Body
717
+ el(
718
+ "box",
719
+ { flexDirection: "row", flexGrow: 1, minHeight: 0 },
720
+ // Left: Results List (44%)
721
+ el(
722
+ "scrollbox",
723
+ {
724
+ id: "local-memory-list",
725
+ ref: (r: unknown) => {
726
+ listScrollRef = r;
727
+ },
728
+ width: "44%",
729
+ height: "100%",
730
+ flexShrink: 0,
731
+ border: ["right"],
732
+ borderColor: () =>
733
+ focusPane() === "list" ? theme().text.base : theme().border.base,
734
+ scrollbarOptions: { visible: false },
735
+ onMouseDown: () => setFocusPane("list"),
736
+ },
737
+ createComponent(Show, {
738
+ get when() {
739
+ return hits().length > 0;
740
+ },
741
+ get fallback() {
742
+ return el(
743
+ "box",
744
+ { paddingX: 2, paddingY: 1 },
745
+ el(
746
+ "text",
747
+ { fg: () => theme().text.muted },
748
+ "No matching memory entries found."
749
+ )
750
+ );
751
+ },
752
+ get children() {
753
+ return createComponent(For, {
754
+ get each() {
755
+ return hits();
756
+ },
757
+ children: (item: MemoryHit, idx: () => number) => {
758
+ const isSelected = () => selectedIndex() === idx();
759
+ return el(
760
+ "box",
761
+ {
762
+ id: () => `memory-row-${idx()}`,
763
+ flexDirection: "column",
764
+ paddingX: 1,
765
+ paddingY: 0,
766
+ marginBottom: 1,
767
+ flexShrink: 0,
768
+ backgroundColor: () =>
769
+ isSelected()
770
+ ? theme().background.action.primary.focused
771
+ : undefined,
772
+ onMouseUp: () => setSelectedIndex(idx()),
773
+ onMouseOver: () => setSelectedIndex(idx()),
774
+ },
775
+ el(
776
+ "box",
777
+ {
778
+ flexDirection: "row",
779
+ justifyContent: "space-between",
780
+ width: "100%",
781
+ },
782
+ el(
783
+ "text",
784
+ {
785
+ wrapMode: "none",
786
+ fg: () =>
787
+ isSelected()
788
+ ? theme().text.action.primary.focused
789
+ : theme().text.base,
790
+ attributes: () =>
791
+ isSelected() ? TextAttributes.BOLD : undefined,
792
+ },
793
+ () => `${isSelected() ? "› " : " "}[${item.entry.id}]`
794
+ ),
795
+ el(
796
+ "text",
797
+ {
798
+ wrapMode: "none",
799
+ fg: () =>
800
+ isSelected()
801
+ ? theme().text.action.primary.focused
802
+ : theme().text.muted,
803
+ },
804
+ () =>
805
+ query().trim()
806
+ ? `${item.score.toFixed(2)} · ${item.entry.file.replace(/\.md$/, "")}`
807
+ : item.entry.file.replace(/\.md$/, "")
808
+ )
809
+ ),
810
+ el(
811
+ "text",
812
+ {
813
+ wrapMode: "none",
814
+ fg: () =>
815
+ isSelected()
816
+ ? theme().text.action.primary.focused
817
+ : theme().text.muted,
818
+ },
819
+ () => ` ${item.entry.fact.slice(0, 56)}`
820
+ )
821
+ );
822
+ },
823
+ });
824
+ },
825
+ })
826
+ ),
827
+
828
+ // Right: Full Memory Entry Preview (56%)
829
+ el(
830
+ "scrollbox",
831
+ {
832
+ id: "local-memory-preview",
833
+ ref: (r: unknown) => {
834
+ previewScrollRef = r;
835
+ },
836
+ flexGrow: 1,
837
+ minWidth: 0,
838
+ minHeight: 0,
839
+ paddingX: 2,
840
+ paddingY: 1,
841
+ focused: () => focusPane() === "preview",
842
+ onMouseDown: () => setFocusPane("preview"),
843
+ },
844
+ createComponent(Show, {
845
+ get when() {
846
+ return selectedHit();
847
+ },
848
+ get fallback() {
849
+ return el(
850
+ "text",
851
+ { fg: () => theme().text.muted },
852
+ "Select a memory entry on the left to inspect it."
853
+ );
854
+ },
855
+ get children() {
856
+ return el(
857
+ "box",
858
+ { flexDirection: "column", gap: 1 },
859
+ el(
860
+ "text",
861
+ {
862
+ fg: () => theme().text.base,
863
+ attributes: TextAttributes.BOLD,
864
+ },
865
+ () => `[${selectedHit()?.entry.id ?? ""}]`
866
+ ),
867
+ el(
868
+ "text",
869
+ { fg: () => theme().text.muted, wrapMode: "word" },
870
+ () => {
871
+ const h = selectedHit();
872
+ if (!h) return "";
873
+ return `File: ${h.entry.file} · Date: ${h.entry.date || "N/A"} · Score: ${h.score.toFixed(3)}`;
874
+ }
875
+ ),
876
+ el(
877
+ "text",
878
+ { fg: () => theme().text.muted, wrapMode: "word" },
879
+ () => `Tags: [${selectedHit()?.entry.tags ?? ""}]`
880
+ ),
881
+ el(
882
+ "box",
883
+ {
884
+ flexDirection: "row",
885
+ flexWrap: "wrap",
886
+ marginTop: 1,
887
+ },
888
+ createComponent(For, {
889
+ get each() {
890
+ return splitHighlightedText(
891
+ selectedHit()?.entry.fact ?? "",
892
+ query()
893
+ );
894
+ },
895
+ children: (seg: { text: string; match: boolean }) =>
896
+ el(
897
+ "text",
898
+ {
899
+ fg: () =>
900
+ seg.match
901
+ ? theme().text.action.primary.base
902
+ : theme().text.base,
903
+ attributes: () =>
904
+ seg.match ? TextAttributes.BOLD : undefined,
905
+ },
906
+ seg.text
907
+ ),
908
+ })
909
+ ),
910
+ createComponent(Show, {
911
+ get when() {
912
+ return Boolean(selectedSessionBody());
913
+ },
914
+ get children() {
915
+ return el(
916
+ "box",
917
+ {
918
+ flexDirection: "column",
919
+ marginTop: 1,
920
+ paddingTop: 1,
921
+ border: ["top"],
922
+ borderColor: () => theme().border.base,
923
+ },
924
+ el(
925
+ "text",
926
+ {
927
+ fg: () => theme().text.base,
928
+ attributes: TextAttributes.BOLD,
929
+ },
930
+ "Full Session Checkpoint Markdown:"
931
+ ),
932
+ el(
933
+ "text",
934
+ { fg: () => theme().text.muted, wrapMode: "word" },
935
+ () => selectedSessionBody()
936
+ )
937
+ );
938
+ },
939
+ })
940
+ );
941
+ },
942
+ })
943
+ )
944
+ ),
945
+
946
+ // 4. Footer Bar
947
+ el(
948
+ "box",
949
+ {
950
+ flexDirection: "row",
951
+ justifyContent: "space-between",
952
+ paddingX: 2,
953
+ paddingY: 1,
954
+ flexShrink: 0,
955
+ border: ["top"],
956
+ borderColor: () => theme().border.base,
957
+ },
958
+ el(
959
+ "text",
960
+ { fg: () => theme().text.muted },
961
+ "enter select · ↑/↓ or ^n/^k move · ^t type · ^g topic · ^r mode · ^l resync · tab pane · esc"
962
+ ),
963
+ el(
964
+ "text",
965
+ { fg: () => theme().text.muted },
966
+ "0 tokens (100% local)"
967
+ )
968
+ )
969
+ );
970
+ }
971
+
972
+ return (props: DialogProps) => createComponent(LocalMemoryDialog, props);
973
+ }
974
+
975
+ async function openFallbackSelectDialog(
976
+ context: TuiPluginContext,
977
+ rootDir: string,
978
+ initialQuery: string
979
+ ) {
980
+ const hits: MemoryHit[] = initialQuery.trim()
981
+ ? await searchMemory(rootDir, initialQuery, "hybrid", 40)
982
+ : ((loadCachedVectors(rootDir) || []) as MemoryEntry[])
983
+ .slice()
984
+ .reverse()
985
+ .map((entry) => ({ score: 1, semanticScore: 0, entry }));
986
+
987
+ if (!hits.length) {
988
+ context.ui.toast.show({
989
+ title: "Local Memory",
990
+ message: initialQuery
991
+ ? `No memories matched "${initialQuery}".`
992
+ : "No memories found.",
993
+ variant: "warning",
994
+ });
995
+ return;
996
+ }
997
+
998
+ const options = hits.map((h) => ({
999
+ title: `[${h.entry.id}] (${h.entry.file})`,
1000
+ value: h.entry.id,
1001
+ description: h.entry.fact,
1002
+ footer: `Tags: [${h.entry.tags}] · Date: ${h.entry.date || "N/A"}`,
1003
+ }));
1004
+
1005
+ await context.ui.dialog.select<string>({
1006
+ title: initialQuery ? `Local Memory: "${initialQuery}" (0 tokens)` : "Local Memory (0 tokens)",
1007
+ placeholder: "Filter memories...",
1008
+ options,
1009
+ });
1010
+ }
1011
+
1012
+ export default {
1013
+ id: "opencode-local-memory",
1014
+ async setup(context: TuiPluginContext) {
1015
+ if (!context?.ui) {
1016
+ return;
1017
+ }
1018
+ const rootDir = resolveMemoryDir((context as any)?.options?.directory);
1019
+ const renderDialogPromise = loadTuiRenderer().catch(() => null);
1020
+
1021
+ const openMemoryPopup = async (rawArgs?: string) => {
1022
+ const initialQuery = typeof rawArgs === "string" ? rawArgs.trim() : "";
1023
+ const renderDialog = await renderDialogPromise;
1024
+ if (!renderDialog) {
1025
+ await openFallbackSelectDialog(context, rootDir, initialQuery);
1026
+ return;
1027
+ }
1028
+
1029
+ try {
1030
+ context.ui.dialog.show(() =>
1031
+ renderDialog({
1032
+ context,
1033
+ rootDir,
1034
+ initialQuery,
1035
+ close: () => context.ui.dialog.clear(),
1036
+ })
1037
+ );
1038
+ context.ui.dialog.set({
1039
+ size: "xlarge",
1040
+ centered: true,
1041
+ });
1042
+ } catch {
1043
+ await openFallbackSelectDialog(context, rootDir, initialQuery);
1044
+ }
1045
+ };
1046
+
1047
+ const quickStoreFromSlash = async (rawArgs?: string) => {
1048
+ const text = typeof rawArgs === "string" ? rawArgs.trim() : "";
1049
+ const parts = text.split("|").map((s) => s.trim());
1050
+ if (parts.length < 2) {
1051
+ context.ui.toast.show({
1052
+ title: "Local Memory Add (0 tokens)",
1053
+ message: "Usage: /memory-add <topic> | <tags> | <fact> (or /memory-add <topic> | <fact>)",
1054
+ variant: "warning",
1055
+ });
1056
+ return;
1057
+ }
1058
+ const topic = parts[0] || "preferences";
1059
+ const tags = parts.length >= 3 ? parts[1] : topic;
1060
+ const fact = parts.length >= 3 ? parts.slice(2).join(" | ") : parts[1];
1061
+ try {
1062
+ const saved = await storeMemoryFact(rootDir, { topic, tags, fact });
1063
+ context.ui.toast.show({
1064
+ title: `Stored [${saved.id}] (0 tokens)`,
1065
+ message: `${saved.file}: ${saved.fact.slice(0, 90)}`,
1066
+ variant: "success",
1067
+ });
1068
+ } catch (err) {
1069
+ context.ui.toast.show({
1070
+ title: "Local Memory Error",
1071
+ message: err instanceof Error ? err.message : String(err),
1072
+ variant: "error",
1073
+ });
1074
+ }
1075
+ };
1076
+
1077
+ context.ui.slot({
1078
+ append: "app",
1079
+ render() {
1080
+ context.keymap.layer(() => ({
1081
+ mode: "global",
1082
+ commands: [
1083
+ {
1084
+ id: "local.memory.search",
1085
+ title: "Search local memory (0 tokens)...",
1086
+ description:
1087
+ "Interactive zero-token popup to search local memories (topics/*.md + sessions/*.md) with semantic + keyword + regex matching",
1088
+ category: "Memory",
1089
+ palette: true,
1090
+ slash: {
1091
+ name: "memory",
1092
+ arguments: true,
1093
+ },
1094
+ run: (input) => {
1095
+ const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
1096
+ void openMemoryPopup(rawArgs);
1097
+ },
1098
+ },
1099
+ {
1100
+ id: "local.memory.add",
1101
+ title: "Store local memory fact (0 tokens)...",
1102
+ description:
1103
+ "Zero-token slash command to store a memory fact directly: /memory-add <topic> | <tags> | <fact>",
1104
+ category: "Memory",
1105
+ palette: false,
1106
+ slash: {
1107
+ name: "memory-add",
1108
+ arguments: true,
1109
+ },
1110
+ run: (input) => {
1111
+ const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
1112
+ void quickStoreFromSlash(rawArgs);
1113
+ },
1114
+ },
1115
+ ],
1116
+ }));
1117
+ return null;
1118
+ },
1119
+ });
1120
+ },
1121
+ };