dsh-live-compact 1.1.12 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-live-compact",
3
- "version": "1.1.12",
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>",
@@ -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
@@ -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;
@@ -533,6 +549,27 @@ export function resetShadowAccessState() {
533
549
  shadowWarnings.clear();
534
550
  }
535
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
+
536
573
  export function shadowAccessFused() {
537
574
  return Atomics.load(shadowFuseState, 0) !== 0;
538
575
  }
@@ -602,7 +639,7 @@ function lockedDirectory(entry) {
602
639
  const previous = lockedDirs.get(entry.absolute) ?? lockedDirs.get(entry.canonical);
603
640
  if (!previous) return false;
604
641
  if (!sameAccessEntry(previous, entry)) throw new Error("spine: shadow permission directory identity changed");
605
- lockedDirs.set(entry.absolute, previous);
642
+ rememberLockedEntry(lockedDirs, entry.absolute, previous);
606
643
  return true;
607
644
  }
608
645
 
@@ -1007,7 +1044,6 @@ try {
1007
1044
  exit 1
1008
1045
  }
1009
1046
  `;
1010
- const WINDOWS_ACL_COMMAND = Buffer.from(WINDOWS_ACL_SCRIPT, "utf16le").toString("base64");
1011
1047
 
1012
1048
  export function shadowAccessPlan(platform = process.platform, userSid = "", kind = "dir") {
1013
1049
  if (platform === "win32") {
@@ -1104,17 +1140,18 @@ export function defaultShadowAccessRunner({
1104
1140
  });
1105
1141
  const result = execFile(
1106
1142
  powershellPath,
1107
- ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", WINDOWS_ACL_COMMAND],
1143
+ // Issue #67 reported a build that rejects -EncodedCommand after whoami.
1144
+ ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_ACL_SCRIPT],
1108
1145
  { env: childEnv, encoding: "utf8", stdio: "pipe", windowsHide: true, timeout: 15000, maxBuffer: 65536 },
1109
1146
  );
1110
1147
  if (String(result).trim() !== "DSH_SHADOW_ACL_OK") throw new Error("spine: shadow DACL verification not confirmed");
1111
1148
  const after = accessEntry(path, kind);
1112
1149
  if (!sameAccessEntry(before, after)) throw new Error("spine: shadow permission target identity changed");
1113
1150
  if (kind === "dir") {
1114
- lockedDirs.set(after.absolute, after);
1115
- lockedDirs.set(after.canonical, after);
1151
+ rememberLockedEntry(lockedDirs, after.absolute, after);
1152
+ rememberLockedEntry(lockedDirs, after.canonical, after);
1116
1153
  } else {
1117
- lockedFiles.set(after.canonical, after);
1154
+ rememberLockedEntry(lockedFiles, after.canonical, after);
1118
1155
  }
1119
1156
  } catch (error) {
1120
1157
  error.step = kind === "file" ? "file" : "dir";
@@ -1180,7 +1217,7 @@ export function tightenCreatedShadow(file, fd, access, { remember = true, skipRu
1180
1217
  if (!entry.identity || entry.identity !== accessIdentity(opened) || opened.nlink !== 1n) {
1181
1218
  throw new Error("spine: shadow published file identity changed");
1182
1219
  }
1183
- if (remember) lockedFiles.set(entry.canonical, entry);
1220
+ if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
1184
1221
  return;
1185
1222
  } catch (cause) {
1186
1223
  tripFuse();
@@ -1199,7 +1236,7 @@ export function tightenCreatedShadow(file, fd, access, { remember = true, skipRu
1199
1236
  throw new Error("spine: shadow created file identity changed");
1200
1237
  }
1201
1238
  // Only this wx-created object is known to inherit our confirmed DACL.
1202
- if (remember) lockedFiles.set(entry.canonical, entry);
1239
+ if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
1203
1240
  return;
1204
1241
  }
1205
1242
  } catch (cause) {
@@ -1300,6 +1337,9 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1300
1337
  }
1301
1338
  renameSync(target, file);
1302
1339
  protectedPath = file;
1340
+ // staging 临时名一次性且永不复用:发布后其锁表条目已成死重,随 rename 同步
1341
+ // 释放,避免每次保存向 lockedFiles 残留一个永不复用的条目。
1342
+ releaseLockedFile(target);
1303
1343
  if (basename(file) !== DECISIONS_NAME) {
1304
1344
  decisionRotationAt.delete(rotationScope.root);
1305
1345
  decisionUsageBytes.delete(rotationScope.root);
@@ -1593,6 +1633,9 @@ function rotateShadowLocked({
1593
1633
  break;
1594
1634
  }
1595
1635
  }
1636
+ // 文件已被删除(或本就 ENOENT):同步释放其锁表条目,使锁表随 rotation
1637
+ // 收敛而不是只增不减。unlink 失败(文件仍在盘上)时不会走到这里。
1638
+ releaseLockedFile(file.path);
1596
1639
  used -= file.size;
1597
1640
  freed += file.size;
1598
1641
  deleted += 1;
@@ -1600,6 +1643,9 @@ function rotateShadowLocked({
1600
1643
  try {
1601
1644
  unlink(`${file.path}.meta.json`);
1602
1645
  } catch {}
1646
+ // meta.json 通常已随之删除;即便 unlink 因占用等失败,释放缓存条目也是
1647
+ // 安全方向——下次 tightenShadow 会重新收紧(fail-closed),不会绕过锁。
1648
+ releaseLockedFile(`${file.path}.meta.json`);
1603
1649
  }
1604
1650
  }
1605
1651
  const fits = used + incomingBytes <= cap;
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 estimateTokens(text) {
32
- const cjk = (text.match(/[\u4e00-\u9fff]/g) || []).length;
33
- return Math.ceil(cjk / 1.5 + (text.length - cjk) / 4);
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
- let prose = uncovered || "";
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:",