@aeondave/pi-persona-mind 0.9.7 → 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 (54) hide show
  1. package/AGENTS.md +137 -137
  2. package/CHANGELOG.md +287 -282
  3. package/LICENSE +24 -24
  4. package/README.md +1 -1
  5. package/docs/DESIGN.md +605 -605
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +11 -2
  8. package/src/core/auto-optimize.ts +323 -323
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -155
  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 -189
  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 -201
  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 -565
  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 -48
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/session-memory.ts +127 -127
  45. package/src/tools/backlog.ts +126 -126
  46. package/src/tools/memory-handoff.ts +30 -30
  47. package/src/tools/memory-history.ts +46 -46
  48. package/src/tools/memory.ts +6 -4
  49. package/src/ui/card-frame.ts +161 -161
  50. package/src/ui/inspector-frame.ts +44 -44
  51. package/src/ui/memory-inspector.ts +464 -464
  52. package/src/ui/mind-result-card.ts +48 -48
  53. package/src/ui/presentation.ts +87 -87
  54. package/src/ui/session-note-card.ts +58 -58
@@ -1,54 +1,54 @@
1
- /** Mind's own session preferences. Active persona ownership never comes from this file. */
2
- import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { TextDecoder } from "node:util";
5
- import { captureMode } from "./capture.ts";
6
-
7
- export interface MindSettings { mindCapture: "auto" | "prompt" | "off"; mindNudge: boolean }
8
- const snapshots = new Map<string, MindSettings>();
9
- const MAX_SETTINGS_BYTES = 1024 * 1024;
10
-
11
- function savedPreferences(path: string): Partial<MindSettings> {
12
- let fd: number | undefined;
13
- try {
14
- const listed = statSync(path);
15
- if (!listed.isFile() || !Number.isSafeInteger(listed.size) || listed.size > MAX_SETTINGS_BYTES) return {};
16
- fd = openSync(path, "r");
17
- const opened = fstatSync(fd);
18
- if (!opened.isFile() || opened.size !== listed.size || opened.size > MAX_SETTINGS_BYTES) return {};
19
- const bytes = Buffer.allocUnsafe(opened.size);
20
- let offset = 0;
21
- while (offset < bytes.length) {
22
- const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
23
- if (count === 0) return {};
24
- offset += count;
25
- }
26
- if (fstatSync(fd).size !== opened.size) return {};
27
- const parsed: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, ""));
28
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
29
- const row = parsed as Record<string, unknown>;
30
- if (row.version !== 1 || !row.preferences || typeof row.preferences !== "object" || Array.isArray(row.preferences)) return {};
31
- const prefs = row.preferences as Record<string, unknown>;
32
- if (prefs.mindCapture !== undefined && prefs.mindCapture !== "auto" && prefs.mindCapture !== "prompt" && prefs.mindCapture !== "off") return {};
33
- if (prefs.mindNudge !== undefined && typeof prefs.mindNudge !== "boolean") return {};
34
- return { ...(prefs.mindCapture === undefined ? {} : { mindCapture: prefs.mindCapture as MindSettings["mindCapture"] }), ...(prefs.mindNudge === undefined ? {} : { mindNudge: prefs.mindNudge as boolean }) };
35
- } catch { return {}; }
36
- finally { if (fd !== undefined) closeSync(fd); }
37
- }
38
-
39
- export function resolveMindSettings(agentDir: string, env: NodeJS.ProcessEnv, sessionId: string): MindSettings {
40
- const key = `${sessionId}\0${agentDir}`;
41
- const cached = snapshots.get(key);
42
- if (cached) return { ...cached };
43
- const saved = savedPreferences(join(agentDir, "persona", "settings.json"));
44
- const settings: MindSettings = {
45
- mindCapture: env.PI_PERSONA_MIND_CAPTURE !== undefined ? captureMode(env) : saved.mindCapture ?? "auto",
46
- mindNudge: env.PI_PERSONA_MIND_NUDGE !== undefined ? env.PI_PERSONA_MIND_NUDGE !== "off" : saved.mindNudge ?? true,
47
- };
48
- snapshots.set(key, settings);
49
- return { ...settings };
50
- }
51
-
52
- export function resetMindSettings(sessionId: string): void {
53
- for (const key of snapshots.keys()) if (key.startsWith(`${sessionId}\0`)) snapshots.delete(key);
54
- }
1
+ /** Mind's own session preferences. Active persona ownership never comes from this file. */
2
+ import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { TextDecoder } from "node:util";
5
+ import { captureMode } from "./capture.ts";
6
+
7
+ export interface MindSettings { mindCapture: "auto" | "prompt" | "off"; mindNudge: boolean }
8
+ const snapshots = new Map<string, MindSettings>();
9
+ const MAX_SETTINGS_BYTES = 1024 * 1024;
10
+
11
+ function savedPreferences(path: string): Partial<MindSettings> {
12
+ let fd: number | undefined;
13
+ try {
14
+ const listed = statSync(path);
15
+ if (!listed.isFile() || !Number.isSafeInteger(listed.size) || listed.size > MAX_SETTINGS_BYTES) return {};
16
+ fd = openSync(path, "r");
17
+ const opened = fstatSync(fd);
18
+ if (!opened.isFile() || opened.size !== listed.size || opened.size > MAX_SETTINGS_BYTES) return {};
19
+ const bytes = Buffer.allocUnsafe(opened.size);
20
+ let offset = 0;
21
+ while (offset < bytes.length) {
22
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
23
+ if (count === 0) return {};
24
+ offset += count;
25
+ }
26
+ if (fstatSync(fd).size !== opened.size) return {};
27
+ const parsed: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, ""));
28
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
29
+ const row = parsed as Record<string, unknown>;
30
+ if (row.version !== 1 || !row.preferences || typeof row.preferences !== "object" || Array.isArray(row.preferences)) return {};
31
+ const prefs = row.preferences as Record<string, unknown>;
32
+ if (prefs.mindCapture !== undefined && prefs.mindCapture !== "auto" && prefs.mindCapture !== "prompt" && prefs.mindCapture !== "off") return {};
33
+ if (prefs.mindNudge !== undefined && typeof prefs.mindNudge !== "boolean") return {};
34
+ return { ...(prefs.mindCapture === undefined ? {} : { mindCapture: prefs.mindCapture as MindSettings["mindCapture"] }), ...(prefs.mindNudge === undefined ? {} : { mindNudge: prefs.mindNudge as boolean }) };
35
+ } catch { return {}; }
36
+ finally { if (fd !== undefined) closeSync(fd); }
37
+ }
38
+
39
+ export function resolveMindSettings(agentDir: string, env: NodeJS.ProcessEnv, sessionId: string): MindSettings {
40
+ const key = `${sessionId}\0${agentDir}`;
41
+ const cached = snapshots.get(key);
42
+ if (cached) return { ...cached };
43
+ const saved = savedPreferences(join(agentDir, "persona", "settings.json"));
44
+ const settings: MindSettings = {
45
+ mindCapture: env.PI_PERSONA_MIND_CAPTURE !== undefined ? captureMode(env) : saved.mindCapture ?? "auto",
46
+ mindNudge: env.PI_PERSONA_MIND_NUDGE !== undefined ? env.PI_PERSONA_MIND_NUDGE !== "off" : saved.mindNudge ?? true,
47
+ };
48
+ snapshots.set(key, settings);
49
+ return { ...settings };
50
+ }
51
+
52
+ export function resetMindSettings(sessionId: string): void {
53
+ for (const key of snapshots.keys()) if (key.startsWith(`${sessionId}\0`)) snapshots.delete(key);
54
+ }
@@ -1,163 +1,163 @@
1
- /** Bounded write-ahead before images. Missing/corrupt history is never repaired to empty. */
2
- import { isExpired, isSafeMemoryContent, memoryContentKey, validateMemory, type MemoryEntry } from "./memory.ts";
3
- import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS, MAX_OPTIMIZE_SOURCES, samePersistedMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
4
- import { JsonStore, StoreCapacityError, StoreConflictError, withFileLock } from "./store.ts";
5
-
6
- export const MAX_OPTIMIZE_HISTORY = 32;
7
- export const MAX_OPTIMIZE_HISTORY_BYTES = 2 * 1024 * 1024;
8
- interface ReceiptBase {
9
- receiptId: string;
10
- target: OptimizeTarget;
11
- persona: string;
12
- createdAt: string;
13
- /** Prepared may mean interrupted before OR after memory commit; exact facts decide undo. */
14
- state: "prepared" | "applied" | "undone" | "rejected";
15
- storePath: string;
16
- /** Memory-store fingerprint the receipt was prepared against. Bytes still equal to it mean the replacement is not in effect (never landed, or rolled back by backup recovery), so there is nothing to undo. */
17
- fingerprint?: string;
18
- changes: OptimizeChange[];
19
- }
20
- /** Missing origin is the existing persisted optimizer contract, never an ordinary replacement. */
21
- export type OptimizeReceipt = ReceiptBase & (
22
- | { origin?: "optimization"; planId: string }
23
- | { origin: "replacement"; planId?: never }
24
- );
25
- export interface OptimizeHistory {
26
- ok: true; target: OptimizeTarget; receipts: OptimizeReceipt[]; retained: number; omitted: number;
27
- limit: number; maxBytes: number; withheldUnsafe: number;
28
- }
29
- export interface OptimizeUndone { ok: true; receiptId: string; target: OptimizeTarget; restored: number; warning?: string }
30
- export interface OptimizeReceiptDetail { ok: true; target: OptimizeTarget; receipt: OptimizeReceipt }
31
-
32
- function validateReceipt(raw: unknown): OptimizeReceipt | null {
33
- if (!raw || typeof raw !== "object") return null;
34
- const value = raw as Partial<OptimizeReceipt>;
35
- const validId = (id: unknown) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id);
36
- if (!validId(value.receiptId)) return null;
37
- if (value.origin === "replacement" ? value.planId !== undefined : !validId(value.planId) || value.origin !== undefined && value.origin !== "optimization") return null;
38
- if (!isOptimizeTarget(value.target) || typeof value.persona !== "string" || !value.persona || value.persona.length > 128) return null;
39
- // Writers use Date.toISOString(). Bound before parsing so metadata cannot expand discovery output.
40
- if (typeof value.createdAt !== "string" || value.createdAt.length > 27) return null;
41
- const createdAt = Date.parse(value.createdAt);
42
- if (!Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== value.createdAt) return null;
43
- if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
44
- if (typeof value.storePath !== "string" || value.storePath.length > 32_768 || !value.storePath) return null;
45
- if (value.fingerprint !== undefined && (typeof value.fingerprint !== "string" || !/^[\da-f]{64}$/.test(value.fingerprint))) return null;
46
- if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
47
- const changes: OptimizeChange[] = [];
48
- const sourceIds = new Set<string>(); const replacementIds = new Set<string>();
49
- for (const change of value.changes) {
50
- if (!change || !Array.isArray(change.before) || !change.before.length || change.before.length > MAX_OPTIMIZE_SOURCES) return null;
51
- const before: MemoryEntry[] = [];
52
- for (const source of change.before) {
53
- const entry = validateMemory(source);
54
- if (!entry || sourceIds.has(entry.id)) return null;
55
- sourceIds.add(entry.id); before.push(entry);
56
- }
57
- const after = validateMemory(change.after);
58
- if (!after || replacementIds.has(after.id)) return null;
59
- replacementIds.add(after.id); changes.push({ before, after });
60
- }
61
- const receipt: ReceiptBase = { receiptId: value.receiptId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
62
- state: value.state!, storePath: value.storePath, ...(value.fingerprint === undefined ? {} : { fingerprint: value.fingerprint }), changes };
63
- return value.origin === "replacement" ? { ...receipt, origin: "replacement" } : { ...receipt, origin: "optimization", planId: value.planId! };
64
- }
65
-
66
- /** Strict CAS avoids JsonStore.update's recovery semantics, which are unsuitable for recovery logs. */
67
- export class OptimizeHistoryStore {
68
- private readonly store: JsonStore<OptimizeReceipt>;
69
- readonly path: string;
70
- constructor(path: string, now: () => number) {
71
- this.path = path;
72
- this.store = new JsonStore(path, { version: 1, validateEntry: validateReceipt, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES, maxEntries: MAX_OPTIMIZE_HISTORY, now });
73
- }
74
- async exclusive<T>(run: () => Promise<T>): Promise<T> { return withFileLock(`${this.path}.transaction.lock`, run); }
75
- async read(): Promise<OptimizeReceipt[]> { return (await this.store.inspectStrict()).store.entries; }
76
- /** `currentFingerprint` is the memory store's verified current fingerprint, used only to resolve this writer's own intents that are not in effect. */
77
- async prepare(receipt: OptimizeReceipt, currentFingerprint?: string): Promise<void> {
78
- const snapshot = await this.store.inspectStrict();
79
- let entries = [...snapshot.store.entries, receipt];
80
- // Only settled history can be evicted. An unresolved crash intent may own the only before image.
81
- const bytes = () => Buffer.byteLength(`${JSON.stringify({ ...snapshot.store, sequence: snapshot.store.sequence + 1, entries }, null, 2)}\n`, "utf8");
82
- let resolved = false;
83
- while (entries.length > MAX_OPTIMIZE_HISTORY || bytes() > MAX_OPTIMIZE_HISTORY_BYTES) {
84
- const index = entries.findIndex((entry) => entry.receiptId !== receipt.receiptId && entry.state !== "prepared");
85
- if (index < 0 && !resolved && currentFingerprint !== undefined) {
86
- // Byte-identical memory since preparation means that intent is not in effect, whether it never
87
- // committed or backup recovery rolled it back, so no before image is needed. Only receipts of
88
- // this store and owner qualify: the history file is shared across personas, and another owner's
89
- // intent is theirs to settle. A receipt without a fingerprint, or prepared against other bytes, stays protected.
90
- resolved = true;
91
- const mine = (entry: OptimizeReceipt) => entry.storePath === receipt.storePath && entry.persona === receipt.persona && entry.target === receipt.target;
92
- entries = entries.map((entry): OptimizeReceipt => entry.receiptId !== receipt.receiptId && entry.state === "prepared" && entry.fingerprint === currentFingerprint && mine(entry) ? { ...entry, state: "rejected" } : entry);
93
- continue;
94
- }
95
- if (index < 0) throw new Error("optimizer history capacity exhausted by recovery receipts; replacement refused");
96
- entries.splice(index, 1);
97
- }
98
- await this.store.compareAndUpdate(snapshot.fingerprint, () => entries);
99
- }
100
- async settle(receiptId: string, state: OptimizeReceipt["state"]): Promise<void> {
101
- const snapshot = await this.store.inspectStrict();
102
- if (!snapshot.store.entries.some((receipt) => receipt.receiptId === receiptId)) throw new Error("optimizer recovery receipt disappeared; history requires repair");
103
- await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => entries.map((receipt) => receipt.receiptId === receiptId ? { ...receipt, state } : receipt));
104
- }
105
-
106
- /** Caller owns the memory transaction lock. Both writers share this write-ahead/CAS protocol. */
107
- async commit(store: JsonStore<MemoryEntry>, fingerprint: string, receipt: OptimizeReceipt | undefined,
108
- mutate: (entries: MemoryEntry[]) => MemoryEntry[], assertCurrent: () => void = () => {}): Promise<{ entries: MemoryEntry[]; warning?: string }> {
109
- return this.exclusive(async () => {
110
- assertCurrent();
111
- if ((await store.inspectStrict()).fingerprint !== fingerprint) throw new StoreConflictError();
112
- if (receipt) await this.prepare({ ...receipt, fingerprint }, fingerprint);
113
- let callbackRejected = false;
114
- let entries: MemoryEntry[];
115
- try {
116
- entries = (await store.compareAndUpdate(fingerprint, (current) => {
117
- try { assertCurrent(); return mutate(current); }
118
- catch (error) { callbackRejected = true; throw error; }
119
- })).entries;
120
- } catch (error) {
121
- if (receipt) {
122
- // Capacity is checked during serialization, before any write. Any other error may follow
123
- // the rename, so only memory bytes still identical to the prepared fingerprint show that the
124
- // replacement is not in effect (it never landed, or backup recovery rolled it back); a changed
125
- // or unreadable store keeps the only before image prepared.
126
- const unwritten = callbackRejected || error instanceof StoreConflictError || error instanceof StoreCapacityError
127
- || await store.inspectStrict().then((current) => current.fingerprint === fingerprint, () => false);
128
- if (unwritten) await this.settle(receipt.receiptId, "rejected").catch(() => {});
129
- else throw new Error(`memory replacement outcome uncertain; durable receipt ${receipt.receiptId} remains prepared: ${error instanceof Error ? error.message : "storage failure"}`);
130
- }
131
- throw error;
132
- }
133
- if (receipt) {
134
- try { await this.settle(receipt.receiptId, "applied"); }
135
- catch { return { entries, warning: "replacement committed; durable receipt remains prepared because history finalization failed" }; }
136
- }
137
- return { entries };
138
- });
139
- }
140
- }
141
-
142
- /** Revert only exact affected rows, never a whole historical snapshot. */
143
- export function restoreReceipt(entries: readonly MemoryEntry[], receipt: OptimizeReceipt, persona: string, now: number): { ok: true; entries: MemoryEntry[]; restored: number } | OptimizeFailure {
144
- if (receipt.persona !== persona) return { ok: false, reason: "receipt belongs to a different persona owner" };
145
- if (receipt.origin === "replacement") return { ok: false, reason: "ordinary replacement history is read-only; optimizer undo is unavailable for this receipt" };
146
- if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
147
- const before = receipt.changes.flatMap((change) => change.before);
148
- const after = receipt.changes.map((change) => change.after);
149
- if ([...before, ...after].some((entry) => !isSafeMemoryContent(entry))) return { ok: false, reason: "receipt contains unsafe memory content" };
150
- if ((receipt.target === "project" || receipt.target === "project-long") && [...before, ...after].some((entry) => entry.persona !== persona)) return { ok: false, reason: "receipt contains foreign or unowned project facts" };
151
- if ([...before, ...after].some((entry) => isExpired(entry, now))) return { ok: false, reason: "receipt contains expired sources; undo cannot revive expired memory" };
152
- const selected = new Set<MemoryEntry>();
153
- for (const replacement of after) {
154
- const matches = entries.filter((entry) => entry.id === replacement.id);
155
- if (matches.length !== 1 || !samePersistedMemory(matches[0]!, replacement)) return { ok: false, reason: "affected replacement changed or is missing; undo refused" };
156
- selected.add(matches[0]!);
157
- }
158
- const untouched = entries.filter((entry) => !selected.has(entry));
159
- for (const source of before) {
160
- if (untouched.some((entry) => entry.id === source.id || memoryContentKey(entry) === memoryContentKey(source))) return { ok: false, reason: "restored source collides with a current fact; undo refused" };
161
- }
162
- return { ok: true, entries: [...untouched, ...structuredClone(before)], restored: before.length };
163
- }
1
+ /** Bounded write-ahead before images. Missing/corrupt history is never repaired to empty. */
2
+ import { isExpired, isSafeMemoryContent, memoryContentKey, validateMemory, type MemoryEntry } from "./memory.ts";
3
+ import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS, MAX_OPTIMIZE_SOURCES, samePersistedMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
4
+ import { JsonStore, StoreCapacityError, StoreConflictError, withFileLock } from "./store.ts";
5
+
6
+ export const MAX_OPTIMIZE_HISTORY = 32;
7
+ export const MAX_OPTIMIZE_HISTORY_BYTES = 2 * 1024 * 1024;
8
+ interface ReceiptBase {
9
+ receiptId: string;
10
+ target: OptimizeTarget;
11
+ persona: string;
12
+ createdAt: string;
13
+ /** Prepared may mean interrupted before OR after memory commit; exact facts decide undo. */
14
+ state: "prepared" | "applied" | "undone" | "rejected";
15
+ storePath: string;
16
+ /** Memory-store fingerprint the receipt was prepared against. Bytes still equal to it mean the replacement is not in effect (never landed, or rolled back by backup recovery), so there is nothing to undo. */
17
+ fingerprint?: string;
18
+ changes: OptimizeChange[];
19
+ }
20
+ /** Missing origin is the existing persisted optimizer contract, never an ordinary replacement. */
21
+ export type OptimizeReceipt = ReceiptBase & (
22
+ | { origin?: "optimization"; planId: string }
23
+ | { origin: "replacement"; planId?: never }
24
+ );
25
+ export interface OptimizeHistory {
26
+ ok: true; target: OptimizeTarget; receipts: OptimizeReceipt[]; retained: number; omitted: number;
27
+ limit: number; maxBytes: number; withheldUnsafe: number;
28
+ }
29
+ export interface OptimizeUndone { ok: true; receiptId: string; target: OptimizeTarget; restored: number; warning?: string }
30
+ export interface OptimizeReceiptDetail { ok: true; target: OptimizeTarget; receipt: OptimizeReceipt }
31
+
32
+ function validateReceipt(raw: unknown): OptimizeReceipt | null {
33
+ if (!raw || typeof raw !== "object") return null;
34
+ const value = raw as Partial<OptimizeReceipt>;
35
+ const validId = (id: unknown) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id);
36
+ if (!validId(value.receiptId)) return null;
37
+ if (value.origin === "replacement" ? value.planId !== undefined : !validId(value.planId) || value.origin !== undefined && value.origin !== "optimization") return null;
38
+ if (!isOptimizeTarget(value.target) || typeof value.persona !== "string" || !value.persona || value.persona.length > 128) return null;
39
+ // Writers use Date.toISOString(). Bound before parsing so metadata cannot expand discovery output.
40
+ if (typeof value.createdAt !== "string" || value.createdAt.length > 27) return null;
41
+ const createdAt = Date.parse(value.createdAt);
42
+ if (!Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== value.createdAt) return null;
43
+ if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
44
+ if (typeof value.storePath !== "string" || value.storePath.length > 32_768 || !value.storePath) return null;
45
+ if (value.fingerprint !== undefined && (typeof value.fingerprint !== "string" || !/^[\da-f]{64}$/.test(value.fingerprint))) return null;
46
+ if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
47
+ const changes: OptimizeChange[] = [];
48
+ const sourceIds = new Set<string>(); const replacementIds = new Set<string>();
49
+ for (const change of value.changes) {
50
+ if (!change || !Array.isArray(change.before) || !change.before.length || change.before.length > MAX_OPTIMIZE_SOURCES) return null;
51
+ const before: MemoryEntry[] = [];
52
+ for (const source of change.before) {
53
+ const entry = validateMemory(source);
54
+ if (!entry || sourceIds.has(entry.id)) return null;
55
+ sourceIds.add(entry.id); before.push(entry);
56
+ }
57
+ const after = validateMemory(change.after);
58
+ if (!after || replacementIds.has(after.id)) return null;
59
+ replacementIds.add(after.id); changes.push({ before, after });
60
+ }
61
+ const receipt: ReceiptBase = { receiptId: value.receiptId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
62
+ state: value.state!, storePath: value.storePath, ...(value.fingerprint === undefined ? {} : { fingerprint: value.fingerprint }), changes };
63
+ return value.origin === "replacement" ? { ...receipt, origin: "replacement" } : { ...receipt, origin: "optimization", planId: value.planId! };
64
+ }
65
+
66
+ /** Strict CAS avoids JsonStore.update's recovery semantics, which are unsuitable for recovery logs. */
67
+ export class OptimizeHistoryStore {
68
+ private readonly store: JsonStore<OptimizeReceipt>;
69
+ readonly path: string;
70
+ constructor(path: string, now: () => number) {
71
+ this.path = path;
72
+ this.store = new JsonStore(path, { version: 1, validateEntry: validateReceipt, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES, maxEntries: MAX_OPTIMIZE_HISTORY, now });
73
+ }
74
+ async exclusive<T>(run: () => Promise<T>): Promise<T> { return withFileLock(`${this.path}.transaction.lock`, run); }
75
+ async read(): Promise<OptimizeReceipt[]> { return (await this.store.inspectStrict()).store.entries; }
76
+ /** `currentFingerprint` is the memory store's verified current fingerprint, used only to resolve this writer's own intents that are not in effect. */
77
+ async prepare(receipt: OptimizeReceipt, currentFingerprint?: string): Promise<void> {
78
+ const snapshot = await this.store.inspectStrict();
79
+ let entries = [...snapshot.store.entries, receipt];
80
+ // Only settled history can be evicted. An unresolved crash intent may own the only before image.
81
+ const bytes = () => Buffer.byteLength(`${JSON.stringify({ ...snapshot.store, sequence: snapshot.store.sequence + 1, entries }, null, 2)}\n`, "utf8");
82
+ let resolved = false;
83
+ while (entries.length > MAX_OPTIMIZE_HISTORY || bytes() > MAX_OPTIMIZE_HISTORY_BYTES) {
84
+ const index = entries.findIndex((entry) => entry.receiptId !== receipt.receiptId && entry.state !== "prepared");
85
+ if (index < 0 && !resolved && currentFingerprint !== undefined) {
86
+ // Byte-identical memory since preparation means that intent is not in effect, whether it never
87
+ // committed or backup recovery rolled it back, so no before image is needed. Only receipts of
88
+ // this store and owner qualify: the history file is shared across personas, and another owner's
89
+ // intent is theirs to settle. A receipt without a fingerprint, or prepared against other bytes, stays protected.
90
+ resolved = true;
91
+ const mine = (entry: OptimizeReceipt) => entry.storePath === receipt.storePath && entry.persona === receipt.persona && entry.target === receipt.target;
92
+ entries = entries.map((entry): OptimizeReceipt => entry.receiptId !== receipt.receiptId && entry.state === "prepared" && entry.fingerprint === currentFingerprint && mine(entry) ? { ...entry, state: "rejected" } : entry);
93
+ continue;
94
+ }
95
+ if (index < 0) throw new Error("optimizer history capacity exhausted by recovery receipts; replacement refused");
96
+ entries.splice(index, 1);
97
+ }
98
+ await this.store.compareAndUpdate(snapshot.fingerprint, () => entries);
99
+ }
100
+ async settle(receiptId: string, state: OptimizeReceipt["state"]): Promise<void> {
101
+ const snapshot = await this.store.inspectStrict();
102
+ if (!snapshot.store.entries.some((receipt) => receipt.receiptId === receiptId)) throw new Error("optimizer recovery receipt disappeared; history requires repair");
103
+ await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => entries.map((receipt) => receipt.receiptId === receiptId ? { ...receipt, state } : receipt));
104
+ }
105
+
106
+ /** Caller owns the memory transaction lock. Both writers share this write-ahead/CAS protocol. */
107
+ async commit(store: JsonStore<MemoryEntry>, fingerprint: string, receipt: OptimizeReceipt | undefined,
108
+ mutate: (entries: MemoryEntry[]) => MemoryEntry[], assertCurrent: () => void = () => {}): Promise<{ entries: MemoryEntry[]; warning?: string }> {
109
+ return this.exclusive(async () => {
110
+ assertCurrent();
111
+ if ((await store.inspectStrict()).fingerprint !== fingerprint) throw new StoreConflictError();
112
+ if (receipt) await this.prepare({ ...receipt, fingerprint }, fingerprint);
113
+ let callbackRejected = false;
114
+ let entries: MemoryEntry[];
115
+ try {
116
+ entries = (await store.compareAndUpdate(fingerprint, (current) => {
117
+ try { assertCurrent(); return mutate(current); }
118
+ catch (error) { callbackRejected = true; throw error; }
119
+ })).entries;
120
+ } catch (error) {
121
+ if (receipt) {
122
+ // Capacity is checked during serialization, before any write. Any other error may follow
123
+ // the rename, so only memory bytes still identical to the prepared fingerprint show that the
124
+ // replacement is not in effect (it never landed, or backup recovery rolled it back); a changed
125
+ // or unreadable store keeps the only before image prepared.
126
+ const unwritten = callbackRejected || error instanceof StoreConflictError || error instanceof StoreCapacityError
127
+ || await store.inspectStrict().then((current) => current.fingerprint === fingerprint, () => false);
128
+ if (unwritten) await this.settle(receipt.receiptId, "rejected").catch(() => {});
129
+ else throw new Error(`memory replacement outcome uncertain; durable receipt ${receipt.receiptId} remains prepared: ${error instanceof Error ? error.message : "storage failure"}`);
130
+ }
131
+ throw error;
132
+ }
133
+ if (receipt) {
134
+ try { await this.settle(receipt.receiptId, "applied"); }
135
+ catch { return { entries, warning: "replacement committed; durable receipt remains prepared because history finalization failed" }; }
136
+ }
137
+ return { entries };
138
+ });
139
+ }
140
+ }
141
+
142
+ /** Revert only exact affected rows, never a whole historical snapshot. */
143
+ export function restoreReceipt(entries: readonly MemoryEntry[], receipt: OptimizeReceipt, persona: string, now: number): { ok: true; entries: MemoryEntry[]; restored: number } | OptimizeFailure {
144
+ if (receipt.persona !== persona) return { ok: false, reason: "receipt belongs to a different persona owner" };
145
+ if (receipt.origin === "replacement") return { ok: false, reason: "ordinary replacement history is read-only; optimizer undo is unavailable for this receipt" };
146
+ if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
147
+ const before = receipt.changes.flatMap((change) => change.before);
148
+ const after = receipt.changes.map((change) => change.after);
149
+ if ([...before, ...after].some((entry) => !isSafeMemoryContent(entry))) return { ok: false, reason: "receipt contains unsafe memory content" };
150
+ if ((receipt.target === "project" || receipt.target === "project-long") && [...before, ...after].some((entry) => entry.persona !== persona)) return { ok: false, reason: "receipt contains foreign or unowned project facts" };
151
+ if ([...before, ...after].some((entry) => isExpired(entry, now))) return { ok: false, reason: "receipt contains expired sources; undo cannot revive expired memory" };
152
+ const selected = new Set<MemoryEntry>();
153
+ for (const replacement of after) {
154
+ const matches = entries.filter((entry) => entry.id === replacement.id);
155
+ if (matches.length !== 1 || !samePersistedMemory(matches[0]!, replacement)) return { ok: false, reason: "affected replacement changed or is missing; undo refused" };
156
+ selected.add(matches[0]!);
157
+ }
158
+ const untouched = entries.filter((entry) => !selected.has(entry));
159
+ for (const source of before) {
160
+ if (untouched.some((entry) => entry.id === source.id || memoryContentKey(entry) === memoryContentKey(source))) return { ok: false, reason: "restored source collides with a current fact; undo refused" };
161
+ }
162
+ return { ok: true, entries: [...untouched, ...structuredClone(before)], restored: before.length };
163
+ }