@aeondave/pi-persona-mind 0.9.1 → 0.9.2

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/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.2](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.9.2) - 2026-11-18
6
+
7
+ - F10 divides its title, content and keys with the same rules as F9, and its key legend uses the
8
+ same glyphs for the plain keys (`↑↓`, `⏎`, `esc`). The margin above and below the content comes
9
+ from the shared inspector frame of pi-persona 1.19.0; with 1.18.1 the window keeps its previous
10
+ height.
11
+
5
12
  ## [0.9.1](https://github.com/AeonDave/pi-persona-mind/releases/tag/v0.9.1) - 2026-11-18
6
13
 
7
14
  - Require pi-persona 1.18.1 or later for the shared F9/F10 inspector frame.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <h1 align="center">pi-persona-mind</h1>
2
2
 
3
3
  <p align="center">
4
- <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.1/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
4
+ <img src="https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.2/assets/banner.png" alt="pi-persona-mind — durable memory for Pi">
5
5
  </p>
6
6
 
7
7
  [![CI](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/AeonDave/pi-persona-mind/actions/workflows/test.yml)
@@ -25,7 +25,7 @@ knowledge reviews use the current session model and incur model usage.
25
25
 
26
26
  ## Quick start
27
27
 
28
- Mind 0.9.1 requires **Pi 1.5.2**, **Node.js 22.19.0+**, and
28
+ Mind 0.9.2 requires **Pi 1.5.2**, **Node.js 22.19.0+**, and
29
29
  [**pi-persona 1.18.1+**](https://github.com/AeonDave/pi-persona) loaded in the same instance.
30
30
 
31
31
  ```bash
package/docs/DESIGN.md CHANGED
@@ -17,7 +17,7 @@ patch an installed host.
17
17
  Mind requires a loaded compatible pi-persona through its versioned local companion handshake.
18
18
  Missing/incompatible presence leaves tools inactive and suppresses capture, storage/import,
19
19
  injection and reminders. A settings file or installed npm package is not proof of an active
20
- companion. Mind 0.9.1 requires Persona 1.18.1 or later for these paired contracts. Its optional npm
20
+ companion. Mind 0.9.2 requires Persona 1.18.1 or later for these paired contracts. Its optional npm
21
21
  peer declares that requirement without auto-installing or activating another extension.
22
22
 
23
23
  The node-only core has no Pi imports. The factory wires native Pi hooks, tools, scope, scheduling
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeondave/pi-persona-mind",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local memory for Pi with pi-persona — durable project and persona facts, session notes, bounded retrieval, and supervised automatic consolidation.",
@@ -52,7 +52,7 @@
52
52
  "verify": "npm run typecheck && npm test"
53
53
  },
54
54
  "pi": {
55
- "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.1/assets/banner.png",
55
+ "image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.2/assets/banner.png",
56
56
  "extensions": [
57
57
  "./src/index.ts"
58
58
  ]
@@ -1,145 +1,145 @@
1
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { getKeybindings, setKeybindings, Input, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type Focusable, type TUI, type KeybindingsManager } from "@earendil-works/pi-tui";
3
- import type { InspectorItem, InspectorPage, InspectorRequest, InspectorScope, InspectorTab } from "../extension/inspector-data.ts";
4
- import { sanitizeCardText } from "./presentation.ts";
5
- import type { InspectorFrame } from "./inspector-frame.ts";
6
-
7
- const TABS: InspectorTab[] = ["memories", "context", "timeline"];
8
- const TAB_LABELS: Record<InspectorTab, string> = { memories: "Memories", context: "Context", timeline: "Timeline" };
9
- const SCOPES: InspectorScope[] = ["session", "project", "project-long", "persona", "shared"];
10
-
11
- export interface MemoryInspectorOptions {
12
- frame?: InspectorFrame;
13
- load: (request: InspectorRequest) => Promise<InspectorPage>;
14
- isCurrent: () => boolean;
15
- initialTab?: InspectorTab;
16
- signal?: AbortSignal;
17
- /** Allocated overlay rows; matches the host overlay maxHeight after margins. */
18
- viewportHeight?: () => number;
19
- onAction?: (request: InspectorRequest & { selectedId?: string }) => Promise<void>;
20
- }
21
-
22
- type View = "list" | "detail" | "source" | "help";
23
-
24
- export class MemoryInspectorComponent implements Component, Focusable {
25
- private tab: InspectorTab;
26
- private scope: InspectorScope = "session";
27
- private query = "";
28
- private _focused = false;
29
- private helpReturn: Exclude<View, "help"> = "list";
30
- private sourceReturn: "list" | "detail" = "list";
31
- private helpScroll = 0;
32
- private wrappedCache: { width: number; body: string; lines: string[] } | undefined;
33
- private page: InspectorPage | undefined;
34
- private selected = 0;
35
- private view: View = "list";
36
- private item: InspectorItem | undefined;
37
- private offsets: number[] = [0];
38
- private generation = 0;
39
- private closed = false;
40
- private loading = true;
41
- private error = "";
42
- private searching = false;
43
- private detailScroll = 0;
44
- private sourceScroll = 0;
45
- private listStart = 0;
46
- private listCapacity = 1;
47
- private detailCapacity = 1;
48
- private readonly frame: InspectorFrame;
49
- private readonly searchInput = new Input({ prompt: "/ " });
50
- private pendingAction: (InspectorRequest & { selectedId?: string }) | undefined;
51
-
52
- get focused(): boolean { return this._focused; }
53
- set focused(value: boolean) { this._focused = value; this.searchInput.focused = value && this.searching; }
54
- readonly capturesViewportInput = true;
55
- private readonly onAbort: () => void;
56
- private readonly tui: TUI;
57
- private readonly theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string };
58
- private readonly keybindings: KeybindingsManager;
59
- private readonly done: (result: void) => void;
60
- private readonly options: MemoryInspectorOptions;
61
-
62
- constructor(
63
- tui: TUI,
64
- theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
65
- keybindings: KeybindingsManager,
66
- done: (result: void) => void,
67
- options: MemoryInspectorOptions,
68
- ) {
69
- this.tui = tui;
70
- this.theme = theme;
71
- this.keybindings = keybindings;
72
- this.searchInput.onEscape = () => { this.setSearching(false); this.tui.requestRender(); };
73
- this.searchInput.onSubmit = (value) => {
74
- this.query = sanitizeCardText(value);
75
- this.setSearching(false);
76
- this.resetAndLoad();
77
- this.tui.requestRender();
78
- };
79
- this.done = done;
80
- this.options = options;
81
- if (!options.frame) throw new Error("Inspector frame requires compatible loaded pi-persona");
82
- this.frame = options.frame;
83
- this.tab = options.initialTab ?? "memories";
84
- this.onAbort = () => this.close();
85
- if (options.signal?.aborted) this.close();
86
- else options.signal?.addEventListener("abort", this.onAbort, { once: true });
87
- if (!this.closed) this.startLoad();
88
- }
89
-
90
- private isCurrent(): boolean {
91
- if (this.closed) return false;
92
- if (!this.options.isCurrent()) { this.close(); return false; }
93
- return true;
94
- }
95
-
96
- private close(): void {
97
- if (this.closed) return;
98
- this.closed = true;
99
- this.generation++;
100
- this.options.signal?.removeEventListener("abort", this.onAbort);
101
- this.done();
102
- }
103
-
104
- private request(): InspectorRequest {
105
- return { tab: this.tab, scope: this.scope, query: this.query, offset: this.offsets.at(-1) ?? 0 };
106
- }
107
-
108
- private startLoad(): void {
109
- const generation = ++this.generation;
110
- this.loading = true;
111
- this.error = "";
112
- this.page = undefined;
113
- this.selected = 0;
114
- const req = this.request();
115
- // Always consume rejections: input handlers and the component factory are synchronous.
116
- void this.options.load(req).then((result) => {
117
- if (!this.isCurrent() || generation !== this.generation) return;
118
- this.page = result;
119
- this.loading = false;
120
- this.error = "";
121
- this.selected = Math.min(this.selected, Math.max(0, result.items.length - 1));
122
- this.tui.requestRender();
123
- }, (error: unknown) => {
124
- if (!this.isCurrent() || generation !== this.generation) return;
125
- this.loading = false;
126
- this.error = error instanceof Error ? error.message : "Unable to load inspector data";
127
- this.tui.requestRender();
128
- }).catch(() => { /* Keep the custom UI path free of unhandled callback failures. */ });
129
- }
130
-
131
- private resetAndLoad(): void { this.offsets = [0]; this.view = "list"; this.item = undefined; this.startLoad(); }
132
-
133
- private switchTab(): void {
134
- this.tab = TABS[(TABS.indexOf(this.tab) + 1) % TABS.length]!;
135
- this.query = "";
136
- this.searchInput.setValue("");
137
- this.resetAndLoad();
138
- }
139
-
140
- handleInput(data: string): void {
141
- if (!this.isCurrent()) return;
142
- if (matchesKey(data, "f10")) { this.close(); return; }
3
+ import type { InspectorItem, InspectorPage, InspectorRequest, InspectorScope, InspectorTab } from "../extension/inspector-data.ts";
4
+ import { sanitizeCardText } from "./presentation.ts";
5
+ import type { InspectorFrame } from "./inspector-frame.ts";
6
+
7
+ const TABS: InspectorTab[] = ["memories", "context", "timeline"];
8
+ const TAB_LABELS: Record<InspectorTab, string> = { memories: "Memories", context: "Context", timeline: "Timeline" };
9
+ const SCOPES: InspectorScope[] = ["session", "project", "project-long", "persona", "shared"];
10
+
11
+ export interface MemoryInspectorOptions {
12
+ frame?: InspectorFrame;
13
+ load: (request: InspectorRequest) => Promise<InspectorPage>;
14
+ isCurrent: () => boolean;
15
+ initialTab?: InspectorTab;
16
+ signal?: AbortSignal;
17
+ /** Allocated overlay rows; matches the host overlay maxHeight after margins. */
18
+ viewportHeight?: () => number;
19
+ onAction?: (request: InspectorRequest & { selectedId?: string }) => Promise<void>;
20
+ }
21
+
22
+ type View = "list" | "detail" | "source" | "help";
23
+
24
+ export class MemoryInspectorComponent implements Component, Focusable {
25
+ private tab: InspectorTab;
26
+ private scope: InspectorScope = "session";
27
+ private query = "";
28
+ private _focused = false;
29
+ private helpReturn: Exclude<View, "help"> = "list";
30
+ private sourceReturn: "list" | "detail" = "list";
31
+ private helpScroll = 0;
32
+ private wrappedCache: { width: number; body: string; lines: string[] } | undefined;
33
+ private page: InspectorPage | undefined;
34
+ private selected = 0;
35
+ private view: View = "list";
36
+ private item: InspectorItem | undefined;
37
+ private offsets: number[] = [0];
38
+ private generation = 0;
39
+ private closed = false;
40
+ private loading = true;
41
+ private error = "";
42
+ private searching = false;
43
+ private detailScroll = 0;
44
+ private sourceScroll = 0;
45
+ private listStart = 0;
46
+ private listCapacity = 1;
47
+ private detailCapacity = 1;
48
+ private readonly frame: InspectorFrame;
49
+ private readonly searchInput = new Input({ prompt: "/ " });
50
+ private pendingAction: (InspectorRequest & { selectedId?: string }) | undefined;
51
+
52
+ get focused(): boolean { return this._focused; }
53
+ set focused(value: boolean) { this._focused = value; this.searchInput.focused = value && this.searching; }
54
+ readonly capturesViewportInput = true;
55
+ private readonly onAbort: () => void;
56
+ private readonly tui: TUI;
57
+ private readonly theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string };
58
+ private readonly keybindings: KeybindingsManager;
59
+ private readonly done: (result: void) => void;
60
+ private readonly options: MemoryInspectorOptions;
61
+
62
+ constructor(
63
+ tui: TUI,
64
+ theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
65
+ keybindings: KeybindingsManager,
66
+ done: (result: void) => void,
67
+ options: MemoryInspectorOptions,
68
+ ) {
69
+ this.tui = tui;
70
+ this.theme = theme;
71
+ this.keybindings = keybindings;
72
+ this.searchInput.onEscape = () => { this.setSearching(false); this.tui.requestRender(); };
73
+ this.searchInput.onSubmit = (value) => {
74
+ this.query = sanitizeCardText(value);
75
+ this.setSearching(false);
76
+ this.resetAndLoad();
77
+ this.tui.requestRender();
78
+ };
79
+ this.done = done;
80
+ this.options = options;
81
+ if (!options.frame) throw new Error("Inspector frame requires compatible loaded pi-persona");
82
+ this.frame = options.frame;
83
+ this.tab = options.initialTab ?? "memories";
84
+ this.onAbort = () => this.close();
85
+ if (options.signal?.aborted) this.close();
86
+ else options.signal?.addEventListener("abort", this.onAbort, { once: true });
87
+ if (!this.closed) this.startLoad();
88
+ }
89
+
90
+ private isCurrent(): boolean {
91
+ if (this.closed) return false;
92
+ if (!this.options.isCurrent()) { this.close(); return false; }
93
+ return true;
94
+ }
95
+
96
+ private close(): void {
97
+ if (this.closed) return;
98
+ this.closed = true;
99
+ this.generation++;
100
+ this.options.signal?.removeEventListener("abort", this.onAbort);
101
+ this.done();
102
+ }
103
+
104
+ private request(): InspectorRequest {
105
+ return { tab: this.tab, scope: this.scope, query: this.query, offset: this.offsets.at(-1) ?? 0 };
106
+ }
107
+
108
+ private startLoad(): void {
109
+ const generation = ++this.generation;
110
+ this.loading = true;
111
+ this.error = "";
112
+ this.page = undefined;
113
+ this.selected = 0;
114
+ const req = this.request();
115
+ // Always consume rejections: input handlers and the component factory are synchronous.
116
+ void this.options.load(req).then((result) => {
117
+ if (!this.isCurrent() || generation !== this.generation) return;
118
+ this.page = result;
119
+ this.loading = false;
120
+ this.error = "";
121
+ this.selected = Math.min(this.selected, Math.max(0, result.items.length - 1));
122
+ this.tui.requestRender();
123
+ }, (error: unknown) => {
124
+ if (!this.isCurrent() || generation !== this.generation) return;
125
+ this.loading = false;
126
+ this.error = error instanceof Error ? error.message : "Unable to load inspector data";
127
+ this.tui.requestRender();
128
+ }).catch(() => { /* Keep the custom UI path free of unhandled callback failures. */ });
129
+ }
130
+
131
+ private resetAndLoad(): void { this.offsets = [0]; this.view = "list"; this.item = undefined; this.startLoad(); }
132
+
133
+ private switchTab(): void {
134
+ this.tab = TABS[(TABS.indexOf(this.tab) + 1) % TABS.length]!;
135
+ this.query = "";
136
+ this.searchInput.setValue("");
137
+ this.resetAndLoad();
138
+ }
139
+
140
+ handleInput(data: string): void {
141
+ if (!this.isCurrent()) return;
142
+ if (matchesKey(data, "f10")) { this.close(); return; }
143
143
  if (this.searching) {
144
144
  const global = getKeybindings();
145
145
  try {
@@ -154,307 +154,311 @@ export class MemoryInspectorComponent implements Component, Focusable {
154
154
  const clean = sanitizeCardText(value);
155
155
  if (clean !== value) this.searchInput.setValue(clean);
156
156
  this.tui.requestRender();
157
- return;
158
- }
159
- if (this.keybindings.matches(data, "tui.select.cancel")) {
160
- if (this.view === "source") this.view = this.sourceReturn;
161
- else if (this.view === "detail") this.view = "list";
162
- else if (this.view === "help") this.view = this.helpReturn;
163
- else this.close();
164
- this.tui.requestRender(); return;
165
- }
166
- if (this.view !== "list") {
167
- if (data === "a" && this.tab === "memories" && this.view === "detail" && this.options.onAction) {
168
- this.pendingAction = { ...this.request(), ...(this.item ? { selectedId: this.item.id } : {}) };
169
- this.close();
170
- return;
171
- }
172
- const currentScroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
173
- const delta = Math.max(1, this.detailCapacity - 1);
174
- if (this.keybindings.matches(data, "tui.select.up")) this.setDetailScroll(Math.max(0, currentScroll - 1));
175
- else if (this.keybindings.matches(data, "tui.select.down")) this.setDetailScroll(currentScroll + 1);
176
- else if (this.keybindings.matches(data, "tui.select.pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) this.setDetailScroll(Math.max(0, currentScroll - delta));
177
- else if (this.keybindings.matches(data, "tui.select.pageDown") || this.keybindings.matches(data, "tui.altScreen.pageDown")) this.setDetailScroll(currentScroll + delta);
178
- else if (data === "s" && this.view === "detail" && this.item?.source) {
179
- this.sourceReturn = "detail"; this.view = "source"; this.sourceScroll = 0;
180
- } else if (data === "?" && this.view !== "help") {
181
- this.helpReturn = this.view; this.helpScroll = 0; this.view = "help";
182
- }
183
- this.tui.requestRender(); return;
184
- }
185
- if (data === "a" && this.tab === "memories" && this.options.onAction) {
186
- const selected = this.page?.items[this.selected];
187
- this.pendingAction = { ...this.request(), ...(selected ? { selectedId: selected.id } : {}) };
188
- this.close();
189
- return;
190
- }
191
- if (matchesKey(data, "tab")) this.switchTab();
192
- else if (matchesKey(data, "shift+tab")) {
193
- this.tab = TABS[(TABS.indexOf(this.tab) + TABS.length - 1) % TABS.length]!;
194
- this.query = ""; this.searchInput.setValue(""); this.resetAndLoad();
195
- }
196
- else if (this.keybindings.matches(data, "tui.select.up") && this.page) this.selected = Math.max(0, this.selected - 1);
197
- else if (this.keybindings.matches(data, "tui.select.down") && this.page) this.selected = Math.max(0, Math.min(this.page.items.length - 1, this.selected + 1));
198
- else if ((this.keybindings.matches(data, "tui.select.pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) && this.page) this.selected = Math.max(0, this.selected - this.listCapacity);
199
- else if ((this.keybindings.matches(data, "tui.select.pageDown") || this.keybindings.matches(data, "tui.altScreen.pageDown")) && this.page) this.selected = Math.max(0, Math.min(this.page.items.length - 1, this.selected + this.listCapacity));
200
- else if (this.keybindings.matches(data, "tui.select.confirm")) {
201
- this.item = this.page?.items[this.selected]; if (this.item) { this.view = "detail"; this.detailScroll = 0; }
202
- } else if (matchesKey(data, "left") && this.tab === "memories") {
203
- this.scope = SCOPES[(SCOPES.indexOf(this.scope) + SCOPES.length - 1) % SCOPES.length]!; this.resetAndLoad();
204
- } else if (matchesKey(data, "right") && this.tab === "memories") {
205
- this.scope = SCOPES[(SCOPES.indexOf(this.scope) + 1) % SCOPES.length]!; this.resetAndLoad();
206
- } else if (data === "/" && this.tab !== "context") {
207
- this.searchInput.setValue(this.query); this.setSearching(true);
208
- } else if (data === "?") {
209
- this.helpReturn = "list"; this.helpScroll = 0; this.view = "help";
210
- } else if (data === "s" && this.page?.items[this.selected]?.source) {
211
- this.item = this.page.items[this.selected]; this.sourceReturn = "list"; this.view = "source"; this.sourceScroll = 0;
212
- } else if (data === "n" && this.page?.nextOffset !== undefined) {
213
- this.offsets.push(this.page.nextOffset); this.startLoad();
214
- } else if (data === "p" && this.offsets.length > 1) {
215
- this.offsets.pop(); this.startLoad();
216
- } else if (data === "r") this.startLoad();
217
- this.tui.requestRender();
218
- }
219
-
220
- private setSearching(value: boolean): void {
221
- this.searching = value;
222
- this.searchInput.focused = this.focused && value;
223
- }
224
-
225
- private setDetailScroll(offset: number): void {
226
- if (this.view === "source") this.sourceScroll = offset;
227
- else if (this.view === "help") this.helpScroll = offset;
228
- else this.detailScroll = offset;
229
- }
230
-
231
- render(width: number, height?: number): string[] {
232
- if (!this.isCurrent() || width <= 0) return [];
233
- const layout = this.frame.layout(width, height ?? this.options.viewportHeight?.() ?? this.tui.terminal?.rows ?? 1);
234
- return this.frame.render(this.renderContent(layout.contentWidth, layout.contentRows), layout, (text) => this.theme.fg("border", text));
235
- }
236
-
237
- private renderContent(safeWidth: number, rows: number): string[] {
238
- const t = this.theme;
239
- const oneLine = (value: string) => sanitizeCardText(value).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
240
- const fit = (value: string) => truncateToWidth(value, safeWidth, "…");
241
- const dim = (value: string) => t.fg("dim", fit(value));
242
- const accent = (value: string) => t.fg("accent", fit(value));
243
- const key = (action: "tui.select.up" | "tui.select.down" | "tui.select.confirm" | "tui.input.submit" | "tui.select.cancel" | "tui.select.pageUp" | "tui.select.pageDown") => {
244
- const names = this.keybindings.getKeys(action);
245
- return names.length ? names.map((name) => name.replace(/^pageUp$/i, "PgUp").replace(/^pageDown$/i, "PgDn").replace(/^escape$/i, "Esc").replace(/^return$/i, "Enter").replace(/(^|[+])([a-z])/g, (_match, prefix: string, letter: string) => `${prefix}${letter.toUpperCase()}`)).join("/") : "unbound";
246
- };
247
- const pair = (left: "tui.select.up" | "tui.select.down" | "tui.select.pageUp" | "tui.select.pageDown", right: "tui.select.up" | "tui.select.down" | "tui.select.pageUp" | "tui.select.pageDown") => {
248
- const first = key(left);
249
- const second = key(right);
250
- return first === "unbound" || second === "unbound" ? "unbound" : `${first}/${second}`;
251
- };
252
- const selected = this.page?.items[this.selected];
253
- const status = this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : undefined;
254
- const result: string[] = [];
255
- const footer = (parts: string[]) => wrapTextWithAnsi(parts.join(" · "), safeWidth).map(dim);
256
- if (this.view === "list") {
257
- this.listCapacity = 1;
258
- const compactItems = this.page?.items ?? [];
259
- const scopeNames: Record<InspectorScope, string> = { session: "Session", project: "Working", "project-long": "Project", persona: "Persona", shared: "Shared" };
260
- const activeScope = this.tab === "memories" ? accent(t.bold(scopeNames[this.scope])) : accent(t.bold(TAB_LABELS[this.tab]));
261
- if (this.searching) {
262
- this.searchInput.focused = this.focused;
263
- if (rows >= 3) result.push(accent(t.bold("Memory inspector")));
264
- if (rows >= 7) result.push("");
265
- if (rows >= 4) result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
266
- result.push(this.searchInput.render(safeWidth)[0] ?? "/");
267
- if (rows >= 7) result.push("");
268
- if (rows >= 2) result.push(dim(`${key("tui.input.submit")} apply · ${key("tui.select.cancel")} cancel`));
269
- return result.slice(0, rows).map(fit);
270
- }
271
- if (rows <= 4) {
272
- const compact = compactItems[this.selected];
273
- const selection = compact ? accent(`▸ ${oneLine(compact.title)}`) : this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : dim("No items");
274
- if (rows === 1) result.push(selection);
275
- else { result.push(activeScope); result.push(selection); }
276
- return result.slice(0, rows).map(fit);
277
- }
278
- if (rows <= 9 || safeWidth < 20) {
279
- result.push(accent(t.bold("Memory inspector")));
280
- result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
281
- const compact = compactItems[this.selected];
282
- if (compact) result.push(accent(`▸ ${oneLine(compact.title)}`));
283
- else if (this.loading) result.push(dim("Loading…"));
284
- else if (this.error) result.push(t.fg("error", fit(oneLine(this.error))));
285
- else result.push(dim("No items"));
286
- if (rows >= 6 && compactItems.length) result.push(dim(`${(this.page?.offset ?? 0) + this.selected + 1} selected · ${(this.page?.offset ?? 0) + 1}-${(this.page?.offset ?? 0) + compactItems.length} of ${this.page?.total ?? 0}`));
287
- if (rows >= 7) result.push(dim(`${pair("tui.select.up", "tui.select.down")} select · ${key("tui.select.confirm")} open · ${key("tui.select.cancel")}/F10 close`));
288
- return result.slice(0, rows).map(fit);
289
- }
290
- result.push(accent(t.bold("Memory inspector")));
291
- result.push(TABS.map((tab) => tab === this.tab ? accent(t.bold(`[${TAB_LABELS[tab]}]`)) : dim(TAB_LABELS[tab])).join(dim(" ")));
292
- if (this.tab === "memories") {
293
- const scopeStrip = safeWidth >= 72 ? ` · ${SCOPES.map((scope) => scope === this.scope ? accent(t.bold(`[${scopeNames[scope]}]`)) : dim(scopeNames[scope])).join(dim(" "))}` : "";
294
- result.push(`${dim("Scope: ")}${activeScope}${scopeStrip}`);
295
- } else result.push(dim(`Search: ${this.query ? oneLine(this.query) : "none"} · Tab switch clears search`));
296
- if (this.tab === "memories") result.push(dim(`Search: ${this.query ? oneLine(this.query) : "none"} · Tab switch clears search`));
297
- const items = this.page?.items ?? [];
298
- const total = this.page?.total ?? 0;
299
- const offset = this.page?.offset ?? 0;
300
- const current = items.length ? `${offset + Math.min(this.selected + 1, items.length)} selected · ${offset + 1}-${offset + items.length} of ${total}` : `0 selected · 0 of ${total}`;
301
- if (status) result.push(status);
302
- result.push(dim(current));
303
- if (this.page?.notice) result.push(dim("Coverage notice · ? help"));
304
- if (!this.loading && !this.error && items.length === 0) result.push(dim("No items on this page."));
305
- const optional: string[] = [];
306
- if (this.tab === "memories") optional.push("←/→ scope");
307
- if (this.tab !== "context") optional.push("/ search");
308
- if (this.tab === "memories" && this.options.onAction) optional.push("a actions");
309
- if (selected?.source) optional.push("s source");
310
- if (this.page?.nextOffset !== undefined || this.offsets.length > 1) optional.push("n/p result pages");
311
- let footers = [footer(["Tab / Shift+Tab tabs", ...optional.slice(0, 2)]), footer([`${pair("tui.select.up", "tui.select.down")} select`, `${key("tui.select.confirm")} open`, ...optional.slice(2, 4)]), footer(["? help", `${key("tui.select.cancel")}/F10 close`, ...optional.slice(4)])].flat();
312
- if (rows - result.length - footers.length < 1) footers = [dim(`? help · ${key("tui.select.cancel")}/F10 close`)];
313
- // Spend whitespace only when at least one record still fits. Match F9's
314
- // title/content/footer separation rather than crowding the frame chrome.
315
- const spaced = rows - result.length - footers.length >= 4;
316
- if (spaced) { result.splice(1, 0, ""); result.push(""); }
317
- const capacity = Math.max(0, rows - result.length - footers.length - Number(spaced));
318
- this.listCapacity = Math.max(1, capacity);
319
- const maxStart = Math.max(0, items.length - capacity);
320
- this.listStart = Math.min(this.listStart, maxStart);
321
- if (this.selected < this.listStart) this.listStart = this.selected;
322
- else if (capacity > 0 && this.selected >= this.listStart + capacity) this.listStart = this.selected - capacity + 1;
323
- for (let i = this.listStart; i < Math.min(items.length, this.listStart + capacity); i++) {
324
- const entry = items[i]!;
325
- const marker = entry.source ? " [source]" : "";
326
- const line = `${i === this.selected ? "▸ " : " "}${oneLine(entry.title)}`;
327
- const rendered = i === this.selected ? `${accent(line)}${marker ? dim(marker) : ""}` : `${fit(line)}${marker ? dim(marker) : ""}`;
328
- result.push(truncateToWidth(rendered, safeWidth));
329
- }
330
- if (spaced) result.push("");
331
- result.push(...footers);
332
- } else {
333
- let breadcrumb: string;
334
- if (this.view === "help") breadcrumb = `Memory inspector › ${TAB_LABELS[this.tab]} › Help`;
335
- else {
336
- const prefix = `Memory inspector › ${TAB_LABELS[this.tab]} › `;
337
- const suffix = this.view === "source" ? " › Source" : "";
338
- const titleWidth = Math.max(1, safeWidth - visibleWidth(prefix) - visibleWidth(suffix));
339
- breadcrumb = `${prefix}${truncateToWidth(oneLine(this.item?.title ?? "Detail"), titleWidth, "…")}${suffix}`;
340
- }
341
- result.push(accent(t.bold(breadcrumb)));
342
- let body: string;
343
- const missingSource = this.view === "detail" && !this.item?.source;
344
- if (this.view === "help") {
345
- const actions = this.tab === "memories" && this.options.onAction ? "a runs the explicit memory action (closes this view first)." : "No explicit action is available in this view.";
346
- const helpItem = this.helpReturn === "list" ? selected : this.item;
347
- const sourceHelp = helpItem?.source ? `s opens the linked source text; ${key("tui.select.cancel")} returns to the view that opened it.` : "Source text is read-only; it is shown only when linked to a record.";
348
- body = [
349
- "Navigation: In the list, Tab / Shift+Tab switch tabs; switching tabs clears the search query. ← / → changes memory scope in the Memories list only.",
350
- `${key("tui.select.up")} / ${key("tui.select.down")} moves selection within a list; ${key("tui.select.confirm")} opens the selected record. In detail/source/help, the arrow keys scroll the current text instead.`,
351
- "n / p moves to the next / previous result page only when available. / starts search in Memories and Timeline; Context has no search.",
352
- `${sourceHelp} ${actions}`,
353
- "Records and linked sources are read-only here. A linked source is a reference, not independent verification. Explicit actions are separate from reading; the cancel key goes back, F10 closes.",
354
- "Scope names: Session is session-only; Working is API project (working memory); Project is API project-long; Persona and Shared are wider durable scopes.",
355
- this.page?.notice || "No additional coverage notice.",
356
- ].join("\n\n");
357
- } else if (this.view === "source") body = this.item?.source?.body ?? "";
358
- else body = this.item?.body ?? "";
359
- let wrapped: string[];
360
- if (this.wrappedCache?.width === safeWidth && this.wrappedCache.body === body) wrapped = this.wrappedCache.lines;
361
- else {
362
- wrapped = wrapTextWithAnsi(sanitizeCardText(body), safeWidth);
363
- // Width changes reflow text: retain the first visible text, not its old wrapped-row index.
364
- if (this.wrappedCache?.body === body) {
365
- const previousScroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
366
- const length = (line: string) => line.replace(/\s/g, "").length;
367
- const offset = this.wrappedCache.lines.slice(0, previousScroll).reduce((total, line) => total + length(line), 0);
368
- let consumed = 0;
369
- let mapped = 0;
370
- while (mapped < wrapped.length - 1 && consumed + length(wrapped[mapped]!) <= offset) consumed += length(wrapped[mapped++]!);
371
- this.setDetailScroll(mapped);
372
- }
373
- this.wrappedCache = { width: safeWidth, body, lines: wrapped };
374
- }
375
- const displayWrapped = [...wrapped];
376
- const missingSourceIndex = missingSource ? displayWrapped.push("", "Source unavailable for this item.") - 1 : -1;
377
- const actions = this.view === "detail" && this.tab === "memories" && this.options.onAction ? ["a actions"] : [];
378
- const pageKeys = `${pair("tui.select.pageUp", "tui.select.pageDown")} page`;
379
- let footers = safeWidth < 20
380
- ? [dim(`↑↓ scroll/${key("tui.select.cancel")}`)]
381
- : safeWidth < 32
382
- ? footer([`${pair("tui.select.up", "tui.select.down")} scroll`, `${key("tui.select.cancel")} back`])
383
- : [
384
- ...footer([`${pair("tui.select.up", "tui.select.down")} scroll`, pageKeys]),
385
- ...footer([...(this.view === "detail" && this.item?.source ? ["s source"] : []), ...actions, `${key("tui.select.cancel")} back`, "F10 close"]),
386
- ];
387
- const scroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
388
- // Content wins over chrome, including extremely short detail/source/help views.
389
- if (rows < 3) result.length = 0;
390
- const indicatorRows = rows >= 5 ? 2 : 0;
391
- if (rows - result.length - footers.length - indicatorRows < 1) {
392
- footers = rows - result.length - indicatorRows >= 2 ? [dim(`${key("tui.select.cancel")} back · F10 close`)] : [];
393
- }
394
- const spaced = rows - result.length - footers.length - indicatorRows >= 3;
395
- if (spaced) result.push("");
396
- const capacity = Math.max(0, rows - result.length - footers.length - indicatorRows - Number(spaced));
397
- this.detailCapacity = Math.max(1, capacity);
398
- const maxStart = Math.max(0, displayWrapped.length - capacity);
399
- const start = Math.min(scroll, maxStart);
400
- this.setDetailScroll(start);
401
- if (indicatorRows && start > 0) result.push(dim(`▲ ${start} lines above`));
402
- result.push(...displayWrapped.slice(start, start + capacity).map((line, index) => start + index === missingSourceIndex ? t.fg("warning", fit(line)) : this.view === "help" ? dim(line) : fit(line)));
403
- if (indicatorRows && start + capacity < displayWrapped.length) result.push(dim(`▼ ${displayWrapped.length - start - capacity} lines below`));
404
- if (spaced) result.push("");
405
- result.push(...footers);
406
- }
407
- return result.slice(0, rows).map(fit);
408
- }
409
-
410
- takeAction(): (InspectorRequest & { selectedId?: string }) | undefined {
411
- const action = this.pendingAction;
412
- this.pendingAction = undefined;
413
- return action;
414
- }
415
-
416
- invalidate(): void {}
417
- dispose(): void { this.options.signal?.removeEventListener("abort", this.onAbort); this.closed = true; this.generation++; }
418
- }
419
-
420
- export function createMemoryInspectorComponent(
421
- tui: TUI,
422
- theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
423
- keybindings: KeybindingsManager,
424
- done: (result: void) => void,
425
- options: MemoryInspectorOptions,
426
- ): MemoryInspectorComponent {
427
- return new MemoryInspectorComponent(tui, theme, keybindings, done, options);
428
- }
429
-
430
- export async function openMemoryInspector(
431
- ctx: ExtensionContext,
432
- options: MemoryInspectorOptions,
433
- ): Promise<void> {
434
- if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires interactive mode", "warning"); return; }
435
- if (options.signal?.aborted || !options.isCurrent()) return;
436
- const frame = options.frame;
437
- if (!frame) { ctx.ui.notify("Memory inspector unavailable: reload a compatible pi-persona extension.", "warning"); return; }
438
- try {
439
- let overlayTui: TUI | undefined;
440
- let component: MemoryInspectorComponent | undefined;
441
- await ctx.ui.custom<void>((tui, theme, keybindings, done) => {
442
- overlayTui = tui;
443
- component = new MemoryInspectorComponent(tui, theme, keybindings, done, {
444
- ...options,
445
- viewportHeight: () => frame.viewportRows(tui.terminal?.rows ?? 1),
446
- });
447
- return component;
448
- }, {
449
- overlay: true,
450
- overlayOptions: () => {
451
- const rows = overlayTui?.terminal?.rows ?? 1;
452
- return { width: "90%", maxHeight: frame.viewportRows(rows), margin: 1 };
453
- },
454
- });
455
- const action = component?.takeAction();
456
- if (action && !options.signal?.aborted && options.isCurrent() && options.onAction) await options.onAction(action);
457
- } catch (error) {
458
- if (!options.signal?.aborted && options.isCurrent()) ctx.ui.notify(`Memory inspector closed: ${error instanceof Error ? error.message : "unknown error"}`, "warning");
459
- }
460
- }
157
+ return;
158
+ }
159
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
160
+ if (this.view === "source") this.view = this.sourceReturn;
161
+ else if (this.view === "detail") this.view = "list";
162
+ else if (this.view === "help") this.view = this.helpReturn;
163
+ else this.close();
164
+ this.tui.requestRender(); return;
165
+ }
166
+ if (this.view !== "list") {
167
+ if (data === "a" && this.tab === "memories" && this.view === "detail" && this.options.onAction) {
168
+ this.pendingAction = { ...this.request(), ...(this.item ? { selectedId: this.item.id } : {}) };
169
+ this.close();
170
+ return;
171
+ }
172
+ const currentScroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
173
+ const delta = Math.max(1, this.detailCapacity - 1);
174
+ if (this.keybindings.matches(data, "tui.select.up")) this.setDetailScroll(Math.max(0, currentScroll - 1));
175
+ else if (this.keybindings.matches(data, "tui.select.down")) this.setDetailScroll(currentScroll + 1);
176
+ else if (this.keybindings.matches(data, "tui.select.pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) this.setDetailScroll(Math.max(0, currentScroll - delta));
177
+ else if (this.keybindings.matches(data, "tui.select.pageDown") || this.keybindings.matches(data, "tui.altScreen.pageDown")) this.setDetailScroll(currentScroll + delta);
178
+ else if (data === "s" && this.view === "detail" && this.item?.source) {
179
+ this.sourceReturn = "detail"; this.view = "source"; this.sourceScroll = 0;
180
+ } else if (data === "?" && this.view !== "help") {
181
+ this.helpReturn = this.view; this.helpScroll = 0; this.view = "help";
182
+ }
183
+ this.tui.requestRender(); return;
184
+ }
185
+ if (data === "a" && this.tab === "memories" && this.options.onAction) {
186
+ const selected = this.page?.items[this.selected];
187
+ this.pendingAction = { ...this.request(), ...(selected ? { selectedId: selected.id } : {}) };
188
+ this.close();
189
+ return;
190
+ }
191
+ if (matchesKey(data, "tab")) this.switchTab();
192
+ else if (matchesKey(data, "shift+tab")) {
193
+ this.tab = TABS[(TABS.indexOf(this.tab) + TABS.length - 1) % TABS.length]!;
194
+ this.query = ""; this.searchInput.setValue(""); this.resetAndLoad();
195
+ }
196
+ else if (this.keybindings.matches(data, "tui.select.up") && this.page) this.selected = Math.max(0, this.selected - 1);
197
+ else if (this.keybindings.matches(data, "tui.select.down") && this.page) this.selected = Math.max(0, Math.min(this.page.items.length - 1, this.selected + 1));
198
+ else if ((this.keybindings.matches(data, "tui.select.pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) && this.page) this.selected = Math.max(0, this.selected - this.listCapacity);
199
+ else if ((this.keybindings.matches(data, "tui.select.pageDown") || this.keybindings.matches(data, "tui.altScreen.pageDown")) && this.page) this.selected = Math.max(0, Math.min(this.page.items.length - 1, this.selected + this.listCapacity));
200
+ else if (this.keybindings.matches(data, "tui.select.confirm")) {
201
+ this.item = this.page?.items[this.selected]; if (this.item) { this.view = "detail"; this.detailScroll = 0; }
202
+ } else if (matchesKey(data, "left") && this.tab === "memories") {
203
+ this.scope = SCOPES[(SCOPES.indexOf(this.scope) + SCOPES.length - 1) % SCOPES.length]!; this.resetAndLoad();
204
+ } else if (matchesKey(data, "right") && this.tab === "memories") {
205
+ this.scope = SCOPES[(SCOPES.indexOf(this.scope) + 1) % SCOPES.length]!; this.resetAndLoad();
206
+ } else if (data === "/" && this.tab !== "context") {
207
+ this.searchInput.setValue(this.query); this.setSearching(true);
208
+ } else if (data === "?") {
209
+ this.helpReturn = "list"; this.helpScroll = 0; this.view = "help";
210
+ } else if (data === "s" && this.page?.items[this.selected]?.source) {
211
+ this.item = this.page.items[this.selected]; this.sourceReturn = "list"; this.view = "source"; this.sourceScroll = 0;
212
+ } else if (data === "n" && this.page?.nextOffset !== undefined) {
213
+ this.offsets.push(this.page.nextOffset); this.startLoad();
214
+ } else if (data === "p" && this.offsets.length > 1) {
215
+ this.offsets.pop(); this.startLoad();
216
+ } else if (data === "r") this.startLoad();
217
+ this.tui.requestRender();
218
+ }
219
+
220
+ private setSearching(value: boolean): void {
221
+ this.searching = value;
222
+ this.searchInput.focused = this.focused && value;
223
+ }
224
+
225
+ private setDetailScroll(offset: number): void {
226
+ if (this.view === "source") this.sourceScroll = offset;
227
+ else if (this.view === "help") this.helpScroll = offset;
228
+ else this.detailScroll = offset;
229
+ }
230
+
231
+ render(width: number, height?: number): string[] {
232
+ if (!this.isCurrent() || width <= 0) return [];
233
+ const layout = this.frame.layout(width, height ?? this.options.viewportHeight?.() ?? this.tui.terminal?.rows ?? 1);
234
+ return this.frame.render(this.renderContent(layout.contentWidth, layout.contentRows), layout, (text) => this.theme.fg("border", text));
235
+ }
236
+
237
+ private renderContent(safeWidth: number, rows: number): string[] {
238
+ const t = this.theme;
239
+ const oneLine = (value: string) => sanitizeCardText(value).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
240
+ const fit = (value: string) => truncateToWidth(value, safeWidth, "…");
241
+ const dim = (value: string) => t.fg("dim", fit(value));
242
+ const accent = (value: string) => t.fg("accent", fit(value));
243
+ const key = (action: "tui.select.up" | "tui.select.down" | "tui.select.confirm" | "tui.input.submit" | "tui.select.cancel" | "tui.select.pageUp" | "tui.select.pageDown") => {
244
+ const names = this.keybindings.getKeys(action);
245
+ // Plain Enter/Escape use the F9 legend's glyphs; a chorded or remapped key keeps its name.
246
+ return names.length ? names.map((name) => /^(?:enter|return)$/i.test(name) ? "⏎" : /^escape$/i.test(name) ? "esc" : name.replace(/^pageUp$/i, "PgUp").replace(/^pageDown$/i, "PgDn").replace(/^escape$/i, "Esc").replace(/^return$/i, "Enter").replace(/(^|[+])([a-z])/g, (_match, prefix: string, letter: string) => `${prefix}${letter.toUpperCase()}`)).join("/") : "unbound";
247
+ };
248
+ const pair = (left: "tui.select.up" | "tui.select.down" | "tui.select.pageUp" | "tui.select.pageDown", right: "tui.select.up" | "tui.select.down" | "tui.select.pageUp" | "tui.select.pageDown") => {
249
+ const first = key(left);
250
+ const second = key(right);
251
+ if (first === "Up" && second === "Down") return "↑↓";
252
+ return first === "unbound" || second === "unbound" ? "unbound" : `${first}/${second}`;
253
+ };
254
+ const selected = this.page?.items[this.selected];
255
+ const status = this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : undefined;
256
+ const result: string[] = [];
257
+ const footer = (parts: string[]) => wrapTextWithAnsi(parts.join(" · "), safeWidth).map(dim);
258
+ // Title, content and keys are divided the way F9 divides them.
259
+ const rule = () => dim("─".repeat(safeWidth));
260
+ if (this.view === "list") {
261
+ this.listCapacity = 1;
262
+ const compactItems = this.page?.items ?? [];
263
+ const scopeNames: Record<InspectorScope, string> = { session: "Session", project: "Working", "project-long": "Project", persona: "Persona", shared: "Shared" };
264
+ const activeScope = this.tab === "memories" ? accent(t.bold(scopeNames[this.scope])) : accent(t.bold(TAB_LABELS[this.tab]));
265
+ if (this.searching) {
266
+ this.searchInput.focused = this.focused;
267
+ if (rows >= 3) result.push(accent(t.bold("Memory inspector")));
268
+ if (rows >= 7) result.push(rule());
269
+ if (rows >= 4) result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
270
+ result.push(this.searchInput.render(safeWidth)[0] ?? "/");
271
+ if (rows >= 7) result.push(rule());
272
+ if (rows >= 2) result.push(dim(`${key("tui.input.submit")} apply · ${key("tui.select.cancel")} cancel`));
273
+ return result.slice(0, rows).map(fit);
274
+ }
275
+ if (rows <= 4) {
276
+ const compact = compactItems[this.selected];
277
+ const selection = compact ? accent(`▸ ${oneLine(compact.title)}`) : this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : dim("No items");
278
+ if (rows === 1) result.push(selection);
279
+ else { result.push(activeScope); result.push(selection); }
280
+ return result.slice(0, rows).map(fit);
281
+ }
282
+ if (rows <= 9 || safeWidth < 20) {
283
+ result.push(accent(t.bold("Memory inspector")));
284
+ result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
285
+ const compact = compactItems[this.selected];
286
+ if (compact) result.push(accent(`▸ ${oneLine(compact.title)}`));
287
+ else if (this.loading) result.push(dim("Loading…"));
288
+ else if (this.error) result.push(t.fg("error", fit(oneLine(this.error))));
289
+ else result.push(dim("No items"));
290
+ if (rows >= 6 && compactItems.length) result.push(dim(`${(this.page?.offset ?? 0) + this.selected + 1} selected · ${(this.page?.offset ?? 0) + 1}-${(this.page?.offset ?? 0) + compactItems.length} of ${this.page?.total ?? 0}`));
291
+ if (rows >= 7) result.push(dim(`${pair("tui.select.up", "tui.select.down")} select · ${key("tui.select.confirm")} open · ${key("tui.select.cancel")}/F10 close`));
292
+ return result.slice(0, rows).map(fit);
293
+ }
294
+ result.push(accent(t.bold("Memory inspector")));
295
+ result.push(TABS.map((tab) => tab === this.tab ? accent(t.bold(`[${TAB_LABELS[tab]}]`)) : dim(TAB_LABELS[tab])).join(dim(" ")));
296
+ if (this.tab === "memories") {
297
+ const scopeStrip = safeWidth >= 72 ? ` · ${SCOPES.map((scope) => scope === this.scope ? accent(t.bold(`[${scopeNames[scope]}]`)) : dim(scopeNames[scope])).join(dim(" "))}` : "";
298
+ result.push(`${dim("Scope: ")}${activeScope}${scopeStrip}`);
299
+ } else result.push(dim(`Search: ${this.query ? oneLine(this.query) : "none"} · Tab switch clears search`));
300
+ if (this.tab === "memories") result.push(dim(`Search: ${this.query ? oneLine(this.query) : "none"} · Tab switch clears search`));
301
+ const items = this.page?.items ?? [];
302
+ const total = this.page?.total ?? 0;
303
+ const offset = this.page?.offset ?? 0;
304
+ const current = items.length ? `${offset + Math.min(this.selected + 1, items.length)} selected · ${offset + 1}-${offset + items.length} of ${total}` : `0 selected · 0 of ${total}`;
305
+ if (status) result.push(status);
306
+ result.push(dim(current));
307
+ if (this.page?.notice) result.push(dim("Coverage notice · ? help"));
308
+ if (!this.loading && !this.error && items.length === 0) result.push(dim("No items on this page."));
309
+ const optional: string[] = [];
310
+ if (this.tab === "memories") optional.push("←/→ scope");
311
+ if (this.tab !== "context") optional.push("/ search");
312
+ if (this.tab === "memories" && this.options.onAction) optional.push("a actions");
313
+ if (selected?.source) optional.push("s source");
314
+ if (this.page?.nextOffset !== undefined || this.offsets.length > 1) optional.push("n/p result pages");
315
+ let footers = [footer(["Tab / Shift+Tab tabs", ...optional.slice(0, 2)]), footer([`${pair("tui.select.up", "tui.select.down")} select`, `${key("tui.select.confirm")} open`, ...optional.slice(2, 4)]), footer(["? help", `${key("tui.select.cancel")}/F10 close`, ...optional.slice(4)])].flat();
316
+ if (rows - result.length - footers.length < 1) footers = [dim(`? help · ${key("tui.select.cancel")}/F10 close`)];
317
+ // Spend separator rows only when at least one record still fits. Match F9's
318
+ // title/content/keys division rather than crowding the frame chrome.
319
+ const spaced = rows - result.length - footers.length >= 4;
320
+ if (spaced) { result.splice(1, 0, rule()); result.push(""); }
321
+ const capacity = Math.max(0, rows - result.length - footers.length - Number(spaced));
322
+ this.listCapacity = Math.max(1, capacity);
323
+ const maxStart = Math.max(0, items.length - capacity);
324
+ this.listStart = Math.min(this.listStart, maxStart);
325
+ if (this.selected < this.listStart) this.listStart = this.selected;
326
+ else if (capacity > 0 && this.selected >= this.listStart + capacity) this.listStart = this.selected - capacity + 1;
327
+ for (let i = this.listStart; i < Math.min(items.length, this.listStart + capacity); i++) {
328
+ const entry = items[i]!;
329
+ const marker = entry.source ? " [source]" : "";
330
+ const line = `${i === this.selected ? "▸ " : " "}${oneLine(entry.title)}`;
331
+ const rendered = i === this.selected ? `${accent(line)}${marker ? dim(marker) : ""}` : `${fit(line)}${marker ? dim(marker) : ""}`;
332
+ result.push(truncateToWidth(rendered, safeWidth));
333
+ }
334
+ if (spaced) result.push(rule());
335
+ result.push(...footers);
336
+ } else {
337
+ let breadcrumb: string;
338
+ if (this.view === "help") breadcrumb = `Memory inspector › ${TAB_LABELS[this.tab]} › Help`;
339
+ else {
340
+ const prefix = `Memory inspector › ${TAB_LABELS[this.tab]} › `;
341
+ const suffix = this.view === "source" ? " › Source" : "";
342
+ const titleWidth = Math.max(1, safeWidth - visibleWidth(prefix) - visibleWidth(suffix));
343
+ breadcrumb = `${prefix}${truncateToWidth(oneLine(this.item?.title ?? "Detail"), titleWidth, "…")}${suffix}`;
344
+ }
345
+ result.push(accent(t.bold(breadcrumb)));
346
+ let body: string;
347
+ const missingSource = this.view === "detail" && !this.item?.source;
348
+ if (this.view === "help") {
349
+ const actions = this.tab === "memories" && this.options.onAction ? "a runs the explicit memory action (closes this view first)." : "No explicit action is available in this view.";
350
+ const helpItem = this.helpReturn === "list" ? selected : this.item;
351
+ const sourceHelp = helpItem?.source ? `s opens the linked source text; ${key("tui.select.cancel")} returns to the view that opened it.` : "Source text is read-only; it is shown only when linked to a record.";
352
+ body = [
353
+ "Navigation: In the list, Tab / Shift+Tab switch tabs; switching tabs clears the search query. ← / → changes memory scope in the Memories list only.",
354
+ `${key("tui.select.up")} / ${key("tui.select.down")} moves selection within a list; ${key("tui.select.confirm")} opens the selected record. In detail/source/help, the arrow keys scroll the current text instead.`,
355
+ "n / p moves to the next / previous result page only when available. / starts search in Memories and Timeline; Context has no search.",
356
+ `${sourceHelp} ${actions}`,
357
+ "Records and linked sources are read-only here. A linked source is a reference, not independent verification. Explicit actions are separate from reading; the cancel key goes back, F10 closes.",
358
+ "Scope names: Session is session-only; Working is API project (working memory); Project is API project-long; Persona and Shared are wider durable scopes.",
359
+ this.page?.notice || "No additional coverage notice.",
360
+ ].join("\n\n");
361
+ } else if (this.view === "source") body = this.item?.source?.body ?? "";
362
+ else body = this.item?.body ?? "";
363
+ let wrapped: string[];
364
+ if (this.wrappedCache?.width === safeWidth && this.wrappedCache.body === body) wrapped = this.wrappedCache.lines;
365
+ else {
366
+ wrapped = wrapTextWithAnsi(sanitizeCardText(body), safeWidth);
367
+ // Width changes reflow text: retain the first visible text, not its old wrapped-row index.
368
+ if (this.wrappedCache?.body === body) {
369
+ const previousScroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
370
+ const length = (line: string) => line.replace(/\s/g, "").length;
371
+ const offset = this.wrappedCache.lines.slice(0, previousScroll).reduce((total, line) => total + length(line), 0);
372
+ let consumed = 0;
373
+ let mapped = 0;
374
+ while (mapped < wrapped.length - 1 && consumed + length(wrapped[mapped]!) <= offset) consumed += length(wrapped[mapped++]!);
375
+ this.setDetailScroll(mapped);
376
+ }
377
+ this.wrappedCache = { width: safeWidth, body, lines: wrapped };
378
+ }
379
+ const displayWrapped = [...wrapped];
380
+ const missingSourceIndex = missingSource ? displayWrapped.push("", "Source unavailable for this item.") - 1 : -1;
381
+ const actions = this.view === "detail" && this.tab === "memories" && this.options.onAction ? ["a actions"] : [];
382
+ const pageKeys = `${pair("tui.select.pageUp", "tui.select.pageDown")} page`;
383
+ let footers = safeWidth < 20
384
+ ? [dim(`↑↓ scroll/${key("tui.select.cancel")}`)]
385
+ : safeWidth < 32
386
+ ? footer([`${pair("tui.select.up", "tui.select.down")} scroll`, `${key("tui.select.cancel")} back`])
387
+ : [
388
+ ...footer([`${pair("tui.select.up", "tui.select.down")} scroll`, pageKeys]),
389
+ ...footer([...(this.view === "detail" && this.item?.source ? ["s source"] : []), ...actions, `${key("tui.select.cancel")} back`, "F10 close"]),
390
+ ];
391
+ const scroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
392
+ // Content wins over chrome, including extremely short detail/source/help views.
393
+ if (rows < 3) result.length = 0;
394
+ const indicatorRows = rows >= 5 ? 2 : 0;
395
+ if (rows - result.length - footers.length - indicatorRows < 1) {
396
+ footers = rows - result.length - indicatorRows >= 2 ? [dim(`${key("tui.select.cancel")} back · F10 close`)] : [];
397
+ }
398
+ const spaced = rows - result.length - footers.length - indicatorRows >= 3;
399
+ if (spaced) result.push(rule());
400
+ const capacity = Math.max(0, rows - result.length - footers.length - indicatorRows - Number(spaced));
401
+ this.detailCapacity = Math.max(1, capacity);
402
+ const maxStart = Math.max(0, displayWrapped.length - capacity);
403
+ const start = Math.min(scroll, maxStart);
404
+ this.setDetailScroll(start);
405
+ if (indicatorRows && start > 0) result.push(dim(`▲ ${start} lines above`));
406
+ result.push(...displayWrapped.slice(start, start + capacity).map((line, index) => start + index === missingSourceIndex ? t.fg("warning", fit(line)) : this.view === "help" ? dim(line) : fit(line)));
407
+ if (indicatorRows && start + capacity < displayWrapped.length) result.push(dim(`▼ ${displayWrapped.length - start - capacity} lines below`));
408
+ if (spaced) result.push(rule());
409
+ result.push(...footers);
410
+ }
411
+ return result.slice(0, rows).map(fit);
412
+ }
413
+
414
+ takeAction(): (InspectorRequest & { selectedId?: string }) | undefined {
415
+ const action = this.pendingAction;
416
+ this.pendingAction = undefined;
417
+ return action;
418
+ }
419
+
420
+ invalidate(): void {}
421
+ dispose(): void { this.options.signal?.removeEventListener("abort", this.onAbort); this.closed = true; this.generation++; }
422
+ }
423
+
424
+ export function createMemoryInspectorComponent(
425
+ tui: TUI,
426
+ theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
427
+ keybindings: KeybindingsManager,
428
+ done: (result: void) => void,
429
+ options: MemoryInspectorOptions,
430
+ ): MemoryInspectorComponent {
431
+ return new MemoryInspectorComponent(tui, theme, keybindings, done, options);
432
+ }
433
+
434
+ export async function openMemoryInspector(
435
+ ctx: ExtensionContext,
436
+ options: MemoryInspectorOptions,
437
+ ): Promise<void> {
438
+ if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires interactive mode", "warning"); return; }
439
+ if (options.signal?.aborted || !options.isCurrent()) return;
440
+ const frame = options.frame;
441
+ if (!frame) { ctx.ui.notify("Memory inspector unavailable: reload a compatible pi-persona extension.", "warning"); return; }
442
+ try {
443
+ let overlayTui: TUI | undefined;
444
+ let component: MemoryInspectorComponent | undefined;
445
+ await ctx.ui.custom<void>((tui, theme, keybindings, done) => {
446
+ overlayTui = tui;
447
+ component = new MemoryInspectorComponent(tui, theme, keybindings, done, {
448
+ ...options,
449
+ viewportHeight: () => frame.viewportRows(tui.terminal?.rows ?? 1),
450
+ });
451
+ return component;
452
+ }, {
453
+ overlay: true,
454
+ overlayOptions: () => {
455
+ const rows = overlayTui?.terminal?.rows ?? 1;
456
+ return { width: "90%", maxHeight: frame.viewportRows(rows), margin: 1 };
457
+ },
458
+ });
459
+ const action = component?.takeAction();
460
+ if (action && !options.signal?.aborted && options.isCurrent() && options.onAction) await options.onAction(action);
461
+ } catch (error) {
462
+ if (!options.signal?.aborted && options.isCurrent()) ctx.ui.notify(`Memory inspector closed: ${error instanceof Error ? error.message : "unknown error"}`, "warning");
463
+ }
464
+ }