@aeondave/pi-persona-mind 0.8.7 → 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.
package/src/index.ts CHANGED
@@ -28,11 +28,18 @@ import { resetMindSettings, resolveMindSettings } from "./core/mind-settings.ts"
28
28
  import { MindService } from "./core/service.ts";
29
29
  import { registerBacklogTool } from "./tools/backlog.ts";
30
30
  import { registerMemoryTool } from "./tools/memory.ts";
31
- import { renderExpandableCard } from "./ui/presentation.ts";
31
+ import { cardFrameDetailHint, cardFramePresentation, createMindCardUI } from "./ui/card-frame.ts";
32
32
  import { createSessionMemory } from "./session-memory.ts";
33
33
  import { registerSessionNoteRenderer } from "./ui/session-note-card.ts";
34
34
  import type { MemoryOptimizer } from "./core/optimize-service.ts";
35
35
  import { registerMindCommands } from "./extension/mind-command.ts";
36
+ import { createMemoryInspector } from "./extension/memory-inspector.ts";
37
+ import { loadInspectorPage } from "./extension/inspector-data.ts";
38
+ import { openMemoryInspector } from "./ui/memory-inspector.ts";
39
+ import { queryInspectorFrame } from "./ui/inspector-frame.ts";
40
+ import { createKnowledgeReview } from "./extension/knowledge-review.ts";
41
+ import { launchMindWorker } from "./extension/mind-worker.ts";
42
+ import { runMindInspectorActions } from "./extension/mind-actions.ts";
36
43
  import { MIND_RESULT_ENTRY_TYPE, registerMindResultRenderer } from "./ui/mind-result-card.ts";
37
44
  import { parsePersonaMemoryOwner, PERSONA_MEMORY_OWNER_CHANGED, personaGuardedTools, queryPersonaDependency, queryPersonaMemoryOwner } from "./extension/persona-dependency.ts";
38
45
  import { createMindActivityRunner } from "./extension/activity.ts";
@@ -307,8 +314,9 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
307
314
  return new MindService(resolveMindScope(ctx), { onWarn: (message) => surfaceWarning(ctx, message) });
308
315
  };
309
316
  const sessionMemory = createSessionMemory(pi);
310
- registerSessionNoteRenderer(pi);
311
- registerMindResultRenderer(pi);
317
+ const mindCardUI = createMindCardUI(pi);
318
+ registerSessionNoteRenderer(pi, mindCardUI);
319
+ registerMindResultRenderer(pi, mindCardUI);
312
320
  let optimizerCache: { manager: ExtensionContext["sessionManager"]; key: string; optimizer: MemoryOptimizer } | undefined;
313
321
  const discardOptimizer = (): void => {
314
322
  optimizerCache?.optimizer.invalidate();
@@ -336,9 +344,15 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
336
344
  });
337
345
  };
338
346
 
339
- pi.registerEntryRenderer<{ content: string }>(WAKE_ENTRY_TYPE, (entry, { expanded }, theme) => {
347
+ pi.registerEntryRenderer<{ content: string }>(WAKE_ENTRY_TYPE, (entry, { expanded, keyHint }, theme) => {
340
348
  const body = typeof entry.data?.content === "string" ? entry.data.content : "";
341
- return renderExpandableCard("pi-persona-mind", body, expanded, theme);
349
+ return mindCardUI.renderCard(cardFramePresentation("pi-persona-mind", body), {
350
+ expanded,
351
+ theme,
352
+ outputPad: mindCardUI.outputPad(),
353
+ detailHint: cardFrameDetailHint(keyHint),
354
+ expansionKey: entry,
355
+ });
342
356
  });
343
357
 
344
358
  /** Human-visible due reminder: toast + collapsed card. Must never sendUserMessage / triggerTurn. */
@@ -523,6 +537,30 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
523
537
  // the markers, only a compatible, enabled supervisor may use the full mind.
524
538
  const isDelegatedLeg = process.env.PI_PERSONA_LEG === "1" || process.env.PI_PERSONA_CHILD === "1";
525
539
  const autoOptimize = installAutoOptimize(pi, { isDelegatedLeg, available, captureOwner: captureMemoryOwner, scope: resolveMindScope, persona: rawMindPersona, mind: getMind });
540
+ const knowledgeReview = createKnowledgeReview({
541
+ captureOwner: captureMemoryOwner,
542
+ mind: getMind,
543
+ reserve: (target) => autoOptimize.reserveReview(target),
544
+ launch: (ctx, task) => launchMindWorker(pi, ctx.sessionManager.getSessionId(), rawMindPersona(ctx), task),
545
+ appendResult: (ctx, title, body) => {
546
+ if (!available(ctx) || !sessionMemory.isCurrent(ctx)) throw new Error("knowledge review owner is unavailable");
547
+ pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body });
548
+ },
549
+ });
550
+ const inspector = createMemoryInspector({
551
+ unavailableReason: (ctx) => unavailableReason(ctx) ?? (isDelegatedLeg || !sessionMemory.isCurrent(ctx) ? "Memory inspector requires an active supervisor session owner." : undefined),
552
+ captureOwner: captureMemoryOwner,
553
+ load: (ctx, request) => loadInspectorPage(ctx, getMind(ctx), sessionMemory, request),
554
+ show: (ctx, options) => {
555
+ const frame = queryInspectorFrame(pi.events);
556
+ return openMemoryInspector(ctx, { ...options, ...(frame ? { frame } : {}) });
557
+ },
558
+ actions: (ctx, request, current) => runMindInspectorActions(ctx, request, current, { consolidate: (target) => autoOptimize.startExplicit(target), review: knowledgeReview }),
559
+ });
560
+ if (!isDelegatedLeg) pi.registerShortcut("f10", { description: "Inspect memory, sources and timeline", handler: (ctx) => inspector.open(ctx) });
561
+ pi.on("session_tree", () => { discardOptimizer(); inspector.invalidate(); knowledgeReview.interrupt(); });
562
+ pi.on("agent_start", () => knowledgeReview.interrupt());
563
+ pi.on("model_select", () => knowledgeReview.interrupt());
526
564
 
527
565
  // Withhold the write tools from a worker: a leg reading/writing the supervisor persona's LTM/STM/
528
566
  // backlog is exactly the bleed we prevent. It still INHERITS the lean block below (read-only, curated).
@@ -567,6 +605,8 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
567
605
  if (ctx && currentSessionContext && ctx.sessionManager !== currentSessionContext.sessionManager) return;
568
606
  if (personaUnavailable) return;
569
607
  personaUnavailable = true;
608
+ knowledgeReview.interrupt();
609
+ inspector.invalidate();
570
610
  autoOptimize.revoke();
571
611
  discardOptimizer();
572
612
  sessionMemory.deactivate();
@@ -642,7 +682,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
642
682
  ctx,
643
683
  `${headline}\n${list}${more}\nReview when ready — stale leads auto-remove after ~48h; keep durable facts in long-term memory.`,
644
684
  );
645
- await mind.acknowledgeDue(due.map((item) => item.id));
685
+ await mind.acknowledgeDue(due.map((item) => ({ id: item.id, dueAtEpochMs: item.dueAtEpochMs! })));
646
686
  } catch {
647
687
  /* raced shutdown */
648
688
  }
@@ -682,7 +722,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
682
722
  ctx,
683
723
  `backlog due — ${compactMemoryText(live.text, MAX_WAKE_TEXT_CHARS)} (id ${live.id}). Review when ready.`,
684
724
  );
685
- await mind.acknowledgeDue([live.id]);
725
+ await mind.acknowledgeDue([{ id: live.id, dueAtEpochMs: live.dueAtEpochMs }]);
686
726
  } catch (err) {
687
727
  if (wakeCurrent(generation, nextOwnerPath)) surfaceWarning(ctx, `could not re-check due backlog item ${item.id}: ${err instanceof Error ? err.message : String(err)}`);
688
728
  }
@@ -709,6 +749,8 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
709
749
  return;
710
750
  }
711
751
  if (activeScopeKey === nextKey) return;
752
+ knowledgeReview.interrupt();
753
+ inspector.invalidate();
712
754
  discardOptimizer();
713
755
  clearTimers();
714
756
  releaseWakeOwner();
@@ -722,8 +764,11 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
722
764
  };
723
765
 
724
766
  const refreshStatus = async (ctx: ExtensionContext): Promise<void> => {
767
+ let ownerCurrent = (): boolean => false;
725
768
  try {
769
+ ownerCurrent = captureMemoryOwner(ctx);
726
770
  const s = await getMind(ctx).summary();
771
+ if (!ownerCurrent()) return;
727
772
  if (warningStatusActive) {
728
773
  setStatus(ctx, "mind warning · /mind doctor", "warning");
729
774
  return;
@@ -732,7 +777,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
732
777
  const label = `mind ${s.ltm}L·${s.projectLtm}P·${s.stm}S · backlog ${s.backlogOpen}`;
733
778
  setStatus(ctx, label);
734
779
  } catch (err) {
735
- 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)}`);
736
781
  }
737
782
  };
738
783
 
@@ -794,6 +839,8 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
794
839
  // persists every turn while the mind stays empty (that would be the nag we avoid).
795
840
  let emptyAnnounced = false;
796
841
  const resetSessionTransientState = (): number => {
842
+ knowledgeReview.interrupt();
843
+ inspector.invalidate();
797
844
  sessionLifecycleGeneration++;
798
845
  captureInputGeneration++;
799
846
  pendingCaptureNotice = undefined;
@@ -814,69 +861,62 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
814
861
  nestedBlockedRelays.delete(oldest);
815
862
  }
816
863
  };
817
- const captureDirectCues = async (
864
+ const captureDirectCues = (
818
865
  text: string,
819
866
  ctx: ExtensionContext,
820
867
  lifecycleGeneration: number,
821
868
  inputGeneration: number,
822
- ): Promise<CaptureNotice | undefined> => {
869
+ ): CaptureNotice | undefined => {
823
870
  const cues = detectCaptureCues(text);
824
871
  if (cues.length === 0) return undefined;
825
872
  const explicit = capturePolicy === "auto" ? cues.filter((cue) => cue.strong) : [];
826
- const mind = explicit.length > 0 ? getMind(ctx) : undefined;
827
873
  const ownerCurrent = captureMemoryOwner(ctx);
828
874
  const isCurrent = (): boolean => lifecycleGeneration === sessionLifecycleGeneration && inputGeneration === captureInputGeneration && ownerCurrent();
829
- if (explicit.length > 0) {
830
- await ensureLegacyMigrated(ctx);
831
- if (isCurrent()) await reconcileScope(ctx, lifecycleGeneration);
832
- }
833
- const stored: string[] = [];
875
+ const stored: Array<{ id: string; storage: "session" | "memory" }> = [];
834
876
  const failures: string[] = [];
835
- if (mind) {
836
- for (const cue of explicit) {
837
- const label = cue.kind === "preference" ? "User preference" : cue.kind === "rationale" ? "Durable user decision" : "User explicitly asked to retain";
838
- const result = await mind.remember({
839
- term: cue.term,
840
- kind: cue.kind,
841
- text: `${label}: ${cue.candidate}`,
842
- tags: ["auto-captured"],
843
- source: "direct user persistence cue",
844
- });
845
- if (result.ok) {
846
- stored.push(result.entry.id);
847
- if (isCurrent()) autoOptimize.memoryAdded(ctx, cue.term === "long" ? "persona" : "project");
848
- }
849
- else failures.push(result.reason);
850
- }
877
+ for (const cue of explicit) {
878
+ // No migration, persistent memory-store read/write, or optimizer notification belongs to
879
+ // automatic capture. SessionMemory performs the owner check immediately before append.
880
+ if (!isCurrent()) break;
881
+ const label = cue.kind === "preference" ? "User preference" : cue.kind === "rationale" ? "User decision" : "User asked to retain";
882
+ const result = sessionMemory.remember(ctx, {
883
+ kind: cue.kind,
884
+ text: `${label}: ${cue.candidate}`,
885
+ source: "direct user persistence cue",
886
+ });
887
+ if (result.ok) stored.push({ id: result.entry.id, storage: result.storage });
888
+ else failures.push(result.reason);
851
889
  }
852
- // Durable writes from the accepted user input are preserved across a session change, but its
853
- // acknowledgement and prompt/UI state belong only to the session/input that accepted it.
890
+ // Captures already appended remain on the accepting native owner; notices remain input/session-local.
854
891
  if (!isCurrent()) return undefined;
855
892
  for (const cue of explicit) rememberCueHint(cue.snippet);
856
893
 
857
894
  let hint = "";
858
895
  if (stored.length > 0) {
859
- hint = `⟢ pi-persona-mind — already captured ${stored.length} explicit user memor${stored.length === 1 ? "y" : "ies"} (${stored.join(", ")}); do not duplicate ${stored.length === 1 ? "it" : "them"}.`;
896
+ const ids = stored.map(({ id }) => id);
897
+ const persistentSession = stored.every(({ storage }) => storage === "session");
898
+ hint = persistentSession
899
+ ? `⟢ pi-persona-mind — saved ${stored.length} cue${stored.length === 1 ? "" : "s"} as native active-branch session note${stored.length === 1 ? "" : "s"} only (${ids.join(", ")}). This is not a project/persona/shared durable save; do not duplicate the session note. If broader durability is intended, make a separate deliberate memory remember call with an explicit scope chosen from the user's actual intent.`
900
+ : `⟢ pi-persona-mind — kept ${stored.length} cue${stored.length === 1 ? "" : "s"} as session-only note${stored.length === 1 ? "" : "s"} in this runtime's in-memory session (${ids.join(", ")}); this host has no persistent session file, so it is not restart-durable. No project/persona/shared store was written. Do not duplicate the session note; broader durability needs a separate deliberate memory remember call with an explicit scope chosen from actual user intent.`;
860
901
  try {
861
- ctx.ui.notify(`[pi-persona-mind] Captured ${stored.length} explicit memor${stored.length === 1 ? "y" : "ies"}.`, "info");
902
+ ctx.ui.notify(`[pi-persona-mind] ${persistentSession ? "Saved only as active-branch session notes; no durable memory store was written." : "Kept session-only notes in this runtime's in-memory session; no durable memory store was written."}`, "info");
862
903
  } catch {
863
904
  /* headless/no UI */
864
905
  }
865
- await refreshStatus(ctx);
866
906
  }
867
907
  if (failures.length > 0) {
868
- const reason = failures[0] ?? "unknown storage failure";
869
- const retryHint = `⚠ pi-persona-mind could not auto-capture one explicit user memory: ${reason}. Before final, retry once with a safe declarative \`memory remember\` entry.`;
908
+ const reason = failures[0] ?? "unknown session append failure";
909
+ const retryHint = `⚠ pi-persona-mind could not append a session-only note: ${reason}. No external or durable write was attempted. Do not fall back to a durable store; if retention is still wanted, retry with term=session or make a separate deliberate long-term memory call with an explicit scope chosen from actual user intent.`;
870
910
  hint = [hint, retryHint].filter(Boolean).join("\n\n");
871
- surfaceWarning(ctx, `automatic capture failed: ${reason}`);
911
+ surfaceWarning(ctx, `session-only automatic capture failed: ${reason}`);
872
912
  }
873
913
  if (!hint && nudgeEnabled) {
874
914
  const cue = cues[0];
875
915
  if (cue) {
876
916
  rememberCueHint(cue.snippet);
877
- hint = `⟢ pi-persona-mind — possible durable ${cue.kind} detected in direct user input. Save one safe declarative memory only if it should outlive this task.`;
917
+ hint = `⟢ pi-persona-mind — possible ${cue.kind} candidate detected in direct user input. For task-specific or uncertain retention use memory remember with term=session. Use term=long only with an explicit project, persona, or shared scope when that broader lifetime matches the user's actual intent.`;
878
918
  try {
879
- ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", `💡 worth remembering? memory remember (${cue.kind})`) : `💡 worth remembering? (${cue.kind})`);
919
+ ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", `💡 review candidate · memory remember (${cue.kind}, term=session)` ) : `💡 review candidate (${cue.kind}, term=session)`);
880
920
  } catch {
881
921
  /* cosmetic */
882
922
  }
@@ -890,6 +930,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
890
930
  // explicit persist-intent is safe to commit deterministically before the model runs. Everything
891
931
  // softer remains a model-visible candidate governed by the standing tool guideline.
892
932
  pi.on("input", async (event, ctx) => {
933
+ knowledgeReview.interrupt();
893
934
  if (!available(ctx)) return;
894
935
  const lifecycleGeneration = sessionLifecycleGeneration;
895
936
  const inputGeneration = ++captureInputGeneration;
@@ -1037,6 +1078,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1037
1078
  }
1038
1079
  }
1039
1080
  }
1081
+ const inspectorCurrent = inspector.captureContext(ctx);
1040
1082
  let block = "";
1041
1083
  const query = directInputPrompt ?? latestDirectInputPrompt ?? "";
1042
1084
  const sessionBlock = isDelegatedLeg ? "" : sessionMemory.injection(ctx, { query, maxTokens: 600 });
@@ -1058,6 +1100,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1058
1100
  else emptyAnnounced = true;
1059
1101
  }
1060
1102
  const injected = [block, sessionBlock, cueHint].filter(Boolean).join("\n\n");
1103
+ if (!isDelegatedLeg) inspector.recordContext(ctx, injected, inspectorCurrent);
1061
1104
  if (injected) return { systemPrompt: `${event.systemPrompt}\n\n${injected}` };
1062
1105
  return;
1063
1106
  });
@@ -1176,6 +1219,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1176
1219
  if (!ctx) return;
1177
1220
  const changed = parsePersonaMemoryOwner(value, sessionIdOf(ctx));
1178
1221
  if (!changed) return;
1222
+ knowledgeReview.interrupt();
1179
1223
  if (!changed.ready) { onPersonaUnavailable(); return; }
1180
1224
  if (!available(ctx)) return;
1181
1225
  autoOptimize.activate(ctx);
@@ -1189,7 +1233,7 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1189
1233
  })().catch((error: unknown) => { if (generation === sessionLifecycleGeneration && available(ctx)) surfaceWarning(ctx, `could not activate Persona memory owner: ${error instanceof Error ? error.message : String(error)}`); });
1190
1234
  });
1191
1235
 
1192
- pi.on("session_shutdown", (_event, ctx) => {
1236
+ pi.on("session_shutdown", async (_event, ctx) => {
1193
1237
  currentSessionContext = undefined;
1194
1238
  discardOptimizer();
1195
1239
  sessionMemory.deactivate();
@@ -1202,11 +1246,14 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1202
1246
  wakeGeneration++;
1203
1247
  clearTimers();
1204
1248
  releaseWakeOwner();
1249
+ await knowledgeReview.join();
1205
1250
  });
1206
1251
 
1207
1252
  registerMindCommands(pi, {
1208
1253
  agentDir, resolveScope: resolveMindScope, rawPersona: rawMindPersona, getMind,
1209
1254
  getSessionMemory: () => sessionMemory, getOptimizer, ensureLegacyMigrated, surfaceWarning,
1255
+ openInspector: (ctx, tab) => inspector.open(ctx, tab),
1256
+ knowledgeReview,
1210
1257
  migrationStatus,
1211
1258
  unavailableReason,
1212
1259
  activity: getActivity,
@@ -84,8 +84,12 @@ export function createSessionMemory(pi: Pick<ExtensionAPI, "appendEntry">): Sess
84
84
  const max = Number.isFinite(opts.max) ? Math.max(1, Math.min(50, Math.floor(opts.max!))) : 8;
85
85
  const query = opts.query ?? "";
86
86
  if (query.length > 2_000) return { ...status, ok: false, reason: "session recall query exceeds 2000 characters", hits: [], total: 0, withheld: 0, max };
87
- const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
88
- const matched = snapshot.notes.filter((note) => words.every((word) => `${note.text} ${note.source ?? ""}`.toLocaleLowerCase().includes(word))).reverse();
87
+ // Source provenance remains searchable as lexical metadata; native branch order owns
88
+ // recency ties, including equal timestamps or a host clock that moved backwards.
89
+ const ranked = rankRetrievalEntries(snapshot.notes.map((note, position) => ({
90
+ note, position, id: note.id, text: note.text, tags: note.source ? [note.source] : [],
91
+ })), query, (a, b) => b.position - a.position);
92
+ const matched = ranked.filter((match) => !query.trim() || match.score > 0).map((match) => match.entry.note);
89
93
  return { ...status, hits: matched.slice(0, max), total: matched.length, withheld: Math.max(0, matched.length - max), max };
90
94
  },
91
95
  read(ctx, id) {
@@ -119,8 +119,8 @@ export function registerBacklogTool(pi: ExtensionAPI, getMind: GetMind): void {
119
119
  ? say(`${params.id} → ${state}.`, { id: params.id, state, ok: true })
120
120
  : say(`Not updated: ${r.reason ?? `backlog item "${params.id}" does not exist or cannot transition to ${state}`}.`, { ok: false, reason: r.reason ?? "invalid state transition" });
121
121
  },
122
- renderResult(result, { expanded }, theme) {
123
- return renderExpandableResult(toolResultText(result), expanded, theme);
122
+ renderResult(result, { expanded }, theme, context) {
123
+ return renderExpandableResult(toolResultText(result), expanded, theme, () => context.keyHint("app.tools.expand", "to expand"));
124
124
  },
125
125
  });
126
126
  }
@@ -42,13 +42,13 @@ const MemoryParams = Type.Object({
42
42
  }),
43
43
  term: Type.Optional(
44
44
  Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("session")], {
45
- description: "remember: long = durable persona identity; short = expiring project note; session = active-branch note only, never copied into persona archives. Required for remember.",
45
+ description: "remember: choose the lifetime explicitly. session = active-branch only (use for task-specific or uncertain choices such as models, strategies, and task constraints); short = expiring project working context; long = durable and requires an explicit scope. Kind does not change lifetime; an objective may be session-local or short-lived.",
46
46
  }),
47
47
  ),
48
48
  kind: Type.Optional(
49
49
  Type.Union(
50
50
  MEMORY_KINDS.map((k) => Type.Literal(k)),
51
- { description: "remember: the category of the fact. Required for remember." },
51
+ { description: "remember: content category only; kind never promotes a short or session lifetime. Required for remember." },
52
52
  ),
53
53
  ),
54
54
  text: Type.Optional(
@@ -65,7 +65,7 @@ const MemoryParams = Type.Object({
65
65
  derivedFrom: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_ID_CHARS }), { maxItems: MAX_MEMORY_DERIVED_IDS, description: "remember: optional ids of memories distilled into this fact" })),
66
66
  query: Type.Optional(Type.String({ maxLength: MAX_RECALL_QUERY_CHARS, description: "recall: keywords (empty = most recent); optimize inspect: optional substring filter" })),
67
67
  scope: Type.Optional(
68
- Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("both"), Type.Literal("session"), Type.Literal("project"), Type.Literal("persona"), Type.Literal("shared")], { description: "remember/promote: project|persona|shared; long remember defaults persona, promote defaults project. recall/read/forget: project includes repository durable + working facts; long includes all durable tiers; both includes all active stores; session is branch-local." }),
68
+ Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("both"), Type.Literal("session"), Type.Literal("project"), Type.Literal("persona"), Type.Literal("shared")], { description: "remember(long): REQUIRED destination project|persona|shared; no implicit default. Use project for stable facts of this repository, persona for facts intended across all projects of this persona, and shared only when intended across personas. remember(short) defaults to project and only accepts project; remember(session) accepts no scope or redundant session. This selects API routing; it is not authenticated consent. promote defaults to project. recall/read/forget: project includes repository durable + working facts; long includes all durable tiers; both includes all active stores; session is branch-local." }),
69
69
  ),
70
70
  max: Type.Optional(Type.Number({ description: "recall: maximum results, clamped to 1..50 (default 8); optimize inspect: entry page 1..100 (default 20)" })),
71
71
  offset: Type.Optional(Type.Number({ minimum: 0, maximum: DEFAULT_STORE_MAX_ENTRIES, multipleOf: 1, description: `optimize inspect: zero-based page offset from 0 to ${DEFAULT_STORE_MAX_ENTRIES} (default 0)` })),
@@ -86,6 +86,14 @@ const MemoryParams = Type.Object({
86
86
 
87
87
  type MemoryToolParams = Type.Static<typeof MemoryParams>;
88
88
 
89
+ const SESSION_REMEMBER_EXAMPLE = '{ action: "remember", term: "session", kind: "note", text: "Keep this branch focused." }';
90
+ const SHORT_REMEMBER_EXAMPLE = '{ action: "remember", term: "short", kind: "note", text: "The staging environment is read-only today." }';
91
+ const LONG_REMEMBER_EXAMPLE = '{ action: "remember", term: "long", scope: "project", kind: "invariant", text: "This repository requires strict typechecks." }';
92
+
93
+ function rememberCorrection(message: string, example: string): string {
94
+ return `${message} Retry with a complete remember action, for example: ${example}`;
95
+ }
96
+
89
97
  /** How many colliding facts an ambiguity refusal names before it summarizes the rest. */
90
98
  const MAX_AMBIGUITY_CANDIDATES_SHOWN = 5;
91
99
 
@@ -107,15 +115,13 @@ export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMe
107
115
  label: "Memory",
108
116
  promptSnippet: "memory — persist, recall, inspect, and explicitly consolidate durable facts, project context, and active-session notes",
109
117
  promptGuidelines: [
110
- "Before the final answer, use `memory` once when this turn established a durable user preference, architectural decision/invariant, or verified lesson that is not simply re-derivable from the repository. A user who explicitly labels a fact durable/permanent is asking for capture even without the word 'remember'. Use `backlog` for unfinished intent. Skip routine transcript, guesses, and secrets.",
118
+ "Before the final answer, use `memory` when useful context should be retained. The model chooses lifetime and scope from meaning and context; users need not name API scopes or say a literal 'global'. Genuinely portable preferences belong in persona/shared memory; subject matter alone, including a model or strategy name, never determines scope. Choose `term=session` for task-specific or uncertain choices (including models, strategies, and task constraints); use `term=short` for expiring project working context; use `term=long` only with an explicit `scope`: `project` for stable repository facts, `persona` for facts intended across all projects of this persona, and `shared` only when truly intended across personas. An explicit scope selects the API destination; it is not authenticated consent. AUTO capture is provisional session-only and never makes a durable save; do not duplicate that session note. Broader durability requires a deliberate memory call with a scope chosen from the actual user intent. Use `backlog` for unfinished work; skip secrets and re-derivable facts.",
111
119
  "For consolidation, inspect first, read the full selected entries, compare them with the newest primary evidence, then stage explicit rewrites/merges that preserve exceptions and provenance. Review the exact before/after plan and character counts; apply the exact staged plan within the user's authorized memory-maintenance scope. Inspect is read-only and never calls a model or applies changes by itself.",
112
120
  ],
113
121
  description: [
114
- "Your durable, persona-scoped memory. `remember` a fact so it survives context compaction and",
115
- "restarts — long-term for who this persona is to the user (preferences/conventions/lessons),",
116
- "long with scope=project for durable repository knowledge, short for project notes that auto-delete after ~48h, or session for active-branch notes only. Scope=shared explicitly shares durable facts across personas. Promotion preserves project scope by default. `recall` searches; `read` gets full text; `forget` retires by id with optional scope. For `optimize`, inspect candidates, read full entries, compare against current evidence, stage explicit reviewed replacements preserving exceptions and provenance, then apply only an authorized exact plan. Inspect is read-only; it does not call a model or write.",
117
- "Facts are re-injected into your context automatically each turn, so remember what you would",
118
- "want to know next session. Keep entries DECLARATIVE, never store secrets.",
122
+ "`remember` stores context for an explicitly chosen lifetime: `session` for active-branch notes only (best for task-specific or uncertain choices), `short` for expiring project working context, or `long` for durable facts with a REQUIRED explicit `scope=project|persona|shared`. Use project for stable repository facts, persona for intent across all projects of the same persona, and shared only for intent across personas. Long-term scope has no implicit default; the scope selects an API destination and does not authenticate consent. Automatic cue capture is always provisional session-only, even for explicit durability phrases; it does not make an external/durable save. Broader retention needs a deliberate scoped memory call. Promotion defaults to project. `recall` searches; `read` gets full text; `forget` retires by id with optional scope. For `optimize`, inspect candidates, read full entries, compare against current evidence, stage explicit reviewed replacements preserving exceptions and provenance, then apply an exact reviewed plan. Inspect is read-only; it does not call a model or write.",
123
+ "Stored facts remain available through recall/read; relevant facts are ranked for bounded context each turn.",
124
+ "Keep entries DECLARATIVE, never store secrets.",
119
125
  ].join(" "),
120
126
  parameters: MemoryParams,
121
127
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
@@ -132,7 +138,7 @@ export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMe
132
138
  return say(`Memory is unavailable: ${message || "unknown persistence failure"}`, { ok: false, reason: "storage_error" });
133
139
  }
134
140
  },
135
- renderResult(result, { expanded }, theme) {
141
+ renderResult(result, { expanded }, theme, context) {
136
142
  const body = toolResultText(result);
137
143
  const details = result.details && typeof result.details === "object" ? result.details as Record<string, unknown> : undefined;
138
144
  // Recognize old receipts too, so reopening a session does not restore the noisy card.
@@ -142,9 +148,9 @@ export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMe
142
148
  const summary = typeof details?.summary === "string"
143
149
  ? details.summary
144
150
  : savedSession ? "Session note saved" : `${savedTerm === "long" ? "Long" : "Short"}-term saved`;
145
- return renderExpandableResult(summary, true, theme);
151
+ return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"), summary);
146
152
  }
147
- return renderExpandableResult(body, expanded, theme);
153
+ return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"));
148
154
  },
149
155
  });
150
156
  }
@@ -165,16 +171,32 @@ function validateMemoryParams(value: unknown): string | undefined {
165
171
  if (prototype !== Object.prototype && prototype !== null) return "memory action parameters must be a plain object.";
166
172
  const params = value as Record<string, unknown>;
167
173
  if (typeof params.action !== "string" || !Object.hasOwn(KEYS, params.action)) return "Unknown memory action.";
168
- if (Reflect.ownKeys(params).some((key) => typeof key !== "string" || !KEYS[params.action as string]!.has(key))) return `memory ${params.action} received a field that does not belong to that action.`;
169
174
  const has = (key: string) => Object.hasOwn(params, key);
175
+ const unknownFields = Reflect.ownKeys(params).filter((key) => typeof key !== "string" || !KEYS[params.action as string]!.has(key)).map(String);
176
+ if (unknownFields.length > 0) {
177
+ if (params.action === "remember" && params.term === "session") return rememberCorrection(`memory remember term=session does not accept field(s): ${unknownFields.join(", ")}.`, SESSION_REMEMBER_EXAMPLE);
178
+ return `memory ${params.action} received unsupported field(s): ${unknownFields.join(", ")}.`;
179
+ }
170
180
  const str = (key: string, min: number, max: number) => typeof params[key] === "string" && (params[key] as string).length >= min && (params[key] as string).length <= max;
171
181
  if (params.action === "remember") {
172
- if (params.term !== "long" && params.term !== "short" && params.term !== "session") return "memory remember needs term=long|short|session.";
173
- if (typeof params.kind !== "string" || !(MEMORY_KINDS as readonly string[]).includes(params.kind)) return "memory remember needs a valid kind.";
174
- if (!str("text", 1, MAX_MEMORY_TEXT_CHARS)) return `memory remember text must contain 1..${MAX_MEMORY_TEXT_CHARS} characters.`;
175
- if (params.term === "session" && ["tags", "ttlHours", "supersedes", "scope", "derivedFrom"].some(has)) return "session notes accept only kind, text, and optional source.";
176
- if (params.scope !== undefined && !["project", "persona", "shared"].includes(String(params.scope))) return "remember scope must be project, persona, or shared.";
177
- if (params.term === "short" && params.scope !== undefined && params.scope !== "project") return "short-term notes belong to project scope.";
182
+ if (params.term !== "long" && params.term !== "short" && params.term !== "session") return rememberCorrection("memory remember is missing a valid term; choose long, short, or session.", SESSION_REMEMBER_EXAMPLE);
183
+ const example = params.term === "long" ? LONG_REMEMBER_EXAMPLE : params.term === "short" ? SHORT_REMEMBER_EXAMPLE : SESSION_REMEMBER_EXAMPLE;
184
+ if (typeof params.kind !== "string" || !(MEMORY_KINDS as readonly string[]).includes(params.kind)) return rememberCorrection("memory remember needs a valid kind.", example);
185
+ if (!str("text", 1, MAX_MEMORY_TEXT_CHARS)) return rememberCorrection(`memory remember text must contain 1..${MAX_MEMORY_TEXT_CHARS} characters.`, example);
186
+ if (params.term === "session") {
187
+ const unsupported = ["tags", "ttlHours", "supersedes", "derivedFrom"].filter(has);
188
+ const incompatibleScope = params.scope !== undefined && params.scope !== "session";
189
+ const fields = [...unsupported, ...(incompatibleScope ? ["scope"] : [])];
190
+ if (fields.length > 0) return rememberCorrection(`memory remember term=session does not support field(s): ${fields.join(", ")}; only kind, text, optional source, and optional scope=session are valid.`, SESSION_REMEMBER_EXAMPLE);
191
+ if (params.source !== undefined && (typeof params.source !== "string" || params.source.length > MAX_MEMORY_SOURCE_CHARS)) return rememberCorrection(`memory source must be at most ${MAX_MEMORY_SOURCE_CHARS} characters.`, example);
192
+ return;
193
+ }
194
+ if (params.term === "long" && params.scope === undefined) return rememberCorrection("memory remember term=long requires an explicit scope=project|persona|shared; there is no implicit long-term destination. Choose the scope that matches the user's actual intent (scope is an API destination, not authenticated consent).", LONG_REMEMBER_EXAMPLE);
195
+ if (params.scope !== undefined && !["project", "persona", "shared"].includes(String(params.scope))) {
196
+ const required = params.term === "long" ? "long-term scope must be project, persona, or shared" : "short-term scope must be project";
197
+ return rememberCorrection(`memory remember field scope is invalid: ${required}.`, example);
198
+ }
199
+ if (params.term === "short" && params.scope !== undefined && params.scope !== "project") return rememberCorrection("short-term notes belong to project scope.", SHORT_REMEMBER_EXAMPLE);
178
200
  if (params.tags !== undefined && (!Array.isArray(params.tags) || params.tags.length > MAX_MEMORY_TAGS || !Array.from(params.tags).every((tag) => typeof tag === "string" && tag.length <= MAX_MEMORY_TAG_CHARS))) return "memory tags exceed their bounds.";
179
201
  if (params.derivedFrom !== undefined && (!Array.isArray(params.derivedFrom) || params.derivedFrom.length > MAX_MEMORY_DERIVED_IDS || !Array.from(params.derivedFrom).every((id) => isMemoryId(id)))) return "memory derivedFrom ids are invalid or exceed their bound.";
180
202
  if (params.source !== undefined && (typeof params.source !== "string" || params.source.length > MAX_MEMORY_SOURCE_CHARS)) return "memory source exceeds its bound.";
@@ -235,20 +257,24 @@ async function runMemoryAction(mind: MindService, params: MemoryToolParams, ctx:
235
257
  ? say(`Remembered session note ${result.entry.id}. It belongs to this active session only.`, { ok: true, action: "remember", storage: result.storage, id: result.entry.id, summary: `Session note saved — ${compactMemoryText(result.entry.text, 80)}` })
236
258
  : say(`Not stored: ${result.reason}`, { ok: false, reason: result.reason });
237
259
  }
238
- const input: RememberInput = { term: params.term, kind: params.kind, text: params.text };
260
+ const input: RememberInput = params.term === "long"
261
+ ? { term: "long", scope: params.scope as "project" | "persona" | "shared", kind: params.kind, text: params.text }
262
+ : { term: "short", ...(params.scope === "project" ? { scope: "project" as const } : {}), kind: params.kind, text: params.text };
239
263
  if (params.tags) input.tags = params.tags;
240
264
  if (params.ttlHours !== undefined) input.ttlHours = params.ttlHours;
241
265
  if (params.supersedes) input.supersedes = params.supersedes;
242
- if (params.scope === "project" || params.scope === "persona" || params.scope === "shared") input.scope = params.scope;
243
266
  if (params.source) input.source = params.source;
244
267
  if (params.derivedFrom) input.derivedFrom = params.derivedFrom;
245
268
  const r = await mind.remember(input);
269
+ const destination = params.term === "long" ? params.scope as "project" | "persona" | "shared" : "project";
246
270
  return r.ok
247
- ? say(`Remembered ${r.entry.id} — ${r.entry.expiresAt ? "short" : "long"}-term ${params.kind}. It will re-appear in your context.`, {
271
+ ? say(`Remembered ${r.entry.id} — ${r.entry.expiresAt ? "short" : "long"}-term ${params.kind} in ${destination} scope. Available through memory recall/read and ranked for bounded context.`, {
248
272
  id: r.entry.id,
249
273
  ok: true,
250
- scope: params.scope ?? (r.entry.expiresAt ? "project" : "persona"),
251
- summary: `${params.scope ?? (r.entry.expiresAt ? "project" : "persona")} · ${r.entry.expiresAt ? "working" : "durable"} saved — ${compactMemoryText(r.entry.text, 80)}`,
274
+ scope: destination,
275
+ // Native receipt metadata, not model-supplied source authority or a new archive.
276
+ recording: { version: 1, persona: mind.inspectionScope().persona, projectRoot: mind.inspectionScope().projectRoot, target: params.term === "short" ? "project" : destination === "project" ? "project-long" : destination },
277
+ summary: `${destination} · ${r.entry.expiresAt ? "working" : "durable"} saved — ${compactMemoryText(r.entry.text, 80)}`,
252
278
  })
253
279
  : say(`Not stored: ${r.reason}`, { ok: false, reason: r.reason });
254
280
  }
@@ -370,6 +396,7 @@ async function runMemoryAction(mind: MindService, params: MemoryToolParams, ctx:
370
396
  // forget
371
397
  if (!params.id) return say("memory forget needs { id } (see recall).", { ok: false, reason: "missing id" });
372
398
  if (params.id.startsWith("session:")) {
399
+ if (params.scope !== undefined && params.scope !== "session") return say("A session note id can only be forgotten with scope=session.", { ok: false, reason: "scope_mismatch" });
373
400
  if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
374
401
  const result = sessionMemory.forget(ctx, params.id);
375
402
  return result.ok