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