@aeondave/pi-persona-mind 0.9.2 → 0.9.4

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,427 +1,466 @@
1
- /**
2
- * The `memory` tool — the agent-facing surface for durable knowledge.
3
- *
4
- * remember: store a fact, long-term (durable persona identity) or short-term (decaying project
5
- * note). recall: keyword + recency search. forget: delete by id. All content is declarative and
6
- * scanned before it is persisted (the service enforces both). Thin glue: it translates tool
7
- * parameters into MindService calls and formats the result the model sees.
8
- */
9
-
10
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
- import { Type } from "typebox";
12
-
13
- import { renderExpandableResult, toolResultText } from "../ui/presentation.ts";
14
-
15
- import {
16
- clampRecallMax,
17
- compactMemoryText,
18
- isMemoryId,
19
- MEMORY_KINDS,
20
- MAX_MEMORY_DERIVED_IDS,
21
- MAX_MEMORY_ID_CHARS,
22
- MAX_MEMORY_SOURCE_CHARS,
23
- MAX_MEMORY_TAGS,
24
- MAX_MEMORY_TAG_CHARS,
25
- MAX_MEMORY_TEXT_CHARS,
26
- MAX_RECALL_QUERY_CHARS,
27
- } from "../core/memory.ts";
28
- import type { MindService, RememberInput } from "../core/service.ts";
29
- import type { SessionMemory } from "../session-memory.ts";
30
- import type { MemoryOptimizer } from "../core/optimize-service.ts";
31
- import { isOptimizeOperation, MAX_OPTIMIZE_TOTAL_SOURCES, runOptimizeAction } from "./memory-optimize.ts";
32
- import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS } from "../core/optimize.ts";
33
- import { DEFAULT_STORE_MAX_ENTRIES } from "../core/store.ts";
34
- import { runMindActivity } from "../extension/activity.ts";
35
- import type { MindActivityRunner } from "../extension/activity.ts";
36
-
37
- export type GetMind = (ctx: ExtensionContext) => MindService;
38
-
39
- const MemoryParams = Type.Object({
40
- action: Type.Union([Type.Literal("remember"), Type.Literal("recall"), Type.Literal("read"), Type.Literal("forget"), Type.Literal("promote"), Type.Literal("optimize")], {
41
- description: "remember = store · recall = search · read = retrieve full text · forget = delete/tombstone by id · promote = graduate short-term · optimize = inspect, stage, or explicitly apply a consolidation",
42
- }),
43
- term: Type.Optional(
44
- Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("session")], {
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
- }),
47
- ),
48
- kind: Type.Optional(
49
- Type.Union(
50
- MEMORY_KINDS.map((k) => Type.Literal(k)),
51
- { description: "remember: content category only; kind never promotes a short or session lifetime. Required for remember." },
52
- ),
53
- ),
54
- text: Type.Optional(
55
- Type.String({
56
- maxLength: MAX_MEMORY_TEXT_CHARS,
57
- description:
58
- "remember: the fact, DECLARATIVE not imperative ('the user prefers verbose recon', never 'always be verbose'). Do not store secrets or anything re-derivable from the repo. Required for remember.",
59
- }),
60
- ),
61
- tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optional tags to aid later recall" })),
62
- ttlHours: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "remember(short): hours until it is deleted from the store (default 48)" })),
63
- supersedes: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "remember: id of an existing entry this one replaces" })),
64
- source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS, description: "remember: optional human-citable origin of this fact (e.g. 'the user said', 'child scout')" })),
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
- query: Type.Optional(Type.String({ maxLength: MAX_RECALL_QUERY_CHARS, description: "recall: keywords (empty = most recent); optimize inspect: optional substring filter" })),
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(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
- ),
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
- 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)` })),
72
- id: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "read/forget/promote: exact entry id; session:<UUID> addresses an active-session note" })),
73
- mode: Type.Optional(Type.Union([Type.Literal("inspect"), Type.Literal("stage"), Type.Literal("apply"), Type.Literal("history"), Type.Literal("undo")], { description: "optimize: inspect candidates; stage an immutable proposal; apply a plan; history retrieves bounded durable before/after receipts; undo safely restores a receipt's unchanged affected facts (default inspect)" })),
74
- target: Type.Optional(Type.Union([Type.Literal("project"), Type.Literal("project-long"), Type.Literal("persona"), Type.Literal("shared")], { description: "optimize: project = working memory, project-long = durable repository knowledge, persona/shared = durable identity/common facts" })),
75
- fingerprint: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "optimize stage: exact fingerprint from the corresponding inspection" })),
76
- operations: Type.Optional(Type.Array(Type.Object({
77
- sourceIds: Type.Array(Type.String({ maxLength: MAX_MEMORY_ID_CHARS }), { minItems: 1, maxItems: 16 }),
78
- kind: Type.Union(MEMORY_KINDS.map((kind) => Type.Literal(kind))),
79
- text: Type.String({ minLength: 1, maxLength: MAX_MEMORY_TEXT_CHARS }),
80
- tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optimize stage: omitted tags inherit the normalized union from selected sources; an explicit empty array clears them" })),
81
- source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS })),
82
- }, { additionalProperties: false }), { maxItems: 8, description: "optimize stage: explicit replacements; source IDs must be disjoint and total no more than 64" })),
83
- planId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "optimize apply: exact unexpired staged plan id" })),
84
- receiptId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "optimize undo: exact retained durable receipt id; also supply target" })),
85
- }, { additionalProperties: false });
86
-
87
- type MemoryToolParams = Type.Static<typeof MemoryParams>;
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
-
97
- /** How many colliding facts an ambiguity refusal names before it summarizes the rest. */
98
- const MAX_AMBIGUITY_CANDIDATES_SHOWN = 5;
99
-
100
- interface ToolResult {
101
- content: { type: "text"; text: string }[];
102
- details: Record<string, unknown>;
103
- }
104
-
105
- function say(text: string, details: Record<string, unknown> = {}): ToolResult {
106
- return { content: [{ type: "text", text }], details };
107
- }
108
-
109
- export type GetOptimizer = (ctx: ExtensionContext) => MemoryOptimizer;
110
- export type GetMindActivity = (ctx: ExtensionContext) => MindActivityRunner | undefined;
111
-
112
- export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity): void {
113
- pi.registerTool({
114
- name: "memory",
115
- label: "Memory",
116
- promptSnippet: "memory — persist, recall, inspect, and explicitly consolidate durable facts, project context, and active-session notes",
117
- promptGuidelines: [
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.",
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.",
120
- ],
121
- description: [
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.",
125
- ].join(" "),
126
- parameters: MemoryParams,
127
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
128
- try {
129
- const invalid = validateMemoryParams(params);
130
- if (invalid) return say(invalid, { ok: false, reason: "invalid_parameters" });
131
- return await runMemoryAction(getMind(ctx), params, ctx, sessionMemory, getOptimizer, getActivity);
132
- } catch (err) {
133
- // One loud surface for every action. `remember`/`promote` already convert a store failure into
134
- // a result, but `recall`/`forget` let it throw — so a store written by a different build
135
- // (StoreVersionError) escapes as a tool crash for two actions and reads as a tidy reason for
136
- // the other two. The model reads this boundary, so it reports the same way either way.
137
- const message = err instanceof Error ? err.message : String(err);
138
- return say(`Memory is unavailable: ${message || "unknown persistence failure"}`, { ok: false, reason: "storage_error" });
139
- }
140
- },
141
- renderResult(result, { expanded }, theme, context) {
142
- const body = toolResultText(result);
143
- const details = result.details && typeof result.details === "object" ? result.details as Record<string, unknown> : undefined;
144
- // Recognize old receipts too, so reopening a session does not restore the noisy card.
145
- const savedTerm = details?.ok === true ? /^Remembered \S+ — (long|short)-term /.exec(body)?.[1] : undefined;
146
- const savedSession = details?.ok === true && details.action === "remember" && details.storage === "session";
147
- if (savedTerm || savedSession) {
148
- const summary = typeof details?.summary === "string"
149
- ? details.summary
150
- : savedSession ? "Session note saved" : `${savedTerm === "long" ? "Long" : "Short"}-term saved`;
151
- return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"), summary);
152
- }
153
- return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"));
154
- },
155
- });
156
- }
157
-
158
- const KEYS: Record<string, ReadonlySet<string>> = {
159
- remember: new Set(["action", "term", "kind", "text", "tags", "ttlHours", "supersedes", "scope", "source", "derivedFrom"]),
160
- recall: new Set(["action", "query", "scope", "max"]),
161
- read: new Set(["action", "id", "scope"]),
162
- forget: new Set(["action", "id", "scope"]),
163
- promote: new Set(["action", "id", "scope"]),
164
- optimize: new Set(["action", "mode", "target", "query", "max", "offset", "fingerprint", "operations", "planId", "receiptId"]),
165
- };
166
-
167
- /** The host validates TypeBox schemas, but execute is also callable directly by SDK clients. */
168
- function validateMemoryParams(value: unknown): string | undefined {
169
- if (!value || typeof value !== "object" || Array.isArray(value)) return "memory expects one object of action parameters.";
170
- const prototype = Object.getPrototypeOf(value);
171
- if (prototype !== Object.prototype && prototype !== null) return "memory action parameters must be a plain object.";
172
- const params = value as Record<string, unknown>;
173
- if (typeof params.action !== "string" || !Object.hasOwn(KEYS, params.action)) return "Unknown memory action.";
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
- }
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;
181
- if (params.action === "remember") {
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);
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.";
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.";
202
- if (params.source !== undefined && (typeof params.source !== "string" || params.source.length > MAX_MEMORY_SOURCE_CHARS)) return "memory source exceeds its bound.";
203
- if (params.supersedes !== undefined && !isMemoryId(params.supersedes)) return "memory supersedes must be a safe entry id.";
204
- if (params.ttlHours !== undefined && (typeof params.ttlHours !== "number" || !Number.isFinite(params.ttlHours) || params.ttlHours <= 0)) return "memory ttlHours must be a positive finite number.";
205
- return;
206
- }
207
- if (params.action === "recall") {
208
- if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory recall query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
209
- if (params.scope !== undefined && !["long", "short", "both", "session", "project", "persona", "shared"].includes(String(params.scope))) return "unknown recall scope.";
210
- if (params.max !== undefined && (typeof params.max !== "number" || !Number.isFinite(params.max))) return "memory max must be a finite number.";
211
- return;
212
- }
213
- if (params.action === "read" || params.action === "forget" || params.action === "promote") {
214
- if (!isMemoryId(params.id)) return `memory ${params.action} needs a safe exact id.`;
215
- if (params.scope !== undefined && !(params.action === "promote" ? ["project", "persona", "shared"] : ["long", "short", "both", "session", "project", "persona", "shared"]).includes(String(params.scope))) return "invalid scope for memory action.";
216
- return;
217
- }
218
- const mode = params.mode ?? "inspect";
219
- if (!["inspect", "stage", "apply", "history", "undo"].includes(String(mode))) return "memory optimize mode must be inspect, stage, apply, history, or undo.";
220
- if (params.target !== undefined && !isOptimizeTarget(params.target)) return "memory optimize target must be project, project-long, persona, or shared.";
221
- if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory optimize query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
222
- if (params.max !== undefined && (typeof params.max !== "number" || !Number.isSafeInteger(params.max) || params.max < 1 || params.max > 100)) return "memory optimize max must be an integer from 1 to 100.";
223
- if (params.offset !== undefined && (typeof params.offset !== "number" || !Number.isSafeInteger(params.offset) || params.offset < 0 || params.offset > DEFAULT_STORE_MAX_ENTRIES)) return `memory optimize offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}.`;
224
- if (mode === "history") {
225
- if (["query", "offset", "fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize history only accepts target and max.";
226
- return;
227
- }
228
- if (mode === "undo") {
229
- if (["query", "max", "offset", "fingerprint", "operations", "planId"].some(has)) return "memory optimize undo only accepts receiptId and target.";
230
- if (!str("receiptId", 1, 160) || params.target === undefined) return "memory optimize undo needs receiptId and an explicit target.";
231
- return;
232
- }
233
- if (mode === "inspect") {
234
- if (["fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize inspect only accepts target, query, max, and offset.";
235
- return;
236
- }
237
- if (mode === "stage") {
238
- if (["query", "max", "offset", "planId", "receiptId"].some(has)) return "memory optimize stage only accepts target, fingerprint, and operations.";
239
- if (!str("fingerprint", 1, 256) || !Array.isArray(params.operations) || params.operations.length < 1 || params.operations.length > MAX_OPTIMIZE_OPERATIONS || !Array.from(params.operations).every(isOptimizeOperation)) return `memory optimize stage needs a fingerprint and 1..${MAX_OPTIMIZE_OPERATIONS} bounded operations.`;
240
- const sourceCount = params.operations.reduce((sum: number, operation: { sourceIds: string[] }) => sum + operation.sourceIds.length, 0);
241
- if (sourceCount > MAX_OPTIMIZE_TOTAL_SOURCES || params.operations.length > MAX_OPTIMIZE_OPERATIONS) return `memory optimize stage allows at most ${MAX_OPTIMIZE_OPERATIONS} operations and ${MAX_OPTIMIZE_TOTAL_SOURCES} total source IDs.`;
242
- return;
243
- }
244
- if (["target", "query", "max", "offset", "fingerprint", "operations", "receiptId"].some(has)) return "memory optimize apply only accepts planId.";
245
- if (!str("planId", 1, 160)) return "memory optimize apply needs the id of a staged plan.";
246
- }
247
-
248
- async function runMemoryAction(mind: MindService, params: MemoryToolParams, ctx: ExtensionContext, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity): Promise<ToolResult> {
249
- if (params.action === "remember") {
250
- if (!params.term || !params.kind || !params.text) {
251
- return say("memory remember needs { term: long|short|session, kind, text }.", { ok: false, reason: "missing required fields" });
252
- }
253
- if (params.term === "session") {
254
- if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
255
- const result = sessionMemory.remember(ctx, { kind: params.kind, text: params.text, ...(params.source === undefined ? {} : { source: params.source }) });
256
- return result.ok
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)}` })
258
- : say(`Not stored: ${result.reason}`, { ok: false, reason: result.reason });
259
- }
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 };
263
- if (params.tags) input.tags = params.tags;
264
- if (params.ttlHours !== undefined) input.ttlHours = params.ttlHours;
265
- if (params.supersedes) input.supersedes = params.supersedes;
266
- if (params.source) input.source = params.source;
267
- if (params.derivedFrom) input.derivedFrom = params.derivedFrom;
268
- const r = await mind.remember(input);
269
- const destination = params.term === "long" ? params.scope as "project" | "persona" | "shared" : "project";
270
- return r.ok
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.`, {
272
- id: r.entry.id,
273
- ok: true,
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)}`,
278
- })
279
- : say(`Not stored: ${r.reason}`, { ok: false, reason: r.reason });
280
- }
281
-
282
- if (params.action === "recall") {
283
- const query = params.query ?? "";
284
- if (query.length > MAX_RECALL_QUERY_CHARS) {
285
- return say(`memory recall query exceeds the ${MAX_RECALL_QUERY_CHARS}-character limit.`, {
286
- ok: false,
287
- reason: "query_too_long",
288
- });
289
- }
290
- const max = clampRecallMax(params.max);
291
- if (params.scope === "session") {
292
- if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
293
- const result = sessionMemory.recall(ctx, { query, max });
294
- if (!result.ok) return say(`Session memory unavailable: ${result.reason ?? "read failed"}`, { ok: false, reason: result.reason ?? "session_read_failed" });
295
- if (result.hits.length === 0) return say(query ? "No active-session notes match the supplied query." : "There are no active-session notes.", { ok: true, storage: result.storage, count: 0, total: result.total, withheld: result.withheld, max: result.max, ids: [] });
296
- const lines = result.hits.map((note) => `- [${note.id}] (${note.kind}) ${compactMemoryText(note.text, 120)}`);
297
- return say(`${result.hits.length} session note(s)${result.withheld ? ` of ${result.total}` : ""}:\n${lines.join("\n")}${result.withheld ? `\n… +${result.withheld} more; narrow the query or raise max.` : ""}`, { ok: true, storage: result.storage, count: result.hits.length, total: result.total, withheld: result.withheld, max: result.max, ids: result.hits.map((note) => note.id) });
298
- }
299
- const nativeScope = params.scope ?? "both";
300
- const { hits, total, withheldUnsafe } = await mind.recall(query, nativeScope, max);
301
- if (hits.length === 0) return say(query ? "No memory matches the supplied query." : "Your memory is empty.", { count: 0, ok: true });
302
- const withheld = total - hits.length;
303
- const more = [
304
- withheld > 0 ? `… +${withheld} more match(es) — narrow the query or raise max.` : "",
305
- withheldUnsafe > 0 ? `⚠ ${withheldUnsafe} stored entr${withheldUnsafe === 1 ? "y was" : "ies were"} withheld as unsafe.` : "",
306
- ]
307
- .filter(Boolean)
308
- .join("\n");
309
- const lines = hits.map((e) => `- [${e.id}] (${e.kind}) ${compactMemoryText(e.text, 80)}`);
310
- return say(`${hits.length} recalled${withheld > 0 ? ` of ${total}` : ""}:\n${lines.join("\n")}${more ? `\n${more}` : ""}`, {
311
- count: hits.length,
312
- total,
313
- max,
314
- withheld,
315
- withheldUnsafe,
316
- ids: hits.map((e) => e.id),
317
- });
318
- }
319
-
320
- if (params.action === "read") {
321
- if (!params.id) return say("memory read needs { id } (see recall).", { ok: false, reason: "missing id" });
322
- if (params.id.startsWith("session:")) {
323
- if (params.scope !== undefined && params.scope !== "session") return say("A session note id can only be read with scope=session.", { ok: false, reason: "scope_mismatch" });
324
- if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
325
- const result = sessionMemory.read(ctx, params.id);
326
- if (!result.ok) return say(`Session note not found: ${result.reason}`, { ok: false, reason: result.reason });
327
- return say(`${result.entry.id} (${result.entry.kind}) · active session\nrecorded: ${result.entry.recordedAt}\norigin session: ${result.entry.originSessionId} (provenance only; not auto-resolved or imported)${result.entry.source ? `\nsource: ${result.entry.source}` : ""}\n\n${result.entry.text}`, { ok: true, storage: result.storage, entry: result.entry });
328
- }
329
- if (params.scope === "session") return say("scope=session requires a session:<UUID> note id.", { ok: false, reason: "scope_mismatch" });
330
- const nativeScope = params.scope ?? "both";
331
- const result = await mind.readMemory(params.id, nativeScope);
332
- if (!result.ok) return say(`Memory read refused: ${result.reason}`, { ok: false, reason: result.reason });
333
- const lines = result.entries.map(({ entry, target }) => `${entry.id} (${target}/${entry.kind})\nrecorded: ${entry.recordedAt} · last seen: ${entry.lastSeenAt}${entry.expiresAt ? ` · expires: ${entry.expiresAt}` : ""}${entry.source ? `\nsource: ${entry.source}` : ""}${entry.derivedFrom?.length ? `\nderived from: ${entry.derivedFrom.join(", ")}` : ""}${entry.tags.length ? `\ntags: ${entry.tags.join(", ")}` : ""}\n\n${entry.text}`);
334
- const suffix = result.withheld ? `\n\n${result.withheld} identical-scope copy/copies omitted.` : "";
335
- return say(`${lines.join("\n\n---\n\n")}${suffix}`, { ok: true, total: result.total, withheld: result.withheld, entries: result.entries });
336
- }
337
-
338
- if (params.action === "optimize") {
339
- if (!getOptimizer) return say("Memory optimization is unavailable.", { ok: false, reason: "optimizer_unavailable" });
340
- const ownerCurrent = sessionMemory?.captureOwner(ctx);
341
- if (ownerCurrent && !ownerCurrent()) return say("The active session owner is unavailable; no optimization ran.", { ok: false, reason: "owner_unavailable" });
342
- const optimizer = getOptimizer(ctx);
343
- const input = {
344
- mode: params.mode ?? "inspect",
345
- ...(params.target === undefined ? {} : { target: params.target }),
346
- ...(params.query === undefined ? {} : { query: params.query }),
347
- ...(params.max === undefined ? {} : { max: params.max }),
348
- ...(params.offset === undefined ? {} : { offset: params.offset }),
349
- ...(params.fingerprint === undefined ? {} : { fingerprint: params.fingerprint }),
350
- ...(params.operations === undefined ? {} : { operations: params.operations }),
351
- ...(params.planId === undefined ? {} : { planId: params.planId }),
352
- ...(params.receiptId === undefined ? {} : { receiptId: params.receiptId }),
353
- } as const;
354
- const phase = input.mode === "history" ? "inspect" : input.mode === "undo" ? "apply" : input.mode;
355
- let target = input.target ?? "project";
356
- let hasTarget = true;
357
- if (input.mode === "apply") {
358
- const plan = input.planId ? optimizer.getPlan(input.planId) : undefined;
359
- if (plan?.ok) target = plan.target;
360
- else hasTarget = false;
361
- }
362
- const operation = () => runOptimizeAction(optimizer, input);
363
- const result = hasTarget
364
- ? await runMindActivity(getActivity?.(ctx), phase, target, operation, (outcome) => outcome.details.ok === true)
365
- : await operation();
366
- let current = false;
367
- try { current = (!ownerCurrent || ownerCurrent()) && (!sessionMemory || sessionMemory.isCurrent(ctx)) && getOptimizer(ctx) === optimizer; }
368
- catch { current = false; }
369
- if (!current) {
370
- if (params.mode === "undo" && result.details.ok === true) return say("Memory undo completed before the active owner changed. Inspect the target memory before further edits.", { ok: true, outcome: "undone_before_owner_change", receiptId: result.details.receiptId });
371
- if (params.mode === "undo") return say("The active owner changed while undo was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
372
- if (params.mode === "apply" && result.details.ok === true) return say("The staged memory plan was applied before the active owner changed. Inspect the target memory before any further edits.", { ok: true, outcome: "applied_before_owner_change", planId: result.details.planId });
373
- if (params.mode === "apply") return say("The active owner changed while apply was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
374
- return say("The active memory owner changed while this read-only or staging operation was running; no stale result or plan was returned.", { ok: false, reason: "owner_changed" });
375
- }
376
- return result;
377
- }
378
-
379
- if (params.action === "promote") {
380
- if (!params.id) return say("memory promote needs { id } (a short-term memory to make durable).", { ok: false, reason: "missing id" });
381
- const target = params.scope === "persona" || params.scope === "shared" ? params.scope : "project";
382
- const r = await mind.promote(params.id, target);
383
- if (!r.ok) return say(r.reason ? `Not promoted: ${r.reason}` : `No live short-term memory with id "${params.id}".`, { ok: false, ...(r.reason ? { reason: r.reason } : {}) });
384
- // The graduation stands, but the lineage handle it carried over may be one of the shared v1 ids the
385
- // store refuses to act on — say so, or a bare "Promoted" reads as "and the old fact is retired".
386
- const skipped = r.ambiguousSupersedes
387
- ? ` Its supersedes id ${r.ambiguousSupersedes} is shared by several stored memories, so nothing was retired — recall them and retire the one you meant by its own id.`
388
- : "";
389
- return say(`Promoted ${params.id} to durable ${target} memory — it will no longer decay.${skipped}`, {
390
- ok: true,
391
- id: params.id,
392
- ...(r.ambiguousSupersedes ? { ambiguousSupersedes: r.ambiguousSupersedes } : {}),
393
- });
394
- }
395
-
396
- // forget
397
- if (!params.id) return say("memory forget needs { id } (see recall).", { ok: false, reason: "missing id" });
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" });
400
- if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
401
- const result = sessionMemory.forget(ctx, params.id);
402
- return result.ok
403
- ? say(`Forgot active-session note ${params.id}. The transcript history remains; the note is tombstoned on this branch.`, { ok: true, storage: result.storage, removed: result.removed })
404
- : say(`Session note not forgotten: ${result.reason}`, { ok: false, reason: result.reason });
405
- }
406
- if (params.scope === "session") return say("scope=session requires a session note id.", { ok: false });
407
- const { removed, reason, candidates } = await mind.forget(params.id, params.scope ?? "both");
408
- if (removed > 0) return say(`Forgot ${params.id}.`, { ok: true, removed });
409
- if (reason !== "ambiguous_id") return say(`No memory with id "${params.id}".`, { ok: false, removed: 0, reason: "not_found" });
410
- // A refusal the caller cannot act on leaves a store nobody can ever repair, so name each colliding
411
- // fact by an id of its own. The one still holding the shared handle becomes addressable once the
412
- // others are gone — the collision shrinks by one with every delete.
413
- const shown = (candidates ?? []).slice(0, MAX_AMBIGUITY_CANDIDATES_SHOWN);
414
- const rest = (candidates?.length ?? 0) - shown.length;
415
- const lines = shown.map((c) => `- [${c.id}] (${c.kind}) ${compactMemoryText(c.text, 120)}${c.resolves ? "" : " — still the shared handle; forget the others first"}`);
416
- return say(
417
- [
418
- `Memory id "${params.id}" is a legacy handle shared by ${candidates?.length ?? 0} distinct memories, so nothing was deleted.`,
419
- "Forget the one you meant by its own current id:",
420
- ...lines,
421
- rest > 0 ? `… +${rest} more share that handle.` : "",
422
- ]
423
- .filter(Boolean)
424
- .join("\n"),
425
- { ok: false, removed: 0, reason, candidates: shown.map((c) => ({ id: c.id, kind: c.kind, resolves: c.resolves })) },
426
- );
427
- }
1
+ /**
2
+ * The `memory` tool — the agent-facing surface for durable knowledge.
3
+ *
4
+ * remember: store a fact, long-term (durable persona identity) or short-term (decaying project
5
+ * note). recall: keyword + recency search. forget: delete by id. All content is declarative and
6
+ * scanned before it is persisted (the service enforces both). Thin glue: it translates tool
7
+ * parameters into MindService calls and formats the result the model sees.
8
+ */
9
+
10
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import { Type } from "typebox";
12
+
13
+ import { renderExpandableResult, toolResultText } from "../ui/presentation.ts";
14
+
15
+ import {
16
+ clampRecallMax,
17
+ compactMemoryText,
18
+ isMemoryId,
19
+ MEMORY_KINDS,
20
+ MAX_MEMORY_DERIVED_IDS,
21
+ MAX_MEMORY_ID_CHARS,
22
+ MAX_MEMORY_SOURCE_CHARS,
23
+ MAX_MEMORY_TAGS,
24
+ MAX_MEMORY_TAG_CHARS,
25
+ MAX_MEMORY_TEXT_CHARS,
26
+ MAX_RECALL_QUERY_CHARS,
27
+ } from "../core/memory.ts";
28
+ import type { MindService, RememberInput } from "../core/service.ts";
29
+ import type { SessionMemory } from "../session-memory.ts";
30
+ import type { MemoryOptimizer } from "../core/optimize-service.ts";
31
+ import { isOptimizeOperation, MAX_OPTIMIZE_TOTAL_SOURCES, runOptimizeAction } from "./memory-optimize.ts";
32
+ import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS } from "../core/optimize.ts";
33
+ import { DEFAULT_STORE_MAX_ENTRIES } from "../core/store.ts";
34
+ import { runMindActivity } from "../extension/activity.ts";
35
+ import type { MindActivityRunner } from "../extension/activity.ts";
36
+ import type { HandoffInput } from "../core/handoff.ts";
37
+ import type { HandoffResult } from "../core/handoff-store.ts";
38
+ import { formatHandoffResult, validateHandoffInput } from "./memory-handoff.ts";
39
+ import { MAX_MEMORY_HISTORY_TEXT_CHARS, runMemoryHistory } from "./memory-history.ts";
40
+
41
+ export type GetMind = (ctx: ExtensionContext) => MindService;
42
+
43
+ const MemoryParams = Type.Object({
44
+ action: Type.Union([Type.Literal("remember"), Type.Literal("recall"), Type.Literal("read"), Type.Literal("forget"), Type.Literal("promote"), Type.Literal("optimize"), Type.Literal("handoff"), Type.Literal("history")], {
45
+ description: "remember = store · recall = search · read = retrieve full text · forget = delete/tombstone by id · promote = graduate short-term · optimize = inspect, stage, or explicitly apply a consolidation · history = discover/read change receipts · handoff = explicit cross-session work snapshot",
46
+ }),
47
+ handoff: Type.Optional(Type.Union([
48
+ Type.Object({ operation: Type.Literal("save"), goal: Type.String({ minLength: 1, maxLength: 4096 }), completed: Type.Array(Type.String({ minLength: 1, maxLength: 2048 }), { maxItems: 32 }), pending: Type.Array(Type.String({ minLength: 1, maxLength: 2048 }), { maxItems: 32 }), nextStep: Type.String({ minLength: 1, maxLength: 4096 }), references: Type.Array(Type.String({ minLength: 1, maxLength: 2048 }), { maxItems: 32 }) }, { additionalProperties: false }),
49
+ Type.Object({ operation: Type.Literal("list") }, { additionalProperties: false }),
50
+ Type.Object({ operation: Type.Literal("read"), id: Type.String({ pattern: "^[a-f0-9]{32}$" }) }, { additionalProperties: false }),
51
+ Type.Object({ operation: Type.Literal("complete"), id: Type.String({ pattern: "^[a-f0-9]{32}$" }), revision: Type.Integer({ minimum: 1 }), resolution: Type.String({ minLength: 1, maxLength: 4096 }) }, { additionalProperties: false }),
52
+ Type.Object({ operation: Type.Literal("forget"), id: Type.String({ pattern: "^[a-f0-9]{32}$" }), revision: Type.Integer({ minimum: 1 }) }, { additionalProperties: false }),
53
+ ])),
54
+ term: Type.Optional(
55
+ Type.Union([Type.Literal("long"), Type.Literal("short"), Type.Literal("session")], {
56
+ 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.",
57
+ }),
58
+ ),
59
+ kind: Type.Optional(
60
+ Type.Union(
61
+ MEMORY_KINDS.map((k) => Type.Literal(k)),
62
+ { description: "remember: content category only; kind never promotes a short or session lifetime. Required for remember." },
63
+ ),
64
+ ),
65
+ text: Type.Optional(
66
+ Type.String({
67
+ maxLength: MAX_MEMORY_TEXT_CHARS,
68
+ description:
69
+ "remember: the fact, DECLARATIVE not imperative ('the user prefers verbose recon', never 'always be verbose'). Do not store secrets or anything re-derivable from the repo. Required for remember.",
70
+ }),
71
+ ),
72
+ tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optional tags to aid later recall" })),
73
+ ttlHours: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "remember(short): hours until it is deleted from the store (default 48)" })),
74
+ supersedes: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "remember: id of an entry this one replaces within the destination scope and lifetime; an id found only in another tier is refused" })),
75
+ source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS, description: "remember: optional human-citable origin of this fact (e.g. 'the user said', 'child scout')" })),
76
+ 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" })),
77
+ query: Type.Optional(Type.String({ maxLength: MAX_RECALL_QUERY_CHARS, description: "recall: keywords (empty = most recent); optimize inspect: optional substring filter" })),
78
+ scope: Type.Optional(
79
+ 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." }),
80
+ ),
81
+ max: Type.Optional(Type.Number({ description: "recall: maximum results, clamped to 1..50 (default 8); optimize inspect: entry page 1..100 (default 20)" })),
82
+ offset: Type.Optional(Type.Number({ minimum: 0, maximum: MAX_MEMORY_HISTORY_TEXT_CHARS, multipleOf: 1, description: `optimize inspect: entry offset 0..${DEFAULT_STORE_MAX_ENTRIES}; history detail: character offset from the previous page` })),
83
+ id: Type.Optional(Type.String({ maxLength: MAX_MEMORY_ID_CHARS, description: "read/forget/promote: exact entry id; session:<UUID> addresses an active-session note" })),
84
+ mode: Type.Optional(Type.Union([Type.Literal("inspect"), Type.Literal("stage"), Type.Literal("apply"), Type.Literal("history"), Type.Literal("undo")], { description: "optimize: inspect candidates; stage an immutable proposal; apply a plan; history retrieves bounded durable before/after receipts; undo safely restores a receipt's unchanged affected facts (default inspect)" })),
85
+ target: Type.Optional(Type.Union([Type.Literal("project"), Type.Literal("project-long"), Type.Literal("persona"), Type.Literal("shared")], { description: "optimize: project = working memory, project-long = durable repository knowledge, persona/shared = durable identity/common facts" })),
86
+ fingerprint: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "optimize stage: exact fingerprint from the corresponding inspection" })),
87
+ operations: Type.Optional(Type.Array(Type.Object({
88
+ sourceIds: Type.Array(Type.String({ maxLength: MAX_MEMORY_ID_CHARS }), { minItems: 1, maxItems: 16 }),
89
+ kind: Type.Union(MEMORY_KINDS.map((kind) => Type.Literal(kind))),
90
+ text: Type.String({ minLength: 1, maxLength: MAX_MEMORY_TEXT_CHARS }),
91
+ tags: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MEMORY_TAG_CHARS }), { maxItems: MAX_MEMORY_TAGS, description: "optimize stage: omitted tags inherit the normalized union from selected sources; an explicit empty array clears them" })),
92
+ source: Type.Optional(Type.String({ maxLength: MAX_MEMORY_SOURCE_CHARS })),
93
+ }, { additionalProperties: false }), { maxItems: 8, description: "optimize stage: explicit replacements; source IDs must be disjoint and total no more than 64" })),
94
+ planId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "optimize apply: exact unexpired staged plan id" })),
95
+ receiptId: Type.Optional(Type.String({ minLength: 1, maxLength: 160, description: "history detail or optimize undo: exact retained receipt id; also supply target" })),
96
+ }, { additionalProperties: false });
97
+
98
+ type MemoryToolParams = Type.Static<typeof MemoryParams>;
99
+
100
+ const SESSION_REMEMBER_EXAMPLE = '{ action: "remember", term: "session", kind: "note", text: "Keep this branch focused." }';
101
+ const SHORT_REMEMBER_EXAMPLE = '{ action: "remember", term: "short", kind: "note", text: "The staging environment is read-only today." }';
102
+ const LONG_REMEMBER_EXAMPLE = '{ action: "remember", term: "long", scope: "project", kind: "invariant", text: "This repository requires strict typechecks." }';
103
+
104
+ function rememberCorrection(message: string, example: string): string {
105
+ return `${message} Retry with a complete remember action, for example: ${example}`;
106
+ }
107
+
108
+ /** How many colliding facts an ambiguity refusal names before it summarizes the rest. */
109
+ const MAX_AMBIGUITY_CANDIDATES_SHOWN = 5;
110
+
111
+ interface ToolResult {
112
+ content: { type: "text"; text: string }[];
113
+ details: Record<string, unknown>;
114
+ }
115
+
116
+ function say(text: string, details: Record<string, unknown> = {}): ToolResult {
117
+ return { content: [{ type: "text", text }], details };
118
+ }
119
+
120
+ export type GetOptimizer = (ctx: ExtensionContext) => MemoryOptimizer;
121
+ export type GetMindActivity = (ctx: ExtensionContext) => MindActivityRunner | undefined;
122
+ export type RunHandoff = (ctx: ExtensionContext, input: HandoffInput) => Promise<HandoffResult>;
123
+
124
+ export function registerMemoryTool(pi: ExtensionAPI, getMind: GetMind, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity, handoff?: RunHandoff): void {
125
+ pi.registerTool({
126
+ name: "memory",
127
+ label: "Memory",
128
+ promptSnippet: "memory — persist, recall, inspect, and explicitly consolidate durable facts, project context, and active-session notes",
129
+ promptGuidelines: [
130
+ "For a deliberate cross-session project task handoff, use memory action=handoff with operation save/list/read/complete/forget. Handoffs are explicit, bounded snapshots, may be stale and are never injected automatically. Complete requires an explicit resolution; retained pending items are historical.",
131
+ "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.",
132
+ "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.",
133
+ ],
134
+ description: [
135
+ "`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.",
136
+ "Stored facts remain available through recall/read; relevant facts are ranked for bounded context each turn. `history` lists compact change receipts; use receiptId plus an explicit target for before/after detail, and the returned nextOffset for later pages. Historical facts are not active memory.",
137
+ "Keep entries DECLARATIVE, never store secrets.",
138
+ ].join(" "),
139
+ parameters: MemoryParams,
140
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
141
+ try {
142
+ const invalid = validateMemoryParams(params);
143
+ if (invalid) return say(invalid, { ok: false, reason: "invalid_parameters" });
144
+ if (params.action === "handoff") {
145
+ if (!handoff || !params.handoff) return say("Handoff unavailable in this session.", { ok: false });
146
+ const result = await handoff(ctx, params.handoff);
147
+ return say(formatHandoffResult(result), { ok: result.ok, action: "handoff" });
148
+ }
149
+ if (params.action === "history") {
150
+ if (!getOptimizer || !sessionMemory) return say("Memory history is unavailable.", { ok: false });
151
+ const ownerCurrent = sessionMemory.captureOwner(ctx);
152
+ if (!ownerCurrent()) return say("Memory owner unavailable.", { ok: false });
153
+ const optimizer = getOptimizer(ctx);
154
+ const result = await runMemoryHistory(optimizer, { ...(params.target === undefined ? {} : { target: params.target }), ...(params.max === undefined ? {} : { max: params.max }), ...(params.receiptId === undefined ? {} : { receiptId: params.receiptId }), ...(params.offset === undefined ? {} : { offset: params.offset }) });
155
+ if (!ownerCurrent() || getOptimizer(ctx) !== optimizer) return say("Memory owner changed; history was withheld.", { ok: false });
156
+ return result;
157
+ }
158
+ return await runMemoryAction(getMind(ctx), params, ctx, sessionMemory, getOptimizer, getActivity);
159
+ } catch (err) {
160
+ // One loud surface for every action. `remember`/`promote` already convert a store failure into
161
+ // a result, but `recall`/`forget` let it throw — so a store written by a different build
162
+ // (StoreVersionError) escapes as a tool crash for two actions and reads as a tidy reason for
163
+ // the other two. The model reads this boundary, so it reports the same way either way.
164
+ const message = err instanceof Error ? err.message : String(err);
165
+ return say(`Memory is unavailable: ${message || "unknown persistence failure"}`, { ok: false, reason: "storage_error" });
166
+ }
167
+ },
168
+ renderResult(result, { expanded }, theme, context) {
169
+ const body = toolResultText(result);
170
+ const details = result.details && typeof result.details === "object" ? result.details as Record<string, unknown> : undefined;
171
+ // Recognize old receipts too, so reopening a session does not restore the noisy card.
172
+ const savedTerm = details?.ok === true ? /^Remembered \S+ — (long|short)-term /.exec(body)?.[1] : undefined;
173
+ const savedSession = details?.ok === true && details.action === "remember" && details.storage === "session";
174
+ if (savedTerm || savedSession) {
175
+ const summary = typeof details?.summary === "string"
176
+ ? details.summary
177
+ : savedSession ? "Session note saved" : `${savedTerm === "long" ? "Long" : "Short"}-term saved`;
178
+ return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"), summary);
179
+ }
180
+ return renderExpandableResult(body, expanded, theme, () => context.keyHint("app.tools.expand", "to expand"));
181
+ },
182
+ });
183
+ }
184
+
185
+ const KEYS: Record<string, ReadonlySet<string>> = {
186
+ remember: new Set(["action", "term", "kind", "text", "tags", "ttlHours", "supersedes", "scope", "source", "derivedFrom"]),
187
+ recall: new Set(["action", "query", "scope", "max"]),
188
+ read: new Set(["action", "id", "scope"]),
189
+ forget: new Set(["action", "id", "scope"]),
190
+ promote: new Set(["action", "id", "scope"]),
191
+ optimize: new Set(["action", "mode", "target", "query", "max", "offset", "fingerprint", "operations", "planId", "receiptId"]),
192
+ handoff: new Set(["action", "handoff"]),
193
+ history: new Set(["action", "target", "max", "receiptId", "offset"]),
194
+ };
195
+
196
+ /** The host validates TypeBox schemas, but execute is also callable directly by SDK clients. */
197
+ function validateMemoryParams(value: unknown): string | undefined {
198
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "memory expects one object of action parameters.";
199
+ const prototype = Object.getPrototypeOf(value);
200
+ if (prototype !== Object.prototype && prototype !== null) return "memory action parameters must be a plain object.";
201
+ const params = value as Record<string, unknown>;
202
+ if (typeof params.action !== "string" || !Object.hasOwn(KEYS, params.action)) return "Unknown memory action.";
203
+ const has = (key: string) => Object.hasOwn(params, key);
204
+ const unknownFields = Reflect.ownKeys(params).filter((key) => typeof key !== "string" || !KEYS[params.action as string]!.has(key)).map(String);
205
+ if (unknownFields.length > 0) {
206
+ if (params.action === "remember" && params.term === "session") return rememberCorrection(`memory remember term=session does not accept field(s): ${unknownFields.join(", ")}.`, SESSION_REMEMBER_EXAMPLE);
207
+ return `memory ${params.action} received unsupported field(s): ${unknownFields.join(", ")}.`;
208
+ }
209
+ const str = (key: string, min: number, max: number) => typeof params[key] === "string" && (params[key] as string).length >= min && (params[key] as string).length <= max;
210
+ if (params.action === "handoff") return validateHandoffInput(params.handoff) ? undefined : "memory handoff requires a valid, bounded handoff payload.";
211
+ if (params.action === "history") {
212
+ if (params.target !== undefined && !isOptimizeTarget(params.target)) return "unknown history target.";
213
+ if (params.receiptId !== undefined && (!str("receiptId", 1, 160) || params.target === undefined)) return "history detail requires receiptId and target.";
214
+ if (params.max !== undefined && (!Number.isSafeInteger(params.max) || (params.max as number) < 1 || (params.max as number) > 32 || params.receiptId !== undefined)) return "history max must be 1..32 and is only valid for list.";
215
+ if (params.offset !== undefined && (!Number.isSafeInteger(params.offset) || (params.offset as number) < 0 || (params.offset as number) > MAX_MEMORY_HISTORY_TEXT_CHARS || params.receiptId === undefined)) return `history offset requires a receiptId and must be between 0 and ${MAX_MEMORY_HISTORY_TEXT_CHARS}.`;
216
+ return;
217
+ }
218
+ if (params.action === "remember") {
219
+ 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);
220
+ const example = params.term === "long" ? LONG_REMEMBER_EXAMPLE : params.term === "short" ? SHORT_REMEMBER_EXAMPLE : SESSION_REMEMBER_EXAMPLE;
221
+ if (typeof params.kind !== "string" || !(MEMORY_KINDS as readonly string[]).includes(params.kind)) return rememberCorrection("memory remember needs a valid kind.", example);
222
+ if (!str("text", 1, MAX_MEMORY_TEXT_CHARS)) return rememberCorrection(`memory remember text must contain 1..${MAX_MEMORY_TEXT_CHARS} characters.`, example);
223
+ if (params.term === "session") {
224
+ const unsupported = ["tags", "ttlHours", "supersedes", "derivedFrom"].filter(has);
225
+ const incompatibleScope = params.scope !== undefined && params.scope !== "session";
226
+ const fields = [...unsupported, ...(incompatibleScope ? ["scope"] : [])];
227
+ 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);
228
+ 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);
229
+ return;
230
+ }
231
+ 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);
232
+ if (params.scope !== undefined && !["project", "persona", "shared"].includes(String(params.scope))) {
233
+ const required = params.term === "long" ? "long-term scope must be project, persona, or shared" : "short-term scope must be project";
234
+ return rememberCorrection(`memory remember field scope is invalid: ${required}.`, example);
235
+ }
236
+ if (params.term === "short" && params.scope !== undefined && params.scope !== "project") return rememberCorrection("short-term notes belong to project scope.", SHORT_REMEMBER_EXAMPLE);
237
+ 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.";
238
+ 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.";
239
+ if (params.source !== undefined && (typeof params.source !== "string" || params.source.length > MAX_MEMORY_SOURCE_CHARS)) return "memory source exceeds its bound.";
240
+ if (params.supersedes !== undefined && !isMemoryId(params.supersedes)) return "memory supersedes must be a safe entry id.";
241
+ if (params.ttlHours !== undefined && (typeof params.ttlHours !== "number" || !Number.isFinite(params.ttlHours) || params.ttlHours <= 0)) return "memory ttlHours must be a positive finite number.";
242
+ return;
243
+ }
244
+ if (params.action === "recall") {
245
+ if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory recall query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
246
+ if (params.scope !== undefined && !["long", "short", "both", "session", "project", "persona", "shared"].includes(String(params.scope))) return "unknown recall scope.";
247
+ if (params.max !== undefined && (typeof params.max !== "number" || !Number.isFinite(params.max))) return "memory max must be a finite number.";
248
+ return;
249
+ }
250
+ if (params.action === "read" || params.action === "forget" || params.action === "promote") {
251
+ if (!isMemoryId(params.id)) return `memory ${params.action} needs a safe exact id.`;
252
+ if (params.scope !== undefined && !(params.action === "promote" ? ["project", "persona", "shared"] : ["long", "short", "both", "session", "project", "persona", "shared"]).includes(String(params.scope))) return "invalid scope for memory action.";
253
+ return;
254
+ }
255
+ const mode = params.mode ?? "inspect";
256
+ if (!["inspect", "stage", "apply", "history", "undo"].includes(String(mode))) return "memory optimize mode must be inspect, stage, apply, history, or undo.";
257
+ if (params.target !== undefined && !isOptimizeTarget(params.target)) return "memory optimize target must be project, project-long, persona, or shared.";
258
+ if (params.query !== undefined && !str("query", 0, MAX_RECALL_QUERY_CHARS)) return `memory optimize query exceeds ${MAX_RECALL_QUERY_CHARS} characters.`;
259
+ if (params.max !== undefined && (typeof params.max !== "number" || !Number.isSafeInteger(params.max) || params.max < 1 || params.max > 100)) return "memory optimize max must be an integer from 1 to 100.";
260
+ if (params.offset !== undefined && (typeof params.offset !== "number" || !Number.isSafeInteger(params.offset) || params.offset < 0 || params.offset > DEFAULT_STORE_MAX_ENTRIES)) return `memory optimize offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}.`;
261
+ if (mode === "history") {
262
+ if (["query", "offset", "fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize history only accepts target and max.";
263
+ return;
264
+ }
265
+ if (mode === "undo") {
266
+ if (["query", "max", "offset", "fingerprint", "operations", "planId"].some(has)) return "memory optimize undo only accepts receiptId and target.";
267
+ if (!str("receiptId", 1, 160) || params.target === undefined) return "memory optimize undo needs receiptId and an explicit target.";
268
+ return;
269
+ }
270
+ if (mode === "inspect") {
271
+ if (["fingerprint", "operations", "planId", "receiptId"].some(has)) return "memory optimize inspect only accepts target, query, max, and offset.";
272
+ return;
273
+ }
274
+ if (mode === "stage") {
275
+ if (["query", "max", "offset", "planId", "receiptId"].some(has)) return "memory optimize stage only accepts target, fingerprint, and operations.";
276
+ if (!str("fingerprint", 1, 256) || !Array.isArray(params.operations) || params.operations.length < 1 || params.operations.length > MAX_OPTIMIZE_OPERATIONS || !Array.from(params.operations).every(isOptimizeOperation)) return `memory optimize stage needs a fingerprint and 1..${MAX_OPTIMIZE_OPERATIONS} bounded operations.`;
277
+ const sourceCount = params.operations.reduce((sum: number, operation: { sourceIds: string[] }) => sum + operation.sourceIds.length, 0);
278
+ if (sourceCount > MAX_OPTIMIZE_TOTAL_SOURCES || params.operations.length > MAX_OPTIMIZE_OPERATIONS) return `memory optimize stage allows at most ${MAX_OPTIMIZE_OPERATIONS} operations and ${MAX_OPTIMIZE_TOTAL_SOURCES} total source IDs.`;
279
+ return;
280
+ }
281
+ if (["target", "query", "max", "offset", "fingerprint", "operations", "receiptId"].some(has)) return "memory optimize apply only accepts planId.";
282
+ if (!str("planId", 1, 160)) return "memory optimize apply needs the id of a staged plan.";
283
+ }
284
+
285
+ async function runMemoryAction(mind: MindService, params: MemoryToolParams, ctx: ExtensionContext, sessionMemory?: SessionMemory, getOptimizer?: GetOptimizer, getActivity?: GetMindActivity): Promise<ToolResult> {
286
+ if (params.action === "remember") {
287
+ if (!params.term || !params.kind || !params.text) {
288
+ return say("memory remember needs { term: long|short|session, kind, text }.", { ok: false, reason: "missing required fields" });
289
+ }
290
+ if (params.term === "session") {
291
+ if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
292
+ const result = sessionMemory.remember(ctx, { kind: params.kind, text: params.text, ...(params.source === undefined ? {} : { source: params.source }) });
293
+ return result.ok
294
+ ? 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)}` })
295
+ : say(`Not stored: ${result.reason}`, { ok: false, reason: result.reason });
296
+ }
297
+ const input: RememberInput = params.term === "long"
298
+ ? { term: "long", scope: params.scope as "project" | "persona" | "shared", kind: params.kind, text: params.text }
299
+ : { term: "short", ...(params.scope === "project" ? { scope: "project" as const } : {}), kind: params.kind, text: params.text };
300
+ if (params.tags) input.tags = params.tags;
301
+ if (params.ttlHours !== undefined) input.ttlHours = params.ttlHours;
302
+ if (params.supersedes) input.supersedes = params.supersedes;
303
+ if (params.source) input.source = params.source;
304
+ if (params.derivedFrom) input.derivedFrom = params.derivedFrom;
305
+ const r = await mind.remember(input);
306
+ const destination = params.term === "long" ? params.scope as "project" | "persona" | "shared" : "project";
307
+ return r.ok
308
+ ? 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.${r.receiptId ? ` Replacement receipt: ${r.receiptId}.` : ""}${r.warning ? ` Warning: ${r.warning}` : ""}`, {
309
+ id: r.entry.id,
310
+ ok: true,
311
+ ...(r.receiptId ? { receiptId: r.receiptId } : {}),
312
+ ...(r.warning ? { warning: r.warning } : {}),
313
+ scope: destination,
314
+ // Native receipt metadata, not model-supplied source authority or a new archive.
315
+ recording: { version: 1, persona: mind.inspectionScope().persona, projectRoot: mind.inspectionScope().projectRoot, target: params.term === "short" ? "project" : destination === "project" ? "project-long" : destination },
316
+ summary: `${destination} · ${r.entry.expiresAt ? "working" : "durable"} saved${r.warning ? " · history warning; expand for details" : ` — ${compactMemoryText(r.entry.text, 80)}`}`,
317
+ })
318
+ : say(`Not stored: ${r.reason}`, { ok: false, reason: r.reason });
319
+ }
320
+
321
+ if (params.action === "recall") {
322
+ const query = params.query ?? "";
323
+ if (query.length > MAX_RECALL_QUERY_CHARS) {
324
+ return say(`memory recall query exceeds the ${MAX_RECALL_QUERY_CHARS}-character limit.`, {
325
+ ok: false,
326
+ reason: "query_too_long",
327
+ });
328
+ }
329
+ const max = clampRecallMax(params.max);
330
+ if (params.scope === "session") {
331
+ if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
332
+ const result = sessionMemory.recall(ctx, { query, max });
333
+ if (!result.ok) return say(`Session memory unavailable: ${result.reason ?? "read failed"}`, { ok: false, reason: result.reason ?? "session_read_failed" });
334
+ if (result.hits.length === 0) return say(query ? "No active-session notes match the supplied query." : "There are no active-session notes.", { ok: true, storage: result.storage, count: 0, total: result.total, withheld: result.withheld, max: result.max, ids: [] });
335
+ const lines = result.hits.map((note) => `- [${note.id}] (${note.kind}) ${compactMemoryText(note.text, 120)}`);
336
+ return say(`${result.hits.length} session note(s)${result.withheld ? ` of ${result.total}` : ""}:\n${lines.join("\n")}${result.withheld ? `\n… +${result.withheld} more; narrow the query or raise max.` : ""}`, { ok: true, storage: result.storage, count: result.hits.length, total: result.total, withheld: result.withheld, max: result.max, ids: result.hits.map((note) => note.id) });
337
+ }
338
+ const nativeScope = params.scope ?? "both";
339
+ const { hits, total, withheldUnsafe } = await mind.recall(query, nativeScope, max);
340
+ if (hits.length === 0) return say(query ? "No memory matches the supplied query." : "Your memory is empty.", { count: 0, ok: true });
341
+ const withheld = total - hits.length;
342
+ const more = [
343
+ withheld > 0 ? `… +${withheld} more match(es) — narrow the query or raise max.` : "",
344
+ withheldUnsafe > 0 ? `⚠ ${withheldUnsafe} stored entr${withheldUnsafe === 1 ? "y was" : "ies were"} withheld as unsafe.` : "",
345
+ ]
346
+ .filter(Boolean)
347
+ .join("\n");
348
+ const lines = hits.map((e) => `- [${e.id}] (${e.kind}) ${compactMemoryText(e.text, 80)}`);
349
+ return say(`${hits.length} recalled${withheld > 0 ? ` of ${total}` : ""}:\n${lines.join("\n")}${more ? `\n${more}` : ""}`, {
350
+ count: hits.length,
351
+ total,
352
+ max,
353
+ withheld,
354
+ withheldUnsafe,
355
+ ids: hits.map((e) => e.id),
356
+ });
357
+ }
358
+
359
+ if (params.action === "read") {
360
+ if (!params.id) return say("memory read needs { id } (see recall).", { ok: false, reason: "missing id" });
361
+ if (params.id.startsWith("session:")) {
362
+ if (params.scope !== undefined && params.scope !== "session") return say("A session note id can only be read with scope=session.", { ok: false, reason: "scope_mismatch" });
363
+ if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
364
+ const result = sessionMemory.read(ctx, params.id);
365
+ if (!result.ok) return say(`Session note not found: ${result.reason}`, { ok: false, reason: result.reason });
366
+ return say(`${result.entry.id} (${result.entry.kind}) · active session\nrecorded: ${result.entry.recordedAt}\norigin session: ${result.entry.originSessionId} (provenance only; not auto-resolved or imported)${result.entry.source ? `\nsource: ${result.entry.source}` : ""}\n\n${result.entry.text}`, { ok: true, storage: result.storage, entry: result.entry });
367
+ }
368
+ if (params.scope === "session") return say("scope=session requires a session:<UUID> note id.", { ok: false, reason: "scope_mismatch" });
369
+ const nativeScope = params.scope ?? "both";
370
+ const result = await mind.readMemory(params.id, nativeScope);
371
+ if (!result.ok) return say(`Memory read refused: ${result.reason}`, { ok: false, reason: result.reason });
372
+ const lines = result.entries.map(({ entry, target }) => `${entry.id} (${target}/${entry.kind})\nrecorded: ${entry.recordedAt} · last seen: ${entry.lastSeenAt}${entry.expiresAt ? ` · expires: ${entry.expiresAt}` : ""}${entry.source ? `\nsource: ${entry.source}` : ""}${entry.derivedFrom?.length ? `\nderived from: ${entry.derivedFrom.join(", ")}` : ""}${entry.tags.length ? `\ntags: ${entry.tags.join(", ")}` : ""}\n\n${entry.text}`);
373
+ const suffix = result.withheld ? `\n\n${result.withheld} identical-scope copy/copies omitted.` : "";
374
+ return say(`${lines.join("\n\n---\n\n")}${suffix}`, { ok: true, total: result.total, withheld: result.withheld, entries: result.entries });
375
+ }
376
+
377
+ if (params.action === "optimize") {
378
+ if (!getOptimizer) return say("Memory optimization is unavailable.", { ok: false, reason: "optimizer_unavailable" });
379
+ const ownerCurrent = sessionMemory?.captureOwner(ctx);
380
+ if (ownerCurrent && !ownerCurrent()) return say("The active session owner is unavailable; no optimization ran.", { ok: false, reason: "owner_unavailable" });
381
+ const optimizer = getOptimizer(ctx);
382
+ const input = {
383
+ mode: params.mode ?? "inspect",
384
+ ...(params.target === undefined ? {} : { target: params.target }),
385
+ ...(params.query === undefined ? {} : { query: params.query }),
386
+ ...(params.max === undefined ? {} : { max: params.max }),
387
+ ...(params.offset === undefined ? {} : { offset: params.offset }),
388
+ ...(params.fingerprint === undefined ? {} : { fingerprint: params.fingerprint }),
389
+ ...(params.operations === undefined ? {} : { operations: params.operations }),
390
+ ...(params.planId === undefined ? {} : { planId: params.planId }),
391
+ ...(params.receiptId === undefined ? {} : { receiptId: params.receiptId }),
392
+ } as const;
393
+ const phase = input.mode === "history" ? "inspect" : input.mode === "undo" ? "apply" : input.mode;
394
+ let target = input.target ?? "project";
395
+ let hasTarget = true;
396
+ if (input.mode === "apply") {
397
+ const plan = input.planId ? optimizer.getPlan(input.planId) : undefined;
398
+ if (plan?.ok) target = plan.target;
399
+ else hasTarget = false;
400
+ }
401
+ const operation = () => runOptimizeAction(optimizer, input);
402
+ const result = hasTarget
403
+ ? await runMindActivity(getActivity?.(ctx), phase, target, operation, (outcome) => outcome.details.ok === true)
404
+ : await operation();
405
+ let current = false;
406
+ try { current = (!ownerCurrent || ownerCurrent()) && (!sessionMemory || sessionMemory.isCurrent(ctx)) && getOptimizer(ctx) === optimizer; }
407
+ catch { current = false; }
408
+ if (!current) {
409
+ if (params.mode === "undo" && result.details.ok === true) return say("Memory undo completed before the active owner changed. Inspect the target memory before further edits.", { ok: true, outcome: "undone_before_owner_change", receiptId: result.details.receiptId });
410
+ if (params.mode === "undo") return say("The active owner changed while undo was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
411
+ if (params.mode === "apply" && result.details.ok === true) return say("The staged memory plan was applied before the active owner changed. Inspect the target memory before any further edits.", { ok: true, outcome: "applied_before_owner_change", planId: result.details.planId });
412
+ if (params.mode === "apply") return say("The active owner changed while apply was running. Inspect the target memory before retrying; the mutation outcome may be unknown.", { ok: false, outcome: "unknown", reason: "owner_changed" });
413
+ return say("The active memory owner changed while this read-only or staging operation was running; no stale result or plan was returned.", { ok: false, reason: "owner_changed" });
414
+ }
415
+ return result;
416
+ }
417
+
418
+ if (params.action === "promote") {
419
+ if (!params.id) return say("memory promote needs { id } (a short-term memory to make durable).", { ok: false, reason: "missing id" });
420
+ const target = params.scope === "persona" || params.scope === "shared" ? params.scope : "project";
421
+ const r = await mind.promote(params.id, target);
422
+ if (!r.ok) return say(r.reason ? `Not promoted: ${r.reason}` : `No live short-term memory with id "${params.id}".`, { ok: false, ...(r.reason ? { reason: r.reason } : {}) });
423
+ // The graduation stands, but the lineage handle it carried over may be one of the shared v1 ids the
424
+ // store refuses to act on — say so, or a bare "Promoted" reads as "and the old fact is retired".
425
+ const skipped = r.ambiguousSupersedes
426
+ ? ` Its supersedes id ${r.ambiguousSupersedes} is shared by several stored memories, so nothing was retired — recall them and retire the one you meant by its own id.`
427
+ : "";
428
+ return say(`Promoted ${params.id} to durable ${target} memory — it will no longer decay.${skipped}`, {
429
+ ok: true,
430
+ id: params.id,
431
+ ...(r.ambiguousSupersedes ? { ambiguousSupersedes: r.ambiguousSupersedes } : {}),
432
+ });
433
+ }
434
+
435
+ // forget
436
+ if (!params.id) return say("memory forget needs { id } (see recall).", { ok: false, reason: "missing id" });
437
+ if (params.id.startsWith("session:")) {
438
+ 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" });
439
+ if (!sessionMemory) return say("Active-session memory is unavailable.", { ok: false, reason: "session_memory_unavailable" });
440
+ const result = sessionMemory.forget(ctx, params.id);
441
+ return result.ok
442
+ ? say(`Forgot active-session note ${params.id}. The transcript history remains; the note is tombstoned on this branch.`, { ok: true, storage: result.storage, removed: result.removed })
443
+ : say(`Session note not forgotten: ${result.reason}`, { ok: false, reason: result.reason });
444
+ }
445
+ if (params.scope === "session") return say("scope=session requires a session note id.", { ok: false });
446
+ const { removed, reason, candidates } = await mind.forget(params.id, params.scope ?? "both");
447
+ if (removed > 0) return say(`Forgot ${params.id}.`, { ok: true, removed });
448
+ if (reason !== "ambiguous_id") return say(`No memory with id "${params.id}".`, { ok: false, removed: 0, reason: "not_found" });
449
+ // A refusal the caller cannot act on leaves a store nobody can ever repair, so name each colliding
450
+ // fact by an id of its own. The one still holding the shared handle becomes addressable once the
451
+ // others are gone — the collision shrinks by one with every delete.
452
+ const shown = (candidates ?? []).slice(0, MAX_AMBIGUITY_CANDIDATES_SHOWN);
453
+ const rest = (candidates?.length ?? 0) - shown.length;
454
+ const lines = shown.map((c) => `- [${c.id}] (${c.kind}) ${compactMemoryText(c.text, 120)}${c.resolves ? "" : " — still the shared handle; forget the others first"}`);
455
+ return say(
456
+ [
457
+ `Memory id "${params.id}" is a legacy handle shared by ${candidates?.length ?? 0} distinct memories, so nothing was deleted.`,
458
+ "Forget the one you meant by its own current id:",
459
+ ...lines,
460
+ rest > 0 ? `… +${rest} more share that handle.` : "",
461
+ ]
462
+ .filter(Boolean)
463
+ .join("\n"),
464
+ { ok: false, removed: 0, reason, candidates: shown.map((c) => ({ id: c.id, kind: c.kind, resolves: c.resolves })) },
465
+ );
466
+ }