dsh-live-compact 1.1.5 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +21 -9
- package/gate.js +61 -6
- package/index.js +302 -46
- package/package.json +4 -3
- package/plan.js +32 -5
- package/raw.js +32 -8
- package/shadow.js +42 -15
- package/thunder.js +8 -1
package/index.js
CHANGED
|
@@ -22,7 +22,7 @@ import { 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
|
-
import { captureOwnedToolResult, contentHash, rawExcerptText, rawName, readRawToolResult, restoreToolText, runPruneAfterCapture, verifiedRaw } from "./raw.js";
|
|
25
|
+
import { captureOwnedToolResult, contentHash, PRUNE_MARKER, rawExcerptText, rawName, readRawToolResult, restoreToolText, runPruneAfterCapture, verifiedRaw } from "./raw.js";
|
|
26
26
|
import {
|
|
27
27
|
ensureShadowDir,
|
|
28
28
|
flushDrainStats,
|
|
@@ -39,6 +39,7 @@ import {
|
|
|
39
39
|
} from "./shadow.js";
|
|
40
40
|
import { buildSendLess, decideThunder } from "./thunder.js";
|
|
41
41
|
import { inCooldown, skipLiveOfficialCompaction } from "./cooldown.js";
|
|
42
|
+
import { activeCompactionPeers, warnCompactionStandDown } from "./gate.js";
|
|
42
43
|
|
|
43
44
|
const { BasicCompactionEngine } = await loadBase();
|
|
44
45
|
const { CompactionId, toolPairingBalancedAfter, toolPairingBalancedBefore } = await loadCompaction();
|
|
@@ -56,6 +57,7 @@ const CAPTURE_RESULT_BATCH = 1;
|
|
|
56
57
|
const RECOVER_RAW_BATCH = 1;
|
|
57
58
|
const CAPTURE_RETRY_LIMIT = 8;
|
|
58
59
|
const RECOVERY_ACL_REAUTH_LIMIT = 32;
|
|
60
|
+
const SHADOW_WORKER_TIMEOUT_MS = 30000;
|
|
59
61
|
|
|
60
62
|
const shadowWorkers = new Map();
|
|
61
63
|
|
|
@@ -66,7 +68,7 @@ function shadowWorkerFor(root) {
|
|
|
66
68
|
const worker = new Worker(new URL("./shadow-save-worker.mjs", import.meta.url), {
|
|
67
69
|
workerData: { spineWorker: 1, accessFuse: shadowAccessFuseBuffer() },
|
|
68
70
|
});
|
|
69
|
-
entry = { worker, nextId: 1, pending: new Map(), idleTimer: null, retired: false };
|
|
71
|
+
entry = { worker, nextId: 1, pending: new Map(), idleTimer: null, retired: false, timedOut: false };
|
|
70
72
|
const removeEntry = () => {
|
|
71
73
|
if (shadowWorkers.get(key) === entry) shadowWorkers.delete(key);
|
|
72
74
|
};
|
|
@@ -88,7 +90,10 @@ function shadowWorkerFor(root) {
|
|
|
88
90
|
clearTimeout(entry.idleTimer);
|
|
89
91
|
entry.idleTimer = null;
|
|
90
92
|
}
|
|
91
|
-
for (const { reject } of entry.pending.values())
|
|
93
|
+
for (const { reject, timer } of entry.pending.values()) {
|
|
94
|
+
if (timer) clearTimeout(timer);
|
|
95
|
+
reject(error);
|
|
96
|
+
}
|
|
92
97
|
entry.pending.clear();
|
|
93
98
|
removeEntry();
|
|
94
99
|
worker.terminate().catch(() => {});
|
|
@@ -96,7 +101,9 @@ function shadowWorkerFor(root) {
|
|
|
96
101
|
worker.on("message", (message) => {
|
|
97
102
|
const task = entry.pending.get(message?.id);
|
|
98
103
|
if (!task) return;
|
|
104
|
+
if (task.timer) clearTimeout(task.timer);
|
|
99
105
|
entry.pending.delete(message.id);
|
|
106
|
+
if (entry.timedOut && entry.pending.size === 0) entry.timedOut = false;
|
|
100
107
|
if (message?.ok) {
|
|
101
108
|
task.resolve(message.result);
|
|
102
109
|
scheduleIdleExit();
|
|
@@ -124,16 +131,33 @@ function shadowWorkerFor(root) {
|
|
|
124
131
|
|
|
125
132
|
function runShadowWorker(payload) {
|
|
126
133
|
const entry = shadowWorkerFor(payload.shadow);
|
|
134
|
+
if (entry.timedOut) {
|
|
135
|
+
return Promise.reject(Object.assign(new Error("spine: shadow worker is finishing a timed-out transaction"), { code: "ESHADOWWORKER" }));
|
|
136
|
+
}
|
|
127
137
|
if (entry.idleTimer) {
|
|
128
138
|
clearTimeout(entry.idleTimer);
|
|
129
139
|
entry.idleTimer = null;
|
|
130
140
|
}
|
|
131
141
|
const id = entry.nextId++;
|
|
132
142
|
return new Promise((resolve, reject) => {
|
|
133
|
-
|
|
143
|
+
const task = { resolve, reject, timer: null, timedOut: false };
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
const error = Object.assign(new Error("spine: shadow worker timed out"), { code: "ESHADOWWORKER" });
|
|
146
|
+
// Do not terminate a worker that may hold the rotation lock. Worker
|
|
147
|
+
// threads share process.pid, so killing it can leave a live-PID lock
|
|
148
|
+
// which every later session refuses to recover. Reject this caller but
|
|
149
|
+
// keep the pending task until the worker naturally releases its lock.
|
|
150
|
+
task.timedOut = true;
|
|
151
|
+
entry.timedOut = true;
|
|
152
|
+
reject(error);
|
|
153
|
+
}, SHADOW_WORKER_TIMEOUT_MS);
|
|
154
|
+
timer.unref?.();
|
|
155
|
+
task.timer = timer;
|
|
156
|
+
entry.pending.set(id, task);
|
|
134
157
|
try {
|
|
135
158
|
entry.worker.postMessage({ id, payload });
|
|
136
159
|
} catch (error) {
|
|
160
|
+
clearTimeout(timer);
|
|
137
161
|
entry.pending.delete(id);
|
|
138
162
|
reject(error);
|
|
139
163
|
entry.scheduleIdleExit();
|
|
@@ -141,8 +165,29 @@ function runShadowWorker(payload) {
|
|
|
141
165
|
});
|
|
142
166
|
}
|
|
143
167
|
|
|
168
|
+
function failShadowWorker(entry, error) {
|
|
169
|
+
if (!entry || entry.retired) return;
|
|
170
|
+
entry.retired = true;
|
|
171
|
+
if (entry.idleTimer) {
|
|
172
|
+
clearTimeout(entry.idleTimer);
|
|
173
|
+
entry.idleTimer = null;
|
|
174
|
+
}
|
|
175
|
+
for (const { reject, timer } of entry.pending.values()) {
|
|
176
|
+
if (timer) clearTimeout(timer);
|
|
177
|
+
reject(error);
|
|
178
|
+
}
|
|
179
|
+
entry.pending.clear();
|
|
180
|
+
for (const [key, value] of shadowWorkers) {
|
|
181
|
+
if (value === entry) shadowWorkers.delete(key);
|
|
182
|
+
}
|
|
183
|
+
entry.worker.terminate().catch(() => {});
|
|
184
|
+
}
|
|
185
|
+
|
|
144
186
|
function recoveryRetryable(record, dir, toolCallId) {
|
|
145
187
|
if (record?.retryable === true || record?.reason === "unwritable") return true;
|
|
188
|
+
// A raw body without its metadata marker is an incomplete publication. If
|
|
189
|
+
// the current event is still available, captureOne can rebuild the pair.
|
|
190
|
+
if (record?.reason === "missing-meta") return true;
|
|
146
191
|
// A completely absent backup has never been captured and can be retried.
|
|
147
192
|
// If its metadata is still present, the body was damaged after capture and
|
|
148
193
|
// must remain fail-closed rather than being silently overwritten.
|
|
@@ -150,6 +195,11 @@ function recoveryRetryable(record, dir, toolCallId) {
|
|
|
150
195
|
return false;
|
|
151
196
|
}
|
|
152
197
|
|
|
198
|
+
function captureErrorRetryable(error) {
|
|
199
|
+
const code = error?.code;
|
|
200
|
+
return code === "ESHADOWBUSY" || ["EAGAIN", "EBUSY", "EINTR", "EIO"].includes(code);
|
|
201
|
+
}
|
|
202
|
+
|
|
153
203
|
function eventContent(session, seq) {
|
|
154
204
|
const event = session.eventAt(seq);
|
|
155
205
|
if (event?.type === "assistant/message") return event.data?.message?.content ?? event.data?.content;
|
|
@@ -170,7 +220,27 @@ function isCheckpoint(session, seq) {
|
|
|
170
220
|
// 自己的卡片,以及已经写过的官方标记,都要停住。新卡片不再用官方标记。
|
|
171
221
|
// Stop on our own cards and on older official markers. New cards do not use the official marker.
|
|
172
222
|
if (kind === SPINE_SOURCE_KIND || kind === "compact-checkpoint") return true;
|
|
173
|
-
|
|
223
|
+
// The legacy text marker is only meaningful on a user/message card and only
|
|
224
|
+
// at the beginning of its text. A tool result or an ordinary sentence that
|
|
225
|
+
// merely mentions the marker must not create a permanent cut boundary.
|
|
226
|
+
if (event?.type !== "user/message") return false;
|
|
227
|
+
const text = eventText(session, seq).trimStart();
|
|
228
|
+
return text === MARK || text.startsWith(`${MARK}\n`) || text.startsWith(`${MARK}\r\n`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function latestTurnCompleted(events) {
|
|
232
|
+
let lastStart = -1;
|
|
233
|
+
let lastEnd = -1;
|
|
234
|
+
let reason;
|
|
235
|
+
for (let index = 0; index < (events || []).length; index += 1) {
|
|
236
|
+
const event = events[index];
|
|
237
|
+
if (event?.type === "turn/start") lastStart = index;
|
|
238
|
+
if (event?.type === "turn/end") {
|
|
239
|
+
lastEnd = index;
|
|
240
|
+
reason = event.data?.reason?.kind;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return lastEnd > lastStart && reason === "completed";
|
|
174
244
|
}
|
|
175
245
|
|
|
176
246
|
function spineCheckpointSource(compactionId) {
|
|
@@ -367,8 +437,6 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
367
437
|
const cutEnd = span ? reservedCutEnd(visible[span.start].index, first) : null;
|
|
368
438
|
if (span && cutEnd === null) return null;
|
|
369
439
|
if (cutEnd !== null) {
|
|
370
|
-
const keptEnd = visible[span.end].index;
|
|
371
|
-
for (let index = visible[span.start].index; index <= keptEnd; index += 1) keptTokens += priced[index].tokens;
|
|
372
440
|
end = cutEnd;
|
|
373
441
|
while (end >= first && classifications[end].isGenuineUserBoundary && !(floorCard >= 0 && end - 1 <= floorCard)) end -= 1;
|
|
374
442
|
if (floorCard >= 0 && end <= floorCard) return null;
|
|
@@ -379,7 +447,7 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
379
447
|
}
|
|
380
448
|
if (floorCard >= 0 && end <= floorCard) return null;
|
|
381
449
|
}
|
|
382
|
-
const longSpan = newestLong && visible[newestLong.start].index > floorCard
|
|
450
|
+
const longSpan = !context.disableLongRead && newestLong && visible[newestLong.start].index > floorCard
|
|
383
451
|
? { start: visible[newestLong.start].index, end: visible[newestLong.end].index }
|
|
384
452
|
: null;
|
|
385
453
|
if (!longSpan && (end < first || isCheckpoint(session, nodes[end]))) return null;
|
|
@@ -456,6 +524,9 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
456
524
|
};
|
|
457
525
|
let usedLongCut = false;
|
|
458
526
|
let picked = null;
|
|
527
|
+
const fallbackWithoutLongRead = () => context.disableLongRead
|
|
528
|
+
? null
|
|
529
|
+
: selectNewestChunk(session, measurement, key, { ...context, disableLongRead: true });
|
|
459
530
|
if (longSpan) {
|
|
460
531
|
const longPicked = cutLongReadRound(items, longSpan.start, longSpan.end, cutOptions);
|
|
461
532
|
if (longPicked && longPicked.start >= longSpan.start && longPicked.end <= longSpan.end) {
|
|
@@ -481,27 +552,39 @@ function selectNewestChunk(session, measurement, key = DEFAULT_KEY, context = {}
|
|
|
481
552
|
}
|
|
482
553
|
}
|
|
483
554
|
}
|
|
484
|
-
if (pairStart < 0) return null;
|
|
485
|
-
if (usedLongCut && pairStart < longSpan.start) return
|
|
486
|
-
if (!pointerSpanAllowed(items, pairStart, picked.end, context.engine || "cloud")) return null;
|
|
487
|
-
if (!cutOk(toolPairingBalancedBefore, session, nodes[pairStart])) return null;
|
|
555
|
+
if (pairStart < 0) return usedLongCut ? fallbackWithoutLongRead() : null;
|
|
556
|
+
if (usedLongCut && pairStart < longSpan.start) return fallbackWithoutLongRead();
|
|
557
|
+
if (!pointerSpanAllowed(items, pairStart, picked.end, context.engine || "cloud")) return usedLongCut ? fallbackWithoutLongRead() : null;
|
|
558
|
+
if (!cutOk(toolPairingBalancedBefore, session, nodes[pairStart])) return usedLongCut ? fallbackWithoutLongRead() : null;
|
|
488
559
|
picked.start = pairStart;
|
|
489
560
|
}
|
|
490
|
-
if (usedLongCut && (picked.start < longSpan.start || picked.end > longSpan.end)) return
|
|
561
|
+
if (usedLongCut && (picked.start < longSpan.start || picked.end > longSpan.end)) return fallbackWithoutLongRead();
|
|
491
562
|
const start = picked.start;
|
|
492
563
|
end = picked.end;
|
|
493
564
|
const tokens = items.slice(start, end + 1).reduce((sum, item) => sum + item.tokens, 0);
|
|
494
565
|
const pieces = spanPieces(start, end);
|
|
495
|
-
if (picked.pointerOnly && pieces.some((piece) => piece.role === "tool" && isToolFailure(piece.text, piece.isError)))
|
|
566
|
+
if (picked.pointerOnly && pieces.some((piece) => piece.role === "tool" && isToolFailure(piece.text, piece.isError))) {
|
|
567
|
+
return usedLongCut ? fallbackWithoutLongRead() : null;
|
|
568
|
+
}
|
|
496
569
|
let card = picked.pointerOnly
|
|
497
570
|
? { ok: true, text: pointerOnlyText(pieces), hardLines: [], missing: [], needsBackup: false, rawPaths: [] }
|
|
498
571
|
: buildCard(pieces.map((piece) => piece.text).join("\n"), liveText(start, end), pieces, extras);
|
|
499
|
-
if (card.ok !== true) return null;
|
|
572
|
+
if (card.ok !== true) return usedLongCut ? fallbackWithoutLongRead() : null;
|
|
500
573
|
card = attachBackupHint(card, freshShadowFile("cut", key));
|
|
501
574
|
if (!card.text.includes("不是备份文件路径")) card = { ...card, text: `${card.text}\n序号是本会话日志里的事件号,不是备份文件路径。` };
|
|
502
575
|
if (!cutOk(toolPairingBalancedAfter, session, nodes[end])) return null;
|
|
503
576
|
let after = 0;
|
|
504
577
|
for (let index = end + 1; index < priced.length; index += 1) after += priced[index].tokens;
|
|
578
|
+
// `keptTokens` must describe retained rounds to the right of the actual
|
|
579
|
+
// cut. A long-read cut can be newer than the ordinary rounds selected above;
|
|
580
|
+
// counting those older rounds made `tailBeyondKept` negative and disabled
|
|
581
|
+
// the tail guard.
|
|
582
|
+
for (const round of rounds) {
|
|
583
|
+
const roundStart = visible[round.start]?.index;
|
|
584
|
+
const roundEnd = visible[round.end]?.index;
|
|
585
|
+
if (!Number.isInteger(roundStart) || !Number.isInteger(roundEnd) || roundStart <= end) continue;
|
|
586
|
+
for (let index = roundStart; index <= roundEnd; index += 1) keptTokens += priced[index].tokens;
|
|
587
|
+
}
|
|
505
588
|
let prefix = 0;
|
|
506
589
|
for (let index = 0; index < start; index += 1) prefix += priced[index].tokens;
|
|
507
590
|
return { start: nodes[start], end: nodes[end], tokens, after, keptTokens, card, prefix };
|
|
@@ -544,20 +627,25 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
544
627
|
});
|
|
545
628
|
ctx.on("session/event", (session, event) => {
|
|
546
629
|
try {
|
|
630
|
+
if (this.standDown?.()) return;
|
|
547
631
|
this.noteEvent(session, event);
|
|
548
632
|
if (event?.type !== "tool/result") return;
|
|
549
633
|
const id = event.data?.message?.toolCallId;
|
|
550
634
|
if (!id) return;
|
|
551
635
|
const key = this.rawKey(session, id);
|
|
552
|
-
const cached = this.
|
|
553
|
-
if (cached && !cached.retryable)
|
|
636
|
+
const cached = this.cachedCaptureFor(session, event);
|
|
637
|
+
if (cached && !cached.retryable) {
|
|
638
|
+
this.noteCaptureResult(session, event, cached);
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
554
641
|
if (this.pendingCaptureKeys.has(key)) return;
|
|
555
642
|
this.pendingCaptureKeys.add(key);
|
|
556
643
|
let job;
|
|
557
644
|
job = new Promise((resolve) => {
|
|
558
645
|
scheduleImmediate(() => {
|
|
559
646
|
try {
|
|
560
|
-
|
|
647
|
+
if (this.standDown?.()) return;
|
|
648
|
+
const current = this.cachedCaptureFor(session, event);
|
|
561
649
|
if (!current || current.retryable) {
|
|
562
650
|
const record = this.captureOne(session, event);
|
|
563
651
|
this.noteCaptureResult(session, event, record);
|
|
@@ -580,16 +668,17 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
580
668
|
});
|
|
581
669
|
ctx.on("agent/status", ({ agent, status }) => {
|
|
582
670
|
if (status !== "idle") return;
|
|
671
|
+
if (this.standDown?.()) return;
|
|
583
672
|
const state = this.stateFor(agent);
|
|
584
673
|
if (state.warming) return;
|
|
585
674
|
const events = agent.session.snapshotEvents();
|
|
586
|
-
const done = events
|
|
675
|
+
const done = latestTurnCompleted(events);
|
|
587
676
|
if (!done) return;
|
|
588
677
|
state.warming = true;
|
|
589
678
|
const job = this.finishTurn(agent, events, { deferCapture: true })
|
|
590
679
|
.catch((error) => noteShadowWarning(this.ctx?.logger, error))
|
|
591
680
|
.finally(() => {
|
|
592
|
-
state.warming = false;
|
|
681
|
+
if (!state.pendingMaintenance) state.warming = false;
|
|
593
682
|
this.pendingCuts.delete(job);
|
|
594
683
|
});
|
|
595
684
|
this.pendingCuts.add(job);
|
|
@@ -600,6 +689,24 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
600
689
|
}
|
|
601
690
|
}
|
|
602
691
|
|
|
692
|
+
standDown() {
|
|
693
|
+
const peers = activeCompactionPeers(this.ctx);
|
|
694
|
+
if (peers.length) warnCompactionStandDown(this.ctx);
|
|
695
|
+
return peers.length > 0;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
ownedSignal(signal) {
|
|
699
|
+
const controller = new AbortController();
|
|
700
|
+
const dispose = this.ctx.on("internal/status", () => {
|
|
701
|
+
if (this.standDown?.()) controller.abort();
|
|
702
|
+
}, { global: true });
|
|
703
|
+
if (this.standDown?.()) controller.abort();
|
|
704
|
+
return {
|
|
705
|
+
signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
|
|
706
|
+
dispose,
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
603
710
|
stateFor(agent) {
|
|
604
711
|
const key = sessionKey(agent);
|
|
605
712
|
let state = this.sessionState.get(key);
|
|
@@ -672,6 +779,9 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
672
779
|
retryRequested: false,
|
|
673
780
|
captureRetryAttempts: 0,
|
|
674
781
|
progressed: false,
|
|
782
|
+
hadRetry: false,
|
|
783
|
+
failed: false,
|
|
784
|
+
maintenanceRequested: options.maintenanceRequested === true,
|
|
675
785
|
eventTail: Number.isInteger(events?.at?.(-1)?.seq) ? events.at(-1).seq : -1,
|
|
676
786
|
surfaceTail: agent.session.surface?.nodes?.at?.(-1) ?? -1,
|
|
677
787
|
freezeSnapshot: options.freezeSnapshot === true,
|
|
@@ -700,6 +810,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
700
810
|
scheduleImmediate(() => {
|
|
701
811
|
task.scheduled = false;
|
|
702
812
|
try {
|
|
813
|
+
if (this.standDown?.()) {
|
|
814
|
+
this.finishCaptureCatchup(task);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
703
817
|
const latest = task.freezeSnapshot ? null : task.session.snapshotEvents?.();
|
|
704
818
|
const latestTail = Number.isInteger(latest?.at?.(-1)?.seq) ? latest.at(-1).seq : -1;
|
|
705
819
|
const latestSurfaceTail = task.session.surface?.nodes?.at?.(-1) ?? -1;
|
|
@@ -739,6 +853,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
739
853
|
task.eventIndex = result.nextIndex;
|
|
740
854
|
task.progressed ||= result.progressed;
|
|
741
855
|
if (result.retryable) {
|
|
856
|
+
task.hadRetry = true;
|
|
742
857
|
task.captureRetryAttempts += 1;
|
|
743
858
|
const previousMax = this.captureRetryStats?.get(task.key) || 0;
|
|
744
859
|
if (task.captureRetryAttempts > previousMax) this.captureRetryStats.set(task.key, task.captureRetryAttempts);
|
|
@@ -749,6 +864,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
749
864
|
this.queueCaptureRetry(task);
|
|
750
865
|
return;
|
|
751
866
|
}
|
|
867
|
+
if (result.blocked) {
|
|
868
|
+
task.captureBlocked = true;
|
|
869
|
+
this.finishCaptureCatchup(task);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
752
872
|
if (result.progressed) task.captureRetryAttempts = 0;
|
|
753
873
|
if (!result.done) {
|
|
754
874
|
this.queueCaptureCatchup(task);
|
|
@@ -767,6 +887,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
767
887
|
}
|
|
768
888
|
this.finishCaptureCatchup(task);
|
|
769
889
|
} catch (error) {
|
|
890
|
+
task.failed = true;
|
|
770
891
|
noteShadowWarning(this.ctx?.logger, error);
|
|
771
892
|
this.finishCaptureCatchup(task);
|
|
772
893
|
}
|
|
@@ -779,23 +900,38 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
779
900
|
this.pendingCatchups.delete(task.key);
|
|
780
901
|
this.pendingCatchupJobs.delete(task.promise);
|
|
781
902
|
task.resolve();
|
|
782
|
-
if (task.
|
|
903
|
+
if (task.failed || task.captureBlocked) {
|
|
904
|
+
const state = this.stateFor(task.agent);
|
|
905
|
+
state.pendingMaintenance = false;
|
|
906
|
+
state.warming = false;
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
if (!this.standDown?.() && !task.captureBlocked &&
|
|
910
|
+
(task.retryRequested || task.maintenanceRequested)) {
|
|
911
|
+
this.scheduleMaintenanceRetry(task.agent);
|
|
912
|
+
}
|
|
783
913
|
}
|
|
784
914
|
|
|
785
915
|
scheduleMaintenanceRetry(agent) {
|
|
916
|
+
if (this.standDown?.()) return;
|
|
786
917
|
const state = this.stateFor(agent);
|
|
787
918
|
if (state.retryScheduled) return;
|
|
788
919
|
state.retryScheduled = true;
|
|
789
920
|
scheduleImmediate(() => {
|
|
790
921
|
state.retryScheduled = false;
|
|
791
|
-
if (
|
|
922
|
+
if (this.standDown?.()) return;
|
|
923
|
+
if (state.warming && !state.pendingMaintenance) {
|
|
924
|
+
scheduleImmediate(() => this.scheduleMaintenanceRetry(agent));
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
792
927
|
const events = agent.session.snapshotEvents();
|
|
793
|
-
const done = events
|
|
928
|
+
const done = latestTurnCompleted(events);
|
|
794
929
|
if (!done) return;
|
|
795
930
|
state.warming = true;
|
|
796
|
-
const job = this.finishTurn(agent, events, {
|
|
931
|
+
const job = this.finishTurn(agent, events, { maintenanceRetry: true, skipCapture: true })
|
|
797
932
|
.catch((error) => noteShadowWarning(this.ctx?.logger, error))
|
|
798
933
|
.finally(() => {
|
|
934
|
+
state.pendingMaintenance = false;
|
|
799
935
|
state.warming = false;
|
|
800
936
|
this.pendingCuts.delete(job);
|
|
801
937
|
});
|
|
@@ -804,14 +940,19 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
804
940
|
}
|
|
805
941
|
|
|
806
942
|
async finishTurn(agent, events, options = {}) {
|
|
943
|
+
if (this.standDown?.()) return null;
|
|
807
944
|
const settings = readSettings(this.liveConfig);
|
|
808
945
|
const state = this.stateFor(agent);
|
|
809
946
|
const signal = AbortSignal.timeout(30000);
|
|
810
947
|
const ev = events || agent.session.snapshotEvents();
|
|
811
948
|
const deferCapture = options.deferCapture === true;
|
|
812
949
|
let catchup = { finished: true, progressed: false, retryRequested: false };
|
|
813
|
-
if (
|
|
814
|
-
|
|
950
|
+
if (options.skipCapture) {
|
|
951
|
+
// A completed idle catch-up or a failed-cut retry already established
|
|
952
|
+
// the capture surface. Re-run maintenance without rescanning events.
|
|
953
|
+
} else if (deferCapture) {
|
|
954
|
+
state.pendingMaintenance = true;
|
|
955
|
+
catchup = this.scheduleCaptureCatchup(agent, ev, settings, { maintenanceRequested: true });
|
|
815
956
|
} else {
|
|
816
957
|
if (ev.length > CAPTURE_EVENT_BATCH) {
|
|
817
958
|
catchup = this.scheduleCaptureCatchup(agent, ev, settings, { freezeSnapshot: true });
|
|
@@ -820,20 +961,44 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
820
961
|
this.captureNew(agent.session, ev, settings);
|
|
821
962
|
}
|
|
822
963
|
}
|
|
964
|
+
// Never enter the host's maintenance gate while another session's
|
|
965
|
+
// catch-up is still running. The host may serialize runMaintenance across
|
|
966
|
+
// agents; defer this pass and retry after the catch-up settles instead of
|
|
967
|
+
// making finishTurn wait or holding the global gate.
|
|
968
|
+
if (catchup?.promise && !catchup.finished) {
|
|
969
|
+
if (options.maintenanceRetry || (!deferCapture && ev.length <= CAPTURE_EVENT_BATCH)) {
|
|
970
|
+
await catchup.promise;
|
|
971
|
+
} else {
|
|
972
|
+
return null;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
await this.flushPendingCaptures();
|
|
823
976
|
const jobs = collectJobs(ev);
|
|
824
977
|
const calls = indexToolCalls(ev);
|
|
825
978
|
try {
|
|
826
979
|
await agent.runMaintenance(async (agentSignal) => {
|
|
980
|
+
if (this.standDown?.()) return;
|
|
827
981
|
const op = AbortSignal.any([agentSignal, signal]);
|
|
828
982
|
let measurement = this.ctx.tokenMeter.measure(agent.session);
|
|
829
|
-
|
|
983
|
+
const settleTurnBaseline = () => {
|
|
984
|
+
state.turnBase = measurement.totalTokens;
|
|
985
|
+
state.maxTurnGrowth = 0;
|
|
986
|
+
};
|
|
987
|
+
if (measurement.totalTokens < settings.minTokens || measurement.totalTokens >= settings.bigGate) {
|
|
988
|
+
settleTurnBaseline();
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
830
991
|
// Restored cards establish a baseline; a live card still skips once,
|
|
831
992
|
// even when maintenance or engine construction is delayed.
|
|
832
993
|
if (skipLiveOfficialCompaction(agent.session)) {
|
|
833
994
|
this.ctx.logger?.info?.("spine cooldown: live official compaction seen, skip this pass");
|
|
995
|
+
settleTurnBaseline();
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
if (inCooldown(agent.session, { windowMs: settings.cooldownMs })) {
|
|
999
|
+
settleTurnBaseline();
|
|
834
1000
|
return;
|
|
835
1001
|
}
|
|
836
|
-
if (inCooldown(agent.session, { windowMs: settings.cooldownMs })) return;
|
|
837
1002
|
this.ensurePruneGuard();
|
|
838
1003
|
const resolved = this.engineFor(agent);
|
|
839
1004
|
if (state.engine !== resolved.engine || state.engineSource !== resolved.source) {
|
|
@@ -879,8 +1044,8 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
879
1044
|
try {
|
|
880
1045
|
state.localOnly = true;
|
|
881
1046
|
state.approvedCard = chunk.card;
|
|
882
|
-
await this.
|
|
883
|
-
|
|
1047
|
+
const committed = await this.commitSelectedSpan(agent, chunk, op, { drain });
|
|
1048
|
+
if (committed === false) break;
|
|
884
1049
|
measurement = this.ctx.tokenMeter.measure(agent.session);
|
|
885
1050
|
const after = measurement.totalTokens;
|
|
886
1051
|
reduced = after < before;
|
|
@@ -915,6 +1080,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
915
1080
|
}
|
|
916
1081
|
if (drainNotes.length) flushDrainStats(shadowDirectory(), drainNotes, { sid: state.key, drain });
|
|
917
1082
|
state.turnBase = measurement.totalTokens;
|
|
1083
|
+
state.maxTurnGrowth = 0;
|
|
918
1084
|
await this.ctx.sessions?.flush?.(agent.session);
|
|
919
1085
|
this.rememberPrefix(agent);
|
|
920
1086
|
});
|
|
@@ -955,7 +1121,8 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
955
1121
|
return ids;
|
|
956
1122
|
}
|
|
957
1123
|
|
|
958
|
-
async commitSelectedSpan(agent, chunk, signal) {
|
|
1124
|
+
async commitSelectedSpan(agent, chunk, signal, options = {}) {
|
|
1125
|
+
if (this.standDown?.()) return false;
|
|
959
1126
|
signal?.throwIfAborted();
|
|
960
1127
|
const session = agent.session;
|
|
961
1128
|
if (chunk.card?.ok !== true || !chunk.card.text) throw new Error("spine: approved card missing; leaving the span");
|
|
@@ -1022,6 +1189,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1022
1189
|
}
|
|
1023
1190
|
const summarized = await this.summarize({ messages, liveCompact: { card: chunk.card } }, agent, signal);
|
|
1024
1191
|
signal?.throwIfAborted();
|
|
1192
|
+
if (this.standDown?.()) return false;
|
|
1025
1193
|
assertCurrentSpan(shadowedSeqs);
|
|
1026
1194
|
const compactionId = CompactionId(randomUUID());
|
|
1027
1195
|
const checkpointMessage = createUserMessage({
|
|
@@ -1031,10 +1199,20 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1031
1199
|
],
|
|
1032
1200
|
source: spineCheckpointSource(compactionId),
|
|
1033
1201
|
});
|
|
1034
|
-
const framedTokens = this.ctx.tokenMeter.estimateMessage
|
|
1202
|
+
const framedTokens = typeof this.ctx.tokenMeter.estimateMessage === "function"
|
|
1203
|
+
? this.ctx.tokenMeter.estimateMessage(checkpointMessage)
|
|
1204
|
+
: Math.ceil(JSON.stringify(checkpointMessage.content || []).length / 4) + 8;
|
|
1035
1205
|
if (typeof framedTokens === "number" && framedTokens >= chunk.tokens) {
|
|
1036
1206
|
throw new Error(`summary is not smaller than the shadowed content (${framedTokens} >= ${chunk.tokens})`);
|
|
1037
1207
|
}
|
|
1208
|
+
if (options.drain === true && Number.isFinite(chunk.prefix) && chunk.prefix > 0) {
|
|
1209
|
+
const estimatedSaved = chunk.tokens - Number(framedTokens || 0);
|
|
1210
|
+
const minimumSaved = Math.ceil(chunk.tokens * 0.01);
|
|
1211
|
+
if (estimatedSaved < minimumSaved) {
|
|
1212
|
+
this.ctx.logger?.warn?.(`spine drain stopped: estimated saving ${estimatedSaved} < rewrite guard ${minimumSaved}`);
|
|
1213
|
+
return false;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1038
1216
|
const lifecycle = { compactionId, turn: null };
|
|
1039
1217
|
let started = false;
|
|
1040
1218
|
let replaced = false;
|
|
@@ -1068,6 +1246,8 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1068
1246
|
} catch {}
|
|
1069
1247
|
}
|
|
1070
1248
|
if (!replaced) throw error;
|
|
1249
|
+
this.ctx.logger?.warn?.(`spine compaction persistence unknown after replacement: ${message}`);
|
|
1250
|
+
return false;
|
|
1071
1251
|
}
|
|
1072
1252
|
}
|
|
1073
1253
|
|
|
@@ -1081,11 +1261,27 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1081
1261
|
}
|
|
1082
1262
|
|
|
1083
1263
|
async compactIfNeeded(agent, trigger, signal) {
|
|
1264
|
+
if (this.standDown?.()) return null;
|
|
1084
1265
|
const state = this.stateFor(agent);
|
|
1085
1266
|
state.liveAgent = agent;
|
|
1086
1267
|
state.localOnly = false;
|
|
1087
1268
|
this.ensurePruneGuard();
|
|
1088
|
-
|
|
1269
|
+
const owned = this.ownedSignal(signal);
|
|
1270
|
+
try {
|
|
1271
|
+
return await super.compactIfNeeded(agent, trigger, owned.signal);
|
|
1272
|
+
} finally {
|
|
1273
|
+
owned.dispose?.();
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
async compactNow(agent, signal, sourceCommandId) {
|
|
1278
|
+
if (this.standDown?.()) return null;
|
|
1279
|
+
const owned = this.ownedSignal(signal);
|
|
1280
|
+
try {
|
|
1281
|
+
return await super.compactNow(agent, owned.signal, sourceCommandId);
|
|
1282
|
+
} finally {
|
|
1283
|
+
owned.dispose?.();
|
|
1284
|
+
}
|
|
1089
1285
|
}
|
|
1090
1286
|
|
|
1091
1287
|
// Preserve explicit URL precedence. Only the exact account provider gets
|
|
@@ -1094,9 +1290,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1094
1290
|
const header = agent?.session?.requestHeader?.()?.config || {};
|
|
1095
1291
|
const context = agent?.session?.requestContext?.() || {};
|
|
1096
1292
|
const provider = header.provider || context.provider || "";
|
|
1293
|
+
const model = header.model || context.model || "";
|
|
1097
1294
|
const listed = this.listedProviders();
|
|
1098
1295
|
const baseURL = resolveProviderBaseURL({
|
|
1099
1296
|
provider,
|
|
1297
|
+
model,
|
|
1100
1298
|
headerURL: header.baseURL || context.baseURL || "",
|
|
1101
1299
|
listed,
|
|
1102
1300
|
layers: this.providerLayers(),
|
|
@@ -1168,10 +1366,21 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1168
1366
|
try {
|
|
1169
1367
|
const loaded = createRequire(anchor)("@earendil-works/pi-ai/providers/all");
|
|
1170
1368
|
const list = typeof loaded.builtinProviders === "function" ? loaded.builtinProviders() : [];
|
|
1171
|
-
return list.map((entry) =>
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1369
|
+
return list.map((entry) => {
|
|
1370
|
+
let models = [];
|
|
1371
|
+
try {
|
|
1372
|
+
const declared = typeof entry?.getModels === "function" ? entry.getModels() : entry?.models || [];
|
|
1373
|
+
models = (Array.isArray(declared) ? declared : []).map((model) => ({
|
|
1374
|
+
id: model?.id || "",
|
|
1375
|
+
baseURL: model?.baseUrl || model?.baseURL || "",
|
|
1376
|
+
})).filter((model) => model.id && model.baseURL);
|
|
1377
|
+
} catch {}
|
|
1378
|
+
return {
|
|
1379
|
+
id: entry?.id || "",
|
|
1380
|
+
baseURL: entry?.baseUrl || entry?.baseURL || "",
|
|
1381
|
+
models,
|
|
1382
|
+
};
|
|
1383
|
+
}).filter((entry) => entry.id && (entry.baseURL || entry.models.length));
|
|
1175
1384
|
} catch {}
|
|
1176
1385
|
}
|
|
1177
1386
|
return [];
|
|
@@ -1200,12 +1409,31 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1200
1409
|
return `${session?.id || DEFAULT_KEY}\0${toolCallId}`;
|
|
1201
1410
|
}
|
|
1202
1411
|
|
|
1412
|
+
cachedCaptureFor(session, event) {
|
|
1413
|
+
const id = event?.data?.message?.toolCallId;
|
|
1414
|
+
if (!id) return null;
|
|
1415
|
+
const key = this.rawKey(session, id);
|
|
1416
|
+
const cached = this.rawSeen.get(key);
|
|
1417
|
+
if (!cached || cached.retryable === true) return cached || null;
|
|
1418
|
+
if (!cached.ok || !Number.isInteger(cached.bytes) || typeof cached.sha256 !== "string") return cached;
|
|
1419
|
+
const text = messageText(event.data?.message);
|
|
1420
|
+
if (String(text).includes(PRUNE_MARKER)) return cached;
|
|
1421
|
+
const bytes = Buffer.byteLength(String(text ?? ""), "utf8");
|
|
1422
|
+
const sha256 = contentHash(String(text ?? ""));
|
|
1423
|
+
if (cached.bytes === bytes && cached.sha256 === sha256) return cached;
|
|
1424
|
+
const refused = { ok: false, reason: "duplicate-tool-call-id", toolCallId: id, retryable: false };
|
|
1425
|
+
this.rawSeen.set(key, refused);
|
|
1426
|
+
return refused;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1203
1429
|
captureOne(session, event, access = {}) {
|
|
1430
|
+
if (this.standDown?.()) return null;
|
|
1204
1431
|
const id = event?.data?.message?.toolCallId;
|
|
1205
1432
|
if (!id) return null;
|
|
1206
1433
|
const key = session?.id || DEFAULT_KEY;
|
|
1207
1434
|
const mapKey = this.rawKey(session, id);
|
|
1208
|
-
|
|
1435
|
+
const cached = this.cachedCaptureFor(session, event);
|
|
1436
|
+
if (cached && !cached.retryable) return cached;
|
|
1209
1437
|
const platform = access.platform ?? process.platform;
|
|
1210
1438
|
if (!access.runner && platform === "win32" && shadowAccessFused()) {
|
|
1211
1439
|
const skipped = { ok: false, reason: "unwritable", toolCallId: id };
|
|
@@ -1247,7 +1475,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1247
1475
|
}
|
|
1248
1476
|
const message = error instanceof Error ? error.message : String(error);
|
|
1249
1477
|
this.ctx?.logger?.warn?.(`spine: raw backup failed: ${message}`);
|
|
1250
|
-
const record = { ok: false, reason: "unwritable", toolCallId: id, retryable: error
|
|
1478
|
+
const record = { ok: false, reason: "unwritable", toolCallId: id, retryable: captureErrorRetryable(error) };
|
|
1251
1479
|
this.rawSeen.set(mapKey, record);
|
|
1252
1480
|
return record;
|
|
1253
1481
|
}
|
|
@@ -1307,12 +1535,22 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1307
1535
|
}
|
|
1308
1536
|
|
|
1309
1537
|
captureNewBatch(session, events, settings = readSettings(this.liveConfig), limits = {}) {
|
|
1538
|
+
if (this.standDown?.()) {
|
|
1539
|
+
return {
|
|
1540
|
+
seen: new Set(),
|
|
1541
|
+
progressed: false,
|
|
1542
|
+
retryable: false,
|
|
1543
|
+
done: true,
|
|
1544
|
+
nextIndex: Number.isInteger(limits.startIndex) ? limits.startIndex : 0,
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1310
1547
|
if (!Array.isArray(events)) events = [];
|
|
1311
1548
|
const key = session?.id || DEFAULT_KEY;
|
|
1312
1549
|
const cursor = this.captureCursorStart(session, events, settings);
|
|
1313
1550
|
let next = cursor;
|
|
1314
1551
|
let retry = null;
|
|
1315
1552
|
let retryIndex = null;
|
|
1553
|
+
let blocked = null;
|
|
1316
1554
|
let processed = 0;
|
|
1317
1555
|
let captures = 0;
|
|
1318
1556
|
let progressed = false;
|
|
@@ -1335,7 +1573,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1335
1573
|
const id = event.data?.message?.toolCallId;
|
|
1336
1574
|
if (id && !seen.has(id)) {
|
|
1337
1575
|
seen.add(id);
|
|
1338
|
-
const cached = this.
|
|
1576
|
+
const cached = this.cachedCaptureFor(session, event);
|
|
1339
1577
|
const record = cached && !cached.retryable ? cached : this.captureOne(session, event);
|
|
1340
1578
|
if (!cached || cached.retryable) {
|
|
1341
1579
|
if (record?.ok) progressed = true;
|
|
@@ -1345,18 +1583,23 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1345
1583
|
if (record?.retryable && retry === null) {
|
|
1346
1584
|
retry = seq;
|
|
1347
1585
|
retryIndex = index;
|
|
1586
|
+
} else if (record?.ok === false && !record.retryable && blocked === null) {
|
|
1587
|
+
// Never advance a cursor beyond a permanent integrity failure.
|
|
1588
|
+
// The failed event must remain visible for a later repair/retry.
|
|
1589
|
+
blocked = seq;
|
|
1590
|
+
retryIndex = index;
|
|
1348
1591
|
}
|
|
1349
1592
|
}
|
|
1350
1593
|
}
|
|
1351
1594
|
next = seq + 1;
|
|
1352
1595
|
processed += 1;
|
|
1353
|
-
if (retry !== null || processed >= eventLimit || captures >= resultLimit) {
|
|
1596
|
+
if (retry !== null || blocked !== null || processed >= eventLimit || captures >= resultLimit) {
|
|
1354
1597
|
exhausted = false;
|
|
1355
1598
|
index += 1;
|
|
1356
1599
|
break;
|
|
1357
1600
|
}
|
|
1358
1601
|
}
|
|
1359
|
-
next = retry ?? next;
|
|
1602
|
+
next = retry ?? blocked ?? next;
|
|
1360
1603
|
this.captureCursor.set(key, next);
|
|
1361
1604
|
this.writeCaptureCursor(key, next);
|
|
1362
1605
|
const lastEvent = events.at(-1);
|
|
@@ -1365,17 +1608,20 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1365
1608
|
seen,
|
|
1366
1609
|
progressed,
|
|
1367
1610
|
retryable: retry !== null,
|
|
1368
|
-
|
|
1611
|
+
blocked: blocked !== null,
|
|
1612
|
+
done: exhausted && retry === null && blocked === null && next > lastSeq,
|
|
1369
1613
|
nextIndex: retryIndex ?? index,
|
|
1370
1614
|
};
|
|
1371
1615
|
}
|
|
1372
1616
|
|
|
1373
1617
|
captureNew(session, events, settings = readSettings(this.liveConfig)) {
|
|
1618
|
+
if (this.standDown?.()) return new Set();
|
|
1374
1619
|
if (!Array.isArray(events)) events = [];
|
|
1375
1620
|
const key = session?.id || DEFAULT_KEY;
|
|
1376
1621
|
const cursor = this.captureCursorStart(session, events, settings);
|
|
1377
1622
|
let next = cursor;
|
|
1378
1623
|
let retry = null;
|
|
1624
|
+
let blocked = null;
|
|
1379
1625
|
const seen = new Set();
|
|
1380
1626
|
for (const event of events) {
|
|
1381
1627
|
const seq = Number.isInteger(event?.seq) ? event.seq : next;
|
|
@@ -1385,17 +1631,19 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1385
1631
|
const id = event.data?.message?.toolCallId;
|
|
1386
1632
|
if (id && !seen.has(id)) {
|
|
1387
1633
|
seen.add(id);
|
|
1388
|
-
const cached = this.
|
|
1634
|
+
const cached = this.cachedCaptureFor(session, event);
|
|
1389
1635
|
const record = cached && !cached.retryable ? cached : this.captureOne(session, event);
|
|
1390
1636
|
this.noteCaptureResult(session, event, record);
|
|
1391
1637
|
if (record?.retryable && retry === null) retry = seq;
|
|
1638
|
+
else if (record?.ok === false && !record.retryable && blocked === null) blocked = seq;
|
|
1392
1639
|
}
|
|
1393
1640
|
}
|
|
1394
1641
|
next = seq + 1;
|
|
1642
|
+
if (blocked !== null) break;
|
|
1395
1643
|
}
|
|
1396
1644
|
// Scanning later events is useful, but is not proof of a successful backup.
|
|
1397
1645
|
// Their completed records stay cached while the first busy result is retried.
|
|
1398
|
-
next = retry ?? next;
|
|
1646
|
+
next = retry ?? blocked ?? next;
|
|
1399
1647
|
this.captureCursor.set(key, next);
|
|
1400
1648
|
this.writeCaptureCursor(key, next);
|
|
1401
1649
|
this.recoverVisibleRaw(session);
|
|
@@ -1426,6 +1674,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1426
1674
|
}
|
|
1427
1675
|
|
|
1428
1676
|
writeCaptureCursor(key, cursor, access = {}) {
|
|
1677
|
+
if (this.standDown?.()) return;
|
|
1429
1678
|
if (this.persistCapture !== true || !Number.isSafeInteger(cursor) || cursor < 0) return;
|
|
1430
1679
|
let tmp;
|
|
1431
1680
|
let fd;
|
|
@@ -1452,6 +1701,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1452
1701
|
}
|
|
1453
1702
|
|
|
1454
1703
|
recoverVisibleRaw(session, access = {}) {
|
|
1704
|
+
if (this.standDown?.()) return;
|
|
1455
1705
|
const dir = sessionDir(shadowDirectory(), session?.id || DEFAULT_KEY);
|
|
1456
1706
|
const ids = [...new Set(this.surfaceToolIds(session))];
|
|
1457
1707
|
if (ids.length && existsSync(dir)) ensureShadowDir(dir, access);
|
|
@@ -1486,6 +1736,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1486
1736
|
}
|
|
1487
1737
|
|
|
1488
1738
|
recoverVisibleRawBatch(session, access = {}, startIndex = 0, limit = RECOVER_RAW_BATCH, visibleIds = null) {
|
|
1739
|
+
if (this.standDown?.()) return { nextIndex: startIndex, done: true, progressed: false };
|
|
1489
1740
|
const ids = visibleIds || [...new Set(this.surfaceToolIds(session))];
|
|
1490
1741
|
const dir = sessionDir(shadowDirectory(), session?.id || DEFAULT_KEY);
|
|
1491
1742
|
if (ids.length && startIndex === 0 && existsSync(dir)) {
|
|
@@ -1536,6 +1787,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1536
1787
|
}
|
|
1537
1788
|
|
|
1538
1789
|
captureSession(session) {
|
|
1790
|
+
if (this.standDown?.()) return new Set();
|
|
1539
1791
|
const key = session?.id || DEFAULT_KEY;
|
|
1540
1792
|
const events = session?.snapshotEvents?.() || [];
|
|
1541
1793
|
const fingerprint = this.captureRecoveryFingerprint(session, events);
|
|
@@ -1592,6 +1844,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1592
1844
|
}
|
|
1593
1845
|
|
|
1594
1846
|
ensurePruneGuard() {
|
|
1847
|
+
if (this.standDown?.()) return;
|
|
1595
1848
|
if (this.pruneGuarded) return;
|
|
1596
1849
|
let pruner;
|
|
1597
1850
|
try {
|
|
@@ -1609,6 +1862,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1609
1862
|
function guarded(session) {
|
|
1610
1863
|
const engine = pruner.__spineEngine;
|
|
1611
1864
|
try {
|
|
1865
|
+
if (engine.standDown?.()) return;
|
|
1612
1866
|
engine.captureSession(session);
|
|
1613
1867
|
return runPruneAfterCapture(engine.surfaceToolIds(session), engine.rawVerifiedSet(session), () => original(session));
|
|
1614
1868
|
} catch (error) {
|
|
@@ -1651,6 +1905,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1651
1905
|
access = {},
|
|
1652
1906
|
rotationIO = {},
|
|
1653
1907
|
) {
|
|
1908
|
+
if (this.standDown?.()) return { ok: false, reason: "stand-down" };
|
|
1654
1909
|
return saveShadowImpl.call(
|
|
1655
1910
|
this,
|
|
1656
1911
|
messages,
|
|
@@ -1672,6 +1927,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1672
1927
|
access = {},
|
|
1673
1928
|
rotationIO = {},
|
|
1674
1929
|
) {
|
|
1930
|
+
if (this.standDown?.()) return { ok: false, reason: "stand-down" };
|
|
1675
1931
|
if (!access.runner && (access.platform ?? process.platform) === "win32" && shadowAccessFused()) {
|
|
1676
1932
|
const error = new Error("spine: shadow permission already failed; backup refused");
|
|
1677
1933
|
error.code = "ESHADOWACCESS";
|
|
@@ -1767,7 +2023,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1767
2023
|
role: message?.role ?? message?.message?.role,
|
|
1768
2024
|
text: messageText(message),
|
|
1769
2025
|
})));
|
|
1770
|
-
const facts = [...
|
|
2026
|
+
const facts = [...(trunk.hardFacts || []), ...(trunk.missingFacts || [])];
|
|
1771
2027
|
const slim = buildSendLess({ taskLine, uncovered: trunk.uncovered, facts });
|
|
1772
2028
|
return this.summarizeOfficial({
|
|
1773
2029
|
...input,
|