dsh-live-compact 1.1.10 → 1.1.12

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/index.js CHANGED
@@ -17,16 +17,18 @@ import { closeSync, existsSync, openSync, readFileSync, renameSync, unlinkSync,
17
17
  import { createRequire } from "node:module";
18
18
  import { setImmediate as scheduleImmediate } from "node:timers";
19
19
  import { Worker } from "node:worker_threads";
20
- import { dirname, join } from "node:path";
21
- import { pathToFileURL } from "node:url";
20
+ import { basename, dirname, join, resolve as resolvePath } from "node:path";
21
+ import { fileURLToPath, pathToFileURL } from "node:url";
22
22
  import { loadBase, loadCompaction, loadLlm } from "./adapter.js";
23
23
  import { DEFAULTS, engineConfig, readSettings } from "./settings.js";
24
24
  import { attachBackupHint, backgroundJobId, backupClaimOk, buildCard, collectJobs, cutLongReadRound, finishedToolRounds, indexToolCalls, isToolFailure, jobCutDecision, keptToolRounds, messageText, planMessages, pointerOnlyText, pointerSpanAllowed, RAIL_TOKENS, readResultLabel, reservedCutEnd, resolveEngine, resolveProviderBaseURL, roundHasLongRead, selectCutIndexes, shadowSections, takeLocalCut, withoutFullBackupClaim } from "./plan.js";
25
25
  import { captureOwnedToolResult, contentHash, PRUNE_MARKER, rawExcerptText, rawName, readRawToolResult, restoreToolText, runPruneAfterCapture, verifiedRaw } from "./raw.js";
26
26
  import {
27
27
  ensureShadowDir,
28
+ appendDecision,
28
29
  flushDrainStats,
29
30
  noteShadowWarning,
31
+ recoverTimedOutShadowWorker,
30
32
  saveShadowTransaction,
31
33
  shadowDirectory,
32
34
  shadowFileBody,
@@ -41,6 +43,92 @@ import { buildSendLess, decideThunder } from "./thunder.js";
41
43
  import { inCooldown, skipLiveOfficialCompaction } from "./cooldown.js";
42
44
  import { activeCompactionPeers, warnCompactionStandDown } from "./gate.js";
43
45
 
46
+ const PI_AI_CATALOG = "@earendil-works/pi-ai/providers/all";
47
+ const PI_AI_PACKAGE = "@earendil-works/pi-ai";
48
+
49
+ function catalogExportTarget(value) {
50
+ if (typeof value === "string") return value;
51
+ if (!value || typeof value !== "object") return "";
52
+ return value.import || value.node || value.default || value.require || "";
53
+ }
54
+
55
+ function catalogPackageRoots(anchor) {
56
+ let dir;
57
+ try { dir = anchor.startsWith("file:") ? dirname(fileURLToPath(anchor)) : dirname(anchor); } catch { return []; }
58
+ const roots = [];
59
+ for (let count = 0; count < 12; count += 1) {
60
+ roots.push(join(dir, "node_modules", PI_AI_PACKAGE));
61
+ const parent = dirname(dir);
62
+ if (parent === dir) break;
63
+ dir = parent;
64
+ }
65
+ return roots;
66
+ }
67
+
68
+ async function importCatalogFromPackage(root) {
69
+ const packageFile = join(root, "package.json");
70
+ if (!existsSync(packageFile)) return [];
71
+ let packageJson;
72
+ try { packageJson = JSON.parse(readFileSync(packageFile, "utf8")); } catch { return []; }
73
+ const target = catalogExportTarget(packageJson.exports?.["./providers/all"]);
74
+ const candidates = target
75
+ ? [resolvePath(root, target)]
76
+ : [join(root, "providers", "all.js"), join(root, "providers", "all.mjs"), join(root, "providers", "all", "index.js")];
77
+ for (const candidate of candidates) {
78
+ try {
79
+ const normalized = normalizeCatalogModule(await import(pathToFileURL(candidate).href));
80
+ if (normalized.length) return normalized;
81
+ } catch {}
82
+ }
83
+ return [];
84
+ }
85
+
86
+ function normalizeCatalogModule(loaded) {
87
+ const source = loaded?.builtinProviders ? loaded : loaded?.default;
88
+ const list = typeof source?.builtinProviders === "function" ? source.builtinProviders() : [];
89
+ return list.map((entry) => {
90
+ let models = [];
91
+ try {
92
+ const declared = typeof entry?.getModels === "function" ? entry.getModels() : entry?.models || [];
93
+ models = (Array.isArray(declared) ? declared : []).map((model) => ({
94
+ id: model?.id || "",
95
+ baseURL: model?.baseUrl || model?.baseURL || "",
96
+ })).filter((model) => model.id && model.baseURL);
97
+ } catch {}
98
+ return {
99
+ id: entry?.id || "",
100
+ baseURL: entry?.baseUrl || entry?.baseURL || "",
101
+ models,
102
+ };
103
+ }).filter((entry) => entry.id && (entry.baseURL || entry.models.length));
104
+ }
105
+
106
+ async function loadPiAiCatalog() {
107
+ try {
108
+ return normalizeCatalogModule(await import(PI_AI_CATALOG));
109
+ } catch {}
110
+ try {
111
+ const resolved = typeof import.meta.resolve === "function" ? import.meta.resolve(PI_AI_CATALOG) : null;
112
+ if (resolved) return normalizeCatalogModule(await import(resolved));
113
+ } catch {}
114
+ const anchors = [import.meta.url];
115
+ try {
116
+ if (process.argv[1]) anchors.push(pathToFileURL(process.argv[1]).href);
117
+ } catch {}
118
+ for (const anchor of anchors) {
119
+ for (const root of catalogPackageRoots(anchor)) {
120
+ const normalized = await importCatalogFromPackage(root);
121
+ if (normalized.length) return normalized;
122
+ }
123
+ try {
124
+ const loaded = createRequire(anchor)(PI_AI_CATALOG);
125
+ const normalized = normalizeCatalogModule(loaded);
126
+ if (normalized.length) return normalized;
127
+ } catch {}
128
+ }
129
+ return [];
130
+ }
131
+
44
132
  const { BasicCompactionEngine } = await loadBase();
45
133
  const { CompactionId, toolPairingBalancedAfter, toolPairingBalancedBefore } = await loadCompaction();
46
134
  const { createUserMessage } = await loadLlm();
@@ -58,6 +146,9 @@ const RECOVER_RAW_BATCH = 1;
58
146
  const CAPTURE_RETRY_LIMIT = 8;
59
147
  const RECOVERY_ACL_REAUTH_LIMIT = 32;
60
148
  const SHADOW_WORKER_TIMEOUT_MS = 30000;
149
+ const SHADOW_WORKER_RECOVERY_MS = 60000;
150
+ const PRESTEP_WAIT_TIMEOUT_MS = 3000;
151
+ const SHADOW_WORKER_IDLE_MS = process.platform === "win32" ? 60000 : 500;
61
152
 
62
153
  const shadowWorkers = new Map();
63
154
 
@@ -65,13 +156,23 @@ function shadowWorkerFor(root) {
65
156
  const key = String(root);
66
157
  let entry = shadowWorkers.get(key);
67
158
  if (entry) return entry;
68
- const worker = new Worker(new URL("./shadow-save-worker.mjs", import.meta.url), {
69
- workerData: { spineWorker: 1, accessFuse: shadowAccessFuseBuffer() },
159
+ // DSH Tauri starts the host with --input-type=module --eval. Passing a
160
+ // filtered execArgv array makes Node re-parse host-only V8 flags such as
161
+ // --max-old-space-size and can throw ERR_WORKER_INVALID_EXEC_ARGV. An eval
162
+ // bootstrap keeps the worker's native argv inheritance and dynamically
163
+ // imports the module URL without re-running the host's eval script.
164
+ const workerURL = new URL("./shadow-save-worker.mjs", import.meta.url).href;
165
+ const workerBootstrap = `import(${JSON.stringify(workerURL)}).catch((error) => { setImmediate(() => { throw error; }); });`;
166
+ const ownerToken = randomBytes(24).toString("hex");
167
+ const worker = new Worker(workerBootstrap, {
168
+ eval: true,
169
+ workerData: { spineWorker: 1, spineOwner: ownerToken, accessFuse: shadowAccessFuseBuffer() },
70
170
  });
71
- entry = { worker, nextId: 1, pending: new Map(), idleTimer: null, retired: false, timedOut: false };
171
+ entry = { worker, root: key, ownerToken, nextId: 1, pending: new Map(), idleTimer: null, recoveryTimer: null, retired: false, timedOut: false };
72
172
  const removeEntry = () => {
73
173
  if (shadowWorkers.get(key) === entry) shadowWorkers.delete(key);
74
174
  };
175
+ entry.removeEntry = removeEntry;
75
176
  const scheduleIdleExit = () => {
76
177
  if (entry.retired || entry.pending.size || entry.idleTimer) return;
77
178
  entry.idleTimer = setTimeout(() => {
@@ -80,8 +181,9 @@ function shadowWorkerFor(root) {
80
181
  entry.retired = true;
81
182
  removeEntry();
82
183
  worker.terminate().catch(() => {});
83
- }, 500);
184
+ }, SHADOW_WORKER_IDLE_MS);
84
185
  entry.idleTimer.unref?.();
186
+ worker.unref?.();
85
187
  };
86
188
  entry.scheduleIdleExit = scheduleIdleExit;
87
189
  const fail = (error) => {
@@ -90,20 +192,32 @@ function shadowWorkerFor(root) {
90
192
  clearTimeout(entry.idleTimer);
91
193
  entry.idleTimer = null;
92
194
  }
195
+ if (entry.recoveryTimer) {
196
+ clearTimeout(entry.recoveryTimer);
197
+ entry.recoveryTimer = null;
198
+ }
93
199
  for (const { reject, timer } of entry.pending.values()) {
94
200
  if (timer) clearTimeout(timer);
95
201
  reject(error);
96
202
  }
97
203
  entry.pending.clear();
98
204
  removeEntry();
99
- worker.terminate().catch(() => {});
205
+ worker.terminate()
206
+ .then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
207
+ .catch(() => {});
100
208
  };
101
209
  worker.on("message", (message) => {
102
210
  const task = entry.pending.get(message?.id);
103
211
  if (!task) return;
104
212
  if (task.timer) clearTimeout(task.timer);
105
213
  entry.pending.delete(message.id);
106
- if (entry.timedOut && entry.pending.size === 0) entry.timedOut = false;
214
+ if (entry.timedOut && entry.pending.size === 0) {
215
+ entry.timedOut = false;
216
+ if (entry.recoveryTimer) {
217
+ clearTimeout(entry.recoveryTimer);
218
+ entry.recoveryTimer = null;
219
+ }
220
+ }
107
221
  if (message?.ok) {
108
222
  task.resolve(message.result);
109
223
  scheduleIdleExit();
@@ -137,6 +251,7 @@ function runShadowWorker(payload) {
137
251
  if (entry.idleTimer) {
138
252
  clearTimeout(entry.idleTimer);
139
253
  entry.idleTimer = null;
254
+ entry.worker.ref?.();
140
255
  }
141
256
  const id = entry.nextId++;
142
257
  return new Promise((resolve, reject) => {
@@ -149,6 +264,27 @@ function runShadowWorker(payload) {
149
264
  // keep the pending task until the worker naturally releases its lock.
150
265
  task.timedOut = true;
151
266
  entry.timedOut = true;
267
+ // Let the host exit while a blocked filesystem call drains. A bounded
268
+ // recovery removes the poisoned entry later without killing a worker
269
+ // that may still own a rotation lock.
270
+ if ([...entry.pending.values()].every((pending) => pending.timedOut)) entry.worker.unref?.();
271
+ if (!entry.recoveryTimer) {
272
+ entry.recoveryTimer = setTimeout(() => {
273
+ if (entry.retired) return;
274
+ entry.retired = true;
275
+ entry.timedOut = false;
276
+ for (const pending of entry.pending.values()) {
277
+ if (pending.timer) clearTimeout(pending.timer);
278
+ pending.reject(Object.assign(new Error("spine: shadow worker recovery expired"), { code: "ESHADOWWORKER" }));
279
+ }
280
+ entry.pending.clear();
281
+ entry.removeEntry?.();
282
+ entry.worker.terminate()
283
+ .then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
284
+ .catch(() => {});
285
+ }, SHADOW_WORKER_RECOVERY_MS);
286
+ entry.recoveryTimer.unref?.();
287
+ }
152
288
  reject(error);
153
289
  }, SHADOW_WORKER_TIMEOUT_MS);
154
290
  timer.unref?.();
@@ -180,7 +316,9 @@ function failShadowWorker(entry, error) {
180
316
  for (const [key, value] of shadowWorkers) {
181
317
  if (value === entry) shadowWorkers.delete(key);
182
318
  }
183
- entry.worker.terminate().catch(() => {});
319
+ entry.worker.terminate()
320
+ .then(() => recoverTimedOutShadowWorker(entry.root, entry.ownerToken))
321
+ .catch(() => {});
184
322
  }
185
323
 
186
324
  function recoveryRetryable(record, dir, toolCallId) {
@@ -258,6 +396,31 @@ function latestCompletedTurnEnd(events) {
258
396
  return found;
259
397
  }
260
398
 
399
+ function latestTurnStart(events) {
400
+ let found = null;
401
+ for (const event of events || []) {
402
+ if (event?.type === "turn/start") found = event;
403
+ }
404
+ return found;
405
+ }
406
+
407
+ function turnStartForBoundary(events, boundary) {
408
+ const list = events || [];
409
+ const boundaryTurn = boundary?.data?.turn;
410
+ const boundaryIndex = boundary?.seq == null
411
+ ? -1
412
+ : list.findIndex((event) => event?.seq === boundary.seq);
413
+ let found = null;
414
+ for (let index = 0; index < list.length; index += 1) {
415
+ if (boundaryIndex >= 0 && index >= boundaryIndex) break;
416
+ const event = list[index];
417
+ if (event?.type !== "turn/start") continue;
418
+ if (boundaryTurn !== undefined && event?.data?.turn !== boundaryTurn) continue;
419
+ found = event;
420
+ }
421
+ return found;
422
+ }
423
+
261
424
  function maintenanceOperationSignal(agentSignal, timeoutSignal) {
262
425
  const controller = new AbortController();
263
426
  const forwardAgent = () => {
@@ -282,10 +445,16 @@ function maintenanceOperationSignal(agentSignal, timeoutSignal) {
282
445
  return controller.signal;
283
446
  }
284
447
 
285
- function spineCheckpointSource(compactionId) {
448
+ function spineCheckpointSource(compactionId, rawPaths = []) {
286
449
  // 不用 compact-checkpoint。官方压缩会把那种节点当成上一版摘要再摘一次。
287
450
  // Do not use compact-checkpoint. Official compaction treats that kind as a prior summary and shrinks it again.
288
- return Object.freeze({ kind: SPINE_SOURCE_KIND, compactionId });
451
+ const rawNames = [...new Set((rawPaths || []).map((path) => basename(String(path || "")))
452
+ .filter((name) => name && name !== "." && name !== ".."))];
453
+ return Object.freeze({
454
+ kind: SPINE_SOURCE_KIND,
455
+ compactionId,
456
+ ...(rawNames.length ? { rawNames } : {}),
457
+ });
289
458
  }
290
459
 
291
460
  function eventRole(session, seq) {
@@ -437,7 +606,7 @@ export { saveShadowImpl as saveShadow };
437
606
  // Pick one span from the tail, as in 1.0.6. Do not cross a genuine user message.
438
607
  // Tool pairs stay balanced. The newest settings.keepRounds finished rounds stay verbatim.
439
608
  // Under settings.chunkMin, return null.
440
- function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}) {
609
+ export function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}) {
441
610
  const settings = context.settings ?? readSettings();
442
611
  const decision = jobCutDecision(context.jobs || []);
443
612
  if (!decision.cut) return null;
@@ -460,7 +629,6 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
460
629
  }
461
630
  if (floorCard >= 0 && end <= floorCard) return null;
462
631
  while (end >= first && !cutOk(toolPairingBalancedAfter, session, nodes[end])) end -= 1;
463
- let keptTokens = 0;
464
632
  const visible = [];
465
633
  for (let index = first; index <= end; index += 1) {
466
634
  const event = session.eventAt(nodes[index]);
@@ -569,12 +737,8 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
569
737
  drain: context.drain === true,
570
738
  urgentTokens: URGENT_TOKENS,
571
739
  };
572
- let usedLongCut = false;
573
- let picked = null;
574
740
  let longPicked = null;
575
- const fallbackWithoutLongRead = () => context.disableLongRead
576
- ? null
577
- : selectNewestChunk(session, measurement, key, { ...context, disableLongRead: true });
741
+ const forceLongRead = context.forceLongRead === true;
578
742
  if (longSpan) {
579
743
  const candidate = cutLongReadRound(items, longSpan.start, longSpan.end, cutOptions);
580
744
  if (candidate && candidate.start >= longSpan.start && candidate.end <= longSpan.end) {
@@ -585,107 +749,122 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
585
749
  if (end >= first && !isCheckpoint(session, nodes[end])) {
586
750
  ordinaryPicked = selectCutIndexes(items, cutOptions);
587
751
  }
588
- if (longPicked && ordinaryPicked) {
752
+ const candidates = [];
753
+ const addCandidate = (candidate, usedLongCut) => {
754
+ if (!candidate || candidates.some((item) => item.candidate === candidate)) return;
755
+ candidates.push({ candidate, usedLongCut });
756
+ };
757
+ if (forceLongRead) {
758
+ addCandidate(longPicked, true);
759
+ } else if (longPicked && ordinaryPicked) {
589
760
  const longTokens = longPicked.tokens || 0;
590
761
  const ordinaryTokens = ordinaryPicked.tokens || 0;
591
762
  if (ordinaryTokens >= longTokens) {
592
- picked = ordinaryPicked;
763
+ addCandidate(ordinaryPicked, false);
764
+ addCandidate(longPicked, true);
593
765
  } else {
594
- picked = longPicked;
595
- usedLongCut = true;
596
- }
597
- } else if (ordinaryPicked) {
598
- picked = ordinaryPicked;
599
- } else if (longPicked) {
600
- picked = longPicked;
601
- usedLongCut = true;
602
- }
603
- if (!picked) return null;
604
- if (picked.pointerOnly) {
605
- const result = session.eventAt(nodes[picked.end]);
606
- const id = result?.data?.message?.toolCallId;
607
- let pairStart = -1;
608
- if (id) {
609
- for (let index = picked.end - 1; index >= 0; index -= 1) {
610
- const blocks = session.eventAt(nodes[index])?.data?.message?.content || [];
611
- if (blocks.some((block) => block?.type === "tool-call" && block.id === id)) {
612
- pairStart = index;
613
- break;
766
+ addCandidate(longPicked, true);
767
+ addCandidate(ordinaryPicked, false);
768
+ }
769
+ } else {
770
+ addCandidate(ordinaryPicked, false);
771
+ addCandidate(longPicked, true);
772
+ }
773
+ if (!candidates.length) return null;
774
+
775
+ const evaluateCandidate = ({ candidate, usedLongCut }) => {
776
+ const picked = { ...candidate };
777
+ if (picked.pointerOnly) {
778
+ const result = session.eventAt(nodes[picked.end]);
779
+ const id = result?.data?.message?.toolCallId;
780
+ let pairStart = -1;
781
+ if (id) {
782
+ for (let index = picked.end - 1; index >= 0; index -= 1) {
783
+ const blocks = session.eventAt(nodes[index])?.data?.message?.content || [];
784
+ if (blocks.some((block) => block?.type === "tool-call" && block.id === id)) {
785
+ pairStart = index;
786
+ break;
787
+ }
614
788
  }
615
789
  }
616
- }
617
- if (pairStart < 0) return usedLongCut ? fallbackWithoutLongRead() : null;
618
- if (usedLongCut && pairStart < longSpan.start) return fallbackWithoutLongRead();
619
- if (!pointerSpanAllowed(items, pairStart, picked.end, context.engine || "cloud")) return usedLongCut ? fallbackWithoutLongRead() : null;
620
- if (!cutOk(toolPairingBalancedBefore, session, nodes[pairStart])) return usedLongCut ? fallbackWithoutLongRead() : null;
621
- picked.start = pairStart;
622
- }
623
- if (usedLongCut && (picked.start < longSpan.start || picked.end > longSpan.end)) return fallbackWithoutLongRead();
624
-
625
- // 1.0.6 selected the newest legal end, then grew the cut left until the
626
- // 32K rail, a user/checkpoint, an unbalanced tool pair, or an incomplete
627
- // card stopped it. Returning the first >= CHUNK_MIN phase leaves a tiny
628
- // 1.9K tail in a long drain and defeats the low-water goal. Restore that
629
- // core selection rule while keeping the newer source and checkpoint guards.
630
- if (!picked.pointerOnly) {
631
- let expandedStart = picked.start;
632
- let expandedTokens = items.slice(expandedStart, picked.end + 1)
633
- .reduce((sum, item) => sum + (item.tokens || 0), 0);
634
- while (expandedStart > first) {
635
- const previous = expandedStart - 1;
636
- if (isCheckpoint(session, nodes[previous])) break;
637
- if (classifications[previous].isGenuineUserBoundary) break;
638
- if (usedLongCut && previous < longSpan.start) break;
639
- const nextTokens = expandedTokens + (priced[previous].tokens || 0);
640
- if (nextTokens > settings.chunkMax) break;
641
- const trialPieces = spanPieces(previous, picked.end);
642
- const trialCard = buildCard(
643
- trialPieces.map((piece) => piece.text).join("\n"),
644
- liveText(previous, picked.end),
645
- trialPieces,
646
- extras,
647
- );
648
- if (trialCard.ok !== true) break;
649
- expandedStart = previous;
650
- expandedTokens = nextTokens;
651
- }
652
- while (expandedStart <= picked.end &&
653
- !cutOk(toolPairingBalancedBefore, session, nodes[expandedStart])) {
654
- expandedTokens -= priced[expandedStart].tokens || 0;
655
- expandedStart += 1;
656
- }
657
- if (expandedStart > picked.end) return usedLongCut ? fallbackWithoutLongRead() : null;
658
- picked.start = expandedStart;
659
- }
660
- const start = picked.start;
661
- end = picked.end;
662
- const tokens = items.slice(start, end + 1).reduce((sum, item) => sum + item.tokens, 0);
663
- const pieces = spanPieces(start, end);
664
- if (picked.pointerOnly && pieces.some((piece) => piece.role === "tool" && isToolFailure(piece.text, piece.isError))) {
665
- return usedLongCut ? fallbackWithoutLongRead() : null;
666
- }
667
- let card = picked.pointerOnly
668
- ? { ok: true, text: pointerOnlyText(pieces), hardLines: [], missing: [], needsBackup: false, rawPaths: [] }
669
- : buildCard(pieces.map((piece) => piece.text).join("\n"), liveText(start, end), pieces, extras);
670
- if (card.ok !== true) return usedLongCut ? fallbackWithoutLongRead() : null;
671
- card = attachBackupHint(card, freshShadowFile("cut", key));
672
- if (!card.text.includes("不是备份文件路径")) card = { ...card, text: `${card.text}\n序号是本会话日志里的事件号,不是备份文件路径。` };
673
- if (!cutOk(toolPairingBalancedAfter, session, nodes[end])) return null;
674
- let after = 0;
675
- for (let index = end + 1; index < priced.length; index += 1) after += priced[index].tokens;
676
- // `keptTokens` must describe retained rounds to the right of the actual
677
- // cut. A long-read cut can be newer than the ordinary rounds selected above;
678
- // counting those older rounds made `tailBeyondKept` negative and disabled
679
- // the tail guard.
680
- for (const round of rounds) {
681
- const roundStart = visible[round.start]?.index;
682
- const roundEnd = visible[round.end]?.index;
683
- if (!Number.isInteger(roundStart) || !Number.isInteger(roundEnd) || roundStart <= end) continue;
684
- for (let index = roundStart; index <= roundEnd; index += 1) keptTokens += priced[index].tokens;
685
- }
686
- let prefix = 0;
687
- for (let index = 0; index < start; index += 1) prefix += priced[index].tokens;
688
- return { start: nodes[start], end: nodes[end], tokens, after, keptTokens, card, prefix };
790
+ if (pairStart < 0) return null;
791
+ if (usedLongCut && pairStart < longSpan.start) return null;
792
+ if (!pointerSpanAllowed(items, pairStart, picked.end, context.engine || "cloud")) return null;
793
+ if (!cutOk(toolPairingBalancedBefore, session, nodes[pairStart])) return null;
794
+ picked.start = pairStart;
795
+ }
796
+ if (usedLongCut && (picked.start < longSpan.start || picked.end > longSpan.end)) return null;
797
+
798
+ // 1.0.6 selected the newest legal end, then grew the cut left until the
799
+ // 32K rail, a user/checkpoint, an unbalanced tool pair, or an incomplete
800
+ // card stopped it. Returning the first >= CHUNK_MIN phase leaves a tiny
801
+ // 1.9K tail in a long drain and defeats the low-water goal. Restore that
802
+ // core selection rule while keeping the newer source and checkpoint guards.
803
+ if (!picked.pointerOnly) {
804
+ let expandedStart = picked.start;
805
+ let expandedTokens = items.slice(expandedStart, picked.end + 1)
806
+ .reduce((sum, item) => sum + (item.tokens || 0), 0);
807
+ while (expandedStart > first) {
808
+ const previous = expandedStart - 1;
809
+ if (isCheckpoint(session, nodes[previous])) break;
810
+ if (classifications[previous].isGenuineUserBoundary) break;
811
+ if (usedLongCut && previous < longSpan.start) break;
812
+ const nextTokens = expandedTokens + (priced[previous].tokens || 0);
813
+ if (nextTokens > settings.chunkMax) break;
814
+ const trialPieces = spanPieces(previous, picked.end);
815
+ const trialCard = buildCard(
816
+ trialPieces.map((piece) => piece.text).join("\n"),
817
+ liveText(previous, picked.end),
818
+ trialPieces,
819
+ extras,
820
+ );
821
+ if (trialCard.ok !== true) break;
822
+ expandedStart = previous;
823
+ expandedTokens = nextTokens;
824
+ }
825
+ while (expandedStart <= picked.end &&
826
+ !cutOk(toolPairingBalancedBefore, session, nodes[expandedStart])) {
827
+ expandedTokens -= priced[expandedStart].tokens || 0;
828
+ expandedStart += 1;
829
+ }
830
+ if (expandedStart > picked.end) return null;
831
+ picked.start = expandedStart;
832
+ }
833
+ const start = picked.start;
834
+ const candidateEnd = picked.end;
835
+ const tokens = items.slice(start, candidateEnd + 1).reduce((sum, item) => sum + item.tokens, 0);
836
+ const pieces = spanPieces(start, candidateEnd);
837
+ if (picked.pointerOnly && pieces.some((piece) => piece.role === "tool" && isToolFailure(piece.text, piece.isError))) return null;
838
+ let card = picked.pointerOnly
839
+ ? { ok: true, text: pointerOnlyText(pieces), hardLines: [], missing: [], needsBackup: false, rawPaths: [] }
840
+ : buildCard(pieces.map((piece) => piece.text).join("\n"), liveText(start, candidateEnd), pieces, extras);
841
+ if (card.ok !== true) return null;
842
+ if (!cutOk(toolPairingBalancedAfter, session, nodes[candidateEnd])) return null;
843
+ let after = 0;
844
+ for (let index = candidateEnd + 1; index < priced.length; index += 1) after += priced[index].tokens;
845
+ // `keptTokens` must describe retained rounds to the right of the actual
846
+ // cut. A long-read cut can be newer than the ordinary rounds selected above;
847
+ // counting those older rounds made `tailBeyondKept` negative and disabled
848
+ // the tail guard.
849
+ let candidateKeptTokens = 0;
850
+ for (const round of rounds) {
851
+ const roundStart = visible[round.start]?.index;
852
+ const roundEnd = visible[round.end]?.index;
853
+ if (!Number.isInteger(roundStart) || !Number.isInteger(roundEnd) || roundStart <= candidateEnd) continue;
854
+ for (let index = roundStart; index <= roundEnd; index += 1) candidateKeptTokens += priced[index].tokens;
855
+ }
856
+ let prefix = 0;
857
+ for (let index = 0; index < start; index += 1) prefix += priced[index].tokens;
858
+ if (!card.text.includes("不是备份文件路径")) card = { ...card, text: `${card.text}\n序号是本会话日志里的事件号,不是备份文件路径。` };
859
+ card = attachBackupHint(card, freshShadowFile("cut", key));
860
+ return { start: nodes[start], end: nodes[candidateEnd], tokens, after, keptTokens: candidateKeptTokens, card, prefix };
861
+ };
862
+
863
+ for (const candidate of candidates) {
864
+ const result = evaluateCandidate(candidate);
865
+ if (result) return result;
866
+ }
867
+ return null;
689
868
  }
690
869
 
691
870
  export const BIG_GATE = DEFAULTS.bigGate;
@@ -712,11 +891,21 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
712
891
  retryableCaptureSeeded = new Set();
713
892
  captureRecoveryHolds = new Map();
714
893
  pruneGuarded = false;
894
+ catalogCache = [];
895
+ catalogPromise = null;
715
896
 
716
897
  constructor(ctx, config, resolvedConfig) {
717
898
  if (process.env.SPINE_ENGINE_FAIL === "construct") throw new Error("spine: constructor refused");
718
899
  super(ctx, resolvedConfig ?? engineConfig(config));
719
900
  this.persistCapture = true;
901
+ this.catalogPromise = loadPiAiCatalog().then((catalog) => {
902
+ this.catalogCache = catalog;
903
+ if (!catalog.length) this.catalogPromise = null;
904
+ return catalog;
905
+ }).catch(() => {
906
+ this.catalogPromise = null;
907
+ return [];
908
+ });
720
909
  if (process.env.SPINE_ENGINE_FAIL === "after-super") throw new Error("spine: after super");
721
910
  this.liveConfig = config;
722
911
  try {
@@ -790,7 +979,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
790
979
  ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
791
980
  await this.waitForMaintenance(agent, signal);
792
981
  return typeof next === "function" ? next() : undefined;
793
- });
982
+ }, { prepend: true });
794
983
  ctx.on("agent/turn-stopping", async ({ agent, signal }) => {
795
984
  await this.runTurnStoppingMaintenance(agent, signal);
796
985
  });
@@ -806,6 +995,53 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
806
995
  return peers.length > 0;
807
996
  }
808
997
 
998
+ recordDecision(state, record = {}) {
999
+ const key = state?.key || DEFAULT_KEY;
1000
+ const prefix = `${key}\0`;
1001
+ const session = state?.liveAgent?.session;
1002
+ this.reconcileCardRawPaths(state, session);
1003
+ const protectPaths = [];
1004
+ if (state?.lastCardPath) protectPaths.push(state.lastCardPath);
1005
+ for (const rawPath of state?.cardRawPaths || []) {
1006
+ if (!rawPath) continue;
1007
+ protectPaths.push(rawPath, `${rawPath}.meta.json`);
1008
+ }
1009
+ const liveIds = new Set();
1010
+ for (const seq of session?.surface?.nodes || []) {
1011
+ const event = session.eventAt?.(seq);
1012
+ const id = event?.type === "tool/result" ? event.data?.message?.toolCallId : "";
1013
+ if (id) liveIds.add(id);
1014
+ }
1015
+ for (const [rawKey, raw] of this.rawSeen || []) {
1016
+ if (!rawKey.startsWith(prefix) || !raw?.path || !liveIds.has(rawKey.slice(prefix.length))) continue;
1017
+ protectPaths.push(raw.path, `${raw.path}.meta.json`);
1018
+ }
1019
+ appendDecision(shadowDirectory(), { sid: key, ...record }, { protectPaths });
1020
+ }
1021
+
1022
+ reconcileCardRawPaths(state, session) {
1023
+ if (!state || !session?.surface?.nodes) return;
1024
+ const root = sessionDir(shadowDirectory(), state.key || DEFAULT_KEY);
1025
+ const paths = [];
1026
+ let sawSpineCard = false;
1027
+ for (const seq of session.surface.nodes) {
1028
+ const event = session.eventAt?.(seq);
1029
+ const source = event?.type === "user/message" ? event.data?.source : null;
1030
+ if (source?.kind !== SPINE_SOURCE_KIND) continue;
1031
+ sawSpineCard = true;
1032
+ for (const name of Array.isArray(source.rawNames) ? source.rawNames : []) {
1033
+ if (typeof name !== "string" || !name || name !== basename(name)) continue;
1034
+ paths.push(join(root, name));
1035
+ }
1036
+ }
1037
+ if (sawSpineCard) {
1038
+ state.cardRawPaths = [...new Set(paths)];
1039
+ state.cardRawPathsStructured = true;
1040
+ } else if (state.cardRawPathsStructured) {
1041
+ state.cardRawPaths = [];
1042
+ }
1043
+ }
1044
+
809
1045
  ownedSignal(signal) {
810
1046
  const controller = new AbortController();
811
1047
  const dispose = this.ctx.on("internal/status", () => {
@@ -838,10 +1074,19 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
838
1074
  turnBase: null,
839
1075
  maxTurnGrowth: 0,
840
1076
  maintenanceJob: null,
1077
+ retryWaitingJob: null,
1078
+ maintenanceAbort: null,
1079
+ maintenanceOwner: null,
841
1080
  turnEndScheduled: false,
842
1081
  turnEndPending: false,
843
1082
  turnEndSeq: -1,
844
1083
  lastMaintenanceTurnEndSeq: -1,
1084
+ lastStoppingTurnEndSeq: -1,
1085
+ lastStoppingTurnStartSeq: -1,
1086
+ rawCutRetryAttempts: 0,
1087
+ lastCardPath: "",
1088
+ cardRawPaths: [],
1089
+ cardRawPathsStructured: false,
845
1090
  };
846
1091
  this.sessionState.set(key, state);
847
1092
  if (this.sessionState.size > MAX_TRACKED_SESSIONS) {
@@ -867,16 +1112,37 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
867
1112
  return;
868
1113
  }
869
1114
  if (state.turnEndSeq <= state.lastMaintenanceTurnEndSeq) return;
1115
+ const boundary = state.turnEndEvent || latestCompletedTurnEnd(events);
1116
+ const boundaryStartSeq = turnStartForBoundary(events, boundary)?.seq;
1117
+ const activeStartSeq = boundaryStartSeq ?? latestTurnStart(events)?.seq;
1118
+ const sameStoppingTurn = Number.isInteger(state.lastStoppingTurnStartSeq) &&
1119
+ state.lastStoppingTurnStartSeq >= 0 && Number.isInteger(activeStartSeq)
1120
+ ? state.lastStoppingTurnStartSeq === activeStartSeq
1121
+ : state.lastStoppingTurnEndSeq >= 0 && state.turnEndSeq === state.lastStoppingTurnEndSeq;
1122
+ if (state.lastStoppingTurnStartSeq >= 0 && Number.isInteger(activeStartSeq) && !sameStoppingTurn) {
1123
+ state.lastStoppingTurnStartSeq = -1;
1124
+ state.lastStoppingTurnEndSeq = -1;
1125
+ }
1126
+ if (sameStoppingTurn) {
1127
+ state.lastMaintenanceTurnEndSeq = state.turnEndSeq;
1128
+ state.lastStoppingTurnStartSeq = -1;
1129
+ state.lastStoppingTurnEndSeq = -1;
1130
+ return;
1131
+ }
870
1132
  if (state.turnEndSeq > state.lastMaintenanceTurnEndSeq) {
871
1133
  state.lastMaintenanceTurnEndSeq = state.turnEndSeq;
872
1134
  }
873
1135
  state.warming = true;
874
1136
  let job;
875
- job = this.finishTurn(agent, events, { deferCapture: true })
1137
+ job = (async () => {
1138
+ await null;
1139
+ return this.finishTurn(agent, events, { deferCapture: true });
1140
+ })()
876
1141
  .catch((error) => noteShadowWarning(this.ctx?.logger, error))
877
1142
  .finally(() => {
878
1143
  if (!state.pendingMaintenance) state.warming = false;
879
1144
  if (state.maintenanceJob === job) state.maintenanceJob = null;
1145
+ if (state.maintenanceAbort) state.maintenanceAbort = null;
880
1146
  this.pendingCuts.delete(job);
881
1147
  if (state.turnEndPending && !state.warming) {
882
1148
  state.turnEndPending = false;
@@ -895,25 +1161,72 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
895
1161
  return;
896
1162
  }
897
1163
  state.warming = true;
898
- try {
899
- const settings = readSettings(this.liveConfig);
900
- const events = agent.session.snapshotEvents();
901
- let catchup = { finished: true, progressed: false, retryRequested: false };
902
- if (events.length > CAPTURE_EVENT_BATCH) {
903
- catchup = this.scheduleCaptureCatchup(agent, events, settings, { freezeSnapshot: true });
904
- } else {
905
- await this.flushPendingCaptures();
906
- this.captureNew(agent.session, events, settings);
907
- }
908
- if (catchup?.promise && !catchup.finished) await catchup.promise;
909
- await this.flushPendingCaptures();
910
- await this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true });
911
- } finally {
912
- state.warming = false;
913
- if (state.turnEndPending) {
914
- state.turnEndPending = false;
915
- this.scheduleTurnEndMaintenance(agent, state.turnEndSeq);
1164
+ const owner = {};
1165
+ const maintenanceAbort = new AbortController();
1166
+ state.maintenanceOwner = owner;
1167
+ state.maintenanceAbort = maintenanceAbort;
1168
+ const forwardAbort = () => {
1169
+ if (!maintenanceAbort.signal.aborted) maintenanceAbort.abort(signal?.reason);
1170
+ };
1171
+ signal?.addEventListener("abort", forwardAbort, { once: true });
1172
+ if (signal?.aborted) forwardAbort();
1173
+ let job;
1174
+ job = (async () => {
1175
+ await null;
1176
+ try {
1177
+ const settings = readSettings(this.liveConfig);
1178
+ const events = agent.session.snapshotEvents();
1179
+ const stoppingEnd = latestCompletedTurnEnd(events);
1180
+ const stoppingSeq = stoppingEnd?.seq;
1181
+ const stoppingStartSeq = (turnStartForBoundary(events, stoppingEnd) || latestTurnStart(events))?.seq;
1182
+ if (Number.isInteger(stoppingSeq)) {
1183
+ state.turnEndSeq = Number.isInteger(state.turnEndSeq) ? Math.max(state.turnEndSeq, stoppingSeq) : stoppingSeq;
1184
+ state.turnEndEvent = stoppingEnd;
1185
+ }
1186
+ let catchup = { finished: true, progressed: false, retryRequested: false };
1187
+ if (events.length > CAPTURE_EVENT_BATCH) {
1188
+ catchup = this.scheduleCaptureCatchup(agent, events, settings, { freezeSnapshot: true });
1189
+ } else {
1190
+ await this.flushPendingCaptures(agent.session);
1191
+ this.captureNew(agent.session, events, settings);
1192
+ }
1193
+ if (catchup?.promise && !catchup.finished) await catchup.promise;
1194
+ if (maintenanceAbort.signal.aborted) return false;
1195
+ await this.flushPendingCaptures(agent.session);
1196
+ if (maintenanceAbort.signal.aborted) return false;
1197
+ const completed = await this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true });
1198
+ if (completed === true && (stoppingSeq !== undefined || stoppingStartSeq !== undefined)) {
1199
+ state.lastStoppingTurnEndSeq = stoppingSeq ?? -1;
1200
+ state.lastStoppingTurnStartSeq = stoppingStartSeq ?? -1;
1201
+ }
1202
+ } finally {
1203
+ signal?.removeEventListener("abort", forwardAbort);
1204
+ this.pendingCuts.delete(job);
1205
+ if (state.maintenanceOwner === owner) {
1206
+ state.warming = false;
1207
+ state.pendingMaintenance = false;
1208
+ state.maintenanceAbort = null;
1209
+ state.maintenanceOwner = null;
1210
+ if (state.maintenanceJob === job) state.maintenanceJob = null;
1211
+ if (state.turnEndPending) {
1212
+ state.turnEndPending = false;
1213
+ this.scheduleTurnEndMaintenance(agent, state.turnEndSeq);
1214
+ }
1215
+ }
916
1216
  }
1217
+ })();
1218
+ state.maintenanceJob = job;
1219
+ this.pendingCuts.add(job);
1220
+ if (!signal) await job;
1221
+ else {
1222
+ let abort;
1223
+ const aborted = new Promise((resolve) => {
1224
+ abort = () => resolve();
1225
+ if (signal.aborted) resolve();
1226
+ else signal.addEventListener("abort", abort, { once: true });
1227
+ });
1228
+ try { await Promise.race([job, aborted]); }
1229
+ finally { signal.removeEventListener("abort", abort); }
917
1230
  }
918
1231
  }
919
1232
 
@@ -952,24 +1265,58 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
952
1265
 
953
1266
  async waitForMaintenance(agent, signal) {
954
1267
  const state = this.stateFor(agent);
955
- while (!signal?.aborted) {
956
- const jobs = [];
957
- if (state.maintenanceJob) jobs.push(state.maintenanceJob);
958
- const catchup = this.pendingCatchups.get(state.key);
959
- if (catchup?.promise) jobs.push(catchup.promise);
960
- if (!jobs.length) break;
961
- const settled = Promise.allSettled(jobs);
962
- if (!signal) {
963
- await settled;
964
- continue;
1268
+ const timeoutMs = Number.isFinite(this.prestepWaitTimeoutMs)
1269
+ ? Math.max(1, this.prestepWaitTimeoutMs)
1270
+ : PRESTEP_WAIT_TIMEOUT_MS;
1271
+ const timeoutController = new AbortController();
1272
+ const timeoutTimer = setTimeout(() => timeoutController.abort({ kind: "prestep-timeout" }), timeoutMs);
1273
+ try {
1274
+ const waitSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
1275
+ while (!waitSignal.aborted) {
1276
+ const jobs = [];
1277
+ if (state.maintenanceJob) jobs.push(state.maintenanceJob);
1278
+ const catchup = this.pendingCatchups.get(state.key);
1279
+ if (catchup?.promise) jobs.push(catchup.promise);
1280
+ if (!jobs.length) {
1281
+ if (!(state.pendingMaintenance || state.warming || state.retryScheduled)) break;
1282
+ await new Promise((resolve) => scheduleImmediate(resolve));
1283
+ if (timeoutController.signal.aborted && !signal?.aborted) {
1284
+ state.maintenanceAbort?.abort({ kind: "prestep-timeout" });
1285
+ if (Number.isInteger(state.turnEndSeq)) {
1286
+ state.lastMaintenanceTurnEndSeq = state.turnEndSeq - 1;
1287
+ state.turnEndPending = true;
1288
+ this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
1289
+ }
1290
+ this.recordDecision(state, { phase: "prestep", result: "timeout", timeoutMs });
1291
+ this.ctx.logger?.warn?.(`spine: maintenance wait exceeded ${timeoutMs}ms; letting provider request continue`);
1292
+ return;
1293
+ }
1294
+ continue;
1295
+ }
1296
+ const settled = Promise.allSettled(jobs);
1297
+ let abort;
1298
+ const aborted = new Promise((resolve) => {
1299
+ abort = () => resolve();
1300
+ waitSignal.addEventListener("abort", abort, { once: true });
1301
+ });
1302
+ await Promise.race([settled, aborted]);
1303
+ waitSignal.removeEventListener("abort", abort);
1304
+ if (!waitSignal.aborted) await new Promise((resolve) => scheduleImmediate(resolve));
1305
+ if (timeoutController.signal.aborted && !signal?.aborted) {
1306
+ state.maintenanceAbort?.abort({ kind: "prestep-timeout" });
1307
+ if (Number.isInteger(state.turnEndSeq)) {
1308
+ state.lastMaintenanceTurnEndSeq = state.turnEndSeq - 1;
1309
+ state.turnEndPending = true;
1310
+ this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
1311
+ }
1312
+ this.recordDecision(state, { phase: "prestep", result: "timeout", timeoutMs });
1313
+ this.ctx.logger?.warn?.(`spine: maintenance wait exceeded ${timeoutMs}ms; letting provider request continue`);
1314
+ return;
1315
+ }
1316
+ if (signal?.aborted) return;
965
1317
  }
966
- let abort;
967
- const aborted = new Promise((resolve) => {
968
- abort = () => resolve();
969
- signal.addEventListener("abort", abort, { once: true });
970
- });
971
- await Promise.race([settled, aborted]);
972
- signal.removeEventListener("abort", abort);
1318
+ } finally {
1319
+ clearTimeout(timeoutTimer);
973
1320
  }
974
1321
  }
975
1322
 
@@ -997,6 +1344,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
997
1344
  task.events = events;
998
1345
  task.settings = settings;
999
1346
  task.freezeSnapshot ||= options.freezeSnapshot === true;
1347
+ task.maintenanceRequested ||= options.maintenanceRequested === true;
1000
1348
  return task;
1001
1349
  }
1002
1350
  let resolve;
@@ -1094,7 +1442,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1094
1442
  const previousMax = this.captureRetryStats?.get(task.key) || 0;
1095
1443
  if (task.captureRetryAttempts > previousMax) this.captureRetryStats.set(task.key, task.captureRetryAttempts);
1096
1444
  if (task.captureRetryAttempts >= CAPTURE_RETRY_LIMIT) {
1097
- this.finishCaptureCatchup(task);
1445
+ task.phase = "visible";
1446
+ task.recoverIndex = 0;
1447
+ task.visibleIds = [...new Set(this.surfaceToolIds(task.session))];
1448
+ this.queueCaptureCatchup(task);
1098
1449
  return;
1099
1450
  }
1100
1451
  this.queueCaptureRetry(task);
@@ -1102,7 +1453,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1102
1453
  }
1103
1454
  if (result.blocked) {
1104
1455
  task.captureBlocked = true;
1105
- this.finishCaptureCatchup(task);
1456
+ task.retryRequested = true;
1457
+ task.phase = "visible";
1458
+ task.recoverIndex = 0;
1459
+ task.visibleIds = [...new Set(this.surfaceToolIds(task.session))];
1460
+ this.queueCaptureCatchup(task);
1106
1461
  return;
1107
1462
  }
1108
1463
  if (result.progressed) task.captureRetryAttempts = 0;
@@ -1136,41 +1491,109 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1136
1491
  this.pendingCatchups.delete(task.key);
1137
1492
  this.pendingCatchupJobs.delete(task.promise);
1138
1493
  task.resolve();
1139
- if (task.failed || task.captureBlocked) {
1494
+ if (task.failed) {
1140
1495
  const state = this.stateFor(task.agent);
1141
- state.pendingMaintenance = false;
1142
- state.warming = false;
1496
+ if (state.maintenanceOwner) {
1497
+ // Keep a stopping owner's lifecycle barrier until its finally block;
1498
+ // otherwise a failed catch-up can overlap the next maintenance job.
1499
+ state.pendingMaintenance = true;
1500
+ state.warming = true;
1501
+ state.turnEndPending = true;
1502
+ } else {
1503
+ state.pendingMaintenance = false;
1504
+ state.warming = false;
1505
+ }
1143
1506
  return;
1144
1507
  }
1145
- if (!this.standDown?.() && !task.captureBlocked &&
1146
- (task.retryRequested || task.maintenanceRequested)) {
1147
- this.scheduleMaintenanceRetry(task.agent);
1508
+ const state = this.stateFor(task.agent);
1509
+ if (!this.standDown?.() &&
1510
+ (task.captureBlocked || task.retryRequested || task.maintenanceRequested)) {
1511
+ // Keep the lifecycle visibly warming until the scheduled retry has
1512
+ // completed. Real idle hooks use this state as their await barrier.
1513
+ state.pendingMaintenance = true;
1514
+ state.warming = true;
1515
+ if (state.maintenanceOwner) {
1516
+ // A turn-stopping owner is already going to finish this catch-up and
1517
+ // run maintenance. Queue the boundary behind that owner instead of
1518
+ // replacing its abort controller with a concurrent retry job.
1519
+ state.turnEndPending = true;
1520
+ } else {
1521
+ this.scheduleMaintenanceRetry(task.agent);
1522
+ }
1523
+ } else if (this.standDown?.() || !latestTurnCompleted(task.agent.session.snapshotEvents?.() || [])) {
1524
+ // A catch-up can finish after the next turn has already started. Do not
1525
+ // leave the session permanently warming; the next persisted turn/end
1526
+ // must be allowed to schedule a fresh maintenance pass.
1527
+ if (state.maintenanceOwner) {
1528
+ state.turnEndPending = true;
1529
+ } else {
1530
+ state.pendingMaintenance = false;
1531
+ state.warming = false;
1532
+ }
1533
+ } else if (!state.maintenanceOwner) {
1534
+ // A reused catch-up can finish without a retry request after a newer
1535
+ // maintenance caller has already dropped its barrier. Do not retain a
1536
+ // stale warming flag in that case; an active turn-stopping owner clears
1537
+ // its own state in its finally block.
1538
+ state.pendingMaintenance = false;
1539
+ state.warming = false;
1148
1540
  }
1149
1541
  }
1150
1542
 
1151
1543
  scheduleMaintenanceRetry(agent) {
1152
1544
  if (this.standDown?.()) return;
1153
1545
  const state = this.stateFor(agent);
1546
+ if (state.maintenanceOwner) {
1547
+ state.turnEndPending = true;
1548
+ return;
1549
+ }
1154
1550
  if (state.retryScheduled) return;
1155
1551
  state.retryScheduled = true;
1156
1552
  scheduleImmediate(() => {
1157
1553
  state.retryScheduled = false;
1158
- if (this.standDown?.()) return;
1159
- if (state.warming && !state.pendingMaintenance) {
1160
- scheduleImmediate(() => this.scheduleMaintenanceRetry(agent));
1554
+ if (this.standDown?.()) {
1555
+ state.pendingMaintenance = false;
1556
+ state.warming = false;
1557
+ return;
1558
+ }
1559
+ if (state.maintenanceJob) {
1560
+ const waitingJob = state.maintenanceJob;
1561
+ if (state.retryWaitingJob === waitingJob) return;
1562
+ state.retryWaitingJob = waitingJob;
1563
+ const retryAfterJob = () => {
1564
+ if (state.retryWaitingJob !== waitingJob) return;
1565
+ state.retryWaitingJob = null;
1566
+ if (!state.maintenanceJob && state.pendingMaintenance) {
1567
+ this.scheduleMaintenanceRetry(agent);
1568
+ }
1569
+ };
1570
+ Promise.resolve(waitingJob).then(retryAfterJob, retryAfterJob);
1161
1571
  return;
1162
1572
  }
1573
+ if (state.warming && !state.pendingMaintenance) state.warming = false;
1163
1574
  const events = agent.session.snapshotEvents();
1164
1575
  const done = latestTurnCompleted(events);
1165
- if (!done) return;
1576
+ if (!done) {
1577
+ state.pendingMaintenance = false;
1578
+ state.warming = false;
1579
+ return;
1580
+ }
1166
1581
  state.warming = true;
1582
+ const retryAbort = new AbortController();
1583
+ state.maintenanceAbort = retryAbort;
1167
1584
  const job = this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true })
1168
1585
  .catch((error) => noteShadowWarning(this.ctx?.logger, error))
1169
1586
  .finally(() => {
1587
+ const sameJob = state.maintenanceJob === job && state.maintenanceAbort === retryAbort;
1588
+ this.pendingCuts.delete(job);
1589
+ if (!sameJob) return;
1590
+ const requeueBoundary = state.turnEndPending;
1591
+ state.turnEndPending = false;
1170
1592
  state.pendingMaintenance = false;
1171
1593
  state.warming = false;
1172
- if (state.maintenanceJob === job) state.maintenanceJob = null;
1173
- this.pendingCuts.delete(job);
1594
+ state.maintenanceAbort = null;
1595
+ state.maintenanceJob = null;
1596
+ if (requeueBoundary) this.scheduleTurnEndMaintenance(agent, state.turnEndSeq, state.turnEndEvent);
1174
1597
  });
1175
1598
  state.maintenanceJob = job;
1176
1599
  this.pendingCuts.add(job);
@@ -1181,7 +1604,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1181
1604
  if (this.standDown?.()) return null;
1182
1605
  const settings = readSettings(this.liveConfig);
1183
1606
  const state = this.stateFor(agent);
1184
- const signal = AbortSignal.timeout(30000);
1607
+ if (state.maintenanceAbort?.signal.aborted) return false;
1608
+ if (!state.maintenanceAbort) {
1609
+ state.maintenanceAbort = new AbortController();
1610
+ }
1611
+ const signal = AbortSignal.any([AbortSignal.timeout(30000), state.maintenanceAbort.signal]);
1612
+ let maintenanceCompleted = false;
1185
1613
  const ev = events || agent.session.snapshotEvents();
1186
1614
  const deferCapture = options.deferCapture === true;
1187
1615
  let catchup = { finished: true, progressed: false, retryRequested: false };
@@ -1190,12 +1618,18 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1190
1618
  // the capture surface. Re-run maintenance without rescanning events.
1191
1619
  } else if (deferCapture) {
1192
1620
  state.pendingMaintenance = true;
1193
- catchup = this.scheduleCaptureCatchup(agent, ev, settings, { maintenanceRequested: true });
1621
+ try {
1622
+ catchup = this.scheduleCaptureCatchup(agent, ev, settings, { maintenanceRequested: true });
1623
+ } catch (error) {
1624
+ state.pendingMaintenance = false;
1625
+ state.warming = false;
1626
+ throw error;
1627
+ }
1194
1628
  } else {
1195
1629
  if (ev.length > CAPTURE_EVENT_BATCH) {
1196
1630
  catchup = this.scheduleCaptureCatchup(agent, ev, settings, { freezeSnapshot: true });
1197
1631
  } else {
1198
- await this.flushPendingCaptures();
1632
+ await this.flushPendingCaptures(agent.session);
1199
1633
  this.captureNew(agent.session, ev, settings);
1200
1634
  }
1201
1635
  }
@@ -1210,7 +1644,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1210
1644
  return null;
1211
1645
  }
1212
1646
  }
1213
- await this.flushPendingCaptures();
1647
+ await this.flushPendingCaptures(agent.session);
1214
1648
  const jobs = collectJobs(ev);
1215
1649
  const calls = indexToolCalls(ev);
1216
1650
  try {
@@ -1221,33 +1655,58 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1221
1655
  // started at that point, so let it finish under the bounded timeout;
1222
1656
  // user/host cancellation reasons still abort the operation.
1223
1657
  const op = maintenanceOperationSignal(agentSignal, signal);
1658
+ const markCompleted = () => {
1659
+ if (!op.aborted && !signal.aborted) maintenanceCompleted = true;
1660
+ };
1224
1661
  let measurement = this.ctx.tokenMeter.measure(agent.session);
1225
1662
  const settleTurnBaseline = () => {
1226
1663
  state.turnBase = measurement.totalTokens;
1227
1664
  state.maxTurnGrowth = 0;
1228
1665
  };
1229
1666
  if (measurement.totalTokens < settings.minTokens || measurement.totalTokens >= settings.bigGate) {
1667
+ this.recordDecision(state, {
1668
+ phase: "maintenance-skip",
1669
+ reason: measurement.totalTokens < settings.minTokens ? "below-min-tokens" : "above-big-gate",
1670
+ totalTokens: measurement.totalTokens,
1671
+ });
1230
1672
  settleTurnBaseline();
1673
+ markCompleted();
1231
1674
  return;
1232
1675
  }
1233
1676
  // Restored cards establish a baseline; a live card still skips once,
1234
1677
  // even when maintenance or engine construction is delayed.
1235
- if (skipLiveOfficialCompaction(agent.session)) {
1678
+ if (!op.aborted && skipLiveOfficialCompaction(agent.session)) {
1679
+ this.recordDecision(state, { phase: "maintenance-skip", reason: "official-checkpoint" });
1236
1680
  this.ctx.logger?.info?.("spine cooldown: live official compaction seen, skip this pass");
1237
1681
  settleTurnBaseline();
1682
+ markCompleted();
1238
1683
  return;
1239
1684
  }
1240
1685
  if (inCooldown(agent.session, { windowMs: settings.cooldownMs })) {
1686
+ this.recordDecision(state, { phase: "maintenance-skip", reason: "cooldown" });
1241
1687
  settleTurnBaseline();
1688
+ markCompleted();
1242
1689
  return;
1243
1690
  }
1244
1691
  this.ensurePruneGuard();
1692
+ // The pi-ai catalog is loaded asynchronously so ESM-only providers are
1693
+ // discoverable. Do not classify the first request as local merely
1694
+ // because catalogProviders() was called before the import settled.
1695
+ if (this.catalogPromise) await this.catalogPromise;
1245
1696
  const resolved = this.engineFor(agent);
1246
1697
  if (state.engine !== resolved.engine || state.engineSource !== resolved.source) {
1247
1698
  this.ctx.logger?.info?.(`spine engine=${resolved.engine} source=${resolved.source}`);
1248
1699
  state.engine = resolved.engine;
1249
1700
  state.engineSource = resolved.source;
1250
1701
  }
1702
+ this.recordDecision(state, {
1703
+ phase: "engine",
1704
+ engine: resolved.engine,
1705
+ source: resolved.source,
1706
+ provider: agent?.session?.requestHeader?.()?.config?.provider || "",
1707
+ model: agent?.session?.requestHeader?.()?.config?.model || "",
1708
+ catalogReady: this.catalogCache.length > 0,
1709
+ });
1251
1710
  const cloud = resolved.engine !== "local";
1252
1711
  // 预测下一轮会过 32000 时收尾;没有增长基线时仍由已有 48000 紧急线接管。
1253
1712
  // Drain a projected request over 32000. Without a growth baseline, the existing 48000 urgent line still takes over.
@@ -1258,6 +1717,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1258
1717
  const projected = state.maxTurnGrowth > 0 && last + state.maxTurnGrowth > settings.keepRoundTokens;
1259
1718
  const drain = cloud && (projected || last >= URGENT_TOKENS);
1260
1719
  const drainNotes = [];
1720
+ let maintenanceFailed = false;
1261
1721
  for (let pass = 0; pass < 8; pass += 1) {
1262
1722
  const measured = measurement;
1263
1723
  if (drain && measured.totalTokens <= settings.keepRoundTokens) break;
@@ -1272,8 +1732,15 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1272
1732
  });
1273
1733
  if (chunk === null) {
1274
1734
  if (drain && measured.totalTokens > settings.keepRoundTokens) {
1735
+ this.recordDecision(state, {
1736
+ phase: "cut-skip",
1737
+ reason: "no-legal-span",
1738
+ totalTokens: measured.totalTokens,
1739
+ drain: true,
1740
+ });
1275
1741
  this.ctx.logger?.warn?.(`spine drain stopped at ${measured.totalTokens}; no legal span`);
1276
1742
  } else {
1743
+ this.recordDecision(state, { phase: "cut-skip", reason: "no-legal-span", totalTokens: measured.totalTokens, drain: false });
1277
1744
  this.ctx.logger?.debug?.("spine cut skipped");
1278
1745
  }
1279
1746
  break;
@@ -1287,12 +1754,24 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1287
1754
  state.localOnly = true;
1288
1755
  state.approvedCard = chunk.card;
1289
1756
  const committed = await this.commitSelectedSpan(agent, chunk, op, { drain });
1290
- if (committed === false) break;
1757
+ if (committed === false) {
1758
+ maintenanceFailed = true;
1759
+ break;
1760
+ }
1291
1761
  measurement = this.ctx.tokenMeter.measure(agent.session);
1292
1762
  const after = measurement.totalTokens;
1293
1763
  reduced = after < before;
1294
1764
  const saved = before - after;
1295
1765
  if (saved > 0) {
1766
+ this.recordDecision(state, {
1767
+ phase: "cut",
1768
+ result: "committed",
1769
+ before,
1770
+ after,
1771
+ saved,
1772
+ tokens: chunk.tokens,
1773
+ drain,
1774
+ });
1296
1775
  drainNotes.push({
1297
1776
  kind: "cut",
1298
1777
  saved,
@@ -1307,14 +1786,20 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1307
1786
  this.ctx.logger?.info?.(`spine cut ${Date.now() - started}ms ${before} -> ${after} chunk=${chunk.tokens} saved=${saved}`);
1308
1787
  } catch (error) {
1309
1788
  const message = error instanceof Error ? error.message : String(error);
1310
- if (message.includes("raw backup missing before cut")) {
1789
+ if (message.includes("raw backup missing before cut") && error?.retryable === true) {
1311
1790
  catchup.retryRequested = true;
1312
- if (catchup.finished && catchup.progressed) this.scheduleMaintenanceRetry(agent);
1791
+ if (catchup.finished && state.rawCutRetryAttempts < CAPTURE_RETRY_LIMIT) {
1792
+ state.rawCutRetryAttempts += 1;
1793
+ this.scheduleMaintenanceRetry(agent);
1794
+ }
1313
1795
  }
1796
+ maintenanceFailed = true;
1797
+ this.recordDecision(state, { phase: "cut", result: "failed", reason: message, drain });
1314
1798
  this.ctx.logger?.warn?.(`spine cut failed: ${message}`);
1315
1799
  break;
1316
1800
  }
1317
1801
  if (!reduced) {
1802
+ maintenanceFailed = true;
1318
1803
  this.ctx.logger?.warn?.(`spine cut did not reduce ${before}; leaving the prefix for the gate`);
1319
1804
  break;
1320
1805
  }
@@ -1325,6 +1810,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1325
1810
  state.maxTurnGrowth = 0;
1326
1811
  await this.ctx.sessions?.flush?.(agent.session);
1327
1812
  this.rememberPrefix(agent);
1813
+ if (!maintenanceFailed) {
1814
+ state.rawCutRetryAttempts = 0;
1815
+ markCompleted();
1816
+ }
1328
1817
  });
1329
1818
  } catch (error) {
1330
1819
  const message = error instanceof Error ? error.message : String(error);
@@ -1332,6 +1821,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1332
1821
  } finally {
1333
1822
  state.localOnly = false;
1334
1823
  }
1824
+ return maintenanceCompleted;
1335
1825
  }
1336
1826
 
1337
1827
  async flushPendingCaptures(session = null, ids = null) {
@@ -1415,12 +1905,21 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1415
1905
  this.rawSeen.set(this.rawKey(session, id), raw);
1416
1906
  } catch (error) {
1417
1907
  noteShadowWarning(this.ctx?.logger, error);
1418
- raw = { ...raw, ok: false, reason: "unwritable", toolCallId: id, aclVerified: false };
1908
+ raw = {
1909
+ ...raw,
1910
+ ok: false,
1911
+ reason: "unwritable",
1912
+ toolCallId: id,
1913
+ aclVerified: false,
1914
+ retryable: raw?.retryable === true || captureErrorRetryable(error),
1915
+ };
1419
1916
  this.rawSeen.set(this.rawKey(session, id), raw);
1420
1917
  }
1421
1918
  }
1422
1919
  if (!id || !verifiedRaw(raw).ok) {
1423
- throw new Error(`spine: raw backup missing before cut: ${id || "unknown"}`);
1920
+ const missing = new Error(`spine: raw backup missing before cut: ${id || "unknown"}`);
1921
+ missing.retryable = raw == null || raw.retryable === true;
1922
+ throw missing;
1424
1923
  }
1425
1924
  }
1426
1925
  messages.push({
@@ -1430,6 +1929,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1430
1929
  });
1431
1930
  }
1432
1931
  const summarized = await this.summarize({ messages, liveCompact: { card: chunk.card } }, agent, signal);
1932
+ if (typeof this.stateFor === "function") {
1933
+ const state = this.stateFor(agent);
1934
+ state.lastCardPath = chunk.card?.shadowFile || "";
1935
+ state.cardRawPaths = [...new Set([...(state.cardRawPaths || []), ...(chunk.card?.rawPaths || [])])];
1936
+ state.cardRawPathsStructured = true;
1937
+ }
1433
1938
  signal?.throwIfAborted();
1434
1939
  if (this.standDown?.()) return false;
1435
1940
  assertCurrentSpan(shadowedSeqs);
@@ -1439,7 +1944,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1439
1944
  { type: "text", text: `${CHECKPOINT_PREAMBLE}\n\n${MARK}` },
1440
1945
  ...summarized.summary,
1441
1946
  ],
1442
- source: spineCheckpointSource(compactionId),
1947
+ source: spineCheckpointSource(compactionId, chunk.card?.rawPaths || []),
1443
1948
  });
1444
1949
  const framedTokens = typeof this.ctx.tokenMeter.estimateMessage === "function"
1445
1950
  ? this.ctx.tokenMeter.estimateMessage(checkpointMessage)
@@ -1600,32 +2105,17 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1600
2105
  }
1601
2106
 
1602
2107
  catalogProviders() {
1603
- const anchors = [import.meta.url];
1604
- try {
1605
- if (process.argv[1]) anchors.push(pathToFileURL(process.argv[1]).href);
1606
- } catch {}
1607
- for (const anchor of anchors) {
1608
- try {
1609
- const loaded = createRequire(anchor)("@earendil-works/pi-ai/providers/all");
1610
- const list = typeof loaded.builtinProviders === "function" ? loaded.builtinProviders() : [];
1611
- return list.map((entry) => {
1612
- let models = [];
1613
- try {
1614
- const declared = typeof entry?.getModels === "function" ? entry.getModels() : entry?.models || [];
1615
- models = (Array.isArray(declared) ? declared : []).map((model) => ({
1616
- id: model?.id || "",
1617
- baseURL: model?.baseUrl || model?.baseURL || "",
1618
- })).filter((model) => model.id && model.baseURL);
1619
- } catch {}
1620
- return {
1621
- id: entry?.id || "",
1622
- baseURL: entry?.baseUrl || entry?.baseURL || "",
1623
- models,
1624
- };
1625
- }).filter((entry) => entry.id && (entry.baseURL || entry.models.length));
1626
- } catch {}
2108
+ if (!this.catalogPromise) {
2109
+ this.catalogPromise = loadPiAiCatalog().then((catalog) => {
2110
+ this.catalogCache = catalog;
2111
+ if (!catalog.length) this.catalogPromise = null;
2112
+ return catalog;
2113
+ }).catch(() => {
2114
+ this.catalogPromise = null;
2115
+ return [];
2116
+ });
1627
2117
  }
1628
- return [];
2118
+ return this.catalogCache || [];
1629
2119
  }
1630
2120
 
1631
2121
  profilePatchText() {
@@ -1657,6 +2147,13 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1657
2147
  const key = this.rawKey(session, id);
1658
2148
  const cached = this.rawSeen.get(key);
1659
2149
  if (!cached || cached.retryable === true) return cached || null;
2150
+ if (cached.unrecoverable) {
2151
+ const text = messageText(event.data?.message);
2152
+ if (String(text).includes(PRUNE_MARKER)) return cached;
2153
+ const refused = { ok: false, reason: "duplicate-tool-call-id", toolCallId: id, retryable: false };
2154
+ this.rawSeen.set(key, refused);
2155
+ return refused;
2156
+ }
1660
2157
  if (!cached.ok || !Number.isInteger(cached.bytes) || typeof cached.sha256 !== "string") return cached;
1661
2158
  const text = messageText(event.data?.message);
1662
2159
  if (String(text).includes(PRUNE_MARKER)) return cached;
@@ -1822,7 +2319,12 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1822
2319
  captures += 1;
1823
2320
  }
1824
2321
  this.noteCaptureResult(session, event, record);
1825
- if (record?.retryable && retry === null) {
2322
+ if (record?.unrecoverable) {
2323
+ // The host already discarded the original body. It cannot be
2324
+ // reconstructed, but it must not pin the cursor forever; the
2325
+ // visible marker remains protected by the raw lookup path.
2326
+ progressed = true;
2327
+ } else if (record?.retryable && retry === null) {
1826
2328
  retry = seq;
1827
2329
  retryIndex = index;
1828
2330
  } else if (record?.ok === false && !record.retryable && blocked === null) {
@@ -1876,7 +2378,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
1876
2378
  const cached = this.cachedCaptureFor(session, event);
1877
2379
  const record = cached && !cached.retryable ? cached : this.captureOne(session, event);
1878
2380
  this.noteCaptureResult(session, event, record);
1879
- if (record?.retryable && retry === null) retry = seq;
2381
+ if (record?.unrecoverable) {
2382
+ // Advance beyond an already-pruned result so later events can be
2383
+ // captured on the same catch-up pass.
2384
+ } else if (record?.retryable && retry === null) retry = seq;
1880
2385
  else if (record?.ok === false && !record.retryable && blocked === null) blocked = seq;
1881
2386
  }
1882
2387
  }
@@ -2228,19 +2733,23 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
2228
2733
  const card = input?.liveCompact?.card;
2229
2734
  if (card?.needsBackup && !card.shadowFile) throw new Error("spine: omit refused; backup path missing");
2230
2735
  const restored = this.restoreRawMessages(input.messages, state.key);
2231
- await this.saveShadowAsync(restored, true, card?.shadowFile, state.key, card?.rawPaths || []);
2736
+ const protectRawPaths = [...new Set([...(state.cardRawPaths || []), ...(card?.rawPaths || [])])];
2737
+ await this.saveShadowAsync(restored, true, card?.shadowFile, state.key, protectRawPaths);
2232
2738
  if (card?.needsBackup && !existsSync(card.shadowFile)) throw new Error("spine: shadow backup was not written");
2233
2739
  const text = backupClaimOk(restored) ? decision.text : withoutFullBackupClaim(decision.text, card?.shadowFile);
2234
2740
  const block = { type: "text", text };
2235
2741
  return { summary: [block], provider: "local", model: "spine-extract", rawOutput: [block] };
2236
2742
  }
2237
2743
  try {
2744
+ const officialShadowFile = freshShadowFile("official", state.key);
2238
2745
  await this.saveShadowAsync(
2239
2746
  this.restoreRawMessages(input.messages, state.key),
2240
2747
  false,
2241
- freshShadowFile("official", state.key),
2748
+ officialShadowFile,
2242
2749
  state.key,
2750
+ state.cardRawPaths || [],
2243
2751
  );
2752
+ state.lastCardPath = officialShadowFile;
2244
2753
  } catch (error) {
2245
2754
  if (
2246
2755
  error?.code === "ESHADOWACCESS" ||
@@ -2274,6 +2783,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
2274
2783
  }
2275
2784
 
2276
2785
  async summarizeOfficial(input, agent, signal) {
2786
+ this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "started" });
2277
2787
  const result = await super.summarize(input, agent, signal);
2278
2788
  const blocks = Array.isArray(result?.summary) ? result.summary : [];
2279
2789
  const usable = blocks.some((block) => {
@@ -2283,9 +2793,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
2283
2793
  return Array.isArray(block.content) && block.content.some((part) => typeof part?.text === "string" && part.text.trim());
2284
2794
  });
2285
2795
  if (!usable) {
2796
+ this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "empty" });
2286
2797
  this.ctx.logger?.warn?.("spine: official summarizer returned no usable summary; leaving the span untouched");
2287
2798
  throw new Error("spine: official summarizer returned no usable summary");
2288
2799
  }
2800
+ this.recordDecision(this.stateFor(agent), { phase: "official-summary", result: "usable" });
2289
2801
  return result;
2290
2802
  }
2291
2803
  }