@aeondave/pi-persona-mind 0.9.6 → 0.9.8

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.
Files changed (55) hide show
  1. package/AGENTS.md +137 -135
  2. package/CHANGELOG.md +287 -270
  3. package/LICENSE +24 -24
  4. package/README.md +84 -171
  5. package/docs/DESIGN.md +605 -573
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +15 -6
  8. package/src/core/auto-optimize.ts +323 -249
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -154
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -180
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -205
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -569
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -0
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/index.ts +1357 -1310
  45. package/src/session-memory.ts +127 -122
  46. package/src/tools/backlog.ts +126 -126
  47. package/src/tools/memory-handoff.ts +30 -30
  48. package/src/tools/memory-history.ts +46 -46
  49. package/src/tools/memory.ts +6 -4
  50. package/src/ui/card-frame.ts +161 -161
  51. package/src/ui/inspector-frame.ts +44 -44
  52. package/src/ui/memory-inspector.ts +464 -464
  53. package/src/ui/mind-result-card.ts +48 -48
  54. package/src/ui/presentation.ts +87 -87
  55. package/src/ui/session-note-card.ts +58 -56
@@ -1,180 +1,189 @@
1
- /** Session-local staged plans over strict one-file memory snapshots. No model calls or hidden jobs. */
2
- import { randomUUID } from "node:crypto";
3
- import { isExpired, isSafeMemoryContent, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
4
- import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeReceiptDetail, type OptimizeUndone } from "./optimize-history.ts";
5
- import {
6
- isOptimizeTarget, MAX_OPTIMIZE_ENTRIES, MAX_OPTIMIZE_PLANS, OPTIMIZE_PLAN_TTL_MS,
7
- optimizeCandidates, planConsolidation,
8
- type OptimizeApplied, type OptimizeFailure, type OptimizeInspection, type OptimizeInspectOptions,
9
- type OptimizePlan, type OptimizePreviewInput, type OptimizeTarget,
10
- } from "./optimize.ts";
11
- import { DEFAULT_STORE_MAX_ENTRIES, type JsonStore, withFileLock } from "./store.ts";
12
-
13
- export interface MemoryOptimizerOptions {
14
- stores: Record<OptimizeTarget, JsonStore<MemoryEntry>>;
15
- persona: string;
16
- now?: () => number;
17
- /** Shares MindService's mutation ordering with promote/forget/reset. */
18
- mutationLock?: string;
19
- /** Defaults to a scope-bound sidecar beside each target store. */
20
- historyPaths?: Partial<Record<OptimizeTarget, string>>;
21
- }
22
- interface StagedPlan { plan: OptimizePlan; next: MemoryEntry[] }
23
-
24
- function failure(error: unknown): OptimizeFailure {
25
- return { ok: false, reason: error instanceof Error ? error.message : "memory optimizer storage failure" };
26
- }
27
-
28
- export class MemoryOptimizer {
29
- private readonly options: MemoryOptimizerOptions;
30
- private readonly now: () => number;
31
- private readonly plans = new Map<string, StagedPlan>();
32
- private readonly histories = new Map<OptimizeTarget, OptimizeHistoryStore>();
33
- private generation = 0;
34
- constructor(options: MemoryOptimizerOptions) {
35
- this.options = { ...options, stores: { ...options.stores } };
36
- this.now = options.now ?? Date.now;
37
- }
38
-
39
- /** Ownership/lifecycle adapters discard this instance or explicitly invalidate its plans. */
40
- invalidate(): void { this.plans.clear(); this.generation++; }
41
-
42
- async inspect(target: OptimizeTarget = "project", options: OptimizeInspectOptions = {}): Promise<OptimizeInspection | OptimizeFailure> {
43
- if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
44
- if (options.query !== undefined && (typeof options.query !== "string" || options.query.length > MAX_RECALL_QUERY_CHARS)) return { ok: false, reason: `query exceeds ${MAX_RECALL_QUERY_CHARS} characters` };
45
- const offset = options.offset ?? 0;
46
- if (!Number.isSafeInteger(offset) || offset < 0 || offset > DEFAULT_STORE_MAX_ENTRIES) return { ok: false, reason: `offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}` };
47
- try {
48
- const snapshot = await this.options.stores[target].inspectStrict();
49
- const active = snapshot.store.entries.filter((entry) => !isExpired(entry, this.now()));
50
- const query = options.query?.trim().toLowerCase();
51
- const eligible = active.filter((entry) => isSafeMemoryContent(entry) && (!query || `${entry.text} ${entry.tags.join(" ")}`.toLowerCase().includes(query)));
52
- const max = options.max === undefined || !Number.isFinite(options.max) ? 20 : Math.max(1, Math.min(MAX_OPTIMIZE_ENTRIES, Math.floor(options.max)));
53
- const entries = eligible.slice().sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt) || a.id.localeCompare(b.id)).slice(offset, offset + max);
54
- const nextOffset = offset + entries.length;
55
- return { ok: true, target, fingerprint: snapshot.fingerprint, entries, total: active.length, withheld: active.length - entries.length, candidates: optimizeCandidates(entries), offset, matched: eligible.length,
56
- ...(nextOffset < eligible.length ? { nextOffset } : {}) };
57
- } catch (error) { return failure(error); }
58
- }
59
-
60
- async preview(input: OptimizePreviewInput): Promise<OptimizePlan | OptimizeFailure> {
61
- const generation = this.generation;
62
- const target = input.target ?? "project";
63
- if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
64
- try {
65
- const snapshot = await this.options.stores[target].inspectStrict();
66
- if (this.generation !== generation) return { ok: false, reason: "memory owner changed; preview invalidated before staging" };
67
- if (snapshot.fingerprint !== input.fingerprint) return { ok: false, reason: "memory store changed since inspection; inspect again" };
68
- const now = this.now();
69
- const result = planConsolidation(snapshot.store.entries, input.operations, target, this.options.persona, now);
70
- if (!result.ok) return result;
71
- const plan: OptimizePlan = { ok: true, planId: randomUUID(), target, fingerprint: snapshot.fingerprint, expiresAt: new Date(now + OPTIMIZE_PLAN_TTL_MS).toISOString(), changes: result.changes, beforeCount: snapshot.store.entries.length, afterCount: result.entries.length };
72
- this.expirePlans();
73
- while (this.plans.size >= MAX_OPTIMIZE_PLANS) this.plans.delete(this.plans.keys().next().value!);
74
- this.plans.set(plan.planId, structuredClone({ plan, next: result.entries }));
75
- return structuredClone(plan);
76
- } catch (error) { return failure(error); }
77
- }
78
-
79
- getPlan(planId: string): OptimizePlan | OptimizeFailure {
80
- this.expirePlans();
81
- const stored = this.plans.get(planId);
82
- return stored ? structuredClone(stored.plan) : { ok: false, reason: "plan not found or expired; inspect and stage again" };
83
- }
84
-
85
- /** Parent-only synchronous evidence checks run again under the store's CAS lock. */
86
- async apply(planId: string, assertEvidenceFresh?: () => void): Promise<OptimizeApplied | OptimizeFailure> {
87
- this.expirePlans();
88
- const staged = this.plans.get(planId);
89
- if (!staged) return { ok: false, reason: "plan not found or expired; inspect and stage again" };
90
- try {
91
- let receiptId: string | undefined;
92
- let warning: string | undefined;
93
- const commit = async () => {
94
- const assertCurrent = () => {
95
- if (this.plans.get(planId) !== staged || this.now() >= Date.parse(staged.plan.expiresAt)) throw new Error("plan expired or invalidated; inspect and stage again");
96
- if (staged.plan.changes.some((change) => change.before.some((entry) => isExpired(entry, this.now())))) throw new Error("a source expired since preview; inspect and stage again");
97
- assertEvidenceFresh?.();
98
- };
99
- const store = this.options.stores[staged.plan.target];
100
- const history = this.historyStore(staged.plan.target);
101
- let receipt: OptimizeReceipt | undefined;
102
- if (staged.plan.changes.length) {
103
- receiptId = randomUUID();
104
- receipt = { receiptId, planId, origin: "optimization", target: staged.plan.target, persona: this.options.persona, createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: structuredClone(staged.plan.changes) };
105
- }
106
- const result = await history.commit(store, staged.plan.fingerprint, receipt, () => structuredClone(staged.next), assertCurrent);
107
- this.plans.delete(planId);
108
- warning = result.warning;
109
- };
110
- if (this.options.mutationLock) await withFileLock(this.options.mutationLock, commit); else await commit();
111
- return { ok: true, planId, target: staged.plan.target, changed: staged.plan.changes.length, beforeCount: staged.plan.beforeCount, afterCount: staged.plan.afterCount, ...(receiptId ? { receiptId } : {}), ...(warning ? { warning } : {}) };
112
- } catch (error) { return failure(error); }
113
- }
114
-
115
- async history(target: OptimizeTarget = "project", max = 20): Promise<OptimizeHistory | OptimizeFailure> {
116
- if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
117
- if (!Number.isFinite(max) || max < 1) return { ok: false, reason: "history max must be a positive finite number" };
118
- try {
119
- const storePath = this.options.stores[target].filePath;
120
- const all = (await this.historyStore(target).read()).filter((receipt) => receipt.target === target && receipt.storePath === storePath && receipt.persona === this.options.persona);
121
- const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(isSafeMemoryContent)));
122
- const receipts = safe.slice().reverse().slice(0, Math.min(MAX_OPTIMIZE_HISTORY, Math.floor(max)));
123
- return { ok: true, target, receipts, retained: all.length, omitted: safe.length - receipts.length, withheldUnsafe: all.length - safe.length, limit: MAX_OPTIMIZE_HISTORY, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES };
124
- } catch (error) { return failure(error); }
125
- }
126
-
127
- /** Exact, bounded read through the same owner/content filters as history; no active-store IO. */
128
- async getReceipt(receiptId: string, target: OptimizeTarget): Promise<OptimizeReceiptDetail | OptimizeFailure> {
129
- if (typeof receiptId !== "string" || !/^[\da-f-]{36}$/i.test(receiptId)) return { ok: false, reason: "invalid memory receipt id" };
130
- const history = await this.history(target, MAX_OPTIMIZE_HISTORY);
131
- if (!history.ok) return history;
132
- const receipt = history.receipts.find((entry) => entry.receiptId === receiptId);
133
- return receipt ? { ok: true, target, receipt } : { ok: false, reason: "memory receipt not found in this scope, unsafe, or no longer retained" };
134
- }
135
-
136
- async undo(receiptId: string, target?: OptimizeTarget): Promise<OptimizeUndone | OptimizeFailure> {
137
- const generation = this.generation;
138
- if (target !== undefined && !isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
139
- try {
140
- const candidates: OptimizeTarget[] = target ? [target] : ["project", "project-long", "persona", "shared"];
141
- for (const candidate of candidates) {
142
- const history = this.historyStore(candidate);
143
- const found = (await history.read()).some((receipt) => receipt.receiptId === receiptId && receipt.target === candidate && receipt.storePath === this.options.stores[candidate].filePath);
144
- if (!found) continue;
145
- const commit = async () => history.exclusive(async (): Promise<OptimizeUndone | OptimizeFailure> => {
146
- const receipt = (await history.read()).find((entry) => entry.receiptId === receiptId && entry.target === candidate && entry.storePath === this.options.stores[candidate].filePath);
147
- if (!receipt) return { ok: false, reason: "optimizer receipt is no longer retained" };
148
- const store = this.options.stores[candidate];
149
- const snapshot = await store.inspectStrict();
150
- let restored = 0;
151
- await store.compareAndUpdate(snapshot.fingerprint, (entries) => {
152
- if (this.generation !== generation) throw new Error("memory owner changed; undo invalidated before commit");
153
- const result = restoreReceipt(entries, receipt, this.options.persona, this.now());
154
- if (!result.ok) throw new Error(result.reason);
155
- restored = result.restored;
156
- return result.entries;
157
- });
158
- try { await history.settle(receiptId, "undone"); }
159
- catch { return { ok: true, receiptId, target: candidate, restored, warning: "undo committed; history finalization failed, affected-fact checks prevent duplicate undo" }; }
160
- return { ok: true, receiptId, target: candidate, restored };
161
- });
162
- return this.options.mutationLock ? await withFileLock(this.options.mutationLock, commit) : await commit();
163
- }
164
- return { ok: false, reason: "optimizer receipt not found in this scope or no longer retained" };
165
- } catch (error) { return failure(error); }
166
- }
167
-
168
- private historyStore(target: OptimizeTarget): OptimizeHistoryStore {
169
- let history = this.histories.get(target);
170
- if (!history) {
171
- history = new OptimizeHistoryStore(this.options.historyPaths?.[target] ?? `${this.options.stores[target].filePath}.optimize-history.json`, this.now);
172
- this.histories.set(target, history);
173
- }
174
- return history;
175
- }
176
-
177
- private expirePlans(): void {
178
- for (const [id, staged] of this.plans) if (this.now() >= Date.parse(staged.plan.expiresAt)) this.plans.delete(id);
179
- }
180
- }
1
+ /** Session-local staged plans over strict one-file memory snapshots. No model calls or hidden jobs. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { inspectAutoReviewPage, type AutoOptimizeTarget, type AutoReviewCursor, type AutoReviewSnapshot } from "./auto-optimize.ts";
4
+ import { isExpired, isSafeMemoryContent, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
5
+ import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeReceiptDetail, type OptimizeUndone } from "./optimize-history.ts";
6
+ import {
7
+ isOptimizeTarget, MAX_OPTIMIZE_ENTRIES, MAX_OPTIMIZE_PLANS, OPTIMIZE_PLAN_TTL_MS,
8
+ optimizeCandidates, planConsolidation,
9
+ type OptimizeApplied, type OptimizeFailure, type OptimizeInspection, type OptimizeInspectOptions,
10
+ type OptimizePlan, type OptimizePreviewInput, type OptimizeTarget,
11
+ } from "./optimize.ts";
12
+ import { DEFAULT_STORE_MAX_ENTRIES, type JsonStore, withFileLock } from "./store.ts";
13
+
14
+ export interface MemoryOptimizerOptions {
15
+ stores: Record<OptimizeTarget, JsonStore<MemoryEntry>>;
16
+ persona: string;
17
+ now?: () => number;
18
+ /** Shares MindService's mutation ordering with promote/forget/reset. */
19
+ mutationLock?: string;
20
+ /** Defaults to a scope-bound sidecar beside each target store. */
21
+ historyPaths?: Partial<Record<OptimizeTarget, string>>;
22
+ }
23
+ interface StagedPlan { plan: OptimizePlan; next: MemoryEntry[] }
24
+
25
+ function failure(error: unknown): OptimizeFailure {
26
+ return { ok: false, reason: error instanceof Error ? error.message : "memory optimizer storage failure" };
27
+ }
28
+
29
+ export class MemoryOptimizer {
30
+ private readonly options: MemoryOptimizerOptions;
31
+ private readonly now: () => number;
32
+ private readonly plans = new Map<string, StagedPlan>();
33
+ private readonly histories = new Map<OptimizeTarget, OptimizeHistoryStore>();
34
+ private generation = 0;
35
+ constructor(options: MemoryOptimizerOptions) {
36
+ this.options = { ...options, stores: { ...options.stores } };
37
+ this.now = options.now ?? Date.now;
38
+ }
39
+
40
+ /** Ownership/lifecycle adapters discard this instance or explicitly invalidate its plans. */
41
+ invalidate(): void { this.plans.clear(); this.generation++; }
42
+
43
+ async inspect(target: OptimizeTarget = "project", options: OptimizeInspectOptions = {}): Promise<OptimizeInspection | OptimizeFailure> {
44
+ if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
45
+ if (options.query !== undefined && (typeof options.query !== "string" || options.query.length > MAX_RECALL_QUERY_CHARS)) return { ok: false, reason: `query exceeds ${MAX_RECALL_QUERY_CHARS} characters` };
46
+ const offset = options.offset ?? 0;
47
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > DEFAULT_STORE_MAX_ENTRIES) return { ok: false, reason: `offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}` };
48
+ try {
49
+ const snapshot = await this.options.stores[target].inspectStrict();
50
+ const active = snapshot.store.entries.filter((entry) => !isExpired(entry, this.now()));
51
+ const query = options.query?.trim().toLowerCase();
52
+ const eligible = active.filter((entry) => isSafeMemoryContent(entry) && (!query || `${entry.text} ${entry.tags.join(" ")}`.toLowerCase().includes(query)));
53
+ const max = options.max === undefined || !Number.isFinite(options.max) ? 20 : Math.max(1, Math.min(MAX_OPTIMIZE_ENTRIES, Math.floor(options.max)));
54
+ const entries = eligible.slice().sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt) || a.id.localeCompare(b.id)).slice(offset, offset + max);
55
+ const nextOffset = offset + entries.length;
56
+ return { ok: true, target, fingerprint: snapshot.fingerprint, entries, total: active.length, withheld: active.length - entries.length, candidates: optimizeCandidates(entries), offset, matched: eligible.length,
57
+ ...(nextOffset < eligible.length ? { nextOffset } : {}) };
58
+ } catch (error) { return failure(error); }
59
+ }
60
+
61
+ /** Internal maintenance traversal with a private cursor and no mutation or recovery writes. */
62
+ async inspectReviewPage(target: AutoOptimizeTarget, cursor: AutoReviewCursor): Promise<AutoReviewSnapshot | OptimizeFailure> {
63
+ try {
64
+ const snapshot = await this.options.stores[target].inspectStrict();
65
+ return inspectAutoReviewPage(snapshot.store.entries, snapshot.fingerprint, target, this.options.persona, this.now(), cursor);
66
+ } catch (error) { return failure(error); }
67
+ }
68
+
69
+ async preview(input: OptimizePreviewInput): Promise<OptimizePlan | OptimizeFailure> {
70
+ const generation = this.generation;
71
+ const target = input.target ?? "project";
72
+ if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
73
+ try {
74
+ const snapshot = await this.options.stores[target].inspectStrict();
75
+ if (this.generation !== generation) return { ok: false, reason: "memory owner changed; preview invalidated before staging" };
76
+ if (snapshot.fingerprint !== input.fingerprint) return { ok: false, reason: "memory store changed since inspection; inspect again" };
77
+ const now = this.now();
78
+ const result = planConsolidation(snapshot.store.entries, input.operations, target, this.options.persona, now);
79
+ if (!result.ok) return result;
80
+ const plan: OptimizePlan = { ok: true, planId: randomUUID(), target, fingerprint: snapshot.fingerprint, expiresAt: new Date(now + OPTIMIZE_PLAN_TTL_MS).toISOString(), changes: result.changes, beforeCount: snapshot.store.entries.length, afterCount: result.entries.length };
81
+ this.expirePlans();
82
+ while (this.plans.size >= MAX_OPTIMIZE_PLANS) this.plans.delete(this.plans.keys().next().value!);
83
+ this.plans.set(plan.planId, structuredClone({ plan, next: result.entries }));
84
+ return structuredClone(plan);
85
+ } catch (error) { return failure(error); }
86
+ }
87
+
88
+ getPlan(planId: string): OptimizePlan | OptimizeFailure {
89
+ this.expirePlans();
90
+ const stored = this.plans.get(planId);
91
+ return stored ? structuredClone(stored.plan) : { ok: false, reason: "plan not found or expired; inspect and stage again" };
92
+ }
93
+
94
+ /** Parent-only synchronous evidence checks run again under the store's CAS lock. */
95
+ async apply(planId: string, assertEvidenceFresh?: () => void): Promise<OptimizeApplied | OptimizeFailure> {
96
+ this.expirePlans();
97
+ const staged = this.plans.get(planId);
98
+ if (!staged) return { ok: false, reason: "plan not found or expired; inspect and stage again" };
99
+ try {
100
+ let receiptId: string | undefined;
101
+ let warning: string | undefined;
102
+ const commit = async () => {
103
+ const assertCurrent = () => {
104
+ if (this.plans.get(planId) !== staged || this.now() >= Date.parse(staged.plan.expiresAt)) throw new Error("plan expired or invalidated; inspect and stage again");
105
+ if (staged.plan.changes.some((change) => change.before.some((entry) => isExpired(entry, this.now())))) throw new Error("a source expired since preview; inspect and stage again");
106
+ assertEvidenceFresh?.();
107
+ };
108
+ const store = this.options.stores[staged.plan.target];
109
+ const history = this.historyStore(staged.plan.target);
110
+ let receipt: OptimizeReceipt | undefined;
111
+ if (staged.plan.changes.length) {
112
+ receiptId = randomUUID();
113
+ receipt = { receiptId, planId, origin: "optimization", target: staged.plan.target, persona: this.options.persona, createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: structuredClone(staged.plan.changes) };
114
+ }
115
+ const result = await history.commit(store, staged.plan.fingerprint, receipt, () => structuredClone(staged.next), assertCurrent);
116
+ this.plans.delete(planId);
117
+ warning = result.warning;
118
+ };
119
+ if (this.options.mutationLock) await withFileLock(this.options.mutationLock, commit); else await commit();
120
+ return { ok: true, planId, target: staged.plan.target, changed: staged.plan.changes.length, beforeCount: staged.plan.beforeCount, afterCount: staged.plan.afterCount, ...(receiptId ? { receiptId } : {}), ...(warning ? { warning } : {}) };
121
+ } catch (error) { return failure(error); }
122
+ }
123
+
124
+ async history(target: OptimizeTarget = "project", max = 20): Promise<OptimizeHistory | OptimizeFailure> {
125
+ if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
126
+ if (!Number.isFinite(max) || max < 1) return { ok: false, reason: "history max must be a positive finite number" };
127
+ try {
128
+ const storePath = this.options.stores[target].filePath;
129
+ const all = (await this.historyStore(target).read()).filter((receipt) => receipt.target === target && receipt.storePath === storePath && receipt.persona === this.options.persona);
130
+ const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(isSafeMemoryContent)));
131
+ const receipts = safe.slice().reverse().slice(0, Math.min(MAX_OPTIMIZE_HISTORY, Math.floor(max)));
132
+ return { ok: true, target, receipts, retained: all.length, omitted: safe.length - receipts.length, withheldUnsafe: all.length - safe.length, limit: MAX_OPTIMIZE_HISTORY, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES };
133
+ } catch (error) { return failure(error); }
134
+ }
135
+
136
+ /** Exact, bounded read through the same owner/content filters as history; no active-store IO. */
137
+ async getReceipt(receiptId: string, target: OptimizeTarget): Promise<OptimizeReceiptDetail | OptimizeFailure> {
138
+ if (typeof receiptId !== "string" || !/^[\da-f-]{36}$/i.test(receiptId)) return { ok: false, reason: "invalid memory receipt id" };
139
+ const history = await this.history(target, MAX_OPTIMIZE_HISTORY);
140
+ if (!history.ok) return history;
141
+ const receipt = history.receipts.find((entry) => entry.receiptId === receiptId);
142
+ return receipt ? { ok: true, target, receipt } : { ok: false, reason: "memory receipt not found in this scope, unsafe, or no longer retained" };
143
+ }
144
+
145
+ async undo(receiptId: string, target?: OptimizeTarget): Promise<OptimizeUndone | OptimizeFailure> {
146
+ const generation = this.generation;
147
+ if (target !== undefined && !isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
148
+ try {
149
+ const candidates: OptimizeTarget[] = target ? [target] : ["project", "project-long", "persona", "shared"];
150
+ for (const candidate of candidates) {
151
+ const history = this.historyStore(candidate);
152
+ const found = (await history.read()).some((receipt) => receipt.receiptId === receiptId && receipt.target === candidate && receipt.storePath === this.options.stores[candidate].filePath);
153
+ if (!found) continue;
154
+ const commit = async () => history.exclusive(async (): Promise<OptimizeUndone | OptimizeFailure> => {
155
+ const receipt = (await history.read()).find((entry) => entry.receiptId === receiptId && entry.target === candidate && entry.storePath === this.options.stores[candidate].filePath);
156
+ if (!receipt) return { ok: false, reason: "optimizer receipt is no longer retained" };
157
+ const store = this.options.stores[candidate];
158
+ const snapshot = await store.inspectStrict();
159
+ let restored = 0;
160
+ await store.compareAndUpdate(snapshot.fingerprint, (entries) => {
161
+ if (this.generation !== generation) throw new Error("memory owner changed; undo invalidated before commit");
162
+ const result = restoreReceipt(entries, receipt, this.options.persona, this.now());
163
+ if (!result.ok) throw new Error(result.reason);
164
+ restored = result.restored;
165
+ return result.entries;
166
+ });
167
+ try { await history.settle(receiptId, "undone"); }
168
+ catch { return { ok: true, receiptId, target: candidate, restored, warning: "undo committed; history finalization failed, affected-fact checks prevent duplicate undo" }; }
169
+ return { ok: true, receiptId, target: candidate, restored };
170
+ });
171
+ return this.options.mutationLock ? await withFileLock(this.options.mutationLock, commit) : await commit();
172
+ }
173
+ return { ok: false, reason: "optimizer receipt not found in this scope or no longer retained" };
174
+ } catch (error) { return failure(error); }
175
+ }
176
+
177
+ private historyStore(target: OptimizeTarget): OptimizeHistoryStore {
178
+ let history = this.histories.get(target);
179
+ if (!history) {
180
+ history = new OptimizeHistoryStore(this.options.historyPaths?.[target] ?? `${this.options.stores[target].filePath}.optimize-history.json`, this.now);
181
+ this.histories.set(target, history);
182
+ }
183
+ return history;
184
+ }
185
+
186
+ private expirePlans(): void {
187
+ for (const [id, staged] of this.plans) if (this.now() >= Date.parse(staged.plan.expiresAt)) this.plans.delete(id);
188
+ }
189
+ }