@aeondave/pi-persona-mind 0.0.0-stage → 0.8.4

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