@aeondave/pi-persona-mind 0.8.7 → 0.9.1

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.
@@ -11,7 +11,21 @@ export const AUTO_ATTEMPT_ENTRY = "pi-persona-mind-auto-attempt";
11
11
  type Target = AutoOptimizeTarget;
12
12
  type Optimizer = Pick<MemoryOptimizer, "inspect" | "preview" | "apply" | "invalidate">;
13
13
  interface CoverageCursor { offset: number; withinPage: number }
14
- export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target }
14
+ export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target; explicit?: true }
15
+ /** Parent-held single-flight lease spanning evidence, worker, preview and user apply. */
16
+ export interface ReviewReservation {
17
+ current(): boolean;
18
+ launched(digest: string): void;
19
+ settled(): void;
20
+ release(): void;
21
+ }
22
+ export interface AutoOptimizeReportContext {
23
+ automatic: boolean;
24
+ target: Target;
25
+ phase: "proposal" | "result";
26
+ summary: string;
27
+ attention: boolean;
28
+ }
15
29
  export interface AutoOptimizeOwner {
16
30
  key: string; persona: string;
17
31
  allowedTargets: readonly Target[];
@@ -19,7 +33,7 @@ export interface AutoOptimizeOwner {
19
33
  optimizer(): Optimizer;
20
34
  launch(task: string): MindWorkerAdmission;
21
35
  /** Must persist the proposal successfully before application is allowed. */
22
- report(title: string, body: string): void;
36
+ report(title: string, body: string, context?: AutoOptimizeReportContext): void;
23
37
  recordAttempt(attempt: AutoAttempt): void;
24
38
  attempts: AutoAttempt[];
25
39
  }
@@ -32,6 +46,7 @@ export class AutoOptimizeScheduler {
32
46
  private enabled = true;
33
47
  private pending = new Set<Target>();
34
48
  private retryTargets = new Set<Target>();
49
+ private retryAttempts = new Map<Target, { digest: string; at: number }>();
35
50
  private cursors = new Map<Target, CoverageCursor>();
36
51
  private inputTokens = 0;
37
52
  private seen = new Set<string>();
@@ -41,6 +56,7 @@ export class AutoOptimizeScheduler {
41
56
  private timer: (() => void) | undefined;
42
57
  private timerGeneration = 0;
43
58
  private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean } | undefined;
59
+ private review: { target: Target; attempt?: { digest: string; at: number }; settled: boolean } | undefined;
44
60
  private work: Promise<void> = Promise.resolve();
45
61
  private last = "waiting for new memory";
46
62
 
@@ -55,16 +71,21 @@ export class AutoOptimizeScheduler {
55
71
  this.seen = new Set([...settledDigests].slice(-64));
56
72
  this.lastAttempt = Math.max(-Infinity, ...owner.attempts.filter((a) => a.at <= this.now()).map((a) => a.at));
57
73
  if (this.enabled) {
58
- for (const attempt of owner.attempts) {
59
- if (attempt.state === "started" && !settledDigests.has(attempt.digest) && attempt.target && owner.allowedTargets.includes(attempt.target)) {
74
+ // A later attempt supersedes the interrupted trigger for that tier, even when new
75
+ // records changed its digest. Never resurrect an older launch after the retry settled.
76
+ const latestByTarget = new Map<Target, AutoAttempt>();
77
+ for (const attempt of owner.attempts) if (attempt.target) latestByTarget.set(attempt.target, attempt);
78
+ for (const attempt of latestByTarget.values()) {
79
+ if (attempt.state === "started" && !attempt.explicit && !settledDigests.has(attempt.digest) && attempt.target && owner.allowedTargets.includes(attempt.target)) {
60
80
  this.pending.add(attempt.target);
61
81
  this.retryTargets.add(attempt.target);
82
+ this.retryAttempts.set(attempt.target, { digest: attempt.digest, at: attempt.at });
62
83
  }
63
84
  }
64
85
  }
65
86
  this.last = this.retryTargets.size ? "interrupted review pending" : "waiting for new memory";
66
87
  }
67
- 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; }
88
+ stop(): void { this.review = undefined; this.interrupt(); this.owner = undefined; this.pending.clear(); this.retryTargets.clear(); this.retryAttempts.clear(); this.cursors.clear(); this.inputTokens = 0; this.seen.clear(); this.lastAttempt = -Infinity; }
68
89
  interrupt(): void {
69
90
  this.timer?.(); this.timer = undefined; this.timerGeneration++; this.generation++;
70
91
  if (this.enabled && !this.running?.explicit && this.running?.retryTarget) {
@@ -81,6 +102,7 @@ export class AutoOptimizeScheduler {
81
102
  this.interrupt();
82
103
  this.pending.clear();
83
104
  this.retryTargets.clear();
105
+ this.retryAttempts.clear();
84
106
  this.last = "automatic review disabled";
85
107
  }
86
108
  else {
@@ -95,13 +117,14 @@ export class AutoOptimizeScheduler {
95
117
  : this.pending.size === 0 ? this.lastAttempt === -Infinity ? "first review waits for new memory" : "no dirty memory; new memory is required"
96
118
  : this.lastAttempt === -Infinity ? "first dirty review is ready after idle"
97
119
  : `dirty review pending; ${remaining.toLocaleString("en-US")} main input tokens remain`;
98
- 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`;
120
+ const activity = this.review ? `knowledge review ${this.review.attempt ? "active" : "reserved"} — ${this.review.target}` : this.running ? "Mind worker active" : this.last;
121
+ 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`;
99
122
  }
100
123
  memoryAdded(target: Target): void { if (this.enabled && this.owner && this.allows(this.owner, target)) this.pending.add(target); }
101
124
  tokensUsed(mainInputTokens: number): void { if (this.owner && Number.isSafeInteger(mainInputTokens) && mainInputTokens > 0) this.inputTokens = Math.min(AUTO_INPUT_TOKEN_THRESHOLD, this.inputTokens + mainInputTokens); }
102
125
  settled(): void {
103
126
  const owner = this.owner;
104
- if (!this.enabled || !owner || !this.safeCurrent(owner) || !owner.idle() || this.running || this.timer || !this.pending.size) return;
127
+ if (!this.enabled || !owner || !this.safeCurrent(owner) || !owner.idle() || this.running || this.review || this.timer || !this.pending.size) return;
105
128
  const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
106
129
  const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
107
130
  if (!eligiblePending) return;
@@ -110,16 +133,51 @@ export class AutoOptimizeScheduler {
110
133
  this.timer = this.schedule(() => {
111
134
  if (timerGeneration !== this.timerGeneration) return;
112
135
  this.timer = undefined;
113
- if (generation !== this.generation || this.running) return;
136
+ if (generation !== this.generation || this.running || this.review) return;
114
137
  this.work = this.run().catch(() => { this.last = "inspection failed; no automatic retry"; });
115
138
  }, Math.max(AUTO_IDLE_MS, this.lastAttempt + AUTO_COOLDOWN_MS - this.now()));
116
139
  }
140
+ /** Reserve explicit review without spending an attempt or cancelling a real worker.
141
+ * Lease identity, not scheduler generation, survives the review's own UI prompts.
142
+ */
143
+ reserveReview(target: Target): ReviewReservation | undefined {
144
+ const owner = this.owner;
145
+ if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || !this.allows(owner, target) || this.running || this.review) return undefined;
146
+ this.timer?.(); this.timer = undefined; this.timerGeneration++;
147
+ const lease: NonNullable<AutoOptimizeScheduler["review"]> = { target, settled: false };
148
+ this.review = lease;
149
+ const current = () => this.review === lease && this.safeCurrent(owner) && this.safeIdle(owner) && this.allows(owner, target);
150
+ return {
151
+ current,
152
+ launched: (digest) => {
153
+ if (!current()) throw new Error("knowledge review reservation is no longer current or was released");
154
+ if (lease.attempt) throw new Error("knowledge review launch already recorded");
155
+ if (!/^[a-f0-9]{64}$/.test(digest)) throw new Error("knowledge review digest must be a SHA-256 lowercase hex string");
156
+ const at = this.now();
157
+ // Called only after actual Persona admission: reset even if recording fails.
158
+ lease.attempt = { digest, at };
159
+ this.lastAttempt = at; this.inputTokens = 0;
160
+ this.retryTargets.delete(target); this.retryAttempts.delete(target);
161
+ this.remember(owner, target, digest, "started", at, true);
162
+ },
163
+ settled: () => {
164
+ if (!current() || !lease.attempt || lease.settled) return;
165
+ this.remember(owner, target, lease.attempt.digest, "settled", lease.attempt.at, true);
166
+ lease.settled = true;
167
+ },
168
+ release: () => {
169
+ if (this.review !== lease) return;
170
+ this.review = undefined;
171
+ this.last = lease.settled ? "knowledge review settled" : "knowledge review released; no automatic retry";
172
+ },
173
+ };
174
+ }
117
175
  /** Current writable tiers, in the order a bare explicit request will review. */
118
176
  targets(): readonly Target[] { return this.owner ? [...new Set(this.owner.allowedTargets)].slice(0, 3) : []; }
119
177
  /** Start one named pass, or one bounded sequential pass over every allowed nonshared tier. */
120
178
  startExplicit(target?: Target): boolean {
121
179
  const owner = this.owner;
122
- if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || (target !== undefined && !this.allows(owner, target))) return false;
180
+ if (!owner || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review || (target !== undefined && !this.allows(owner, target))) return false;
123
181
  const targets = target === undefined ? [...this.targets()] : [target];
124
182
  if (targets.length === 0) return false;
125
183
  this.timer?.(); this.timer = undefined; this.timerGeneration++;
@@ -139,15 +197,20 @@ export class AutoOptimizeScheduler {
139
197
  private safeCurrent(owner: AutoOptimizeOwner): boolean { try { return this.owner === owner && owner.current(); } catch { return false; } }
140
198
  private safeIdle(owner: AutoOptimizeOwner): boolean { try { return owner.idle(); } catch { return false; } }
141
199
  private allows(owner: AutoOptimizeOwner, target: Target): boolean { return owner.allowedTargets.includes(target); }
142
- private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number): void {
143
- owner.recordAttempt({ digest, target, at, state });
200
+ private remember(owner: AutoOptimizeOwner, target: Target, digest: string, state: AutoAttempt["state"], at: number, explicit = false): void {
201
+ owner.recordAttempt({ digest, target, at, state, ...(explicit ? { explicit: true } : {}) });
144
202
  if (state === "settled") {
145
203
  this.seen.add(digest); while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
146
204
  }
147
205
  }
206
+ private settleSkippedRetry(owner: AutoOptimizeOwner, target: Target): void {
207
+ const attempt = this.retryTargets.has(target) ? this.retryAttempts.get(target) : undefined;
208
+ if (attempt) this.remember(owner, target, attempt.digest, "settled", attempt.at);
209
+ this.retryAttempts.delete(target);
210
+ }
148
211
  private async run(explicitTargets?: readonly Target[], explicit = false, qualifyTargets = false): Promise<void> {
149
212
  const owner = this.owner;
150
- if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running) return;
213
+ if (!owner || (!explicit && !this.enabled) || !this.safeCurrent(owner) || !this.safeIdle(owner) || this.running || this.review) return;
151
214
  const generation = this.generation;
152
215
  const disabledGeneration = this.disabledGeneration;
153
216
  const current = () => generation === this.generation && (explicit || this.enabled) && this.safeIdle(owner) && this.safeCurrent(owner);
@@ -168,7 +231,7 @@ export class AutoOptimizeScheduler {
168
231
  let nextCursor: CoverageCursor | undefined;
169
232
  let retryRequiresSettled = false;
170
233
  let activeTarget: Target | undefined;
171
- const report = (target: Target, title: string, body: string, summary?: string, stopped = false): boolean => {
234
+ const report = (target: Target, title: string, body: string, summary?: string, stopped = false, attention = stopped): boolean => {
172
235
  if (!current()) return false;
173
236
  const remaining = stopped && qualifyTargets ? targets.slice(targets.indexOf(target) + 1) : [];
174
237
  const stoppedLine = remaining.length ? `Batch stopped; not reviewed: ${remaining.join(", ")}.\n` : "";
@@ -176,7 +239,9 @@ export class AutoOptimizeScheduler {
176
239
  const qualifiedBody = qualifyTargets && !body.startsWith("Target:")
177
240
  ? `Target: ${target} — ${outcome}\n${stoppedLine}${body}`
178
241
  : body;
179
- owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody);
242
+ owner.report(qualifyTargets ? `${title} — ${target}` : title, qualifiedBody, {
243
+ automatic: !explicit, target, phase: title.endsWith("proposal") ? "proposal" : "result", summary: outcome, attention,
244
+ });
180
245
  return true;
181
246
  };
182
247
  this.running = running;
@@ -238,6 +303,7 @@ export class AutoOptimizeScheduler {
238
303
  : { offset: cursor.offset, withinPage: page.nextRotation };
239
304
  const input = page.input;
240
305
  if (!input) {
306
+ if (!explicit) this.settleSkippedRetry(owner, target);
241
307
  this.cursors.set(target, nextCursor);
242
308
  this.retryTargets.delete(target);
243
309
  this.last = "no eligible records in this bounded page";
@@ -245,13 +311,23 @@ export class AutoOptimizeScheduler {
245
311
  continue;
246
312
  }
247
313
  if (!explicit && this.seen.has(input.digest)) {
314
+ this.settleSkippedRetry(owner, target);
248
315
  this.cursors.set(target, nextCursor);
249
316
  this.retryTargets.delete(target);
250
317
  this.last = "this bounded record set was already reviewed";
251
318
  continue;
252
319
  }
320
+ if (!explicit && !input.entries.some((entry, index) => input.entries.some((other, otherIndex) => otherIndex !== index && other.kind === entry.kind && other.persona === entry.persona))) {
321
+ this.settleSkippedRetry(owner, target);
322
+ this.seen.add(input.digest);
323
+ while (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!);
324
+ this.cursors.set(target, nextCursor);
325
+ this.retryTargets.delete(target);
326
+ this.last = "no eligible same-kind pair in this bounded page";
327
+ continue;
328
+ }
253
329
  if (!current()) return;
254
- const worker = owner.launch(buildAutoPrompt(input));
330
+ const worker = owner.launch(buildAutoPrompt(input, explicit ? "explicit" : "automatic"));
255
331
  if (!worker.ok) {
256
332
  if (!explicit) this.pending.add(target);
257
333
  this.last = worker.reason;
@@ -262,22 +338,31 @@ export class AutoOptimizeScheduler {
262
338
  running.cancel = worker.cancel;
263
339
  running.retryTarget = target;
264
340
  this.retryTargets.delete(target);
265
- if (!explicit) { this.lastAttempt = attemptAt; this.inputTokens = 0; }
341
+ // Explicit requests bypass admission gates, but every actual worker resets the
342
+ // automatic baseline so a queued dirty tier cannot run again seconds later.
343
+ this.lastAttempt = attemptAt; this.inputTokens = 0;
266
344
  this.last = "Mind is reviewing memory";
267
345
  unsettledTarget = target;
268
346
  const settle = (): void => {
269
- if (!explicit) this.remember(owner, target, input.digest, "settled", attemptAt);
347
+ this.remember(owner, target, input.digest, "settled", attemptAt, explicit);
270
348
  if (nextCursor) this.cursors.set(target, nextCursor);
349
+ this.retryAttempts.delete(target);
271
350
  unsettledTarget = undefined;
272
351
  };
273
352
  try {
353
+ this.remember(owner, target, input.digest, "started", attemptAt, explicit);
274
354
  if (!explicit) {
275
- this.remember(owner, target, input.digest, "started", attemptAt);
355
+ this.retryAttempts.set(target, { digest: input.digest, at: attemptAt });
276
356
  attemptRecorded = true;
277
357
  }
278
358
  } catch {
279
359
  try { running.cancel?.(); } catch { /* best-effort stop before apply */ }
280
360
  this.last = "attempt could not be saved; worker cancelled before apply";
361
+ // Keep the one-worker slot until cancellation has actually joined its worker.
362
+ try { await worker.completion; } catch { /* failed cancellation is still terminal */ }
363
+ report(target, explicit ? "Mind optimization result" : "Mind automatic result",
364
+ `Bounded review stopped: ${this.last}; memory unchanged.\nWorker ${worker.runId} · ${worker.model} · ${worker.thinking}`,
365
+ "attempt could not be saved; memory unchanged", explicit, true);
281
366
  return;
282
367
  }
283
368
  const result = await worker.completion;
@@ -296,27 +381,31 @@ export class AutoOptimizeScheduler {
296
381
  const provenance = `Worker ${worker.runId} · ${worker.model} · ${worker.thinking}${result.resultRef ? `\nTerminal report: ${result.resultRef}` : ""}`;
297
382
  if (!result.ok) {
298
383
  settle(); this.last = "worker failed; memory unchanged";
299
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}${result.error ? `: ${result.error}` : ""}\n${provenance}`, "worker failed; memory unchanged", explicit);
384
+ 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);
300
385
  return;
301
386
  }
302
387
  const parsed = parseAutoProposal(result.output, input);
303
388
  if (!parsed.ok) {
304
389
  settle(); this.last = "proposal refused; memory unchanged";
305
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}\n${provenance}`, "proposal refused; memory unchanged", explicit);
390
+ report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded review · ${this.last}: ${parsed.reason}\n${provenance}`, "proposal refused; memory unchanged", explicit, true);
306
391
  return;
307
392
  }
308
393
  if (!parsed.operations.length) {
309
394
  settle(); this.last = "bounded review found no safe consolidation in this record set";
310
- report(target, explicit ? "Mind optimization result" : "Mind automatic optimization", `Bounded coverage: one selected record window; ${this.last}.\n${provenance}`, "reviewed no-op; no safe consolidation in this window");
395
+ 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");
311
396
  if (!explicit) return;
312
397
  continue;
313
398
  }
399
+ if (!explicit && parsed.operations.some((operation) => operation.sourceIds.length < 2)) {
400
+ settle(); this.last = "proposal ineligible for automatic consolidation; memory unchanged";
401
+ return;
402
+ }
314
403
  if (!current()) return;
315
404
  const plan = await optimizer.preview({ target: input.target, fingerprint: input.fingerprint, operations: parsed.operations });
316
405
  if (!current()) return;
317
406
  if (!plan.ok) {
318
407
  settle(); this.last = "store or proposal changed; nothing applied";
319
- 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);
408
+ 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);
320
409
  return;
321
410
  }
322
411
  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;
@@ -329,14 +418,34 @@ export class AutoOptimizeScheduler {
329
418
  ? applied.receiptId ? `\nUndo: /mind optimize undo ${applied.receiptId} ${applied.target}.` : "\nNo durable undo receipt was returned."
330
419
  : "";
331
420
  const warning = applied.ok && applied.warning ? `\nWarning: ${applied.warning}` : "";
421
+ const needsAttention = !applied.ok || Boolean(applied.warning) || (applied.ok && !applied.receiptId);
332
422
  const resultSummary = applied.ok
333
- ? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : ""}`
423
+ ? `${applied.changed} replacement${applied.changed === 1 ? "" : "s"} applied${applied.warning ? "; receipt finalization warning" : !applied.receiptId && !explicit ? "; receipt warning" : ""}`
334
424
  : `not applied: ${applied.reason}`;
335
- 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)))) return;
425
+ 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;
336
426
  if (!applied.ok || applied.warning || !explicit) return;
337
427
  }
338
428
  } catch (error) {
339
- if (!explicit) throw error;
429
+ if (!explicit) {
430
+ this.last = "automatic review failed unexpectedly; inspect current memory before retrying because apply may have completed";
431
+ if (unsettledTarget && current()) {
432
+ const attempt = this.retryAttempts.get(unsettledTarget);
433
+ if (attempt) {
434
+ try {
435
+ // Terminal failure is not completed coverage. Persist suppression without
436
+ // advancing the cursor, so reload cannot retry a possibly committed apply.
437
+ this.remember(owner, unsettledTarget, attempt.digest, "settled", attempt.at);
438
+ this.retryAttempts.delete(unsettledTarget);
439
+ this.retryTargets.delete(unsettledTarget);
440
+ unsettledTarget = undefined;
441
+ } catch { /* Keep the warning even when terminal accounting cannot be saved. */ }
442
+ }
443
+ }
444
+ if (activeTarget && current()) {
445
+ try { report(activeTarget, "Mind automatic result", this.last, "review failed; inspect memory before retrying", false, true); } catch { /* reporting can itself fail */ }
446
+ }
447
+ return;
448
+ }
340
449
  this.last = "explicit review failed unexpectedly; inspect current memory before retrying because apply may have completed";
341
450
  if (activeTarget && current()) report(activeTarget, "Mind optimization result", `Bounded review failed unexpectedly; ${this.last}.`, "review failed unexpectedly; inspect current memory before retrying", true);
342
451
  } finally {
@@ -0,0 +1,69 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { MemoryEntry } from "../core/memory.ts";
3
+ import { buildInspectorTimeline, findMemoryRecordingSource, findSessionNoteRecordingSource, INSPECTOR_PAGE_SIZE, MAX_INSPECTOR_BRANCH_ENTRIES } from "../core/memory-inspector.ts";
4
+ import type { SessionMemory } from "../session-memory.ts";
5
+ import type { MindService } from "../core/service.ts";
6
+
7
+ export type InspectorTab = "memories" | "context" | "timeline";
8
+ export type InspectorScope = "session" | "project" | "project-long" | "persona" | "shared";
9
+ export interface InspectorRequest { tab: InspectorTab; scope: InspectorScope; query: string; offset: number }
10
+ export interface InspectorItem { id: string; title: string; body: string; source?: { title: string; body: string } }
11
+ export interface InspectorPage { items: InspectorItem[]; total: number; offset: number; nextOffset?: number; notice: string }
12
+
13
+ const PAGE_SIZE = INSPECTOR_PAGE_SIZE;
14
+ const safeOffset = (offset: number): number => Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
15
+ const safeQuery = (query: string): string => typeof query === "string" ? query.slice(0, 512) : "";
16
+ function inspectionScope(mind: MindService): ReturnType<MindService["inspectionScope"]> | undefined {
17
+ try { return mind.inspectionScope(); } catch { return undefined; }
18
+ }
19
+ function unavailable(notice: string): InspectorPage { return { items: [], total: 0, offset: 0, notice }; }
20
+ function sessionNoteItems(ctx: ExtensionContext, sessionMemory: SessionMemory, request: InspectorRequest): InspectorPage {
21
+ const snapshot = sessionMemory.snapshot(ctx);
22
+ if (!snapshot.ok) return unavailable(`Active-session notes unavailable: ${snapshot.reason ?? "snapshot failed"}.`);
23
+ let branch: unknown[] = [];
24
+ let noteHistory: unknown[] = [];
25
+ try {
26
+ branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
27
+ noteHistory = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
28
+ } catch { /* current snapshot remains useful; source is omitted without native evidence */ }
29
+ const query = safeQuery(request.query).trim().toLowerCase();
30
+ const entries = snapshot.notes.filter((note) => !query || `${note.kind} ${note.text} ${note.source ?? ""}`.toLowerCase().includes(query)).sort((a, b) => Date.parse(b.recordedAt) - Date.parse(a.recordedAt));
31
+ const offset = safeOffset(request.offset);
32
+ const page = entries.slice(offset, offset + PAGE_SIZE);
33
+ return { items: page.map((note) => {
34
+ const source = findSessionNoteRecordingSource(note, branch, noteHistory);
35
+ const body = [`text: ${note.text}`, `id: ${note.id}`, `kind: ${note.kind}`, `recorded: ${note.recordedAt}`, `origin session id: ${note.originSessionId}`, ...(note.source === undefined ? [] : [`literal source metadata (not opened): ${note.source}`]), ...(source ? [] : ["No resolvable recording in this active-branch window."])].join("\n");
36
+ return { id: note.id, title: `${note.kind} · ${note.recordedAt} · ${note.text.replace(/\s+/g, " ").slice(0, 100)}`, body, ...(source ? { source } : {}) };
37
+ }), total: entries.length, offset, ...(offset + page.length < entries.length ? { nextOffset: offset + page.length } : {}), notice: `Active-branch session notes only (${snapshot.storage} storage). Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} native entries. ${entries.length} matching active notes.` };
38
+ }
39
+
40
+ export async function loadInspectorPage(ctx: ExtensionContext, mind: MindService, sessionMemory: SessionMemory, request: InspectorRequest): Promise<InspectorPage> {
41
+ const offset = safeOffset(request.offset);
42
+ const query = safeQuery(request.query);
43
+ if (request.tab === "context") return unavailable("No context snapshot is available from the read-only inspector data layer.");
44
+ if (request.tab === "timeline") {
45
+ try {
46
+ const branch = ctx.sessionManager.getBranch();
47
+ const history = ctx.sessionManager.getEntries().filter((entry) => entry.type === "custom" && entry.customType === "pi-persona-mind-session-note").map((entry) => entry.type === "custom" ? entry.data : undefined);
48
+ const page = buildInspectorTimeline(branch, history, { query, offset });
49
+ return { items: page.items.map(({ id, title, body, source }) => ({ id, title, body, ...(source ? { source } : {}) })), total: page.total, offset: page.offset, ...(page.nextOffset === undefined ? {} : { nextOffset: page.nextOffset }), notice: page.notice };
50
+ } catch { return unavailable("Native active-branch timeline is unavailable."); }
51
+ }
52
+ if (request.scope === "session") return sessionNoteItems(ctx, sessionMemory, { ...request, query, offset });
53
+ const activeScope = inspectionScope(mind);
54
+ if (!activeScope) return unavailable("Mind inspection scope is unavailable; no memory store was read.");
55
+ if ((request.scope === "project" || request.scope === "project-long") && activeScope.homeWorkspace) return unavailable("Project memory scopes are unavailable in the home workspace.");
56
+ try {
57
+ const target = request.scope;
58
+ const inspection = await mind.createOptimizer().inspect(target, { query, offset, max: PAGE_SIZE });
59
+ if (!inspection.ok) return unavailable(`Memory inspection unavailable: ${inspection.reason}`);
60
+ let branch: unknown[] = [];
61
+ try { branch = ctx.sessionManager.getBranch().slice(-MAX_INSPECTOR_BRANCH_ENTRIES); } catch { /* missing native branch means no recording-source link */ }
62
+ const items = inspection.entries.map((entry: MemoryEntry) => {
63
+ const source = activeScope ? findMemoryRecordingSource(entry, branch, target, activeScope) : undefined;
64
+ const details = [`text: ${entry.text}`, `id: ${entry.id}`, `target: ${target}`, `kind: ${entry.kind}`, `recorded: ${entry.recordedAt}`, `last seen: ${entry.lastSeenAt}`, ...(entry.expiresAt ? [`expires: ${entry.expiresAt}`] : []), ...(entry.tags.length ? [`tags: ${entry.tags.join(", ")}`] : []), ...(entry.persona ? [`persona marker: ${entry.persona}`] : []), ...(entry.source ? [`literal source metadata (not opened): ${entry.source}`] : []), ...(entry.derivedFrom?.length ? [`derivedFrom literal IDs (not opened): ${entry.derivedFrom.join(", ")}`] : []), ...(entry.supersedes ? [`supersedes literal ID (not opened): ${entry.supersedes}`] : []), ...(source ? [] : ["No resolvable recording in this active-branch window."])];
65
+ return { id: entry.id, title: entry.text, body: details.join("\n"), ...(source ? { source } : {}) };
66
+ });
67
+ return { items, total: inspection.matched, offset: inspection.offset, ...(inspection.nextOffset === undefined ? {} : { nextOffset: inspection.nextOffset }), notice: `${target} memory; read-only inspection. ${inspection.matched} matching safe entries in this store. Recording-source lookup covers the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} active-branch entries. Source and derivedFrom values are literal provenance, not verified evidence or cross-store links.` };
68
+ } catch { return unavailable("Memory inspection failed safely; no store recovery or mutation was attempted."); }
69
+ }
@@ -0,0 +1,215 @@
1
+ /** Explicit evidence-grounded review. Proposals are data; only a separately approved CAS plan writes. */
2
+ import { createHash } from "node:crypto";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { MindService } from "../core/service.ts";
5
+ import type { MemoryOptimizer } from "../core/optimize-service.ts";
6
+ import type { OptimizePlan } from "../core/optimize.ts";
7
+ import { buildKnowledgeReviewTask, formatKnowledgeReview, parseKnowledgeReview, type ReviewPacket, type ReviewTarget } from "../core/knowledge-review.ts";
8
+ import { collectReviewEvidence, type ReviewEvidenceSnapshot } from "./review-evidence.ts";
9
+ import type { ReviewReservation } from "./auto-optimize.ts";
10
+ import type { MindWorkerAdmission } from "./mind-worker.ts";
11
+
12
+ export interface KnowledgeReviewDeps {
13
+ captureOwner(ctx: ExtensionContext): () => boolean;
14
+ mind(ctx: ExtensionContext): MindService;
15
+ reserve(target: ReviewTarget): ReviewReservation | undefined;
16
+ launch(ctx: ExtensionContext, task: string): MindWorkerAdmission;
17
+ appendResult(ctx: ExtensionContext, title: string, body: string): void;
18
+ collect?: typeof collectReviewEvidence;
19
+ }
20
+ interface PendingReview {
21
+ ctx: ExtensionContext;
22
+ current(): boolean;
23
+ optimizer: MemoryOptimizer;
24
+ packet: ReviewPacket;
25
+ evidence: ReviewEvidenceSnapshot;
26
+ body: string;
27
+ expiresAt: number;
28
+ plan?: OptimizePlan;
29
+ }
30
+
31
+ export function createKnowledgeReview(deps: KnowledgeReviewDeps) {
32
+ let generation = 0;
33
+ let dialogs = new AbortController();
34
+ let preparing = false;
35
+ let running: { cancel(): void } | undefined;
36
+ let work: Promise<void> = Promise.resolve();
37
+ let applyWork: Promise<void> = Promise.resolve();
38
+ let pending: PendingReview | undefined;
39
+ let applying = false;
40
+ const collect = deps.collect ?? collectReviewEvidence;
41
+ const notify = (ctx: ExtensionContext, message: string): void => ctx.ui.notify(message, "info");
42
+ const drop = (): void => { pending?.optimizer.invalidate(); pending = undefined; };
43
+ const interrupt = (): void => { generation++; dialogs.abort(); dialogs = new AbortController(); running?.cancel(); drop(); };
44
+ const snapshot = (): PendingReview | undefined => {
45
+ if (pending && (!pending.current() || Date.now() >= pending.expiresAt)) drop();
46
+ return pending;
47
+ };
48
+ const requireCurrent = (current: () => boolean): void => { if (!current()) throw new Error("knowledge-review owner, branch or model changed"); };
49
+
50
+ async function start(ctx: ExtensionContext, target: ReviewTarget, selectedId?: string): Promise<void> {
51
+ if (target !== "project" && target !== "project-long" && target !== "persona") { notify(ctx, "Knowledge review supports project, project-long and persona only; shared/session are not writable review targets."); return; }
52
+ if (preparing || running || applying) { notify(ctx, "Mind knowledge review is busy."); return; }
53
+ if (snapshot()) { notify(ctx, "A knowledge review is already staged. Use /mind review show, apply or discard first."); return; }
54
+ if (ctx.mode !== "tui" || !ctx.hasUI) { notify(ctx, "Knowledge review requires the interactive terminal for evidence selection and approval."); return; }
55
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) { notify(ctx, "Wait for the foreground to settle before starting a knowledge review."); return; }
56
+ const accepted = generation;
57
+ const signal = dialogs.signal;
58
+ const owner = deps.captureOwner(ctx);
59
+ const current = () => accepted === generation && owner();
60
+ requireCurrent(current);
61
+ const mind = deps.mind(ctx);
62
+ const scope = mind.inspectionScope();
63
+ if (scope.homeWorkspace && target !== "persona") { notify(ctx, "Home allows persona review only; no project evidence is read."); return; }
64
+ preparing = true;
65
+ let reservation: ReviewReservation | undefined;
66
+ let optimizer: MemoryOptimizer | undefined;
67
+ try {
68
+ optimizer = mind.createOptimizer();
69
+ const inspection = await optimizer.inspect(target, { max: 100 });
70
+ requireCurrent(current);
71
+ if (!inspection.ok) throw new Error(inspection.reason);
72
+ let memories = inspection.entries.filter((entry) => target === "persona" || entry.persona === scope.persona);
73
+ if (selectedId) {
74
+ // A selected row can be beyond the first page. Full-read it, then bind staging to
75
+ // the already captured raw store fingerprint; concurrent changes still refuse CAS.
76
+ const found = await mind.readMemory(selectedId, target === "project-long" || target === "project" ? "project" : "persona");
77
+ requireCurrent(current);
78
+ if (!found.ok) throw new Error(found.reason);
79
+ memories = found.entries.filter((entry) => entry.target === target && (target === "persona" || entry.entry.persona === scope.persona)).map(({ entry }) => entry);
80
+ if (memories.length !== 1) throw new Error("selected memory is unavailable or ambiguous in this owner/target");
81
+ }
82
+ // Full facts only: never silently feed a chopped assertion to the reviewer.
83
+ const admitted = [] as typeof memories;
84
+ let bytes = 0;
85
+ for (const memory of memories) {
86
+ const size = JSON.stringify(memory).length;
87
+ if (admitted.length < 6 && bytes + size <= 12_000) { admitted.push(memory); bytes += size; }
88
+ }
89
+ if (!admitted.length) { notify(ctx, "No complete safe owned facts fit this bounded review. No worker started."); return; }
90
+ const pathsInput = scope.homeWorkspace ? "" : await ctx.ui.input("Repository evidence for knowledge review", "Explicit relative files, comma-separated (e.g. README.md, package.json); empty = user-role messages only", { signal });
91
+ requireCurrent(current);
92
+ if (pathsInput === undefined) return;
93
+ const paths = pathsInput.split(/[\n,]/).map((path) => path.trim()).filter(Boolean);
94
+ const model = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "unavailable";
95
+ const acceptedByUser = await ctx.ui.confirm("Review knowledge — no automatic changes", `${admitted.length} complete ${target} fact(s). Evidence: ${paths.length ? paths.join(", ") : "no repository files"} and bounded active-branch user-role text (authorship/quotes must be assessed). Worker: ${model}, current session model; additional model usage. Corrections will require separate approval. Retirement recommendations never delete automatically. Continue?`, { signal });
96
+ requireCurrent(current);
97
+ if (!acceptedByUser) return;
98
+ reservation = deps.reserve(target);
99
+ if (!reservation) { notify(ctx, "Mind maintenance or the foreground is busy. No review worker started."); return; }
100
+ const evidence = await collect(ctx, paths, current);
101
+ requireCurrent(current);
102
+ if (!reservation.current()) throw new Error("Mind maintenance reservation was revoked; no worker started.");
103
+ if (!evidence.evidence.length) {
104
+ deps.appendResult(ctx, "Mind knowledge review — no evidence", `No safe evidence was admitted; no worker started.\n${evidence.coverage.join("\n")}`);
105
+ notify(ctx, "No safe evidence was admitted. No worker started; inspect the coverage report."); return;
106
+ }
107
+ const packet: ReviewPacket = { target, memories: admitted, evidence: evidence.evidence, coverage: [
108
+ `${admitted.length} full facts supplied from a bounded inspection of ${inspection.entries.length} records; store has ${inspection.total} active records. This is not a complete archive review.`,
109
+ ...(selectedId ? [`Explicitly selected memory: ${selectedId}.`] : []), ...evidence.coverage,
110
+ ] };
111
+ const task = buildKnowledgeReviewTask(packet);
112
+ evidence.assertFresh(); requireCurrent(current);
113
+ const admission = deps.launch(ctx, task);
114
+ if (!admission.ok) throw new Error(admission.reason);
115
+ const lease = reservation;
116
+ const reviewOptimizer = optimizer;
117
+ running = admission;
118
+ reservation = undefined; optimizer = undefined;
119
+ work = (async () => {
120
+ let completed = false;
121
+ try {
122
+ lease.launched(createHash("sha256").update(`knowledge-review\n${task}`).digest("hex"));
123
+ const result = await admission.completion;
124
+ requireCurrent(current);
125
+ if (!lease.current()) throw new Error("Mind maintenance reservation was revoked.");
126
+ if (!result.ok || result.status !== "done") throw new Error("Knowledge review stopped or failed; no changes were applied.");
127
+ completed = true;
128
+ const parsed = parseKnowledgeReview(result.output, packet);
129
+ if (!parsed.ok) throw new Error(`Knowledge review proposal refused: ${parsed.reason}`);
130
+ evidence.assertFresh(); requireCurrent(current);
131
+ let plan: OptimizePlan | undefined;
132
+ if (parsed.operations.length) {
133
+ const staged = await reviewOptimizer.preview({ target, fingerprint: inspection.fingerprint, operations: parsed.operations });
134
+ requireCurrent(current);
135
+ if (!staged.ok) throw new Error(staged.reason);
136
+ plan = staged;
137
+ }
138
+ const body = `${formatKnowledgeReview(packet, parsed.findings)}\n\nWorker: ${admission.runId} · ${admission.model}${result.resultRef ? ` · result: ${result.resultRef}` : ""}\n${plan ? `${plan.changes.length} correction(s) staged, not applied. Plan expires at ${plan.expiresAt}. /mind review apply asks for approval; /mind review discard abandons this plan.` : "No executable corrections. Retirement recommendations require a separate deliberate memory forget; nothing was deleted."}\nUse /mind review show to inspect this report again. Source references are evidence supplied to an LLM, not independently verified truth.`;
139
+ deps.appendResult(ctx, "Mind knowledge review — proposal", body);
140
+ requireCurrent(current);
141
+ pending = { ctx, current, optimizer: reviewOptimizer, packet, evidence, body, expiresAt: plan ? Date.parse(plan.expiresAt) : Date.now() + 600_000, ...(plan ? { plan } : {}) };
142
+ notify(ctx, `mind · ${target} knowledge review ready; no changes applied. /mind review show`);
143
+ } catch (error) {
144
+ reviewOptimizer.invalidate();
145
+ admission.cancel();
146
+ await admission.completion.catch(() => {});
147
+ if (current()) {
148
+ try { deps.appendResult(ctx, "Mind knowledge review — not applied", error instanceof Error ? error.message : "Knowledge review failed."); }
149
+ catch { /* no persistence fallback and no application */ }
150
+ notify(ctx, "mind · knowledge review did not stage changes; inspect the report.");
151
+ }
152
+ } finally {
153
+ if (completed && current()) { try { lease.settled(); } catch { notify(ctx, "Mind review accounting could not be persisted; inspect /mind doctor before retrying."); } }
154
+ lease.release();
155
+ if (running === admission) running = undefined;
156
+ }
157
+ })();
158
+ notify(ctx, `mind · ${target} evidence review started on ${admission.model}; inspect the result before applying.`);
159
+ } catch (error) {
160
+ if (current()) notify(ctx, error instanceof Error ? error.message : "Knowledge review unavailable.");
161
+ } finally { reservation?.release(); optimizer?.invalidate(); preparing = false; }
162
+ }
163
+
164
+ async function show(ctx: ExtensionContext): Promise<void> {
165
+ const review = snapshot();
166
+ if (!review) { notify(ctx, running || preparing ? "Knowledge review is running." : "No active knowledge review; start /mind review [project|project-long|persona]."); return; }
167
+ deps.appendResult(ctx, "Mind knowledge review — staged", review.body);
168
+ }
169
+ function apply(ctx: ExtensionContext): Promise<void> {
170
+ const review = snapshot();
171
+ if (!review?.plan) { notify(ctx, "No executable correction plan is staged. Retirement recommendations are not deletions."); return Promise.resolve(); }
172
+ if (applying || preparing || running || !ctx.isIdle() || ctx.hasPendingMessages()) { notify(ctx, "Mind or the foreground is busy; no review changes applied."); return Promise.resolve(); }
173
+ if (ctx.mode !== "tui" || !ctx.hasUI) { notify(ctx, "Applying a knowledge review requires interactive approval."); return Promise.resolve(); }
174
+ const plan = review.plan;
175
+ applying = true;
176
+ // Register before any dialog/report callback can reenter lifecycle cleanup. Rejected
177
+ // overlapping calls must never replace the promise for the admitted writer.
178
+ applyWork = Promise.resolve().then(async () => {
179
+ let lease: ReviewReservation | undefined;
180
+ let applyAttempted = false;
181
+ let committed = false;
182
+ try {
183
+ if (snapshot() !== review) return;
184
+ deps.appendResult(ctx, "Mind knowledge review — approve these corrections", review.body);
185
+ const approved = await ctx.ui.confirm("Apply knowledge corrections?", `Apply exactly ${plan.changes.length} displayed correction(s) to ${review.packet.target}? No retirement recommendations will be deleted. Sources, scope and store freshness will be checked again; consolidation history/undo is retained.`, { signal: dialogs.signal });
186
+ if (!approved) return;
187
+ if (snapshot() !== review) throw new Error("Knowledge review changed or expired; inspect again.");
188
+ lease = deps.reserve(review.packet.target);
189
+ if (!lease) throw new Error("Mind maintenance is busy; no review changes applied.");
190
+ const fresh = () => { requireCurrent(review.current); if (pending !== review || !lease?.current()) throw new Error("Review plan or maintenance reservation invalidated"); review.evidence.assertFresh(); };
191
+ fresh();
192
+ applyAttempted = true;
193
+ const result = await review.optimizer.apply(plan.planId, fresh);
194
+ committed = result.ok;
195
+ if (!review.current()) return;
196
+ if (!result.ok) throw new Error(result.reason);
197
+ drop();
198
+ deps.appendResult(ctx, "Mind knowledge review — applied", `${result.changed} correction(s) applied to ${result.target}.${result.receiptId ? ` Undo receipt: ${result.receiptId}. Use /mind optimize undo ${result.receiptId} ${result.target}.` : ""}${result.warning ? `\nWarning: ${result.warning}` : ""}`);
199
+ notify(ctx, `mind · ${result.target} · ${result.changed} reviewed correction(s) applied`);
200
+ } catch (error) {
201
+ if (review.current()) {
202
+ const reason = error instanceof Error ? error.message : "Review apply failed";
203
+ notify(ctx, committed ? `Corrections were applied, but reporting failed: ${reason}. Inspect /mind optimize history ${review.packet.target}.`
204
+ : applyAttempted ? `Review apply was refused or failed: ${reason}. A persistence error may have an uncertain outcome; inspect /mind optimize history ${review.packet.target} before retrying.` : reason);
205
+ }
206
+ } finally { try { lease?.release(); } finally { applying = false; } }
207
+ });
208
+ return applyWork;
209
+ }
210
+ // Revocation prevents admission/guarded writes, but cannot roll back a committed store.
211
+ // Join includes confirmation, persistence and receipt finalization, even after interrupt().
212
+ return { start, show, apply, interrupt, join: async () => { await Promise.all([work, applyWork]); }, hasPending: () => snapshot() !== undefined,
213
+ discard(ctx: ExtensionContext): void { interrupt(); notify(ctx, "Knowledge review cancelled/discarded; no pending plan remains. Already applied changes require history/undo."); },
214
+ };
215
+ }