dsh-live-compact 1.1.13 → 1.1.14
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 +9 -0
- package/README.md +11 -7
- package/adapter.js +11 -0
- package/cordis.patch.yml +1 -5
- package/gate.js +21 -12
- package/index.js +86 -16
- package/package.json +1 -1
- package/shadow-save-worker.mjs +2 -0
- package/shadow.js +267 -111
- package/shell.js +136 -22
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# 版本变更
|
|
2
2
|
|
|
3
|
+
## 1.1.14
|
|
4
|
+
|
|
5
|
+
- #51 在已有 shadow 根记录轮末维护何时开始、延期、结束或取消,以及本次提交的小切数。状态日志保留最近 256 KiB 的完整记录。
|
|
6
|
+
- #56 宿主拒绝无效的模型压缩预算时,即使尚未备份工具结果,也会尝试将拒绝原因写进私有决策日志。每个会话只去重已经写入的拒绝。
|
|
7
|
+
- #73 在 POSIX 上读回备份权限。目录须为 0700,文件须为 0600。正文和捕获游标写入前核对打开的文件身份及权限,不符时拒绝备份并保留原文。
|
|
8
|
+
- #71 用统计锁串行更新逐刀明细。每个 shadow 根最多保留 1 MiB 最新完整记录,累计统计继续保存在 `spine-stats.json`。
|
|
9
|
+
- #72 同一备份根可分别恢复多个已确认进程退出的锁。记录按完整锁身份保存,原锁及已有恢复记录保留。进程仍存活或无法确认时继续拒绝备份并记录原因。
|
|
10
|
+
- #74 兼容使用根上下文符号的 DSH/Cordis。Live Compact 完成初始化后才移交宿主原版压缩,激活失败会保留原版并记录原因,停用后按原配置恢复。
|
|
11
|
+
|
|
3
12
|
## 1.1.13
|
|
4
13
|
|
|
5
14
|
- 已执行工具的任务触及单步输出上限后,宿主队列可继续原任务。若首次续接只有思考输出并再次触顶,插件会最后续接一次,提示模型从小工具调用开始。归档保留每次截断和续接的结束状态。
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
一段对话做久了,读过的日志、跑过的命令和工具输出会越积越多。Live Compact 会在每轮结束时检查,能安全收短的长输出就整理一下。这一步在本机做,无需再请求模型。只替换选中的一段,切点前面的内容保持原样。整理前会备份原文,备份失败就保留原来的内容。
|
|
4
4
|
|
|
5
|
-
当前稳定版 [v1.1.
|
|
5
|
+
当前稳定版 [v1.1.14](https://github.com/Tranquillitatis-Lab/dsh-live-compact/releases/tag/v1.1.14)。版本变更见 [CHANGELOG.md](CHANGELOG.md)。
|
|
6
6
|
|
|
7
7
|
## 测评实证
|
|
8
8
|
|
|
@@ -33,13 +33,13 @@
|
|
|
33
33
|
headless:
|
|
34
34
|
|
|
35
35
|
```sh
|
|
36
|
-
dsh plugin --profile headless add dsh-live-compact@1.1.
|
|
36
|
+
dsh plugin --profile headless add dsh-live-compact@1.1.14
|
|
37
37
|
```
|
|
38
38
|
|
|
39
39
|
网页端:
|
|
40
40
|
|
|
41
41
|
```sh
|
|
42
|
-
dsh plugin --profile web add dsh-live-compact@1.1.
|
|
42
|
+
dsh plugin --profile web add dsh-live-compact@1.1.14
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
想先装到本机看版本:
|
|
@@ -120,7 +120,7 @@ Issue #19 里下一轮输入回到 21 万到 24 万、前缀被打掉的那一
|
|
|
120
120
|
- 预设不再硬等 gate。gate 加载失败时,网页预设不会卡在等待。换包前先试加载,失败就保留原版名字。
|
|
121
121
|
- 换上之后带上 0.8、65536、8192。预设里已有的配置优先。
|
|
122
122
|
- 预设 id 写在外层或内层都能换。standard、ptc、cordis、minimal 在 0.2.1-rc.5 上都会换。TUI 仍不碰。
|
|
123
|
-
-
|
|
123
|
+
- 原版压缩已启用时,Live Compact 初始化完成后才接管。激活失败会保留原版,并记下「本会话未接管」。如果旧的 profile 用户补丁另外关闭了 `compaction-basic`,可在宿主的插件管理中重新启用它。两种引擎都装不上时,外壳会报告失败原因。
|
|
124
124
|
- headless 的宿主包自己关掉了原版压缩。插件不能把那一行重新打开。网页预设不注入 gate,漏换这一轮就继续用原版。
|
|
125
125
|
|
|
126
126
|
## Windows 备份权限
|
|
@@ -191,8 +191,8 @@ Windows 会重新设置备份访问权限,失败时停止写备份并保留原
|
|
|
191
191
|
从 npm 装。headless 和网页是两个 profile,要各装一次。桌面端是另一个 profile,普通 `dsh plugin --profile desktop` 会被拒绝。
|
|
192
192
|
|
|
193
193
|
```sh
|
|
194
|
-
dsh plugin --profile headless add dsh-live-compact@1.1.
|
|
195
|
-
dsh plugin --profile web add dsh-live-compact@1.1.
|
|
194
|
+
dsh plugin --profile headless add dsh-live-compact@1.1.14
|
|
195
|
+
dsh plugin --profile web add dsh-live-compact@1.1.14
|
|
196
196
|
```
|
|
197
197
|
|
|
198
198
|
想先装到本机看版本:
|
|
@@ -217,7 +217,11 @@ DSH-TUI 先不要装。本包已补预设压缩隔离组的接管;TUI 仍需
|
|
|
217
217
|
|
|
218
218
|
被切掉的原文会写到 `~/.dsh/compaction-spine/shadow`。Unix 权限为目录 0700 / 文件 0600;Windows 新建/修正后的备份允许当前用户、SYSTEM、Administrators,历史文件及缓存限制见上面的 ACL 说明。上限 256MB。快满时删最老的备份。卡片里的序号是会话日志的事件号。要在当前会话的备份里找一行,用 `import { searchShadow } from "dsh-live-compact/shadow-search"`。插件自己不会去搜。
|
|
219
219
|
|
|
220
|
-
`
|
|
220
|
+
`spine-maintenance.jsonl` 在已有 shadow 目录记录轮末维护状态。同一个 `operation` 对应一次尝试,`deferred` 表示补抓未结束,`completed` 的 `cuts` 是该次提交的小切数。宿主拒绝模型压力预算时,配置原因会写入 `spine-decisions.jsonl`。
|
|
221
|
+
|
|
222
|
+
`dsh-live-compact stats` 的 `saved` 是切完当下少掉的 token,`rewrite` 是同一次收尾实际要重写的尾巴,只记一次。同一步连切不会按刀数把尾巴乘上去。这两个数口径不同,比值不是盈亏。桌面端没有终端,`rg "spine cut"` 只在终端输出里找得到。每个 shadow 根的 `spine-cuts.jsonl` 最多保留 1 MiB 最近的完整逐刀明细,累计计数记录在 `spine-stats.json`。
|
|
223
|
+
|
|
224
|
+
POSIX 备份目录所在的文件系统须实际强制 0700/0600 权限。插件会读回目录及文件的权限,并在写正文前拒绝权限不符的备份。
|
|
221
225
|
|
|
222
226
|
改上限:
|
|
223
227
|
|
package/adapter.js
CHANGED
|
@@ -6,6 +6,17 @@
|
|
|
6
6
|
|
|
7
7
|
export const STOCK_ENGINE = "@deepseek-ai/dsh-compaction-basic";
|
|
8
8
|
|
|
9
|
+
const ROOT = Symbol.for("cordis.root");
|
|
10
|
+
|
|
11
|
+
export function contextProperty(ctx, key) {
|
|
12
|
+
try { return ctx?.[key]; } catch { return undefined; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function rootContext(ctx) {
|
|
16
|
+
const root = contextProperty(ctx, ROOT) ?? contextProperty(ctx, "root") ?? ctx;
|
|
17
|
+
return root && (typeof root === "object" || typeof root === "function") ? root : undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
9
20
|
export const loadBase = () => import("@deepseek-ai/dsh-compaction-basic");
|
|
10
21
|
|
|
11
22
|
export const loadCompaction = () => import("@deepseek-ai/dsh-compaction");
|
package/cordis.patch.yml
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
#
|
|
2
|
-
# The entry installs its preset listener before constructing the engine.
|
|
1
|
+
# Keep the host stock entry available until Live Compact has activated.
|
|
3
2
|
# takeoverPresets controls future preset loads, not existing session engines.
|
|
4
|
-
- id: compaction-basic
|
|
5
|
-
name: '@deepseek-ai/dsh-compaction-basic'
|
|
6
|
-
disabled: true
|
|
7
3
|
- insert:
|
|
8
4
|
- id: compaction-spine
|
|
9
5
|
name: dsh-live-compact
|
package/gate.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { STOCK_ENGINE as STOCK } from "./adapter.js";
|
|
2
|
+
import { contextProperty, rootContext, STOCK_ENGINE as STOCK } from "./adapter.js";
|
|
3
3
|
import { configSnapshot, engineConfig } from "./settings.js";
|
|
4
4
|
|
|
5
5
|
const OURS = "dsh-live-compact";
|
|
@@ -19,7 +19,7 @@ export const PRESET_ENGINE_CONFIG = Object.freeze(engineConfig());
|
|
|
19
19
|
export function activeCompactionPeers(ctx) {
|
|
20
20
|
const peers = [];
|
|
21
21
|
if (process.env.SPINE_STAND_DOWN === "1") peers.push("SPINE_STAND_DOWN");
|
|
22
|
-
const registry = ctx
|
|
22
|
+
const registry = contextProperty(ctx, "registry");
|
|
23
23
|
if (!registry || typeof registry.values !== "function") return peers;
|
|
24
24
|
try {
|
|
25
25
|
for (const runtime of registry.values()) {
|
|
@@ -40,10 +40,10 @@ export function compactionStandDown(ctx) {
|
|
|
40
40
|
return activeCompactionPeers(ctx).length > 0;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
export function warnCompactionStandDown(ctx, logger = ctx
|
|
43
|
+
export function warnCompactionStandDown(ctx, logger = contextProperty(ctx, "logger")) {
|
|
44
44
|
const peers = activeCompactionPeers(ctx);
|
|
45
45
|
if (!peers.length) return peers;
|
|
46
|
-
const root = ctx
|
|
46
|
+
const root = rootContext(ctx);
|
|
47
47
|
const key = peers.join(",");
|
|
48
48
|
if (root && standDownNotices.get(root) === key) return peers;
|
|
49
49
|
if (root) standDownNotices.set(root, key);
|
|
@@ -188,21 +188,20 @@ const installedGates = new WeakMap();
|
|
|
188
188
|
|
|
189
189
|
function entryDepth(ctx) {
|
|
190
190
|
let depth = 0;
|
|
191
|
-
for (let fiber = ctx
|
|
191
|
+
for (let fiber = contextProperty(ctx, "fiber"); fiber?.runtime; fiber = contextProperty(fiber.parent, "fiber")) depth++;
|
|
192
192
|
return depth;
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
export function installPresetGate(ctx, config = {}, { legacy = false } = {}) {
|
|
195
|
+
export function installPresetGate(ctx, config = {}, { legacy = false, deferCommit = false } = {}) {
|
|
196
196
|
const depth = entryDepth(ctx);
|
|
197
|
-
const
|
|
197
|
+
const root = rootContext(ctx);
|
|
198
|
+
if (!root) throw new Error("spine: Cordis root context unavailable");
|
|
199
|
+
const previous = installedGates.get(root);
|
|
198
200
|
if (previous) {
|
|
199
201
|
if (legacy && !previous.legacy) return;
|
|
200
202
|
if (legacy === previous.legacy && (depth > previous.depth || (depth === previous.depth && previous.active))) return;
|
|
201
|
-
previous.active = false;
|
|
202
|
-
previous.disposeListener?.();
|
|
203
203
|
}
|
|
204
|
-
const gate = { depth, legacy, active:
|
|
205
|
-
installedGates.set(ctx.root, gate);
|
|
204
|
+
const gate = { depth, legacy, active: false };
|
|
206
205
|
ctx.effect(() => () => { gate.active = false; });
|
|
207
206
|
const enabled = () => {
|
|
208
207
|
const value = config.takeoverPresets ?? true;
|
|
@@ -211,11 +210,11 @@ export function installPresetGate(ctx, config = {}, { legacy = false } = {}) {
|
|
|
211
210
|
const seen = new Set();
|
|
212
211
|
gate.disposeListener = ctx.on("internal/config", function (fiber, next) {
|
|
213
212
|
const resolved = next();
|
|
213
|
+
if (!gate.active) return resolved;
|
|
214
214
|
if (compactionStandDown(ctx)) {
|
|
215
215
|
warnCompactionStandDown(ctx);
|
|
216
216
|
return resolved;
|
|
217
217
|
}
|
|
218
|
-
if (!gate.active) return resolved;
|
|
219
218
|
const selector = enabled();
|
|
220
219
|
if (!selector || (Array.isArray(selector) && selector.length === 0)) return resolved;
|
|
221
220
|
const loadable = packageLoadable();
|
|
@@ -236,6 +235,16 @@ export function installPresetGate(ctx, config = {}, { legacy = false } = {}) {
|
|
|
236
235
|
}
|
|
237
236
|
return rewritten;
|
|
238
237
|
}, { global: true });
|
|
238
|
+
const commit = () => {
|
|
239
|
+
installedGates.set(root, gate);
|
|
240
|
+
gate.active = true;
|
|
241
|
+
if (previous) {
|
|
242
|
+
previous.active = false;
|
|
243
|
+
try { previous.disposeListener?.()?.catch?.(() => {}); } catch {}
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
if (deferCommit) return commit;
|
|
247
|
+
commit();
|
|
239
248
|
}
|
|
240
249
|
|
|
241
250
|
// Legacy entry for existing compositions; new installs only register compaction-spine.
|
package/index.js
CHANGED
|
@@ -19,19 +19,23 @@ import { setImmediate as scheduleImmediate } from "node:timers";
|
|
|
19
19
|
import { Worker } from "node:worker_threads";
|
|
20
20
|
import { basename, dirname, join, resolve as resolvePath } from "node:path";
|
|
21
21
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
22
|
-
import { loadBase, loadCompaction, loadLlm } from "./adapter.js";
|
|
22
|
+
import { contextProperty, loadBase, loadCompaction, loadLlm, rootContext } 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
|
+
ensureShadowDirIdentity,
|
|
28
29
|
appendDecision,
|
|
30
|
+
appendMaintenanceStatus,
|
|
31
|
+
directoryIdentity,
|
|
29
32
|
flushDrainStats,
|
|
30
33
|
noteShadowWarning,
|
|
31
34
|
recoverTimedOutShadowWorker,
|
|
32
35
|
saveShadowTransaction,
|
|
33
36
|
shadowDirectory,
|
|
34
37
|
shadowFileBody,
|
|
38
|
+
shadowFileIdentity,
|
|
35
39
|
shadowMaxBytes,
|
|
36
40
|
sessionDir,
|
|
37
41
|
shadowAccessFused,
|
|
@@ -45,6 +49,31 @@ import { activeCompactionPeers, warnCompactionStandDown } from "./gate.js";
|
|
|
45
49
|
|
|
46
50
|
const PI_AI_CATALOG = "@earendil-works/pi-ai/providers/all";
|
|
47
51
|
const PI_AI_PACKAGE = "@earendil-works/pi-ai";
|
|
52
|
+
|
|
53
|
+
function startMaintenanceStatus(state, turn, turnEndSeq) {
|
|
54
|
+
const hasTurn = Number.isSafeInteger(turn) && turn >= 0;
|
|
55
|
+
const hasEnd = Number.isSafeInteger(turnEndSeq) && turnEndSeq >= 0;
|
|
56
|
+
if (!hasTurn && !hasEnd) return null;
|
|
57
|
+
const observation = {
|
|
58
|
+
sid: state.key,
|
|
59
|
+
operation: randomUUID(),
|
|
60
|
+
turn: hasTurn ? turn : null,
|
|
61
|
+
turnEndSeq: hasEnd ? turnEndSeq : null,
|
|
62
|
+
cuts: 0,
|
|
63
|
+
};
|
|
64
|
+
appendMaintenanceStatus(shadowDirectory(), { ...observation, result: "started" });
|
|
65
|
+
return observation;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function endMaintenanceStatus(observation, outcome, signal) {
|
|
69
|
+
if (!observation) return;
|
|
70
|
+
let result = "failed";
|
|
71
|
+
if (outcome === true) result = "completed";
|
|
72
|
+
else if (signal?.aborted) result = "cancelled";
|
|
73
|
+
else if (outcome === null) result = "deferred";
|
|
74
|
+
appendMaintenanceStatus(shadowDirectory(), { ...observation, result });
|
|
75
|
+
}
|
|
76
|
+
|
|
48
77
|
// DSH emits these user/message records as host bookkeeping. They are carried in
|
|
49
78
|
// the same event channel as user input, but must not fragment a compactable span.
|
|
50
79
|
// Keep unknown kinds conservative because source metadata is not authentication.
|
|
@@ -405,6 +434,9 @@ function shadowWorkerFor(root) {
|
|
|
405
434
|
}
|
|
406
435
|
const error = new Error(message?.error?.message || "spine: shadow worker failed");
|
|
407
436
|
if (message?.error?.code) error.code = message.error.code;
|
|
437
|
+
if (typeof message?.error?.step === "string" && message.error.step.length <= 64) {
|
|
438
|
+
error.step = message.error.step;
|
|
439
|
+
}
|
|
408
440
|
task.reject(error);
|
|
409
441
|
releaseShadowSlot(entry, task);
|
|
410
442
|
scheduleIdleExit();
|
|
@@ -1354,9 +1386,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1354
1386
|
if (!state.opPinCount) state.opPin = null;
|
|
1355
1387
|
}
|
|
1356
1388
|
|
|
1357
|
-
constructor(ctx, config, resolvedConfig) {
|
|
1389
|
+
constructor(ctx, config, resolvedConfig, { strictActivation = false, deferActivation = false } = {}) {
|
|
1358
1390
|
if (process.env.SPINE_ENGINE_FAIL === "construct") throw new Error("spine: constructor refused");
|
|
1359
|
-
|
|
1391
|
+
const effective = resolvedConfig ?? engineConfig(config);
|
|
1392
|
+
const waitForInit = deferActivation && (effective.auto === undefined || effective.auto === true);
|
|
1393
|
+
super(ctx, waitForInit ? { ...effective, auto: false } : effective);
|
|
1360
1394
|
this.persistCapture = true;
|
|
1361
1395
|
this.catalogPromise = loadPiAiCatalog().then((catalog) => {
|
|
1362
1396
|
this.catalogCache = catalog;
|
|
@@ -1368,6 +1402,16 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1368
1402
|
});
|
|
1369
1403
|
if (process.env.SPINE_ENGINE_FAIL === "after-super") throw new Error("spine: after super");
|
|
1370
1404
|
this.liveConfig = config;
|
|
1405
|
+
if (!deferActivation) this.registerLifecycle(ctx, strictActivation);
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
activateAfterInit(auto) {
|
|
1409
|
+
this.config = Object.freeze({ ...this.config, auto });
|
|
1410
|
+
if (auto) this._registerAutomaticCompaction();
|
|
1411
|
+
this.registerLifecycle(this.ctx, true);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
registerLifecycle(ctx, strictActivation) {
|
|
1371
1415
|
try {
|
|
1372
1416
|
ctx.effect(() => async () => {
|
|
1373
1417
|
await Promise.allSettled([...this.pendingCuts, ...this.pendingCaptures, ...this.pendingCatchupJobs]);
|
|
@@ -1448,6 +1492,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1448
1492
|
await this.runTurnStoppingMaintenance(agent, signal, turn);
|
|
1449
1493
|
});
|
|
1450
1494
|
} catch (error) {
|
|
1495
|
+
if (strictActivation) throw error;
|
|
1451
1496
|
const message = error instanceof Error ? error.message : String(error);
|
|
1452
1497
|
ctx.logger?.warn?.(`spine: 本会话未接管自动小切。${message}`);
|
|
1453
1498
|
}
|
|
@@ -1480,7 +1525,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1480
1525
|
if (!rawKey.startsWith(prefix) || !raw?.path || !liveIds.has(rawKey.slice(prefix.length))) continue;
|
|
1481
1526
|
protectPaths.push(raw.path, `${raw.path}.meta.json`);
|
|
1482
1527
|
}
|
|
1483
|
-
appendDecision(shadowDirectory(), { sid: key, ...record }, { protectPaths });
|
|
1528
|
+
return appendDecision(shadowDirectory(), { sid: key, ...record }, { protectPaths });
|
|
1484
1529
|
}
|
|
1485
1530
|
|
|
1486
1531
|
reconcileCardRawPaths(state, session) {
|
|
@@ -1637,6 +1682,8 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1637
1682
|
let job;
|
|
1638
1683
|
job = (async () => {
|
|
1639
1684
|
await null;
|
|
1685
|
+
let observation;
|
|
1686
|
+
let outcome = false;
|
|
1640
1687
|
try {
|
|
1641
1688
|
const settings = readSettings(this.liveConfig);
|
|
1642
1689
|
const events = agent.session.snapshotEvents();
|
|
@@ -1645,6 +1692,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1645
1692
|
const stoppingEnd = stoppingStartSeq === undefined || previousEnd?.seq > stoppingStartSeq
|
|
1646
1693
|
? previousEnd : null;
|
|
1647
1694
|
const stoppingSeq = stoppingEnd?.seq;
|
|
1695
|
+
observation = startMaintenanceStatus(state, turn ?? stoppingEnd?.data?.turn, stoppingSeq);
|
|
1648
1696
|
if (Number.isInteger(stoppingSeq)) {
|
|
1649
1697
|
state.turnEndSeq = Number.isInteger(state.turnEndSeq) ? Math.max(state.turnEndSeq, stoppingSeq) : stoppingSeq;
|
|
1650
1698
|
state.turnEndEvent = stoppingEnd;
|
|
@@ -1662,17 +1710,19 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
1662
1710
|
if (maintenanceAbort.signal.aborted) return false;
|
|
1663
1711
|
const stoppingTurn = agent.status === "running" && signal && Number.isSafeInteger(turn)
|
|
1664
1712
|
? turn : undefined;
|
|
1665
|
-
|
|
1713
|
+
outcome = await this.finishTurn(agent, events, {
|
|
1666
1714
|
maintenanceRetry: true,
|
|
1667
1715
|
skipCapture: true,
|
|
1668
1716
|
stoppingTurn,
|
|
1717
|
+
observation,
|
|
1669
1718
|
});
|
|
1670
|
-
if (
|
|
1719
|
+
if (outcome === true && (stoppingSeq !== undefined || stoppingStartSeq !== undefined)) {
|
|
1671
1720
|
state.lastStoppingTurnEndSeq = stoppingSeq ?? -1;
|
|
1672
1721
|
state.lastStoppingTurnStartSeq = stoppingStartSeq ?? -1;
|
|
1673
1722
|
}
|
|
1674
1723
|
if (stoppingTurn !== undefined) this.queueOutputRecovery(agent, signal, stoppingTurn, events);
|
|
1675
1724
|
} finally {
|
|
1725
|
+
endMaintenanceStatus(observation, outcome, maintenanceAbort.signal);
|
|
1676
1726
|
this.unpinLiveAgent(state);
|
|
1677
1727
|
signal?.removeEventListener("abort", forwardAbort);
|
|
1678
1728
|
this.pendingCuts.delete(job);
|
|
@@ -2139,9 +2189,15 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2139
2189
|
const ownedAbort = state.maintenanceAbort ? null : new AbortController();
|
|
2140
2190
|
if (ownedAbort) state.maintenanceAbort = ownedAbort;
|
|
2141
2191
|
const signal = AbortSignal.any([AbortSignal.timeout(30000), state.maintenanceAbort.signal]);
|
|
2192
|
+
let observation = options.observation;
|
|
2193
|
+
let outcome = false;
|
|
2142
2194
|
try {
|
|
2143
2195
|
let maintenanceCompleted = false;
|
|
2144
2196
|
const ev = events || agent.session.snapshotEvents();
|
|
2197
|
+
if (!observation) {
|
|
2198
|
+
const boundary = latestCompletedTurnEnd(ev) || state.turnEndEvent;
|
|
2199
|
+
observation = startMaintenanceStatus(state, boundary?.data?.turn, boundary?.seq);
|
|
2200
|
+
}
|
|
2145
2201
|
const deferCapture = options.deferCapture === true;
|
|
2146
2202
|
let catchup = { finished: true, progressed: false, retryRequested: false };
|
|
2147
2203
|
if (options.skipCapture) {
|
|
@@ -2172,6 +2228,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2172
2228
|
if (options.maintenanceRetry || (!deferCapture && ev.length <= CAPTURE_EVENT_BATCH)) {
|
|
2173
2229
|
await catchup.promise;
|
|
2174
2230
|
} else {
|
|
2231
|
+
outcome = null;
|
|
2175
2232
|
return null;
|
|
2176
2233
|
}
|
|
2177
2234
|
}
|
|
@@ -2340,6 +2397,7 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2340
2397
|
}
|
|
2341
2398
|
if (!drain) break;
|
|
2342
2399
|
}
|
|
2400
|
+
if (observation) observation.cuts = drainNotes.filter((note) => note.kind === "cut" && note.saved > 0).length;
|
|
2343
2401
|
if (drainNotes.length) flushDrainStats(shadowDirectory(), drainNotes, { sid: state.key, drain });
|
|
2344
2402
|
state.turnBase = measurement.totalTokens;
|
|
2345
2403
|
state.maxTurnGrowth = 0;
|
|
@@ -2356,9 +2414,11 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2356
2414
|
} finally {
|
|
2357
2415
|
state.localOnly = false;
|
|
2358
2416
|
}
|
|
2359
|
-
|
|
2417
|
+
outcome = maintenanceCompleted;
|
|
2418
|
+
return outcome;
|
|
2360
2419
|
} finally {
|
|
2361
2420
|
if (ownedAbort && state.maintenanceAbort === ownedAbort) state.maintenanceAbort = null;
|
|
2421
|
+
if (!options.observation) endMaintenanceStatus(observation, outcome, signal);
|
|
2362
2422
|
}
|
|
2363
2423
|
}
|
|
2364
2424
|
|
|
@@ -2563,16 +2623,17 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2563
2623
|
return result;
|
|
2564
2624
|
} catch (error) {
|
|
2565
2625
|
if (error instanceof Error && error.constructor.name === "TargetPressureConfigError" &&
|
|
2566
|
-
state.reportedPressureConfigError !== error.message
|
|
2567
|
-
state.reportedPressureConfigError = error.message;
|
|
2626
|
+
state.reportedPressureConfigError !== error.message) {
|
|
2568
2627
|
try {
|
|
2569
|
-
|
|
2628
|
+
ensureShadowDir(shadowDirectory());
|
|
2629
|
+
const recorded = this.recordDecision(state, {
|
|
2570
2630
|
phase: "official-compaction",
|
|
2571
2631
|
trigger,
|
|
2572
2632
|
result: "rejected",
|
|
2573
2633
|
reason: "invalid-pressure-config",
|
|
2574
2634
|
detail: error.message,
|
|
2575
2635
|
});
|
|
2636
|
+
if (recorded) state.reportedPressureConfigError = error.message;
|
|
2576
2637
|
} catch {}
|
|
2577
2638
|
}
|
|
2578
2639
|
throw error;
|
|
@@ -2626,11 +2687,10 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2626
2687
|
}
|
|
2627
2688
|
|
|
2628
2689
|
hostService(name) {
|
|
2629
|
-
const nodes = [this.ctx, this.ctx
|
|
2690
|
+
const nodes = [this.ctx, rootContext(this.ctx), contextProperty(this.ctx, "parent")];
|
|
2630
2691
|
for (const node of nodes) {
|
|
2631
|
-
if (!node || typeof node.get !== "function") continue;
|
|
2632
2692
|
try {
|
|
2633
|
-
const hit = node
|
|
2693
|
+
const hit = node?.get?.(name);
|
|
2634
2694
|
if (hit) return hit;
|
|
2635
2695
|
} catch {}
|
|
2636
2696
|
}
|
|
@@ -2988,25 +3048,35 @@ export default class SpineCompactionEngine extends BasicCompactionEngine {
|
|
|
2988
3048
|
if (this.persistCapture !== true || !Number.isSafeInteger(cursor) || cursor < 0) return;
|
|
2989
3049
|
let tmp;
|
|
2990
3050
|
let fd;
|
|
3051
|
+
let tmpIdentity = "";
|
|
2991
3052
|
try {
|
|
2992
3053
|
ensureShadowDir(shadowDirectory(), access);
|
|
2993
3054
|
const file = this.captureCursorFile(key);
|
|
2994
3055
|
// Cursor metadata is outside the payload cap and needs no rotation lock.
|
|
2995
3056
|
// Secure the parent first so Windows temps inherit its private ACL.
|
|
2996
|
-
|
|
3057
|
+
const parent = dirname(file);
|
|
3058
|
+
const parentIdentity = ensureShadowDirIdentity(parent, access);
|
|
2997
3059
|
const candidate = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
2998
3060
|
fd = openSync(candidate, "wx", 0o600);
|
|
2999
3061
|
tmp = candidate;
|
|
3000
|
-
tightenCreatedShadow(tmp, fd, access, { remember: false });
|
|
3062
|
+
tmpIdentity = tightenCreatedShadow(tmp, fd, access, { remember: false });
|
|
3063
|
+
if (parentIdentity && directoryIdentity(parent) !== parentIdentity) {
|
|
3064
|
+
throw Object.assign(new Error("spine: capture cursor directory identity changed"), { code: "ESHADOWACCESS", step: "dir" });
|
|
3065
|
+
}
|
|
3001
3066
|
writeFileSync(fd, JSON.stringify({ v: 1, key, cursor }));
|
|
3002
3067
|
closeSync(fd);
|
|
3003
3068
|
fd = undefined;
|
|
3069
|
+
if (shadowFileIdentity(tmp) !== tmpIdentity) {
|
|
3070
|
+
throw Object.assign(new Error("spine: capture cursor temp identity changed"), { code: "ESHADOWACCESS", step: "file" });
|
|
3071
|
+
}
|
|
3004
3072
|
renameSync(tmp, file);
|
|
3073
|
+
tmp = undefined;
|
|
3005
3074
|
} catch (error) {
|
|
3006
3075
|
noteShadowWarning(this.ctx?.logger, error);
|
|
3007
3076
|
} finally {
|
|
3077
|
+
if (tmp && fd !== undefined && !tmpIdentity) tmpIdentity = shadowFileIdentity(tmp, fd);
|
|
3008
3078
|
if (fd !== undefined) { try { closeSync(fd); } catch {} }
|
|
3009
|
-
if (tmp) { try { unlinkSync(tmp); } catch {} }
|
|
3079
|
+
if (tmp && tmpIdentity && shadowFileIdentity(tmp) === tmpIdentity) { try { unlinkSync(tmp); } catch {} }
|
|
3010
3080
|
}
|
|
3011
3081
|
}
|
|
3012
3082
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-live-compact",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.14",
|
|
4
4
|
"description": "In-place newest-turn compaction for DeepSeek Harness. Compress while the task runs and keep the prefix.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "MerkyorLynn <268568828+MerkyorLynn@users.noreply.github.com>",
|
package/shadow-save-worker.mjs
CHANGED
|
@@ -26,10 +26,12 @@ async function handle(id, payload) {
|
|
|
26
26
|
const result = saveShadowTransaction(normalizeShadowBody(payload));
|
|
27
27
|
parentPort.postMessage({ id, ok: true, result });
|
|
28
28
|
} catch (error) {
|
|
29
|
+
const step = error?.step || error?.cause?.step;
|
|
29
30
|
parentPort.postMessage({ id, ok: false, error: {
|
|
30
31
|
name: error?.name || "Error",
|
|
31
32
|
message: error?.message || String(error),
|
|
32
33
|
code: error?.code,
|
|
34
|
+
step: typeof step === "string" && step.length <= 64 ? step : undefined,
|
|
33
35
|
} });
|
|
34
36
|
}
|
|
35
37
|
}
|
package/shadow.js
CHANGED
|
@@ -15,9 +15,9 @@ import { workerData } from "node:worker_threads";
|
|
|
15
15
|
import {
|
|
16
16
|
constants as fsConstants,
|
|
17
17
|
chmodSync,
|
|
18
|
-
appendFileSync,
|
|
19
18
|
closeSync,
|
|
20
19
|
existsSync,
|
|
20
|
+
fchmodSync,
|
|
21
21
|
fstatSync,
|
|
22
22
|
fsyncSync,
|
|
23
23
|
linkSync,
|
|
@@ -88,7 +88,7 @@ function realDirectory(dir) {
|
|
|
88
88
|
return realpathSync.native(dir);
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
function directoryIdentity(dir) {
|
|
91
|
+
export function directoryIdentity(dir) {
|
|
92
92
|
const info = statSync(dir, { bigint: true });
|
|
93
93
|
if (!info.isDirectory() || info.ino <= 0n) return "";
|
|
94
94
|
return `${info.dev}:${info.ino}`;
|
|
@@ -293,6 +293,18 @@ function hasLinklessRecovery(root, record) {
|
|
|
293
293
|
}
|
|
294
294
|
}
|
|
295
295
|
|
|
296
|
+
function publishLinklessRecovery(root, record) {
|
|
297
|
+
let fd;
|
|
298
|
+
try {
|
|
299
|
+
fd = openSync(join(root, linklessRecoveryName(record)), "wx", 0o600);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (error?.code === "EEXIST" && hasLinklessRecovery(root, record)) return;
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
305
|
+
if (!hasLinklessRecovery(root, record)) throw new Error("shadow recovery fence disappeared");
|
|
306
|
+
}
|
|
307
|
+
|
|
296
308
|
function verifyRotationGuard(root, identity, guard) {
|
|
297
309
|
if (identity && directoryIdentity(root) !== identity) throw new Error("shadow directory identity changed");
|
|
298
310
|
if (!guard.record) {
|
|
@@ -368,21 +380,36 @@ function recoverRotationGuard(root, identity, guard) {
|
|
|
368
380
|
try { recovery = readRotationRecord(recovered); } catch (error) {
|
|
369
381
|
if (error?.code !== "ENOENT") throw error;
|
|
370
382
|
}
|
|
371
|
-
|
|
372
|
-
const knownDead =
|
|
383
|
+
const priorRecovery = recovery && sameRotationRecord(recovery, guard.record);
|
|
384
|
+
const knownDead = priorRecovery || hasLinklessRecovery(root, guard.record);
|
|
373
385
|
if (!knownDead) {
|
|
374
386
|
let dead = false;
|
|
375
387
|
try { process.kill(guard.record.pid, 0); } catch (error) { dead = error?.code === "ESRCH"; }
|
|
376
|
-
if (!dead)
|
|
388
|
+
if (!dead) {
|
|
389
|
+
if (recovery) {
|
|
390
|
+
throw Object.assign(new Error("shadow recovery identity changed"), { step: "rotation-recovery-conflict" });
|
|
391
|
+
}
|
|
392
|
+
throw new Error("shadow holder is live or its death is unknown");
|
|
393
|
+
}
|
|
377
394
|
}
|
|
378
395
|
// Persist shared participation BEFORE permitting any action or recording
|
|
379
396
|
// recovery. A later reused PID cannot resurrect this exact proven-dead token.
|
|
380
397
|
persistRotationShared(root);
|
|
381
398
|
verifyRotationGuard(root, identity, guard);
|
|
382
399
|
if (!knownDead) {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
400
|
+
if (recovery) {
|
|
401
|
+
publishLinklessRecovery(root, guard.record);
|
|
402
|
+
} else {
|
|
403
|
+
try {
|
|
404
|
+
publishRotationRecord(recovered, guard.record);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (error?.code === "ESHADOWLINKUNSUPPORTED" ||
|
|
407
|
+
(error?.code === "EEXIST" && !sameRotationRecord(readRotationRecord(recovered), guard.record))) {
|
|
408
|
+
publishLinklessRecovery(root, guard.record);
|
|
409
|
+
} else if (error?.code !== "EEXIST") {
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
386
413
|
}
|
|
387
414
|
syncRotationDirectory(root);
|
|
388
415
|
}
|
|
@@ -628,7 +655,7 @@ function accessEntry(path, kind) {
|
|
|
628
655
|
if (kind === "dir" ? !info.isDirectory() : !info.isFile() || info.nlink !== 1n) {
|
|
629
656
|
throw new Error("spine: unsupported shadow permission target");
|
|
630
657
|
}
|
|
631
|
-
return { absolute, canonical, identity: accessIdentity(info) };
|
|
658
|
+
return { absolute, canonical, identity: accessIdentity(info), mode: info.mode };
|
|
632
659
|
}
|
|
633
660
|
|
|
634
661
|
function sameAccessEntry(left, right) {
|
|
@@ -649,10 +676,12 @@ export function shadowDirLocked(path) {
|
|
|
649
676
|
|
|
650
677
|
export function noteShadowWarning(logger, error) {
|
|
651
678
|
const code = error?.code || "ESHADOWACCESS";
|
|
652
|
-
if (shadowWarnings.has(code)) return;
|
|
653
|
-
shadowWarnings.add(code);
|
|
654
|
-
const status = error?.cause?.status ?? error?.status;
|
|
655
679
|
const step = error?.step || error?.cause?.step || "";
|
|
680
|
+
const separateReason = step === "rotation-recovery-conflict" || step === "dir-mode" || step === "file-mode";
|
|
681
|
+
const key = separateReason ? `${code}:${step}` : code;
|
|
682
|
+
if (shadowWarnings.has(key)) return;
|
|
683
|
+
shadowWarnings.add(key);
|
|
684
|
+
const status = error?.cause?.status ?? error?.status;
|
|
656
685
|
const where = step ? ` ${step}` : "";
|
|
657
686
|
const exit = status == null ? "" : ` exit ${status}`;
|
|
658
687
|
logger?.warn?.(`spine: shadow permission failed ${code}${where}${exit}`);
|
|
@@ -699,6 +728,9 @@ export function shadowFileBody(sessionKey, body) {
|
|
|
699
728
|
export const STATS_NAME = "spine-stats.json";
|
|
700
729
|
export const CUTS_NAME = "spine-cuts.jsonl";
|
|
701
730
|
export const DECISIONS_NAME = "spine-decisions.jsonl";
|
|
731
|
+
export const MAINTENANCE_NAME = "spine-maintenance.jsonl";
|
|
732
|
+
const CUTS_LOG_MAX_BYTES = 1024 * 1024;
|
|
733
|
+
const MAINTENANCE_LOG_MAX_BYTES = 256 * 1024;
|
|
702
734
|
|
|
703
735
|
export function appendDecision(dir, record = {}, { protectPaths = [] } = {}) {
|
|
704
736
|
try {
|
|
@@ -888,11 +920,134 @@ function acquireStatsLock(lock) {
|
|
|
888
920
|
return null;
|
|
889
921
|
}
|
|
890
922
|
|
|
923
|
+
function withCutStatsLock(dir, action) {
|
|
924
|
+
const lock = join(dir, "spine-stats.lock");
|
|
925
|
+
const fd = acquireStatsLock(lock);
|
|
926
|
+
if (fd === null) return null;
|
|
927
|
+
try {
|
|
928
|
+
return action();
|
|
929
|
+
} catch {
|
|
930
|
+
return null;
|
|
931
|
+
} finally {
|
|
932
|
+
try { closeSync(fd); } catch {}
|
|
933
|
+
try { unlinkSync(lock); } catch {}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function completeLogSuffix(bytes, discardFirst) {
|
|
938
|
+
const first = discardFirst ? bytes.indexOf(0x0a) + 1 : 0;
|
|
939
|
+
const end = bytes.lastIndexOf(0x0a) + 1;
|
|
940
|
+
if ((discardFirst && !first) || end <= first) return Buffer.alloc(0);
|
|
941
|
+
return bytes.subarray(first, end);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function logSuffix(fd, size, budget) {
|
|
945
|
+
// Include one byte before the retained range to recognize an exact line boundary.
|
|
946
|
+
const offset = Math.max(0, size - budget - 1);
|
|
947
|
+
const bytes = Buffer.alloc(size - offset);
|
|
948
|
+
let read = 0;
|
|
949
|
+
while (read < bytes.length) {
|
|
950
|
+
const count = readSync(fd, bytes, read, bytes.length - read, offset + read);
|
|
951
|
+
if (!count) break;
|
|
952
|
+
read += count;
|
|
953
|
+
}
|
|
954
|
+
return completeLogSuffix(bytes.subarray(0, read), size > budget);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function verifyLogFile(file, observed) {
|
|
958
|
+
const named = lstatSync(file, { bigint: true });
|
|
959
|
+
if (!named.isFile() || named.nlink !== 1n || !observed.isFile() || observed.nlink !== 1n ||
|
|
960
|
+
!accessIdentity(named) || accessIdentity(named) !== accessIdentity(observed) ||
|
|
961
|
+
named.size !== observed.size || named.mtimeNs !== observed.mtimeNs || named.ctimeNs !== observed.ctimeNs) {
|
|
962
|
+
throw new Error("spine: log identity changed");
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function replaceLog(file, observed, retained, incoming) {
|
|
967
|
+
const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
968
|
+
const fd = openSync(tmp, "wx", 0o600);
|
|
969
|
+
try {
|
|
970
|
+
try {
|
|
971
|
+
writeFileSync(fd, Buffer.concat([retained, incoming]));
|
|
972
|
+
fsyncSync(fd);
|
|
973
|
+
} finally {
|
|
974
|
+
closeSync(fd);
|
|
975
|
+
}
|
|
976
|
+
verifyLogFile(file, observed);
|
|
977
|
+
renameSync(tmp, file);
|
|
978
|
+
} finally {
|
|
979
|
+
try { unlinkSync(tmp); } catch {}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function appendBoundedLog(file, body, maxBytes) {
|
|
984
|
+
const bytes = Buffer.from(body);
|
|
985
|
+
const incoming = bytes.length <= maxBytes
|
|
986
|
+
? bytes
|
|
987
|
+
: completeLogSuffix(bytes.subarray(bytes.length - maxBytes - 1), true);
|
|
988
|
+
let before;
|
|
989
|
+
try {
|
|
990
|
+
before = lstatSync(file, { bigint: true });
|
|
991
|
+
} catch (error) {
|
|
992
|
+
if (error?.code !== "ENOENT") throw error;
|
|
993
|
+
if (incoming.length) writeFileSync(file, incoming, { flag: "wx", mode: 0o600 });
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (!before.isFile() || before.nlink !== 1n) throw new Error("spine: unsupported log target");
|
|
997
|
+
const fd = openSync(file, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW ?? 0));
|
|
998
|
+
let observed;
|
|
999
|
+
let retained;
|
|
1000
|
+
try {
|
|
1001
|
+
observed = fstatSync(fd, { bigint: true });
|
|
1002
|
+
verifyLogFile(file, before);
|
|
1003
|
+
verifyLogFile(file, observed);
|
|
1004
|
+
const size = Number(observed.size);
|
|
1005
|
+
if (!Number.isSafeInteger(size)) throw new Error("spine: invalid log size");
|
|
1006
|
+
const last = Buffer.alloc(1);
|
|
1007
|
+
const complete = size === 0 || (readSync(fd, last, 0, 1, size - 1) === 1 && last[0] === 0x0a);
|
|
1008
|
+
if (complete && size + incoming.length <= maxBytes) {
|
|
1009
|
+
if (incoming.length) writeFileSync(fd, incoming);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
retained = logSuffix(fd, size, maxBytes - incoming.length);
|
|
1013
|
+
} finally {
|
|
1014
|
+
closeSync(fd);
|
|
1015
|
+
}
|
|
1016
|
+
replaceLog(file, observed, retained, incoming);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
export function appendMaintenanceStatus(dir, record) {
|
|
1020
|
+
try {
|
|
1021
|
+
if (!existsSync(dir)) return false;
|
|
1022
|
+
const root = ensureShadowDirIdentity(dir);
|
|
1023
|
+
return withCutStatsLock(dir, () => {
|
|
1024
|
+
if (!root || directoryIdentity(dir) !== root) return false;
|
|
1025
|
+
const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record });
|
|
1026
|
+
appendBoundedLog(join(dir, MAINTENANCE_NAME), `${line}\n`, MAINTENANCE_LOG_MAX_BYTES);
|
|
1027
|
+
return true;
|
|
1028
|
+
}) === true;
|
|
1029
|
+
} catch {
|
|
1030
|
+
return false;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function writeCutStats(dir, next) {
|
|
1035
|
+
const file = join(dir, STATS_NAME);
|
|
1036
|
+
const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
1037
|
+
try {
|
|
1038
|
+
writeFileSync(tmp, JSON.stringify(next));
|
|
1039
|
+
renameSync(tmp, file);
|
|
1040
|
+
return next;
|
|
1041
|
+
} finally {
|
|
1042
|
+
try { unlinkSync(tmp); } catch {}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
891
1046
|
export function flushDrainStats(dir, notes, meta = {}) {
|
|
892
1047
|
const cuts = (notes || []).filter((note) => note?.kind === "cut" && note.saved > 0);
|
|
893
1048
|
const charged = drainRewrite(notes);
|
|
894
1049
|
const saved = cuts.reduce((sum, note) => sum + note.saved, 0);
|
|
895
|
-
|
|
1050
|
+
const firstCut = (notes || []).findIndex((note) => note?.kind === "cut");
|
|
896
1051
|
const lines = (notes || []).map((note, index) => JSON.stringify({
|
|
897
1052
|
v: 1,
|
|
898
1053
|
ts: new Date().toISOString(),
|
|
@@ -901,7 +1056,7 @@ export function flushDrainStats(dir, notes, meta = {}) {
|
|
|
901
1056
|
pass: index,
|
|
902
1057
|
drain: meta.drain === true,
|
|
903
1058
|
saved: note.saved || 0,
|
|
904
|
-
rewriteCharged:
|
|
1059
|
+
rewriteCharged: index === firstCut ? charged : 0,
|
|
905
1060
|
tailBeyondKept: note.tailBeyondKept || 0,
|
|
906
1061
|
prefix: note.prefix || 0,
|
|
907
1062
|
afterPrefix: note.afterPrefix || 0,
|
|
@@ -910,69 +1065,35 @@ export function flushDrainStats(dir, notes, meta = {}) {
|
|
|
910
1065
|
gate: note.gate || "cut",
|
|
911
1066
|
}));
|
|
912
1067
|
if (!lines.length) return charged;
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
const fd = acquireStatsLock(lock);
|
|
926
|
-
if (fd === null) return null;
|
|
927
|
-
try {
|
|
928
|
-
const prev = readCutStats(dir);
|
|
929
|
-
const locked = {
|
|
930
|
-
cuts: prev.cuts + cuts,
|
|
931
|
-
savedTokens: prev.savedTokens + saved,
|
|
932
|
-
rewriteTokens: prev.rewriteTokens + rewrite,
|
|
933
|
-
drains: (Number(prev.drains) || 0) + 1,
|
|
934
|
-
updatedAt: new Date().toISOString(),
|
|
935
|
-
};
|
|
936
|
-
writeFileSync(tmp, JSON.stringify(locked));
|
|
937
|
-
renameSync(tmp, file);
|
|
938
|
-
return locked;
|
|
939
|
-
} finally {
|
|
940
|
-
try { unlinkSync(tmp); } catch {}
|
|
941
|
-
closeSync(fd);
|
|
942
|
-
try { unlinkSync(lock); } catch {}
|
|
1068
|
+
withCutStatsLock(dir, () => {
|
|
1069
|
+
if (cuts.length) {
|
|
1070
|
+
try {
|
|
1071
|
+
const prev = readCutStats(dir);
|
|
1072
|
+
writeCutStats(dir, {
|
|
1073
|
+
cuts: prev.cuts + cuts.length,
|
|
1074
|
+
savedTokens: prev.savedTokens + saved,
|
|
1075
|
+
rewriteTokens: prev.rewriteTokens + charged,
|
|
1076
|
+
drains: prev.drains + 1,
|
|
1077
|
+
updatedAt: new Date().toISOString(),
|
|
1078
|
+
});
|
|
1079
|
+
} catch {}
|
|
943
1080
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
1081
|
+
try { appendBoundedLog(join(dir, CUTS_NAME), `${lines.join("\n")}\n`, CUTS_LOG_MAX_BYTES); } catch {}
|
|
1082
|
+
});
|
|
1083
|
+
return charged;
|
|
947
1084
|
}
|
|
948
1085
|
|
|
949
1086
|
export function recordCutStats(dir, { saved = 0, rewrite = 0 } = {}) {
|
|
950
1087
|
if (!(saved > 0)) return readCutStats(dir);
|
|
951
|
-
|
|
952
|
-
const
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
cuts: prev.cuts + 1,
|
|
961
|
-
savedTokens: prev.savedTokens + saved,
|
|
962
|
-
rewriteTokens: prev.rewriteTokens + rewrite,
|
|
963
|
-
updatedAt: new Date().toISOString(),
|
|
964
|
-
};
|
|
965
|
-
writeFileSync(tmp, JSON.stringify(locked));
|
|
966
|
-
renameSync(tmp, file);
|
|
967
|
-
return locked;
|
|
968
|
-
} finally {
|
|
969
|
-
try { unlinkSync(tmp); } catch {}
|
|
970
|
-
closeSync(fd);
|
|
971
|
-
try { unlinkSync(lock); } catch {}
|
|
972
|
-
}
|
|
973
|
-
} catch {
|
|
974
|
-
return null;
|
|
975
|
-
}
|
|
1088
|
+
return withCutStatsLock(dir, () => {
|
|
1089
|
+
const prev = readCutStats(dir);
|
|
1090
|
+
return writeCutStats(dir, {
|
|
1091
|
+
cuts: prev.cuts + 1,
|
|
1092
|
+
savedTokens: prev.savedTokens + saved,
|
|
1093
|
+
rewriteTokens: prev.rewriteTokens + rewrite,
|
|
1094
|
+
updatedAt: new Date().toISOString(),
|
|
1095
|
+
});
|
|
1096
|
+
});
|
|
976
1097
|
}
|
|
977
1098
|
|
|
978
1099
|
function validWindowsSid(sid) {
|
|
@@ -1071,6 +1192,15 @@ export function shadowAccessPlan(platform = process.platform, userSid = "", kind
|
|
|
1071
1192
|
};
|
|
1072
1193
|
}
|
|
1073
1194
|
|
|
1195
|
+
function verifyPosixShadowMode(mode, expected, kind) {
|
|
1196
|
+
if ((mode & 0o777n) !== BigInt(expected)) {
|
|
1197
|
+
const actual = (mode & 0o777n).toString(8).padStart(4, "0");
|
|
1198
|
+
const error = new Error(`spine: shadow ${kind} mode ${actual} did not match ${expected.toString(8).padStart(4, "0")}`);
|
|
1199
|
+
error.step = `${kind}-mode`;
|
|
1200
|
+
throw error;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1074
1204
|
export function defaultShadowAccessRunner({
|
|
1075
1205
|
path,
|
|
1076
1206
|
kind,
|
|
@@ -1080,7 +1210,14 @@ export function defaultShadowAccessRunner({
|
|
|
1080
1210
|
} = {}) {
|
|
1081
1211
|
if (platform !== "win32") {
|
|
1082
1212
|
const plan = shadowAccessPlan(platform);
|
|
1083
|
-
|
|
1213
|
+
const expected = kind === "dir" ? plan.dirMode : plan.fileMode;
|
|
1214
|
+
const before = accessEntry(path, kind);
|
|
1215
|
+
chmodSync(before.canonical, expected);
|
|
1216
|
+
const after = accessEntry(path, kind);
|
|
1217
|
+
if (!sameAccessEntry(before, after)) {
|
|
1218
|
+
throw new Error("spine: shadow permission target identity changed");
|
|
1219
|
+
}
|
|
1220
|
+
verifyPosixShadowMode(after.mode, expected, kind);
|
|
1084
1221
|
return true;
|
|
1085
1222
|
}
|
|
1086
1223
|
|
|
@@ -1209,45 +1346,61 @@ export function ensureShadowDir(dir, access = {}) {
|
|
|
1209
1346
|
return dir;
|
|
1210
1347
|
}
|
|
1211
1348
|
|
|
1212
|
-
export function
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
throw new Error("spine: shadow published file identity changed");
|
|
1219
|
-
}
|
|
1220
|
-
if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
|
|
1221
|
-
return;
|
|
1222
|
-
} catch (cause) {
|
|
1223
|
-
tripFuse();
|
|
1224
|
-
const error = new Error("spine: shadow permission action failed; backup refused", { cause });
|
|
1225
|
-
error.code = "ESHADOWACCESS";
|
|
1226
|
-
error.step = "file";
|
|
1227
|
-
throw error;
|
|
1228
|
-
}
|
|
1349
|
+
export function ensureShadowDirIdentity(dir, access = {}) {
|
|
1350
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1351
|
+
const identity = directoryIdentity(dir);
|
|
1352
|
+
tightenShadow(dir, "dir", access);
|
|
1353
|
+
if (identity && directoryIdentity(dir) !== identity) {
|
|
1354
|
+
throw Object.assign(new Error("spine: shadow directory identity changed"), { code: "ESHADOWACCESS", step: "dir" });
|
|
1229
1355
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1356
|
+
return identity;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
function openedShadowEntry(file, fd) {
|
|
1360
|
+
const entry = accessEntry(file, "file");
|
|
1361
|
+
const opened = fstatSync(fd, { bigint: true });
|
|
1362
|
+
if (!opened.isFile() || opened.nlink !== 1n || !entry.identity || entry.identity !== accessIdentity(opened)) {
|
|
1363
|
+
throw new Error("spine: shadow created file identity changed");
|
|
1364
|
+
}
|
|
1365
|
+
return { entry, mode: opened.mode };
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
export function shadowFileIdentity(file, fd) {
|
|
1369
|
+
try {
|
|
1370
|
+
return fd === undefined ? accessEntry(file, "file").identity : openedShadowEntry(file, fd).entry.identity;
|
|
1371
|
+
} catch {
|
|
1372
|
+
return "";
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
export function tightenCreatedShadow(file, fd, access = {}, { remember = true, skipRunner = false } = {}) {
|
|
1377
|
+
const platform = access.platform ?? process.platform;
|
|
1378
|
+
const windows = platform === "win32" && !access.runner;
|
|
1379
|
+
const nativePosix = platform !== "win32" && !access.runner;
|
|
1380
|
+
try {
|
|
1381
|
+
// Only a file created under an already verified Windows parent inherits its DACL.
|
|
1382
|
+
const inherited = windows && !skipRunner && !shadowAccessFused() && shadowDirLocked(dirname(file));
|
|
1383
|
+
if (!skipRunner && !nativePosix && !inherited) tightenShadow(file, "file", access);
|
|
1384
|
+
const plan = nativePosix ? shadowAccessPlan(platform) : null;
|
|
1385
|
+
if (plan && !skipRunner) {
|
|
1386
|
+
openedShadowEntry(file, fd);
|
|
1387
|
+
fchmodSync(fd, plan.fileMode);
|
|
1388
|
+
}
|
|
1389
|
+
const { entry, mode } = openedShadowEntry(file, fd);
|
|
1390
|
+
if (plan) {
|
|
1391
|
+
verifyPosixShadowMode(mode, plan.fileMode, "file");
|
|
1392
|
+
verifyPosixShadowMode(accessEntry(dirname(file), "dir").mode, plan.dirMode, "dir");
|
|
1248
1393
|
}
|
|
1394
|
+
if (remember && (skipRunner || inherited)) rememberLockedEntry(lockedFiles, entry.canonical, entry);
|
|
1395
|
+
return entry.identity;
|
|
1396
|
+
} catch (cause) {
|
|
1397
|
+
if (cause?.code === "ESHADOWACCESS") throw cause;
|
|
1398
|
+
if (windows) tripFuse();
|
|
1399
|
+
const error = new Error("spine: shadow permission action failed; backup refused", { cause });
|
|
1400
|
+
error.code = "ESHADOWACCESS";
|
|
1401
|
+
error.step = cause?.step || "file";
|
|
1402
|
+
throw error;
|
|
1249
1403
|
}
|
|
1250
|
-
tightenShadow(file, "file", access);
|
|
1251
1404
|
}
|
|
1252
1405
|
|
|
1253
1406
|
export function discardShadowFiles(files, cause, unlink = unlinkSync) {
|
|
@@ -1320,6 +1473,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1320
1473
|
}
|
|
1321
1474
|
// Confirm ACL/mode before any secret bytes are written to the staged file.
|
|
1322
1475
|
tightenCreatedShadow(target, fd, access);
|
|
1476
|
+
rememberShadowParent(dir);
|
|
1323
1477
|
// Full replacement bytes are a conservative charge, even for overwrites,
|
|
1324
1478
|
// partial writes and failed cleanup. Metadata/owner/stats are not capacity.
|
|
1325
1479
|
if (shadowUsage && isPluginShadowName(basename(file))) {
|
|
@@ -1355,6 +1509,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1355
1509
|
closeSync(opened);
|
|
1356
1510
|
return file;
|
|
1357
1511
|
} catch (error) {
|
|
1512
|
+
const identity = fd !== null ? shadowFileIdentity(protectedPath, fd) : "";
|
|
1358
1513
|
if (fd !== null) {
|
|
1359
1514
|
try {
|
|
1360
1515
|
closeSync(fd);
|
|
@@ -1365,8 +1520,9 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1365
1520
|
// Do not unlink through a replacement directory after a failed write.
|
|
1366
1521
|
let sameParent = false;
|
|
1367
1522
|
try { sameParent = !parentIdentity || directoryIdentity(dir) === parentIdentity; } catch {}
|
|
1368
|
-
if (sameParent
|
|
1369
|
-
|
|
1523
|
+
if (sameParent && identity && shadowFileIdentity(protectedPath) === identity) {
|
|
1524
|
+
discardShadowFiles([protectedPath], error, unlink);
|
|
1525
|
+
} else shadowUsage = null;
|
|
1370
1526
|
}
|
|
1371
1527
|
throw error;
|
|
1372
1528
|
}
|
package/shell.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 薄入口。这个文件必须能求值,引擎加载失败也不能把这里抛掉。
|
|
3
3
|
* Thin entry. This file must evaluate even when the engine cannot load.
|
|
4
|
-
* A throw here leaves stock disabled and /compact waiting.
|
|
5
4
|
*
|
|
6
5
|
* 预检查只解析配置,校验交给实际引擎;构造失败时释放本次注册,不重试原版盖掉报错。
|
|
7
6
|
* Resolve config before construction; let the engine validate it and preserve its actual error.
|
|
8
7
|
*/
|
|
9
|
-
import { loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
|
|
8
|
+
import { contextProperty, loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
|
|
10
9
|
import { configSchema, engineConfig } from "./settings.js";
|
|
11
10
|
import { installPresetGate } from "./gate.js";
|
|
12
11
|
|
|
12
|
+
const CORDIS_INIT = Symbol.for("cordis.init");
|
|
13
|
+
const ISOLATE = Symbol.for("cordis.isolate");
|
|
14
|
+
|
|
13
15
|
let Engine = null;
|
|
14
16
|
let Stock = null;
|
|
15
17
|
let CompactionEngine = null;
|
|
@@ -60,14 +62,13 @@ export function preflightConfig(config = {}) {
|
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
function compactionRecord(ctx) {
|
|
63
|
-
const key = ctx?.[
|
|
65
|
+
const key = ctx?.[ISOLATE]?.compaction;
|
|
64
66
|
return key === undefined ? undefined : ctx?.reflect?.store?.[key];
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
function releaseCompaction(ctx, previous) {
|
|
69
|
+
function releaseCompaction(ctx, previous, key = ctx?.[ISOLATE]?.compaction) {
|
|
68
70
|
const store = ctx?.reflect?.store;
|
|
69
|
-
const
|
|
70
|
-
const current = compactionRecord(ctx);
|
|
71
|
+
const current = key === undefined ? undefined : store?.[key];
|
|
71
72
|
const currentFiber = current?.fiber ?? current?.ctx?.fiber;
|
|
72
73
|
const contextFiber = ctx?.fiber;
|
|
73
74
|
if (!current || current === previous || currentFiber !== contextFiber) return false;
|
|
@@ -79,7 +80,7 @@ function releaseCompaction(ctx, previous) {
|
|
|
79
80
|
function detachRootStockCompaction(ctx) {
|
|
80
81
|
const store = ctx?.reflect?.store;
|
|
81
82
|
const current = compactionRecord(ctx);
|
|
82
|
-
const key = ctx?.[
|
|
83
|
+
const key = ctx?.[ISOLATE]?.compaction;
|
|
83
84
|
const fiber = current?.fiber ?? current?.ctx?.fiber;
|
|
84
85
|
const moduleName = fiber?.entry?.options?.name;
|
|
85
86
|
if (!current || moduleName !== STOCK_ENGINE || fiber === ctx?.fiber) return false;
|
|
@@ -87,23 +88,37 @@ function detachRootStockCompaction(ctx) {
|
|
|
87
88
|
const fiberStore = fiber?.store;
|
|
88
89
|
if (fiberStore?.compaction === current) delete fiberStore.compaction;
|
|
89
90
|
delete store[key];
|
|
90
|
-
return { store, key, current, fiber, fiberStore };
|
|
91
|
+
return { store, key, current, fiber, fiberStore, uid: fiber?.uid, epoch: fiber?._runner?.epoch };
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
function commitRootStockCompaction(replacement) {
|
|
94
95
|
if (!replacement || replacement.committed) return false;
|
|
95
|
-
|
|
96
|
+
const options = replacement.fiber?.entry?.options;
|
|
97
|
+
const disabled = options && Object.getOwnPropertyDescriptor(options, "disabled");
|
|
96
98
|
try {
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
// The loader writes unrequested disposals back as disabled. Mark this
|
|
100
|
+
// synchronous notification as intentional without changing its config.
|
|
101
|
+
if (options) options.disabled = true;
|
|
102
|
+
replacement.retirement = Promise.resolve(replacement.fiber?.dispose?.());
|
|
103
|
+
replacement.retirement.catch(() => {});
|
|
104
|
+
replacement.committed = true;
|
|
105
|
+
} finally {
|
|
106
|
+
if (disabled) Object.defineProperty(options, "disabled", disabled);
|
|
107
|
+
else if (options) delete options.disabled;
|
|
108
|
+
}
|
|
102
109
|
return true;
|
|
103
110
|
}
|
|
104
111
|
|
|
105
112
|
function rollbackRootStockCompaction(replacement) {
|
|
106
113
|
if (!replacement || replacement.committed) return false;
|
|
114
|
+
const { fiber, uid, epoch, key } = replacement;
|
|
115
|
+
const entry = fiber?.entry;
|
|
116
|
+
const scope = replacement.current.ctx?.[ISOLATE];
|
|
117
|
+
if (fiber?.uid === null || fiber?.uid !== uid || fiber?._runner?.epoch !== epoch ||
|
|
118
|
+
(fiber?.state !== undefined && ![1, 2].includes(fiber.state)) ||
|
|
119
|
+
(scope && scope.compaction !== key) || entry?.disabled) return false;
|
|
120
|
+
if (entry?.parent?.tree && (!currentLoaderEntry(entry) || entry.fiber?.ctx?.fiber !== fiber ||
|
|
121
|
+
![1, 2].includes(entry.parent.ctx?.fiber?.state) || ![1, 2].includes(entry.parent.tree.ctx?.fiber?.state))) return false;
|
|
107
122
|
const current = replacement.store?.[replacement.key];
|
|
108
123
|
if (current !== undefined && current !== replacement.current) return false;
|
|
109
124
|
replacement.store[replacement.key] = replacement.current;
|
|
@@ -122,14 +137,62 @@ export function releaseRootStockCompaction(ctx, { deferDispose = false } = {}) {
|
|
|
122
137
|
replacement.rollback = () => rollbackRootStockCompaction(replacement);
|
|
123
138
|
return replacement;
|
|
124
139
|
}
|
|
125
|
-
commitRootStockCompaction(replacement);
|
|
140
|
+
try { commitRootStockCompaction(replacement); } catch (error) {
|
|
141
|
+
rollbackRootStockCompaction(replacement);
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
126
144
|
return true;
|
|
127
145
|
}
|
|
128
146
|
|
|
147
|
+
function currentLoaderEntry(entry) {
|
|
148
|
+
return entry && entry.parent?.tree?.store?.[entry.options?.id] === entry;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function configuredRootStock(ctx) {
|
|
152
|
+
const owner = ctx.fiber?.entry;
|
|
153
|
+
if (owner?.options?.id !== "compaction-spine") return undefined;
|
|
154
|
+
const stock = owner.parent?.tree?.store?.["compaction-basic"];
|
|
155
|
+
return stock?.options?.name === STOCK_ENGINE && stock.options.isolate?.compaction !== true && !stock.disabled ? stock : undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sameCompactionRealm(ctx, entry) {
|
|
159
|
+
return ctx[ISOLATE]?.compaction === entry.ctx?.[ISOLATE]?.compaction;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function activationCheck(ctx) {
|
|
163
|
+
const fiber = ctx.fiber;
|
|
164
|
+
const entry = fiber?.entry;
|
|
165
|
+
const uid = fiber?.uid;
|
|
166
|
+
const epoch = fiber?._runner?.epoch;
|
|
167
|
+
const scope = ctx[ISOLATE];
|
|
168
|
+
return () => !fiber?.runtime || (uid != null && fiber.uid === uid && fiber._runner?.epoch === epoch &&
|
|
169
|
+
ctx[ISOLATE] === scope && (!entry || (currentLoaderEntry(entry) && !entry.disabled)));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function restoreStockOnUnload(ctx, replacement) {
|
|
173
|
+
const entry = replacement.fiber?.entry;
|
|
174
|
+
if (typeof entry?.update !== "function") return;
|
|
175
|
+
const installed = compactionRecord(ctx);
|
|
176
|
+
ctx.effect(() => async () => {
|
|
177
|
+
if (!replacement.committed) return;
|
|
178
|
+
await replacement.retirement;
|
|
179
|
+
const parent = entry.parent?.ctx?.fiber;
|
|
180
|
+
const tree = entry.parent?.tree?.ctx?.fiber;
|
|
181
|
+
if (!currentLoaderEntry(entry) || entry.disabled || ![1, 2].includes(parent?.state) ||
|
|
182
|
+
![1, 2].includes(tree?.state) ||
|
|
183
|
+
entry.ctx?.[ISOLATE]?.compaction !== ctx[ISOLATE]?.compaction) return;
|
|
184
|
+
const current = compactionRecord(ctx);
|
|
185
|
+
if (current && current !== installed) return;
|
|
186
|
+
releaseCompaction(ctx, replacement.current);
|
|
187
|
+
await entry.update({}, false, true);
|
|
188
|
+
await entry.fiber?.await?.();
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
129
192
|
function visibleTakeover(ctx, reason) {
|
|
130
193
|
const line = `spine: ${MARK}。${reason}`;
|
|
131
194
|
console.error(line);
|
|
132
|
-
ctx
|
|
195
|
+
try { contextProperty(ctx, "logger")?.warn?.(line); } catch {}
|
|
133
196
|
}
|
|
134
197
|
|
|
135
198
|
const MARK = "本会话未接管";
|
|
@@ -155,11 +218,30 @@ const UnavailableCompaction = CompactionEngine
|
|
|
155
218
|
: null;
|
|
156
219
|
|
|
157
220
|
export default class LiveCompactEntry {
|
|
158
|
-
static inject = ["llm", "tokenMeter", "sessions"];
|
|
221
|
+
static inject = Stock?.inject ?? ["llm", "tokenMeter", "sessions"];
|
|
159
222
|
static Config = Schema || Stock?.Config || Engine?.Config;
|
|
160
223
|
|
|
161
224
|
constructor(ctx, config) {
|
|
162
|
-
|
|
225
|
+
const isCurrent = activationCheck(ctx);
|
|
226
|
+
const stock = configuredRootStock(ctx);
|
|
227
|
+
if (stock && (stock._initTask || (stock.fiber?.state === 1 && sameCompactionRealm(ctx, stock)))) {
|
|
228
|
+
// Loader mounts siblings in parallel. Wait for the configured stock
|
|
229
|
+
// entry to finish publishing before choosing the owner to replace.
|
|
230
|
+
return { [CORDIS_INIT]: async () => {
|
|
231
|
+
try { await stock._initTask; } catch {} // The loader reports import failures.
|
|
232
|
+
if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
|
|
233
|
+
if (sameCompactionRealm(ctx, stock)) {
|
|
234
|
+
try { await stock.fiber?.await?.(); } catch {} // The loader reports activation failures.
|
|
235
|
+
}
|
|
236
|
+
if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
|
|
237
|
+
const engine = this.activate(ctx, config, isCurrent);
|
|
238
|
+
return engine[CORDIS_INIT]?.();
|
|
239
|
+
} };
|
|
240
|
+
}
|
|
241
|
+
return this.activate(ctx, config, isCurrent);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
activate(ctx, config, isCurrent) {
|
|
163
245
|
const previousCompaction = compactionRecord(ctx);
|
|
164
246
|
let cause = loadError;
|
|
165
247
|
let resolvedConfig;
|
|
@@ -173,21 +255,53 @@ export default class LiveCompactEntry {
|
|
|
173
255
|
skipStock = true;
|
|
174
256
|
}
|
|
175
257
|
}
|
|
258
|
+
let constructed = false;
|
|
176
259
|
if (!loadError && !skipStock && Engine) {
|
|
177
260
|
let rootStockReplacement = false;
|
|
261
|
+
const rollback = () => {
|
|
262
|
+
releaseCompaction(ctx, previousCompaction, rootStockReplacement?.key);
|
|
263
|
+
rootStockReplacement?.rollback?.();
|
|
264
|
+
};
|
|
265
|
+
const commit = (engine, deferred) => {
|
|
266
|
+
if (!isCurrent()) { rollback(); return; }
|
|
267
|
+
if (deferred) engine.activateAfterInit(resolvedConfig.auto ?? true);
|
|
268
|
+
const commitGate = installPresetGate(ctx, config, { deferCommit: true });
|
|
269
|
+
if (rootStockReplacement) restoreStockOnUnload(ctx, rootStockReplacement);
|
|
270
|
+
rootStockReplacement?.commit?.();
|
|
271
|
+
commitGate?.();
|
|
272
|
+
};
|
|
178
273
|
try {
|
|
179
274
|
rootStockReplacement = releaseRootStockCompaction(ctx, { deferDispose: true });
|
|
180
|
-
|
|
181
|
-
|
|
275
|
+
if (previousCompaction && !rootStockReplacement) throw new Error("spine: compaction already provided by another engine");
|
|
276
|
+
constructed = true;
|
|
277
|
+
const deferActivation = Boolean(rootStockReplacement && typeof Engine.prototype[CORDIS_INIT] === "function");
|
|
278
|
+
const engine = new Engine(ctx, config, resolvedConfig, { strictActivation: true, deferActivation });
|
|
279
|
+
const initialize = engine[CORDIS_INIT];
|
|
280
|
+
if (typeof initialize === "function") {
|
|
281
|
+
engine[CORDIS_INIT] = async () => {
|
|
282
|
+
try {
|
|
283
|
+
const dispose = await initialize.call(engine);
|
|
284
|
+
commit(engine, deferActivation);
|
|
285
|
+
return dispose;
|
|
286
|
+
} catch (error) {
|
|
287
|
+
rollback();
|
|
288
|
+
visibleTakeover(ctx, reasonText(error));
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
} else commit(engine, deferActivation);
|
|
182
293
|
return engine;
|
|
183
294
|
} catch (error) {
|
|
184
295
|
cause = error instanceof Error ? error : new Error(String(error));
|
|
185
|
-
|
|
186
|
-
rootStockReplacement?.rollback?.();
|
|
296
|
+
rollback();
|
|
187
297
|
skipStock = true;
|
|
188
298
|
}
|
|
189
299
|
}
|
|
190
300
|
cause ??= new Error("spine: engine missing");
|
|
301
|
+
if (previousCompaction || (constructed && ctx.fiber?.runtime)) {
|
|
302
|
+
visibleTakeover(ctx, reasonText(cause));
|
|
303
|
+
throw cause;
|
|
304
|
+
}
|
|
191
305
|
if (!skipStock && process.env.SPINE_STOCK_FAIL !== "1" && Stock) {
|
|
192
306
|
try {
|
|
193
307
|
visibleTakeover(ctx, `这一轮用原版压缩。${reasonText(cause)}`);
|