@aeondave/pi-persona-mind 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/AGENTS.md +137 -135
  2. package/CHANGELOG.md +287 -270
  3. package/LICENSE +24 -24
  4. package/README.md +84 -171
  5. package/docs/DESIGN.md +605 -573
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +15 -6
  8. package/src/core/auto-optimize.ts +323 -249
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -154
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -180
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -205
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -569
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -0
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/index.ts +1357 -1310
  45. package/src/session-memory.ts +127 -122
  46. package/src/tools/backlog.ts +126 -126
  47. package/src/tools/memory-handoff.ts +30 -30
  48. package/src/tools/memory-history.ts +46 -46
  49. package/src/tools/memory.ts +6 -4
  50. package/src/ui/card-frame.ts +161 -161
  51. package/src/ui/inspector-frame.ts +44 -44
  52. package/src/ui/memory-inspector.ts +464 -464
  53. package/src/ui/mind-result-card.ts +48 -48
  54. package/src/ui/presentation.ts +87 -87
  55. package/src/ui/session-note-card.ts +58 -56
@@ -1,569 +1,565 @@
1
- /** Event-driven maintenance: one visible Persona worker, bounded evidence, existing CAS writes. */
2
- import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoInputPage, type AutoInputSkipReason, type AutoOptimizeTarget } from "../core/auto-optimize.ts";
3
- import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
- import type { MindWorkerAdmission, MindWorkerResult } from "./mind-worker.ts";
5
- import type { OptimizeFailure, OptimizeInspection, OptimizePlan } from "../core/optimize.ts";
6
-
7
- export const AUTO_INPUT_TOKEN_THRESHOLD = 1_000_000;
8
- export const AUTO_COOLDOWN_MS = 5 * 60_000;
9
- export const AUTO_IDLE_MS = 2_000;
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;
17
- type Target = AutoOptimizeTarget;
18
- type Optimizer = Pick<MemoryOptimizer, "inspect" | "preview" | "apply" | "invalidate">;
19
- interface CoverageCursor { offset: number; withinPage: number }
20
- export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target; explicit?: true }
21
- /** Parent-held single-flight lease spanning evidence, worker, preview and user apply. */
22
- export interface ReviewReservation {
23
- current(): boolean;
24
- launched(digest: string): void;
25
- settled(): void;
26
- release(): void;
27
- }
28
- export interface AutoOptimizeReportContext {
29
- automatic: boolean;
30
- target: Target;
31
- phase: "proposal" | "result";
32
- summary: string;
33
- attention: boolean;
34
- }
35
- export interface AutoOptimizeOwner {
36
- key: string; persona: string;
37
- allowedTargets: readonly Target[];
38
- current(): boolean; idle(): boolean;
39
- optimizer(): Optimizer;
40
- launch(task: string): MindWorkerAdmission;
41
- /** Must persist the proposal successfully before application is allowed. */
42
- report(title: string, body: string, context?: AutoOptimizeReportContext): void;
43
- recordAttempt(attempt: AutoAttempt): void;
44
- attempts: AutoAttempt[];
45
- }
46
- interface Options { now?: () => number; schedule?: (work: () => void, delay: number) => () => void }
47
-
48
- export class AutoOptimizeScheduler {
49
- private readonly now: () => number;
50
- private readonly schedule: NonNullable<Options["schedule"]>;
51
- private owner: AutoOptimizeOwner | undefined;
52
- private enabled = true;
53
- private pending = new Set<Target>();
54
- private retryTargets = new Set<Target>();
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 }>();
57
- private cursors = new Map<Target, CoverageCursor>();
58
- private inputTokens = 0;
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>();
63
- private lastAttempt = -Infinity;
64
- private generation = 0;
65
- private disabledGeneration = 0;
66
- private timer: (() => void) | undefined;
67
- private timerGeneration = 0;
68
- private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean; parkOnInterrupt?: string } | undefined;
69
- private review: { target: Target; attempt?: { digest: string; at: number }; settled: boolean } | undefined;
70
- private work: Promise<void> = Promise.resolve();
71
- private last = "waiting for new memory";
72
-
73
- constructor(options: Options = {}) {
74
- this.now = options.now ?? Date.now;
75
- this.schedule = options.schedule ?? ((work, delay) => { const timer = setTimeout(work, delay); timer.unref(); return () => clearTimeout(timer); });
76
- }
77
- activate(owner: AutoOptimizeOwner, enabled = this.enabled): void {
78
- this.stop(); this.owner = owner; this.enabled = enabled;
79
- this.attempts = owner.attempts.slice(-ATTEMPT_HISTORY);
80
- this.cursors = new Map(owner.allowedTargets.map((target) => [target, { offset: 0, withinPage: 0 }]));
81
- const settledDigests = new Set(owner.attempts.filter((attempt) => attempt.state === "settled").map((attempt) => attempt.digest));
82
- this.seen = new Set([...settledDigests].slice(-64));
83
- this.lastAttempt = Math.max(-Infinity, ...owner.attempts.filter((a) => a.at <= this.now()).map((a) => a.at));
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 });
98
- }
99
- this.last = this.retryTargets.size ? "interrupted review pending" : parked ? "interrupted review parked until its records change" : "waiting for new memory";
100
- }
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; }
102
- interrupt(): void {
103
- this.timer?.(); this.timer = undefined; this.timerGeneration++; this.generation++;
104
- if (this.enabled && !this.running?.explicit && this.running?.retryTarget && !this.running.parkOnInterrupt) {
105
- this.pending.add(this.running.retryTarget);
106
- this.retryTargets.add(this.running.retryTarget);
107
- }
108
- this.running?.optimizer.invalidate(); this.running?.cancel?.();
109
- }
110
- setEnabled(enabled: boolean): void {
111
- const wasEnabled = this.enabled;
112
- this.enabled = enabled;
113
- if (!enabled) {
114
- this.disabledGeneration++;
115
- this.interrupt();
116
- this.pending.clear();
117
- this.retryTargets.clear();
118
- this.retryAttempts.clear();
119
- this.last = "automatic review disabled";
120
- }
121
- else {
122
- if (!wasEnabled) this.last = "waiting for new memory";
123
- this.settled();
124
- }
125
- }
126
- status(): string {
127
- const remaining = Math.max(0, AUTO_INPUT_TOKEN_THRESHOLD - this.inputTokens);
128
- const retryPending = [...this.pending].some((target) => this.retryTargets.has(target));
129
- const gate = retryPending ? "interrupted review pending; retry follows cooldown without another token wait"
130
- : this.pending.size === 0 ? this.lastAttempt === -Infinity ? "first review waits for new memory" : "no dirty memory; new memory is required"
131
- : this.lastAttempt === -Infinity ? "first dirty review is ready after idle"
132
- : `dirty review pending; ${remaining.toLocaleString("en-US")} main input tokens remain`;
133
- const activity = this.review ? `knowledge review ${this.review.attempt ? "active" : "reserved"} — ${this.review.target}` : this.running ? "Mind worker active" : this.last;
134
- return `${this.enabled ? "on" : "off"} · ${activity} · ${gate} · ${this.inputTokens.toLocaleString("en-US")}/${AUTO_INPUT_TOKEN_THRESHOLD.toLocaleString("en-US")} main input tokens since last attempt`;
135
- }
136
- memoryAdded(target: Target): void { if (this.enabled && this.owner && this.allows(this.owner, target)) this.pending.add(target); }
137
- tokensUsed(mainInputTokens: number): void { if (this.owner && Number.isSafeInteger(mainInputTokens) && mainInputTokens > 0) this.inputTokens = Math.min(AUTO_INPUT_TOKEN_THRESHOLD, this.inputTokens + mainInputTokens); }
138
- settled(): void {
139
- const owner = this.owner;
140
- if (!this.enabled || !owner || !this.safeCurrent(owner) || !owner.idle() || this.running || this.review || this.timer || !this.pending.size) return;
141
- const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
142
- const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
143
- if (!eligiblePending) return;
144
- const generation = this.generation;
145
- const timerGeneration = ++this.timerGeneration;
146
- this.timer = this.schedule(() => {
147
- if (timerGeneration !== this.timerGeneration) return;
148
- this.timer = undefined;
149
- if (generation !== this.generation || this.running || this.review) return;
150
- this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
151
- }, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
152
- }
153
- /** Reserve explicit review without spending an attempt or cancelling a real worker.
154
- * Lease identity, not scheduler generation, survives the review's own UI prompts.
155
- */
156
- reserveReview(target: Target): ReviewReservation | undefined {
157
- const owner = this.owner;
158
- if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || !this.allows(owner, target) || this.running || this.review) return undefined;
159
- this.timer?.(); this.timer = undefined; this.timerGeneration++;
160
- const lease: NonNullable<AutoOptimizeScheduler["review"]> = { target, settled: false };
161
- this.review = lease;
162
- const current = () => this.review === lease && this.safeCurrent(owner) && this.safeIdle(owner) && this.allows(owner, target);
163
- return {
164
- current,
165
- launched: (digest) => {
166
- if (!current()) throw new Error("knowledge review reservation is no longer current or was released");
167
- if (lease.attempt) throw new Error("knowledge review launch already recorded");
168
- if (!/^[a-f0-9]{64}$/.test(digest)) throw new Error("knowledge review digest must be a SHA-256 lowercase hex string");
169
- const at = this.now();
170
- // Called only after actual Persona admission: reset even if recording fails.
171
- lease.attempt = { digest, at };
172
- this.lastAttempt = at; this.inputTokens = 0;
173
- this.retryTargets.delete(target); this.retryAttempts.delete(target);
174
- this.remember(owner, target, digest, "started", at, true);
175
- },
176
- settled: () => {
177
- if (!current() || !lease.attempt || lease.settled) return;
178
- this.remember(owner, target, lease.attempt.digest, "settled", lease.attempt.at, true);
179
- lease.settled = true;
180
- },
181
- release: () => {
182
- if (this.review !== lease) return;
183
- this.review = undefined;
184
- this.last = lease.settled ? "knowledge review settled" : "knowledge review released; no automatic retry";
185
- },
186
- };
187
- }
188
- /** Current writable tiers, in the order a bare explicit request will review. */
189
- targets(): readonly Target[] { return this.owner ? [...new Set(this.owner.allowedTargets)].slice(0, 3) : []; }
190
- /** Start one named pass, or one bounded sequential pass over every allowed nonshared tier. */
191
- startExplicit(target?: Target): boolean {
192
- const owner = this.owner;
193
- if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review || (target !== undefined && !this.allows(owner, target))) return false;
194
- const targets = target === undefined ? [...this.targets()] : [target];
195
- if (targets.length === 0) return false;
196
- this.timer?.(); this.timer = undefined; this.timerGeneration++;
197
- const generation = this.generation;
198
- const qualifyTargets = target === undefined;
199
- this.work = this.run(targets, true, qualifyTargets).catch(() => {
200
- if (generation !== this.generation || !this.safeCurrent(owner) || !this.safeIdle(owner)) return;
201
- this.last = "explicit review failed; inspect current memory before retrying because apply may have completed";
202
- const label = targets.join(", ");
203
- try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", qualifyTargets ? `Targets ${label} — failed unexpectedly; inspect current memory before retrying because apply may have completed.\n${this.last}.` : `Bounded review failed unexpectedly; ${this.last}.`); } catch { /* owner reporting is best-effort */ }
204
- }).finally(() => {
205
- if (generation === this.generation && this.safeCurrent(owner) && this.safeIdle(owner) && this.pending.size) this.settled();
206
- });
207
- return true;
208
- }
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
- }
216
- private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
217
- private safeIdle(owner: AutoOptimizeOwner): boolean { try { return owner.idle(); } catch { return false; } }
218
- private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
219
- private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number, explicit = false): void {
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();
223
- if (state === "settled") {
224
- this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
225
- }
226
- }
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;
237
- this.retryAttempts.delete(target);
238
- this.retryTargets.delete(target);
239
- }
240
- private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
241
- const owner = this.owner;
242
- if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review) return;
243
- const generation = this.generation;
244
- const disabledGeneration = this.disabledGeneration;
245
- const current = () => generation === this.generation && (explicit || this.enabled) && this.safeIdle(owner) && this.safeCurrent(owner);
246
- const mayRetry = () => !explicit && this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
247
- const targets = explicit ? explicitTargets ?? [] : [...this.pending];
248
- let optimizer: Optimizer;
249
- try { optimizer = owner.optimizer(); } catch (error) {
250
- if (!explicit) throw error;
251
- if (!current()) return;
252
- this.last = "optimizer setup failed; no worker started, no memory changed";
253
- const body = `${qualifyTargets ? "Batch stopped; not reviewed" : "Target not reviewed"}: ${targets.join(", ")}.\nBounded review could not start: ${this.last}. See /mind doctor.`;
254
- try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", body); } catch { /* owner reporting is best-effort */ }
255
- return;
256
- }
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);
262
- let attemptRecorded = false;
263
- let unsettledTarget: Target | undefined;
264
- let nextCursor: CoverageCursor | undefined;
265
- let retryRequiresSettled = false;
266
- let activeTarget: Target | undefined;
267
- const report = (target: Target, title: string, body: string, summary?: string, stopped = false, attention = stopped): boolean => {
268
- if (!current()) return false;
269
- const remaining = stopped && qualifyTargets ? targets.slice(targets.indexOf(target) + 1) : [];
270
- const stoppedLine = remaining.length ? `Batch stopped; not reviewed: ${remaining.join(", ")}.\n` : "";
271
- const outcome = `${summary ?? body.split("\n", 1)[0] ?? "review result"}${remaining.length ? ` · not reviewed: ${remaining.join(", ")}` : ""}`;
272
- const qualifiedBody = qualifyTargets && !body.startsWith("Target:")
273
- ? `Target: ${target} — ${outcome}\n${stoppedLine}${body}`
274
- : body;
275
- owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody, {
276
- automatic: !explicit, target, phase: title.endsWith("proposal") ? "proposal" : "result", summary: outcome, attention,
277
- });
278
- return true;
279
- };
280
- this.running = running;
281
- try {
282
- for (const target of targets) {
283
- activeTarget = target;
284
- if (!current()) return;
285
- if (!this.allows(owner, target)) { this.pending.delete(target); this.retryTargets.delete(target); continue; }
286
- const retry = this.retryTargets.has(target);
287
- const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
288
- if (!explicit && !retry && !tokenReady) continue;
289
- if (!explicit) this.pending.delete(target);
290
- const cursor = this.cursors.get(target) ?? { offset: 0, withinPage: 0 };
291
- let inspection: OptimizeInspection | OptimizeFailure;
292
- let newestInspection: OptimizeInspection | undefined;
293
- try {
294
- inspection = await optimizer.inspect(target, { max: 100, offset: cursor.offset });
295
- if (inspection.ok && cursor.offset > 0) {
296
- const latest = await optimizer.inspect(target, { max: 100, offset: 0 });
297
- if (latest.ok && latest.target === target && latest.fingerprint === inspection.fingerprint) newestInspection = latest;
298
- else {
299
- if (mayRetry()) this.pending.add(target);
300
- this.last = explicit ? "store changed during bounded inspection; the selected window was not reviewed" : "store changed during bounded inspection; waiting for the next settled event";
301
- if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection snapshot changed; no worker started", true);
302
- return;
303
- }
304
- }
305
- } catch {
306
- if (!current()) {
307
- if (mayRetry()) this.pending.add(target);
308
- return;
309
- }
310
- this.last = "store inspection failed; see /mind doctor";
311
- if (explicit) report(target, "Mind optimization result", `Bounded review could not inspect this record window: ${this.last}.`, "inspection failed; no worker started", true);
312
- if (explicit) return;
313
- continue;
314
- }
315
- if (!current()) {
316
- // An interruption can invalidate the in-flight read without revoking the owner.
317
- // Keep its trigger so a later settled event can retry the inspection.
318
- if (mayRetry()) this.pending.add(target);
319
- return;
320
- }
321
- if (!inspection.ok) {
322
- this.last = "store inspection refused; see /mind doctor";
323
- if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection refused; no worker started", true);
324
- if (explicit) return;
325
- continue;
326
- }
327
- if (inspection.target !== target) {
328
- this.last = "store inspection returned a different tier; no worker started";
329
- if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection returned the wrong target; no worker started", true);
330
- if (explicit) return;
331
- continue;
332
- }
333
- const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, newestInspection);
334
- nextCursor = page.pageComplete
335
- ? { offset: inspection.nextOffset ?? 0, withinPage: 0 }
336
- : { offset: cursor.offset, withinPage: page.nextRotation };
337
- const input = page.input;
338
- if (!input) {
339
- if (explicit) this.retryTargets.delete(target);
340
- else this.skipRetryWindow(target, cursor);
341
- this.cursors.set(target, nextCursor);
342
- this.last = "no eligible records in this bounded page";
343
- if (explicit && !report(target, "Mind optimization result", formatAutoInputSkip(target, inspection, page))) return;
344
- continue;
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
- }
354
- if (!explicit && this.seen.has(input.digest)) {
355
- this.skipRetryWindow(target, cursor);
356
- this.cursors.set(target, nextCursor);
357
- this.last = "this bounded record set was already reviewed";
358
- continue;
359
- }
360
- if (!explicit && !input.entries.some((entry, index) => input.entries.some((other, otherIndex) => otherIndex !== index && other.kind === entry.kind && other.persona === entry.persona))) {
361
- this.skipRetryWindow(target, cursor);
362
- this.seen.add(input.digest);
363
- while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
364
- this.cursors.set(target, nextCursor);
365
- this.last = "no eligible same-kind pair in this bounded page";
366
- continue;
367
- }
368
- if (!current()) return;
369
- const worker = owner.launch(buildAutoPrompt(input, explicit ? "explicit" : "automatic"));
370
- if (!worker.ok) {
371
- if (!explicit) this.pending.add(target);
372
- this.last = worker.reason;
373
- if (explicit) report(target, "Mind optimization result", `Bounded review was not admitted: ${worker.reason}. No memory changed.`, "worker admission refused; no memory changed", true);
374
- return;
375
- }
376
- const attemptAt = this.now();
377
- running.cancel = worker.cancel;
378
- running.retryTarget = target;
379
- this.retryTargets.delete(target);
380
- // Explicit requests bypass admission gates, but every actual worker resets the
381
- // automatic baseline so a queued dirty tier cannot run again seconds later.
382
- this.lastAttempt = attemptAt; this.inputTokens = 0;
383
- this.last = "Mind is reviewing memory";
384
- unsettledTarget = target;
385
- const settle = (): void => {
386
- this.remember(owner, target, input.digest, "settled", attemptAt, explicit);
387
- if (nextCursor) this.cursors.set(target, nextCursor);
388
- this.retryAttempts.delete(target);
389
- unsettledTarget = undefined;
390
- };
391
- try {
392
- this.remember(owner, target, input.digest, "started", attemptAt, explicit);
393
- if (!explicit) {
394
- this.retryAttempts.set(target, { digest: input.digest, at: attemptAt, cursor });
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;
399
- }
400
- } catch {
401
- try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
402
- this.last = "attempt could not be saved; worker cancelled before apply";
403
- // Keep the one-worker slot until cancellation has actually joined its worker.
404
- try { await Promise.race([worker.completion, workerWaitReleased]); } catch { /* failed cancellation is still terminal */ }
405
- report(target, explicit ? "Mind optimization result" : "Mind automatic result",
406
- `Bounded review stopped: ${this.last}; memory unchanged.\nWorker ${worker.runId} · ${worker.model} · ${worker.thinking}`,
407
- "attempt could not be saved; memory unchanged", explicit, true);
408
- return;
409
- }
410
- const result = await Promise.race([worker.completion, workerWaitReleased]);
411
- if (!current()) return;
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
- }
420
- if (!explicit) {
421
- retryRequiresSettled = true;
422
- this.pending.add(target);
423
- this.retryTargets.add(target);
424
- }
425
- unsettledTarget = undefined;
426
- this.last = explicit ? "explicit review stopped; memory unchanged" : "review interrupted; waiting for the next settled event";
427
- if (explicit) report(target, "Mind optimization result", this.last, "worker stopped; memory unchanged", true);
428
- return;
429
- }
430
- const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
431
- if (!result.ok) {
432
- settle(); this.last = "worker failed; memory unchanged";
433
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}\n${provenance}`, "worker failed; memory unchanged", explicit, true);
434
- return;
435
- }
436
- const parsed = parseAutoProposal(result.output, input);
437
- if (!parsed.ok) {
438
- settle(); this.last = "proposal refused; memory unchanged";
439
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}\n${provenance}`, "proposal refused; memory unchanged", explicit, true);
440
- return;
441
- }
442
- if (!parsed.operations.length) {
443
- settle(); this.last = "bounded review found no safe consolidation in this record set";
444
- if (explicit) report(target, "Mind optimization result", `Bounded coverage: one selected record window; ${this.last}.\n${provenance}`, "reviewed no-op; no safe consolidation in this window");
445
- if (!explicit) return;
446
- continue;
447
- }
448
- if (!explicit && parsed.operations.some((operation) => operation.sourceIds.length < 2)) {
449
- settle(); this.last = "proposal ineligible for automatic consolidation; memory unchanged";
450
- return;
451
- }
452
- if (!current()) return;
453
- const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
454
- if (!current()) return;
455
- if (!plan.ok) {
456
- settle(); this.last = "store or proposal changed; nothing applied";
457
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}: ${plan.reason}\n${provenance}`, "proposal refused or stale; nothing applied", explicit, true);
458
- return;
459
- }
460
- if (!report(target, explicit ? "Mind optimization proposal" : "Mind automatic proposal", `${provenance}\n${formatAutoPlan(plan)}\n${explicit ? "Validated apply pending" : "Automatic apply pending"}; it proceeds only while this owner and snapshot remain current.`, "proposal staged; validated apply pending")) return;
461
- if (!current()) return;
462
- const applied = await optimizer.apply(plan.planId);
463
- if (!current()) return;
464
- settle();
465
- this.last = applied.ok ? `${applied.beforeCount} → ${applied.afterCount} memories; ${applied.changed} replacement(s)` : `not applied: ${applied.reason}`;
466
- const receipt = applied.ok
467
- ? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
468
- : "";
469
- const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
470
- const needsAttention = !applied.ok || Boolean(applied.warning) || (applied.ok && !applied.receiptId);
471
- const resultSummary = applied.ok
472
- ? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : !applied.receiptId && !explicit ? "; receipt warning" : ""}`
473
- : `not applied: ${applied.reason}`;
474
- if (!report(target, explicit ? "Mind optimization result" : "Mind automatic result", `Bounded coverage: one selected record window; ${this.last}\n${provenance}${receipt}${warning}`, resultSummary, explicit && (!applied.ok || Boolean(applied.warning)), needsAttention)) return;
475
- if (!applied.ok || applied.warning || !explicit) return;
476
- }
477
- } catch (error) {
478
- if (!explicit) {
479
- this.last = "automatic review failed unexpectedly; inspect current memory before retrying because apply may have completed";
480
- if (unsettledTarget && current()) {
481
- const attempt = this.retryAttempts.get(unsettledTarget);
482
- if (attempt) {
483
- try {
484
- // Terminal failure is not completed coverage. Persist suppression without
485
- // advancing the cursor, so reload cannot retry a possibly committed apply.
486
- this.remember(owner, unsettledTarget, attempt.digest, "settled", attempt.at);
487
- this.retryAttempts.delete(unsettledTarget);
488
- this.retryTargets.delete(unsettledTarget);
489
- unsettledTarget = undefined;
490
- } catch { /* Keep the warning even when terminal accounting cannot be saved. */ }
491
- }
492
- }
493
- if (activeTarget && current()) {
494
- try { report(activeTarget, "Mind automatic result", this.last, "review failed; inspect memory before retrying", false, true); } catch { /* reporting can itself fail */ }
495
- }
496
- return;
497
- }
498
- this.last = "explicit review failed unexpectedly; inspect current memory before retrying because apply may have completed";
499
- if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying", true);
500
- } finally {
501
- try { optimizer.invalidate(); } catch { /* Run-local plan cleanup cannot change completed review/apply results. */ }
502
- this.workerReleases.delete(releaseWorkerWait);
503
- if (this.running === running) this.running = undefined;
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
- }
514
- }
515
- // One actual attempt may leave other dirty tiers pending; they need the input floor
516
- // and cooldown. Only the same interrupted tier bypasses the token floor.
517
- if (!explicit && attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
518
- }
519
- }
520
- }
521
-
522
- export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Extract<AutoInputPage, { reason: AutoInputSkipReason }>): string {
523
- const offset = Number.isSafeInteger(inspection.offset) && inspection.offset >= 0 ? inspection.offset : 0;
524
- const returned = Array.isArray(inspection.entries) ? inspection.entries.length : 0;
525
- const matched = Number.isSafeInteger(inspection.matched) && inspection.matched >= 0 ? inspection.matched : 0;
526
- const total = Number.isSafeInteger(inspection.total) && inspection.total >= 0 ? inspection.total : 0;
527
- const eligible = Number.isSafeInteger(page.eligibleCount) && page.eligibleCount >= 0 ? page.eligibleCount : 0;
528
- const coverage = page.pageComplete ? "candidate page covered" : `within-page rotation continues at ${page.nextRotation}`;
529
- const morePages = inspection.nextOffset === undefined ? "" : `; further inspection page starts at ${inspection.nextOffset}`;
530
- const reasons = {
531
- "invalid-input": "the bounded input or owner identity was invalid",
532
- "empty-page": "the selected page is empty or exhausted; this does not establish that the whole target is empty",
533
- "no-safe-owned-facts": "this page contains no safe, owned eligible facts",
534
- "single-short-record": "the only admitted safe, owned fact in this selected window is shorter than the 1,200-character single-record minimum",
535
- "input-budget": "the 24,000-character input budget cannot admit enough full records in this window; records are not split or truncated",
536
- } satisfies Record<AutoInputSkipReason, string>;
537
- const headlines: Record<AutoInputSkipReason, string> = {
538
- "invalid-input": "invalid input",
539
- "empty-page": "empty/exhausted page",
540
- "no-safe-owned-facts": "no safe/owned facts",
541
- "single-short-record": "single fact under 1,200 characters",
542
- "input-budget": "full-record input budget too small",
543
- };
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]}.`;
545
- }
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
-
563
- function workerWasStopped(result: MindWorkerResult): boolean {
564
- return result.status === "stopped";
565
- }
566
-
567
- function formatAutoPlan(plan: OptimizePlan): string {
568
- return `Staged proposed change · ${plan.beforeCount} entries → ${plan.afterCount}\n${JSON.stringify(plan.changes, null, 2)}`;
569
- }
1
+ /** Event-driven maintenance: one visible Persona worker, bounded evidence, existing CAS writes. */
2
+ import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoInputPage, type AutoInputSkipReason, type AutoOptimizeTarget, type AutoReviewCursor, type AutoReviewSnapshot } from "../core/auto-optimize.ts";
3
+ import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
+ import type { MindWorkerAdmission, MindWorkerResult } from "./mind-worker.ts";
5
+ import type { OptimizeFailure, OptimizeInspection, OptimizePlan } from "../core/optimize.ts";
6
+
7
+ export const AUTO_INPUT_TOKEN_THRESHOLD = 1_000_000;
8
+ export const AUTO_COOLDOWN_MS = 5 * 60_000;
9
+ export const AUTO_IDLE_MS = 2_000;
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;
17
+ type Target = AutoOptimizeTarget;
18
+ type Optimizer = Pick<MemoryOptimizer, "inspectReviewPage" | "preview" | "apply" | "invalidate">;
19
+ export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target; explicit?: true }
20
+ /** Parent-held single-flight lease spanning evidence, worker, preview and user apply. */
21
+ export interface ReviewReservation {
22
+ current(): boolean;
23
+ launched(digest: string): void;
24
+ settled(): void;
25
+ release(): void;
26
+ }
27
+ export interface AutoOptimizeReportContext {
28
+ automatic: boolean;
29
+ target: Target;
30
+ phase: "proposal" | "result";
31
+ summary: string;
32
+ attention: boolean;
33
+ }
34
+ export interface AutoOptimizeOwner {
35
+ key: string; persona: string;
36
+ allowedTargets: readonly Target[];
37
+ current(): boolean; idle(): boolean;
38
+ optimizer(): Optimizer;
39
+ launch(task: string): MindWorkerAdmission;
40
+ /** Must persist the proposal successfully before application is allowed. */
41
+ report(title: string, body: string, context?: AutoOptimizeReportContext): void;
42
+ recordAttempt(attempt: AutoAttempt): void;
43
+ attempts: AutoAttempt[];
44
+ }
45
+ interface Options { now?: () => number; schedule?: (work: () => void, delay: number) => () => void }
46
+
47
+ export class AutoOptimizeScheduler {
48
+ private readonly now: () => number;
49
+ private readonly schedule: NonNullable<Options["schedule"]>;
50
+ private owner: AutoOptimizeOwner | undefined;
51
+ private enabled = true;
52
+ private pending = new Set<Target>();
53
+ private retryTargets = new Set<Target>();
54
+ /** The launch cursor is known only in memory; a restored retry has no verifiable position. */
55
+ private retryAttempts = new Map<Target, { digest: string; at: number; cursor?: AutoReviewCursor }>();
56
+ private cursors = new Map<Target, AutoReviewCursor>();
57
+ private inputTokens = 0;
58
+ private seen = new Set<string>();
59
+ /** Receipts as a restart would load them: parking is derived from these, never from enabled or retry state. */
60
+ private attempts: AutoAttempt[] = [];
61
+ private workerReleases = new Set<() => void>();
62
+ private lastAttempt = -Infinity;
63
+ private generation = 0;
64
+ private disabledGeneration = 0;
65
+ private timer: (() => void) | undefined;
66
+ private timerGeneration = 0;
67
+ private running: { optimizer: Optimizer; generation: number; settledGeneration?: number; cancel?: () => void; retryTarget?: Target; explicit?: boolean; parkOnInterrupt?: string } | undefined;
68
+ private review: { target: Target; attempt?: { digest: string; at: number }; settled: boolean } | undefined;
69
+ private work: Promise<void> = Promise.resolve();
70
+ private last = "waiting for new memory";
71
+
72
+ constructor(options: Options = {}) {
73
+ this.now = options.now ?? Date.now;
74
+ this.schedule = options.schedule ?? ((work, delay) => { const timer = setTimeout(work, delay); timer.unref(); return () => clearTimeout(timer); });
75
+ }
76
+ activate(owner: AutoOptimizeOwner, enabled = this.enabled): void {
77
+ this.stop(); this.owner = owner; this.enabled = enabled;
78
+ this.attempts = owner.attempts.slice(-ATTEMPT_HISTORY);
79
+ this.cursors = new Map(owner.allowedTargets.map((target) => [target, { offset: 0, withinPage: 0 }]));
80
+ const settledDigests = new Set(owner.attempts.filter((attempt) => attempt.state === "settled").map((attempt) => attempt.digest));
81
+ this.seen = new Set([...settledDigests].slice(-64));
82
+ this.lastAttempt = Math.max(-Infinity, ...owner.attempts.filter((a) => a.at <= this.now()).map((a) => a.at));
83
+ // A later attempt supersedes the interrupted trigger for that tier, even when new
84
+ // records changed its digest. Never resurrect an older launch after the retry settled.
85
+ const latestByTarget = new Map<Target, AutoAttempt>();
86
+ for (const attempt of this.attempts) if (attempt.target) latestByTarget.set(attempt.target, attempt);
87
+ let parked = false;
88
+ for (const attempt of latestByTarget.values()) {
89
+ if (attempt.state !== "started" || attempt.explicit || settledDigests.has(attempt.digest) || !attempt.target || !owner.allowedTargets.includes(attempt.target)) continue;
90
+ // Two consecutive interrupted launches of one input already spent its single retry; a
91
+ // restore must not grant another background run (e.g. a review that keeps hitting a deadline).
92
+ if (interruptedTwice(this.attempts, attempt.target, attempt.digest)) { parked = true; continue; }
93
+ if (!this.enabled) continue;
94
+ this.pending.add(attempt.target);
95
+ this.retryTargets.add(attempt.target);
96
+ this.retryAttempts.set(attempt.target, { digest: attempt.digest, at: attempt.at });
97
+ }
98
+ this.last = this.retryTargets.size ? "interrupted review pending" : parked ? "interrupted review parked until its records change" : "waiting for new memory";
99
+ }
100
+ 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; }
101
+ interrupt(): void {
102
+ this.timer?.(); this.timer = undefined; this.timerGeneration++; this.generation++;
103
+ if (this.enabled && !this.running?.explicit && this.running?.retryTarget && !this.running.parkOnInterrupt) {
104
+ this.pending.add(this.running.retryTarget);
105
+ this.retryTargets.add(this.running.retryTarget);
106
+ }
107
+ this.running?.optimizer.invalidate(); this.running?.cancel?.();
108
+ }
109
+ setEnabled(enabled: boolean): void {
110
+ const wasEnabled = this.enabled;
111
+ this.enabled = enabled;
112
+ if (!enabled) {
113
+ this.disabledGeneration++;
114
+ this.interrupt();
115
+ this.pending.clear();
116
+ this.retryTargets.clear();
117
+ this.retryAttempts.clear();
118
+ this.last = "automatic review disabled";
119
+ }
120
+ else {
121
+ if (!wasEnabled) this.last = "waiting for new memory";
122
+ this.settled();
123
+ }
124
+ }
125
+ status(): string {
126
+ const remaining = Math.max(0, AUTO_INPUT_TOKEN_THRESHOLD - this.inputTokens);
127
+ const retryPending = [...this.pending].some((target) => this.retryTargets.has(target));
128
+ const gate = retryPending ? "interrupted review pending; retry follows cooldown without another token wait"
129
+ : this.pending.size === 0 ? this.lastAttempt === -Infinity ? "first review waits for new memory" : "no dirty memory; new memory is required"
130
+ : this.lastAttempt === -Infinity ? "first dirty review is ready after idle"
131
+ : `dirty review pending; ${remaining.toLocaleString("en-US")} main input tokens remain`;
132
+ const activity = this.review ? `knowledge review ${this.review.attempt ? "active" : "reserved"} — ${this.review.target}` : this.running ? "Mind worker active" : this.last;
133
+ return `${this.enabled ? "on" : "off"} · ${activity} · ${gate} · ${this.inputTokens.toLocaleString("en-US")}/${AUTO_INPUT_TOKEN_THRESHOLD.toLocaleString("en-US")} main input tokens since last attempt`;
134
+ }
135
+ memoryAdded(target: Target): void { if (this.enabled && this.owner && this.allows(this.owner, target)) this.pending.add(target); }
136
+ tokensUsed(mainInputTokens: number): void { if (this.owner && Number.isSafeInteger(mainInputTokens) && mainInputTokens > 0) this.inputTokens = Math.min(AUTO_INPUT_TOKEN_THRESHOLD, this.inputTokens + mainInputTokens); }
137
+ settled(): void {
138
+ const owner = this.owner;
139
+ if (!this.enabled || !owner || !this.safeCurrent(owner) || !this.safeIdle(owner)) return;
140
+ if (this.running) {
141
+ // The foreground can settle before a cancelled worker or inspection releases its slot.
142
+ // Retain that edge only while it belongs to the latest generation.
143
+ if (this.running.generation !== this.generation) this.running.settledGeneration = this.generation;
144
+ return;
145
+ }
146
+ if (this.review || this.timer || !this.pending.size) return;
147
+ const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
148
+ const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
149
+ if (!eligiblePending) return;
150
+ const generation = this.generation;
151
+ const timerGeneration = ++this.timerGeneration;
152
+ this.timer = this.schedule(() => {
153
+ if (timerGeneration !== this.timerGeneration) return;
154
+ this.timer = undefined;
155
+ if (generation !== this.generation || this.running || this.review) return;
156
+ this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
157
+ }, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
158
+ }
159
+ /** Reserve explicit review without spending an attempt or cancelling a real worker.
160
+ * Lease identity, not scheduler generation, survives the review's own UI prompts.
161
+ */
162
+ reserveReview(target: Target): ReviewReservation | undefined {
163
+ const owner = this.owner;
164
+ if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || !this.allows(owner, target) || this.running || this.review) return undefined;
165
+ this.timer?.(); this.timer = undefined; this.timerGeneration++;
166
+ const lease: NonNullable<AutoOptimizeScheduler["review"]> = { target, settled: false };
167
+ this.review = lease;
168
+ const current = () => this.review === lease && this.safeCurrent(owner) && this.safeIdle(owner) && this.allows(owner, target);
169
+ return {
170
+ current,
171
+ launched: (digest) => {
172
+ if (!current()) throw new Error("knowledge review reservation is no longer current or was released");
173
+ if (lease.attempt) throw new Error("knowledge review launch already recorded");
174
+ if (!/^[a-f0-9]{64}$/.test(digest)) throw new Error("knowledge review digest must be a SHA-256 lowercase hex string");
175
+ const at = this.now();
176
+ // Called only after actual Persona admission: reset even if recording fails.
177
+ lease.attempt = { digest, at };
178
+ this.lastAttempt = at; this.inputTokens = 0;
179
+ this.retryTargets.delete(target); this.retryAttempts.delete(target);
180
+ this.remember(owner, target, digest, "started", at, true);
181
+ },
182
+ settled: () => {
183
+ if (!current() || !lease.attempt || lease.settled) return;
184
+ this.remember(owner, target, lease.attempt.digest, "settled", lease.attempt.at, true);
185
+ lease.settled = true;
186
+ },
187
+ release: () => {
188
+ if (this.review !== lease) return;
189
+ this.review = undefined;
190
+ this.last = lease.settled ? "knowledge review settled" : "knowledge review released; no automatic retry";
191
+ },
192
+ };
193
+ }
194
+ /** Current writable tiers, in the order a bare explicit request will review. */
195
+ targets(): readonly Target[] { return this.owner ? [...new Set(this.owner.allowedTargets)].slice(0, 3) : []; }
196
+ /** Start one named pass, or one bounded sequential pass over every allowed nonshared tier. */
197
+ startExplicit(target?: Target): boolean {
198
+ const owner = this.owner;
199
+ if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review || (target !== undefined && !this.allows(owner, target))) return false;
200
+ const targets = target === undefined ? [...this.targets()] : [target];
201
+ if (targets.length === 0) return false;
202
+ this.timer?.(); this.timer = undefined; this.timerGeneration++;
203
+ const generation = this.generation;
204
+ const qualifyTargets = target === undefined;
205
+ this.work = this.run(targets, true, qualifyTargets).catch(() => {
206
+ if (generation !== this.generation || !this.safeCurrent(owner) || !this.safeIdle(owner)) return;
207
+ this.last = "explicit review failed; inspect current memory before retrying because apply may have completed";
208
+ const label = targets.join(", ");
209
+ try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", qualifyTargets ? `Targets ${label} — failed unexpectedly; inspect current memory before retrying because apply may have completed.\n${this.last}.` : `Bounded review failed unexpectedly; ${this.last}.`); } catch { /* owner reporting is best-effort */ }
210
+ }).finally(() => {
211
+ if (generation === this.generation && this.safeCurrent(owner) && this.safeIdle(owner) && this.pending.size) this.settled();
212
+ });
213
+ return true;
214
+ }
215
+ /** Joins admitted work; a bound releases only the wait for the remote worker's completion. */
216
+ join(workerWaitMs?: number): Promise<void> {
217
+ const work = this.work;
218
+ if (workerWaitMs === undefined) return work;
219
+ const cancel = this.schedule(() => { for (const release of this.workerReleases) release(); }, workerWaitMs);
220
+ return work.finally(cancel);
221
+ }
222
+ private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
223
+ private safeIdle(owner: AutoOptimizeOwner): boolean { try { return owner.idle(); } catch { return false; } }
224
+ private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
225
+ private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number, explicit = false): void {
226
+ const attempt: AutoAttempt = { digest, target, at, state, ...(explicit ? { explicit: true } : {}) };
227
+ owner.recordAttempt(attempt);
228
+ this.attempts.push(attempt); if (this.attempts.length > ATTEMPT_HISTORY) this.attempts.shift();
229
+ if (state === "settled") {
230
+ this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
231
+ }
232
+ }
233
+ /**
234
+ * A skipped window never settles a pending retry; only a completed review does. The retry is
235
+ * dropped without a receipt when its own launch cursor no longer yields its input. Elsewhere
236
+ * (rotation moved, or a restore that cannot know the position) it stays owed, not pending:
237
+ * the next dirty trigger for the tier may use it, and any launch on the tier consumes it.
238
+ */
239
+ private skipRetryWindow(target: Target, cursor: AutoReviewCursor): void {
240
+ const launchedAt = this.retryAttempts.get(target)?.cursor;
241
+ const ownWindow = launchedAt === cursor;
242
+ if (this.retryTargets.has(target) && !ownWindow) return;
243
+ this.retryAttempts.delete(target);
244
+ this.retryTargets.delete(target);
245
+ }
246
+ private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
247
+ const owner = this.owner;
248
+ if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review) return;
249
+ const generation = this.generation;
250
+ const disabledGeneration = this.disabledGeneration;
251
+ const current = () => generation === this.generation && (explicit || this.enabled) && this.safeIdle(owner) && this.safeCurrent(owner);
252
+ const mayRetry = () => !explicit && this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
253
+ const targets = explicit ? explicitTargets ?? [] : [...this.pending];
254
+ let optimizer: Optimizer;
255
+ try { optimizer = owner.optimizer(); } catch (error) {
256
+ if (!explicit) throw error;
257
+ if (!current()) return;
258
+ this.last = "optimizer setup failed; no worker started, no memory changed";
259
+ const body = `${qualifyTargets ? "Batch stopped; not reviewed" : "Target not reviewed"}: ${targets.join(", ")}.\nBounded review could not start: ${this.last}. See /mind doctor.`;
260
+ try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", body); } catch { /* owner reporting is best-effort */ }
261
+ return;
262
+ }
263
+ const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, generation, explicit };
264
+ // Latched, so a second wait in the same run (cancel-then-join) also returns once released.
265
+ let releaseWorkerWait!: () => void;
266
+ const workerWaitReleased = new Promise<MindWorkerResult>((resolve) => { releaseWorkerWait = () => resolve(WORKER_WAIT_RELEASED); });
267
+ this.workerReleases.add(releaseWorkerWait);
268
+ let attemptRecorded = false;
269
+ let unsettledTarget: Target | undefined;
270
+ let nextCursor: AutoReviewCursor | undefined;
271
+ let retryRequiresSettled = false;
272
+ let activeTarget: Target | undefined;
273
+ const report = (target: Target, title: string, body: string, summary?: string, stopped = false, attention = stopped): boolean => {
274
+ if (!current()) return false;
275
+ const remaining = stopped && qualifyTargets ? targets.slice(targets.indexOf(target) + 1) : [];
276
+ const stoppedLine = remaining.length ? `Batch stopped; not reviewed: ${remaining.join(", ")}.\n` : "";
277
+ const outcome = `${summary ?? body.split("\n", 1)[0] ?? "review result"}${remaining.length ? ` · not reviewed: ${remaining.join(", ")}` : ""}`;
278
+ const qualifiedBody = qualifyTargets && !body.startsWith("Target:")
279
+ ? `Target: ${target} — ${outcome}\n${stoppedLine}${body}`
280
+ : body;
281
+ owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody, {
282
+ automatic: !explicit, target, phase: title.endsWith("proposal") ? "proposal" : "result", summary: outcome, attention,
283
+ });
284
+ return true;
285
+ };
286
+ this.running = running;
287
+ try {
288
+ for (const target of targets) {
289
+ activeTarget = target;
290
+ if (!current()) return;
291
+ if (!this.allows(owner, target)) { this.pending.delete(target); this.retryTargets.delete(target); continue; }
292
+ const retry = this.retryTargets.has(target);
293
+ const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
294
+ if (!explicit && !retry && !tokenReady) continue;
295
+ if (!explicit) this.pending.delete(target);
296
+ const cursor = this.cursors.get(target) ?? { offset: 0, withinPage: 0 };
297
+ let snapshot: AutoReviewSnapshot | OptimizeFailure;
298
+ try {
299
+ snapshot = await optimizer.inspectReviewPage(target, cursor);
300
+ } catch {
301
+ if (!current()) {
302
+ if (mayRetry()) this.pending.add(target);
303
+ return;
304
+ }
305
+ this.last = "store inspection failed; see /mind doctor";
306
+ if (explicit) report(target, "Mind optimization result", `Bounded review could not inspect this record window: ${this.last}.`, "inspection failed; no worker started", true);
307
+ if (explicit) return;
308
+ continue;
309
+ }
310
+ if (!current()) {
311
+ // An interruption can invalidate the in-flight read without revoking the owner.
312
+ // Keep its trigger so a later settled event can retry the inspection.
313
+ if (mayRetry()) this.pending.add(target);
314
+ return;
315
+ }
316
+ if ("ok" in snapshot) {
317
+ this.last = "store inspection refused; see /mind doctor";
318
+ if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection refused; no worker started", true);
319
+ if (explicit) return;
320
+ continue;
321
+ }
322
+ const { inspection, newest, nextBefore } = snapshot;
323
+ if (inspection.target !== target) {
324
+ this.last = "store inspection returned a different tier; no worker started";
325
+ if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection returned the wrong target; no worker started", true);
326
+ if (explicit) return;
327
+ continue;
328
+ }
329
+ const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, { ...(newest ? { newest } : {}), ...(cursor.order ? { order: cursor.order } : {}) });
330
+ nextCursor = page.pageComplete
331
+ ? { offset: inspection.nextOffset ?? 0, withinPage: 0, ...(nextBefore ? { before: nextBefore } : {}) }
332
+ : { offset: cursor.offset, withinPage: page.nextRotation, order: page.order, ...(nextBefore ? { nextBefore } : {}) };
333
+ const input = page.input;
334
+ if (!input) {
335
+ if (explicit) this.retryTargets.delete(target);
336
+ else this.skipRetryWindow(target, cursor);
337
+ this.cursors.set(target, nextCursor);
338
+ this.last = "no eligible records in this bounded page";
339
+ if (explicit && !report(target, "Mind optimization result", formatAutoInputSkip(target, inspection, page))) return;
340
+ continue;
341
+ }
342
+ if (!explicit && interruptedTwice(this.attempts, target, input.digest)) {
343
+ // Rotation passes a parked window without a settled receipt or seen entry, so it is
344
+ // bypassed again whenever the cursor returns while unchanged and is reviewed once it changes.
345
+ this.skipRetryWindow(target, cursor);
346
+ this.cursors.set(target, nextCursor);
347
+ this.last = "this bounded record set is parked until its records change";
348
+ continue;
349
+ }
350
+ if (!explicit && this.seen.has(input.digest)) {
351
+ this.skipRetryWindow(target, cursor);
352
+ this.cursors.set(target, nextCursor);
353
+ this.last = "this bounded record set was already reviewed";
354
+ continue;
355
+ }
356
+ if (!explicit && !input.entries.some((entry, index) => input.entries.some((other, otherIndex) => otherIndex !== index && other.kind === entry.kind && other.persona === entry.persona))) {
357
+ this.skipRetryWindow(target, cursor);
358
+ this.seen.add(input.digest);
359
+ while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
360
+ this.cursors.set(target, nextCursor);
361
+ this.last = "no eligible same-kind pair in this bounded page";
362
+ continue;
363
+ }
364
+ if (!current()) return;
365
+ const worker = owner.launch(buildAutoPrompt(input, explicit ? "explicit" : "automatic"));
366
+ if (!worker.ok) {
367
+ if (!explicit) this.pending.add(target);
368
+ this.last = worker.reason;
369
+ if (explicit) report(target, "Mind optimization result", `Bounded review was not admitted: ${worker.reason}. No memory changed.`, "worker admission refused; no memory changed", true);
370
+ return;
371
+ }
372
+ const attemptAt = this.now();
373
+ running.cancel = worker.cancel;
374
+ running.retryTarget = target;
375
+ this.retryTargets.delete(target);
376
+ // Explicit requests bypass admission gates, but every actual worker resets the
377
+ // automatic baseline so a queued dirty tier cannot run again seconds later.
378
+ this.lastAttempt = attemptAt; this.inputTokens = 0;
379
+ this.last = "Mind is reviewing memory";
380
+ unsettledTarget = target;
381
+ const settle = (): void => {
382
+ this.remember(owner, target, input.digest, "settled", attemptAt, explicit);
383
+ if (nextCursor) this.cursors.set(target, nextCursor);
384
+ this.retryAttempts.delete(target);
385
+ unsettledTarget = undefined;
386
+ };
387
+ try {
388
+ this.remember(owner, target, input.digest, "started", attemptAt, explicit);
389
+ if (!explicit) {
390
+ this.retryAttempts.set(target, { digest: input.digest, at: attemptAt, cursor });
391
+ attemptRecorded = true;
392
+ // The receipts already hold this input's earlier interruption, however that
393
+ // launch ended or was retried: interrupting this one parks it, as after a restart.
394
+ if (interruptedTwice(this.attempts, target, input.digest)) running.parkOnInterrupt = input.digest;
395
+ }
396
+ } catch {
397
+ try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
398
+ this.last = "attempt could not be saved; worker cancelled before apply";
399
+ // Keep the one-worker slot until cancellation has actually joined its worker.
400
+ try { await Promise.race([worker.completion, workerWaitReleased]); } catch { /* failed cancellation is still terminal */ }
401
+ report(target, explicit ? "Mind optimization result" : "Mind automatic result",
402
+ `Bounded review stopped: ${this.last}; memory unchanged.\nWorker ${worker.runId} · ${worker.model} · ${worker.thinking}`,
403
+ "attempt could not be saved; memory unchanged", explicit, true);
404
+ return;
405
+ }
406
+ const result = await Promise.race([worker.completion, workerWaitReleased]);
407
+ if (!current()) return;
408
+ if (workerWasStopped(result)) {
409
+ if (!explicit && running.parkOnInterrupt) {
410
+ unsettledTarget = undefined;
411
+ this.retryAttempts.delete(target);
412
+ this.last = "review interrupted twice on unchanged records; parked until its records change";
413
+ 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");
414
+ return;
415
+ }
416
+ if (!explicit) {
417
+ retryRequiresSettled = true;
418
+ this.pending.add(target);
419
+ this.retryTargets.add(target);
420
+ }
421
+ unsettledTarget = undefined;
422
+ this.last = explicit ? "explicit review stopped; memory unchanged" : "review interrupted; waiting for the next settled event";
423
+ if (explicit) report(target, "Mind optimization result", this.last, "worker stopped; memory unchanged", true);
424
+ return;
425
+ }
426
+ const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
427
+ if (!result.ok) {
428
+ settle(); this.last = "worker failed; memory unchanged";
429
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}\n${provenance}`, "worker failed; memory unchanged", explicit, true);
430
+ return;
431
+ }
432
+ const parsed = parseAutoProposal(result.output, input);
433
+ if (!parsed.ok) {
434
+ settle(); this.last = "proposal refused; memory unchanged";
435
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}\n${provenance}`, "proposal refused; memory unchanged", explicit, true);
436
+ return;
437
+ }
438
+ if (!parsed.operations.length) {
439
+ settle(); this.last = "bounded review found no safe consolidation in this record set";
440
+ if (explicit) report(target, "Mind optimization result", `Bounded coverage: one selected record window; ${this.last}.\n${provenance}`, "reviewed no-op; no safe consolidation in this window");
441
+ if (!explicit) return;
442
+ continue;
443
+ }
444
+ if (!explicit && parsed.operations.some((operation) => operation.sourceIds.length < 2)) {
445
+ settle(); this.last = "proposal ineligible for automatic consolidation; memory unchanged";
446
+ return;
447
+ }
448
+ if (!current()) return;
449
+ const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
450
+ if (!current()) return;
451
+ if (!plan.ok) {
452
+ settle(); this.last = "store or proposal changed; nothing applied";
453
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}: ${plan.reason}\n${provenance}`, "proposal refused or stale; nothing applied", explicit, true);
454
+ return;
455
+ }
456
+ if (!report(target, explicit ? "Mind optimization proposal" : "Mind automatic proposal", `${provenance}\n${formatAutoPlan(plan)}\n${explicit ? "Validated apply pending" : "Automatic apply pending"}; it proceeds only while this owner and snapshot remain current.`, "proposal staged; validated apply pending")) return;
457
+ if (!current()) return;
458
+ const applied = await optimizer.apply(plan.planId);
459
+ if (!current()) return;
460
+ settle();
461
+ this.last = applied.ok ? `${applied.beforeCount} → ${applied.afterCount} memories; ${applied.changed} replacement(s)` : `not applied: ${applied.reason}`;
462
+ const receipt = applied.ok
463
+ ? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
464
+ : "";
465
+ const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
466
+ const needsAttention = !applied.ok || Boolean(applied.warning) || (applied.ok && !applied.receiptId);
467
+ const resultSummary = applied.ok
468
+ ? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : !applied.receiptId && !explicit ? "; receipt warning" : ""}`
469
+ : `not applied: ${applied.reason}`;
470
+ if (!report(target, explicit ? "Mind optimization result" : "Mind automatic result", `Bounded coverage: one selected record window; ${this.last}\n${provenance}${receipt}${warning}`, resultSummary, explicit && (!applied.ok || Boolean(applied.warning)), needsAttention)) return;
471
+ if (!applied.ok || applied.warning || !explicit) return;
472
+ }
473
+ } catch (error) {
474
+ if (!explicit) {
475
+ this.last = "automatic review failed unexpectedly; inspect current memory before retrying because apply may have completed";
476
+ if (unsettledTarget && current()) {
477
+ const attempt = this.retryAttempts.get(unsettledTarget);
478
+ if (attempt) {
479
+ try {
480
+ // Terminal failure is not completed coverage. Persist suppression without
481
+ // advancing the cursor, so reload cannot retry a possibly committed apply.
482
+ this.remember(owner, unsettledTarget, attempt.digest, "settled", attempt.at);
483
+ this.retryAttempts.delete(unsettledTarget);
484
+ this.retryTargets.delete(unsettledTarget);
485
+ unsettledTarget = undefined;
486
+ } catch { /* Keep the warning even when terminal accounting cannot be saved. */ }
487
+ }
488
+ }
489
+ if (activeTarget && current()) {
490
+ try { report(activeTarget, "Mind automatic result", this.last, "review failed; inspect memory before retrying", false, true); } catch { /* reporting can itself fail */ }
491
+ }
492
+ return;
493
+ }
494
+ this.last = "explicit review failed unexpectedly; inspect current memory before retrying because apply may have completed";
495
+ if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying", true);
496
+ } finally {
497
+ try { optimizer.invalidate(); } catch { /* Run-local plan cleanup cannot change completed review/apply results. */ }
498
+ this.workerReleases.delete(releaseWorkerWait);
499
+ if (this.running === running) this.running = undefined;
500
+ if (unsettledTarget !== undefined && !current()) {
501
+ // The receipts already park this input; disabling withdraws retry permission, not that fact.
502
+ if (running.parkOnInterrupt) {
503
+ this.retryAttempts.delete(unsettledTarget);
504
+ if (mayRetry()) this.last = "review interrupted twice on unchanged records; parked until its records change";
505
+ } else if (mayRetry()) {
506
+ this.pending.add(unsettledTarget);
507
+ this.retryTargets.add(unsettledTarget);
508
+ this.last = "review interrupted; waiting for the next settled event";
509
+ }
510
+ }
511
+ // One actual attempt may leave other dirty tiers pending; they need the input floor
512
+ // and cooldown. Only the same interrupted tier bypasses the token floor.
513
+ if (running.settledGeneration === this.generation || (!explicit && attemptRecorded && current() && !retryRequiresSettled)) this.settled();
514
+ }
515
+ }
516
+ }
517
+
518
+ export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Pick<Extract<AutoInputPage, { reason: AutoInputSkipReason }>, "reason" | "eligibleCount" | "nextRotation" | "pageComplete">): string {
519
+ const offset = Number.isSafeInteger(inspection.offset) && inspection.offset >= 0 ? inspection.offset : 0;
520
+ const returned = Array.isArray(inspection.entries) ? inspection.entries.length : 0;
521
+ const matched = Number.isSafeInteger(inspection.matched) && inspection.matched >= 0 ? inspection.matched : 0;
522
+ const total = Number.isSafeInteger(inspection.total) && inspection.total >= 0 ? inspection.total : 0;
523
+ const eligible = Number.isSafeInteger(page.eligibleCount) && page.eligibleCount >= 0 ? page.eligibleCount : 0;
524
+ const coverage = page.pageComplete ? "end of candidate page reached" : `within-page rotation continues at ${page.nextRotation}`;
525
+ const morePages = inspection.nextOffset === undefined ? "" : `; next rotation page position ${inspection.nextOffset}`;
526
+ const reasons = {
527
+ "invalid-input": "the bounded input or owner identity was invalid",
528
+ "empty-page": "the selected page is empty or exhausted; this does not establish that the whole target is empty",
529
+ "no-safe-owned-facts": "this page contains no safe, owned eligible facts",
530
+ "single-short-record": "the only admitted safe, owned fact in this selected window is shorter than the 1,200-character single-record minimum",
531
+ "input-budget": "the 24,000-character input budget cannot admit enough full records in this window; records are not split or truncated",
532
+ } satisfies Record<AutoInputSkipReason, string>;
533
+ const headlines: Record<AutoInputSkipReason, string> = {
534
+ "invalid-input": "invalid input",
535
+ "empty-page": "empty/exhausted page",
536
+ "no-safe-owned-facts": "no safe/owned facts",
537
+ "single-short-record": "single fact under 1,200 characters",
538
+ "input-budget": "full-record input budget too small",
539
+ };
540
+ return `Target: ${target} — skipped: ${headlines[page.reason]}; no worker started, no memory changed.\nSelected page position ${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]}.`;
541
+ }
542
+
543
+ /**
544
+ * True when the tier's receipts hold two consecutive automatic started receipts for this input with
545
+ * no later settlement of it. In-memory scheduling and restart restoration share this one derivation.
546
+ */
547
+ function interruptedTwice(attempts: readonly AutoAttempt[], target: Target, digest: string): boolean {
548
+ let run = 0;
549
+ let parked = false;
550
+ for (const attempt of attempts) {
551
+ if (attempt.target !== target) continue;
552
+ if (attempt.digest === digest && attempt.state === "settled") { run = 0; parked = false; }
553
+ else if (attempt.digest === digest && attempt.state === "started" && !attempt.explicit) { run++; if (run >= 2) parked = true; }
554
+ else run = 0;
555
+ }
556
+ return parked;
557
+ }
558
+
559
+ function workerWasStopped(result: MindWorkerResult): boolean {
560
+ return result.status === "stopped";
561
+ }
562
+
563
+ function formatAutoPlan(plan: OptimizePlan): string {
564
+ return `Staged proposed change · ${plan.beforeCount} entries → ${plan.afterCount}\n${JSON.stringify(plan.changes, null, 2)}`;
565
+ }