@aeondave/pi-persona-mind 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }