@aeondave/pi-persona-mind 0.9.0 → 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.
@@ -1,69 +1,69 @@
1
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { MemoryEntry } from "../core/memory.ts";
3
- import { buildInspectorTimeline, findMemoryRecordingSource, findSessionNoteRecordingSource, INSPECTOR_PAGE_SIZE, MAX_INSPECTOR_BRANCH_ENTRIES } from "../core/memory-inspector.ts";
4
- import type { SessionMemory } from "../session-memory.ts";
5
- import type { MindService } from "../core/service.ts";
6
-
7
- export type InspectorTab = "memories" | "context" | "timeline";
8
- export type InspectorScope = "session" | "project" | "project-long" | "persona" | "shared";
9
- export interface InspectorRequest { tab: InspectorTab; scope: InspectorScope; query: string; offset: number }
10
- export interface InspectorItem { id: string; title: string; body: string; source?: { title: string; body: string } }
11
- export interface InspectorPage { items: InspectorItem[]; total: number; offset: number; nextOffset?: number; notice: string }
12
-
13
- const PAGE_SIZE = INSPECTOR_PAGE_SIZE;
14
- const safeOffset = (offset: number): number => Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
15
- const safeQuery = (query: string): string => typeof query === "string" ? query.slice(0, 512) : "";
16
- function inspectionScope(mind: MindService): ReturnType<MindService["inspectionScope"]> | undefined {
17
- try { return mind.inspectionScope(); } catch { return undefined; }
18
- }
19
- function unavailable(notice: string): InspectorPage { return { items: [], total: 0, offset: 0, notice }; }
20
- function sessionNoteItems(ctx: ExtensionContext, sessionMemory: SessionMemory, request: InspectorRequest): InspectorPage {
21
- const snapshot = sessionMemory.snapshot(ctx);
22
- if (!snapshot.ok) return unavailable(`Active-session notes unavailable: ${snapshot.reason ?? "snapshot failed"}.`);
23
- let branch: unknown[] = [];
24
- let noteHistory: unknown[] = [];
25
- try {
26
- branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
27
- noteHistory = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
28
- } catch { /* current snapshot remains useful; source is omitted without native evidence */ }
29
- const query = safeQuery(request.query).trim().toLowerCase();
30
- const entries = snapshot.notes.filter((note) => !query || `${note.kind} ${note.text} ${note.source ?? ""}`.toLowerCase().includes(query)).sort((a, b) => Date.parse(b.recordedAt) - Date.parse(a.recordedAt));
31
- const offset = safeOffset(request.offset);
32
- const page = entries.slice(offset, offset + PAGE_SIZE);
33
- return { items: page.map((note) => {
34
- const source = findSessionNoteRecordingSource(note, branch, noteHistory);
35
- const body = [`text: ${note.text}`, `id: ${note.id}`, `kind: ${note.kind}`, `recorded: ${note.recordedAt}`, `origin session id: ${note.originSessionId}`, ...(note.source === undefined ? [] : [`literal source metadata (not opened): ${note.source}`]), ...(source ? [] : ["No resolvable recording in this active-branch window."])].join("\n");
36
- return { id: note.id, title: `${note.kind} · ${note.recordedAt} · ${note.text.replace(/\s+/g, " ").slice(0, 100)}`, body, ...(source ? { source } : {}) };
37
- }), total: entries.length, offset, ...(offset + page.length < entries.length ? { nextOffset: offset + page.length } : {}), notice: `Active-branch session notes only (${snapshot.storage} storage). Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} native entries. ${entries.length} matching active notes.` };
38
- }
39
-
40
- export async function loadInspectorPage(ctx: ExtensionContext, mind: MindService, sessionMemory: SessionMemory, request: InspectorRequest): Promise<InspectorPage> {
41
- const offset = safeOffset(request.offset);
42
- const query = safeQuery(request.query);
43
- if (request.tab === "context") return unavailable("No context snapshot is available from the read-only inspector data layer.");
44
- if (request.tab === "timeline") {
45
- try {
46
- const branch = ctx.sessionManager.getBranch();
47
- const history = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
48
- const page = buildInspectorTimeline(branch, history, { query, offset });
49
- return { items: page.items.map(({ id, title, body, source }) => ({ id, title, body, ...(source ? { source } : {}) })), total: page.total, offset: page.offset, ...(page.nextOffset === undefined ? {} : { nextOffset: page.nextOffset }), notice: page.notice };
50
- } catch { return unavailable("Native active-branch timeline is unavailable."); }
51
- }
52
- if (request.scope === "session") return sessionNoteItems(ctx, sessionMemory, { ...request, query, offset });
53
- const activeScope = inspectionScope(mind);
54
- if (!activeScope) return unavailable("Mind inspection scope is unavailable; no memory store was read.");
55
- if ((request.scope === "project" || request.scope === "project-long") && activeScope.homeWorkspace) return unavailable("Project memory scopes are unavailable in the home workspace.");
56
- try {
57
- const target = request.scope;
58
- const inspection = await mind.createOptimizer().inspect(target, { query, offset, max: PAGE_SIZE });
59
- if (!inspection.ok) return unavailable(`Memory inspection unavailable: ${inspection.reason}`);
60
- let branch: unknown[] = [];
61
- try { branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES); } catch { /* missing native branch means no recording-source link */ }
62
- const items = inspection.entries.map((entry: MemoryEntry) => {
63
- const source = activeScope ? findMemoryRecordingSource(entry, branch, target, activeScope) : undefined;
64
- const details = [`text: ${entry.text}`, `id: ${entry.id}`, `target: ${target}`, `kind: ${entry.kind}`, `recorded: ${entry.recordedAt}`, `last seen: ${entry.lastSeenAt}`, ...(entry.expiresAt ? [`expires: ${entry.expiresAt}`] : []), ...(entry.tags.length ? [`tags: ${entry.tags.join(", ")}`] : []), ...(entry.persona ? [`persona marker: ${entry.persona}`] : []), ...(entry.source ? [`literal source metadata (not opened): ${entry.source}`] : []), ...(entry.derivedFrom?.length ? [`derivedFrom literal IDs (not opened): ${entry.derivedFrom.join(", ")}`] : []), ...(entry.supersedes ? [`supersedes literal ID (not opened): ${entry.supersedes}`] : []), ...(source ? [] : ["No resolvable recording in this active-branch window."])];
65
- return { id: entry.id, title: entry.text, body: details.join("\n"), ...(source ? { source } : {}) };
66
- });
67
- return { items, total: inspection.matched, offset: inspection.offset, ...(inspection.nextOffset === undefined ? {} : { nextOffset: inspection.nextOffset }), notice: `${target} memory; read-only inspection. ${inspection.matched} matching safe entries in this store. Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} active-branch entries. Source and derivedFrom values are literal provenance, not verified evidence or cross-store links.` };
68
- } catch { return unavailable("Memory inspection failed safely; no store recovery or mutation was attempted."); }
69
- }
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { MemoryEntry } from "../core/memory.ts";
3
+ import { buildInspectorTimeline, findMemoryRecordingSource, findSessionNoteRecordingSource, INSPECTOR_PAGE_SIZE, MAX_INSPECTOR_BRANCH_ENTRIES } from "../core/memory-inspector.ts";
4
+ import type { SessionMemory } from "../session-memory.ts";
5
+ import type { MindService } from "../core/service.ts";
6
+
7
+ export type InspectorTab = "memories" | "context" | "timeline";
8
+ export type InspectorScope = "session" | "project" | "project-long" | "persona" | "shared";
9
+ export interface InspectorRequest { tab: InspectorTab; scope: InspectorScope; query: string; offset: number }
10
+ export interface InspectorItem { id: string; title: string; body: string; source?: { title: string; body: string } }
11
+ export interface InspectorPage { items: InspectorItem[]; total: number; offset: number; nextOffset?: number; notice: string }
12
+
13
+ const PAGE_SIZE = INSPECTOR_PAGE_SIZE;
14
+ const safeOffset = (offset: number): number => Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
15
+ const safeQuery = (query: string): string => typeof query === "string" ? query.slice(0, 512) : "";
16
+ function inspectionScope(mind: MindService): ReturnType<MindService["inspectionScope"]> | undefined {
17
+ try { return mind.inspectionScope(); } catch { return undefined; }
18
+ }
19
+ function unavailable(notice: string): InspectorPage { return { items: [], total: 0, offset: 0, notice }; }
20
+ function sessionNoteItems(ctx: ExtensionContext, sessionMemory: SessionMemory, request: InspectorRequest): InspectorPage {
21
+ const snapshot = sessionMemory.snapshot(ctx);
22
+ if (!snapshot.ok) return unavailable(`Active-session notes unavailable: ${snapshot.reason ?? "snapshot failed"}.`);
23
+ let branch: unknown[] = [];
24
+ let noteHistory: unknown[] = [];
25
+ try {
26
+ branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
27
+ noteHistory = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
28
+ } catch { /* current snapshot remains useful; source is omitted without native evidence */ }
29
+ const query = safeQuery(request.query).trim().toLowerCase();
30
+ const entries = snapshot.notes.filter((note) => !query || `${note.kind} ${note.text} ${note.source ?? ""}`.toLowerCase().includes(query)).sort((a, b) => Date.parse(b.recordedAt) - Date.parse(a.recordedAt));
31
+ const offset = safeOffset(request.offset);
32
+ const page = entries.slice(offset, offset + PAGE_SIZE);
33
+ return { items: page.map((note) => {
34
+ const source = findSessionNoteRecordingSource(note, branch, noteHistory);
35
+ const body = [`text: ${note.text}`, `id: ${note.id}`, `kind: ${note.kind}`, `recorded: ${note.recordedAt}`, `origin session id: ${note.originSessionId}`, ...(note.source === undefined ? [] : [`literal source metadata (not opened): ${note.source}`]), ...(source ? [] : ["No resolvable recording in this active-branch window."])].join("\n");
36
+ return { id: note.id, title: `${note.kind} · ${note.recordedAt} · ${note.text.replace(/\s+/g, " ").slice(0, 100)}`, body, ...(source ? { source } : {}) };
37
+ }), total: entries.length, offset, ...(offset + page.length < entries.length ? { nextOffset: offset + page.length } : {}), notice: `Active-branch session notes only (${snapshot.storage} storage). Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} native entries. ${entries.length} matching active notes.` };
38
+ }
39
+
40
+ export async function loadInspectorPage(ctx: ExtensionContext, mind: MindService, sessionMemory: SessionMemory, request: InspectorRequest): Promise<InspectorPage> {
41
+ const offset = safeOffset(request.offset);
42
+ const query = safeQuery(request.query);
43
+ if (request.tab === "context") return unavailable("No context snapshot is available from the read-only inspector data layer.");
44
+ if (request.tab === "timeline") {
45
+ try {
46
+ const branch = ctx.sessionManager.getBranch();
47
+ const history = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
48
+ const page = buildInspectorTimeline(branch, history, { query, offset });
49
+ return { items: page.items.map(({ id, title, body, source }) => ({ id, title, body, ...(source ? { source } : {}) })), total: page.total, offset: page.offset, ...(page.nextOffset === undefined ? {} : { nextOffset: page.nextOffset }), notice: page.notice };
50
+ } catch { return unavailable("Native active-branch timeline is unavailable."); }
51
+ }
52
+ if (request.scope === "session") return sessionNoteItems(ctx, sessionMemory, { ...request, query, offset });
53
+ const activeScope = inspectionScope(mind);
54
+ if (!activeScope) return unavailable("Mind inspection scope is unavailable; no memory store was read.");
55
+ if ((request.scope === "project" || request.scope === "project-long") && activeScope.homeWorkspace) return unavailable("Project memory scopes are unavailable in the home workspace.");
56
+ try {
57
+ const target = request.scope;
58
+ const inspection = await mind.createOptimizer().inspect(target, { query, offset, max: PAGE_SIZE });
59
+ if (!inspection.ok) return unavailable(`Memory inspection unavailable: ${inspection.reason}`);
60
+ let branch: unknown[] = [];
61
+ try { branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES); } catch { /* missing native branch means no recording-source link */ }
62
+ const items = inspection.entries.map((entry: MemoryEntry) => {
63
+ const source = activeScope ? findMemoryRecordingSource(entry, branch, target, activeScope) : undefined;
64
+ const details = [`text: ${entry.text}`, `id: ${entry.id}`, `target: ${target}`, `kind: ${entry.kind}`, `recorded: ${entry.recordedAt}`, `last seen: ${entry.lastSeenAt}`, ...(entry.expiresAt ? [`expires: ${entry.expiresAt}`] : []), ...(entry.tags.length ? [`tags: ${entry.tags.join(", ")}`] : []), ...(entry.persona ? [`persona marker: ${entry.persona}`] : []), ...(entry.source ? [`literal source metadata (not opened): ${entry.source}`] : []), ...(entry.derivedFrom?.length ? [`derivedFrom literal IDs (not opened): ${entry.derivedFrom.join(", ")}`] : []), ...(entry.supersedes ? [`supersedes literal ID (not opened): ${entry.supersedes}`] : []), ...(source ? [] : ["No resolvable recording in this active-branch window."])];
65
+ return { id: entry.id, title: entry.text, body: details.join("\n"), ...(source ? { source } : {}) };
66
+ });
67
+ return { items, total: inspection.matched, offset: inspection.offset, ...(inspection.nextOffset === undefined ? {} : { nextOffset: inspection.nextOffset }), notice: `${target} memory; read-only inspection. ${inspection.matched} matching safe entries in this store. Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} active-branch entries. Source and derivedFrom values are literal provenance, not verified evidence or cross-store links.` };
68
+ } catch { return unavailable("Memory inspection failed safely; no store recovery or mutation was attempted."); }
69
+ }
package/src/index.ts CHANGED
@@ -36,6 +36,7 @@ import { registerMindCommands } from "./extension/mind-command.ts";
36
36
  import { createMemoryInspector } from "./extension/memory-inspector.ts";
37
37
  import { loadInspectorPage } from "./extension/inspector-data.ts";
38
38
  import { openMemoryInspector } from "./ui/memory-inspector.ts";
39
+ import { queryInspectorFrame } from "./ui/inspector-frame.ts";
39
40
  import { createKnowledgeReview } from "./extension/knowledge-review.ts";
40
41
  import { launchMindWorker } from "./extension/mind-worker.ts";
41
42
  import { runMindInspectorActions } from "./extension/mind-actions.ts";
@@ -550,7 +551,10 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
550
551
  unavailableReason: (ctx) => unavailableReason(ctx) ?? (isDelegatedLeg || !sessionMemory.isCurrent(ctx) ? "Memory inspector requires an active supervisor session owner." : undefined),
551
552
  captureOwner: captureMemoryOwner,
552
553
  load: (ctx, request) => loadInspectorPage(ctx, getMind(ctx), sessionMemory, request),
553
- show: openMemoryInspector,
554
+ show: (ctx, options) => {
555
+ const frame = queryInspectorFrame(pi.events);
556
+ return openMemoryInspector(ctx, { ...options, ...(frame ? { frame } : {}) });
557
+ },
554
558
  actions: (ctx, request, current) => runMindInspectorActions(ctx, request, current, { consolidate: (target) => autoOptimize.startExplicit(target), review: knowledgeReview }),
555
559
  });
556
560
  if (!isDelegatedLeg) pi.registerShortcut("f10", { description: "Inspect memory, sources and timeline", handler: (ctx) => inspector.open(ctx) });
@@ -678,7 +682,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
678
682
  ctx,
679
683
  `${headline}\n${list}${more}\nReview when ready — stale leads auto-remove after ~48h; keep durable facts in long-term memory.`,
680
684
  );
681
- await mind.acknowledgeDue(due.map((item) => item.id));
685
+ await mind.acknowledgeDue(due.map((item) => ({ id: item.id, dueAtEpochMs: item.dueAtEpochMs! })));
682
686
  } catch {
683
687
  /* raced shutdown */
684
688
  }
@@ -718,7 +722,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
718
722
  ctx,
719
723
  `backlog due — ${compactMemoryText(live.text, MAX_WAKE_TEXT_CHARS)} (id ${live.id}). Review when ready.`,
720
724
  );
721
- await mind.acknowledgeDue([live.id]);
725
+ await mind.acknowledgeDue([{ id: live.id, dueAtEpochMs: live.dueAtEpochMs }]);
722
726
  } catch (err) {
723
727
  if (wakeCurrent(generation, nextOwnerPath)) surfaceWarning(ctx, `could not re-check due backlog item ${item.id}: ${err instanceof Error ? err.message : String(err)}`);
724
728
  }
@@ -760,8 +764,11 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
760
764
  };
761
765
 
762
766
  const refreshStatus = async (ctx: ExtensionContext): Promise<void> => {
767
+ let ownerCurrent = (): boolean => false;
763
768
  try {
769
+ ownerCurrent = captureMemoryOwner(ctx);
764
770
  const s = await getMind(ctx).summary();
771
+ if (!ownerCurrent()) return;
765
772
  if (warningStatusActive) {
766
773
  setStatus(ctx, "mind warning · /mind doctor", "warning");
767
774
  return;
@@ -770,7 +777,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
770
777
  const label = `mind ${s.ltm}L·${s.projectLtm}P·${s.stm}S · backlog ${s.backlogOpen}`;
771
778
  setStatus(ctx, label);
772
779
  } catch (err) {
773
- surfaceWarning(ctx, `could not refresh memory status: ${err instanceof Error ? err.message : String(err)}`);
780
+ if (ownerCurrent()) surfaceWarning(ctx, `could not refresh memory status: ${err instanceof Error ? err.message : String(err)}`);
774
781
  }
775
782
  };
776
783
 
@@ -0,0 +1,44 @@
1
+ /** Structural adapter to Persona's shared, stateless inspector frame. */
2
+ export const INSPECTOR_FRAME_EVENT = "pi-persona:inspector-frame:v1";
3
+
4
+ export interface InspectorLayout {
5
+ width: number;
6
+ height: number;
7
+ contentWidth: number;
8
+ contentRows: number;
9
+ gutter: number;
10
+ framed: boolean;
11
+ }
12
+
13
+ export interface InspectorFrame {
14
+ viewportRows(terminalRows: number): number;
15
+ layout(width: number, height: number): InspectorLayout;
16
+ render(lines: readonly string[], layout: InspectorLayout, border: (text: string) => string): string[];
17
+ }
18
+
19
+ export interface InspectorFrameEventBus { emit(event: string, data: unknown): void; }
20
+
21
+ function validFrame(response: unknown): InspectorFrame | undefined {
22
+ if (!response || typeof response !== "object") return undefined;
23
+ const value = response as Record<string, unknown>;
24
+ if (value.version !== 1 || value.provider !== "pi-persona" || !value.frame || typeof value.frame !== "object") return undefined;
25
+ const frame = value.frame as Record<string, unknown>;
26
+ return typeof frame.viewportRows === "function" && typeof frame.layout === "function" && typeof frame.render === "function"
27
+ ? value.frame as InspectorFrame : undefined;
28
+ }
29
+
30
+ /** Resolve on each opening; late and ambiguous providers cannot select a renderer. */
31
+ export function queryInspectorFrame(events: InspectorFrameEventBus): InspectorFrame | undefined {
32
+ let synchronous = true;
33
+ let count = 0;
34
+ let frame: InspectorFrame | undefined;
35
+ try {
36
+ events.emit(INSPECTOR_FRAME_EVENT, { version: 1, respond(response: unknown) {
37
+ if (!synchronous) return;
38
+ const candidate = validFrame(response);
39
+ if (candidate) { count++; frame = candidate; }
40
+ } });
41
+ } catch { return undefined; }
42
+ finally { synchronous = false; }
43
+ return count === 1 ? frame : undefined;
44
+ }
@@ -1,13 +1,15 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { Input, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type Focusable, type TUI, type KeybindingsManager } from "@earendil-works/pi-tui";
2
+ import { getKeybindings, setKeybindings, Input, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type Focusable, type TUI, type KeybindingsManager } from "@earendil-works/pi-tui";
3
3
  import type { InspectorItem, InspectorPage, InspectorRequest, InspectorScope, InspectorTab } from "../extension/inspector-data.ts";
4
4
  import { sanitizeCardText } from "./presentation.ts";
5
+ import type { InspectorFrame } from "./inspector-frame.ts";
5
6
 
6
7
  const TABS: InspectorTab[] = ["memories", "context", "timeline"];
7
8
  const TAB_LABELS: Record<InspectorTab, string> = { memories: "Memories", context: "Context", timeline: "Timeline" };
8
9
  const SCOPES: InspectorScope[] = ["session", "project", "project-long", "persona", "shared"];
9
10
 
10
11
  export interface MemoryInspectorOptions {
12
+ frame?: InspectorFrame;
11
13
  load: (request: InspectorRequest) => Promise<InspectorPage>;
12
14
  isCurrent: () => boolean;
13
15
  initialTab?: InspectorTab;
@@ -41,22 +43,25 @@ export class MemoryInspectorComponent implements Component, Focusable {
41
43
  private detailScroll = 0;
42
44
  private sourceScroll = 0;
43
45
  private listStart = 0;
46
+ private listCapacity = 1;
47
+ private detailCapacity = 1;
48
+ private readonly frame: InspectorFrame;
44
49
  private readonly searchInput = new Input({ prompt: "/ " });
45
50
  private pendingAction: (InspectorRequest & { selectedId?: string }) | undefined;
46
51
 
47
52
  get focused(): boolean { return this._focused; }
48
- set focused(value: boolean) { this._focused = value; this.searchInput.focused = value; }
53
+ set focused(value: boolean) { this._focused = value; this.searchInput.focused = value && this.searching; }
49
54
  readonly capturesViewportInput = true;
50
55
  private readonly onAbort: () => void;
51
56
  private readonly tui: TUI;
52
- private readonly theme: { fg(name: "accent" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string };
57
+ private readonly theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string };
53
58
  private readonly keybindings: KeybindingsManager;
54
59
  private readonly done: (result: void) => void;
55
60
  private readonly options: MemoryInspectorOptions;
56
61
 
57
62
  constructor(
58
63
  tui: TUI,
59
- theme: { fg(name: "accent" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
64
+ theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
60
65
  keybindings: KeybindingsManager,
61
66
  done: (result: void) => void,
62
67
  options: MemoryInspectorOptions,
@@ -64,8 +69,17 @@ export class MemoryInspectorComponent implements Component, Focusable {
64
69
  this.tui = tui;
65
70
  this.theme = theme;
66
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
+ };
67
79
  this.done = done;
68
80
  this.options = options;
81
+ if (!options.frame) throw new Error("Inspector frame requires compatible loaded pi-persona");
82
+ this.frame = options.frame;
69
83
  this.tab = options.initialTab ?? "memories";
70
84
  this.onAbort = () => this.close();
71
85
  if (options.signal?.aborted) this.close();
@@ -127,15 +141,18 @@ export class MemoryInspectorComponent implements Component, Focusable {
127
141
  if (!this.isCurrent()) return;
128
142
  if (matchesKey(data, "f10")) { this.close(); return; }
129
143
  if (this.searching) {
130
- if (this.keybindings.matches(data, "tui.select.cancel")) { this.searching = false; this.tui.requestRender(); return; }
131
- if (this.keybindings.matches(data, "tui.select.confirm")) {
132
- this.query = sanitizeCardText(this.searchInput.getValue());
133
- this.searching = false;
134
- this.resetAndLoad();
135
- this.tui.requestRender();
136
- return;
144
+ const global = getKeybindings();
145
+ try {
146
+ if (global !== this.keybindings) setKeybindings(this.keybindings);
147
+ this.searchInput.handleInput(data);
148
+ } finally {
149
+ if (global !== this.keybindings) setKeybindings(global);
137
150
  }
138
- this.searchInput.handleInput(data);
151
+ // Native Input owns paste buffering, but pasted terminal controls are not
152
+ // editor content. Strip them from the value before its next render.
153
+ const value = this.searchInput.getValue();
154
+ const clean = sanitizeCardText(value);
155
+ if (clean !== value) this.searchInput.setValue(clean);
139
156
  this.tui.requestRender();
140
157
  return;
141
158
  }
@@ -153,8 +170,7 @@ export class MemoryInspectorComponent implements Component, Focusable {
153
170
  return;
154
171
  }
155
172
  const currentScroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
156
- const viewportRows = this.options.viewportHeight?.() ?? this.tui.terminal?.rows ?? 1;
157
- const delta = Math.max(1, viewportRows - 4);
173
+ const delta = Math.max(1, this.detailCapacity - 1);
158
174
  if (this.keybindings.matches(data, "tui.select.up")) this.setDetailScroll(Math.max(0, currentScroll - 1));
159
175
  else if (this.keybindings.matches(data, "tui.select.down")) this.setDetailScroll(currentScroll + 1);
160
176
  else if (this.keybindings.matches(data, "tui.select.pageUp") || this.keybindings.matches(data, "tui.altScreen.pageUp")) this.setDetailScroll(Math.max(0, currentScroll - delta));
@@ -179,8 +195,8 @@ export class MemoryInspectorComponent implements Component, Focusable {
179
195
  }
180
196
  else if (this.keybindings.matches(data, "tui.select.up") && this.page) this.selected = Math.max(0, this.selected - 1);
181
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));
182
- 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 - Math.max(1, (this.tui.terminal?.rows ?? 1) - 5));
183
- 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 + Math.max(1, (this.tui.terminal?.rows ?? 1) - 5)));
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));
184
200
  else if (this.keybindings.matches(data, "tui.select.confirm")) {
185
201
  this.item = this.page?.items[this.selected]; if (this.item) { this.view = "detail"; this.detailScroll = 0; }
186
202
  } else if (matchesKey(data, "left") && this.tab === "memories") {
@@ -188,7 +204,7 @@ export class MemoryInspectorComponent implements Component, Focusable {
188
204
  } else if (matchesKey(data, "right") && this.tab === "memories") {
189
205
  this.scope = SCOPES[(SCOPES.indexOf(this.scope) + 1) % SCOPES.length]!; this.resetAndLoad();
190
206
  } else if (data === "/" && this.tab !== "context") {
191
- this.searchInput.setValue(this.query); this.searching = true;
207
+ this.searchInput.setValue(this.query); this.setSearching(true);
192
208
  } else if (data === "?") {
193
209
  this.helpReturn = "list"; this.helpScroll = 0; this.view = "help";
194
210
  } else if (data === "s" && this.page?.items[this.selected]?.source) {
@@ -201,6 +217,11 @@ export class MemoryInspectorComponent implements Component, Focusable {
201
217
  this.tui.requestRender();
202
218
  }
203
219
 
220
+ private setSearching(value: boolean): void {
221
+ this.searching = value;
222
+ this.searchInput.focused = this.focused && value;
223
+ }
224
+
204
225
  private setDetailScroll(offset: number): void {
205
226
  if (this.view === "source") this.sourceScroll = offset;
206
227
  else if (this.view === "help") this.helpScroll = offset;
@@ -209,17 +230,8 @@ export class MemoryInspectorComponent implements Component, Focusable {
209
230
 
210
231
  render(width: number, height?: number): string[] {
211
232
  if (!this.isCurrent() || width <= 0) return [];
212
- const outerWidth = Math.max(1, Math.floor(width));
213
- const outerRows = Math.max(1, Math.floor(height ?? this.options.viewportHeight?.() ?? this.tui.terminal?.rows ?? 1));
214
- // Match Persona's F9 frame, but degrade safely when the terminal cannot fit its chrome.
215
- if (outerWidth < 5 || outerRows < 3) return this.renderContent(outerWidth, outerRows);
216
- // F9 combines one column of Text padding with one column inside the frame.
217
- const gutter = " ".repeat(outerWidth >= 7 ? 2 : 1);
218
- const innerWidth = outerWidth - 2 - gutter.length * 2;
219
- const border = (text: string) => this.theme.fg("accent", text);
220
- const body = this.renderContent(innerWidth, outerRows - 2).map((line) =>
221
- `${border("│")}${gutter}${line}${" ".repeat(Math.max(0, innerWidth - visibleWidth(line)))}${gutter}${border("│")}`);
222
- return [border(`┌${"─".repeat(outerWidth - 2)}┐`), ...body, border(`└${"─".repeat(outerWidth - 2)}┘`)];
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));
223
235
  }
224
236
 
225
237
  private renderContent(safeWidth: number, rows: number): string[] {
@@ -228,41 +240,46 @@ export class MemoryInspectorComponent implements Component, Focusable {
228
240
  const fit = (value: string) => truncateToWidth(value, safeWidth, "…");
229
241
  const dim = (value: string) => t.fg("dim", fit(value));
230
242
  const accent = (value: string) => t.fg("accent", fit(value));
231
- const key = (action: "tui.select.up" | "tui.select.down" | "tui.select.confirm" | "tui.select.cancel" | "tui.select.pageUp" | "tui.select.pageDown") => {
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") => {
232
244
  const names = this.keybindings.getKeys(action);
233
- 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";
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";
234
247
  };
235
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") => {
236
249
  const first = key(left);
237
250
  const second = key(right);
251
+ if (first === "Up" && second === "Down") return "↑↓";
238
252
  return first === "unbound" || second === "unbound" ? "unbound" : `${first}/${second}`;
239
253
  };
240
254
  const selected = this.page?.items[this.selected];
241
255
  const status = this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : undefined;
242
256
  const result: string[] = [];
243
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));
244
260
  if (this.view === "list") {
261
+ this.listCapacity = 1;
245
262
  const compactItems = this.page?.items ?? [];
246
263
  const scopeNames: Record<InspectorScope, string> = { session: "Session", project: "Working", "project-long": "Project", persona: "Persona", shared: "Shared" };
247
264
  const activeScope = this.tab === "memories" ? accent(t.bold(scopeNames[this.scope])) : accent(t.bold(TAB_LABELS[this.tab]));
248
265
  if (this.searching) {
249
266
  this.searchInput.focused = this.focused;
250
267
  if (rows >= 3) result.push(accent(t.bold("Memory inspector")));
251
- if (rows >= 7) result.push("");
268
+ if (rows >= 7) result.push(rule());
252
269
  if (rows >= 4) result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
253
270
  result.push(this.searchInput.render(safeWidth)[0] ?? "/");
254
- if (rows >= 7) result.push("");
255
- if (rows >= 2) result.push(dim(`${key("tui.select.confirm")} apply · ${key("tui.select.cancel")} cancel`));
271
+ if (rows >= 7) result.push(rule());
272
+ if (rows >= 2) result.push(dim(`${key("tui.input.submit")} apply · ${key("tui.select.cancel")} cancel`));
256
273
  return result.slice(0, rows).map(fit);
257
274
  }
258
275
  if (rows <= 4) {
259
276
  const compact = compactItems[this.selected];
260
277
  const selection = compact ? accent(`▸ ${oneLine(compact.title)}`) : this.loading ? dim("Loading…") : this.error ? t.fg("error", fit(oneLine(this.error))) : dim("No items");
261
- if (rows === 1) result.push(this.tab === "memories" ? `${activeScope} · ${selection}` : selection);
278
+ if (rows === 1) result.push(selection);
262
279
  else { result.push(activeScope); result.push(selection); }
263
280
  return result.slice(0, rows).map(fit);
264
281
  }
265
- if (rows <= 9) {
282
+ if (rows <= 9 || safeWidth < 20) {
266
283
  result.push(accent(t.bold("Memory inspector")));
267
284
  result.push(this.tab === "memories" ? `${dim("Scope: ")}${activeScope}` : activeScope);
268
285
  const compact = compactItems[this.selected];
@@ -280,10 +297,7 @@ export class MemoryInspectorComponent implements Component, Focusable {
280
297
  const scopeStrip = safeWidth >= 72 ? ` · ${SCOPES.map((scope) => scope === this.scope ? accent(t.bold(`[${scopeNames[scope]}]`)) : dim(scopeNames[scope])).join(dim(" "))}` : "";
281
298
  result.push(`${dim("Scope: ")}${activeScope}${scopeStrip}`);
282
299
  } else result.push(dim(`Search: ${this.query ? oneLine(this.query) : "none"} · Tab switch clears search`));
283
- if (this.searching) {
284
- this.searchInput.focused = this.focused;
285
- result.push(this.searchInput.render(safeWidth)[0] ?? "/");
286
- } else if (this.tab === "memories") 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`));
287
301
  const items = this.page?.items ?? [];
288
302
  const total = this.page?.total ?? 0;
289
303
  const offset = this.page?.offset ?? 0;
@@ -298,14 +312,14 @@ export class MemoryInspectorComponent implements Component, Focusable {
298
312
  if (this.tab === "memories" && this.options.onAction) optional.push("a actions");
299
313
  if (selected?.source) optional.push("s source");
300
314
  if (this.page?.nextOffset !== undefined || this.offsets.length > 1) optional.push("n/p result pages");
301
- const footers = this.searching
302
- ? footer([`${key("tui.select.confirm")} apply`, `${key("tui.select.cancel")} cancel`])
303
- : [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();
304
- // Spend whitespace only when at least one record still fits. Match F9's
305
- // title/content/footer separation rather than crowding the frame chrome.
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.
306
319
  const spaced = rows - result.length - footers.length >= 4;
307
- if (spaced) { result.splice(1, 0, ""); result.push(""); }
320
+ if (spaced) { result.splice(1, 0, rule()); result.push(""); }
308
321
  const capacity = Math.max(0, rows - result.length - footers.length - Number(spaced));
322
+ this.listCapacity = Math.max(1, capacity);
309
323
  const maxStart = Math.max(0, items.length - capacity);
310
324
  this.listStart = Math.min(this.listStart, maxStart);
311
325
  if (this.selected < this.listStart) this.listStart = this.selected;
@@ -317,7 +331,7 @@ export class MemoryInspectorComponent implements Component, Focusable {
317
331
  const rendered = i === this.selected ? `${accent(line)}${marker ? dim(marker) : ""}` : `${fit(line)}${marker ? dim(marker) : ""}`;
318
332
  result.push(truncateToWidth(rendered, safeWidth));
319
333
  }
320
- if (spaced) result.push("");
334
+ if (spaced) result.push(rule());
321
335
  result.push(...footers);
322
336
  } else {
323
337
  let breadcrumb: string;
@@ -348,12 +362,25 @@ export class MemoryInspectorComponent implements Component, Focusable {
348
362
  else body = this.item?.body ?? "";
349
363
  let wrapped: string[];
350
364
  if (this.wrappedCache?.width === safeWidth && this.wrappedCache.body === body) wrapped = this.wrappedCache.lines;
351
- else { wrapped = wrapTextWithAnsi(sanitizeCardText(body), safeWidth); this.wrappedCache = { width: safeWidth, body, lines: wrapped }; }
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
+ }
352
379
  const displayWrapped = [...wrapped];
353
380
  const missingSourceIndex = missingSource ? displayWrapped.push("", "Source unavailable for this item.") - 1 : -1;
354
381
  const actions = this.view === "detail" && this.tab === "memories" && this.options.onAction ? ["a actions"] : [];
355
382
  const pageKeys = `${pair("tui.select.pageUp", "tui.select.pageDown")} page`;
356
- const footers = safeWidth < 20
383
+ let footers = safeWidth < 20
357
384
  ? [dim(`↑↓ scroll/${key("tui.select.cancel")}`)]
358
385
  : safeWidth < 32
359
386
  ? footer([`${pair("tui.select.up", "tui.select.down")} scroll`, `${key("tui.select.cancel")} back`])
@@ -362,17 +389,23 @@ export class MemoryInspectorComponent implements Component, Focusable {
362
389
  ...footer([...(this.view === "detail" && this.item?.source ? ["s source"] : []), ...actions, `${key("tui.select.cancel")} back`, "F10 close"]),
363
390
  ];
364
391
  const scroll = this.view === "source" ? this.sourceScroll : this.view === "help" ? this.helpScroll : this.detailScroll;
365
- const indicatorRows = scroll > 0 ? 2 : 1;
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
+ }
366
398
  const spaced = rows - result.length - footers.length - indicatorRows >= 3;
367
- if (spaced) result.push("");
399
+ if (spaced) result.push(rule());
368
400
  const capacity = Math.max(0, rows - result.length - footers.length - indicatorRows - Number(spaced));
401
+ this.detailCapacity = Math.max(1, capacity);
369
402
  const maxStart = Math.max(0, displayWrapped.length - capacity);
370
403
  const start = Math.min(scroll, maxStart);
371
404
  this.setDetailScroll(start);
372
- if (start > 0) result.push(dim(`▲ ${start} lines above`));
405
+ if (indicatorRows && start > 0) result.push(dim(`▲ ${start} lines above`));
373
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)));
374
- if (start + capacity < displayWrapped.length) result.push(dim(`▼ ${displayWrapped.length - start - capacity} lines below`));
375
- if (spaced) result.push("");
407
+ if (indicatorRows && start + capacity < displayWrapped.length) result.push(dim(`▼ ${displayWrapped.length - start - capacity} lines below`));
408
+ if (spaced) result.push(rule());
376
409
  result.push(...footers);
377
410
  }
378
411
  return result.slice(0, rows).map(fit);
@@ -390,7 +423,7 @@ export class MemoryInspectorComponent implements Component, Focusable {
390
423
 
391
424
  export function createMemoryInspectorComponent(
392
425
  tui: TUI,
393
- theme: { fg(name: "accent" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
426
+ theme: { fg(name: "accent" | "border" | "dim" | "warning" | "error" | "success", text: string): string; bold(text: string): string },
394
427
  keybindings: KeybindingsManager,
395
428
  done: (result: void) => void,
396
429
  options: MemoryInspectorOptions,
@@ -398,17 +431,14 @@ export function createMemoryInspectorComponent(
398
431
  return new MemoryInspectorComponent(tui, theme, keybindings, done, options);
399
432
  }
400
433
 
401
- /** Match F9's 90% overlay, preserving margins and the same outer row limit in render and host. */
402
- export function memoryInspectorViewportRows(terminalRows: number): number {
403
- return Math.max(1, Math.min(Math.floor(terminalRows * 0.9), Math.floor(terminalRows) - 2));
404
- }
405
-
406
434
  export async function openMemoryInspector(
407
435
  ctx: ExtensionContext,
408
436
  options: MemoryInspectorOptions,
409
437
  ): Promise<void> {
410
438
  if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires interactive mode", "warning"); return; }
411
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; }
412
442
  try {
413
443
  let overlayTui: TUI | undefined;
414
444
  let component: MemoryInspectorComponent | undefined;
@@ -416,14 +446,14 @@ export async function openMemoryInspector(
416
446
  overlayTui = tui;
417
447
  component = new MemoryInspectorComponent(tui, theme, keybindings, done, {
418
448
  ...options,
419
- viewportHeight: () => memoryInspectorViewportRows(tui.terminal?.rows ?? 1),
449
+ viewportHeight: () => frame.viewportRows(tui.terminal?.rows ?? 1),
420
450
  });
421
451
  return component;
422
452
  }, {
423
453
  overlay: true,
424
454
  overlayOptions: () => {
425
455
  const rows = overlayTui?.terminal?.rows ?? 1;
426
- return { width: "90%", maxHeight: memoryInspectorViewportRows(rows), margin: 1 };
456
+ return { width: "90%", maxHeight: frame.viewportRows(rows), margin: 1 };
427
457
  },
428
458
  });
429
459
  const action = component?.takeAction();