dsh-live-compact 1.1.12 → 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 +19 -0
- package/README.md +16 -10
- package/adapter.js +11 -0
- package/cordis.patch.yml +1 -5
- package/gate.js +21 -12
- package/index.js +1047 -322
- package/package.json +1 -1
- package/shadow-save-worker.mjs +20 -1
- package/shadow.js +319 -117
- package/shell.js +136 -22
- package/thunder.js +13 -14
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
|
@@ -4,15 +4,34 @@ import { attachShadowAccessFuse, saveShadowTransaction } from "./shadow.js";
|
|
|
4
4
|
const managed = workerData?.spineWorker === 1;
|
|
5
5
|
if (managed) attachShadowAccessFuse(workerData.accessFuse);
|
|
6
6
|
|
|
7
|
+
// SPINE_SAVE_TRANSFER=1 moves the body across as a transferred ArrayBuffer and
|
|
8
|
+
// the arriving view is a plain Uint8Array over memory detached on the sender.
|
|
9
|
+
// Wrap it as a zero-copy Buffer view so saveShadowTransaction/writeShadowFile
|
|
10
|
+
// keep consuming bytes unchanged. String bodies (structured-clone path and the
|
|
11
|
+
// standalone workerData path) and real Buffers pass through untouched.
|
|
12
|
+
function normalizeShadowBody(payload) {
|
|
13
|
+
const body = payload?.body;
|
|
14
|
+
if (typeof body === "string" || body == null || Buffer.isBuffer(body)) return payload;
|
|
15
|
+
if (ArrayBuffer.isView(body)) {
|
|
16
|
+
return { ...payload, body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) };
|
|
17
|
+
}
|
|
18
|
+
if (body instanceof ArrayBuffer) {
|
|
19
|
+
return { ...payload, body: Buffer.from(body, 0, body.byteLength) };
|
|
20
|
+
}
|
|
21
|
+
return payload;
|
|
22
|
+
}
|
|
23
|
+
|
|
7
24
|
async function handle(id, payload) {
|
|
8
25
|
try {
|
|
9
|
-
const result = saveShadowTransaction(payload);
|
|
26
|
+
const result = saveShadowTransaction(normalizeShadowBody(payload));
|
|
10
27
|
parentPort.postMessage({ id, ok: true, result });
|
|
11
28
|
} catch (error) {
|
|
29
|
+
const step = error?.step || error?.cause?.step;
|
|
12
30
|
parentPort.postMessage({ id, ok: false, error: {
|
|
13
31
|
name: error?.name || "Error",
|
|
14
32
|
message: error?.message || String(error),
|
|
15
33
|
code: error?.code,
|
|
34
|
+
step: typeof step === "string" && step.length <= 64 ? step : undefined,
|
|
16
35
|
} });
|
|
17
36
|
}
|
|
18
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,
|
|
@@ -40,6 +40,22 @@ const PLUGIN_NAME = /^(?:(?:cut|official|shadow)-\d+-[0-9a-f]{8}|raw-[0-9a-f]{16
|
|
|
40
40
|
let cachedSid = "";
|
|
41
41
|
const lockedDirs = new Map();
|
|
42
42
|
const lockedFiles = new Map();
|
|
43
|
+
// 锁表硬上界(P1-4):两张表只是"该路径已完成 ACL 收紧"的记忆缓存,不是锁本身;
|
|
44
|
+
// 真正的锁是固化在文件/目录上的 DACL(win32)或权限位(其他平台),不受本表影响。
|
|
45
|
+
// 淘汰安全性论证:
|
|
46
|
+
// 1. 淘汰 ≠ 解锁——条目被淘汰后,下次 tightenShadow 对该路径只是重新执行一次
|
|
47
|
+
// 幂等的收紧 runner;runner 失败仍抛 ESHADOWACCESS 并触发 fuse(fail-closed),
|
|
48
|
+
// 绝不会把"拿不到锁"变成"绕过锁"。
|
|
49
|
+
// 2. 名字一次性不变式——raw 分片名 = sha256(toolCallId) 前 16 hex(raw.js rawName),
|
|
50
|
+
// cut/official/shadow 分片名含随机 hex,staging tmp 名含 randomBytes(8):
|
|
51
|
+
// 名字全局唯一、绝不复用,被淘汰的路径键不会被新文件继承,因此既不会出现
|
|
52
|
+
// "同名新文件误命中旧缓存",也不会造成同名双重加锁。
|
|
53
|
+
// 3. 即便假设发生同名重建,tightenShadow 的缓存命中还需通过 sameAccessEntry 的
|
|
54
|
+
// dev:ino:birthtimeNs 身份比对,身份不同必 miss,旧对象的 ACL 记忆绝不会套到
|
|
55
|
+
// 新对象上。
|
|
56
|
+
// 正常情况下 rotation 会随删除同步回收条目(见 releaseLockedFile),锁表规模随
|
|
57
|
+
// 磁盘存活分片数收敛;本上界 4096 只是兜底(写入失败清理路径等残留)。
|
|
58
|
+
const MAX_LOCK_ENTRIES = 4096;
|
|
43
59
|
let shadowFuseState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
44
60
|
const shadowWarnings = new Set();
|
|
45
61
|
const DECISION_ROTATION_INTERVAL_MS = 1000;
|
|
@@ -72,7 +88,7 @@ function realDirectory(dir) {
|
|
|
72
88
|
return realpathSync.native(dir);
|
|
73
89
|
}
|
|
74
90
|
|
|
75
|
-
function directoryIdentity(dir) {
|
|
91
|
+
export function directoryIdentity(dir) {
|
|
76
92
|
const info = statSync(dir, { bigint: true });
|
|
77
93
|
if (!info.isDirectory() || info.ino <= 0n) return "";
|
|
78
94
|
return `${info.dev}:${info.ino}`;
|
|
@@ -277,6 +293,18 @@ function hasLinklessRecovery(root, record) {
|
|
|
277
293
|
}
|
|
278
294
|
}
|
|
279
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
|
+
|
|
280
308
|
function verifyRotationGuard(root, identity, guard) {
|
|
281
309
|
if (identity && directoryIdentity(root) !== identity) throw new Error("shadow directory identity changed");
|
|
282
310
|
if (!guard.record) {
|
|
@@ -352,21 +380,36 @@ function recoverRotationGuard(root, identity, guard) {
|
|
|
352
380
|
try { recovery = readRotationRecord(recovered); } catch (error) {
|
|
353
381
|
if (error?.code !== "ENOENT") throw error;
|
|
354
382
|
}
|
|
355
|
-
|
|
356
|
-
const knownDead =
|
|
383
|
+
const priorRecovery = recovery && sameRotationRecord(recovery, guard.record);
|
|
384
|
+
const knownDead = priorRecovery || hasLinklessRecovery(root, guard.record);
|
|
357
385
|
if (!knownDead) {
|
|
358
386
|
let dead = false;
|
|
359
387
|
try { process.kill(guard.record.pid, 0); } catch (error) { dead = error?.code === "ESRCH"; }
|
|
360
|
-
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
|
+
}
|
|
361
394
|
}
|
|
362
395
|
// Persist shared participation BEFORE permitting any action or recording
|
|
363
396
|
// recovery. A later reused PID cannot resurrect this exact proven-dead token.
|
|
364
397
|
persistRotationShared(root);
|
|
365
398
|
verifyRotationGuard(root, identity, guard);
|
|
366
399
|
if (!knownDead) {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
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
|
+
}
|
|
370
413
|
}
|
|
371
414
|
syncRotationDirectory(root);
|
|
372
415
|
}
|
|
@@ -533,6 +576,27 @@ export function resetShadowAccessState() {
|
|
|
533
576
|
shadowWarnings.clear();
|
|
534
577
|
}
|
|
535
578
|
|
|
579
|
+
// 记录锁表条目;超过硬上界时按插入序淘汰最旧条目。Map 迭代保持插入序,对已存在
|
|
580
|
+
// 键重复 set 不会改变其位置也不增长表,因此每次新插入至多淘汰一条。安全性论证
|
|
581
|
+
// 见 MAX_LOCK_ENTRIES 处注释:淘汰只是放弃"免重跑收紧"的记忆,不是解锁。
|
|
582
|
+
function rememberLockedEntry(map, key, value) {
|
|
583
|
+
map.set(key, value);
|
|
584
|
+
while (map.size > MAX_LOCK_ENTRIES) {
|
|
585
|
+
const oldest = map.keys().next();
|
|
586
|
+
if (oldest.done) break;
|
|
587
|
+
map.delete(oldest.value);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// rotation/清理删除文件后同步释放其锁表条目,使锁表随分片删除收敛。键与
|
|
592
|
+
// accessEntry 的 canonical 规则一致:真实父目录 + 文件名。父目录已消失时算不出
|
|
593
|
+
// canonical 键,留待硬上界兜底;对不存在的键 delete 是无害空操作。
|
|
594
|
+
function releaseLockedFile(path) {
|
|
595
|
+
try {
|
|
596
|
+
lockedFiles.delete(join(realDirectory(dirname(path)), basename(path)));
|
|
597
|
+
} catch {}
|
|
598
|
+
}
|
|
599
|
+
|
|
536
600
|
export function shadowAccessFused() {
|
|
537
601
|
return Atomics.load(shadowFuseState, 0) !== 0;
|
|
538
602
|
}
|
|
@@ -591,7 +655,7 @@ function accessEntry(path, kind) {
|
|
|
591
655
|
if (kind === "dir" ? !info.isDirectory() : !info.isFile() || info.nlink !== 1n) {
|
|
592
656
|
throw new Error("spine: unsupported shadow permission target");
|
|
593
657
|
}
|
|
594
|
-
return { absolute, canonical, identity: accessIdentity(info) };
|
|
658
|
+
return { absolute, canonical, identity: accessIdentity(info), mode: info.mode };
|
|
595
659
|
}
|
|
596
660
|
|
|
597
661
|
function sameAccessEntry(left, right) {
|
|
@@ -602,7 +666,7 @@ function lockedDirectory(entry) {
|
|
|
602
666
|
const previous = lockedDirs.get(entry.absolute) ?? lockedDirs.get(entry.canonical);
|
|
603
667
|
if (!previous) return false;
|
|
604
668
|
if (!sameAccessEntry(previous, entry)) throw new Error("spine: shadow permission directory identity changed");
|
|
605
|
-
lockedDirs
|
|
669
|
+
rememberLockedEntry(lockedDirs, entry.absolute, previous);
|
|
606
670
|
return true;
|
|
607
671
|
}
|
|
608
672
|
|
|
@@ -612,10 +676,12 @@ export function shadowDirLocked(path) {
|
|
|
612
676
|
|
|
613
677
|
export function noteShadowWarning(logger, error) {
|
|
614
678
|
const code = error?.code || "ESHADOWACCESS";
|
|
615
|
-
if (shadowWarnings.has(code)) return;
|
|
616
|
-
shadowWarnings.add(code);
|
|
617
|
-
const status = error?.cause?.status ?? error?.status;
|
|
618
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;
|
|
619
685
|
const where = step ? ` ${step}` : "";
|
|
620
686
|
const exit = status == null ? "" : ` exit ${status}`;
|
|
621
687
|
logger?.warn?.(`spine: shadow permission failed ${code}${where}${exit}`);
|
|
@@ -662,6 +728,9 @@ export function shadowFileBody(sessionKey, body) {
|
|
|
662
728
|
export const STATS_NAME = "spine-stats.json";
|
|
663
729
|
export const CUTS_NAME = "spine-cuts.jsonl";
|
|
664
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;
|
|
665
734
|
|
|
666
735
|
export function appendDecision(dir, record = {}, { protectPaths = [] } = {}) {
|
|
667
736
|
try {
|
|
@@ -851,11 +920,134 @@ function acquireStatsLock(lock) {
|
|
|
851
920
|
return null;
|
|
852
921
|
}
|
|
853
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
|
+
|
|
854
1046
|
export function flushDrainStats(dir, notes, meta = {}) {
|
|
855
1047
|
const cuts = (notes || []).filter((note) => note?.kind === "cut" && note.saved > 0);
|
|
856
1048
|
const charged = drainRewrite(notes);
|
|
857
1049
|
const saved = cuts.reduce((sum, note) => sum + note.saved, 0);
|
|
858
|
-
|
|
1050
|
+
const firstCut = (notes || []).findIndex((note) => note?.kind === "cut");
|
|
859
1051
|
const lines = (notes || []).map((note, index) => JSON.stringify({
|
|
860
1052
|
v: 1,
|
|
861
1053
|
ts: new Date().toISOString(),
|
|
@@ -864,7 +1056,7 @@ export function flushDrainStats(dir, notes, meta = {}) {
|
|
|
864
1056
|
pass: index,
|
|
865
1057
|
drain: meta.drain === true,
|
|
866
1058
|
saved: note.saved || 0,
|
|
867
|
-
rewriteCharged:
|
|
1059
|
+
rewriteCharged: index === firstCut ? charged : 0,
|
|
868
1060
|
tailBeyondKept: note.tailBeyondKept || 0,
|
|
869
1061
|
prefix: note.prefix || 0,
|
|
870
1062
|
afterPrefix: note.afterPrefix || 0,
|
|
@@ -873,69 +1065,35 @@ export function flushDrainStats(dir, notes, meta = {}) {
|
|
|
873
1065
|
gate: note.gate || "cut",
|
|
874
1066
|
}));
|
|
875
1067
|
if (!lines.length) return charged;
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
const fd = acquireStatsLock(lock);
|
|
889
|
-
if (fd === null) return null;
|
|
890
|
-
try {
|
|
891
|
-
const prev = readCutStats(dir);
|
|
892
|
-
const locked = {
|
|
893
|
-
cuts: prev.cuts + cuts,
|
|
894
|
-
savedTokens: prev.savedTokens + saved,
|
|
895
|
-
rewriteTokens: prev.rewriteTokens + rewrite,
|
|
896
|
-
drains: (Number(prev.drains) || 0) + 1,
|
|
897
|
-
updatedAt: new Date().toISOString(),
|
|
898
|
-
};
|
|
899
|
-
writeFileSync(tmp, JSON.stringify(locked));
|
|
900
|
-
renameSync(tmp, file);
|
|
901
|
-
return locked;
|
|
902
|
-
} finally {
|
|
903
|
-
try { unlinkSync(tmp); } catch {}
|
|
904
|
-
closeSync(fd);
|
|
905
|
-
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 {}
|
|
906
1080
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1081
|
+
try { appendBoundedLog(join(dir, CUTS_NAME), `${lines.join("\n")}\n`, CUTS_LOG_MAX_BYTES); } catch {}
|
|
1082
|
+
});
|
|
1083
|
+
return charged;
|
|
910
1084
|
}
|
|
911
1085
|
|
|
912
1086
|
export function recordCutStats(dir, { saved = 0, rewrite = 0 } = {}) {
|
|
913
1087
|
if (!(saved > 0)) return readCutStats(dir);
|
|
914
|
-
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
cuts: prev.cuts + 1,
|
|
924
|
-
savedTokens: prev.savedTokens + saved,
|
|
925
|
-
rewriteTokens: prev.rewriteTokens + rewrite,
|
|
926
|
-
updatedAt: new Date().toISOString(),
|
|
927
|
-
};
|
|
928
|
-
writeFileSync(tmp, JSON.stringify(locked));
|
|
929
|
-
renameSync(tmp, file);
|
|
930
|
-
return locked;
|
|
931
|
-
} finally {
|
|
932
|
-
try { unlinkSync(tmp); } catch {}
|
|
933
|
-
closeSync(fd);
|
|
934
|
-
try { unlinkSync(lock); } catch {}
|
|
935
|
-
}
|
|
936
|
-
} catch {
|
|
937
|
-
return null;
|
|
938
|
-
}
|
|
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
|
+
});
|
|
939
1097
|
}
|
|
940
1098
|
|
|
941
1099
|
function validWindowsSid(sid) {
|
|
@@ -1007,7 +1165,6 @@ try {
|
|
|
1007
1165
|
exit 1
|
|
1008
1166
|
}
|
|
1009
1167
|
`;
|
|
1010
|
-
const WINDOWS_ACL_COMMAND = Buffer.from(WINDOWS_ACL_SCRIPT, "utf16le").toString("base64");
|
|
1011
1168
|
|
|
1012
1169
|
export function shadowAccessPlan(platform = process.platform, userSid = "", kind = "dir") {
|
|
1013
1170
|
if (platform === "win32") {
|
|
@@ -1035,6 +1192,15 @@ export function shadowAccessPlan(platform = process.platform, userSid = "", kind
|
|
|
1035
1192
|
};
|
|
1036
1193
|
}
|
|
1037
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
|
+
|
|
1038
1204
|
export function defaultShadowAccessRunner({
|
|
1039
1205
|
path,
|
|
1040
1206
|
kind,
|
|
@@ -1044,7 +1210,14 @@ export function defaultShadowAccessRunner({
|
|
|
1044
1210
|
} = {}) {
|
|
1045
1211
|
if (platform !== "win32") {
|
|
1046
1212
|
const plan = shadowAccessPlan(platform);
|
|
1047
|
-
|
|
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);
|
|
1048
1221
|
return true;
|
|
1049
1222
|
}
|
|
1050
1223
|
|
|
@@ -1104,17 +1277,18 @@ export function defaultShadowAccessRunner({
|
|
|
1104
1277
|
});
|
|
1105
1278
|
const result = execFile(
|
|
1106
1279
|
powershellPath,
|
|
1107
|
-
|
|
1280
|
+
// Issue #67 reported a build that rejects -EncodedCommand after whoami.
|
|
1281
|
+
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_ACL_SCRIPT],
|
|
1108
1282
|
{ env: childEnv, encoding: "utf8", stdio: "pipe", windowsHide: true, timeout: 15000, maxBuffer: 65536 },
|
|
1109
1283
|
);
|
|
1110
1284
|
if (String(result).trim() !== "DSH_SHADOW_ACL_OK") throw new Error("spine: shadow DACL verification not confirmed");
|
|
1111
1285
|
const after = accessEntry(path, kind);
|
|
1112
1286
|
if (!sameAccessEntry(before, after)) throw new Error("spine: shadow permission target identity changed");
|
|
1113
1287
|
if (kind === "dir") {
|
|
1114
|
-
lockedDirs
|
|
1115
|
-
lockedDirs
|
|
1288
|
+
rememberLockedEntry(lockedDirs, after.absolute, after);
|
|
1289
|
+
rememberLockedEntry(lockedDirs, after.canonical, after);
|
|
1116
1290
|
} else {
|
|
1117
|
-
lockedFiles
|
|
1291
|
+
rememberLockedEntry(lockedFiles, after.canonical, after);
|
|
1118
1292
|
}
|
|
1119
1293
|
} catch (error) {
|
|
1120
1294
|
error.step = kind === "file" ? "file" : "dir";
|
|
@@ -1172,45 +1346,61 @@ export function ensureShadowDir(dir, access = {}) {
|
|
|
1172
1346
|
return dir;
|
|
1173
1347
|
}
|
|
1174
1348
|
|
|
1175
|
-
export function
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
throw new Error("spine: shadow published file identity changed");
|
|
1182
|
-
}
|
|
1183
|
-
if (remember) lockedFiles.set(entry.canonical, entry);
|
|
1184
|
-
return;
|
|
1185
|
-
} catch (cause) {
|
|
1186
|
-
tripFuse();
|
|
1187
|
-
const error = new Error("spine: shadow permission action failed; backup refused", { cause });
|
|
1188
|
-
error.code = "ESHADOWACCESS";
|
|
1189
|
-
error.step = "file";
|
|
1190
|
-
throw error;
|
|
1191
|
-
}
|
|
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" });
|
|
1192
1355
|
}
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
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");
|
|
1211
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;
|
|
1212
1403
|
}
|
|
1213
|
-
tightenShadow(file, "file", access);
|
|
1214
1404
|
}
|
|
1215
1405
|
|
|
1216
1406
|
export function discardShadowFiles(files, cause, unlink = unlinkSync) {
|
|
@@ -1283,6 +1473,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1283
1473
|
}
|
|
1284
1474
|
// Confirm ACL/mode before any secret bytes are written to the staged file.
|
|
1285
1475
|
tightenCreatedShadow(target, fd, access);
|
|
1476
|
+
rememberShadowParent(dir);
|
|
1286
1477
|
// Full replacement bytes are a conservative charge, even for overwrites,
|
|
1287
1478
|
// partial writes and failed cleanup. Metadata/owner/stats are not capacity.
|
|
1288
1479
|
if (shadowUsage && isPluginShadowName(basename(file))) {
|
|
@@ -1300,6 +1491,9 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1300
1491
|
}
|
|
1301
1492
|
renameSync(target, file);
|
|
1302
1493
|
protectedPath = file;
|
|
1494
|
+
// staging 临时名一次性且永不复用:发布后其锁表条目已成死重,随 rename 同步
|
|
1495
|
+
// 释放,避免每次保存向 lockedFiles 残留一个永不复用的条目。
|
|
1496
|
+
releaseLockedFile(target);
|
|
1303
1497
|
if (basename(file) !== DECISIONS_NAME) {
|
|
1304
1498
|
decisionRotationAt.delete(rotationScope.root);
|
|
1305
1499
|
decisionUsageBytes.delete(rotationScope.root);
|
|
@@ -1315,6 +1509,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1315
1509
|
closeSync(opened);
|
|
1316
1510
|
return file;
|
|
1317
1511
|
} catch (error) {
|
|
1512
|
+
const identity = fd !== null ? shadowFileIdentity(protectedPath, fd) : "";
|
|
1318
1513
|
if (fd !== null) {
|
|
1319
1514
|
try {
|
|
1320
1515
|
closeSync(fd);
|
|
@@ -1325,8 +1520,9 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1325
1520
|
// Do not unlink through a replacement directory after a failed write.
|
|
1326
1521
|
let sameParent = false;
|
|
1327
1522
|
try { sameParent = !parentIdentity || directoryIdentity(dir) === parentIdentity; } catch {}
|
|
1328
|
-
if (sameParent
|
|
1329
|
-
|
|
1523
|
+
if (sameParent && identity && shadowFileIdentity(protectedPath) === identity) {
|
|
1524
|
+
discardShadowFiles([protectedPath], error, unlink);
|
|
1525
|
+
} else shadowUsage = null;
|
|
1330
1526
|
}
|
|
1331
1527
|
throw error;
|
|
1332
1528
|
}
|
|
@@ -1593,6 +1789,9 @@ function rotateShadowLocked({
|
|
|
1593
1789
|
break;
|
|
1594
1790
|
}
|
|
1595
1791
|
}
|
|
1792
|
+
// 文件已被删除(或本就 ENOENT):同步释放其锁表条目,使锁表随 rotation
|
|
1793
|
+
// 收敛而不是只增不减。unlink 失败(文件仍在盘上)时不会走到这里。
|
|
1794
|
+
releaseLockedFile(file.path);
|
|
1596
1795
|
used -= file.size;
|
|
1597
1796
|
freed += file.size;
|
|
1598
1797
|
deleted += 1;
|
|
@@ -1600,6 +1799,9 @@ function rotateShadowLocked({
|
|
|
1600
1799
|
try {
|
|
1601
1800
|
unlink(`${file.path}.meta.json`);
|
|
1602
1801
|
} catch {}
|
|
1802
|
+
// meta.json 通常已随之删除;即便 unlink 因占用等失败,释放缓存条目也是
|
|
1803
|
+
// 安全方向——下次 tightenShadow 会重新收紧(fail-closed),不会绕过锁。
|
|
1804
|
+
releaseLockedFile(`${file.path}.meta.json`);
|
|
1603
1805
|
}
|
|
1604
1806
|
}
|
|
1605
1807
|
const fits = used + incomingBytes <= cap;
|