@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,720 +1,720 @@
1
- /**
2
- * MindService — the integration heart: it binds the durable stores (store.ts) to the resolved
3
- * scope (scope.ts) and the pure faculties (memory.ts / backlog.ts / inject.ts), and exposes the
4
- * high-level operations the Pi tools and hooks call. It has NO Pi imports, so it is fully
5
- * unit-testable over real temp files without a running agent.
6
- *
7
- * Five JSON stores back one scope: persona/shared durable memory, durable repository knowledge,
8
- * short-term (48h, auto-deleted) memory for the project, and the project backlog
9
- * (same default life; a later wake extends it).
10
- */
11
-
12
- import { randomUUID } from "node:crypto";
13
- import type { BacklogEntry, BacklogState, TransitionResult } from "./backlog.ts";
14
- import { clampBacklogMax, compactTerminal, makeBacklog, openItems, orderBacklog, pruneExpired as pruneExpiredBacklog, transition, validateBacklog, viewFor, MAX_BACKLOG_NOTE_CHARS, MAX_BACKLOG_TAGS, MAX_BACKLOG_TAG_CHARS, MAX_BACKLOG_TEXT_CHARS } from "./backlog.ts";
15
- import { contentId } from "./ids.ts";
16
- import type { MindBudget } from "./inject.ts";
17
- import { renderMind } from "./inject.ts";
18
- import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope } from "./memory-read.ts";
19
- import { MemoryOptimizer } from "./optimize-service.ts";
20
- import { OptimizeHistoryStore, type OptimizeReceipt } from "./optimize-history.ts";
21
- import { samePersistedMemory, type OptimizeTarget } from "./optimize.ts";
22
- import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
23
- import { clampRecallMax, isExpired, isMemoryId, isSafeMemoryContent, makeMemory, memoryContentKey, memoryIdMatches, promoteToLong, pruneExpired, recall, sameMemoryContent, supersedeTargets, upsertMemory, validateLongMemory, validateShortMemory, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS } from "./memory.ts";
24
- import { scanContent } from "./scanner.ts";
25
- import { memoryMutationLockPath, type Scope } from "./scope.ts";
26
- import { JsonStore, type JsonStoreOptions, type StoreFile, withFileLock } from "./store.ts";
27
-
28
- const STORE_VERSION = 1;
29
-
30
- /** How many per-fact ids an ambiguity refusal spells out before it summarizes the remainder. */
31
- const MAX_AMBIGUITY_IDS_IN_REASON = 5;
32
-
33
- export interface MindServiceOptions {
34
- now?: () => number;
35
- onWarn?: (message: string) => void;
36
- budget?: MindBudget;
37
- /** Runtime owner snapshot for remember admission/commit; omitted by standalone store callers. */
38
- isCurrent?: () => boolean;
39
- }
40
-
41
- interface RememberInputBase {
42
- kind: MemoryKind;
43
- text: string;
44
- tags?: string[];
45
- ttlHours?: number;
46
- supersedes?: string;
47
- source?: string;
48
- derivedFrom?: string[];
49
- }
50
-
51
- /** Long writes name their destination; short working memory is project-scoped by default. */
52
- export type RememberInput =
53
- | (RememberInputBase & { term: "long"; scope: "project" | "persona" | "shared" })
54
- | (RememberInputBase & { term: "short"; scope?: "project" });
55
-
56
- export interface BacklogAddInput {
57
- text: string;
58
- tags?: string[];
59
- dueInSeconds?: number;
60
- ttlHours?: number;
61
- }
62
-
63
- export interface BacklogListOptions {
64
- all?: boolean;
65
- state?: BacklogState;
66
- /** Optional page size; omitted for the compatibility view, bounded pages use `backlogListPage`. */
67
- max?: number;
68
- }
69
-
70
- export interface BacklogListPage {
71
- items: BacklogEntry[];
72
- total: number;
73
- withheld: number;
74
- }
75
-
76
- export type Recallable = MemoryReadScope;
77
-
78
- /** One of the distinct facts a shared historical handle addresses, named by an id of its own. */
79
- export interface AmbiguousMemory {
80
- /** This fact's CURRENT content id. Distinct facts always hash differently, so it names one entry. */
81
- id: string;
82
- kind: MemoryKind;
83
- text: string;
84
- /** False while this id is still the shared handle itself — the one legacy-encodable member of the
85
- * collision keeps the ambiguous id as its own, and becomes addressable once the others are gone. */
86
- resolves: boolean;
87
- }
88
-
89
- export type RememberResult = { ok: true; entry: MemoryEntry; receiptId?: string; warning?: string } | { ok: false; reason: string };
90
- export type BacklogAddResult = { ok: true; entry: BacklogEntry } | { ok: false; reason: string };
91
- export type BacklogSetResult = { ok: true; entry: BacklogEntry } | { ok: false; reason?: string };
92
- export type ForgetResult = { removed: number; reason?: "ambiguous_id"; candidates?: AmbiguousMemory[] };
93
- export type WorkspaceResetResult =
94
- | { ok: true; stmRemoved: number; backlogRemoved: number; ltmKept: number }
95
- | { ok: false; reason: string };
96
-
97
- function storageFailure(err: unknown): string {
98
- const message = err instanceof Error ? err.message : String(err);
99
- return `storage error: ${message || "unknown persistence failure"}`;
100
- }
101
-
102
- /**
103
- * The distinct facts a shared handle addresses, each named by an id of its OWN. A refusal that offers
104
- * no way forward is a dead end: destroying nothing is right, but the caller still has to be able to
105
- * pick one. Distinct facts always hash to distinct current ids, so every member of a collision is
106
- * nameable — except the single member whose v1 and v2 encodings coincide (that id IS the shared
107
- * handle), which becomes addressable as soon as its neighbours are gone.
108
- */
109
- function ambiguityCandidates(pool: readonly MemoryEntry[], id: string): AmbiguousMemory[] {
110
- const distinct = new Map<string, MemoryEntry>();
111
- for (const entry of pool) if (memoryIdMatches(entry, id)) distinct.set(memoryContentKey(entry), entry);
112
- return [...distinct.values()]
113
- .map((entry) => {
114
- const handle = contentId(entry.kind, entry.text, entry.tags);
115
- const reached = new Set(pool.filter((e) => memoryIdMatches(e, handle)).map((e) => memoryContentKey(e)));
116
- return { id: handle, kind: entry.kind, text: safePersistedText(entry.text).text, resolves: reached.size === 1 };
117
- })
118
- .sort((a, b) => Number(b.resolves) - Number(a.resolves));
119
- }
120
-
121
- function ambiguousSupersedesReason(id: string, candidates: readonly AmbiguousMemory[]): string {
122
- // The reason is read by the model, so the offer list is bounded rather than as long as the collision.
123
- const shown = candidates.slice(0, MAX_AMBIGUITY_IDS_IN_REASON);
124
- const offers = shown.map((c) => (c.resolves ? c.id : `${c.id} (still the shared handle — usable once the others are gone)`)).join(", ");
125
- const rest = candidates.length - shown.length;
126
- return `memory supersedes id ${id} is ambiguous — it addresses ${candidates.length} distinct stored memories; supersede one of them by its own current id instead: ${offers}${rest > 0 ? `, and ${rest} more` : ""}`;
127
- }
128
-
129
- function safePersistedText(text: string): { text: string; withheld: boolean } {
130
- const scan = scanContent(text);
131
- return scan.ok
132
- ? { text, withheld: false }
133
- : { text: `[withheld unsafe stored content — ${scan.reason ?? "content policy"}]`, withheld: true };
134
- }
135
-
136
- function validateNewTextAndTags(text: string, tags: readonly string[] | undefined, label: string, maxText: number, maxTags: number, maxTagChars: number): string | undefined {
137
- if (text.length > maxText) return `${label} text exceeds ${maxText} characters`;
138
- if (tags === undefined) return undefined;
139
- if (!Array.isArray(tags)) return `${label} tags must be an array`;
140
- if (tags.length > maxTags) return `${label} has more than ${maxTags} tags`;
141
- if (tags.some((tag) => typeof tag !== "string" || tag.length > maxTagChars)) return `${label} tag exceeds ${maxTagChars} characters`;
142
- for (const tag of tags) {
143
- const scan = scanContent(tag);
144
- if (!scan.ok) return `${label} tag rejected: ${scan.reason ?? "content policy"}`;
145
- }
146
- return undefined;
147
- }
148
-
149
- function validPositiveFutureOffset(value: number | undefined, unitMs: number, now: number): boolean {
150
- if (value === undefined) return true;
151
- if (!Number.isFinite(value) || value <= 0) return false;
152
- const target = now + value * unitMs;
153
- return Number.isFinite(target) && Number.isFinite(new Date(target).getTime());
154
- }
155
-
156
- export class MindService {
157
- private readonly scope: Scope;
158
- private readonly now: () => number;
159
- private readonly budget: MindBudget | undefined;
160
- private readonly ltm: JsonStore<MemoryEntry>;
161
- private readonly shared: JsonStore<MemoryEntry>;
162
- private readonly projectLtm: JsonStore<MemoryEntry>;
163
- private readonly stm: JsonStore<MemoryEntry>;
164
- private readonly backlog: JsonStore<BacklogEntry>;
165
- private readonly memoryMutationLock: string;
166
- private readonly warn: (message: string) => void;
167
- private readonly isCurrent: () => boolean;
168
-
169
- constructor(
170
- scope: Scope,
171
- opts: MindServiceOptions = {},
172
- ) {
173
- this.scope = scope;
174
- this.now = opts.now ?? Date.now;
175
- this.budget = opts.budget;
176
- this.warn = opts.onWarn ?? (() => {});
177
- this.isCurrent = opts.isCurrent ?? (() => true);
178
- const longOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateLongMemory, now: this.now };
179
- const shortOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateShortMemory, now: this.now };
180
- const backlogOpts: JsonStoreOptions<BacklogEntry> = { version: STORE_VERSION, validateEntry: validateBacklog, now: this.now };
181
- if (opts.onWarn) {
182
- longOpts.onWarn = opts.onWarn;
183
- shortOpts.onWarn = opts.onWarn;
184
- backlogOpts.onWarn = opts.onWarn;
185
- }
186
- this.ltm = new JsonStore<MemoryEntry>(scope.paths.ltm, longOpts);
187
- this.shared = new JsonStore<MemoryEntry>(scope.paths.shared, longOpts);
188
- this.projectLtm = new JsonStore<MemoryEntry>(scope.paths.projectLtm, longOpts);
189
- this.stm = new JsonStore<MemoryEntry>(scope.paths.stm, shortOpts);
190
- this.backlog = new JsonStore<BacklogEntry>(scope.paths.backlog, backlogOpts);
191
- // Persona/shared facts span workspaces. All multi-store memory decisions must serialize
192
- // within the agent profile, including ambiguity checks before promote/forget/supersede.
193
- this.memoryMutationLock = memoryMutationLockPath(scope.paths);
194
- }
195
-
196
- private safeMemories(entries: readonly MemoryEntry[], tier: string): MemoryEntry[] {
197
- let withheld = 0;
198
- const safe = entries.map((entry) => {
199
- const guarded = safePersistedText(entry.text);
200
- if (!guarded.withheld) return entry;
201
- withheld++;
202
- return { ...entry, text: guarded.text };
203
- });
204
- if (withheld > 0) this.warn(`${withheld} unsafe persisted ${tier} memor${withheld === 1 ? "y was" : "ies were"} withheld from model context`);
205
- return safe;
206
- }
207
-
208
- private safeBacklog(entries: readonly BacklogEntry[]): BacklogEntry[] {
209
- let withheld = 0;
210
- const safe = entries.map((entry) => {
211
- const text = safePersistedText(entry.text);
212
- const note = entry.note === undefined ? undefined : safePersistedText(entry.note);
213
- if (!text.withheld && !note?.withheld) return entry;
214
- withheld++;
215
- return {
216
- ...entry,
217
- text: text.text,
218
- ...(note ? { note: note.text } : {}),
219
- };
220
- });
221
- if (withheld > 0) this.warn(`${withheld} unsafe persisted backlog item${withheld === 1 ? " was" : "s were"} withheld from model context`);
222
- return safe;
223
- }
224
-
225
- // ── memory ────────────────────────────────────────────────────────────────
226
-
227
- private memoryStores() {
228
- return { project: this.stm, "project-long": this.projectLtm, persona: this.ltm, shared: this.shared };
229
- }
230
-
231
- /** One plan cache per native session owner. Lifecycle adapters must invalidate/discard it. */
232
- createOptimizer(): MemoryOptimizer {
233
- return new MemoryOptimizer({ stores: this.memoryStores(), persona: this.scope.persona, now: this.now, mutationLock: this.memoryMutationLock });
234
- }
235
-
236
- /** Read-only identity snapshot for inspection and native recording receipts; no store paths or IO. */
237
- inspectionScope(): Pick<Scope, "persona" | "projectRoot" | "homeWorkspace"> {
238
- return { persona: this.scope.persona, projectRoot: this.scope.projectRoot, ...(this.scope.homeWorkspace ? { homeWorkspace: true as const } : {}) };
239
- }
240
-
241
- /** Explicit full retrieval; reads never refresh age/expiry or repair malformed stores. */
242
- readMemory(id: string, scope: MemoryReadScope = "both"): Promise<MemoryReadResult> {
243
- return readMemory(this.memoryStores(), id, scope, this.now());
244
- }
245
-
246
- /** Store a memory (long or short term). Scanned + non-empty-checked before it is persisted. */
247
- async remember(input: RememberInput): Promise<RememberResult> {
248
- if (!this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner is unavailable; no memory was stored" };
249
- if (input.term !== "long" && input.term !== "short") return { ok: false, reason: "unknown memory term" };
250
- if (input.scope !== undefined && !["project", "persona", "shared"].includes(input.scope)) return { ok: false, reason: "unknown memory scope" };
251
- if (input.term === "long" && input.scope === undefined) return { ok: false, reason: "long-term memory requires an explicit scope: project, persona, or shared" };
252
- if (input.term === "short" && input.scope !== undefined && input.scope !== "project") return { ok: false, reason: "short-term memory belongs to the project" };
253
- const now = this.now();
254
- const text = input.text.trim();
255
- if (!text) return { ok: false, reason: "memory text is empty" };
256
- const sizeError = validateNewTextAndTags(text, input.tags, "memory", MAX_MEMORY_TEXT_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS);
257
- if (sizeError) return { ok: false, reason: sizeError };
258
- if (input.source !== undefined && (typeof input.source !== "string" || input.source.length > MAX_MEMORY_SOURCE_CHARS)) {
259
- return { ok: false, reason: `memory source exceeds ${MAX_MEMORY_SOURCE_CHARS} characters` };
260
- }
261
- if (input.source !== undefined) {
262
- const sourceScan = scanContent(input.source);
263
- if (!sourceScan.ok) return { ok: false, reason: `memory source rejected: ${sourceScan.reason ?? "content policy"}` };
264
- }
265
- if (input.supersedes !== undefined && !isMemoryId(input.supersedes)) {
266
- return { ok: false, reason: `memory supersedes id must be one safe token of at most ${MAX_MEMORY_ID_CHARS} characters` };
267
- }
268
- if (input.derivedFrom !== undefined) {
269
- if (!Array.isArray(input.derivedFrom) || input.derivedFrom.length > MAX_MEMORY_DERIVED_IDS) {
270
- return { ok: false, reason: `memory has more than ${MAX_MEMORY_DERIVED_IDS} derived ids` };
271
- }
272
- if (input.derivedFrom.some((id) => !isMemoryId(id))) {
273
- return { ok: false, reason: `memory derived id must be one safe token of at most ${MAX_MEMORY_ID_CHARS} characters` };
274
- }
275
- }
276
- if (!validPositiveFutureOffset(input.ttlHours, 3_600_000, now)) return { ok: false, reason: "ttlHours must be a finite positive duration within the supported date range" };
277
- const scan = scanContent(text);
278
- if (!scan.ok) return { ok: false, reason: scan.reason ?? "rejected by content scanner" };
279
-
280
- // Kind describes content; only the caller-selected term controls lifetime.
281
- const term = input.term;
282
- const makeInput: MemoryInput = { term, kind: input.kind, text };
283
- if (input.tags) makeInput.tags = input.tags;
284
- if (input.ttlHours !== undefined) makeInput.ttlHours = input.ttlHours;
285
- if (input.supersedes) makeInput.supersedes = input.supersedes;
286
- if (input.source) makeInput.source = input.source;
287
- if (input.derivedFrom && input.derivedFrom.length > 0) makeInput.derivedFrom = input.derivedFrom;
288
- if (term === "short" || input.scope === "project") makeInput.persona = this.scope.persona;
289
-
290
- const entry = makeMemory(makeInput, now);
291
- const target: OptimizeTarget = term === "short" ? "project" : input.scope === "project" ? "project-long" : input.scope === "shared" ? "shared" : "persona";
292
- const store = this.memoryStores()[target];
293
- try {
294
- const result = await withFileLock(this.memoryMutationLock, async (): Promise<RememberResult> => {
295
- this.assertRememberOwner();
296
- if (entry.supersedes !== undefined) return this.rememberSuperseding(entry, target);
297
- const updated = await store.update((es) => {
298
- this.assertRememberOwner();
299
- return upsertMemory(term === "short" ? pruneExpired(es, this.now()) : es, entry);
300
- });
301
- return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
302
- });
303
- if (result.ok && !this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner changed while remember was running; the write may have committed in its original scope; inspect that scope before retrying" };
304
- return result;
305
- } catch (err) {
306
- return { ok: false, reason: storageFailure(err) };
307
- }
308
- }
309
-
310
- private rememberOwnerCurrent(): boolean {
311
- try { return this.isCurrent(); } catch { return false; }
312
- }
313
-
314
- private assertRememberOwner(): void {
315
- if (!this.rememberOwnerCurrent()) throw new Error("memory owner changed; remember refused before commit");
316
- }
317
-
318
- /**
319
- * Tolerant read that must have seen every row: a clean read, an absent tier, or a full restore from a valid
320
- * backup. Rows that were preserved but hidden, a quarantine that started the tier empty, or a backup that
321
- * exists but could not be used could hold the very id being superseded, so they refuse instead of passing as
322
- * an empty tier.
323
- */
324
- private async loadCompletely(store: JsonStore<MemoryEntry>): Promise<StoreFile<MemoryEntry>> {
325
- const refuse = (detail: string): Error => new Error(`memory store ${store.filePath} was not read completely, so it cannot be checked for an ambiguous supersedes id: ${detail}`);
326
- let read;
327
- try {
328
- read = await store.loadChecked();
329
- } catch (err) {
330
- throw refuse(err instanceof Error ? err.message : String(err));
331
- }
332
- if (!read.complete) throw refuse(read.reasons.join("; "));
333
- return read.file;
334
- }
335
-
336
- /** Under the memory transaction lock: resolve across tiers, but retire only in the destination. */
337
- private async rememberSuperseding(entry: MemoryEntry, target: OptimizeTarget): Promise<RememberResult> {
338
- const store = this.memoryStores()[target];
339
- // The destination is compare-and-swapped, so only its strict snapshot may anchor the write. The other
340
- // tiers merely feed the ambiguity check, so they are read without blocking on repairable damage: a clean
341
- // read or a full restore from the backup counts. Any tier whose identities were not all checked (hidden
342
- // rows, quarantine, foreign version, I/O error) could hide the id being superseded, so it refuses, naming the store.
343
- const snapshot = await store.inspectStrict().catch((err: unknown) => {
344
- throw new Error(`destination memory store ${store.filePath}: ${(err instanceof Error ? err.message : String(err)).replace("; repair before optimizing", "; repair it before replacing a memory")}`);
345
- });
346
- const others = await Promise.all(Object.values(this.memoryStores()).filter((memoryStore) => memoryStore !== store).map((memoryStore) =>
347
- this.loadCompletely(memoryStore)));
348
- const visible = [snapshot.store, ...others].flatMap((file) => pruneExpired(file.entries, this.now()));
349
- const resolved = supersedeTargets(visible, entry.supersedes!);
350
- if (resolved.ambiguous) return { ok: false, reason: ambiguousSupersedesReason(entry.supersedes!, ambiguityCandidates(visible, entry.supersedes!)) };
351
- const active = pruneExpired(snapshot.store.entries, this.now());
352
- if (resolved.targets.length > 0 && !active.some((candidate) => memoryIdMatches(candidate, entry.supersedes!))) {
353
- return { ok: false, reason: "memory supersedes id exists only outside the destination tier; use the source's scope and lifetime to replace it" };
354
- }
355
- const retired = supersedeTargets(active, entry.supersedes!).targets.filter((candidate) => !sameMemoryContent(candidate, entry));
356
- const mutate = (entries: MemoryEntry[]) => {
357
- this.assertRememberOwner();
358
- if (isExpired(entry, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
359
- return upsertMemory(target === "project" ? pruneExpired(entries, this.now()) : entries, entry);
360
- };
361
- if (!retired.length) {
362
- const updated = await store.compareAndUpdate(snapshot.fingerprint, mutate);
363
- return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
364
- }
365
- const next = mutate(snapshot.store.entries);
366
- const after = next.find((candidate) => sameMemoryContent(candidate, entry))!;
367
- // If the new fact already exists, upsert also updates that row's metadata: retain it too.
368
- const before = active.filter((candidate) => retired.includes(candidate) || sameMemoryContent(candidate, entry));
369
- const receipt: OptimizeReceipt = { receiptId: randomUUID(), origin: "replacement", target, persona: this.scope.persona,
370
- createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: [{ before, after }] };
371
- const history = new OptimizeHistoryStore(`${store.filePath}.optimize-history.json`, this.now);
372
- const updated = await history.commit(store, snapshot.fingerprint, receipt, () => structuredClone(next), () => {
373
- this.assertRememberOwner();
374
- if (before.some((source) => isExpired(source, this.now()))) throw new Error("a superseded source expired before commit; record the current fact again");
375
- if (isExpired(after, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
376
- });
377
- return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry))!, receiptId: receipt.receiptId,
378
- ...(updated.warning ? { warning: updated.warning } : {}) };
379
- }
380
-
381
- /** Preserve repository scope unless the caller explicitly selects a broader durable tier. */
382
- async promote(id: string, target: "project" | "persona" | "shared" = "project"): Promise<{ ok: true; entry: MemoryEntry; ambiguousSupersedes?: string } | { ok: false; reason?: string }> {
383
- if (!["project", "persona", "shared"].includes(target)) return { ok: false, reason: "unknown promotion scope" };
384
- try {
385
- return await withFileLock(this.memoryMutationLock, async () => {
386
- const stm = await this.stm.load();
387
- const matches = stm.entries.filter((e) => memoryIdMatches(e, id));
388
- if (matches.length !== 1) return { ok: false, reason: "source missing or ambiguous" } as const;
389
- const found = matches[0]!;
390
- if (isExpired(found, this.now()) || found.persona !== this.scope.persona) return { ok: false, reason: "source expired or belongs to another persona" } as const;
391
- if (!isSafeMemoryContent(found)) return { ok: false, reason: "source contains unsafe memory content; promotion refused" } as const;
392
- const promoted = promoteToLong(found, this.now());
393
- if (target === "project") promoted.persona = this.scope.persona;
394
- const destination = target === "project" ? this.projectLtm : target === "shared" ? this.shared : this.ltm;
395
- // Write the durable tier FIRST, then remove from short-term: a crash between the two leaves a
396
- // harmless duplicate (collapsed by id on recall/inject) rather than losing the entry entirely.
397
- let globallyAmbiguous = false;
398
- if (promoted.supersedes !== undefined) {
399
- const loaded = await Promise.all(Object.values(this.memoryStores()).map((store) => store.load()));
400
- const visible = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
401
- globallyAmbiguous = supersedeTargets(visible, promoted.supersedes).ambiguous;
402
- }
403
- let unretired: string | undefined;
404
- const updated = await destination.update((es) => {
405
- // The lineage handle rides along from the short-term entry, so it can be one of the shared v1
406
- // ids `upsertMemory` refuses to act on. The graduation still stands, but a caller told only
407
- // "promoted" would believe the retirement happened. Re-derived per attempt: the store may
408
- // replay this mutator after lock recovery, and only the committed attempt counts.
409
- unretired = promoted.supersedes !== undefined && (globallyAmbiguous || supersedeTargets(es, promoted.supersedes).ambiguous) ? promoted.supersedes : undefined;
410
- return upsertMemory(es, promoted, unretired === undefined);
411
- });
412
- await this.stm.update((es) => es.filter((e) => !samePersistedMemory(e, found)));
413
- const entry = updated.entries.find((e) => sameMemoryContent(e, promoted)) ?? promoted;
414
- return unretired === undefined ? ({ ok: true, entry } as const) : ({ ok: true, entry, ambiguousSupersedes: unretired } as const);
415
- });
416
- } catch (err) {
417
- return { ok: false, reason: storageFailure(err) };
418
- }
419
- }
420
-
421
- /** Merge shared ⊕ persona long-term memory (the persona's entry wins on an id conflict). */
422
- private async longMemories(): Promise<MemoryEntry[]> {
423
- const [shared, persona] = await Promise.all([this.shared.load(), this.ltm.load()]);
424
- const merged = new Map<string, MemoryEntry>();
425
- for (const e of [...shared.entries, ...persona.entries]) {
426
- merged.set(memoryContentKey(e), e);
427
- }
428
- return [...merged.values()];
429
- }
430
-
431
- /** Lexical/path recall across the requested tier(s). Returns the top `max` plus the TOTAL
432
- * number of matches, so the caller can tell the model what it withheld. Short-term is pruned first. */
433
- async recall(query: string, term: Recallable, max: number): Promise<{ hits: MemoryEntry[]; total: number; withheldUnsafe: number }> {
434
- const limit = clampRecallMax(max);
435
- const stores = this.memoryStores();
436
- const loaded = await Promise.all(memoryTargets(term).map((target) => stores[target].load()));
437
- const pool = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
438
- // A fact can live in both tiers under different historical IDs (e.g. after migration) — collapse
439
- // by semantic content (keep the most-recently-seen) so it is neither returned twice nor counted.
440
- const deduped = new Map<string, MemoryEntry>();
441
- for (const e of pool) {
442
- const key = memoryContentKey(e);
443
- const previous = deduped.get(key);
444
- if (!previous || Date.parse(e.lastSeenAt) > Date.parse(previous.lastSeenAt)) deduped.set(key, e);
445
- }
446
- const all = recall([...deduped.values()], query, this.now(), { max: Number.MAX_SAFE_INTEGER });
447
- let withheldUnsafe = 0;
448
- const safe = all.map((entry) => {
449
- const guarded = safePersistedText(entry.text);
450
- if (guarded.withheld) withheldUnsafe++;
451
- return guarded.withheld ? { ...entry, text: guarded.text } : entry;
452
- });
453
- return { hits: safe.slice(0, limit), total: safe.length, withheldUnsafe };
454
- }
455
-
456
- /** Remove a memory by id from every memory tier it appears in. Returns how many were removed. */
457
- async forget(id: string, scope: MemoryReadScope = "both"): Promise<ForgetResult> {
458
- return withFileLock(this.memoryMutationLock, async () => {
459
- const allStores = this.memoryStores();
460
- const stores = memoryTargets(scope).map((target) => allStores[target]);
461
- const loaded = await Promise.all(stores.map((store) => store.load()));
462
- const matches = loaded.flatMap((result) => result.entries.filter((entry) => memoryIdMatches(entry, id)));
463
- const representatives = new Set(matches.map((entry) => memoryContentKey(entry)));
464
- // A v1 id can be ambiguous because comma-joining erased the tag boundary. Never delete two
465
- // different semantic facts merely because they share that historical handle — but hand back
466
- // the per-fact ids that DO resolve, or the refusal is a store the caller can never repair.
467
- if (representatives.size > 1) {
468
- return { removed: 0, reason: "ambiguous_id", candidates: ambiguityCandidates(loaded.flatMap((result) => result.entries), id) };
469
- }
470
- let removed = 0;
471
- for (let i = 0; i < stores.length; i++) {
472
- const selected = loaded[i]!.entries.filter((entry) => memoryIdMatches(entry, id));
473
- if (!selected.length) continue;
474
- let removedHere = 0;
475
- await stores[i]!.update((entries) => {
476
- // Imports and normal sessions share the profile lock. Still preserve out-of-band
477
- // edits made through the lower-level store: an alias never selects future facts.
478
- if (selected.some((source) => !entries.some((entry) => samePersistedMemory(entry, source)) && entries.some((entry) => entry.id === source.id))) throw new Error("selected memory changed since lookup; read again before forgetting");
479
- const kept = entries.filter((entry) => !selected.some((source) => samePersistedMemory(entry, source)));
480
- removedHere = entries.length - kept.length;
481
- return kept;
482
- });
483
- removed += removedHere;
484
- }
485
- return { removed };
486
- });
487
- }
488
-
489
- // ── backlog ───────────────────────────────────────────────────────────────
490
-
491
- /** Add a deferred intent (open). Scanned + non-empty-checked. */
492
- async backlogAdd(input: BacklogAddInput): Promise<BacklogAddResult> {
493
- const now = this.now();
494
- const text = input.text.trim();
495
- if (!text) return { ok: false, reason: "backlog text is empty" };
496
- const sizeError = validateNewTextAndTags(text, input.tags, "backlog", MAX_BACKLOG_TEXT_CHARS, MAX_BACKLOG_TAGS, MAX_BACKLOG_TAG_CHARS);
497
- if (sizeError) return { ok: false, reason: sizeError };
498
- if (!validPositiveFutureOffset(input.dueInSeconds, 1_000, now)) return { ok: false, reason: "dueInSeconds must be a finite positive duration within the supported date range" };
499
- if (!validPositiveFutureOffset(input.ttlHours, 3_600_000, now)) return { ok: false, reason: "ttlHours must be a finite positive duration within the supported date range" };
500
- const scan = scanContent(text);
501
- if (!scan.ok) return { ok: false, reason: scan.reason ?? "rejected by content scanner" };
502
- const makeInput = { text, persona: this.scope.persona } as Parameters<typeof makeBacklog>[0];
503
- if (input.tags) makeInput.tags = input.tags;
504
- if (input.dueInSeconds !== undefined) makeInput.dueInSeconds = input.dueInSeconds;
505
- if (input.ttlHours !== undefined) makeInput.ttlHours = input.ttlHours;
506
- const entry = makeBacklog(makeInput, now);
507
- try {
508
- let refused: BacklogEntry | undefined;
509
- let kept: BacklogEntry | undefined;
510
- await this.backlog.update((es) => {
511
- const existing = es.find((e) => e.id === entry.id);
512
- if (existing && existing.state !== "open") {
513
- refused = existing;
514
- return es;
515
- }
516
- if (existing) {
517
- const merged: BacklogEntry = { ...existing };
518
- if (entry.expiresAt !== undefined) merged.expiresAt = entry.expiresAt;
519
- if (entry.dueAtEpochMs !== undefined) merged.dueAtEpochMs = entry.dueAtEpochMs;
520
- kept = merged;
521
- return es.map((e) => (e.id === entry.id ? merged : e));
522
- }
523
- return [...compactTerminal(pruneExpiredBacklog(es, now)), entry];
524
- });
525
- if (refused) return { ok: false, reason: `backlog item already ${refused.state} — use a new wording, or done/drop first` };
526
- return { ok: true, entry: kept ?? entry };
527
- } catch (err) {
528
- return { ok: false, reason: storageFailure(err) };
529
- }
530
- }
531
-
532
- private async backlogView(opts: BacklogListOptions): Promise<BacklogEntry[]> {
533
- const entries = viewFor((await this.backlog.load()).entries, this.scope.persona, opts.all ?? false);
534
- const selected = opts.state ? entries.filter((e) => e.state === opts.state) : openItems(entries);
535
- return this.safeBacklog(orderBacklog(selected, this.now()));
536
- }
537
-
538
- /** The persona's unfinished view by default; `all` crosses personas and `state` selects history. */
539
- async backlogList(opts: BacklogListOptions = {}): Promise<BacklogEntry[]> {
540
- const entries = await this.backlogView(opts);
541
- return opts.max === undefined ? entries : entries.slice(0, clampBacklogMax(opts.max));
542
- }
543
-
544
- /** Bounded tool-facing backlog page with an explicit withheld count. */
545
- async backlogListPage(opts: BacklogListOptions = {}): Promise<BacklogListPage> {
546
- const entries = await this.backlogView(opts);
547
- const max = clampBacklogMax(opts.max);
548
- return { items: entries.slice(0, max), total: entries.length, withheld: Math.max(0, entries.length - max) };
549
- }
550
-
551
- /** Transition one backlog item; ok=false when the id is unknown. */
552
- async backlogSet(id: string, state: BacklogState, note?: string): Promise<BacklogSetResult> {
553
- if (note !== undefined && (typeof note !== "string" || note.length > MAX_BACKLOG_NOTE_CHARS)) {
554
- return { ok: false, reason: `backlog note exceeds ${MAX_BACKLOG_NOTE_CHARS} characters` };
555
- }
556
- if (note !== undefined) {
557
- const noteScan = scanContent(note);
558
- if (!noteScan.ok) return { ok: false, reason: `backlog note rejected: ${noteScan.reason ?? "content policy"}` };
559
- }
560
- try {
561
- let outcome: TransitionResult = { ok: false, entries: [], reason: "not_found" };
562
- const store = await this.backlog.update((es) => {
563
- outcome = transition(es, id, state, note);
564
- return outcome.entries;
565
- });
566
- if (outcome.ok) {
567
- const entry = store.entries.find((e) => e.id === id);
568
- return entry ? { ok: true, entry } : { ok: false, reason: "backlog item disappeared during update" };
569
- }
570
- if (outcome.reason === "not_found") return { ok: false, reason: "backlog item not found" };
571
- const current = store.entries.find((e) => e.id === id);
572
- if (current) {
573
- const closed = current.state === "done" || current.state === "dropped";
574
- return {
575
- ok: false,
576
- reason: closed
577
- ? `already ${current.state} — cannot ${state === "taken" ? "take" : state} a closed item`
578
- : `already ${current.state} — use done or drop`,
579
- };
580
- }
581
- return { ok: false, reason: `cannot transition backlog item to ${state}` };
582
- } catch (err) {
583
- return { ok: false, reason: storageFailure(err) };
584
- }
585
- }
586
-
587
- /** Open backlog items whose wake time has passed (for the session-start re-arm and timer fire). */
588
- async dueBacklog(): Promise<BacklogEntry[]> {
589
- const now = this.now();
590
- return openItems((await this.backlog.load()).entries)
591
- .filter((e) => e.dueAtEpochMs !== undefined && e.dueAtEpochMs <= now)
592
- .map((entry) => {
593
- const guarded = safePersistedText(entry.text);
594
- return guarded.withheld ? { ...entry, text: guarded.text } : entry;
595
- });
596
- }
597
-
598
- /**
599
- * Delete expired STM and backlog rows from disk. Call after delivering due wakes (so a lead that
600
- * expires at its due time still gets one reminder) and before injection so stale leads never
601
- * re-enter the prompt. Best-effort: a store error must not block the session.
602
- */
603
- async sweepExpired(): Promise<{ stmRemoved: number; backlogRemoved: number }> {
604
- const now = this.now();
605
- let stmRemoved = 0;
606
- let backlogRemoved = 0;
607
- try {
608
- await withFileLock(this.memoryMutationLock, async () => {
609
- const stm = await this.stm.load();
610
- const kept = pruneExpired(stm.entries, now);
611
- stmRemoved = stm.entries.length - kept.length;
612
- if (stmRemoved > 0) await this.stm.update(() => kept);
613
- });
614
- const backlog = await this.backlog.load();
615
- const keptB = pruneExpiredBacklog(backlog.entries, now);
616
- if (keptB.length < backlog.entries.length) {
617
- // Another supervisor may append or settle work after the unlocked read. Prune the
618
- // current locked state instead of replacing it with that earlier snapshot.
619
- await this.backlog.update((entries) => {
620
- const kept = pruneExpiredBacklog(entries, now);
621
- backlogRemoved = entries.length - kept.length;
622
- return kept;
623
- });
624
- }
625
- } catch {
626
- /* hygiene must not take the session down */
627
- }
628
- return { stmRemoved, backlogRemoved };
629
- }
630
-
631
- /** Acknowledge only the shown deadline; a concurrent renewal must keep its new alarm. */
632
- async acknowledgeDue(shown: readonly { id: string; dueAtEpochMs: number }[]): Promise<number> {
633
- if (shown.length === 0) return 0;
634
- const wanted = new Map(shown.map((item) => [item.id, item.dueAtEpochMs]));
635
- let cleared = 0;
636
- try {
637
- await this.backlog.update((es) =>
638
- es.map((e) => {
639
- if (e.dueAtEpochMs === undefined) return e;
640
- if (wanted.get(e.id) !== e.dueAtEpochMs) return e;
641
- if (e.state !== "open" && e.state !== "taken") return e;
642
- cleared++;
643
- const next = { ...e };
644
- delete next.dueAtEpochMs;
645
- return next;
646
- }),
647
- );
648
- return cleared;
649
- } catch {
650
- return 0;
651
- }
652
- }
653
-
654
- // ── injection ───────────────────────────────────────────────────────────────
655
-
656
- /**
657
- * Wipe THIS PROJECT's short-term memory and backlog. Long-term persona identity (private + shared)
658
- * is left intact — that is not workspace-scoped. Counts every stored STM/backlog row, including
659
- * expired notes and closed leads, because "reset" means the files are empty.
660
- */
661
- async resetWorkspace(): Promise<WorkspaceResetResult> {
662
- try {
663
- let stmRemoved = 0;
664
- let backlogRemoved = 0;
665
- await withFileLock(this.memoryMutationLock, async () => {
666
- const before = await this.stm.load();
667
- stmRemoved = before.entries.length;
668
- if (stmRemoved > 0) await this.stm.update(() => []);
669
- });
670
- const backlogBefore = await this.backlog.load();
671
- backlogRemoved = backlogBefore.entries.length;
672
- if (backlogRemoved > 0) await this.backlog.update(() => []);
673
- const ltmKept = (await this.longMemories()).length + (await this.projectLtm.load()).entries.length;
674
- return { ok: true, stmRemoved, backlogRemoved, ltmKept };
675
- } catch (err) {
676
- return { ok: false, reason: storageFailure(err) };
677
- }
678
- }
679
-
680
- /** Cheap counts for the status line and `/mind` header (expired STM and closed backlog excluded). */
681
- async summary(): Promise<{ ltm: number; projectLtm: number; stm: number; backlogOpen: number }> {
682
- const now = this.now();
683
- const [ltm, stm, backlog] = await Promise.all([this.longMemories(), this.stm.load(), this.backlog.load()]);
684
- return { ltm: ltm.length, projectLtm: (await this.projectLtm.load()).entries.length, stm: pruneExpired(stm.entries, now).length, backlogOpen: openItems(viewFor(backlog.entries, this.scope.persona, false)).length };
685
- }
686
-
687
- /**
688
- * Assemble the deterministic `<persona-mind>` block. Full mode = long-term ⊕ working-context ⊕
689
- * open backlog. `lean` mode (a DELEGATED worker leg) = the north-star + durable identity (long-term)
690
- * ONLY, dropping the supervisor's working-context (STM) and backlog: a one-shot worker is not the
691
- * persona, so it inherits who the persona IS but not the supervisor's project state or deferred
692
- * intent. (The caller also withholds the write tools + wakes from a leg — see index.ts.)
693
- */
694
- async buildInjection(opts: { lean?: boolean; query?: string; fixedBlocks?: readonly string[]; cleanup?: boolean; leanReferenceTime?: number } = {}): Promise<string> {
695
- // Workers inherit a read-only lean block; they must not mutate the supervisor's stores.
696
- // A background import may own the profile lock while awaiting another store writer. Reads
697
- // already filter expiry; defer disk hygiene until a later turn rather than joining that import.
698
- if (!opts.lean && opts.cleanup !== false) await this.sweepExpired();
699
- const now = this.now();
700
- const context = { ...(opts.query === undefined ? {} : { query: opts.query }), ...(opts.fixedBlocks === undefined ? {} : { fixedBlocks: opts.fixedBlocks }) };
701
- if (opts.lean || this.scope.homeWorkspace) {
702
- const ltm = this.safeMemories(await this.longMemories(), "long-term");
703
- if (opts.lean) {
704
- return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now: opts.leanReferenceTime ?? now, lean: true, ...context, ...(this.budget ? { budget: this.budget } : {}) });
705
- }
706
- return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now, ...context, ...(this.budget ? { budget: this.budget } : {}) });
707
- }
708
- const [ltm, projectRaw, stmRaw, backlogRaw] = await Promise.all([this.longMemories(), this.projectLtm.load(), this.stm.load(), this.backlog.load()]);
709
- return renderMind({
710
- persona: this.scope.persona,
711
- ltm: this.safeMemories(ltm, "long-term"),
712
- projectLtm: this.safeMemories(projectRaw.entries, "project long-term"),
713
- ...context,
714
- stm: this.safeMemories(pruneExpired(stmRaw.entries, now), "short-term"),
715
- backlog: this.safeBacklog(orderBacklog(openItems(viewFor(backlogRaw.entries, this.scope.persona, false)), now)),
716
- now,
717
- ...(this.budget ? { budget: this.budget } : {}),
718
- });
719
- }
720
- }
1
+ /**
2
+ * MindService — the integration heart: it binds the durable stores (store.ts) to the resolved
3
+ * scope (scope.ts) and the pure faculties (memory.ts / backlog.ts / inject.ts), and exposes the
4
+ * high-level operations the Pi tools and hooks call. It has NO Pi imports, so it is fully
5
+ * unit-testable over real temp files without a running agent.
6
+ *
7
+ * Five JSON stores back one scope: persona/shared durable memory, durable repository knowledge,
8
+ * short-term (48h, auto-deleted) memory for the project, and the project backlog
9
+ * (same default life; a later wake extends it).
10
+ */
11
+
12
+ import { randomUUID } from "node:crypto";
13
+ import type { BacklogEntry, BacklogState, TransitionResult } from "./backlog.ts";
14
+ import { clampBacklogMax, compactTerminal, makeBacklog, openItems, orderBacklog, pruneExpired as pruneExpiredBacklog, transition, validateBacklog, viewFor, MAX_BACKLOG_NOTE_CHARS, MAX_BACKLOG_TAGS, MAX_BACKLOG_TAG_CHARS, MAX_BACKLOG_TEXT_CHARS } from "./backlog.ts";
15
+ import { contentId } from "./ids.ts";
16
+ import type { MindBudget } from "./inject.ts";
17
+ import { renderMind } from "./inject.ts";
18
+ import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope } from "./memory-read.ts";
19
+ import { MemoryOptimizer } from "./optimize-service.ts";
20
+ import { OptimizeHistoryStore, type OptimizeReceipt } from "./optimize-history.ts";
21
+ import { samePersistedMemory, type OptimizeTarget } from "./optimize.ts";
22
+ import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
23
+ import { clampRecallMax, isExpired, isMemoryId, isSafeMemoryContent, makeMemory, memoryContentKey, memoryIdMatches, promoteToLong, pruneExpired, recall, sameMemoryContent, supersedeTargets, upsertMemory, validateLongMemory, validateShortMemory, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS } from "./memory.ts";
24
+ import { scanContent } from "./scanner.ts";
25
+ import { memoryMutationLockPath, type Scope } from "./scope.ts";
26
+ import { JsonStore, type JsonStoreOptions, type StoreFile, withFileLock } from "./store.ts";
27
+
28
+ const STORE_VERSION = 1;
29
+
30
+ /** How many per-fact ids an ambiguity refusal spells out before it summarizes the remainder. */
31
+ const MAX_AMBIGUITY_IDS_IN_REASON = 5;
32
+
33
+ export interface MindServiceOptions {
34
+ now?: () => number;
35
+ onWarn?: (message: string) => void;
36
+ budget?: MindBudget;
37
+ /** Runtime owner snapshot for remember admission/commit; omitted by standalone store callers. */
38
+ isCurrent?: () => boolean;
39
+ }
40
+
41
+ interface RememberInputBase {
42
+ kind: MemoryKind;
43
+ text: string;
44
+ tags?: string[];
45
+ ttlHours?: number;
46
+ supersedes?: string;
47
+ source?: string;
48
+ derivedFrom?: string[];
49
+ }
50
+
51
+ /** Long writes name their destination; short working memory is project-scoped by default. */
52
+ export type RememberInput =
53
+ | (RememberInputBase & { term: "long"; scope: "project" | "persona" | "shared" })
54
+ | (RememberInputBase & { term: "short"; scope?: "project" });
55
+
56
+ export interface BacklogAddInput {
57
+ text: string;
58
+ tags?: string[];
59
+ dueInSeconds?: number;
60
+ ttlHours?: number;
61
+ }
62
+
63
+ export interface BacklogListOptions {
64
+ all?: boolean;
65
+ state?: BacklogState;
66
+ /** Optional page size; omitted for the compatibility view, bounded pages use `backlogListPage`. */
67
+ max?: number;
68
+ }
69
+
70
+ export interface BacklogListPage {
71
+ items: BacklogEntry[];
72
+ total: number;
73
+ withheld: number;
74
+ }
75
+
76
+ export type Recallable = MemoryReadScope;
77
+
78
+ /** One of the distinct facts a shared historical handle addresses, named by an id of its own. */
79
+ export interface AmbiguousMemory {
80
+ /** This fact's CURRENT content id. Distinct facts always hash differently, so it names one entry. */
81
+ id: string;
82
+ kind: MemoryKind;
83
+ text: string;
84
+ /** False while this id is still the shared handle itself — the one legacy-encodable member of the
85
+ * collision keeps the ambiguous id as its own, and becomes addressable once the others are gone. */
86
+ resolves: boolean;
87
+ }
88
+
89
+ export type RememberResult = { ok: true; entry: MemoryEntry; receiptId?: string; warning?: string } | { ok: false; reason: string };
90
+ export type BacklogAddResult = { ok: true; entry: BacklogEntry } | { ok: false; reason: string };
91
+ export type BacklogSetResult = { ok: true; entry: BacklogEntry } | { ok: false; reason?: string };
92
+ export type ForgetResult = { removed: number; reason?: "ambiguous_id"; candidates?: AmbiguousMemory[] };
93
+ export type WorkspaceResetResult =
94
+ | { ok: true; stmRemoved: number; backlogRemoved: number; ltmKept: number }
95
+ | { ok: false; reason: string };
96
+
97
+ function storageFailure(err: unknown): string {
98
+ const message = err instanceof Error ? err.message : String(err);
99
+ return `storage error: ${message || "unknown persistence failure"}`;
100
+ }
101
+
102
+ /**
103
+ * The distinct facts a shared handle addresses, each named by an id of its OWN. A refusal that offers
104
+ * no way forward is a dead end: destroying nothing is right, but the caller still has to be able to
105
+ * pick one. Distinct facts always hash to distinct current ids, so every member of a collision is
106
+ * nameable — except the single member whose v1 and v2 encodings coincide (that id IS the shared
107
+ * handle), which becomes addressable as soon as its neighbours are gone.
108
+ */
109
+ function ambiguityCandidates(pool: readonly MemoryEntry[], id: string): AmbiguousMemory[] {
110
+ const distinct = new Map<string, MemoryEntry>();
111
+ for (const entry of pool) if (memoryIdMatches(entry, id)) distinct.set(memoryContentKey(entry), entry);
112
+ return [...distinct.values()]
113
+ .map((entry) => {
114
+ const handle = contentId(entry.kind, entry.text, entry.tags);
115
+ const reached = new Set(pool.filter((e) => memoryIdMatches(e, handle)).map((e) => memoryContentKey(e)));
116
+ return { id: handle, kind: entry.kind, text: safePersistedText(entry.text).text, resolves: reached.size === 1 };
117
+ })
118
+ .sort((a, b) => Number(b.resolves) - Number(a.resolves));
119
+ }
120
+
121
+ function ambiguousSupersedesReason(id: string, candidates: readonly AmbiguousMemory[]): string {
122
+ // The reason is read by the model, so the offer list is bounded rather than as long as the collision.
123
+ const shown = candidates.slice(0, MAX_AMBIGUITY_IDS_IN_REASON);
124
+ const offers = shown.map((c) => (c.resolves ? c.id : `${c.id} (still the shared handle — usable once the others are gone)`)).join(", ");
125
+ const rest = candidates.length - shown.length;
126
+ return `memory supersedes id ${id} is ambiguous — it addresses ${candidates.length} distinct stored memories; supersede one of them by its own current id instead: ${offers}${rest > 0 ? `, and ${rest} more` : ""}`;
127
+ }
128
+
129
+ function safePersistedText(text: string): { text: string; withheld: boolean } {
130
+ const scan = scanContent(text);
131
+ return scan.ok
132
+ ? { text, withheld: false }
133
+ : { text: `[withheld unsafe stored content — ${scan.reason ?? "content policy"}]`, withheld: true };
134
+ }
135
+
136
+ function validateNewTextAndTags(text: string, tags: readonly string[] | undefined, label: string, maxText: number, maxTags: number, maxTagChars: number): string | undefined {
137
+ if (text.length > maxText) return `${label} text exceeds ${maxText} characters`;
138
+ if (tags === undefined) return undefined;
139
+ if (!Array.isArray(tags)) return `${label} tags must be an array`;
140
+ if (tags.length > maxTags) return `${label} has more than ${maxTags} tags`;
141
+ if (tags.some((tag) => typeof tag !== "string" || tag.length > maxTagChars)) return `${label} tag exceeds ${maxTagChars} characters`;
142
+ for (const tag of tags) {
143
+ const scan = scanContent(tag);
144
+ if (!scan.ok) return `${label} tag rejected: ${scan.reason ?? "content policy"}`;
145
+ }
146
+ return undefined;
147
+ }
148
+
149
+ function validPositiveFutureOffset(value: number | undefined, unitMs: number, now: number): boolean {
150
+ if (value === undefined) return true;
151
+ if (!Number.isFinite(value) || value <= 0) return false;
152
+ const target = now + value * unitMs;
153
+ return Number.isFinite(target) && Number.isFinite(new Date(target).getTime());
154
+ }
155
+
156
+ export class MindService {
157
+ private readonly scope: Scope;
158
+ private readonly now: () => number;
159
+ private readonly budget: MindBudget | undefined;
160
+ private readonly ltm: JsonStore<MemoryEntry>;
161
+ private readonly shared: JsonStore<MemoryEntry>;
162
+ private readonly projectLtm: JsonStore<MemoryEntry>;
163
+ private readonly stm: JsonStore<MemoryEntry>;
164
+ private readonly backlog: JsonStore<BacklogEntry>;
165
+ private readonly memoryMutationLock: string;
166
+ private readonly warn: (message: string) => void;
167
+ private readonly isCurrent: () => boolean;
168
+
169
+ constructor(
170
+ scope: Scope,
171
+ opts: MindServiceOptions = {},
172
+ ) {
173
+ this.scope = scope;
174
+ this.now = opts.now ?? Date.now;
175
+ this.budget = opts.budget;
176
+ this.warn = opts.onWarn ?? (() => {});
177
+ this.isCurrent = opts.isCurrent ?? (() => true);
178
+ const longOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateLongMemory, now: this.now };
179
+ const shortOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateShortMemory, now: this.now };
180
+ const backlogOpts: JsonStoreOptions<BacklogEntry> = { version: STORE_VERSION, validateEntry: validateBacklog, now: this.now };
181
+ if (opts.onWarn) {
182
+ longOpts.onWarn = opts.onWarn;
183
+ shortOpts.onWarn = opts.onWarn;
184
+ backlogOpts.onWarn = opts.onWarn;
185
+ }
186
+ this.ltm = new JsonStore<MemoryEntry>(scope.paths.ltm, longOpts);
187
+ this.shared = new JsonStore<MemoryEntry>(scope.paths.shared, longOpts);
188
+ this.projectLtm = new JsonStore<MemoryEntry>(scope.paths.projectLtm, longOpts);
189
+ this.stm = new JsonStore<MemoryEntry>(scope.paths.stm, shortOpts);
190
+ this.backlog = new JsonStore<BacklogEntry>(scope.paths.backlog, backlogOpts);
191
+ // Persona/shared facts span workspaces. All multi-store memory decisions must serialize
192
+ // within the agent profile, including ambiguity checks before promote/forget/supersede.
193
+ this.memoryMutationLock = memoryMutationLockPath(scope.paths);
194
+ }
195
+
196
+ private safeMemories(entries: readonly MemoryEntry[], tier: string): MemoryEntry[] {
197
+ let withheld = 0;
198
+ const safe = entries.map((entry) => {
199
+ const guarded = safePersistedText(entry.text);
200
+ if (!guarded.withheld) return entry;
201
+ withheld++;
202
+ return { ...entry, text: guarded.text };
203
+ });
204
+ if (withheld > 0) this.warn(`${withheld} unsafe persisted ${tier} memor${withheld === 1 ? "y was" : "ies were"} withheld from model context`);
205
+ return safe;
206
+ }
207
+
208
+ private safeBacklog(entries: readonly BacklogEntry[]): BacklogEntry[] {
209
+ let withheld = 0;
210
+ const safe = entries.map((entry) => {
211
+ const text = safePersistedText(entry.text);
212
+ const note = entry.note === undefined ? undefined : safePersistedText(entry.note);
213
+ if (!text.withheld && !note?.withheld) return entry;
214
+ withheld++;
215
+ return {
216
+ ...entry,
217
+ text: text.text,
218
+ ...(note ? { note: note.text } : {}),
219
+ };
220
+ });
221
+ if (withheld > 0) this.warn(`${withheld} unsafe persisted backlog item${withheld === 1 ? " was" : "s were"} withheld from model context`);
222
+ return safe;
223
+ }
224
+
225
+ // ── memory ────────────────────────────────────────────────────────────────
226
+
227
+ private memoryStores() {
228
+ return { project: this.stm, "project-long": this.projectLtm, persona: this.ltm, shared: this.shared };
229
+ }
230
+
231
+ /** One plan cache per native session owner. Lifecycle adapters must invalidate/discard it. */
232
+ createOptimizer(): MemoryOptimizer {
233
+ return new MemoryOptimizer({ stores: this.memoryStores(), persona: this.scope.persona, now: this.now, mutationLock: this.memoryMutationLock });
234
+ }
235
+
236
+ /** Read-only identity snapshot for inspection and native recording receipts; no store paths or IO. */
237
+ inspectionScope(): Pick<Scope, "persona" | "projectRoot" | "homeWorkspace"> {
238
+ return { persona: this.scope.persona, projectRoot: this.scope.projectRoot, ...(this.scope.homeWorkspace ? { homeWorkspace: true as const } : {}) };
239
+ }
240
+
241
+ /** Explicit full retrieval; reads never refresh age/expiry or repair malformed stores. */
242
+ readMemory(id: string, scope: MemoryReadScope = "both"): Promise<MemoryReadResult> {
243
+ return readMemory(this.memoryStores(), id, scope, this.now());
244
+ }
245
+
246
+ /** Store a memory (long or short term). Scanned + non-empty-checked before it is persisted. */
247
+ async remember(input: RememberInput): Promise<RememberResult> {
248
+ if (!this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner is unavailable; no memory was stored" };
249
+ if (input.term !== "long" && input.term !== "short") return { ok: false, reason: "unknown memory term" };
250
+ if (input.scope !== undefined && !["project", "persona", "shared"].includes(input.scope)) return { ok: false, reason: "unknown memory scope" };
251
+ if (input.term === "long" && input.scope === undefined) return { ok: false, reason: "long-term memory requires an explicit scope: project, persona, or shared" };
252
+ if (input.term === "short" && input.scope !== undefined && input.scope !== "project") return { ok: false, reason: "short-term memory belongs to the project" };
253
+ const now = this.now();
254
+ const text = input.text.trim();
255
+ if (!text) return { ok: false, reason: "memory text is empty" };
256
+ const sizeError = validateNewTextAndTags(text, input.tags, "memory", MAX_MEMORY_TEXT_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS);
257
+ if (sizeError) return { ok: false, reason: sizeError };
258
+ if (input.source !== undefined && (typeof input.source !== "string" || input.source.length > MAX_MEMORY_SOURCE_CHARS)) {
259
+ return { ok: false, reason: `memory source exceeds ${MAX_MEMORY_SOURCE_CHARS} characters` };
260
+ }
261
+ if (input.source !== undefined) {
262
+ const sourceScan = scanContent(input.source);
263
+ if (!sourceScan.ok) return { ok: false, reason: `memory source rejected: ${sourceScan.reason ?? "content policy"}` };
264
+ }
265
+ if (input.supersedes !== undefined && !isMemoryId(input.supersedes)) {
266
+ return { ok: false, reason: `memory supersedes id must be one safe token of at most ${MAX_MEMORY_ID_CHARS} characters` };
267
+ }
268
+ if (input.derivedFrom !== undefined) {
269
+ if (!Array.isArray(input.derivedFrom) || input.derivedFrom.length > MAX_MEMORY_DERIVED_IDS) {
270
+ return { ok: false, reason: `memory has more than ${MAX_MEMORY_DERIVED_IDS} derived ids` };
271
+ }
272
+ if (input.derivedFrom.some((id) => !isMemoryId(id))) {
273
+ return { ok: false, reason: `memory derived id must be one safe token of at most ${MAX_MEMORY_ID_CHARS} characters` };
274
+ }
275
+ }
276
+ if (!validPositiveFutureOffset(input.ttlHours, 3_600_000, now)) return { ok: false, reason: "ttlHours must be a finite positive duration within the supported date range" };
277
+ const scan = scanContent(text);
278
+ if (!scan.ok) return { ok: false, reason: scan.reason ?? "rejected by content scanner" };
279
+
280
+ // Kind describes content; only the caller-selected term controls lifetime.
281
+ const term = input.term;
282
+ const makeInput: MemoryInput = { term, kind: input.kind, text };
283
+ if (input.tags) makeInput.tags = input.tags;
284
+ if (input.ttlHours !== undefined) makeInput.ttlHours = input.ttlHours;
285
+ if (input.supersedes) makeInput.supersedes = input.supersedes;
286
+ if (input.source) makeInput.source = input.source;
287
+ if (input.derivedFrom && input.derivedFrom.length > 0) makeInput.derivedFrom = input.derivedFrom;
288
+ if (term === "short" || input.scope === "project") makeInput.persona = this.scope.persona;
289
+
290
+ const entry = makeMemory(makeInput, now);
291
+ const target: OptimizeTarget = term === "short" ? "project" : input.scope === "project" ? "project-long" : input.scope === "shared" ? "shared" : "persona";
292
+ const store = this.memoryStores()[target];
293
+ try {
294
+ const result = await withFileLock(this.memoryMutationLock, async (): Promise<RememberResult> => {
295
+ this.assertRememberOwner();
296
+ if (entry.supersedes !== undefined) return this.rememberSuperseding(entry, target);
297
+ const updated = await store.update((es) => {
298
+ this.assertRememberOwner();
299
+ return upsertMemory(term === "short" ? pruneExpired(es, this.now()) : es, entry);
300
+ });
301
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
302
+ });
303
+ if (result.ok && !this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner changed while remember was running; the write may have committed in its original scope; inspect that scope before retrying" };
304
+ return result;
305
+ } catch (err) {
306
+ return { ok: false, reason: storageFailure(err) };
307
+ }
308
+ }
309
+
310
+ private rememberOwnerCurrent(): boolean {
311
+ try { return this.isCurrent(); } catch { return false; }
312
+ }
313
+
314
+ private assertRememberOwner(): void {
315
+ if (!this.rememberOwnerCurrent()) throw new Error("memory owner changed; remember refused before commit");
316
+ }
317
+
318
+ /**
319
+ * Tolerant read that must have seen every row: a clean read, an absent tier, or a full restore from a valid
320
+ * backup. Rows that were preserved but hidden, a quarantine that started the tier empty, or a backup that
321
+ * exists but could not be used could hold the very id being superseded, so they refuse instead of passing as
322
+ * an empty tier.
323
+ */
324
+ private async loadCompletely(store: JsonStore<MemoryEntry>): Promise<StoreFile<MemoryEntry>> {
325
+ const refuse = (detail: string): Error => new Error(`memory store ${store.filePath} was not read completely, so it cannot be checked for an ambiguous supersedes id: ${detail}`);
326
+ let read;
327
+ try {
328
+ read = await store.loadChecked();
329
+ } catch (err) {
330
+ throw refuse(err instanceof Error ? err.message : String(err));
331
+ }
332
+ if (!read.complete) throw refuse(read.reasons.join("; "));
333
+ return read.file;
334
+ }
335
+
336
+ /** Under the memory transaction lock: resolve across tiers, but retire only in the destination. */
337
+ private async rememberSuperseding(entry: MemoryEntry, target: OptimizeTarget): Promise<RememberResult> {
338
+ const store = this.memoryStores()[target];
339
+ // The destination is compare-and-swapped, so only its strict snapshot may anchor the write. The other
340
+ // tiers merely feed the ambiguity check, so they are read without blocking on repairable damage: a clean
341
+ // read or a full restore from the backup counts. Any tier whose identities were not all checked (hidden
342
+ // rows, quarantine, foreign version, I/O error) could hide the id being superseded, so it refuses, naming the store.
343
+ const snapshot = await store.inspectStrict().catch((err: unknown) => {
344
+ throw new Error(`destination memory store ${store.filePath}: ${(err instanceof Error ? err.message : String(err)).replace("; repair before optimizing", "; repair it before replacing a memory")}`);
345
+ });
346
+ const others = await Promise.all(Object.values(this.memoryStores()).filter((memoryStore) => memoryStore !== store).map((memoryStore) =>
347
+ this.loadCompletely(memoryStore)));
348
+ const visible = [snapshot.store, ...others].flatMap((file) => pruneExpired(file.entries, this.now()));
349
+ const resolved = supersedeTargets(visible, entry.supersedes!);
350
+ if (resolved.ambiguous) return { ok: false, reason: ambiguousSupersedesReason(entry.supersedes!, ambiguityCandidates(visible, entry.supersedes!)) };
351
+ const active = pruneExpired(snapshot.store.entries, this.now());
352
+ if (resolved.targets.length > 0 && !active.some((candidate) => memoryIdMatches(candidate, entry.supersedes!))) {
353
+ return { ok: false, reason: "memory supersedes id exists only outside the destination tier; use the source's scope and lifetime to replace it" };
354
+ }
355
+ const retired = supersedeTargets(active, entry.supersedes!).targets.filter((candidate) => !sameMemoryContent(candidate, entry));
356
+ const mutate = (entries: MemoryEntry[]) => {
357
+ this.assertRememberOwner();
358
+ if (isExpired(entry, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
359
+ return upsertMemory(target === "project" ? pruneExpired(entries, this.now()) : entries, entry);
360
+ };
361
+ if (!retired.length) {
362
+ const updated = await store.compareAndUpdate(snapshot.fingerprint, mutate);
363
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
364
+ }
365
+ const next = mutate(snapshot.store.entries);
366
+ const after = next.find((candidate) => sameMemoryContent(candidate, entry))!;
367
+ // If the new fact already exists, upsert also updates that row's metadata: retain it too.
368
+ const before = active.filter((candidate) => retired.includes(candidate) || sameMemoryContent(candidate, entry));
369
+ const receipt: OptimizeReceipt = { receiptId: randomUUID(), origin: "replacement", target, persona: this.scope.persona,
370
+ createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: [{ before, after }] };
371
+ const history = new OptimizeHistoryStore(`${store.filePath}.optimize-history.json`, this.now);
372
+ const updated = await history.commit(store, snapshot.fingerprint, receipt, () => structuredClone(next), () => {
373
+ this.assertRememberOwner();
374
+ if (before.some((source) => isExpired(source, this.now()))) throw new Error("a superseded source expired before commit; record the current fact again");
375
+ if (isExpired(after, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
376
+ });
377
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry))!, receiptId: receipt.receiptId,
378
+ ...(updated.warning ? { warning: updated.warning } : {}) };
379
+ }
380
+
381
+ /** Preserve repository scope unless the caller explicitly selects a broader durable tier. */
382
+ async promote(id: string, target: "project" | "persona" | "shared" = "project"): Promise<{ ok: true; entry: MemoryEntry; ambiguousSupersedes?: string } | { ok: false; reason?: string }> {
383
+ if (!["project", "persona", "shared"].includes(target)) return { ok: false, reason: "unknown promotion scope" };
384
+ try {
385
+ return await withFileLock(this.memoryMutationLock, async () => {
386
+ const stm = await this.stm.load();
387
+ const matches = stm.entries.filter((e) => memoryIdMatches(e, id));
388
+ if (matches.length !== 1) return { ok: false, reason: "source missing or ambiguous" } as const;
389
+ const found = matches[0]!;
390
+ if (isExpired(found, this.now()) || found.persona !== this.scope.persona) return { ok: false, reason: "source expired or belongs to another persona" } as const;
391
+ if (!isSafeMemoryContent(found)) return { ok: false, reason: "source contains unsafe memory content; promotion refused" } as const;
392
+ const promoted = promoteToLong(found, this.now());
393
+ if (target === "project") promoted.persona = this.scope.persona;
394
+ const destination = target === "project" ? this.projectLtm : target === "shared" ? this.shared : this.ltm;
395
+ // Write the durable tier FIRST, then remove from short-term: a crash between the two leaves a
396
+ // harmless duplicate (collapsed by id on recall/inject) rather than losing the entry entirely.
397
+ let globallyAmbiguous = false;
398
+ if (promoted.supersedes !== undefined) {
399
+ const loaded = await Promise.all(Object.values(this.memoryStores()).map((store) => store.load()));
400
+ const visible = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
401
+ globallyAmbiguous = supersedeTargets(visible, promoted.supersedes).ambiguous;
402
+ }
403
+ let unretired: string | undefined;
404
+ const updated = await destination.update((es) => {
405
+ // The lineage handle rides along from the short-term entry, so it can be one of the shared v1
406
+ // ids `upsertMemory` refuses to act on. The graduation still stands, but a caller told only
407
+ // "promoted" would believe the retirement happened. Re-derived per attempt: the store may
408
+ // replay this mutator after lock recovery, and only the committed attempt counts.
409
+ unretired = promoted.supersedes !== undefined && (globallyAmbiguous || supersedeTargets(es, promoted.supersedes).ambiguous) ? promoted.supersedes : undefined;
410
+ return upsertMemory(es, promoted, unretired === undefined);
411
+ });
412
+ await this.stm.update((es) => es.filter((e) => !samePersistedMemory(e, found)));
413
+ const entry = updated.entries.find((e) => sameMemoryContent(e, promoted)) ?? promoted;
414
+ return unretired === undefined ? ({ ok: true, entry } as const) : ({ ok: true, entry, ambiguousSupersedes: unretired } as const);
415
+ });
416
+ } catch (err) {
417
+ return { ok: false, reason: storageFailure(err) };
418
+ }
419
+ }
420
+
421
+ /** Merge shared ⊕ persona long-term memory (the persona's entry wins on an id conflict). */
422
+ private async longMemories(): Promise<MemoryEntry[]> {
423
+ const [shared, persona] = await Promise.all([this.shared.load(), this.ltm.load()]);
424
+ const merged = new Map<string, MemoryEntry>();
425
+ for (const e of [...shared.entries, ...persona.entries]) {
426
+ merged.set(memoryContentKey(e), e);
427
+ }
428
+ return [...merged.values()];
429
+ }
430
+
431
+ /** Lexical/path recall across the requested tier(s). Returns the top `max` plus the TOTAL
432
+ * number of matches, so the caller can tell the model what it withheld. Short-term is pruned first. */
433
+ async recall(query: string, term: Recallable, max: number): Promise<{ hits: MemoryEntry[]; total: number; withheldUnsafe: number }> {
434
+ const limit = clampRecallMax(max);
435
+ const stores = this.memoryStores();
436
+ const loaded = await Promise.all(memoryTargets(term).map((target) => stores[target].load()));
437
+ const pool = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
438
+ // A fact can live in both tiers under different historical IDs (e.g. after migration) — collapse
439
+ // by semantic content (keep the most-recently-seen) so it is neither returned twice nor counted.
440
+ const deduped = new Map<string, MemoryEntry>();
441
+ for (const e of pool) {
442
+ const key = memoryContentKey(e);
443
+ const previous = deduped.get(key);
444
+ if (!previous || Date.parse(e.lastSeenAt) > Date.parse(previous.lastSeenAt)) deduped.set(key, e);
445
+ }
446
+ const all = recall([...deduped.values()], query, this.now(), { max: Number.MAX_SAFE_INTEGER });
447
+ let withheldUnsafe = 0;
448
+ const safe = all.map((entry) => {
449
+ const guarded = safePersistedText(entry.text);
450
+ if (guarded.withheld) withheldUnsafe++;
451
+ return guarded.withheld ? { ...entry, text: guarded.text } : entry;
452
+ });
453
+ return { hits: safe.slice(0, limit), total: safe.length, withheldUnsafe };
454
+ }
455
+
456
+ /** Remove a memory by id from every memory tier it appears in. Returns how many were removed. */
457
+ async forget(id: string, scope: MemoryReadScope = "both"): Promise<ForgetResult> {
458
+ return withFileLock(this.memoryMutationLock, async () => {
459
+ const allStores = this.memoryStores();
460
+ const stores = memoryTargets(scope).map((target) => allStores[target]);
461
+ const loaded = await Promise.all(stores.map((store) => store.load()));
462
+ const matches = loaded.flatMap((result) => result.entries.filter((entry) => memoryIdMatches(entry, id)));
463
+ const representatives = new Set(matches.map((entry) => memoryContentKey(entry)));
464
+ // A v1 id can be ambiguous because comma-joining erased the tag boundary. Never delete two
465
+ // different semantic facts merely because they share that historical handle — but hand back
466
+ // the per-fact ids that DO resolve, or the refusal is a store the caller can never repair.
467
+ if (representatives.size > 1) {
468
+ return { removed: 0, reason: "ambiguous_id", candidates: ambiguityCandidates(loaded.flatMap((result) => result.entries), id) };
469
+ }
470
+ let removed = 0;
471
+ for (let i = 0; i < stores.length; i++) {
472
+ const selected = loaded[i]!.entries.filter((entry) => memoryIdMatches(entry, id));
473
+ if (!selected.length) continue;
474
+ let removedHere = 0;
475
+ await stores[i]!.update((entries) => {
476
+ // Imports and normal sessions share the profile lock. Still preserve out-of-band
477
+ // edits made through the lower-level store: an alias never selects future facts.
478
+ if (selected.some((source) => !entries.some((entry) => samePersistedMemory(entry, source)) && entries.some((entry) => entry.id === source.id))) throw new Error("selected memory changed since lookup; read again before forgetting");
479
+ const kept = entries.filter((entry) => !selected.some((source) => samePersistedMemory(entry, source)));
480
+ removedHere = entries.length - kept.length;
481
+ return kept;
482
+ });
483
+ removed += removedHere;
484
+ }
485
+ return { removed };
486
+ });
487
+ }
488
+
489
+ // ── backlog ───────────────────────────────────────────────────────────────
490
+
491
+ /** Add a deferred intent (open). Scanned + non-empty-checked. */
492
+ async backlogAdd(input: BacklogAddInput): Promise<BacklogAddResult> {
493
+ const now = this.now();
494
+ const text = input.text.trim();
495
+ if (!text) return { ok: false, reason: "backlog text is empty" };
496
+ const sizeError = validateNewTextAndTags(text, input.tags, "backlog", MAX_BACKLOG_TEXT_CHARS, MAX_BACKLOG_TAGS, MAX_BACKLOG_TAG_CHARS);
497
+ if (sizeError) return { ok: false, reason: sizeError };
498
+ if (!validPositiveFutureOffset(input.dueInSeconds, 1_000, now)) return { ok: false, reason: "dueInSeconds must be a finite positive duration within the supported date range" };
499
+ if (!validPositiveFutureOffset(input.ttlHours, 3_600_000, now)) return { ok: false, reason: "ttlHours must be a finite positive duration within the supported date range" };
500
+ const scan = scanContent(text);
501
+ if (!scan.ok) return { ok: false, reason: scan.reason ?? "rejected by content scanner" };
502
+ const makeInput = { text, persona: this.scope.persona } as Parameters<typeof makeBacklog>[0];
503
+ if (input.tags) makeInput.tags = input.tags;
504
+ if (input.dueInSeconds !== undefined) makeInput.dueInSeconds = input.dueInSeconds;
505
+ if (input.ttlHours !== undefined) makeInput.ttlHours = input.ttlHours;
506
+ const entry = makeBacklog(makeInput, now);
507
+ try {
508
+ let refused: BacklogEntry | undefined;
509
+ let kept: BacklogEntry | undefined;
510
+ await this.backlog.update((es) => {
511
+ const existing = es.find((e) => e.id === entry.id);
512
+ if (existing && existing.state !== "open") {
513
+ refused = existing;
514
+ return es;
515
+ }
516
+ if (existing) {
517
+ const merged: BacklogEntry = { ...existing };
518
+ if (entry.expiresAt !== undefined) merged.expiresAt = entry.expiresAt;
519
+ if (entry.dueAtEpochMs !== undefined) merged.dueAtEpochMs = entry.dueAtEpochMs;
520
+ kept = merged;
521
+ return es.map((e) => (e.id === entry.id ? merged : e));
522
+ }
523
+ return [...compactTerminal(pruneExpiredBacklog(es, now)), entry];
524
+ });
525
+ if (refused) return { ok: false, reason: `backlog item already ${refused.state} — use a new wording, or done/drop first` };
526
+ return { ok: true, entry: kept ?? entry };
527
+ } catch (err) {
528
+ return { ok: false, reason: storageFailure(err) };
529
+ }
530
+ }
531
+
532
+ private async backlogView(opts: BacklogListOptions): Promise<BacklogEntry[]> {
533
+ const entries = viewFor((await this.backlog.load()).entries, this.scope.persona, opts.all ?? false);
534
+ const selected = opts.state ? entries.filter((e) => e.state === opts.state) : openItems(entries);
535
+ return this.safeBacklog(orderBacklog(selected, this.now()));
536
+ }
537
+
538
+ /** The persona's unfinished view by default; `all` crosses personas and `state` selects history. */
539
+ async backlogList(opts: BacklogListOptions = {}): Promise<BacklogEntry[]> {
540
+ const entries = await this.backlogView(opts);
541
+ return opts.max === undefined ? entries : entries.slice(0, clampBacklogMax(opts.max));
542
+ }
543
+
544
+ /** Bounded tool-facing backlog page with an explicit withheld count. */
545
+ async backlogListPage(opts: BacklogListOptions = {}): Promise<BacklogListPage> {
546
+ const entries = await this.backlogView(opts);
547
+ const max = clampBacklogMax(opts.max);
548
+ return { items: entries.slice(0, max), total: entries.length, withheld: Math.max(0, entries.length - max) };
549
+ }
550
+
551
+ /** Transition one backlog item; ok=false when the id is unknown. */
552
+ async backlogSet(id: string, state: BacklogState, note?: string): Promise<BacklogSetResult> {
553
+ if (note !== undefined && (typeof note !== "string" || note.length > MAX_BACKLOG_NOTE_CHARS)) {
554
+ return { ok: false, reason: `backlog note exceeds ${MAX_BACKLOG_NOTE_CHARS} characters` };
555
+ }
556
+ if (note !== undefined) {
557
+ const noteScan = scanContent(note);
558
+ if (!noteScan.ok) return { ok: false, reason: `backlog note rejected: ${noteScan.reason ?? "content policy"}` };
559
+ }
560
+ try {
561
+ let outcome: TransitionResult = { ok: false, entries: [], reason: "not_found" };
562
+ const store = await this.backlog.update((es) => {
563
+ outcome = transition(es, id, state, note);
564
+ return outcome.entries;
565
+ });
566
+ if (outcome.ok) {
567
+ const entry = store.entries.find((e) => e.id === id);
568
+ return entry ? { ok: true, entry } : { ok: false, reason: "backlog item disappeared during update" };
569
+ }
570
+ if (outcome.reason === "not_found") return { ok: false, reason: "backlog item not found" };
571
+ const current = store.entries.find((e) => e.id === id);
572
+ if (current) {
573
+ const closed = current.state === "done" || current.state === "dropped";
574
+ return {
575
+ ok: false,
576
+ reason: closed
577
+ ? `already ${current.state} — cannot ${state === "taken" ? "take" : state} a closed item`
578
+ : `already ${current.state} — use done or drop`,
579
+ };
580
+ }
581
+ return { ok: false, reason: `cannot transition backlog item to ${state}` };
582
+ } catch (err) {
583
+ return { ok: false, reason: storageFailure(err) };
584
+ }
585
+ }
586
+
587
+ /** Open backlog items whose wake time has passed (for the session-start re-arm and timer fire). */
588
+ async dueBacklog(): Promise<BacklogEntry[]> {
589
+ const now = this.now();
590
+ return openItems((await this.backlog.load()).entries)
591
+ .filter((e) => e.dueAtEpochMs !== undefined && e.dueAtEpochMs <= now)
592
+ .map((entry) => {
593
+ const guarded = safePersistedText(entry.text);
594
+ return guarded.withheld ? { ...entry, text: guarded.text } : entry;
595
+ });
596
+ }
597
+
598
+ /**
599
+ * Delete expired STM and backlog rows from disk. Call after delivering due wakes (so a lead that
600
+ * expires at its due time still gets one reminder) and before injection so stale leads never
601
+ * re-enter the prompt. Best-effort: a store error must not block the session.
602
+ */
603
+ async sweepExpired(): Promise<{ stmRemoved: number; backlogRemoved: number }> {
604
+ const now = this.now();
605
+ let stmRemoved = 0;
606
+ let backlogRemoved = 0;
607
+ try {
608
+ await withFileLock(this.memoryMutationLock, async () => {
609
+ const stm = await this.stm.load();
610
+ const kept = pruneExpired(stm.entries, now);
611
+ stmRemoved = stm.entries.length - kept.length;
612
+ if (stmRemoved > 0) await this.stm.update(() => kept);
613
+ });
614
+ const backlog = await this.backlog.load();
615
+ const keptB = pruneExpiredBacklog(backlog.entries, now);
616
+ if (keptB.length < backlog.entries.length) {
617
+ // Another supervisor may append or settle work after the unlocked read. Prune the
618
+ // current locked state instead of replacing it with that earlier snapshot.
619
+ await this.backlog.update((entries) => {
620
+ const kept = pruneExpiredBacklog(entries, now);
621
+ backlogRemoved = entries.length - kept.length;
622
+ return kept;
623
+ });
624
+ }
625
+ } catch {
626
+ /* hygiene must not take the session down */
627
+ }
628
+ return { stmRemoved, backlogRemoved };
629
+ }
630
+
631
+ /** Acknowledge only the shown deadline; a concurrent renewal must keep its new alarm. */
632
+ async acknowledgeDue(shown: readonly { id: string; dueAtEpochMs: number }[]): Promise<number> {
633
+ if (shown.length === 0) return 0;
634
+ const wanted = new Map(shown.map((item) => [item.id, item.dueAtEpochMs]));
635
+ let cleared = 0;
636
+ try {
637
+ await this.backlog.update((es) =>
638
+ es.map((e) => {
639
+ if (e.dueAtEpochMs === undefined) return e;
640
+ if (wanted.get(e.id) !== e.dueAtEpochMs) return e;
641
+ if (e.state !== "open" && e.state !== "taken") return e;
642
+ cleared++;
643
+ const next = { ...e };
644
+ delete next.dueAtEpochMs;
645
+ return next;
646
+ }),
647
+ );
648
+ return cleared;
649
+ } catch {
650
+ return 0;
651
+ }
652
+ }
653
+
654
+ // ── injection ───────────────────────────────────────────────────────────────
655
+
656
+ /**
657
+ * Wipe THIS PROJECT's short-term memory and backlog. Long-term persona identity (private + shared)
658
+ * is left intact — that is not workspace-scoped. Counts every stored STM/backlog row, including
659
+ * expired notes and closed leads, because "reset" means the files are empty.
660
+ */
661
+ async resetWorkspace(): Promise<WorkspaceResetResult> {
662
+ try {
663
+ let stmRemoved = 0;
664
+ let backlogRemoved = 0;
665
+ await withFileLock(this.memoryMutationLock, async () => {
666
+ const before = await this.stm.load();
667
+ stmRemoved = before.entries.length;
668
+ if (stmRemoved > 0) await this.stm.update(() => []);
669
+ });
670
+ const backlogBefore = await this.backlog.load();
671
+ backlogRemoved = backlogBefore.entries.length;
672
+ if (backlogRemoved > 0) await this.backlog.update(() => []);
673
+ const ltmKept = (await this.longMemories()).length + (await this.projectLtm.load()).entries.length;
674
+ return { ok: true, stmRemoved, backlogRemoved, ltmKept };
675
+ } catch (err) {
676
+ return { ok: false, reason: storageFailure(err) };
677
+ }
678
+ }
679
+
680
+ /** Cheap counts for the status line and `/mind` header (expired STM and closed backlog excluded). */
681
+ async summary(): Promise<{ ltm: number; projectLtm: number; stm: number; backlogOpen: number }> {
682
+ const now = this.now();
683
+ const [ltm, stm, backlog] = await Promise.all([this.longMemories(), this.stm.load(), this.backlog.load()]);
684
+ return { ltm: ltm.length, projectLtm: (await this.projectLtm.load()).entries.length, stm: pruneExpired(stm.entries, now).length, backlogOpen: openItems(viewFor(backlog.entries, this.scope.persona, false)).length };
685
+ }
686
+
687
+ /**
688
+ * Assemble the deterministic `<persona-mind>` block. Full mode = long-term ⊕ working-context ⊕
689
+ * open backlog. `lean` mode (a DELEGATED worker leg) = the north-star + durable identity (long-term)
690
+ * ONLY, dropping the supervisor's working-context (STM) and backlog: a one-shot worker is not the
691
+ * persona, so it inherits who the persona IS but not the supervisor's project state or deferred
692
+ * intent. (The caller also withholds the write tools + wakes from a leg — see index.ts.)
693
+ */
694
+ async buildInjection(opts: { lean?: boolean; query?: string; fixedBlocks?: readonly string[]; cleanup?: boolean; leanReferenceTime?: number } = {}): Promise<string> {
695
+ // Workers inherit a read-only lean block; they must not mutate the supervisor's stores.
696
+ // A background import may own the profile lock while awaiting another store writer. Reads
697
+ // already filter expiry; defer disk hygiene until a later turn rather than joining that import.
698
+ if (!opts.lean && opts.cleanup !== false) await this.sweepExpired();
699
+ const now = this.now();
700
+ const context = { ...(opts.query === undefined ? {} : { query: opts.query }), ...(opts.fixedBlocks === undefined ? {} : { fixedBlocks: opts.fixedBlocks }) };
701
+ if (opts.lean || this.scope.homeWorkspace) {
702
+ const ltm = this.safeMemories(await this.longMemories(), "long-term");
703
+ if (opts.lean) {
704
+ return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now: opts.leanReferenceTime ?? now, lean: true, ...context, ...(this.budget ? { budget: this.budget } : {}) });
705
+ }
706
+ return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now, ...context, ...(this.budget ? { budget: this.budget } : {}) });
707
+ }
708
+ const [ltm, projectRaw, stmRaw, backlogRaw] = await Promise.all([this.longMemories(), this.projectLtm.load(), this.stm.load(), this.backlog.load()]);
709
+ return renderMind({
710
+ persona: this.scope.persona,
711
+ ltm: this.safeMemories(ltm, "long-term"),
712
+ projectLtm: this.safeMemories(projectRaw.entries, "project long-term"),
713
+ ...context,
714
+ stm: this.safeMemories(pruneExpired(stmRaw.entries, now), "short-term"),
715
+ backlog: this.safeBacklog(orderBacklog(openItems(viewFor(backlogRaw.entries, this.scope.persona, false)), now)),
716
+ now,
717
+ ...(this.budget ? { budget: this.budget } : {}),
718
+ });
719
+ }
720
+ }