@nandoblanco/opencode-local-memory 0.0.0-stage → 1.0.1

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