dsh-live-compact 1.1.11 → 1.1.12

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.11",
3
+ "version": "1.1.12",
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, retryable: true };
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, retryable: true };
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.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,
@@ -40,6 +42,10 @@ const lockedDirs = new Map();
40
42
  const lockedFiles = new Map();
41
43
  let shadowFuseState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
42
44
  const shadowWarnings = new Set();
45
+ const DECISION_ROTATION_INTERVAL_MS = 1000;
46
+ const decisionRotationAt = new Map();
47
+ const decisionUsageBytes = new Map();
48
+ const decisionUsageMtime = new Map();
43
49
 
44
50
  // No shared byte ledger. A positively dead holder leaves an immutable fence:
45
51
  // recovery enables the original shared scans, never ownership or an estimate.
@@ -48,7 +54,9 @@ const ROTATION_OWNER = ".spine-rotation.owner";
48
54
  const ROTATION_SHARED = ".spine-rotation.shared";
49
55
  const ROTATION_RECOVERED = ".spine-rotation.recovered";
50
56
  const USAGE_MAX_AGE_MS = 60_000;
51
- const rotationOwner = randomBytes(24).toString("hex");
57
+ const rotationOwner = /^[0-9a-f]{48}$/.test(workerData?.spineOwner || "")
58
+ ? workerData.spineOwner
59
+ : randomBytes(24).toString("hex");
52
60
  let rotationScope = null;
53
61
  let shadowUsage = null;
54
62
 
@@ -295,7 +303,13 @@ function releaseRotationGuard(root, identity, guard) {
295
303
 
296
304
  function acquireRotationGuard(root, identity) {
297
305
  const lock = join(root, ROTATION_LOCK);
298
- const record = { pid: process.pid, id: randomBytes(24).toString("hex") };
306
+ // A host transaction gets a fresh fence token every time. Managed workers
307
+ // keep their stable owner token so a timed-out parent can recover exactly
308
+ // the worker-held lock without touching another transaction.
309
+ const transactionId = workerData?.spineWorker === 1
310
+ ? rotationOwner
311
+ : randomBytes(24).toString("hex");
312
+ const record = { pid: process.pid, id: transactionId };
299
313
  let guard;
300
314
  try {
301
315
  const published = publishRotationRecord(lock, record);
@@ -483,6 +497,32 @@ export function withShadowRoot(dir, action) {
483
497
  }
484
498
  }
485
499
 
500
+ // Used only after a worker thread has been terminated. The owner token prevents
501
+ // a parent from deleting another process's live rotation lock when recovering
502
+ // a timed-out worker that shares process.pid with the host.
503
+ export function recoverTimedOutShadowWorker(root, owner) {
504
+ try {
505
+ const real = realDirectory(root);
506
+ const lock = join(real, ROTATION_LOCK);
507
+ const record = readRotationRecord(lock);
508
+ if (record.pid !== process.pid || record.id !== owner) return false;
509
+ try { unlinkSync(lock); } catch (error) { if (error?.code !== "ENOENT") return false; }
510
+ const ownerFile = join(real, ROTATION_OWNER);
511
+ try {
512
+ const current = readRotationOwner(ownerFile);
513
+ if (current.pid === process.pid && current.id === owner) unlinkSync(ownerFile);
514
+ } catch (error) {
515
+ if (error?.code !== "ENOENT") return false;
516
+ }
517
+ // Keep the shared fence immutable. It may represent another participant;
518
+ // recovery of this worker must never re-enable an exclusive fast path.
519
+ syncRotationDirectory(real);
520
+ return true;
521
+ } catch {
522
+ return false;
523
+ }
524
+ }
525
+
486
526
  export function resetShadowAccessState() {
487
527
  cachedSid = "";
488
528
  lockedDirs.clear();
@@ -583,7 +623,7 @@ export function noteShadowWarning(logger, error) {
583
623
  const SESSION_MARK = /^# spine-session (\S+)/;
584
624
 
585
625
  export function isPluginShadowName(name) {
586
- return PLUGIN_NAME.test(name);
626
+ return name === "spine-decisions.jsonl" || PLUGIN_NAME.test(name);
587
627
  }
588
628
 
589
629
  export function sanitizeSessionKey(key) {
@@ -621,6 +661,89 @@ export function shadowFileBody(sessionKey, body) {
621
661
 
622
662
  export const STATS_NAME = "spine-stats.json";
623
663
  export const CUTS_NAME = "spine-cuts.jsonl";
664
+ export const DECISIONS_NAME = "spine-decisions.jsonl";
665
+
666
+ export function appendDecision(dir, record = {}, { protectPaths = [] } = {}) {
667
+ try {
668
+ if (!existsSync(dir)) return false;
669
+ const body = `${JSON.stringify({
670
+ v: 1,
671
+ ts: new Date().toISOString(),
672
+ ...record,
673
+ })}\n`;
674
+ const file = join(dir, DECISIONS_NAME);
675
+ return withShadowRoot(dir, () => {
676
+ const path = scopedFile(file, rotationScope.root);
677
+ if (!path) throw coordinationError(new Error("shadow decision outside root scope"));
678
+ const rotationKey = rotationScope.root;
679
+ const now = Date.now();
680
+ const lastRotation = decisionRotationAt.get(rotationKey) || 0;
681
+ const incomingBytes = Buffer.byteLength(body, "utf8");
682
+ const cap = shadowMaxBytes();
683
+ let knownUsage = decisionUsageBytes.get(rotationKey);
684
+ let rootMtime = null;
685
+ try { rootMtime = statSync(rotationKey).mtimeMs; } catch {}
686
+ const knownMtime = decisionUsageMtime.get(rotationKey);
687
+ const fastPath = rotationScope.exclusive && shadowUsage?.root === rotationKey &&
688
+ shadowUsage?.identity === rotationScope.identity &&
689
+ now - lastRotation < DECISION_ROTATION_INTERVAL_MS &&
690
+ Number.isSafeInteger(knownUsage) && rootMtime !== null && knownMtime === rootMtime;
691
+ if (!fastPath) {
692
+ const rotation = rotateShadowLocked({
693
+ incomingBytes,
694
+ protectPath: path,
695
+ protectPaths,
696
+ sessionKey: record.sid || record.sessionId || "default",
697
+ cap,
698
+ });
699
+ if (!rotation.ok || rotation.oversize) return false;
700
+ decisionRotationAt.set(rotationKey, now);
701
+ knownUsage = rotation.used;
702
+ decisionUsageBytes.set(rotationKey, knownUsage);
703
+ try { decisionUsageMtime.set(rotationKey, statSync(rotationKey).mtimeMs); } catch {}
704
+ } else if (Number.isSafeInteger(knownUsage) && knownUsage + incomingBytes > cap) {
705
+ return false;
706
+ }
707
+ if (existsSync(path)) {
708
+ const beforeOpen = lstatSync(path, { bigint: true });
709
+ if (!beforeOpen.isFile() || beforeOpen.nlink !== 1n) {
710
+ throw coordinationError(new Error("shadow decision is not a single-link regular file"));
711
+ }
712
+ const noFollow = fsConstants.O_NOFOLLOW;
713
+ const fd = openSync(path, fsConstants.O_WRONLY | fsConstants.O_APPEND | (noFollow ?? 0));
714
+ try {
715
+ const opened = fstatSync(fd, { bigint: true });
716
+ const named = lstatSync(path, { bigint: true });
717
+ if (!opened.isFile() || opened.nlink !== 1n || !named.isFile() || named.nlink !== 1n ||
718
+ opened.dev !== named.dev || opened.ino !== named.ino) {
719
+ throw coordinationError(new Error("shadow decision identity changed"));
720
+ }
721
+ writeFileSync(fd, body);
722
+ fsyncSync(fd);
723
+ } finally {
724
+ closeSync(fd);
725
+ }
726
+ if (shadowUsage && isPluginShadowName(basename(path))) {
727
+ shadowUsage.bytes += Buffer.byteLength(body, "utf8");
728
+ }
729
+ decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
730
+ if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
731
+ } else {
732
+ writeShadowFileLocked(path, body, {}, {
733
+ exclusive: false,
734
+ write: writeFileSync,
735
+ unlink: unlinkSync,
736
+ accessPath: file,
737
+ });
738
+ decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
739
+ if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
740
+ }
741
+ return true;
742
+ });
743
+ } catch {
744
+ return false;
745
+ }
746
+ }
624
747
 
625
748
  export function readCutStats(dir) {
626
749
  try {
@@ -643,6 +766,91 @@ export function drainRewrite(notes) {
643
766
  return Math.max(0, (cuts[0].afterPrefix || 0) - later);
644
767
  }
645
768
 
769
+ function acquireStatsLock(lock) {
770
+ for (let attempt = 0; attempt < 3; attempt += 1) {
771
+ let fd;
772
+ let created = false;
773
+ try {
774
+ fd = openSync(lock, "wx", 0o600);
775
+ created = true;
776
+ writeFileSync(fd, String(process.pid));
777
+ fsyncSync(fd);
778
+ return fd;
779
+ } catch (error) {
780
+ if (fd !== undefined) {
781
+ try { closeSync(fd); } catch {}
782
+ }
783
+ if (created) {
784
+ try { unlinkSync(lock); } catch {}
785
+ }
786
+ if (error?.code !== "EEXIST") return null;
787
+ let pid = null;
788
+ let observedText = "";
789
+ let observedStat;
790
+ try {
791
+ observedText = readFileSync(lock, "utf8").trim();
792
+ pid = /^[1-9]\d*$/.test(observedText) ? Number(observedText) : null;
793
+ observedStat = statSync(lock);
794
+ } catch {
795
+ return null;
796
+ }
797
+ const dead = pid !== null && processAlive(pid) === false;
798
+ // Pre-1.1.12 locks were empty files. Only recover one that is old enough
799
+ // to be a legacy crash artifact; a just-created empty lock may still be
800
+ // between open(wx) and its PID write.
801
+ const legacyEmpty = observedText === "" && Number.isFinite(observedStat?.mtimeMs) &&
802
+ Date.now() - observedStat.mtimeMs >= 1000;
803
+ if (dead || legacyEmpty) {
804
+ const recovery = `${lock}.recover`;
805
+ let recoveryFd;
806
+ let removed = false;
807
+ try {
808
+ recoveryFd = openSync(recovery, "wx", 0o600);
809
+ writeFileSync(recoveryFd, String(process.pid));
810
+ fsyncSync(recoveryFd);
811
+ } catch (recoveryError) {
812
+ if (recoveryFd !== undefined) {
813
+ try { closeSync(recoveryFd); } catch {}
814
+ try { unlinkSync(recovery); } catch {}
815
+ }
816
+ if (recoveryError?.code === "EEXIST") {
817
+ let recoveryPid = null;
818
+ try {
819
+ const text = readFileSync(recovery, "utf8").trim();
820
+ recoveryPid = /^[1-9]\d*$/.test(text) ? Number(text) : null;
821
+ } catch {}
822
+ if (recoveryPid !== null && processAlive(recoveryPid) === false) {
823
+ try { unlinkSync(recovery); } catch {}
824
+ continue;
825
+ }
826
+ }
827
+ return null;
828
+ }
829
+ try {
830
+ let current = "";
831
+ let currentStat;
832
+ try {
833
+ current = readFileSync(lock, "utf8").trim();
834
+ currentStat = statSync(lock);
835
+ } catch {}
836
+ const unchanged = current === observedText && currentStat && observedStat &&
837
+ currentStat.dev === observedStat.dev && currentStat.ino === observedStat.ino &&
838
+ currentStat.size === observedStat.size && currentStat.mtimeMs === observedStat.mtimeMs;
839
+ if (unchanged && (dead || legacyEmpty)) {
840
+ try { unlinkSync(lock); removed = true; } catch {}
841
+ }
842
+ } finally {
843
+ try { closeSync(recoveryFd); } catch {}
844
+ try { unlinkSync(recovery); } catch {}
845
+ }
846
+ if (removed) continue;
847
+ }
848
+ return null;
849
+ }
850
+ }
851
+ return null;
852
+ }
853
+
646
854
  export function flushDrainStats(dir, notes, meta = {}) {
647
855
  const cuts = (notes || []).filter((note) => note?.kind === "cut" && note.saved > 0);
648
856
  const charged = drainRewrite(notes);
@@ -677,12 +885,8 @@ function recordDrainStats(dir, { cuts = 0, saved = 0, rewrite = 0 } = {}) {
677
885
  const file = join(dir, STATS_NAME);
678
886
  const lock = join(dir, "spine-stats.lock");
679
887
  const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
680
- let fd;
681
- try {
682
- fd = openSync(lock, "wx");
683
- } catch {
684
- return null;
685
- }
888
+ const fd = acquireStatsLock(lock);
889
+ if (fd === null) return null;
686
890
  try {
687
891
  const prev = readCutStats(dir);
688
892
  const locked = {
@@ -711,12 +915,8 @@ export function recordCutStats(dir, { saved = 0, rewrite = 0 } = {}) {
711
915
  const file = join(dir, STATS_NAME);
712
916
  const lock = join(dir, "spine-stats.lock");
713
917
  const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
714
- let fd;
715
- try {
716
- fd = openSync(lock, "wx");
717
- } catch {
718
- return null;
719
- }
918
+ const fd = acquireStatsLock(lock);
919
+ if (fd === null) return null;
720
920
  try {
721
921
  const prev = readCutStats(dir);
722
922
  const locked = {
@@ -1100,6 +1300,11 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1100
1300
  }
1101
1301
  renameSync(target, file);
1102
1302
  protectedPath = file;
1303
+ if (basename(file) !== DECISIONS_NAME) {
1304
+ decisionRotationAt.delete(rotationScope.root);
1305
+ decisionUsageBytes.delete(rotationScope.root);
1306
+ decisionUsageMtime.delete(rotationScope.root);
1307
+ }
1103
1308
 
1104
1309
  // Keep the caller's spelling for the permission cache/runner. The opened
1105
1310
  // descriptor and the final path now refer to the same published object.
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
- return new Engine(ctx, config, resolvedConfig);
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
  }