@aeondave/pi-persona-mind 0.9.6 → 0.9.7

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.
@@ -1,10 +1,10 @@
1
1
  /** Pure selection and strict proposal contracts for Mind's bounded background reviewer. */
2
2
  import { createHash } from "node:crypto";
3
3
  import {
4
- isMemoryId, isSafeMemoryContent, MEMORY_KINDS, MAX_MEMORY_TEXT_CHARS, validateLongMemory, validateShortMemory,
4
+ isExpired, isMemoryId, isSafeMemoryContent, MEMORY_KINDS, MAX_MEMORY_TEXT_CHARS, validateLongMemory, validateShortMemory,
5
5
  type MemoryEntry, type MemoryKind,
6
6
  } from "./memory.ts";
7
- import type { OptimizeInspection, OptimizeOperation } from "./optimize.ts";
7
+ import { MAX_OPTIMIZE_ENTRIES, optimizeCandidates, type OptimizeInspection, type OptimizeOperation } from "./optimize.ts";
8
8
 
9
9
  export type AutoOptimizeTarget = "project" | "project-long" | "persona";
10
10
 
@@ -18,8 +18,20 @@ export interface AutoOptimizeInput {
18
18
  export type AutoInputSkipReason = "invalid-input" | "empty-page" | "no-safe-owned-facts" | "single-short-record" | "input-budget";
19
19
 
20
20
  export type AutoInputPage =
21
- | { input: AutoOptimizeInput; eligibleCount: number; nextRotation: number; pageComplete: boolean }
22
- | { input?: never; eligibleCount: number; nextRotation: number; pageComplete: boolean; reason: AutoInputSkipReason };
21
+ | { input: AutoOptimizeInput; eligibleCount: number; order: readonly string[]; nextRotation: number; pageComplete: boolean }
22
+ | { input?: never; eligibleCount: number; order: readonly string[]; nextRotation: number; pageComplete: boolean; reason: AutoInputSkipReason };
23
+
24
+ type ReviewPageKey = Pick<MemoryEntry, "recordedAt" | "id">;
25
+ export type AutoReviewCursor = { offset: number; withinPage: number } & (
26
+ | { order?: never; before?: ReviewPageKey; nextBefore?: never }
27
+ /** Frozen order of the current candidate page, without the first pass's pinned newest fact. */
28
+ | { order: readonly string[]; before?: never; nextBefore?: ReviewPageKey }
29
+ );
30
+ export interface AutoReviewSnapshot {
31
+ inspection: OptimizeInspection;
32
+ newest?: MemoryEntry;
33
+ nextBefore?: ReviewPageKey;
34
+ }
23
35
 
24
36
  export type AutoProposalResult = { ok: true; operations: OptimizeOperation[] } | { ok: false; reason: string };
25
37
 
@@ -31,6 +43,41 @@ export const AUTO_OPTIMIZE_MAX_PROMPT_CHARS = 48_000;
31
43
  export const AUTO_OPTIMIZE_MAX_OUTPUT_CHARS = 48_000;
32
44
  const MIN_SINGLE_ENTRY_CHARS = 1_200;
33
45
 
46
+ /** Build the page and newest fact from one strict store snapshot. Touches do not change age order. */
47
+ export function inspectAutoReviewPage(entries: readonly MemoryEntry[], fingerprint: string, target: AutoOptimizeTarget, persona: string, now: number, cursor: AutoReviewCursor): AutoReviewSnapshot {
48
+ const active = entries.filter((entry) => !isExpired(entry, now));
49
+ const eligible = eligibleEntries(target, active, persona);
50
+ const newest = eligible.find(fitsInputAlone);
51
+ let page: MemoryEntry[];
52
+ let nextBefore = cursor.nextBefore;
53
+ if (cursor.order) {
54
+ const byId = new Map(eligible.map((entry) => [entry.id, entry]));
55
+ page = cursor.order.slice(cursor.withinPage).flatMap((id) => {
56
+ const entry = byId.get(id);
57
+ return entry ? [entry] : [];
58
+ });
59
+ } else {
60
+ const older = eligible.filter((entry) => !cursor.before || compareRecorded(entry, cursor.before) > 0).sort(compareRecorded);
61
+ page = older.slice(0, MAX_OPTIMIZE_ENTRIES);
62
+ const oldest = page.at(-1);
63
+ nextBefore = oldest && older.length > MAX_OPTIMIZE_ENTRIES ? { recordedAt: oldest.recordedAt, id: oldest.id } : undefined;
64
+ }
65
+ const inspection: OptimizeInspection = {
66
+ ok: true, target, fingerprint, entries: page, total: active.length, withheld: active.length - page.length,
67
+ candidates: cursor.order ? [] : optimizeCandidates(page), offset: cursor.offset, matched: eligible.length,
68
+ ...(nextBefore ? { nextOffset: cursor.offset + MAX_OPTIMIZE_ENTRIES } : {}),
69
+ };
70
+ return { inspection, ...(newest ? { newest } : {}), ...(nextBefore ? { nextBefore } : {}) };
71
+ }
72
+
73
+ function compareRecorded(a: ReviewPageKey, b: ReviewPageKey): number {
74
+ return Date.parse(b.recordedAt) - Date.parse(a.recordedAt) || a.id.localeCompare(b.id);
75
+ }
76
+
77
+ function fitsInputAlone(entry: MemoryEntry): boolean {
78
+ return JSON.stringify(entry).length + 2 <= AUTO_OPTIMIZE_MAX_INPUT_CHARS;
79
+ }
80
+
34
81
  /** Fixed host-authored reviewer policy included before the untrusted records in the worker task. */
35
82
  export const AUTO_OPTIMIZE_SYSTEM_PROMPT = [
36
83
  "You are Mind's read-only memory-consolidation reviewer. You have no tools; review only the supplied records.",
@@ -45,36 +92,96 @@ export const AUTO_OPTIMIZE_SYSTEM_PROMPT = [
45
92
  * Select bounded full records from one owned store. Shared LTM is intentionally never eligible.
46
93
  * Lexical pairs affect order only; they do not make a semantic decision.
47
94
  */
48
- export function selectAutoInput(inspection: OptimizeInspection, persona: string, rotation = 0, newestInspection?: OptimizeInspection): AutoOptimizeInput | undefined {
49
- return selectAutoInputPage(inspection, persona, rotation, newestInspection).input;
95
+ export function selectAutoInput(inspection: OptimizeInspection, persona: string, rotation = 0): AutoOptimizeInput | undefined {
96
+ return selectAutoInputPage(inspection, persona, rotation).input;
50
97
  }
51
98
 
52
99
  /** Selects one bounded rotating slice and reports cursor progress even when the page has no work. */
53
- export function selectAutoInputPage(inspection: OptimizeInspection, persona: string, rotation = 0, newestInspection?: OptimizeInspection): AutoInputPage {
54
- const empty = (reason: AutoInputSkipReason, eligibleCount = 0): AutoInputPage => ({ eligibleCount, nextRotation: 0, pageComplete: true, reason });
100
+ export function selectAutoInputPage(inspection: OptimizeInspection, persona: string, rotation = 0, review?: Pick<AutoReviewSnapshot, "newest"> & Pick<AutoReviewCursor, "order">): AutoInputPage {
101
+ const empty = (reason: AutoInputSkipReason, eligibleCount = 0): AutoInputPage => ({ eligibleCount, order: [], nextRotation: 0, pageComplete: true, reason });
55
102
  if (!isReviewTarget(inspection?.target) || typeof persona !== "string" || persona.length < 1 || persona.length > 128 ||
56
103
  typeof inspection.fingerprint !== "string" || inspection.fingerprint.length < 1 || inspection.fingerprint.length > 256 || !Array.isArray(inspection.entries) ||
57
104
  !Number.isSafeInteger(inspection.offset) || inspection.offset < 0 || !Number.isSafeInteger(inspection.total) || inspection.total < 0 ||
58
105
  !Number.isSafeInteger(inspection.matched) || inspection.matched < 0) return empty("invalid-input");
59
- const eligible = eligibleEntries(inspection, persona);
60
- const pageEntries = eligible;
106
+ const pageEntries = eligibleEntries(inspection.target, inspection.entries, persona);
61
107
  if (pageEntries.length === 0) {
62
108
  const hasExcludedRows = inspection.entries.length > 0 || (inspection.total > 0 && inspection.matched === 0);
63
109
  return empty(hasExcludedRows ? "no-safe-owned-facts" : "empty-page");
64
110
  }
65
- let newest: MemoryEntry | undefined;
66
- if (inspection.offset === 0) newest = pageEntries[0];
67
- else if (newestInspection && newestInspection.target === inspection.target && newestInspection.offset === 0 && newestInspection.fingerprint === inspection.fingerprint) {
68
- newest = eligibleEntries(newestInspection, persona)[0];
69
- }
111
+ const newest = review ? review.newest : inspection.offset === 0 ? pageEntries.find(fitsInputAlone) : undefined;
70
112
  const byId = new Map(pageEntries.map((entry) => [entry.id, entry]));
71
- const ordered: MemoryEntry[] = [];
113
+ const orderedIds = review?.order ?? prioritizeCandidates(inspection.candidates, pageEntries, byId, newest);
114
+ let position = Number.isSafeInteger(rotation) && rotation > 0 ? Math.min(rotation, orderedIds.length) : 0;
115
+ if (position === orderedIds.length && !newest) return empty("empty-page", pageEntries.length);
116
+ const { order, anchor } = fitReviewWindow(orderedIds, position, byId, newest);
117
+ const selected = anchor ? [anchor] : [];
118
+ let selectedChars = 2 + (anchor ? JSON.stringify(anchor).length : 0);
119
+ let budgetBlocked = false;
120
+ for (; position < order.length && selected.length < AUTO_OPTIMIZE_MAX_ENTRIES; position++) {
121
+ const entry = byId.get(order[position]!);
122
+ if (!entry || entry.id === newest?.id) continue;
123
+ const recordChars = JSON.stringify(entry).length;
124
+ if (2 + recordChars > AUTO_OPTIMIZE_MAX_INPUT_CHARS) { budgetBlocked = true; continue; }
125
+ const additionalChars = recordChars + (selected.length ? 1 : 0);
126
+ // A record only crowded out by other selected rows gets first place on the next pass.
127
+ if (selectedChars + additionalChars > AUTO_OPTIMIZE_MAX_INPUT_CHARS) { budgetBlocked = true; break; }
128
+ selectedChars += additionalChars;
129
+ selected.push(entry);
130
+ }
131
+ const pageComplete = position >= order.length;
132
+ const progress = { eligibleCount: pageEntries.length, order, nextRotation: pageComplete ? 0 : position, pageComplete };
133
+ if (selected.length === 0 || (selected.length === 1 && selected[0]!.text.length < MIN_SINGLE_ENTRY_CHARS)) {
134
+ return { ...progress, reason: budgetBlocked ? "input-budget" : "single-short-record" };
135
+ }
136
+ const digest = semanticDigest(inspection.target, selected);
137
+ return { ...progress, input: { target: inspection.target, fingerprint: inspection.fingerprint, digest, entries: selected } };
138
+ }
139
+
140
+ /** Untie the anchor only when it would exclude the next row or keep a compatible pair apart. */
141
+ function fitReviewWindow(order: readonly string[], start: number, byId: ReadonlyMap<string, MemoryEntry>, newest: MemoryEntry | undefined): { order: readonly string[]; anchor?: MemoryEntry } {
142
+ if (!newest) return { order };
143
+ const firstIndex = order.findIndex((id, index) => {
144
+ const entry = byId.get(id);
145
+ return index >= start && entry !== undefined && id !== newest.id && fitsInputAlone(entry);
146
+ });
147
+ if (firstIndex < 0) return { order, anchor: newest };
148
+ const first = byId.get(order[firstIndex]!)!;
149
+ const firstChars = 2 + JSON.stringify(first).length;
150
+ const anchorChars = 1 + JSON.stringify(newest).length;
151
+ const companionIndex = order.findIndex((id, index) => {
152
+ const entry = byId.get(id);
153
+ return index > firstIndex && entry !== undefined && id !== newest.id && entry.kind === first.kind && entry.persona === first.persona &&
154
+ firstChars + 1 + JSON.stringify(entry).length <= AUTO_OPTIMIZE_MAX_INPUT_CHARS;
155
+ });
156
+ const companion = byId.get(order[companionIndex]!);
157
+ const companionChars = companion ? 1 + JSON.stringify(companion).length : 0;
158
+ const keepAnchor = firstChars + anchorChars + companionChars <= AUTO_OPTIMIZE_MAX_INPUT_CHARS;
159
+ const anchor = keepAnchor ? { anchor: newest } : {};
160
+ if (companionIndex <= firstIndex + 1) return { order, ...anchor };
161
+ // Preserve the existing order if the whole prefix fits. Otherwise reserve the compatible
162
+ // row before unrelated records can fill this window and leave both halves ineligible.
163
+ let chars = firstChars + companionChars + (keepAnchor ? anchorChars : 0);
164
+ let count = keepAnchor ? 3 : 2;
165
+ for (const id of order.slice(firstIndex + 1, companionIndex)) {
166
+ const entry = byId.get(id);
167
+ if (!entry || id === newest.id) continue;
168
+ const recordChars = JSON.stringify(entry).length;
169
+ if (2 + recordChars > AUTO_OPTIMIZE_MAX_INPUT_CHARS) continue;
170
+ chars += 1 + recordChars;
171
+ count++;
172
+ }
173
+ if (chars <= AUTO_OPTIMIZE_MAX_INPUT_CHARS && count <= AUTO_OPTIMIZE_MAX_ENTRIES) return { order, ...anchor };
174
+ const reordered = order.slice();
175
+ reordered.splice(companionIndex, 1);
176
+ reordered.splice(firstIndex + 1, 0, companion!.id);
177
+ return { order: reordered, ...anchor };
178
+ }
179
+
180
+ function prioritizeCandidates(candidates: OptimizeInspection["candidates"], pageEntries: readonly MemoryEntry[], byId: ReadonlyMap<string, MemoryEntry>, newest: MemoryEntry | undefined): string[] {
72
181
  const orderedIds = new Set<string>();
73
- const addOrdered = (entry: MemoryEntry): void => {
74
- if (entry.id !== newest?.id && !orderedIds.has(entry.id)) { orderedIds.add(entry.id); ordered.push(entry); }
75
- };
182
+ const addOrdered = (entry: MemoryEntry): void => { if (entry.id !== newest?.id) orderedIds.add(entry.id); };
76
183
  const recent = (a: MemoryEntry, b: MemoryEntry): number => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt) || a.id.localeCompare(b.id);
77
- const pairs = Array.isArray(inspection.candidates) ? inspection.candidates.flatMap((candidate) => {
184
+ const pairs = Array.isArray(candidates) ? candidates.flatMap((candidate) => {
78
185
  if (!candidate || typeof candidate.leftId !== "string" || typeof candidate.rightId !== "string" || candidate.leftId === candidate.rightId) return [];
79
186
  const left = byId.get(candidate.leftId);
80
187
  const right = byId.get(candidate.rightId);
@@ -86,39 +193,8 @@ export function selectAutoInputPage(inspection: OptimizeInspection, persona: str
86
193
  pairs.sort((a, b) => b.similarity - a.similarity || b.latest - a.latest || a.left.id.localeCompare(b.left.id) || a.right.id.localeCompare(b.right.id));
87
194
  for (const pair of pairs) if (pair.left.id === newest?.id || pair.right.id === newest?.id) for (const entry of [pair.left, pair.right].sort(recent)) addOrdered(entry);
88
195
  for (const pair of pairs) if (pair.left.id !== newest?.id && pair.right.id !== newest?.id) for (const entry of [pair.left, pair.right].sort(recent)) addOrdered(entry);
89
- for (const entry of [...pageEntries].sort(recent)) addOrdered(entry);
90
-
91
- const start = Number.isSafeInteger(rotation) && rotation > 0 ? Math.min(rotation, ordered.length) : 0;
92
- const capacity = Math.max(0, AUTO_OPTIMIZE_MAX_ENTRIES - (newest ? 1 : 0));
93
- const window = ordered.slice(start, start + capacity);
94
- if (window.length === 0 && !newest) return empty("empty-page", pageEntries.length);
95
- const selected: MemoryEntry[] = [];
96
- const selectedIds = new Set<string>();
97
- let budgetBlocked = false;
98
- function tryAdd(entry: MemoryEntry): boolean {
99
- if (selectedIds.has(entry.id) || selected.length >= AUTO_OPTIMIZE_MAX_ENTRIES) return false;
100
- if (JSON.stringify([...selected, entry]).length > AUTO_OPTIMIZE_MAX_INPUT_CHARS) return false;
101
- selectedIds.add(entry.id);
102
- selected.push(entry);
103
- return true;
104
- }
105
- if (newest && !tryAdd(newest)) budgetBlocked = true;
106
- let suppliedFromWindow = 0;
107
- for (const entry of window) {
108
- // Keep the rotation contiguous: when the next row will not fit alongside the pinned newest
109
- // row, leave that row at the cursor for the next admitted pass. Skipping it here would make
110
- // the cursor claim coverage for data the worker never received.
111
- if (!tryAdd(entry)) { budgetBlocked = true; break; }
112
- suppliedFromWindow++;
113
- }
114
- const admittedPosition = start + suppliedFromWindow;
115
- const pageComplete = admittedPosition >= ordered.length;
116
- if (selected.length === 0 || (selected.length === 1 && selected[0]!.text.length < MIN_SINGLE_ENTRY_CHARS)) {
117
- const reason: AutoInputSkipReason = budgetBlocked ? "input-budget" : "single-short-record";
118
- return { eligibleCount: pageEntries.length, nextRotation: pageComplete ? 0 : admittedPosition, pageComplete, reason };
119
- }
120
- const digest = semanticDigest(inspection.target, selected);
121
- return { input: { target: inspection.target, fingerprint: inspection.fingerprint, digest, entries: selected }, eligibleCount: pageEntries.length, nextRotation: pageComplete ? 0 : admittedPosition, pageComplete };
196
+ for (const entry of pageEntries) addOrdered(entry);
197
+ return [...orderedIds];
122
198
  }
123
199
 
124
200
  /**
@@ -203,17 +279,15 @@ function validateInput(input: AutoOptimizeInput): MemoryEntry[] | undefined {
203
279
  return entries;
204
280
  }
205
281
 
206
- function eligibleEntries(inspection: OptimizeInspection, persona: string): MemoryEntry[] {
207
- if (!isReviewTarget(inspection.target) || !Array.isArray(inspection.entries)) return [];
282
+ function eligibleEntries(target: AutoOptimizeTarget, entries: readonly MemoryEntry[], persona: string): MemoryEntry[] {
208
283
  const occurrences = new Map<string, MemoryEntry[]>();
209
- for (const raw of inspection.entries) {
210
- const entry = inspection.target === "project" ? validateShortMemory(raw) : validateLongMemory(raw);
284
+ for (const raw of entries) {
285
+ const entry = target === "project" ? validateShortMemory(raw) : validateLongMemory(raw);
211
286
  if (!entry || !isSafeMemoryContent(entry)) continue;
212
- if (inspection.target === "project" && entry.persona !== persona) continue;
213
- if (inspection.target === "project-long" && entry.persona !== persona) continue;
287
+ if (target !== "persona" && entry.persona !== persona) continue;
214
288
  // Persona LTM is scoped by the store path; reject a contradictory embedded owner marker while
215
289
  // retaining older valid LTM rows that predate that optional marker.
216
- if (inspection.target === "persona" && entry.persona !== undefined && entry.persona !== persona) continue;
290
+ if (target === "persona" && entry.persona !== undefined && entry.persona !== persona) continue;
217
291
  const group = occurrences.get(entry.id) ?? [];
218
292
  group.push(entry);
219
293
  occurrences.set(entry.id, group);
@@ -140,6 +140,7 @@ export function detectCaptureCues(userText: string): CaptureCue[] {
140
140
  if (!cue.re.test(sentence)) continue;
141
141
  const snippet = sentence.length > MAX_SNIPPET ? `${sentence.slice(0, MAX_SNIPPET - 1)}…` : sentence;
142
142
  const candidate = candidateFor(sentence);
143
+ if (found.some((prior) => prior.kind === cue.kind && prior.strong === candidate.explicit && prior.candidate === candidate.text)) break;
143
144
  found.push({ snippet, kind: cue.kind, term: "session", strong: candidate.explicit, candidate: candidate.text });
144
145
  break;
145
146
  }
@@ -1,5 +1,5 @@
1
1
  /** The extension targets current Pi only; this is a floor check, not a compatibility layer. */
2
- export const MIN_PI_VERSION = "1.6.1";
2
+ export const MIN_PI_VERSION = "1.7.0";
3
3
  const minimum = MIN_PI_VERSION.split(".").map(Number);
4
4
 
5
5
  export function isSupportedPiVersion(version: string): boolean {
@@ -1,5 +1,6 @@
1
1
  /** Session-local staged plans over strict one-file memory snapshots. No model calls or hidden jobs. */
2
2
  import { randomUUID } from "node:crypto";
3
+ import { inspectAutoReviewPage, type AutoOptimizeTarget, type AutoReviewCursor, type AutoReviewSnapshot } from "./auto-optimize.ts";
3
4
  import { isExpired, isSafeMemoryContent, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
4
5
  import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeReceiptDetail, type OptimizeUndone } from "./optimize-history.ts";
5
6
  import {
@@ -57,6 +58,14 @@ export class MemoryOptimizer {
57
58
  } catch (error) { return failure(error); }
58
59
  }
59
60
 
61
+ /** Internal maintenance traversal with a private cursor and no mutation or recovery writes. */
62
+ async inspectReviewPage(target: AutoOptimizeTarget, cursor: AutoReviewCursor): Promise<AutoReviewSnapshot | OptimizeFailure> {
63
+ try {
64
+ const snapshot = await this.options.stores[target].inspectStrict();
65
+ return inspectAutoReviewPage(snapshot.store.entries, snapshot.fingerprint, target, this.options.persona, this.now(), cursor);
66
+ } catch (error) { return failure(error); }
67
+ }
68
+
60
69
  async preview(input: OptimizePreviewInput): Promise<OptimizePlan | OptimizeFailure> {
61
70
  const generation = this.generation;
62
71
  const target = input.target ?? "project";
package/src/core/scope.ts CHANGED
@@ -84,17 +84,13 @@ export function sanitizePersona(name: string, platform: NodeJS.Platform | string
84
84
  }
85
85
 
86
86
  /**
87
- * The agent dir the mind should use, mirroring pi-persona's own `PI_AGENT_DIR || getAgentDir()`
88
- * precedence so both extensions co-locate their data: an explicit override (tests) wins, else
89
- * `PI_AGENT_DIR`, else `undefined` — signalling the caller to fall back to Pi's `getAgentDir()`
90
- * (kept lazy so tests that inject a dir never invoke the SDK). Env is injectable for tests.
87
+ * An explicit override wins. Otherwise, `undefined` delegates native profile resolution to Pi.
88
+ * The Persona alias supplies the root only when Pi has no explicit profile selection.
91
89
  */
92
90
  export function preferredAgentDir(explicit: string | undefined, env: NodeJS.ProcessEnv = process.env): string | undefined {
93
91
  if (explicit !== undefined) return explicit;
94
- // Raw value with a truthiness check, exactly as pi-persona does (`PI_AGENT_DIR || getAgentDir()`);
95
- // trimming here would make the two extensions resolve different dirs for a padded value.
96
- const override = env.PI_AGENT_DIR;
97
- return override ? override : undefined;
92
+ if (env.PI_CODING_AGENT_DIR) return undefined;
93
+ return env.PI_AGENT_DIR || undefined;
98
94
  }
99
95
 
100
96
  export interface ProjectSlugOptions {
@@ -1,5 +1,5 @@
1
1
  /** Event-driven maintenance: one visible Persona worker, bounded evidence, existing CAS writes. */
2
- import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoInputPage, type AutoInputSkipReason, type AutoOptimizeTarget } from "../core/auto-optimize.ts";
2
+ import { buildAutoPrompt, parseAutoProposal, selectAutoInputPage, type AutoInputPage, type AutoInputSkipReason, type AutoOptimizeTarget, type AutoReviewCursor, type AutoReviewSnapshot } from "../core/auto-optimize.ts";
3
3
  import type { MemoryOptimizer } from "../core/optimize-service.ts";
4
4
  import type { MindWorkerAdmission, MindWorkerResult } from "./mind-worker.ts";
5
5
  import type { OptimizeFailure, OptimizeInspection, OptimizePlan } from "../core/optimize.ts";
@@ -15,8 +15,7 @@ export const WORKER_WAIT_RELEASED: MindWorkerResult = { status: "stopped", ok: f
15
15
  /** Receipts a restart restores per owner; the in-memory mirror keeps the same window. */
16
16
  const ATTEMPT_HISTORY = 64;
17
17
  type Target = AutoOptimizeTarget;
18
- type Optimizer = Pick<MemoryOptimizer, "inspect" | "preview" | "apply" | "invalidate">;
19
- interface CoverageCursor { offset: number; withinPage: number }
18
+ type Optimizer = Pick<MemoryOptimizer, "inspectReviewPage" | "preview" | "apply" | "invalidate">;
20
19
  export interface AutoAttempt { digest: string; at: number; state: "started" | "settled"; target?: Target; explicit?: true }
21
20
  /** Parent-held single-flight lease spanning evidence, worker, preview and user apply. */
22
21
  export interface ReviewReservation {
@@ -53,8 +52,8 @@ export class AutoOptimizeScheduler {
53
52
  private pending = new Set<Target>();
54
53
  private retryTargets = new Set<Target>();
55
54
  /** The launch cursor is known only in memory; a restored retry has no verifiable position. */
56
- private retryAttempts = new Map<Target, { digest: string; at: number; cursor?: CoverageCursor }>();
57
- private cursors = new Map<Target, CoverageCursor>();
55
+ private retryAttempts = new Map<Target, { digest: string; at: number; cursor?: AutoReviewCursor }>();
56
+ private cursors = new Map<Target, AutoReviewCursor>();
58
57
  private inputTokens = 0;
59
58
  private seen = new Set<string>();
60
59
  /** Receipts as a restart would load them: parking is derived from these, never from enabled or retry state. */
@@ -65,7 +64,7 @@ export class AutoOptimizeScheduler {
65
64
  private disabledGeneration = 0;
66
65
  private timer: (() => void) | undefined;
67
66
  private timerGeneration = 0;
68
- private running: { optimizer: Optimizer; cancel?: () => void; retryTarget?: Target; explicit?: boolean; parkOnInterrupt?: string } | undefined;
67
+ private running: { optimizer: Optimizer; generation: number; settledGeneration?: number; cancel?: () => void; retryTarget?: Target; explicit?: boolean; parkOnInterrupt?: string } | undefined;
69
68
  private review: { target: Target; attempt?: { digest: string; at: number }; settled: boolean } | undefined;
70
69
  private work: Promise<void> = Promise.resolve();
71
70
  private last = "waiting for new memory";
@@ -137,7 +136,14 @@ export class AutoOptimizeScheduler {
137
136
  tokensUsed(mainInputTokens: number): void { if (this.owner && Number.isSafeInteger(mainInputTokens) && mainInputTokens > 0) this.inputTokens = Math.min(AUTO_INPUT_TOKEN_THRESHOLD, this.inputTokens + mainInputTokens); }
138
137
  settled(): void {
139
138
  const owner = this.owner;
140
- if (!this.enabled || !owner || !this.safeCurrent(owner) || !owner.idle() || this.running || this.review || this.timer || !this.pending.size) return;
139
+ if (!this.enabled || !owner || !this.safeCurrent(owner) || !this.safeIdle(owner)) return;
140
+ if (this.running) {
141
+ // The foreground can settle before a cancelled worker or inspection releases its slot.
142
+ // Retain that edge only while it belongs to the latest generation.
143
+ if (this.running.generation !== this.generation) this.running.settledGeneration = this.generation;
144
+ return;
145
+ }
146
+ if (this.review || this.timer || !this.pending.size) return;
141
147
  const tokenReady = this.lastAttempt === -Infinity || this.inputTokens >= AUTO_INPUT_TOKEN_THRESHOLD;
142
148
  const eligiblePending = [...this.pending].some((target) => this.allows(owner, target) && (this.retryTargets.has(target) || tokenReady));
143
149
  if (!eligiblePending) return;
@@ -230,9 +236,9 @@ export class AutoOptimizeScheduler {
230
236
  * (rotation moved, or a restore that cannot know the position) it stays owed, not pending:
231
237
  * the next dirty trigger for the tier may use it, and any launch on the tier consumes it.
232
238
  */
233
- private skipRetryWindow(target: Target, cursor: CoverageCursor): void {
239
+ private skipRetryWindow(target: Target, cursor: AutoReviewCursor): void {
234
240
  const launchedAt = this.retryAttempts.get(target)?.cursor;
235
- const ownWindow = launchedAt?.offset === cursor.offset && launchedAt.withinPage === cursor.withinPage;
241
+ const ownWindow = launchedAt === cursor;
236
242
  if (this.retryTargets.has(target) && !ownWindow) return;
237
243
  this.retryAttempts.delete(target);
238
244
  this.retryTargets.delete(target);
@@ -254,14 +260,14 @@ export class AutoOptimizeScheduler {
254
260
  try { owner.report(qualifyTargets ? `Mind optimization result — ${targets[0]}` : "Mind optimization result", body); } catch { /* owner reporting is best-effort */ }
255
261
  return;
256
262
  }
257
- const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, explicit };
263
+ const running: NonNullable<AutoOptimizeScheduler["running"]> = { optimizer, generation, explicit };
258
264
  // Latched, so a second wait in the same run (cancel-then-join) also returns once released.
259
265
  let releaseWorkerWait!: () => void;
260
266
  const workerWaitReleased = new Promise<MindWorkerResult>((resolve) => { releaseWorkerWait = () => resolve(WORKER_WAIT_RELEASED); });
261
267
  this.workerReleases.add(releaseWorkerWait);
262
268
  let attemptRecorded = false;
263
269
  let unsettledTarget: Target | undefined;
264
- let nextCursor: CoverageCursor | undefined;
270
+ let nextCursor: AutoReviewCursor | undefined;
265
271
  let retryRequiresSettled = false;
266
272
  let activeTarget: Target | undefined;
267
273
  const report = (target: Target, title: string, body: string, summary?: string, stopped = false, attention = stopped): boolean => {
@@ -288,20 +294,9 @@ export class AutoOptimizeScheduler {
288
294
  if (!explicit && !retry && !tokenReady) continue;
289
295
  if (!explicit) this.pending.delete(target);
290
296
  const cursor = this.cursors.get(target) ?? { offset: 0, withinPage: 0 };
291
- let inspection: OptimizeInspection | OptimizeFailure;
292
- let newestInspection: OptimizeInspection | undefined;
297
+ let snapshot: AutoReviewSnapshot | OptimizeFailure;
293
298
  try {
294
- inspection = await optimizer.inspect(target, { max: 100, offset: cursor.offset });
295
- if (inspection.ok && cursor.offset > 0) {
296
- const latest = await optimizer.inspect(target, { max: 100, offset: 0 });
297
- if (latest.ok && latest.target === target && latest.fingerprint === inspection.fingerprint) newestInspection = latest;
298
- else {
299
- if (mayRetry()) this.pending.add(target);
300
- this.last = explicit ? "store changed during bounded inspection; the selected window was not reviewed" : "store changed during bounded inspection; waiting for the next settled event";
301
- if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection snapshot changed; no worker started", true);
302
- return;
303
- }
304
- }
299
+ snapshot = await optimizer.inspectReviewPage(target, cursor);
305
300
  } catch {
306
301
  if (!current()) {
307
302
  if (mayRetry()) this.pending.add(target);
@@ -318,22 +313,23 @@ export class AutoOptimizeScheduler {
318
313
  if (mayRetry()) this.pending.add(target);
319
314
  return;
320
315
  }
321
- if (!inspection.ok) {
316
+ if ("ok" in snapshot) {
322
317
  this.last = "store inspection refused; see /mind doctor";
323
318
  if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection refused; no worker started", true);
324
319
  if (explicit) return;
325
320
  continue;
326
321
  }
322
+ const { inspection, newest, nextBefore } = snapshot;
327
323
  if (inspection.target !== target) {
328
324
  this.last = "store inspection returned a different tier; no worker started";
329
325
  if (explicit) report(target, "Mind optimization result", `Bounded review stopped before worker admission: ${this.last}.`, "inspection returned the wrong target; no worker started", true);
330
326
  if (explicit) return;
331
327
  continue;
332
328
  }
333
- const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, newestInspection);
329
+ const page = selectAutoInputPage(inspection, owner.persona, cursor.withinPage, { ...(newest ? { newest } : {}), ...(cursor.order ? { order: cursor.order } : {}) });
334
330
  nextCursor = page.pageComplete
335
- ? { offset: inspection.nextOffset ?? 0, withinPage: 0 }
336
- : { offset: cursor.offset, withinPage: page.nextRotation };
331
+ ? { offset: inspection.nextOffset ?? 0, withinPage: 0, ...(nextBefore ? { before: nextBefore } : {}) }
332
+ : { offset: cursor.offset, withinPage: page.nextRotation, order: page.order, ...(nextBefore ? { nextBefore } : {}) };
337
333
  const input = page.input;
338
334
  if (!input) {
339
335
  if (explicit) this.retryTargets.delete(target);
@@ -514,19 +510,19 @@ export class AutoOptimizeScheduler {
514
510
  }
515
511
  // One actual attempt may leave other dirty tiers pending; they need the input floor
516
512
  // and cooldown. Only the same interrupted tier bypasses the token floor.
517
- if (!explicit && attemptRecorded && this.pending.size > 0 && current() && !retryRequiresSettled) this.settled();
513
+ if (running.settledGeneration === this.generation || (!explicit && attemptRecorded && current() && !retryRequiresSettled)) this.settled();
518
514
  }
519
515
  }
520
516
  }
521
517
 
522
- export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Extract<AutoInputPage, { reason: AutoInputSkipReason }>): string {
518
+ export function formatAutoInputSkip(target: Target, inspection: OptimizeInspection, page: Pick<Extract<AutoInputPage, { reason: AutoInputSkipReason }>, "reason" | "eligibleCount" | "nextRotation" | "pageComplete">): string {
523
519
  const offset = Number.isSafeInteger(inspection.offset) && inspection.offset >= 0 ? inspection.offset : 0;
524
520
  const returned = Array.isArray(inspection.entries) ? inspection.entries.length : 0;
525
521
  const matched = Number.isSafeInteger(inspection.matched) && inspection.matched >= 0 ? inspection.matched : 0;
526
522
  const total = Number.isSafeInteger(inspection.total) && inspection.total >= 0 ? inspection.total : 0;
527
523
  const eligible = Number.isSafeInteger(page.eligibleCount) && page.eligibleCount >= 0 ? page.eligibleCount : 0;
528
- const coverage = page.pageComplete ? "candidate page covered" : `within-page rotation continues at ${page.nextRotation}`;
529
- const morePages = inspection.nextOffset === undefined ? "" : `; further inspection page starts at ${inspection.nextOffset}`;
524
+ const coverage = page.pageComplete ? "end of candidate page reached" : `within-page rotation continues at ${page.nextRotation}`;
525
+ const morePages = inspection.nextOffset === undefined ? "" : `; next rotation page position ${inspection.nextOffset}`;
530
526
  const reasons = {
531
527
  "invalid-input": "the bounded input or owner identity was invalid",
532
528
  "empty-page": "the selected page is empty or exhausted; this does not establish that the whole target is empty",
@@ -541,7 +537,7 @@ export function formatAutoInputSkip(target: Target, inspection: OptimizeInspecti
541
537
  "single-short-record": "single fact under 1,200 characters",
542
538
  "input-budget": "full-record input budget too small",
543
539
  };
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]}.`;
540
+ return `Target: ${target} — skipped: ${headlines[page.reason]}; no worker started, no memory changed.\nSelected page position ${offset}: ${returned} record(s) returned of ${matched} inspection matches; ${eligible} safe/owned eligible record(s); ${total} active record(s) in this target; ${coverage}${morePages}.\nReason: ${reasons[page.reason]}.`;
545
541
  }
546
542
 
547
543
  /**
@@ -0,0 +1,48 @@
1
+ import type { BeforeAgentStartEvent, ContextWithSystemEvent } from "@earendil-works/pi-coding-agent";
2
+
3
+ type Message = ContextWithSystemEvent["messages"][number];
4
+
5
+ /** Pi emits the starting trigger before queued nextTurn messages. Its context hook receives clones. */
6
+ export class ReferenceAnchor {
7
+ private readonly role: "user" | "custom";
8
+ private readonly customType: string | undefined;
9
+ private timestamp: number | undefined;
10
+ private occurrences = 0;
11
+ private index = -1;
12
+ private compacted = false;
13
+
14
+ constructor(trigger: BeforeAgentStartEvent) {
15
+ this.role = trigger.messageType;
16
+ this.customType = trigger.messageType === "custom" ? trigger.message.customType : undefined;
17
+ }
18
+
19
+ observe(message: Message): void {
20
+ if (this.compacted || message.role !== this.role || (message.role === "custom" && message.customType !== this.customType)) return;
21
+ if (message.role === "user") {
22
+ this.timestamp ??= message.timestamp;
23
+ if (message.timestamp !== this.timestamp) return;
24
+ }
25
+ this.occurrences++;
26
+ }
27
+
28
+ afterCompaction(): void { this.compacted = true; }
29
+
30
+ position(messages: readonly Message[]): number {
31
+ if (this.compacted) return messages.findIndex((message) => message.role === "compactionSummary");
32
+ // Pi stamps custom messages again when persisting them. Their run-local ordinal and
33
+ // custom type survive projection; user messages also retain the original timestamp.
34
+ const matches = (message: Message | undefined) => message?.role === this.role
35
+ && (message.role === "custom" ? message.customType === this.customType : message.timestamp === this.timestamp);
36
+ if (matches(messages[this.index])) return this.index;
37
+ // Count collisions from this run (including identical queued customs) from the tail. An
38
+ // identical prior submission, even in the same millisecond, cannot select older history.
39
+ let remaining = this.occurrences;
40
+ for (let i = messages.length - 1; remaining > 0 && i >= 0; i--) {
41
+ if (matches(messages[i]) && --remaining === 0) {
42
+ this.index = i;
43
+ return i;
44
+ }
45
+ }
46
+ return -1;
47
+ }
48
+ }