pi-tuck 1.0.33 → 1.1.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.
@@ -222,6 +222,18 @@ const SCORE_CHUNK = 1024;
222
222
  export function healDelayMs(attempts, integrity, delays = HEAL_DELAYS_MS, steady = HEAL_STEADY_MS) { return integrity ? steady : delays[attempts] ?? steady; }
223
223
  /** Errors that mean "the history moved or a slice ended; try again", not that the runtime failed. They do not make the state `unavailable`. */
224
224
  const CHURN = /indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
225
+ const OFF_SETUP = ['off-settings', 'off-user', 'off-platform', 'off-project'];
226
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
227
+ export const SEMANTIC_SETUP_TRANSITIONS = {
228
+ 'off-settings': OFF_SETUP,
229
+ 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
230
+ 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
231
+ 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
232
+ 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
233
+ starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
234
+ failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
235
+ ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
236
+ };
225
237
  /** Setup and operator wording have one owner; runtime indexing state remains separate. */
226
238
  export function semanticSetupMessage(setup, detail = {}) {
227
239
  switch (setup) {
@@ -597,7 +609,14 @@ export class SemanticRecallController {
597
609
  _timer;
598
610
  _error = null;
599
611
  get enabled() { return this._enabled; }
600
- set enabled(value) { this._enabled = value; this.touch(); }
612
+ set enabled(value) {
613
+ this._enabled = value;
614
+ if (!value && this.setup === 'ready') {
615
+ const reason = this.error ?? this.cleanupError;
616
+ this.setSetup(reason ? 'failed' : 'off-user', reason ? { stage: 'start', reason } : {});
617
+ }
618
+ this.touch();
619
+ }
601
620
  get current() { return this._current; }
602
621
  set current(value) { this._current = value; this.touch(); }
603
622
  get task() { return this._task; }
@@ -644,7 +663,14 @@ export class SemanticRecallController {
644
663
  }
645
664
  catch { } }); }
646
665
  /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
647
- setSetup(setup, detail = {}) { const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch(); }
666
+ setSetup(setup, detail = {}) {
667
+ if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))
668
+ return;
669
+ const announced = setup === 'ready' && this.setupDetail.announced;
670
+ this.setup = setup;
671
+ this.setupDetail = announced ? { ...detail, announced: true } : detail;
672
+ this.touch();
673
+ }
648
674
  /** Compatibility for hosts that already record an external start failure. */
649
675
  refuse(reason) { this.setSetup('failed', { stage: 'start', reason }); }
650
676
  setupNotice() { return semanticSetupNotice(this.setup, this.setupDetail); }
@@ -669,10 +695,31 @@ export class SemanticRecallController {
669
695
  const text = await readFile(path, 'utf8').catch((error) => { throw error.code === 'ENOENT' ? new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off') : error; });
670
696
  this.configure({ ...JSON.parse(text), ...(runtime?.nativeOwnerHelperPath === undefined ? {} : { nativeOwnerHelperPath: runtime.nativeOwnerHelperPath }) });
671
697
  }
672
- enable() { if (this.closing || this.joiningSearches || this.cleanupError)
673
- throw new Error('Semantic cleanup is unresolved; retry close before enable'); if (!this.config)
674
- throw new Error('Optional local semantic runtime is not configured'); this.setSetup('ready'); this.enabled = true; this.error = null; this.healReason = null; this.healAttempts = 0; this.cancelHeal(); if (this.provider && this.active)
675
- this.schedule(this.provider); }
698
+ enable() {
699
+ // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
700
+ if (['off-user', 'not-installed', 'failed'].includes(this.setup))
701
+ this.setSetup('starting');
702
+ if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))
703
+ return;
704
+ try {
705
+ if (this.closing || this.joiningSearches || this.cleanupError)
706
+ throw new Error('Semantic cleanup is unresolved; retry close before enable');
707
+ if (!this.config)
708
+ throw new Error('Optional local semantic runtime is not configured');
709
+ this.setSetup('ready');
710
+ this.enabled = true;
711
+ this.error = null;
712
+ this.healReason = null;
713
+ this.healAttempts = 0;
714
+ this.cancelHeal();
715
+ if (this.provider && this.active)
716
+ this.schedule(this.provider);
717
+ }
718
+ catch (error) {
719
+ this.setSetup('failed', { stage: 'start', reason: error instanceof Error ? error.message : String(error) });
720
+ throw error;
721
+ }
722
+ }
676
723
  status() { return { setup: this.setup, setupMessage: semanticSetupMessage(this.setup, this.setupDetail), enabled: this.enabled, configured: Boolean(this.config), cleanupError: this.cleanupError, state: (!this.enabled ? 'disabled' : this.healReason !== null || (this.error !== null && !CHURN.test(this.error)) ? 'unavailable' : this.task || this.timer ? 'preparing' : this.current?.complete ? 'ready' : 'waiting'), snapshotId: this.current?.id ?? null, throughEntryId: this.current?.throughEntryId ?? null, eligibleSources: this.current?.sources.length ?? 0, totalUnits: this.current?.units.length ?? 0, coveredUnits: this.current?.indexed.size ?? 0, indexingComplete: Boolean(this.current?.complete), lastError: this.error ?? this.healReason ?? semanticSetupMessage(this.setup, this.setupDetail), window: this.current ? windowCoverage(this.current) : null, recovery: this.healReason === null ? null : { attempts: this.healAttempts, integrity: this.healIntegrity, retryAt: this.healRetryAt === null ? null : new Date(this.healRetryAt).toISOString() }, operations: { ...this.operations }, limits: { keyword: 16000, broad: 20000 } }; }
677
724
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
678
725
  requestCoverage() { const { setup, setupMessage, ...coverage } = this.status(); return coverage; }
@@ -5,6 +5,7 @@ export declare const LOADED_VERSION: string;
5
5
  export declare function statusText(input: {
6
6
  version: string;
7
7
  active: boolean;
8
+ compaction?: import('./compaction.js').CompactionState;
8
9
  branch: readonly {
9
10
  type: string;
10
11
  tokensBefore?: unknown;
@@ -15,6 +15,8 @@ export const LOADED_VERSION = (() => {
15
15
  export function statusText(input) {
16
16
  if (!input.active)
17
17
  return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
18
+ if (input.compaction?.kind === 'standingDown')
19
+ return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
18
20
  const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => e.details?.compactor === "pi-tuck");
19
21
  const last = ours.at(-1), before = last?.tokensBefore, after = last?.details?.tokensAfter;
20
22
  const count = (n) => n.toLocaleString("en-US");
@@ -57,7 +57,7 @@ const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall",
57
57
  * or, with no role, of the tool history
58
58
  * | role " omitted " count " #" index "-#" index ":" ... counted inclusive index range
59
59
  * | role " omitted " count [ " " locator-time { " " locator-time } ] ":" ... omission of unselected text blocks
60
- * | [ locator " " ] title ":" ... section (file ledger, action trail)
60
+ * | [ locator " " ] title ":" ... section (Files, Actions, Kept-read)
61
61
  * locator = "#" index the source's session-wide index, as tuck_recall {"index"} takes it
62
62
  * locator-time = locator [ "@" time-value ] every locator of a record has a time, or none does
63
63
  * role = "user" | "assistant" | "custom" | "toolResult" (omissions only)
package/dist/src/tuck.js CHANGED
@@ -7,6 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.j
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content.js";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
+ import { keptReadCandidates } from "./kept-reads.js";
10
11
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
11
12
  import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
12
13
  /** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
@@ -376,9 +377,26 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
376
377
  let { boundary, high: protectedView } = selected;
377
378
  const sourceRows = rows.filter(row => row.position < boundary);
378
379
  const lists = listsAt(boundary);
379
- let ledger = lists.records;
380
+ const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
381
+ const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
382
+ let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
383
+ const keptReads = [];
384
+ for (const record of keptReadCandidates(entries.slice(0, boundary), indices, entry => readable(entry) !== undefined)) {
385
+ const cost = lineCost([record]);
386
+ if (cost > allowance)
387
+ continue;
388
+ keptReads.push(record);
389
+ allowance -= cost;
390
+ if (keptReads.length === 4)
391
+ break;
392
+ }
393
+ let ledger = [...lists.records, ...keptReads];
380
394
  // List caps are existing ranking policy; only the carried target is a
381
395
  // spending limit. Candidate list sizes have fixed, cached line prices.
396
+ while (keptReads.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
397
+ keptReads.pop();
398
+ ledger = [...lists.records, ...keptReads];
399
+ }
382
400
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
383
401
  ledger = [];
384
402
  for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
@@ -392,7 +410,6 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
392
410
  return row?.message.role === "user" && isTextOnly(row.message.content);
393
411
  }));
394
412
  const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
395
- const maxSummaryCharacters = Math.floor((target - offset - nativeAt(boundary)) * 4) - wrapperCharacters;
396
413
  const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
397
414
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
398
415
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(byId.get(row.id))),
@@ -502,7 +519,12 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
502
519
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
503
520
  });
504
521
  const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
522
+ const keptReadCost = lineCost(keptReads), keptReadIndices = new Set(keptReads.map(record => record.sourceIndex));
523
+ const lastKeptReadPosition = entries.findLastIndex(entry => keptReadIndices.has(indices.get(entry.id)));
505
524
  const extensionPrice = (at) => {
525
+ // Fixed kept reads outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
526
+ if (keptReads.length && (at <= lastKeptReadPosition || keptReadCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
527
+ return Infinity;
506
528
  let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
507
529
  let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
508
530
  for (const range of ranges) {
package/index.ts CHANGED
@@ -72,6 +72,7 @@ export default async function (pi: ExtensionAPI) {
72
72
  pi.on("session_start", (_event, ctx) => {
73
73
  const current = ++session;
74
74
  stderrSaid.clear();
75
+ if (handle.state?.(ctx).kind === "standingDown") return;
75
76
  if (settings.error) once(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
76
77
  if (!appleSilicon)
77
78
  return announce(ctx, "off-platform");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.0.33",
3
+ "version": "1.1.1",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history. Search by meaning on Apple silicon.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "ca81d2cebd530b421127fa0090adc48f14b9532bc7195141dcc4ced449c8f791";
1
+ export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
package/src/compaction.ts CHANGED
@@ -56,6 +56,9 @@ class Refusal extends Error {}
56
56
  class CommitFault extends Error {}
57
57
  /** A refusal for want of room, which the user can remedy: it carries advice. */
58
58
  class CapacityError extends Refusal {}
59
+ function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") {
60
+ try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, level); } catch { /* ended */ }
61
+ }
59
62
  /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
60
63
  * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
61
64
  export const refusalNotice = (message: string, factor: number): string =>
@@ -79,7 +82,8 @@ export const MEASURED_CALIBRATION: Readonly<Record<string, number>> = {};
79
82
  function initialWindow(key: string): number[] {
80
83
  try { const [provider, , id] = JSON.parse(key) as [string, string, string]; return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)]; } catch { return [1]; }
81
84
  }
82
- /** The calibration window a session starts with under accounting identity `key`: the newest compaction on the branch that carries this package's
85
+ export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
86
+ /** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
83
87
  * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
84
88
  * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
85
89
  * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
@@ -88,10 +92,14 @@ function initialWindow(key: string): number[] {
88
92
  export function seedWindow(branch: readonly SessionEntry[], key: string): number[] {
89
93
  for (let i = branch.length; i--;) {
90
94
  const entry = branch[i]!;
91
- const receipt = entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
95
+ const receipt = entry.type === "custom" && entry.customType === CALIBRATION_RECEIPT ? { settings: entry.data as Partial<Receipt["settings"]> | undefined }
96
+ : entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
92
97
  if (receipt === undefined) continue;
93
98
  const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored: unknown = calibrationWindow;
94
- if (calibrationIdentity !== key) return initialWindow(key);
99
+ if (calibrationIdentity !== key) {
100
+ if (entry.type === "custom") continue; // Another model's new observation does not hide this model's last saved seed.
101
+ return initialWindow(key);
102
+ }
95
103
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
96
104
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
97
105
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor)) return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
@@ -99,6 +107,15 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
99
107
  }
100
108
  return initialWindow(key);
101
109
  }
110
+ export type CompactionState = { kind: "active" } | { kind: "standingDown"; reason: string };
111
+ /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
112
+ export function compactionState(model: { api: string; contextWindow?: number } | undefined, enabled: boolean): CompactionState {
113
+ const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
114
+ : model.contextWindow === undefined ? "context window is missing"
115
+ : !Number.isFinite(model.contextWindow) ? "context window is not finite"
116
+ : model.contextWindow <= 0 ? "context window is zero or negative" : undefined;
117
+ return reason ? { kind: "standingDown", reason } : { kind: "active" };
118
+ }
102
119
  export interface CompactionOptions {
103
120
  semanticRecall?: SemanticRecallController;
104
121
  /** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
@@ -186,7 +203,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
186
203
  } });
187
204
  pi.on("session_compact", (_event, ctx) => observe(ctx));
188
205
  // A saved cut moves entries out of view: index them now, in the background, even for a session that has not searched or whose worker the idle limit stopped.
189
- pi.on("session_compact", (_event, ctx) => { semantic.indexAtCut(semanticProvider(ctx)); });
206
+ pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx)) semantic.indexAtCut(semanticProvider(ctx)); });
190
207
  pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
191
208
  pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close();void semanticTransition.catch(error => { options.fail?.(error); }); });
192
209
  pi.on("turn_end", (_event,ctx) => { semantic.schedule(semanticProvider(ctx)); });
@@ -223,7 +240,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
223
240
  }});
224
241
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
225
242
  const state = semantic.status();
226
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
243
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
227
244
  } });
228
245
  // Pi's native start/settled events bracket the run and its post-turn cuts.
229
246
  let run: Run | undefined;
@@ -234,6 +251,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
234
251
  const clips = () => run?.clips ?? emptyClips;
235
252
  const emptyClips = new Map<string, Clip>();
236
253
  const resetRun = () => { run = undefined; pending = undefined; };
254
+ const stateFor = (ctx: ExtensionContext) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
255
+ // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
256
+ const standDown = (ctx: ExtensionContext) => {
257
+ if (stateFor(ctx).kind === "active") return false;
258
+ resetRun();
259
+ windowObservation = undefined;
260
+ lengthStop = false;
261
+ return true;
262
+ };
237
263
  const promptRefusal = () => new Refusal("Prompt check failed: the whole starting prompt cannot fit after cutting to the band and room, shrinking the summary and clipping fresh results. Shorten the prompt or choose a model with a larger context window, then retry");
238
264
  let estimatedTokens = 0;
239
265
  // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
@@ -265,7 +291,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
265
291
  };
266
292
  });
267
293
  // The factor is max(1, the last CALIBRATION_WINDOW paired ratios, overflow bounds and seed): it rises at once and a stale high ratio ages out.
268
- const learn = (value: number) => { ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios); };
294
+ const learn = (value: number, ctx: ExtensionContext) => {
295
+ ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios);
296
+ // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
297
+ if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
298
+ pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
299
+ };
269
300
  const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * factor); };
270
301
  const observeBudget = (rawTokens: number, ctx: ExtensionContext) => {
271
302
  if (options.observeBudget) options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor, ...limits(ctx), context: ctx });
@@ -278,6 +309,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
278
309
  };
279
310
  pi.on("message_end", (event, ctx) => {
280
311
  if (event.message.role !== "assistant") return;
312
+ if (standDown(ctx)) return;
281
313
  const responseMessage = event.message;
282
314
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
283
315
  if (!responseMessage.content.some(b => b.type === "thinking")) recorder.capture("response-actions", "native-public-message-end", responseMessage);
@@ -298,8 +330,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
298
330
  if (overflow) {
299
331
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
300
332
  const learned = bound <= CALIBRATION_CEILING;
301
- ctx.ui.notify(overflowNotice(window, bound, learned), "warning");
302
- if (learned) learn(bound);
333
+ notify(ctx, overflowNotice(window, bound, learned), "warning");
334
+ if (learned) learn(bound, ctx);
303
335
  return;
304
336
  }
305
337
  const usage = message.usage;
@@ -318,9 +350,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
318
350
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
319
351
  // Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
320
352
  // 6,000-token prompt refuse. The overflow branch above learns from a refusal, where the count is a lower bound, and the ceiling is unchanged.
321
- if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio);
353
+ if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio, ctx);
322
354
  });
323
- pi.on("turn_end", event => {
355
+ pi.on("turn_end", (event, ctx) => {
356
+ if (standDown(ctx)) return;
324
357
  if (windowObservation?.message !== event.message) return;
325
358
  const observation = windowObservation; windowObservation = undefined;
326
359
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
@@ -329,18 +362,18 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
329
362
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
330
363
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
331
364
  let lengthStop = false;
332
- pi.on("agent_start", () => { run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
365
+ pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
333
366
  pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
334
367
  pi.on("agent_settled", (_event, ctx) => {
335
368
  try {
336
- if (!lengthStop || !active()) return;
369
+ if (standDown(ctx) || !lengthStop || !active()) return;
337
370
  lengthStop = false;
338
371
  const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
339
- try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, "warning"); } catch { /* ended */ }
372
+ notify(ctx, message, "warning");
340
373
  } finally { resetRun(); }
341
374
  });
342
375
  const active = () => options.active?.() ?? true;
343
- const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings());
376
+ const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
344
377
  // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
345
378
  // not fit (a length stop with text/tools, or a refusal pi-ai classes as a context overflow), hold the catalogue maximum too. A thinking-only
346
379
  // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
@@ -450,7 +483,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
450
483
  recorder.stop("native-attempt-failed");
451
484
  // Every refusal says why, once per attempt: a capacity error with what the user can change, a cut Pi failed to commit with what that
452
485
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
453
- const previous = failure(), notify = !previous;
486
+ const previous = failure(), shouldNotify = !previous;
454
487
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
455
488
  const receipted = run?.refusalReceipted;
456
489
  resetRun();
@@ -461,7 +494,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
461
494
  if (!receipted) receipt("refusal", fault.message, ctx);
462
495
  options.fail?.(error);
463
496
  } finally {
464
- try { if (notify) ctx.ui.notify(fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
497
+ try { if (shouldNotify) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
465
498
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
466
499
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
467
500
  finally { ctx.abort(); }
@@ -533,6 +566,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
533
566
 
534
567
  pi.on("session_before_compact", (event, ctx) => {
535
568
  try {
569
+ if (standDown(ctx)) return;
536
570
  if (!active()) return { cancel: true };
537
571
  if (event.signal.aborted || ctx.signal?.aborted) { recorder.stop("cut-cancelled"); return { cancel: true }; }
538
572
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
@@ -550,7 +584,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
550
584
  access();
551
585
  // pi-tuck's summary is built from the session itself, so text after /compact cannot steer it. The operator asked for a cut: make the one
552
586
  // plain /compact makes and say the text was not used, rather than cancel (which Pi shows as an error, with no cut).
553
- if (event.customInstructions?.trim()) ctx.ui.notify("pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
587
+ if (event.customInstructions?.trim()) notify(ctx, "pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
554
588
  const { response, room } = limits(ctx);
555
589
  const retain = operatorManual || run?.phase === "admitted";
556
590
  // A cut Pi asks for (an operator's /compact, Pi's threshold or overflow recovery) charges what the request must carry whatever is
@@ -602,7 +636,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
602
636
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
603
637
  if (decision.kind === "none" || decision.kind === "defer") return { cancel: true };
604
638
  recorder.stop("no-cut");
605
- ctx.ui.notify(decision.message, "warning");
639
+ notify(ctx, decision.message, "warning");
606
640
  if (operatorManual) receipt("refusal", decision.message, ctx);
607
641
  if (!operatorManual) fail(new (decision.capacity ? CapacityError : Refusal)(decision.message), ctx);
608
642
  return { cancel: true };
@@ -610,14 +644,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
610
644
  try { fail(error, ctx); } finally { return { cancel: true }; }
611
645
  }
612
646
  });
613
- pi.on("session_before_tree", (event) => event.preparation.userWantsSummary ? { cancel: true } : undefined);
647
+ pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
614
648
  pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
615
- const historyToolsEnabled = (ctx: ExtensionContext) => view(ctx).hasTuckCut;
649
+ const historyToolsEnabled = (ctx: ExtensionContext) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
616
650
  const syncHistoryTools = (ctx: ExtensionContext) => { if (active()) applyHistoryTools(pi, historyToolsEnabled(ctx)); };
617
651
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
618
652
  // A plan decided on `input` is for the branch it was decided on: moving in the tree leaves it planned for another branch, whose kept entry
619
653
  // may not be on this one.
620
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), identityFor(ctx)); syncHistoryTools(ctx); });
654
+ pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
621
655
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted") syncHistoryTools(ctx); });
622
656
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
623
657
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
@@ -661,6 +695,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
661
695
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
662
696
  // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
663
697
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages) => {
698
+ if (standDown(ctx)) return;
664
699
  run!.cut.clear();
665
700
  const branchLength = ctx.sessionManager.getBranch().length;
666
701
  if (!active()) return;
@@ -719,6 +754,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
719
754
  run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
720
755
  };
721
756
  pi.on("before_agent_start", async (event, ctx) => {
757
+ if (standDown(ctx)) return;
722
758
  // A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
723
759
  // input, so no run started for it): plan afresh.
724
760
  const prompted = run?.phase === "decided" && event.messageType !== "custom";
@@ -747,6 +783,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
747
783
  // handlers have run. Pi's prepareRequest has not yet snapshotted executable tools. A first cut discovered in context_with_system
748
784
  // would be too late for that snapshot, even if its declarations were repaired there, so make the late prompt decision here.
749
785
  pi.on("message_end", (event, ctx) => {
786
+ if (standDown(ctx)) return;
750
787
  if (event.message.role !== "user" || !active() || run?.phase !== "admitted" || view(ctx).pending) return;
751
788
  try {
752
789
  access();
@@ -928,7 +965,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
928
965
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
929
966
  const entries: SessionBoundaryDraft[] = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
930
967
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
931
- if (run!.thinkingRetryPending) return { entries, continue: false };
968
+ if (run!.thinkingRetryPending) { markBoundary(entries); return { entries, continue: false }; }
932
969
  const preview = liveCut.view(ctx, entries).session;
933
970
  const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
934
971
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
@@ -943,9 +980,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
943
980
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
944
981
  const { room, hardLine } = limits(view);
945
982
  run!.thinkingRetryPending = true;
946
- return { entries: [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
983
+ const drafts = [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
947
984
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
948
- piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }], continue: true };
985
+ piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
986
+ markBoundary(drafts);
987
+ return { entries: drafts, continue: true };
949
988
  }
950
989
  if (decision.kind !== "cut") throw new CapacityError(clampMessage);
951
990
  const messages = projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true);
@@ -971,6 +1010,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
971
1010
  };
972
1011
  pi.on("turn_end", (event, ctx) => {
973
1012
  try {
1013
+ if (standDown(ctx)) return;
974
1014
  if (!active() || run?.phase !== "admitted") return;
975
1015
  if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
976
1016
  return retryLength(event, ctx);
@@ -1061,6 +1101,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1061
1101
  };
1062
1102
  pi.on("context", (event, ctx) => {
1063
1103
  try {
1104
+ if (standDown(ctx)) return;
1064
1105
  if (!active()) return;
1065
1106
  run?.prompt?.id(ctx.sessionManager.getBranch());
1066
1107
  // Before a cut, Pi owns the whole request, including its object identities and system-message serialization.
@@ -1070,6 +1111,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1070
1111
  } catch (error) { try { fail(error, ctx); } finally { return historyToolsEnabled(ctx) ? { messages: [] } : undefined; } }
1071
1112
  });
1072
1113
  pi.on("session_compact_failed", (event, ctx) => {
1114
+ if (standDown(ctx)) return;
1073
1115
  // This compactor's own refusal of a Pi threshold ask (the gate, or an opportunistic cut that cannot reach the band) reaches here as a
1074
1116
  // threshold compaction cancelled and not from an extension: no event for the recorder.
1075
1117
  if (event.reason === "threshold" && event.aborted && !event.fromExtension) return;
@@ -1084,6 +1126,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1084
1126
  if (active() && !event.aborted) fail(new (event.fromExtension ? CommitFault : Error)(event.errorMessage ?? "Compaction failed"), ctx);
1085
1127
  });
1086
1128
  pi.on("agent_before_settle", (event, ctx) => {
1129
+ if (standDown(ctx)) return;
1087
1130
  if (run?.pendingBoundaryCommit) {
1088
1131
  if (event.outcome === "error") {
1089
1132
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
@@ -1100,6 +1143,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1100
1143
  } catch (error) { fail(error, ctx); }
1101
1144
  });
1102
1145
  pi.on("context_with_system", (event, ctx) => {
1146
+ if (standDown(ctx)) return;
1103
1147
  // Reaching the next request boundary proves native commit returned, not durable storage.
1104
1148
  if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1105
1149
  pending = undefined;
@@ -1148,7 +1192,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1148
1192
 
1149
1193
  } catch (error) { fail(error, ctx); }
1150
1194
  });
1151
- return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus};
1195
+ return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus, state: stateFor};
1152
1196
  }
1153
1197
 
1154
1198
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -0,0 +1,36 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { isTextOnly, textOf } from "./tuck/core/content";
3
+ import { extractPath } from "./tuck/core/tool-args";
4
+ import type { TranscriptRecord } from "./tuck/core/transcript";
5
+
6
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
7
+ export function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>,
8
+ resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
9
+ const reads = new Map<string, { path: string; order: number }>(), mutations = new Map<string, number>();
10
+ let order = 0;
11
+ for (const entry of entries) {
12
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
13
+ for (const block of entry.message.content) {
14
+ if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
15
+ !block.arguments || typeof block.arguments !== "object") continue;
16
+ const path = extractPath(block.arguments as Record<string, unknown>);
17
+ if (!path || /[\r\n]/u.test(path)) continue;
18
+ order++;
19
+ if (block.name === "read") reads.set(block.id, { path, order });
20
+ else mutations.set(path, order);
21
+ }
22
+ }
23
+ const seen = new Set<string>(), records: TranscriptRecord[] = [];
24
+ for (let at = entries.length - 1; at >= 0; at--) {
25
+ const entry = entries[at]!;
26
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
27
+ const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
28
+ if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order) continue;
29
+ const text = textOf(entry.message.content);
30
+ if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
31
+ seen.add(read.path);
32
+ records.push({ kind: "section", title: "Kept-read", sourceIndex,
33
+ text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
34
+ }
35
+ return records;
36
+ }
@@ -140,6 +140,18 @@ export function healDelayMs(attempts:number,integrity:boolean,delays:readonly nu
140
140
  const CHURN=/indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
141
141
  export type SemanticState='disabled'|'unavailable'|'preparing'|'ready'|'waiting';
142
142
  export type SemanticSetup = 'off-settings' | 'off-user' | 'not-installed' | 'off-platform' | 'off-project' | 'starting' | 'failed' | 'ready';
143
+ const OFF_SETUP: readonly SemanticSetup[] = ['off-settings', 'off-user', 'off-platform', 'off-project'];
144
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
145
+ export const SEMANTIC_SETUP_TRANSITIONS: Readonly<Record<SemanticSetup, readonly SemanticSetup[]>> = {
146
+ 'off-settings': OFF_SETUP,
147
+ 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
148
+ 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
149
+ 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
150
+ 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
151
+ starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
152
+ failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
153
+ ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
154
+ };
143
155
  interface SetupDetail { installed?: boolean; reason?: string; stage?: 'setup' | 'start'; notice?: string; announced?: boolean }
144
156
  /** Setup and operator wording have one owner; runtime indexing state remains separate. */
145
157
  export function semanticSetupMessage(setup: SemanticSetup, detail: SetupDetail = {}): string | null {
@@ -283,7 +295,11 @@ export class SemanticRecallController {
283
295
  // The fields below decide `status().state`; their setters announce a change to `onStateChange` listeners.
284
296
  private setup: SemanticSetup = 'off-user'; private setupDetail: SetupDetail = {};
285
297
  private _enabled=false;private _current?:Snapshot;private _task?:Promise<void>;private _timer?:ReturnType<typeof setTimeout>;private _error:string|null=null;
286
- private get enabled(){return this._enabled;}private set enabled(value:boolean){this._enabled=value;this.touch();}
298
+ private get enabled(){return this._enabled;}private set enabled(value:boolean){
299
+ this._enabled=value;
300
+ if(!value&&this.setup==='ready'){const reason=this.error??this.cleanupError;this.setSetup(reason?'failed':'off-user',reason?{stage:'start',reason}:{});}
301
+ this.touch();
302
+ }
287
303
  private get current(){return this._current;}private set current(value:Snapshot|undefined){this._current=value;this.touch();}
288
304
  private get task(){return this._task;}private set task(value:Promise<void>|undefined){this._task=value;this.touch();}
289
305
  private get timer(){return this._timer;}private set timer(value:ReturnType<typeof setTimeout>|undefined){this._timer=value;this.touch();}
@@ -303,7 +319,10 @@ export class SemanticRecallController {
303
319
  onStateChange(listener:(state:SemanticState,reason:string|null)=>void):()=>void{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};}
304
320
  private touch(){if(this.announcing)return;this.announcing=true;queueMicrotask(()=>{this.announcing=false;const {state,lastError}=this.status(),key=state+'\0'+(lastError??'');if(key===this.announced)return;this.announced=key;for(const listener of [...this.listeners])try{listener(state,lastError);}catch{}});}
305
321
  /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
306
- setSetup(setup: SemanticSetup, detail: SetupDetail = {}) { const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch(); }
322
+ setSetup(setup: SemanticSetup, detail: SetupDetail = {}) {
323
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))return;
324
+ const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch();
325
+ }
307
326
  /** Compatibility for hosts that already record an external start failure. */
308
327
  refuse(reason:string){this.setSetup('failed', { stage: 'start', reason });}
309
328
  setupNotice(){return semanticSetupNotice(this.setup, this.setupDetail);}
@@ -312,7 +331,13 @@ export class SemanticRecallController {
312
331
  * optional override is a current-process verified dependency, not Task data. */
313
332
  async configureExternal(project:string,selectedPath=runtimeConfigPath(defaultRoot()),runtime?:{nativeOwnerHelperPath?:string}){const path=resolve(selectedPath);outsideProject(project,path,'configuration');if(runtime?.nativeOwnerHelperPath!==undefined)outsideProject(project,runtime.nativeOwnerHelperPath,'runtime');const text=await readFile(path,'utf8').catch((error:NodeJS.ErrnoException)=>{throw error.code==='ENOENT'?new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off'):error;});
314
333
  this.configure({...JSON.parse(text) as SemanticRecallConfig,...(runtime?.nativeOwnerHelperPath===undefined?{}:{nativeOwnerHelperPath:runtime.nativeOwnerHelperPath})});}
315
- enable(){if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
334
+ enable(){
335
+ // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
336
+ if(['off-user','not-installed','failed'].includes(this.setup))this.setSetup('starting');
337
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))return;
338
+ try{if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
339
+ catch(error){this.setSetup('failed',{stage:'start',reason:error instanceof Error?error.message:String(error)});throw error;}
340
+ }
316
341
  status(){return{setup:this.setup,setupMessage:semanticSetupMessage(this.setup,this.setupDetail),enabled:this.enabled,configured:Boolean(this.config),cleanupError:this.cleanupError,state:(!this.enabled?'disabled':this.healReason!==null||(this.error!==null&&!CHURN.test(this.error))?'unavailable':this.task||this.timer?'preparing':this.current?.complete?'ready':'waiting') as SemanticState,snapshotId:this.current?.id??null,throughEntryId:this.current?.throughEntryId??null,eligibleSources:this.current?.sources.length??0,totalUnits:this.current?.units.length??0,coveredUnits:this.current?.indexed.size??0,indexingComplete:Boolean(this.current?.complete),lastError:this.error??this.healReason??semanticSetupMessage(this.setup,this.setupDetail),window:this.current?windowCoverage(this.current):null,recovery:this.healReason===null?null:{attempts:this.healAttempts,integrity:this.healIntegrity,retryAt:this.healRetryAt===null?null:new Date(this.healRetryAt).toISOString()},operations:{...this.operations},limits:{keyword:16000,broad:20000}};}
317
342
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
318
343
  requestCoverage(){const {setup,setupMessage,...coverage}=this.status();return coverage;}