dsh-live-compact 1.1.11 → 1.1.13
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 +27 -0
- package/README.md +14 -12
- package/client.js +32 -13
- package/cordis.patch.yml +1 -0
- package/gate.js +55 -5
- package/index.js +1573 -428
- package/package.json +2 -2
- package/raw.js +2 -2
- package/settings.js +2 -2
- package/shadow-save-worker.mjs +18 -1
- package/shadow.js +274 -23
- package/shell.js +57 -2
- 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.13",
|
|
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>",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"compaction"
|
|
45
45
|
],
|
|
46
46
|
"scripts": {
|
|
47
|
-
"test:gate": "node test/p0-gate.mjs && node test/p0-blockers.mjs && node test/excerpt.mjs && node test/shadow-worker.mjs && node test/shadow-worker-pool.mjs && node test/shadow-worker-fuse.mjs && node --test test/failed-diagnostics.test.mjs test/public-exports.test.mjs test/cooldown.test.mjs test/gate-config.test.mjs test/stand-down.test.mjs test/drain-stopline.mjs test/scan-once.mjs test/issue-19.mjs test/issue-20.mjs test/issue-34.mjs test/issue-49.mjs test/issue-62.mjs test/review-derived.test.mjs test/windows-acl.test.mjs test/issue-27.mjs test/issue-29.mjs test/issue-29-notice.mjs test/client-settings.test.mjs test/settings-integration.test.mjs test/runtime-lifecycle.mjs test/shadow-lifecycle.mjs test/finalize-over-32000.mjs test/p1-fable-review.mjs",
|
|
47
|
+
"test:gate": "node test/p0-gate.mjs && node test/p0-blockers.mjs && node test/excerpt.mjs && node test/shadow-worker.mjs && node test/shadow-worker-pool.mjs && node test/shadow-worker-fuse.mjs && node test/v107.mjs && node --test test/turn-end-bridge.mjs && node --test test/failed-diagnostics.test.mjs test/public-exports.test.mjs test/cooldown.test.mjs test/gate-config.test.mjs test/stand-down.test.mjs test/drain-stopline.mjs test/scan-once.mjs test/issue-19.mjs test/issue-20.mjs test/issue-34.mjs test/issue-49.mjs test/issue-62.mjs test/review-derived.test.mjs test/windows-acl.test.mjs test/issue-27.mjs test/issue-29.mjs test/issue-29-notice.mjs test/client-settings.test.mjs test/settings-integration.test.mjs test/runtime-lifecycle.mjs test/shadow-lifecycle.mjs test/finalize-over-32000.mjs test/p1-fable-review.mjs",
|
|
48
48
|
"test:compat41": "node test/compat-cordis41.mjs",
|
|
49
49
|
"test:live-gate": "python3 -B -m unittest discover -s test/live-fill -p test_*.py"
|
|
50
50
|
},
|
package/raw.js
CHANGED
|
@@ -124,7 +124,7 @@ export function captureToolResult(options) {
|
|
|
124
124
|
const { dir, toolCallId, access = {}, root = shadowRootForDir(dir) } = options;
|
|
125
125
|
if (!toolCallId) return { ok: false, reason: "missing-id", toolCallId: "" };
|
|
126
126
|
if (!existsSync(join(dir, rawName(toolCallId))) && String(options.text ?? "").includes(PRUNE_MARKER)) {
|
|
127
|
-
return { ok: false, reason: "already-pruned", toolCallId,
|
|
127
|
+
return { ok: false, reason: "already-pruned", toolCallId, unrecoverable: true };
|
|
128
128
|
}
|
|
129
129
|
try {
|
|
130
130
|
ensureShadowDir(dir, access);
|
|
@@ -165,7 +165,7 @@ function captureToolResultLocked({
|
|
|
165
165
|
const hash = contentHash(bytes);
|
|
166
166
|
|
|
167
167
|
if (!existsSync(file) && body.includes(PRUNE_MARKER)) {
|
|
168
|
-
return { ok: false, reason: "already-pruned", toolCallId,
|
|
168
|
+
return { ok: false, reason: "already-pruned", toolCallId, unrecoverable: true };
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
const readProtectedExisting = () => readRawToolResult({ dir, toolCallId, access });
|
package/settings.js
CHANGED
|
@@ -105,8 +105,8 @@ export function configSchema(z, stockSchema) {
|
|
|
105
105
|
...Object.fromEntries(Object.entries(stockFields).map(([key, field]) => [
|
|
106
106
|
key, field.meta?.volatile ? field : z(field).volatile(),
|
|
107
107
|
])),
|
|
108
|
-
takeoverPresets: z.boolean().default(true)
|
|
109
|
-
.description("
|
|
108
|
+
takeoverPresets: z.union([z.boolean(), z.array(z.string())]).default(true)
|
|
109
|
+
.description("接管官方预设中的压缩引擎;可填 false 或 preset ID 数组限制接管范围。修改后只影响新加载的预设,已有会话需重建。")
|
|
110
110
|
.volatile(),
|
|
111
111
|
minTokens: count(0)
|
|
112
112
|
.description("轮后小切的起点,上下文到这个 token 数才切一刀。")
|
package/shadow-save-worker.mjs
CHANGED
|
@@ -4,9 +4,26 @@ 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) {
|
|
12
29
|
parentPort.postMessage({ id, ok: false, error: {
|
package/shadow.js
CHANGED
|
@@ -11,7 +11,9 @@ import { execFileSync } from "node:child_process";
|
|
|
11
11
|
import { randomBytes } from "node:crypto";
|
|
12
12
|
import { homedir } from "node:os";
|
|
13
13
|
import { performance } from "node:perf_hooks";
|
|
14
|
+
import { workerData } from "node:worker_threads";
|
|
14
15
|
import {
|
|
16
|
+
constants as fsConstants,
|
|
15
17
|
chmodSync,
|
|
16
18
|
appendFileSync,
|
|
17
19
|
closeSync,
|
|
@@ -38,8 +40,28 @@ const PLUGIN_NAME = /^(?:(?:cut|official|shadow)-\d+-[0-9a-f]{8}|raw-[0-9a-f]{16
|
|
|
38
40
|
let cachedSid = "";
|
|
39
41
|
const lockedDirs = new Map();
|
|
40
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;
|
|
41
59
|
let shadowFuseState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
42
60
|
const shadowWarnings = new Set();
|
|
61
|
+
const DECISION_ROTATION_INTERVAL_MS = 1000;
|
|
62
|
+
const decisionRotationAt = new Map();
|
|
63
|
+
const decisionUsageBytes = new Map();
|
|
64
|
+
const decisionUsageMtime = new Map();
|
|
43
65
|
|
|
44
66
|
// No shared byte ledger. A positively dead holder leaves an immutable fence:
|
|
45
67
|
// recovery enables the original shared scans, never ownership or an estimate.
|
|
@@ -48,7 +70,9 @@ const ROTATION_OWNER = ".spine-rotation.owner";
|
|
|
48
70
|
const ROTATION_SHARED = ".spine-rotation.shared";
|
|
49
71
|
const ROTATION_RECOVERED = ".spine-rotation.recovered";
|
|
50
72
|
const USAGE_MAX_AGE_MS = 60_000;
|
|
51
|
-
const rotationOwner =
|
|
73
|
+
const rotationOwner = /^[0-9a-f]{48}$/.test(workerData?.spineOwner || "")
|
|
74
|
+
? workerData.spineOwner
|
|
75
|
+
: randomBytes(24).toString("hex");
|
|
52
76
|
let rotationScope = null;
|
|
53
77
|
let shadowUsage = null;
|
|
54
78
|
|
|
@@ -295,7 +319,13 @@ function releaseRotationGuard(root, identity, guard) {
|
|
|
295
319
|
|
|
296
320
|
function acquireRotationGuard(root, identity) {
|
|
297
321
|
const lock = join(root, ROTATION_LOCK);
|
|
298
|
-
|
|
322
|
+
// A host transaction gets a fresh fence token every time. Managed workers
|
|
323
|
+
// keep their stable owner token so a timed-out parent can recover exactly
|
|
324
|
+
// the worker-held lock without touching another transaction.
|
|
325
|
+
const transactionId = workerData?.spineWorker === 1
|
|
326
|
+
? rotationOwner
|
|
327
|
+
: randomBytes(24).toString("hex");
|
|
328
|
+
const record = { pid: process.pid, id: transactionId };
|
|
299
329
|
let guard;
|
|
300
330
|
try {
|
|
301
331
|
const published = publishRotationRecord(lock, record);
|
|
@@ -483,6 +513,32 @@ export function withShadowRoot(dir, action) {
|
|
|
483
513
|
}
|
|
484
514
|
}
|
|
485
515
|
|
|
516
|
+
// Used only after a worker thread has been terminated. The owner token prevents
|
|
517
|
+
// a parent from deleting another process's live rotation lock when recovering
|
|
518
|
+
// a timed-out worker that shares process.pid with the host.
|
|
519
|
+
export function recoverTimedOutShadowWorker(root, owner) {
|
|
520
|
+
try {
|
|
521
|
+
const real = realDirectory(root);
|
|
522
|
+
const lock = join(real, ROTATION_LOCK);
|
|
523
|
+
const record = readRotationRecord(lock);
|
|
524
|
+
if (record.pid !== process.pid || record.id !== owner) return false;
|
|
525
|
+
try { unlinkSync(lock); } catch (error) { if (error?.code !== "ENOENT") return false; }
|
|
526
|
+
const ownerFile = join(real, ROTATION_OWNER);
|
|
527
|
+
try {
|
|
528
|
+
const current = readRotationOwner(ownerFile);
|
|
529
|
+
if (current.pid === process.pid && current.id === owner) unlinkSync(ownerFile);
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (error?.code !== "ENOENT") return false;
|
|
532
|
+
}
|
|
533
|
+
// Keep the shared fence immutable. It may represent another participant;
|
|
534
|
+
// recovery of this worker must never re-enable an exclusive fast path.
|
|
535
|
+
syncRotationDirectory(real);
|
|
536
|
+
return true;
|
|
537
|
+
} catch {
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
486
542
|
export function resetShadowAccessState() {
|
|
487
543
|
cachedSid = "";
|
|
488
544
|
lockedDirs.clear();
|
|
@@ -493,6 +549,27 @@ export function resetShadowAccessState() {
|
|
|
493
549
|
shadowWarnings.clear();
|
|
494
550
|
}
|
|
495
551
|
|
|
552
|
+
// 记录锁表条目;超过硬上界时按插入序淘汰最旧条目。Map 迭代保持插入序,对已存在
|
|
553
|
+
// 键重复 set 不会改变其位置也不增长表,因此每次新插入至多淘汰一条。安全性论证
|
|
554
|
+
// 见 MAX_LOCK_ENTRIES 处注释:淘汰只是放弃"免重跑收紧"的记忆,不是解锁。
|
|
555
|
+
function rememberLockedEntry(map, key, value) {
|
|
556
|
+
map.set(key, value);
|
|
557
|
+
while (map.size > MAX_LOCK_ENTRIES) {
|
|
558
|
+
const oldest = map.keys().next();
|
|
559
|
+
if (oldest.done) break;
|
|
560
|
+
map.delete(oldest.value);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// rotation/清理删除文件后同步释放其锁表条目,使锁表随分片删除收敛。键与
|
|
565
|
+
// accessEntry 的 canonical 规则一致:真实父目录 + 文件名。父目录已消失时算不出
|
|
566
|
+
// canonical 键,留待硬上界兜底;对不存在的键 delete 是无害空操作。
|
|
567
|
+
function releaseLockedFile(path) {
|
|
568
|
+
try {
|
|
569
|
+
lockedFiles.delete(join(realDirectory(dirname(path)), basename(path)));
|
|
570
|
+
} catch {}
|
|
571
|
+
}
|
|
572
|
+
|
|
496
573
|
export function shadowAccessFused() {
|
|
497
574
|
return Atomics.load(shadowFuseState, 0) !== 0;
|
|
498
575
|
}
|
|
@@ -562,7 +639,7 @@ function lockedDirectory(entry) {
|
|
|
562
639
|
const previous = lockedDirs.get(entry.absolute) ?? lockedDirs.get(entry.canonical);
|
|
563
640
|
if (!previous) return false;
|
|
564
641
|
if (!sameAccessEntry(previous, entry)) throw new Error("spine: shadow permission directory identity changed");
|
|
565
|
-
lockedDirs
|
|
642
|
+
rememberLockedEntry(lockedDirs, entry.absolute, previous);
|
|
566
643
|
return true;
|
|
567
644
|
}
|
|
568
645
|
|
|
@@ -583,7 +660,7 @@ export function noteShadowWarning(logger, error) {
|
|
|
583
660
|
const SESSION_MARK = /^# spine-session (\S+)/;
|
|
584
661
|
|
|
585
662
|
export function isPluginShadowName(name) {
|
|
586
|
-
return PLUGIN_NAME.test(name);
|
|
663
|
+
return name === "spine-decisions.jsonl" || PLUGIN_NAME.test(name);
|
|
587
664
|
}
|
|
588
665
|
|
|
589
666
|
export function sanitizeSessionKey(key) {
|
|
@@ -621,6 +698,89 @@ export function shadowFileBody(sessionKey, body) {
|
|
|
621
698
|
|
|
622
699
|
export const STATS_NAME = "spine-stats.json";
|
|
623
700
|
export const CUTS_NAME = "spine-cuts.jsonl";
|
|
701
|
+
export const DECISIONS_NAME = "spine-decisions.jsonl";
|
|
702
|
+
|
|
703
|
+
export function appendDecision(dir, record = {}, { protectPaths = [] } = {}) {
|
|
704
|
+
try {
|
|
705
|
+
if (!existsSync(dir)) return false;
|
|
706
|
+
const body = `${JSON.stringify({
|
|
707
|
+
v: 1,
|
|
708
|
+
ts: new Date().toISOString(),
|
|
709
|
+
...record,
|
|
710
|
+
})}\n`;
|
|
711
|
+
const file = join(dir, DECISIONS_NAME);
|
|
712
|
+
return withShadowRoot(dir, () => {
|
|
713
|
+
const path = scopedFile(file, rotationScope.root);
|
|
714
|
+
if (!path) throw coordinationError(new Error("shadow decision outside root scope"));
|
|
715
|
+
const rotationKey = rotationScope.root;
|
|
716
|
+
const now = Date.now();
|
|
717
|
+
const lastRotation = decisionRotationAt.get(rotationKey) || 0;
|
|
718
|
+
const incomingBytes = Buffer.byteLength(body, "utf8");
|
|
719
|
+
const cap = shadowMaxBytes();
|
|
720
|
+
let knownUsage = decisionUsageBytes.get(rotationKey);
|
|
721
|
+
let rootMtime = null;
|
|
722
|
+
try { rootMtime = statSync(rotationKey).mtimeMs; } catch {}
|
|
723
|
+
const knownMtime = decisionUsageMtime.get(rotationKey);
|
|
724
|
+
const fastPath = rotationScope.exclusive && shadowUsage?.root === rotationKey &&
|
|
725
|
+
shadowUsage?.identity === rotationScope.identity &&
|
|
726
|
+
now - lastRotation < DECISION_ROTATION_INTERVAL_MS &&
|
|
727
|
+
Number.isSafeInteger(knownUsage) && rootMtime !== null && knownMtime === rootMtime;
|
|
728
|
+
if (!fastPath) {
|
|
729
|
+
const rotation = rotateShadowLocked({
|
|
730
|
+
incomingBytes,
|
|
731
|
+
protectPath: path,
|
|
732
|
+
protectPaths,
|
|
733
|
+
sessionKey: record.sid || record.sessionId || "default",
|
|
734
|
+
cap,
|
|
735
|
+
});
|
|
736
|
+
if (!rotation.ok || rotation.oversize) return false;
|
|
737
|
+
decisionRotationAt.set(rotationKey, now);
|
|
738
|
+
knownUsage = rotation.used;
|
|
739
|
+
decisionUsageBytes.set(rotationKey, knownUsage);
|
|
740
|
+
try { decisionUsageMtime.set(rotationKey, statSync(rotationKey).mtimeMs); } catch {}
|
|
741
|
+
} else if (Number.isSafeInteger(knownUsage) && knownUsage + incomingBytes > cap) {
|
|
742
|
+
return false;
|
|
743
|
+
}
|
|
744
|
+
if (existsSync(path)) {
|
|
745
|
+
const beforeOpen = lstatSync(path, { bigint: true });
|
|
746
|
+
if (!beforeOpen.isFile() || beforeOpen.nlink !== 1n) {
|
|
747
|
+
throw coordinationError(new Error("shadow decision is not a single-link regular file"));
|
|
748
|
+
}
|
|
749
|
+
const noFollow = fsConstants.O_NOFOLLOW;
|
|
750
|
+
const fd = openSync(path, fsConstants.O_WRONLY | fsConstants.O_APPEND | (noFollow ?? 0));
|
|
751
|
+
try {
|
|
752
|
+
const opened = fstatSync(fd, { bigint: true });
|
|
753
|
+
const named = lstatSync(path, { bigint: true });
|
|
754
|
+
if (!opened.isFile() || opened.nlink !== 1n || !named.isFile() || named.nlink !== 1n ||
|
|
755
|
+
opened.dev !== named.dev || opened.ino !== named.ino) {
|
|
756
|
+
throw coordinationError(new Error("shadow decision identity changed"));
|
|
757
|
+
}
|
|
758
|
+
writeFileSync(fd, body);
|
|
759
|
+
fsyncSync(fd);
|
|
760
|
+
} finally {
|
|
761
|
+
closeSync(fd);
|
|
762
|
+
}
|
|
763
|
+
if (shadowUsage && isPluginShadowName(basename(path))) {
|
|
764
|
+
shadowUsage.bytes += Buffer.byteLength(body, "utf8");
|
|
765
|
+
}
|
|
766
|
+
decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
|
|
767
|
+
if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
|
|
768
|
+
} else {
|
|
769
|
+
writeShadowFileLocked(path, body, {}, {
|
|
770
|
+
exclusive: false,
|
|
771
|
+
write: writeFileSync,
|
|
772
|
+
unlink: unlinkSync,
|
|
773
|
+
accessPath: file,
|
|
774
|
+
});
|
|
775
|
+
decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
|
|
776
|
+
if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
|
|
777
|
+
}
|
|
778
|
+
return true;
|
|
779
|
+
});
|
|
780
|
+
} catch {
|
|
781
|
+
return false;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
624
784
|
|
|
625
785
|
export function readCutStats(dir) {
|
|
626
786
|
try {
|
|
@@ -643,6 +803,91 @@ export function drainRewrite(notes) {
|
|
|
643
803
|
return Math.max(0, (cuts[0].afterPrefix || 0) - later);
|
|
644
804
|
}
|
|
645
805
|
|
|
806
|
+
function acquireStatsLock(lock) {
|
|
807
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
808
|
+
let fd;
|
|
809
|
+
let created = false;
|
|
810
|
+
try {
|
|
811
|
+
fd = openSync(lock, "wx", 0o600);
|
|
812
|
+
created = true;
|
|
813
|
+
writeFileSync(fd, String(process.pid));
|
|
814
|
+
fsyncSync(fd);
|
|
815
|
+
return fd;
|
|
816
|
+
} catch (error) {
|
|
817
|
+
if (fd !== undefined) {
|
|
818
|
+
try { closeSync(fd); } catch {}
|
|
819
|
+
}
|
|
820
|
+
if (created) {
|
|
821
|
+
try { unlinkSync(lock); } catch {}
|
|
822
|
+
}
|
|
823
|
+
if (error?.code !== "EEXIST") return null;
|
|
824
|
+
let pid = null;
|
|
825
|
+
let observedText = "";
|
|
826
|
+
let observedStat;
|
|
827
|
+
try {
|
|
828
|
+
observedText = readFileSync(lock, "utf8").trim();
|
|
829
|
+
pid = /^[1-9]\d*$/.test(observedText) ? Number(observedText) : null;
|
|
830
|
+
observedStat = statSync(lock);
|
|
831
|
+
} catch {
|
|
832
|
+
return null;
|
|
833
|
+
}
|
|
834
|
+
const dead = pid !== null && processAlive(pid) === false;
|
|
835
|
+
// Pre-1.1.12 locks were empty files. Only recover one that is old enough
|
|
836
|
+
// to be a legacy crash artifact; a just-created empty lock may still be
|
|
837
|
+
// between open(wx) and its PID write.
|
|
838
|
+
const legacyEmpty = observedText === "" && Number.isFinite(observedStat?.mtimeMs) &&
|
|
839
|
+
Date.now() - observedStat.mtimeMs >= 1000;
|
|
840
|
+
if (dead || legacyEmpty) {
|
|
841
|
+
const recovery = `${lock}.recover`;
|
|
842
|
+
let recoveryFd;
|
|
843
|
+
let removed = false;
|
|
844
|
+
try {
|
|
845
|
+
recoveryFd = openSync(recovery, "wx", 0o600);
|
|
846
|
+
writeFileSync(recoveryFd, String(process.pid));
|
|
847
|
+
fsyncSync(recoveryFd);
|
|
848
|
+
} catch (recoveryError) {
|
|
849
|
+
if (recoveryFd !== undefined) {
|
|
850
|
+
try { closeSync(recoveryFd); } catch {}
|
|
851
|
+
try { unlinkSync(recovery); } catch {}
|
|
852
|
+
}
|
|
853
|
+
if (recoveryError?.code === "EEXIST") {
|
|
854
|
+
let recoveryPid = null;
|
|
855
|
+
try {
|
|
856
|
+
const text = readFileSync(recovery, "utf8").trim();
|
|
857
|
+
recoveryPid = /^[1-9]\d*$/.test(text) ? Number(text) : null;
|
|
858
|
+
} catch {}
|
|
859
|
+
if (recoveryPid !== null && processAlive(recoveryPid) === false) {
|
|
860
|
+
try { unlinkSync(recovery); } catch {}
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return null;
|
|
865
|
+
}
|
|
866
|
+
try {
|
|
867
|
+
let current = "";
|
|
868
|
+
let currentStat;
|
|
869
|
+
try {
|
|
870
|
+
current = readFileSync(lock, "utf8").trim();
|
|
871
|
+
currentStat = statSync(lock);
|
|
872
|
+
} catch {}
|
|
873
|
+
const unchanged = current === observedText && currentStat && observedStat &&
|
|
874
|
+
currentStat.dev === observedStat.dev && currentStat.ino === observedStat.ino &&
|
|
875
|
+
currentStat.size === observedStat.size && currentStat.mtimeMs === observedStat.mtimeMs;
|
|
876
|
+
if (unchanged && (dead || legacyEmpty)) {
|
|
877
|
+
try { unlinkSync(lock); removed = true; } catch {}
|
|
878
|
+
}
|
|
879
|
+
} finally {
|
|
880
|
+
try { closeSync(recoveryFd); } catch {}
|
|
881
|
+
try { unlinkSync(recovery); } catch {}
|
|
882
|
+
}
|
|
883
|
+
if (removed) continue;
|
|
884
|
+
}
|
|
885
|
+
return null;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
return null;
|
|
889
|
+
}
|
|
890
|
+
|
|
646
891
|
export function flushDrainStats(dir, notes, meta = {}) {
|
|
647
892
|
const cuts = (notes || []).filter((note) => note?.kind === "cut" && note.saved > 0);
|
|
648
893
|
const charged = drainRewrite(notes);
|
|
@@ -677,12 +922,8 @@ function recordDrainStats(dir, { cuts = 0, saved = 0, rewrite = 0 } = {}) {
|
|
|
677
922
|
const file = join(dir, STATS_NAME);
|
|
678
923
|
const lock = join(dir, "spine-stats.lock");
|
|
679
924
|
const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
fd = openSync(lock, "wx");
|
|
683
|
-
} catch {
|
|
684
|
-
return null;
|
|
685
|
-
}
|
|
925
|
+
const fd = acquireStatsLock(lock);
|
|
926
|
+
if (fd === null) return null;
|
|
686
927
|
try {
|
|
687
928
|
const prev = readCutStats(dir);
|
|
688
929
|
const locked = {
|
|
@@ -711,12 +952,8 @@ export function recordCutStats(dir, { saved = 0, rewrite = 0 } = {}) {
|
|
|
711
952
|
const file = join(dir, STATS_NAME);
|
|
712
953
|
const lock = join(dir, "spine-stats.lock");
|
|
713
954
|
const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
fd = openSync(lock, "wx");
|
|
717
|
-
} catch {
|
|
718
|
-
return null;
|
|
719
|
-
}
|
|
955
|
+
const fd = acquireStatsLock(lock);
|
|
956
|
+
if (fd === null) return null;
|
|
720
957
|
try {
|
|
721
958
|
const prev = readCutStats(dir);
|
|
722
959
|
const locked = {
|
|
@@ -807,7 +1044,6 @@ try {
|
|
|
807
1044
|
exit 1
|
|
808
1045
|
}
|
|
809
1046
|
`;
|
|
810
|
-
const WINDOWS_ACL_COMMAND = Buffer.from(WINDOWS_ACL_SCRIPT, "utf16le").toString("base64");
|
|
811
1047
|
|
|
812
1048
|
export function shadowAccessPlan(platform = process.platform, userSid = "", kind = "dir") {
|
|
813
1049
|
if (platform === "win32") {
|
|
@@ -904,17 +1140,18 @@ export function defaultShadowAccessRunner({
|
|
|
904
1140
|
});
|
|
905
1141
|
const result = execFile(
|
|
906
1142
|
powershellPath,
|
|
907
|
-
|
|
1143
|
+
// Issue #67 reported a build that rejects -EncodedCommand after whoami.
|
|
1144
|
+
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_ACL_SCRIPT],
|
|
908
1145
|
{ env: childEnv, encoding: "utf8", stdio: "pipe", windowsHide: true, timeout: 15000, maxBuffer: 65536 },
|
|
909
1146
|
);
|
|
910
1147
|
if (String(result).trim() !== "DSH_SHADOW_ACL_OK") throw new Error("spine: shadow DACL verification not confirmed");
|
|
911
1148
|
const after = accessEntry(path, kind);
|
|
912
1149
|
if (!sameAccessEntry(before, after)) throw new Error("spine: shadow permission target identity changed");
|
|
913
1150
|
if (kind === "dir") {
|
|
914
|
-
lockedDirs
|
|
915
|
-
lockedDirs
|
|
1151
|
+
rememberLockedEntry(lockedDirs, after.absolute, after);
|
|
1152
|
+
rememberLockedEntry(lockedDirs, after.canonical, after);
|
|
916
1153
|
} else {
|
|
917
|
-
lockedFiles
|
|
1154
|
+
rememberLockedEntry(lockedFiles, after.canonical, after);
|
|
918
1155
|
}
|
|
919
1156
|
} catch (error) {
|
|
920
1157
|
error.step = kind === "file" ? "file" : "dir";
|
|
@@ -980,7 +1217,7 @@ export function tightenCreatedShadow(file, fd, access, { remember = true, skipRu
|
|
|
980
1217
|
if (!entry.identity || entry.identity !== accessIdentity(opened) || opened.nlink !== 1n) {
|
|
981
1218
|
throw new Error("spine: shadow published file identity changed");
|
|
982
1219
|
}
|
|
983
|
-
if (remember) lockedFiles
|
|
1220
|
+
if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
|
|
984
1221
|
return;
|
|
985
1222
|
} catch (cause) {
|
|
986
1223
|
tripFuse();
|
|
@@ -999,7 +1236,7 @@ export function tightenCreatedShadow(file, fd, access, { remember = true, skipRu
|
|
|
999
1236
|
throw new Error("spine: shadow created file identity changed");
|
|
1000
1237
|
}
|
|
1001
1238
|
// Only this wx-created object is known to inherit our confirmed DACL.
|
|
1002
|
-
if (remember) lockedFiles
|
|
1239
|
+
if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
|
|
1003
1240
|
return;
|
|
1004
1241
|
}
|
|
1005
1242
|
} catch (cause) {
|
|
@@ -1100,6 +1337,14 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1100
1337
|
}
|
|
1101
1338
|
renameSync(target, file);
|
|
1102
1339
|
protectedPath = file;
|
|
1340
|
+
// staging 临时名一次性且永不复用:发布后其锁表条目已成死重,随 rename 同步
|
|
1341
|
+
// 释放,避免每次保存向 lockedFiles 残留一个永不复用的条目。
|
|
1342
|
+
releaseLockedFile(target);
|
|
1343
|
+
if (basename(file) !== DECISIONS_NAME) {
|
|
1344
|
+
decisionRotationAt.delete(rotationScope.root);
|
|
1345
|
+
decisionUsageBytes.delete(rotationScope.root);
|
|
1346
|
+
decisionUsageMtime.delete(rotationScope.root);
|
|
1347
|
+
}
|
|
1103
1348
|
|
|
1104
1349
|
// Keep the caller's spelling for the permission cache/runner. The opened
|
|
1105
1350
|
// descriptor and the final path now refer to the same published object.
|
|
@@ -1388,6 +1633,9 @@ function rotateShadowLocked({
|
|
|
1388
1633
|
break;
|
|
1389
1634
|
}
|
|
1390
1635
|
}
|
|
1636
|
+
// 文件已被删除(或本就 ENOENT):同步释放其锁表条目,使锁表随 rotation
|
|
1637
|
+
// 收敛而不是只增不减。unlink 失败(文件仍在盘上)时不会走到这里。
|
|
1638
|
+
releaseLockedFile(file.path);
|
|
1391
1639
|
used -= file.size;
|
|
1392
1640
|
freed += file.size;
|
|
1393
1641
|
deleted += 1;
|
|
@@ -1395,6 +1643,9 @@ function rotateShadowLocked({
|
|
|
1395
1643
|
try {
|
|
1396
1644
|
unlink(`${file.path}.meta.json`);
|
|
1397
1645
|
} catch {}
|
|
1646
|
+
// meta.json 通常已随之删除;即便 unlink 因占用等失败,释放缓存条目也是
|
|
1647
|
+
// 安全方向——下次 tightenShadow 会重新收紧(fail-closed),不会绕过锁。
|
|
1648
|
+
releaseLockedFile(`${file.path}.meta.json`);
|
|
1398
1649
|
}
|
|
1399
1650
|
}
|
|
1400
1651
|
const fits = used + incomingBytes <= cap;
|
package/shell.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* 预检查只解析配置,校验交给实际引擎;构造失败时释放本次注册,不重试原版盖掉报错。
|
|
7
7
|
* Resolve config before construction; let the engine validate it and preserve its actual error.
|
|
8
8
|
*/
|
|
9
|
-
import { loadBase, loadCompaction, loadSchema } from "./adapter.js";
|
|
9
|
+
import { loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
|
|
10
10
|
import { configSchema, engineConfig } from "./settings.js";
|
|
11
11
|
import { installPresetGate } from "./gate.js";
|
|
12
12
|
|
|
@@ -76,6 +76,56 @@ function releaseCompaction(ctx, previous) {
|
|
|
76
76
|
return true;
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
function detachRootStockCompaction(ctx) {
|
|
80
|
+
const store = ctx?.reflect?.store;
|
|
81
|
+
const current = compactionRecord(ctx);
|
|
82
|
+
const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
|
|
83
|
+
const fiber = current?.fiber ?? current?.ctx?.fiber;
|
|
84
|
+
const moduleName = fiber?.entry?.options?.name;
|
|
85
|
+
if (!current || moduleName !== STOCK_ENGINE || fiber === ctx?.fiber) return false;
|
|
86
|
+
if (compactionRecord(ctx) !== current) return false;
|
|
87
|
+
const fiberStore = fiber?.store;
|
|
88
|
+
if (fiberStore?.compaction === current) delete fiberStore.compaction;
|
|
89
|
+
delete store[key];
|
|
90
|
+
return { store, key, current, fiber, fiberStore };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function commitRootStockCompaction(replacement) {
|
|
94
|
+
if (!replacement || replacement.committed) return false;
|
|
95
|
+
replacement.committed = true;
|
|
96
|
+
try {
|
|
97
|
+
// Cordis disposal is async. The replacement has already registered, so
|
|
98
|
+
// the old root fiber can now drain its effects without blocking startup.
|
|
99
|
+
const pending = replacement.fiber?.dispose?.();
|
|
100
|
+
pending?.catch?.(() => {});
|
|
101
|
+
} catch {}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function rollbackRootStockCompaction(replacement) {
|
|
106
|
+
if (!replacement || replacement.committed) return false;
|
|
107
|
+
const current = replacement.store?.[replacement.key];
|
|
108
|
+
if (current !== undefined && current !== replacement.current) return false;
|
|
109
|
+
replacement.store[replacement.key] = replacement.current;
|
|
110
|
+
if (replacement.fiberStore && replacement.fiberStore.compaction === undefined) {
|
|
111
|
+
replacement.fiberStore.compaction = replacement.current;
|
|
112
|
+
}
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function releaseRootStockCompaction(ctx, { deferDispose = false } = {}) {
|
|
117
|
+
const replacement = detachRootStockCompaction(ctx);
|
|
118
|
+
if (!replacement) return false;
|
|
119
|
+
if (deferDispose) {
|
|
120
|
+
replacement.committed = false;
|
|
121
|
+
replacement.commit = () => commitRootStockCompaction(replacement);
|
|
122
|
+
replacement.rollback = () => rollbackRootStockCompaction(replacement);
|
|
123
|
+
return replacement;
|
|
124
|
+
}
|
|
125
|
+
commitRootStockCompaction(replacement);
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
79
129
|
function visibleTakeover(ctx, reason) {
|
|
80
130
|
const line = `spine: ${MARK}。${reason}`;
|
|
81
131
|
console.error(line);
|
|
@@ -124,11 +174,16 @@ export default class LiveCompactEntry {
|
|
|
124
174
|
}
|
|
125
175
|
}
|
|
126
176
|
if (!loadError && !skipStock && Engine) {
|
|
177
|
+
let rootStockReplacement = false;
|
|
127
178
|
try {
|
|
128
|
-
|
|
179
|
+
rootStockReplacement = releaseRootStockCompaction(ctx, { deferDispose: true });
|
|
180
|
+
const engine = new Engine(ctx, config, resolvedConfig);
|
|
181
|
+
rootStockReplacement?.commit?.();
|
|
182
|
+
return engine;
|
|
129
183
|
} catch (error) {
|
|
130
184
|
cause = error instanceof Error ? error : new Error(String(error));
|
|
131
185
|
releaseCompaction(ctx, previousCompaction);
|
|
186
|
+
rootStockReplacement?.rollback?.();
|
|
132
187
|
skipStock = true;
|
|
133
188
|
}
|
|
134
189
|
}
|
package/thunder.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
const PROSE_TOKEN_CAP = 32000;
|
|
9
|
+
const CJK_CHARACTER = /[\p{Script=Han}\p{Script=Hangul}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}]/u;
|
|
9
10
|
|
|
10
11
|
export function sharedPrefixLength(previous, next) {
|
|
11
12
|
if (!previous || !next) return 0;
|
|
@@ -28,9 +29,17 @@ export function decideThunder({ previous, next, modelKind, prefixTokens, attachM
|
|
|
28
29
|
return "attach";
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
function limitProse(text, tokens) {
|
|
33
|
+
// Twelfths of a token preserve the estimate at exact budget boundaries.
|
|
34
|
+
const budget = Math.floor(tokens) * 12;
|
|
35
|
+
let cost = 0;
|
|
36
|
+
let end = 0;
|
|
37
|
+
for (const character of text) {
|
|
38
|
+
cost += CJK_CHARACTER.test(character) ? 8 : character.length * 3;
|
|
39
|
+
if (cost > budget) return text.slice(0, end);
|
|
40
|
+
end += character.length;
|
|
41
|
+
}
|
|
42
|
+
return text;
|
|
34
43
|
}
|
|
35
44
|
|
|
36
45
|
export function buildSendLess({ taskLine, uncovered, facts, proseTokens = PROSE_TOKEN_CAP }) {
|
|
@@ -42,17 +51,7 @@ export function buildSendLess({ taskLine, uncovered, facts, proseTokens = PROSE_
|
|
|
42
51
|
}
|
|
43
52
|
return `[unknown] ${String(fact)}`;
|
|
44
53
|
}).filter(Boolean);
|
|
45
|
-
|
|
46
|
-
if (estimateTokens(prose) > proseTokens) {
|
|
47
|
-
let low = 0;
|
|
48
|
-
let high = prose.length;
|
|
49
|
-
while (low < high) {
|
|
50
|
-
const mid = Math.ceil((low + high) / 2);
|
|
51
|
-
if (estimateTokens(prose.slice(0, mid)) <= proseTokens) low = mid;
|
|
52
|
-
else high = mid - 1;
|
|
53
|
-
}
|
|
54
|
-
prose = prose.slice(0, low);
|
|
55
|
-
}
|
|
54
|
+
const prose = limitProse(uncovered || "", proseTokens);
|
|
56
55
|
return [
|
|
57
56
|
taskLine || "Continue the current task.",
|
|
58
57
|
"Facts already copied locally:",
|