@aeondave/pi-persona-mind 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@
9
9
  * (same default life; a later wake extends it).
10
10
  */
11
11
 
12
+ import { randomUUID } from "node:crypto";
12
13
  import type { BacklogEntry, BacklogState, TransitionResult } from "./backlog.ts";
13
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";
14
15
  import { contentId } from "./ids.ts";
@@ -16,12 +17,13 @@ import type { MindBudget } from "./inject.ts";
16
17
  import { renderMind } from "./inject.ts";
17
18
  import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope } from "./memory-read.ts";
18
19
  import { MemoryOptimizer } from "./optimize-service.ts";
19
- import { samePersistedMemory } from "./optimize.ts";
20
+ import { OptimizeHistoryStore, type OptimizeReceipt } from "./optimize-history.ts";
21
+ import { samePersistedMemory, type OptimizeTarget } from "./optimize.ts";
20
22
  import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
21
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";
22
24
  import { scanContent } from "./scanner.ts";
23
25
  import { memoryMutationLockPath, type Scope } from "./scope.ts";
24
- import { JsonStore, type JsonStoreOptions, withFileLock } from "./store.ts";
26
+ import { JsonStore, type JsonStoreOptions, type StoreFile, withFileLock } from "./store.ts";
25
27
 
26
28
  const STORE_VERSION = 1;
27
29
 
@@ -32,6 +34,8 @@ export interface MindServiceOptions {
32
34
  now?: () => number;
33
35
  onWarn?: (message: string) => void;
34
36
  budget?: MindBudget;
37
+ /** Runtime owner snapshot for remember admission/commit; omitted by standalone store callers. */
38
+ isCurrent?: () => boolean;
35
39
  }
36
40
 
37
41
  interface RememberInputBase {
@@ -82,7 +86,7 @@ export interface AmbiguousMemory {
82
86
  resolves: boolean;
83
87
  }
84
88
 
85
- export type RememberResult = { ok: true; entry: MemoryEntry } | { ok: false; reason: string };
89
+ export type RememberResult = { ok: true; entry: MemoryEntry; receiptId?: string; warning?: string } | { ok: false; reason: string };
86
90
  export type BacklogAddResult = { ok: true; entry: BacklogEntry } | { ok: false; reason: string };
87
91
  export type BacklogSetResult = { ok: true; entry: BacklogEntry } | { ok: false; reason?: string };
88
92
  export type ForgetResult = { removed: number; reason?: "ambiguous_id"; candidates?: AmbiguousMemory[] };
@@ -160,6 +164,7 @@ export class MindService {
160
164
  private readonly backlog: JsonStore<BacklogEntry>;
161
165
  private readonly memoryMutationLock: string;
162
166
  private readonly warn: (message: string) => void;
167
+ private readonly isCurrent: () => boolean;
163
168
 
164
169
  constructor(
165
170
  scope: Scope,
@@ -169,6 +174,7 @@ export class MindService {
169
174
  this.now = opts.now ?? Date.now;
170
175
  this.budget = opts.budget;
171
176
  this.warn = opts.onWarn ?? (() => {});
177
+ this.isCurrent = opts.isCurrent ?? (() => true);
172
178
  const longOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateLongMemory, now: this.now };
173
179
  const shortOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateShortMemory, now: this.now };
174
180
  const backlogOpts: JsonStoreOptions<BacklogEntry> = { version: STORE_VERSION, validateEntry: validateBacklog, now: this.now };
@@ -239,6 +245,7 @@ export class MindService {
239
245
 
240
246
  /** Store a memory (long or short term). Scanned + non-empty-checked before it is persisted. */
241
247
  async remember(input: RememberInput): Promise<RememberResult> {
248
+ if (!this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner is unavailable; no memory was stored" };
242
249
  if (input.term !== "long" && input.term !== "short") return { ok: false, reason: "unknown memory term" };
243
250
  if (input.scope !== undefined && !["project", "persona", "shared"].includes(input.scope)) return { ok: false, reason: "unknown memory scope" };
244
251
  if (input.term === "long" && input.scope === undefined) return { ok: false, reason: "long-term memory requires an explicit scope: project, persona, or shared" };
@@ -281,38 +288,96 @@ export class MindService {
281
288
  if (term === "short" || input.scope === "project") makeInput.persona = this.scope.persona;
282
289
 
283
290
  const entry = makeMemory(makeInput, now);
284
- const store = term === "short" ? this.stm : input.scope === "project" ? this.projectLtm : input.scope === "shared" ? this.shared : this.ltm;
291
+ const target: OptimizeTarget = term === "short" ? "project" : input.scope === "project" ? "project-long" : input.scope === "shared" ? "shared" : "persona";
292
+ const store = this.memoryStores()[target];
285
293
  try {
286
- let committed: MemoryEntry | undefined;
287
- let ambiguous: { id: string; candidates: AmbiguousMemory[] } | undefined;
288
- await withFileLock(this.memoryMutationLock, async () => {
289
- if (entry.supersedes !== undefined) {
290
- // Same contract as `forget`: a handle that addresses more than one fact retires none of
291
- // them, and the caller is told so rather than silently getting a partial write. Read under
292
- // the mutation lock every writer holds, so the answer cannot go stale before the update.
293
- // The pool is the one `forget` resolves against — all durable/working stores, not just the one
294
- // being written: a v1 comma-joined id can name a durable fact in `shared` and another in
295
- // `ltm`, and a per-store check would still let the write destroy whichever copy sits in the
296
- // target tier while the delete path refuses the identical handle.
297
- const loaded = await Promise.all(Object.values(this.memoryStores()).map((memoryStore) => memoryStore.load()));
298
- const visible = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
299
- if (supersedeTargets(visible, entry.supersedes).ambiguous) {
300
- ambiguous = { id: entry.supersedes, candidates: ambiguityCandidates(visible, entry.supersedes) };
301
- return;
302
- }
303
- }
304
- const updated = await store.update((es) => upsertMemory(term === "short" ? pruneExpired(es, this.now()) : es, entry));
305
- committed = updated.entries.find((candidate) => sameMemoryContent(candidate, entry));
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 };
306
302
  });
307
- if (ambiguous) {
308
- return { ok: false, reason: ambiguousSupersedesReason(ambiguous.id, ambiguous.candidates) };
309
- }
310
- return { ok: true, entry: committed ?? entry };
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;
311
305
  } catch (err) {
312
306
  return { ok: false, reason: storageFailure(err) };
313
307
  }
314
308
  }
315
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
+
316
381
  /** Preserve repository scope unless the caller explicitly selects a broader durable tier. */
317
382
  async promote(id: string, target: "project" | "persona" | "shared" = "project"): Promise<{ ok: true; entry: MemoryEntry; ambiguousSupersedes?: string } | { ok: false; reason?: string }> {
318
383
  if (!["project", "persona", "shared"].includes(target)) return { ok: false, reason: "unknown promotion scope" };
package/src/core/store.ts CHANGED
@@ -34,6 +34,17 @@ export interface StoreFile<E> {
34
34
  entries: E[];
35
35
  }
36
36
 
37
+ /**
38
+ * A tolerant read together with whether it saw every row. `complete` is false when the result may be
39
+ * missing rows that exist on disk: rows hidden as invalid, a file quarantined to start empty, or an
40
+ * existing backup that could not be used while the live file is absent. `reasons` says why.
41
+ */
42
+ export interface StoreRead<E> {
43
+ file: StoreFile<E>;
44
+ complete: boolean;
45
+ reasons: string[];
46
+ }
47
+
37
48
  export interface StoreSnapshot<E> {
38
49
  store: StoreFile<E>;
39
50
  /** Binds the exact live bytes and store path, including same-sequence replacements. */
@@ -56,7 +67,13 @@ let lockSeq = 0;
56
67
  // JsonStore.load(), but the next atomic rewrite can put them back verbatim instead of silently
57
68
  // erasing data that the current validator does not understand yet.
58
69
  const PRESERVED_INVALID_ENTRIES: unique symbol = Symbol("preservedInvalidEntries");
59
- type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[] };
70
+ // Set on an empty store that stands in for data which exists but could not be read, so loadChecked()
71
+ // can tell it from a store that is genuinely empty. Never persisted.
72
+ const UNREAD_REASON: unique symbol = Symbol("unreadReason");
73
+ type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[]; [UNREAD_REASON]?: string };
74
+
75
+ /** What the `.bak` sidecar offers: nothing, a valid store, or a file that exists but cannot be used. */
76
+ type BackupRead<E> = { kind: "absent" } | { kind: "usable"; store: InternalStoreFile<E> } | { kind: "unusable"; reason: string };
60
77
 
61
78
  export interface AtomicWriteOptions {
62
79
  /** Refresh the `.bak` sidecar from the current live file only when this returns true for its
@@ -784,41 +801,49 @@ export class JsonStore<E> {
784
801
  });
785
802
  }
786
803
 
787
- private async recoverFromBak(reason: string, lockToken?: string): Promise<InternalStoreFile<E> | null> {
788
- if (lockToken === undefined) {
789
- const peek = await this.tryBak();
790
- if (!peek) return null;
791
- // Missing was only an optimistic observation: a writer may repair and commit
792
- // while this reader waits. Re-read live state under its lock before restoring.
793
- return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
804
+ /** A missing backup is normal; one that exists but cannot be used is not, and is never repaired or moved. */
805
+ private async readBak(): Promise<BackupRead<E>> {
806
+ try {
807
+ const store = this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
808
+ return store ? { kind: "usable", store } : { kind: "unusable", reason: "unparseable or unexpected shape" };
809
+ } catch (err) {
810
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { kind: "absent" };
811
+ return { kind: "unusable", reason: err instanceof Error ? err.message : String(err) };
794
812
  }
795
- const bak = await this.tryBak();
796
- if (!bak) return null;
813
+ }
814
+
815
+ /** Restore the last-known-good `.bak` over the live path. Only an unusable backup warns; an absent one is silent. */
816
+ private async recoverFromBak(reason: string): Promise<BackupRead<E>> {
817
+ const bak = await this.readBak();
818
+ if (bak.kind === "unusable") this.onWarn(`mind store: ${this.filePath}.bak rejected — ${bak.reason}`);
819
+ if (bak.kind !== "usable") return bak;
797
820
  this.onWarn(`mind store: ${this.filePath} ${reason}; recovered from ${this.filePath}.bak`);
798
- this.warnInvalidEntries(bak);
799
- await this.restoreLive(bak);
821
+ this.warnInvalidEntries(bak.store);
822
+ await this.restoreLive(bak.store);
800
823
  return bak;
801
824
  }
802
825
 
803
- /** Try to recover the last-known-good `.bak` sidecar. Returns null if it is absent or also bad. */
804
- private async tryBak(): Promise<InternalStoreFile<E> | null> {
805
- try {
806
- return this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
807
- } catch (err) {
808
- if (err instanceof BoundedReadFailure) {
809
- this.onWarn(`mind store: ${this.filePath}.bak rejected — ${err.message}`);
810
- }
811
- return null;
812
- }
826
+ /** Empty stand-in for data that exists but was not read, flagged so loadChecked() reports it incomplete. */
827
+ private unreadEmpty(reason: string): InternalStoreFile<E> {
828
+ const store: InternalStoreFile<E> = this.empty();
829
+ store[UNREAD_REASON] = reason;
830
+ return store;
813
831
  }
814
832
 
815
- private warnInvalidEntries(store: InternalStoreFile<E>): void {
833
+ /** An unreadable live file was set aside: announce it and start empty, flagged incomplete. */
834
+ private startEmpty(reason: string): InternalStoreFile<E> {
835
+ this.onWarn(`mind store: ${this.filePath} ${reason}`);
836
+ return this.unreadEmpty(reason);
837
+ }
838
+
839
+ private invalidEntriesNote(store: InternalStoreFile<E>): string | null {
816
840
  const count = store[PRESERVED_INVALID_ENTRIES]?.length ?? 0;
817
- if (count === 0) return;
818
- this.onWarn(
819
- `mind store: ${this.filePath} contained ${count} invalid entr${count === 1 ? "y" : "ies"}; ` +
820
- "preserved raw and hidden from consumers",
821
- );
841
+ return count === 0 ? null : `contained ${count} invalid entr${count === 1 ? "y" : "ies"}; preserved raw and hidden from consumers`;
842
+ }
843
+
844
+ private warnInvalidEntries(store: InternalStoreFile<E>): void {
845
+ const note = this.invalidEntriesNote(store);
846
+ if (note !== null) this.onWarn(`mind store: ${this.filePath} ${note}`);
822
847
  }
823
848
 
824
849
  private async recoverBoundedFailure(failure: BoundedReadFailure, lockToken?: string): Promise<InternalStoreFile<E>> {
@@ -827,13 +852,12 @@ export class JsonStore<E> {
827
852
  // store lock before quarantine so a writer that repaired the path wins the race safely.
828
853
  return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
829
854
  }
830
- const bak = await this.recoverFromBak(`rejected — ${failure.message}`, lockToken);
831
- if (bak) return bak;
855
+ const bak = await this.recoverFromBak(`rejected — ${failure.message}`);
856
+ if (bak.kind === "usable") return bak.store;
832
857
  const quarantineOptions: QuarantineOptions = {};
833
858
  if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
834
859
  const dest = await quarantineCorrupt(this.filePath, failure.message, quarantineOptions);
835
- this.onWarn(`mind store: ${this.filePath} rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
836
- return this.empty();
860
+ return this.startEmpty(`rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
837
861
  }
838
862
 
839
863
  private async loadInternal(lockToken?: string): Promise<InternalStoreFile<E>> {
@@ -842,8 +866,18 @@ export class JsonStore<E> {
842
866
  raw = await readTextFileBounded(this.filePath, this.maxBytes);
843
867
  } catch (err) {
844
868
  if ((err as NodeJS.ErrnoException).code === "ENOENT") {
845
- const bak = await this.recoverFromBak("missing", lockToken);
846
- return bak ?? this.empty();
869
+ if (lockToken === undefined) {
870
+ // Missing was only an optimistic observation: a writer may repair and commit while this reader
871
+ // waits. Unless there is no backup at all, re-read live state under its lock before restoring.
872
+ if ((await this.readBak()).kind === "absent") return this.empty();
873
+ return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
874
+ }
875
+ const bak = await this.recoverFromBak("missing");
876
+ if (bak.kind === "usable") return bak.store;
877
+ // Only an absent backup makes this tier genuinely empty. One that exists but cannot be used leaves
878
+ // the tier unread: the rows it holds may be exactly the ones a caller needs to see. The backup
879
+ // warning has already been given by recoverFromBak.
880
+ return bak.kind === "unusable" ? this.unreadEmpty(`has no live file and its backup ${this.filePath}.bak could not be used (${bak.reason}); the tier was not read`) : this.empty();
847
881
  }
848
882
  if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
849
883
  throw err;
@@ -865,18 +899,32 @@ export class JsonStore<E> {
865
899
  return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
866
900
  }
867
901
  // Live file is torn/invalid — roll back to the last-known-good backup before giving up.
868
- const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost", lockToken);
869
- if (bak) return bak;
902
+ const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost");
903
+ if (bak.kind === "usable") return bak.store;
870
904
  const quarantineOptions: QuarantineOptions = {};
871
905
  if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
872
906
  const dest = await quarantineCorrupt(this.filePath, "unparseable / unexpected shape", quarantineOptions);
873
- this.onWarn(`mind store: ${this.filePath} was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
874
- return this.empty();
907
+ return this.startEmpty(`was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
908
+ }
909
+
910
+ private plain(store: InternalStoreFile<E>): StoreFile<E> {
911
+ return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
875
912
  }
876
913
 
877
914
  async load(): Promise<StoreFile<E>> {
915
+ return this.plain(await this.loadInternal());
916
+ }
917
+
918
+ /**
919
+ * The same tolerant read as {@link load}, plus whether it saw every row. A missing file with no backup is
920
+ * complete, and so is a restore from a valid backup. Rows hidden as invalid, a quarantine that started the
921
+ * store empty, or a backup that exists but could not be used while the live file is absent are not. A foreign
922
+ * version or an I/O error on the live file still throws, exactly as it does for `load`.
923
+ */
924
+ async loadChecked(): Promise<StoreRead<E>> {
878
925
  const store = await this.loadInternal();
879
- return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
926
+ const reasons = [store[UNREAD_REASON], this.invalidEntriesNote(store)].filter((reason): reason is string => typeof reason === "string");
927
+ return { file: this.plain(store), complete: reasons.length === 0, reasons };
880
928
  }
881
929
 
882
930
  /** Read without recovery, quarantine, warnings or writes; invalid rows make editing unsafe. */
@@ -3,7 +3,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import type { MindService } from "../core/service.ts";
4
4
  import type { Scope } from "../core/scope.ts";
5
5
  import type { AutoOptimizeTarget } from "../core/auto-optimize.ts";
6
- import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, type AutoAttempt, type AutoOptimizeReportContext, type ReviewReservation } from "./auto-optimize.ts";
6
+ import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, SHUTDOWN_WORKER_WAIT_MS, type AutoAttempt, type AutoOptimizeReportContext, type ReviewReservation } from "./auto-optimize.ts";
7
7
  import { launchMindWorker } from "./mind-worker.ts";
8
8
  import { MIND_RESULT_ENTRY_TYPE } from "../ui/mind-result-card.ts";
9
9
 
@@ -131,7 +131,8 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
131
131
  if (target) memoryAdded(ctx, target);
132
132
  });
133
133
  pi.on("agent_settled", (event, ctx) => { if (!event.aborted && safeAvailable(ctx)) { activate(ctx); scheduler.settled(); } });
134
- pi.on("session_shutdown", async () => { revoke(); await scheduler.join(); });
134
+ // Bounded because Mind cannot rely on Persona's shutdown handler running first to force-settle the worker.
135
+ pi.on("session_shutdown", async () => { revoke(); await scheduler.join(SHUTDOWN_WORKER_WAIT_MS); });
135
136
  return { activate, revoke, memoryAdded,
136
137
  status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
137
138
  setEnabled: (enabled) => scheduler.setEnabled(enabled),