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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/AGENTS.md +78 -0
  2. package/CHANGELOG.md +78 -0
  3. package/LICENSE +24 -0
  4. package/README.md +244 -2
  5. package/assets/banner.png +0 -0
  6. package/docs/DESIGN.md +282 -0
  7. package/docs/MEMORY-RESEARCH.md +112 -0
  8. package/package.json +93 -4
  9. package/src/core/auto-optimize.ts +239 -0
  10. package/src/core/backlog.ts +228 -0
  11. package/src/core/blocked.ts +38 -0
  12. package/src/core/capture.ts +146 -0
  13. package/src/core/context-budget.ts +74 -0
  14. package/src/core/host-compat.ts +13 -0
  15. package/src/core/ids.ts +59 -0
  16. package/src/core/inject.ts +247 -0
  17. package/src/core/memory-read.ts +34 -0
  18. package/src/core/memory.ts +308 -0
  19. package/src/core/migrate.ts +713 -0
  20. package/src/core/mind-settings.ts +54 -0
  21. package/src/core/optimize-history.ts +101 -0
  22. package/src/core/optimize-service.ts +182 -0
  23. package/src/core/optimize.ts +133 -0
  24. package/src/core/retrieval.ts +108 -0
  25. package/src/core/scanner.ts +146 -0
  26. package/src/core/scope.ts +205 -0
  27. package/src/core/service.ts +644 -0
  28. package/src/core/session-memory.ts +71 -0
  29. package/src/core/store.ts +948 -0
  30. package/src/extension/activity.ts +79 -0
  31. package/src/extension/auto-optimize-session.ts +118 -0
  32. package/src/extension/auto-optimize.ts +265 -0
  33. package/src/extension/mind-command.ts +335 -0
  34. package/src/extension/mind-worker.ts +32 -0
  35. package/src/extension/persona-dependency.ts +76 -0
  36. package/src/index.ts +1231 -0
  37. package/src/session-memory.ts +118 -0
  38. package/src/tools/backlog.ts +126 -0
  39. package/src/tools/memory-optimize.ts +133 -0
  40. package/src/tools/memory.ts +400 -0
  41. package/src/ui/mind-result-card.ts +15 -0
  42. package/src/ui/presentation.ts +97 -0
  43. package/src/ui/session-note-card.ts +50 -0
@@ -0,0 +1,79 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export const MIND_ACTIVITY_EVENT = "pi-persona:activity:v1";
4
+
5
+ export type MindActivityPhase = "inspect" | "stage" | "apply";
6
+ export type MindActivityState = "running" | "staged" | "done" | "failed";
7
+ export type MindActivityTarget = "project" | "project-long" | "persona" | "shared";
8
+
9
+ export interface MindActivityEvent {
10
+ version: 1;
11
+ producerId: "pi-persona-mind";
12
+ activityId: string;
13
+ sessionId: string;
14
+ phase: MindActivityPhase;
15
+ state: MindActivityState;
16
+ target: MindActivityTarget;
17
+ }
18
+
19
+ export interface MindActivityRunner {
20
+ run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T>;
21
+ }
22
+
23
+ export interface MindActivityOptions {
24
+ sessionId: string;
25
+ enabled(): boolean;
26
+ isCurrent(): boolean;
27
+ emit(channel: string, payload: MindActivityEvent): void;
28
+ }
29
+
30
+ /**
31
+ * Adapts a real local optimize operation to Persona's public activity protocol. The event deliberately
32
+ * carries no memory contents, model/provider, token counts, file paths, or completion claims beyond
33
+ * the operation's own explicit result.
34
+ */
35
+ export function createMindActivityRunner(options: MindActivityOptions): MindActivityRunner {
36
+ function publish(event: MindActivityEvent): void {
37
+ try {
38
+ if (!options.sessionId.trim() || !options.enabled() || !options.isCurrent()) return;
39
+ options.emit(MIND_ACTIVITY_EVENT, event);
40
+ } catch {
41
+ // Activity is a best-effort UI projection. A companion listener cannot alter a memory operation.
42
+ }
43
+ }
44
+ return {
45
+ async run<T>(phase: MindActivityPhase, target: MindActivityTarget, work: () => T | Promise<T>, isSuccess?: (result: T) => boolean): Promise<T> {
46
+ const base = { version: 1 as const, producerId: "pi-persona-mind" as const, activityId: randomUUID(), sessionId: options.sessionId, phase, target };
47
+ publish({ ...base, state: "running" });
48
+ try {
49
+ const result = await work();
50
+ let succeeded = false;
51
+ try { succeeded = (isSuccess ?? defaultSuccess)(result); } catch { /* malformed caller predicate is failure-shaped */ }
52
+ const state: MindActivityState = !succeeded ? "failed" : phase === "stage" ? "staged" : "done";
53
+ publish({ ...base, state });
54
+ return result;
55
+ } catch (error) {
56
+ publish({ ...base, state: "failed" });
57
+ throw error;
58
+ }
59
+ },
60
+ };
61
+ }
62
+
63
+ /** Run normally when no compatible Persona activity runner is available. Entry access is gated elsewhere. */
64
+ export function runMindActivity<T>(
65
+ runner: MindActivityRunner | undefined,
66
+ phase: MindActivityPhase,
67
+ target: MindActivityTarget,
68
+ work: () => T | Promise<T>,
69
+ isSuccess?: (result: T) => boolean,
70
+ ): Promise<T> {
71
+ if (runner) return runner.run(phase, target, work, isSuccess);
72
+ try { return Promise.resolve(work()); }
73
+ catch (error) { return Promise.reject(error); }
74
+ }
75
+
76
+ function defaultSuccess<T>(value: T): boolean {
77
+ const result: unknown = value;
78
+ return !result || typeof result !== "object" || !("ok" in result) || result.ok === true;
79
+ }
@@ -0,0 +1,118 @@
1
+ /** Pi lifecycle adapter. The scheduler never wakes the supervisor or owns its conversation. */
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { MindService } from "../core/service.ts";
4
+ import type { Scope } from "../core/scope.ts";
5
+ import type { AutoOptimizeTarget } from "../core/auto-optimize.ts";
6
+ import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, type AutoAttempt } from "./auto-optimize.ts";
7
+ import { launchMindWorker } from "./mind-worker.ts";
8
+ import { MIND_RESULT_ENTRY_TYPE } from "../ui/mind-result-card.ts";
9
+
10
+ interface Dependencies {
11
+ isDelegatedLeg: boolean;
12
+ available(ctx: ExtensionContext): boolean;
13
+ captureOwner(ctx: ExtensionContext): () => boolean;
14
+ scope(ctx: ExtensionContext): Scope;
15
+ persona(ctx: ExtensionContext): string | null;
16
+ mind(ctx: ExtensionContext): MindService;
17
+ }
18
+
19
+ /** Maps successful memory writes to their owned optimizer tier; shared LTM is never automatic. */
20
+ export function autoOptimizeTarget(input: unknown): AutoOptimizeTarget | undefined {
21
+ if (!input || typeof input !== "object" || Array.isArray(input)) return undefined;
22
+ const value = input as Record<string, unknown>;
23
+ const scope = value.scope;
24
+ if (scope !== undefined && scope !== "project" && scope !== "persona" && scope !== "shared") return undefined;
25
+ if (value.action === "remember") {
26
+ if (value.term === "short") return scope === undefined || scope === "project" ? "project" : undefined;
27
+ if (value.term !== "long" || scope === "shared") return undefined;
28
+ return scope === "project" ? "project-long" : "persona";
29
+ }
30
+ if (value.action === "promote") {
31
+ if (scope === "shared") return undefined;
32
+ return scope === "persona" ? "persona" : "project-long";
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ export interface AutoOptimizeSession {
38
+ activate(ctx: ExtensionContext, resetPreference?: boolean): void;
39
+ revoke(): void;
40
+ memoryAdded(ctx: ExtensionContext, target: AutoOptimizeTarget): void;
41
+ status(): string;
42
+ setEnabled(enabled: boolean): void;
43
+ }
44
+
45
+ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
46
+ const scheduler = new AutoOptimizeScheduler();
47
+ let boundKey: string | undefined;
48
+ let boundContext: ExtensionContext | undefined;
49
+ const tokenEvents = new Set<string>();
50
+ const safeAvailable = (ctx: ExtensionContext): boolean => {
51
+ try { return !deps.isDelegatedLeg && ctx.hasUI && ctx.mode !== "print" && deps.available(ctx); }
52
+ catch { return false; }
53
+ };
54
+ const revoke = (): void => { boundKey = undefined; boundContext = undefined; tokenEvents.clear(); scheduler.stop(); };
55
+ const activate = (ctx: ExtensionContext, resetPreference = false): void => {
56
+ if (!safeAvailable(ctx)) { revoke(); return; }
57
+ const scope = deps.scope(ctx);
58
+ // Automatic project maintenance never creates home-directory stores.
59
+ const key = JSON.stringify([ctx.sessionManager.getSessionId(), ctx.sessionManager.getSessionFile(), scope.persona, scope.paths]);
60
+ if (!resetPreference && boundKey === key && boundContext?.sessionManager === ctx.sessionManager) return;
61
+ boundKey = key; boundContext = ctx; tokenEvents.clear();
62
+ const captured = deps.captureOwner(ctx);
63
+ const current = () => boundKey === key && boundContext?.sessionManager === ctx.sessionManager && safeAvailable(ctx) && captured();
64
+ const attempts: AutoAttempt[] = [];
65
+ for (const entry of ctx.sessionManager.getBranch()) {
66
+ if (entry.type !== "custom" || entry.customType !== AUTO_ATTEMPT_ENTRY || !entry.data || typeof entry.data !== "object") continue;
67
+ const data = entry.data as Record<string, unknown>;
68
+ if (data.version === 1 && data.owner === key && typeof data.digest === "string" && /^[a-f0-9]{64}$/.test(data.digest) && typeof data.at === "number" && Number.isFinite(data.at) && data.at >= 0 && data.at <= Date.now() && (data.state === "started" || data.state === "settled")) {
69
+ const target = data.target === "project" || data.target === "project-long" || data.target === "persona" ? data.target : undefined;
70
+ attempts.push({ digest: data.digest, at: data.at, state: data.state, ...(target ? { target } : {}) });
71
+ if (attempts.length > 64) attempts.shift();
72
+ }
73
+ }
74
+ const owner = {
75
+ key, persona: scope.persona, current,
76
+ allowedTargets: scope.homeWorkspace ? ["persona"] as const : ["project", "project-long", "persona"] as const,
77
+ idle: () => ctx.isIdle() && !ctx.hasPendingMessages(),
78
+ optimizer: () => deps.mind(ctx).createOptimizer(),
79
+ launch: (task: string) => launchMindWorker(pi, ctx.sessionManager.getSessionId(), deps.persona(ctx), task),
80
+ recordAttempt: (attempt: AutoAttempt) => { if (!current()) throw new Error("automatic memory owner changed"); pi.appendEntry(AUTO_ATTEMPT_ENTRY, { version: 1, owner: key, ...attempt }); },
81
+ report: (title: string, body: string) => {
82
+ if (!current()) throw new Error("automatic memory owner changed");
83
+ pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body });
84
+ if (title !== "Mind automatic proposal") ctx.ui.notify(`Mind · ${body.split("\n", 1)[0]!.slice(0, 160)}`, "info");
85
+ }, attempts,
86
+ };
87
+ if (resetPreference) scheduler.activate(owner, process.env.PI_PERSONA_MIND_OPTIMIZE !== "off");
88
+ else scheduler.activate(owner);
89
+ };
90
+ const memoryAdded = (ctx: ExtensionContext, target: AutoOptimizeTarget): void => {
91
+ if (!safeAvailable(ctx)) return;
92
+ activate(ctx);
93
+ if ((target === "persona") || !deps.scope(ctx).homeWorkspace) scheduler.memoryAdded(target);
94
+ };
95
+ pi.on("input", () => { scheduler.interrupt(); });
96
+ pi.on("agent_start", () => { scheduler.interrupt(); });
97
+ pi.on("model_select", () => { scheduler.interrupt(); });
98
+ pi.on("ui_prompt_start", () => { scheduler.interrupt(); });
99
+ pi.on("turn_end", (event, ctx) => {
100
+ if (!safeAvailable(ctx) || event.message.role !== "assistant" || tokenEvents.has(event.messageEntryId)) return;
101
+ activate(ctx);
102
+ tokenEvents.add(event.messageEntryId);
103
+ while (tokenEvents.size > 256) tokenEvents.delete(tokenEvents.values().next().value!);
104
+ const usage = event.message.usage;
105
+ scheduler.tokensUsed(Math.max(0, usage.input));
106
+ });
107
+ pi.on("tool_result", (event, ctx) => {
108
+ if (event.toolName !== "memory" || event.isError || !event.details || typeof event.details !== "object" || (event.details as { ok?: unknown }).ok !== true) return;
109
+ const target = autoOptimizeTarget(event.input);
110
+ if (target) memoryAdded(ctx, target);
111
+ });
112
+ pi.on("agent_settled", (event, ctx) => { if (!event.aborted && safeAvailable(ctx)) { activate(ctx); scheduler.settled(); } });
113
+ pi.on("session_shutdown", async () => { revoke(); await scheduler.join(); });
114
+ return { activate, revoke, memoryAdded,
115
+ status: () => boundContext ? scheduler.status() : "inactive · automatic work requires an interactive Persona session",
116
+ setEnabled: (enabled) => scheduler.setEnabled(enabled),
117
+ };
118
+ }
@@ -0,0 +1,265 @@
1
+ /** Event-driven maintenance: one visible Persona worker, bounded evidence, existing CAS writes. */
2
+ import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, 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
+ type Target = AutoOptimizeTarget;
12
+ type Optimizer = Pick<MemoryOptimizer, "inspect" | "preview" | "apply" | "invalidate">;
13
+ interface CoverageCursor { offset: number; withinPage: number }
14
+ export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target }
15
+ export interface AutoOptimizeOwner {
16
+ key: string; persona: string;
17
+ allowedTargets: readonly Target[];
18
+ current(): boolean; idle(): boolean;
19
+ optimizer(): Optimizer;
20
+ launch(task: string): MindWorkerAdmission;
21
+ /** Must persist the proposal successfully before application is allowed. */
22
+ report(title: string, body: string): void;
23
+ recordAttempt(attempt: AutoAttempt): void;
24
+ attempts: AutoAttempt[];
25
+ }
26
+ interface Options { now?: () => number; schedule?: (work: () => void, delay: number) => () => void }
27
+
28
+ export class AutoOptimizeScheduler {
29
+ private readonly now: () => number;
30
+ private readonly schedule: NonNullable<Options["schedule"]>;
31
+ private owner: AutoOptimizeOwner | undefined;
32
+ private enabled = true;
33
+ private pending = new Set<Target>();
34
+ private retryTargets = new Set<Target>();
35
+ private cursors = new Map<Target, CoverageCursor>();
36
+ private inputTokens = 0;
37
+ private seen = new Set<string>();
38
+ private lastAttempt = -Infinity;
39
+ private generation = 0;
40
+ private disabledGeneration = 0;
41
+ private timer: (() => void) | undefined;
42
+ private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target } | undefined;
43
+ private work: Promise<void> = Promise.resolve();
44
+ private last = "waiting for new memory";
45
+
46
+ constructor(options: Options = {}) {
47
+ this.now = options.now ?? Date.now;
48
+ this.schedule = options.schedule ?? ((work, delay) => { const timer = setTimeout(work, delay); timer.unref(); return () => clearTimeout(timer); });
49
+ }
50
+ activate(owner: AutoOptimizeOwner, enabled = this.enabled): void {
51
+ this.stop(); this.owner = owner; this.enabled = enabled;
52
+ this.cursors = new Map(owner.allowedTargets.map((target) => [target, { offset: 0, withinPage: 0 }]));
53
+ const settledDigests = new Set(owner.attempts.filter((attempt) => attempt.state === "settled").map((attempt) => attempt.digest));
54
+ this.seen = new Set([...settledDigests].slice(-64));
55
+ this.lastAttempt = Math.max(-Infinity, ...owner.attempts.filter((a) => a.at <= this.now()).map((a) => a.at));
56
+ if (this.enabled) {
57
+ for (const attempt of owner.attempts) {
58
+ if (attempt.state === "started" && !settledDigests.has(attempt.digest) && attempt.target && owner.allowedTargets.includes(attempt.target)) {
59
+ this.pending.add(attempt.target);
60
+ this.retryTargets.add(attempt.target);
61
+ }
62
+ }
63
+ }
64
+ this.last = this.retryTargets.size ? "interrupted review pending" : "waiting for new memory";
65
+ }
66
+ stop(): void { this.interrupt(); this.owner = undefined; this.pending.clear(); this.retryTargets.clear(); this.cursors.clear(); this.inputTokens = 0; this.seen.clear(); this.lastAttempt = -Infinity; }
67
+ interrupt(): void {
68
+ this.timer?.(); this.timer = undefined; this.generation++;
69
+ if (this.enabled && this.running?.retryTarget) {
70
+ this.pending.add(this.running.retryTarget);
71
+ this.retryTargets.add(this.running.retryTarget);
72
+ }
73
+ this.running?.optimizer.invalidate(); this.running?.cancel?.();
74
+ }
75
+ setEnabled(enabled: boolean): void {
76
+ const wasEnabled = this.enabled;
77
+ this.enabled = enabled;
78
+ if (!enabled) {
79
+ this.disabledGeneration++;
80
+ this.interrupt();
81
+ this.pending.clear();
82
+ this.retryTargets.clear();
83
+ this.last = "automatic review disabled";
84
+ }
85
+ else {
86
+ if (!wasEnabled) this.last = "waiting for new memory";
87
+ this.settled();
88
+ }
89
+ }
90
+ status(): string {
91
+ const remaining = Math.max(0, AUTO_INPUT_TOKEN_THRESHOLD - this.inputTokens);
92
+ const retryPending = [...this.pending].some((target) => this.retryTargets.has(target));
93
+ const gate = retryPending ? "interrupted review pending; retry follows cooldown without another token wait"
94
+ : this.pending.size === 0 ? this.lastAttempt === -Infinity ? "first review waits for new memory" : "no dirty memory; new memory is required"
95
+ : this.lastAttempt === -Infinity ? "first dirty review is ready after idle"
96
+ : `dirty review pending; ${remaining.toLocaleString("en-US")} main input tokens remain`;
97
+ return `${this.enabled ? "on" : "off"} · ${this.running ? "Mind worker active" : this.last} · ${gate} · ${this.inputTokens.toLocaleString("en-US")}/${AUTO_INPUT_TOKEN_THRESHOLD.toLocaleString("en-US")} main input tokens since last attempt`;
98
+ }
99
+ memoryAdded(target: Target): void { if (this.enabled && this.owner && this.allows(this.owner, target)) this.pending.add(target); }
100
+ tokensUsed(mainInputTokens: number): void { if (this.owner && Number.isSafeInteger(mainInputTokens) && mainInputTokens > 0) this.inputTokens = Math.min(AUTO_INPUT_TOKEN_THRESHOLD, this.inputTokens + mainInputTokens); }
101
+ settled(): void {
102
+ const owner = this.owner;
103
+ if (!this.enabled || !owner || !this.safeCurrent(owner) || !owner.idle() || this.running || this.timer || !this.pending.size) return;
104
+ const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
105
+ const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
106
+ if (!eligiblePending) return;
107
+ const generation = this.generation;
108
+ this.timer = this.schedule(() => {
109
+ this.timer = undefined;
110
+ if (generation !== this.generation) return;
111
+ this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
112
+ }, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
113
+ }
114
+ join(): Promise<void> { return this.work; }
115
+ private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
116
+ private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
117
+ private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number): void {
118
+ owner.recordAttempt({ digest, target, at, state });
119
+ if (state === "settled") {
120
+ this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
121
+ }
122
+ }
123
+ private async run(): Promise<void> {
124
+ const owner = this.owner;
125
+ if (!owner || !this.enabled || !this.safeCurrent(owner) || !owner.idle() || this.running) return;
126
+ const generation = this.generation;
127
+ const disabledGeneration = this.disabledGeneration;
128
+ const current = () => generation === this.generation && this.enabled && this.safeCurrent(owner) && owner.idle();
129
+ const mayRetry = () => this.enabled && this.disabledGeneration === disabledGeneration && this.safeCurrent(owner);
130
+ const optimizer = owner.optimizer();
131
+ const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer };
132
+ let attemptRecorded = false;
133
+ let unsettledTarget: Target | undefined;
134
+ let nextCursor: CoverageCursor | undefined;
135
+ let retryRequiresSettled = false;
136
+ this.running = running;
137
+ try {
138
+ for (const target of [...this.pending]) {
139
+ if (!this.allows(owner, target)) { this.pending.delete(target); this.retryTargets.delete(target); continue; }
140
+ const retry = this.retryTargets.has(target);
141
+ const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
142
+ if (!retry && !tokenReady) continue;
143
+ this.pending.delete(target);
144
+ const cursor = this.cursors.get(target) ?? { offset: 0, withinPage: 0 };
145
+ let inspection: OptimizeInspection | OptimizeFailure;
146
+ let newestInspection: OptimizeInspection | undefined;
147
+ try {
148
+ inspection = await optimizer.inspect(target, { max: 100, offset: cursor.offset });
149
+ if (inspection.ok && cursor.offset > 0) {
150
+ const latest = await optimizer.inspect(target, { max: 100, offset: 0 });
151
+ if (latest.ok && latest.target === target && latest.fingerprint === inspection.fingerprint) newestInspection = latest;
152
+ else {
153
+ if (mayRetry()) this.pending.add(target);
154
+ this.last = "store changed during bounded inspection; waiting for the next settled event";
155
+ return;
156
+ }
157
+ }
158
+ }
159
+ catch {
160
+ if (!current()) {
161
+ if (mayRetry()) this.pending.add(target);
162
+ return;
163
+ }
164
+ this.last = "store inspection failed; see /mind doctor";
165
+ continue;
166
+ }
167
+ if (!current()) {
168
+ // An interruption can invalidate the in-flight read without revoking the owner.
169
+ // Keep its trigger so a later settled event can retry the inspection.
170
+ if (mayRetry()) this.pending.add(target);
171
+ return;
172
+ }
173
+ if (!inspection.ok) { this.last = "store inspection refused; see /mind doctor"; continue; }
174
+ if (inspection.target !== target) { this.last = "store inspection returned a different tier; no worker started"; continue; }
175
+ const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, newestInspection);
176
+ nextCursor = page.pageComplete
177
+ ? { offset: inspection.nextOffset ?? 0, withinPage: 0 }
178
+ : { offset: cursor.offset, withinPage: page.nextRotation };
179
+ const input = page.input;
180
+ if (!input) {
181
+ this.cursors.set(target, nextCursor);
182
+ this.retryTargets.delete(target);
183
+ this.last = "no eligible records in this bounded page";
184
+ continue;
185
+ }
186
+ if (this.seen.has(input.digest)) {
187
+ this.cursors.set(target, nextCursor);
188
+ this.retryTargets.delete(target);
189
+ this.last = "this bounded record set was already reviewed";
190
+ continue;
191
+ }
192
+ const worker = owner.launch(buildAutoPrompt(input));
193
+ if (!worker.ok) { this.pending.add(target); this.last = worker.reason; return; }
194
+ const attemptAt = this.now();
195
+ running.cancel = worker.cancel;
196
+ running.retryTarget = target;
197
+ this.retryTargets.delete(target);
198
+ this.lastAttempt = attemptAt; this.inputTokens = 0; this.last = "Mind is reviewing memory";
199
+ unsettledTarget = target;
200
+ const settle = (): void => {
201
+ this.remember(owner, target, input.digest, "settled", attemptAt);
202
+ if (nextCursor) this.cursors.set(target, nextCursor);
203
+ unsettledTarget = undefined;
204
+ };
205
+ try {
206
+ this.remember(owner, target, input.digest, "started", attemptAt);
207
+ attemptRecorded = true;
208
+ } catch {
209
+ try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
210
+ this.last = "attempt could not be saved; worker cancelled before apply";
211
+ return;
212
+ }
213
+ const result = await worker.completion;
214
+ if (!current()) return;
215
+ if (workerWasStopped(result)) {
216
+ retryRequiresSettled = true;
217
+ this.pending.add(target);
218
+ this.retryTargets.add(target);
219
+ unsettledTarget = undefined;
220
+ this.last = "review interrupted; waiting for the next settled event";
221
+ return;
222
+ }
223
+ if (!result.ok) { settle(); this.last = "worker failed; memory unchanged"; owner.report("Mind automatic optimization", `${this.last}${result.error ? `: ${result.error}` : ""}`); return; }
224
+ const parsed = parseAutoProposal(result.output, input);
225
+ if (!parsed.ok) { settle(); this.last = "proposal refused; memory unchanged"; owner.report("Mind automatic optimization", `${this.last}: ${parsed.reason}`); return; }
226
+ const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
227
+ if (!parsed.operations.length) { settle(); this.last = "bounded review found no safe consolidation in this record set"; owner.report("Mind automatic optimization", `${this.last}\n${provenance}`); return; }
228
+ const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
229
+ if (!current()) return;
230
+ if (!plan.ok) { settle(); this.last = "store or proposal changed; nothing applied"; owner.report("Mind automatic optimization", `${this.last}: ${plan.reason}\n${provenance}`); return; }
231
+ owner.report("Mind automatic proposal", `${provenance}\n${formatAutoPlan(plan)}\nAutomatic apply pending; it proceeds only while this owner and snapshot remain current.`);
232
+ if (!current()) { optimizer.invalidate(); return; }
233
+ const applied = await optimizer.apply(plan.planId);
234
+ if (!current()) return;
235
+ settle();
236
+ this.last = applied.ok ? `${applied.beforeCount} → ${applied.afterCount} memories; ${applied.changed} replacement(s)` : `not applied: ${applied.reason}`;
237
+ const receipt = applied.ok
238
+ ? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
239
+ : "";
240
+ const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
241
+ owner.report("Mind automatic result", `${this.last}\n${provenance}${receipt}${warning}`);
242
+ return; // One worker per pass; other dirty tiers wait for the input floor and cooldown.
243
+ }
244
+ } finally {
245
+ optimizer.invalidate();
246
+ if (this.running === running) this.running = undefined;
247
+ if (unsettledTarget !== undefined && !current() && mayRetry()) {
248
+ this.pending.add(unsettledTarget);
249
+ this.retryTargets.add(unsettledTarget);
250
+ this.last = "review interrupted; waiting for the next settled event";
251
+ }
252
+ // One actual attempt may leave other dirty tiers pending; they need the input floor
253
+ // and cooldown. Only the same interrupted target bypasses the token floor.
254
+ if (attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
255
+ }
256
+ }
257
+ }
258
+
259
+ function workerWasStopped(result: MindWorkerResult): boolean {
260
+ return result.status === "stopped";
261
+ }
262
+
263
+ function formatAutoPlan(plan: OptimizePlan): string {
264
+ return `Staged automatic change · ${plan.beforeCount} entries → ${plan.afterCount}\n${JSON.stringify(plan.changes, null, 2)}`;
265
+ }