@aeondave/pi-persona-mind 0.9.3 → 0.9.5

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.
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),
@@ -8,6 +8,12 @@ export const AUTO_INPUT_TOKEN_THRESHOLD = 1_000_000;
8
8
  export const AUTO_COOLDOWN_MS = 5 * 60_000;
9
9
  export const AUTO_IDLE_MS = 2_000;
10
10
  export const AUTO_ATTEMPT_ENTRY = "pi-persona-mind-auto-attempt";
11
+ /** Shutdown bound for awaiting a Persona worker's completion; local apply/persistence stays joined. */
12
+ export const SHUTDOWN_WORKER_WAIT_MS = 5_000;
13
+ /** Stands in for a worker whose completion shutdown stopped waiting for: an interruption, never completed work. */
14
+ export const WORKER_WAIT_RELEASED: MindWorkerResult = { status: "stopped", ok: false, output: "", error: "Mind stopped waiting for the worker at shutdown" };
15
+ /** Receipts a restart restores per owner; the in-memory mirror keeps the same window. */
16
+ const ATTEMPT_HISTORY = 64;
11
17
  type Target = AutoOptimizeTarget;
12
18
  type Optimizer = Pick<MemoryOptimizer, "inspect" | "preview" | "apply" | "invalidate">;
13
19
  interface CoverageCursor { offset: number; withinPage: number }
@@ -46,16 +52,20 @@ export class AutoOptimizeScheduler {
46
52
  private enabled = true;
47
53
  private pending = new Set<Target>();
48
54
  private retryTargets = new Set<Target>();
49
- private retryAttempts = new Map<Target, { digest: string; at: number }>();
55
+ /** The launch cursor is known only in memory; a restored retry has no verifiable position. */
56
+ private retryAttempts = new Map<Target, { digest: string; at: number; cursor?: CoverageCursor }>();
50
57
  private cursors = new Map<Target, CoverageCursor>();
51
58
  private inputTokens = 0;
52
59
  private seen = new Set<string>();
60
+ /** Receipts as a restart would load them: parking is derived from these, never from enabled or retry state. */
61
+ private attempts: AutoAttempt[] = [];
62
+ private workerReleases = new Set<() => void>();
53
63
  private lastAttempt = -Infinity;
54
64
  private generation = 0;
55
65
  private disabledGeneration = 0;
56
66
  private timer: (() => void) | undefined;
57
67
  private timerGeneration = 0;
58
- private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean } | undefined;
68
+ private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean; parkOnInterrupt?: string } | undefined;
59
69
  private review: { target: Target; attempt?: { digest: string; at: number }; settled: boolean } | undefined;
60
70
  private work: Promise<void> = Promise.resolve();
61
71
  private last = "waiting for new memory";
@@ -66,29 +76,32 @@ export class AutoOptimizeScheduler {
66
76
  }
67
77
  activate(owner: AutoOptimizeOwner, enabled = this.enabled): void {
68
78
  this.stop(); this.owner = owner; this.enabled = enabled;
79
+ this.attempts = owner.attempts.slice(-ATTEMPT_HISTORY);
69
80
  this.cursors = new Map(owner.allowedTargets.map((target) => [target, { offset: 0, withinPage: 0 }]));
70
81
  const settledDigests = new Set(owner.attempts.filter((attempt) => attempt.state === "settled").map((attempt) => attempt.digest));
71
82
  this.seen = new Set([...settledDigests].slice(-64));
72
83
  this.lastAttempt = Math.max(-Infinity, ...owner.attempts.filter((a) => a.at <= this.now()).map((a) => a.at));
73
- if (this.enabled) {
74
- // A later attempt supersedes the interrupted trigger for that tier, even when new
75
- // records changed its digest. Never resurrect an older launch after the retry settled.
76
- const latestByTarget = new Map<Target, AutoAttempt>();
77
- for (const attempt of owner.attempts) if (attempt.target) latestByTarget.set(attempt.target, attempt);
78
- for (const attempt of latestByTarget.values()) {
79
- if (attempt.state === "started" && !attempt.explicit && !settledDigests.has(attempt.digest) && attempt.target && owner.allowedTargets.includes(attempt.target)) {
80
- this.pending.add(attempt.target);
81
- this.retryTargets.add(attempt.target);
82
- this.retryAttempts.set(attempt.target, { digest: attempt.digest, at: attempt.at });
83
- }
84
- }
84
+ // A later attempt supersedes the interrupted trigger for that tier, even when new
85
+ // records changed its digest. Never resurrect an older launch after the retry settled.
86
+ const latestByTarget = new Map<Target, AutoAttempt>();
87
+ for (const attempt of this.attempts) if (attempt.target) latestByTarget.set(attempt.target, attempt);
88
+ let parked = false;
89
+ for (const attempt of latestByTarget.values()) {
90
+ if (attempt.state !== "started" || attempt.explicit || settledDigests.has(attempt.digest) || !attempt.target || !owner.allowedTargets.includes(attempt.target)) continue;
91
+ // Two consecutive interrupted launches of one input already spent its single retry; a
92
+ // restore must not grant another background run (e.g. a review that keeps hitting a deadline).
93
+ if (interruptedTwice(this.attempts, attempt.target, attempt.digest)) { parked = true; continue; }
94
+ if (!this.enabled) continue;
95
+ this.pending.add(attempt.target);
96
+ this.retryTargets.add(attempt.target);
97
+ this.retryAttempts.set(attempt.target, { digest: attempt.digest, at: attempt.at });
85
98
  }
86
- this.last = this.retryTargets.size ? "interrupted review pending" : "waiting for new memory";
99
+ this.last = this.retryTargets.size ? "interrupted review pending" : parked ? "interrupted review parked until its records change" : "waiting for new memory";
87
100
  }
88
- stop(): void { this.review = undefined; this.interrupt(); this.owner = undefined; this.pending.clear(); this.retryTargets.clear(); this.retryAttempts.clear(); this.cursors.clear(); this.inputTokens = 0; this.seen.clear(); this.lastAttempt = -Infinity; }
101
+ stop(): void { this.review = undefined; this.interrupt(); this.owner = undefined; this.pending.clear(); this.retryTargets.clear(); this.retryAttempts.clear(); this.cursors.clear(); this.inputTokens = 0; this.seen.clear(); this.attempts = []; this.lastAttempt = -Infinity; }
89
102
  interrupt(): void {
90
103
  this.timer?.(); this.timer = undefined; this.timerGeneration++; this.generation++;
91
- if (this.enabled && !this.running?.explicit && this.running?.retryTarget) {
104
+ if (this.enabled && !this.running?.explicit && this.running?.retryTarget && !this.running.parkOnInterrupt) {
92
105
  this.pending.add(this.running.retryTarget);
93
106
  this.retryTargets.add(this.running.retryTarget);
94
107
  }
@@ -193,20 +206,36 @@ export class AutoOptimizeScheduler {
193
206
  });
194
207
  return true;
195
208
  }
196
- join(): Promise<void> { return this.work; }
209
+ /** Joins admitted work; a bound releases only the wait for the remote worker's completion. */
210
+ join(workerWaitMs?: number): Promise<void> {
211
+ const work = this.work;
212
+ if (workerWaitMs === undefined) return work;
213
+ const cancel = this.schedule(() => { for (const release of this.workerReleases) release(); }, workerWaitMs);
214
+ return work.finally(cancel);
215
+ }
197
216
  private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
198
217
  private safeIdle(owner: AutoOptimizeOwner): boolean { try { return owner.idle(); } catch { return false; } }
199
218
  private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
200
219
  private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number, explicit = false): void {
201
- owner.recordAttempt({ digest, target, at, state, ...(explicit ? { explicit: true } : {}) });
220
+ const attempt: AutoAttempt = { digest, target, at, state, ...(explicit ? { explicit: true } : {}) };
221
+ owner.recordAttempt(attempt);
222
+ this.attempts.push(attempt); if (this.attempts.length > ATTEMPT_HISTORY) this.attempts.shift();
202
223
  if (state === "settled") {
203
224
  this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
204
225
  }
205
226
  }
206
- private settleSkippedRetry(owner: AutoOptimizeOwner, target: Target): void {
207
- const attempt = this.retryTargets.has(target) ? this.retryAttempts.get(target) : undefined;
208
- if (attempt) this.remember(owner, target, attempt.digest, "settled", attempt.at);
227
+ /**
228
+ * A skipped window never settles a pending retry; only a completed review does. The retry is
229
+ * dropped without a receipt when its own launch cursor no longer yields its input. Elsewhere
230
+ * (rotation moved, or a restore that cannot know the position) it stays owed, not pending:
231
+ * the next dirty trigger for the tier may use it, and any launch on the tier consumes it.
232
+ */
233
+ private skipRetryWindow(target: Target, cursor: CoverageCursor): void {
234
+ const launchedAt = this.retryAttempts.get(target)?.cursor;
235
+ const ownWindow = launchedAt?.offset === cursor.offset && launchedAt.withinPage === cursor.withinPage;
236
+ if (this.retryTargets.has(target) && !ownWindow) return;
209
237
  this.retryAttempts.delete(target);
238
+ this.retryTargets.delete(target);
210
239
  }
211
240
  private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
212
241
  const owner = this.owner;
@@ -226,6 +255,10 @@ export class AutoOptimizeScheduler {
226
255
  return;
227
256
  }
228
257
  const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, explicit };
258
+ // Latched, so a second wait in the same run (cancel-then-join) also returns once released.
259
+ let releaseWorkerWait!: () => void;
260
+ const workerWaitReleased = new Promise<MindWorkerResult>((resolve) => { releaseWorkerWait = () => resolve(WORKER_WAIT_RELEASED); });
261
+ this.workerReleases.add(releaseWorkerWait);
229
262
  let attemptRecorded = false;
230
263
  let unsettledTarget: Target | undefined;
231
264
  let nextCursor: CoverageCursor | undefined;
@@ -303,26 +336,32 @@ export class AutoOptimizeScheduler {
303
336
  : { offset: cursor.offset, withinPage: page.nextRotation };
304
337
  const input = page.input;
305
338
  if (!input) {
306
- if (!explicit) this.settleSkippedRetry(owner, target);
339
+ if (explicit) this.retryTargets.delete(target);
340
+ else this.skipRetryWindow(target, cursor);
307
341
  this.cursors.set(target, nextCursor);
308
- this.retryTargets.delete(target);
309
342
  this.last = "no eligible records in this bounded page";
310
343
  if (explicit && !report(target, "Mind optimization result", formatAutoInputSkip(target, inspection, page))) return;
311
344
  continue;
312
345
  }
346
+ if (!explicit && interruptedTwice(this.attempts, target, input.digest)) {
347
+ // Rotation passes a parked window without a settled receipt or seen entry, so it is
348
+ // bypassed again whenever the cursor returns while unchanged and is reviewed once it changes.
349
+ this.skipRetryWindow(target, cursor);
350
+ this.cursors.set(target, nextCursor);
351
+ this.last = "this bounded record set is parked until its records change";
352
+ continue;
353
+ }
313
354
  if (!explicit && this.seen.has(input.digest)) {
314
- this.settleSkippedRetry(owner, target);
355
+ this.skipRetryWindow(target, cursor);
315
356
  this.cursors.set(target, nextCursor);
316
- this.retryTargets.delete(target);
317
357
  this.last = "this bounded record set was already reviewed";
318
358
  continue;
319
359
  }
320
360
  if (!explicit && !input.entries.some((entry, index) => input.entries.some((other, otherIndex) => otherIndex !== index && other.kind === entry.kind && other.persona === entry.persona))) {
321
- this.settleSkippedRetry(owner, target);
361
+ this.skipRetryWindow(target, cursor);
322
362
  this.seen.add(input.digest);
323
363
  while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
324
364
  this.cursors.set(target, nextCursor);
325
- this.retryTargets.delete(target);
326
365
  this.last = "no eligible same-kind pair in this bounded page";
327
366
  continue;
328
367
  }
@@ -352,22 +391,32 @@ export class AutoOptimizeScheduler {
352
391
  try {
353
392
  this.remember(owner, target, input.digest, "started", attemptAt, explicit);
354
393
  if (!explicit) {
355
- this.retryAttempts.set(target, { digest: input.digest, at: attemptAt });
394
+ this.retryAttempts.set(target, { digest: input.digest, at: attemptAt, cursor });
356
395
  attemptRecorded = true;
396
+ // The receipts already hold this input's earlier interruption, however that
397
+ // launch ended or was retried: interrupting this one parks it, as after a restart.
398
+ if (interruptedTwice(this.attempts, target, input.digest)) running.parkOnInterrupt = input.digest;
357
399
  }
358
400
  } catch {
359
401
  try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
360
402
  this.last = "attempt could not be saved; worker cancelled before apply";
361
403
  // Keep the one-worker slot until cancellation has actually joined its worker.
362
- try { await worker.completion; } catch { /* failed cancellation is still terminal */ }
404
+ try { await Promise.race([worker.completion, workerWaitReleased]); } catch { /* failed cancellation is still terminal */ }
363
405
  report(target, explicit ? "Mind optimization result" : "Mind automatic result",
364
406
  `Bounded review stopped: ${this.last}; memory unchanged.\nWorker ${worker.runId} · ${worker.model} · ${worker.thinking}`,
365
407
  "attempt could not be saved; memory unchanged", explicit, true);
366
408
  return;
367
409
  }
368
- const result = await worker.completion;
410
+ const result = await Promise.race([worker.completion, workerWaitReleased]);
369
411
  if (!current()) return;
370
412
  if (workerWasStopped(result)) {
413
+ if (!explicit && running.parkOnInterrupt) {
414
+ unsettledTarget = undefined;
415
+ this.retryAttempts.delete(target);
416
+ this.last = "review interrupted twice on unchanged records; parked until its records change";
417
+ report(target, "Mind automatic result", `Bounded review interrupted twice on the same records; memory unchanged. It is not retried until those records change.\nWorker ${worker.runId} · ${worker.model} · ${worker.thinking}`, "interrupted twice; parked until its records change");
418
+ return;
419
+ }
371
420
  if (!explicit) {
372
421
  retryRequiresSettled = true;
373
422
  this.pending.add(target);
@@ -450,11 +499,18 @@ export class AutoOptimizeScheduler {
450
499
  if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying", true);
451
500
  } finally {
452
501
  try { optimizer.invalidate(); } catch { /* Run-local plan cleanup cannot change completed review/apply results. */ }
502
+ this.workerReleases.delete(releaseWorkerWait);
453
503
  if (this.running === running) this.running = undefined;
454
- if (unsettledTarget !== undefined && !current() && mayRetry()) {
455
- this.pending.add(unsettledTarget);
456
- this.retryTargets.add(unsettledTarget);
457
- this.last = "review interrupted; waiting for the next settled event";
504
+ if (unsettledTarget !== undefined && !current()) {
505
+ // The receipts already park this input; disabling withdraws retry permission, not that fact.
506
+ if (running.parkOnInterrupt) {
507
+ this.retryAttempts.delete(unsettledTarget);
508
+ if (mayRetry()) this.last = "review interrupted twice on unchanged records; parked until its records change";
509
+ } else if (mayRetry()) {
510
+ this.pending.add(unsettledTarget);
511
+ this.retryTargets.add(unsettledTarget);
512
+ this.last = "review interrupted; waiting for the next settled event";
513
+ }
458
514
  }
459
515
  // One actual attempt may leave other dirty tiers pending; they need the input floor
460
516
  // and cooldown. Only the same interrupted tier bypasses the token floor.
@@ -488,6 +544,22 @@ export function formatAutoInputSkip(target: Target, inspection: OptimizeInspecti
488
544
  return `Target: ${target} — skipped: ${headlines[page.reason]}; no worker started, no memory changed.\nSelected page offset ${offset}: ${returned} record(s) returned of ${matched} inspection matches; ${eligible} safe/owned eligible record(s); ${total} active record(s) in this target; ${coverage}${morePages}.\nReason: ${reasons[page.reason]}.`;
489
545
  }
490
546
 
547
+ /**
548
+ * True when the tier's receipts hold two consecutive automatic started receipts for this input with
549
+ * no later settlement of it. In-memory scheduling and restart restoration share this one derivation.
550
+ */
551
+ function interruptedTwice(attempts: readonly AutoAttempt[], target: Target, digest: string): boolean {
552
+ let run = 0;
553
+ let parked = false;
554
+ for (const attempt of attempts) {
555
+ if (attempt.target !== target) continue;
556
+ if (attempt.digest === digest && attempt.state === "settled") { run = 0; parked = false; }
557
+ else if (attempt.digest === digest && attempt.state === "started" && !attempt.explicit) { run++; if (run >= 2) parked = true; }
558
+ else run = 0;
559
+ }
560
+ return parked;
561
+ }
562
+
491
563
  function workerWasStopped(result: MindWorkerResult): boolean {
492
564
  return result.status === "stopped";
493
565
  }
@@ -6,8 +6,8 @@ import type { MemoryOptimizer } from "../core/optimize-service.ts";
6
6
  import type { OptimizePlan } from "../core/optimize.ts";
7
7
  import { buildKnowledgeReviewTask, formatKnowledgeReview, parseKnowledgeReview, type ReviewPacket, type ReviewTarget } from "../core/knowledge-review.ts";
8
8
  import { collectReviewEvidence, type ReviewEvidenceSnapshot } from "./review-evidence.ts";
9
- import type { ReviewReservation } from "./auto-optimize.ts";
10
- import type { MindWorkerAdmission } from "./mind-worker.ts";
9
+ import { WORKER_WAIT_RELEASED, type ReviewReservation } from "./auto-optimize.ts";
10
+ import type { MindWorkerAdmission, MindWorkerResult } from "./mind-worker.ts";
11
11
 
12
12
  export interface KnowledgeReviewDeps {
13
13
  captureOwner(ctx: ExtensionContext): () => boolean;
@@ -16,6 +16,7 @@ export interface KnowledgeReviewDeps {
16
16
  launch(ctx: ExtensionContext, task: string): MindWorkerAdmission;
17
17
  appendResult(ctx: ExtensionContext, title: string, body: string): void;
18
18
  collect?: typeof collectReviewEvidence;
19
+ schedule?: (work: () => void, delay: number) => () => void;
19
20
  }
20
21
  interface PendingReview {
21
22
  ctx: ExtensionContext;
@@ -38,6 +39,8 @@ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
38
39
  let pending: PendingReview | undefined;
39
40
  let applying = false;
40
41
  const collect = deps.collect ?? collectReviewEvidence;
42
+ const schedule = deps.schedule ?? ((work, delay) => { const timer = setTimeout(work, delay); timer.unref(); return () => clearTimeout(timer); });
43
+ const workerReleases = new Set<() => void>();
41
44
  const notify = (ctx: ExtensionContext, message: string): void => ctx.ui.notify(message, "info");
42
45
  const drop = (): void => { pending?.optimizer.invalidate(); pending = undefined; };
43
46
  const interrupt = (): void => { generation++; dialogs.abort(); dialogs = new AbortController(); running?.cancel(); drop(); };
@@ -116,11 +119,16 @@ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
116
119
  const reviewOptimizer = optimizer;
117
120
  running = admission;
118
121
  reservation = undefined; optimizer = undefined;
122
+ // Latched, so the cancel-then-join wait after a released first wait also returns at once.
123
+ let releaseWorkerWait!: () => void;
124
+ const workerWaitReleased = new Promise<MindWorkerResult>((resolve) => { releaseWorkerWait = () => resolve(WORKER_WAIT_RELEASED); });
125
+ workerReleases.add(releaseWorkerWait);
126
+ const completion = (): Promise<MindWorkerResult> => Promise.race([admission.completion, workerWaitReleased]);
119
127
  work = (async () => {
120
128
  let completed = false;
121
129
  try {
122
130
  lease.launched(createHash("sha256").update(`knowledge-review\n${task}`).digest("hex"));
123
- const result = await admission.completion;
131
+ const result = await completion();
124
132
  requireCurrent(current);
125
133
  if (!lease.current()) throw new Error("Mind maintenance reservation was revoked.");
126
134
  if (!result.ok || result.status !== "done") throw new Error("Knowledge review stopped or failed; no changes were applied.");
@@ -143,7 +151,7 @@ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
143
151
  } catch (error) {
144
152
  reviewOptimizer.invalidate();
145
153
  admission.cancel();
146
- await admission.completion.catch(() => {});
154
+ await completion().catch(() => {});
147
155
  if (current()) {
148
156
  try { deps.appendResult(ctx, "Mind knowledge review — not applied", error instanceof Error ? error.message : "Knowledge review failed."); }
149
157
  catch { /* no persistence fallback and no application */ }
@@ -152,6 +160,7 @@ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
152
160
  } finally {
153
161
  if (completed && current()) { try { lease.settled(); } catch { notify(ctx, "Mind review accounting could not be persisted; inspect /mind doctor before retrying."); } }
154
162
  lease.release();
163
+ workerReleases.delete(releaseWorkerWait);
155
164
  if (running === admission) running = undefined;
156
165
  }
157
166
  })();
@@ -208,8 +217,13 @@ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
208
217
  return applyWork;
209
218
  }
210
219
  // Revocation prevents admission/guarded writes, but cannot roll back a committed store.
211
- // Join includes confirmation, persistence and receipt finalization, even after interrupt().
212
- return { start, show, apply, interrupt, join: async () => { await Promise.all([work, applyWork]); }, hasPending: () => snapshot() !== undefined,
220
+ // Join includes confirmation, persistence and receipt finalization, even after interrupt();
221
+ // a bound releases only the wait for the remote worker, which then ends as interrupted.
222
+ const join = async (workerWaitMs?: number): Promise<void> => {
223
+ const cancel = workerWaitMs === undefined ? undefined : schedule(() => { for (const release of workerReleases) release(); }, workerWaitMs);
224
+ try { await Promise.all([work, applyWork]); } finally { cancel?.(); }
225
+ };
226
+ return { start, show, apply, interrupt, join, hasPending: () => snapshot() !== undefined,
213
227
  discard(ctx: ExtensionContext): void { interrupt(); notify(ctx, "Knowledge review cancelled/discarded; no pending plan remains. Already applied changes require history/undo."); },
214
228
  };
215
229
  }
@@ -0,0 +1,28 @@
1
+ import { contentText } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+
4
+ const WORKER_CONTRACT_ENTRY = "pi-persona-worker-contract";
5
+
6
+ /** The launch task and time of a Persona v1 continuation, from the current native branch. */
7
+ export function workerMemoryAnchor(manager: ExtensionContext["sessionManager"]): { query: string; timestamp: number } | undefined {
8
+ try {
9
+ if (!manager.getSessionFile()) return undefined;
10
+ const branch = manager.getBranch();
11
+ const contracts = branch.filter((entry) => entry.type === "custom" && entry.customType === WORKER_CONTRACT_ENTRY);
12
+ const contract = contracts[0];
13
+ if (contracts.length !== 1 || contract?.type !== "custom") return undefined;
14
+ const data: unknown = contract.data;
15
+ if (!data || typeof data !== "object" || !("version" in data) || data.version !== 1
16
+ || !("sha256" in data) || typeof data.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(data.sha256)) return undefined;
17
+
18
+ for (const entry of branch.slice(branch.indexOf(contract) + 1)) {
19
+ if (entry.type === "message" && entry.message.role === "user") {
20
+ const { content, timestamp } = entry.message;
21
+ if (!Number.isSafeInteger(timestamp) || timestamp <= 0 || timestamp > Date.now()) return undefined;
22
+ const query = contentText(content);
23
+ return query.trim() ? { query, timestamp } : undefined;
24
+ }
25
+ }
26
+ } catch { /* Ordinary per-turn ranking still applies when the branch is unreadable. */ }
27
+ return undefined;
28
+ }
package/src/index.ts CHANGED
@@ -39,12 +39,14 @@ import { loadInspectorPage } from "./extension/inspector-data.ts";
39
39
  import { openMemoryInspector } from "./ui/memory-inspector.ts";
40
40
  import { queryInspectorFrame } from "./ui/inspector-frame.ts";
41
41
  import { createKnowledgeReview } from "./extension/knowledge-review.ts";
42
+ import { SHUTDOWN_WORKER_WAIT_MS } from "./extension/auto-optimize.ts";
42
43
  import { launchMindWorker } from "./extension/mind-worker.ts";
43
44
  import { runMindInspectorActions } from "./extension/mind-actions.ts";
44
45
  import { MIND_RESULT_ENTRY_TYPE, registerMindResultRenderer } from "./ui/mind-result-card.ts";
45
46
  import { parsePersonaMemoryOwner, PERSONA_MEMORY_OWNER_CHANGED, personaGuardedTools, queryPersonaDependency, queryPersonaMemoryOwner } from "./extension/persona-dependency.ts";
46
47
  import { createMindActivityRunner } from "./extension/activity.ts";
47
48
  import { installAutoOptimize } from "./extension/auto-optimize-session.ts";
49
+ import { workerMemoryAnchor } from "./extension/worker-memory-anchor.ts";
48
50
 
49
51
  const STATUS_KEY = "pi-persona-mind";
50
52
  /** Display-only transcript card for a due backlog wake. Never sent to the model; never starts a turn. */
@@ -1095,7 +1097,14 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1095
1097
  const sessionBlock = isDelegatedLeg ? "" : sessionMemory.injection(ctx, { query, maxTokens: 600 });
1096
1098
  try {
1097
1099
  // A worker inherits the LEAN mind (north-star + identity only); the supervisor gets it all.
1098
- block = await withDeadline(getMind(ctx).buildInjection({ lean: isDelegatedLeg, cleanup: !backgroundMigrationPending, query, fixedBlocks: [sessionBlock, cueHint].filter(Boolean).map((text) => `${text}\n\n`) }), INJECT_DEADLINE_MS, "", () => {
1100
+ const memoryAnchor = isDelegatedLeg ? workerMemoryAnchor(ctx.sessionManager) : undefined;
1101
+ block = await withDeadline(getMind(ctx).buildInjection({
1102
+ lean: isDelegatedLeg,
1103
+ cleanup: !backgroundMigrationPending,
1104
+ query: memoryAnchor?.query ?? query,
1105
+ fixedBlocks: [sessionBlock, cueHint].filter(Boolean).map((text) => `${text}\n\n`),
1106
+ ...(memoryAnchor ? { leanReferenceTime: memoryAnchor.timestamp } : {}),
1107
+ }), INJECT_DEADLINE_MS, "", () => {
1099
1108
  if (ownerCurrent()) surfaceWarning(ctx, `memory injection exceeded ${INJECT_DEADLINE_MS}ms and was skipped for this turn`);
1100
1109
  });
1101
1110
  } catch (err) {
@@ -1257,7 +1266,9 @@ export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}):
1257
1266
  wakeGeneration++;
1258
1267
  clearTimers();
1259
1268
  releaseWakeOwner();
1260
- await knowledgeReview.join();
1269
+ // The bound covers only the remote worker wait (load order relative to Persona is not guaranteed);
1270
+ // withDeadline would also cut the admitted apply/persistence join that must finish.
1271
+ await knowledgeReview.join(SHUTDOWN_WORKER_WAIT_MS);
1261
1272
  });
1262
1273
 
1263
1274
  registerMindCommands(pi, {
@@ -31,7 +31,7 @@ export async function runMemoryHistory(optimizer: MemoryOptimizer, input: Memory
31
31
  if (!input.target || input.max !== undefined) return fail("receipt detail requires an explicit target and uses offset instead of max");
32
32
  const detail = await optimizer.getReceipt(input.receiptId, input.target);
33
33
  if (!detail.ok) return fail(detail.reason);
34
- const { storePath: _path, ...receipt } = detail.receipt;
34
+ const { storePath: _path, fingerprint: _fingerprint, ...receipt } = detail.receipt;
35
35
  // Escaping angle brackets preserves the JSON value while preventing a stored field closing the fence.
36
36
  const body = JSON.stringify(receipt, null, 2).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
37
37
  const offset = input.offset ?? 0;