dsh-live-compact 1.1.13 → 1.1.15

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/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,
@@ -58,10 +58,16 @@ const lockedFiles = new Map();
58
58
  const MAX_LOCK_ENTRIES = 4096;
59
59
  let shadowFuseState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
60
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();
61
+ let rotationScanCount = 0;
62
+ let decisionWriteFailures = 0;
63
+
64
+ export function getRotationScanCount() {
65
+ return rotationScanCount;
66
+ }
67
+
68
+ export function getDecisionWriteFailureCount() {
69
+ return decisionWriteFailures;
70
+ }
65
71
 
66
72
  // No shared byte ledger. A positively dead holder leaves an immutable fence:
67
73
  // recovery enables the original shared scans, never ownership or an estimate.
@@ -88,7 +94,7 @@ function realDirectory(dir) {
88
94
  return realpathSync.native(dir);
89
95
  }
90
96
 
91
- function directoryIdentity(dir) {
97
+ export function directoryIdentity(dir) {
92
98
  const info = statSync(dir, { bigint: true });
93
99
  if (!info.isDirectory() || info.ino <= 0n) return "";
94
100
  return `${info.dev}:${info.ino}`;
@@ -293,6 +299,18 @@ function hasLinklessRecovery(root, record) {
293
299
  }
294
300
  }
295
301
 
302
+ function publishLinklessRecovery(root, record) {
303
+ let fd;
304
+ try {
305
+ fd = openSync(join(root, linklessRecoveryName(record)), "wx", 0o600);
306
+ } catch (error) {
307
+ if (error?.code === "EEXIST" && hasLinklessRecovery(root, record)) return;
308
+ throw error;
309
+ }
310
+ try { fsyncSync(fd); } finally { closeSync(fd); }
311
+ if (!hasLinklessRecovery(root, record)) throw new Error("shadow recovery fence disappeared");
312
+ }
313
+
296
314
  function verifyRotationGuard(root, identity, guard) {
297
315
  if (identity && directoryIdentity(root) !== identity) throw new Error("shadow directory identity changed");
298
316
  if (!guard.record) {
@@ -368,21 +386,36 @@ function recoverRotationGuard(root, identity, guard) {
368
386
  try { recovery = readRotationRecord(recovered); } catch (error) {
369
387
  if (error?.code !== "ENOENT") throw error;
370
388
  }
371
- if (recovery && !sameRotationRecord(recovery, guard.record)) throw new Error("shadow recovery identity changed");
372
- const knownDead = !!recovery || hasLinklessRecovery(root, guard.record);
389
+ const priorRecovery = recovery && sameRotationRecord(recovery, guard.record);
390
+ const knownDead = priorRecovery || hasLinklessRecovery(root, guard.record);
373
391
  if (!knownDead) {
374
392
  let dead = false;
375
393
  try { process.kill(guard.record.pid, 0); } catch (error) { dead = error?.code === "ESRCH"; }
376
- if (!dead) throw new Error("shadow holder is live or its death is unknown");
394
+ if (!dead) {
395
+ if (recovery) {
396
+ throw Object.assign(new Error("shadow recovery identity changed"), { step: "rotation-recovery-conflict" });
397
+ }
398
+ throw new Error("shadow holder is live or its death is unknown");
399
+ }
377
400
  }
378
401
  // Persist shared participation BEFORE permitting any action or recording
379
402
  // recovery. A later reused PID cannot resurrect this exact proven-dead token.
380
403
  persistRotationShared(root);
381
404
  verifyRotationGuard(root, identity, guard);
382
405
  if (!knownDead) {
383
- try { publishRotationRecord(recovered, guard.record); } catch (error) {
384
- if (error?.code === "ESHADOWLINKUNSUPPORTED") persistRotationFence(root, linklessRecoveryName(guard.record));
385
- else if (error?.code !== "EEXIST" || !sameRotationRecord(readRotationRecord(recovered), guard.record)) throw error;
406
+ if (recovery) {
407
+ publishLinklessRecovery(root, guard.record);
408
+ } else {
409
+ try {
410
+ publishRotationRecord(recovered, guard.record);
411
+ } catch (error) {
412
+ if (error?.code === "ESHADOWLINKUNSUPPORTED" ||
413
+ (error?.code === "EEXIST" && !sameRotationRecord(readRotationRecord(recovered), guard.record))) {
414
+ publishLinklessRecovery(root, guard.record);
415
+ } else if (error?.code !== "EEXIST") {
416
+ throw error;
417
+ }
418
+ }
386
419
  }
387
420
  syncRotationDirectory(root);
388
421
  }
@@ -628,7 +661,7 @@ function accessEntry(path, kind) {
628
661
  if (kind === "dir" ? !info.isDirectory() : !info.isFile() || info.nlink !== 1n) {
629
662
  throw new Error("spine: unsupported shadow permission target");
630
663
  }
631
- return { absolute, canonical, identity: accessIdentity(info) };
664
+ return { absolute, canonical, identity: accessIdentity(info), mode: info.mode };
632
665
  }
633
666
 
634
667
  function sameAccessEntry(left, right) {
@@ -649,10 +682,15 @@ export function shadowDirLocked(path) {
649
682
 
650
683
  export function noteShadowWarning(logger, error) {
651
684
  const code = error?.code || "ESHADOWACCESS";
652
- if (shadowWarnings.has(code)) return;
653
- shadowWarnings.add(code);
654
- const status = error?.cause?.status ?? error?.status;
655
685
  const step = error?.step || error?.cause?.step || "";
686
+ const separateReason = step === "rotation-recovery-conflict" || step === "dir-mode" || step === "file-mode";
687
+ const key = separateReason ? `${code}:${step}` : code;
688
+ if (shadowWarnings.has(key)) return;
689
+ shadowWarnings.add(key);
690
+ if (error?.code === "ESHADOWACCESS") {
691
+ appendMaintenanceStatus(shadowDirectory(), { phase: "shadow-access", code: "ESHADOWACCESS" });
692
+ }
693
+ const status = error?.cause?.status ?? error?.status;
656
694
  const where = step ? ` ${step}` : "";
657
695
  const exit = status == null ? "" : ` exit ${status}`;
658
696
  logger?.warn?.(`spine: shadow permission failed ${code}${where}${exit}`);
@@ -660,7 +698,7 @@ export function noteShadowWarning(logger, error) {
660
698
  const SESSION_MARK = /^# spine-session (\S+)/;
661
699
 
662
700
  export function isPluginShadowName(name) {
663
- return name === "spine-decisions.jsonl" || PLUGIN_NAME.test(name);
701
+ return PLUGIN_NAME.test(name);
664
702
  }
665
703
 
666
704
  export function sanitizeSessionKey(key) {
@@ -699,87 +737,26 @@ export function shadowFileBody(sessionKey, body) {
699
737
  export const STATS_NAME = "spine-stats.json";
700
738
  export const CUTS_NAME = "spine-cuts.jsonl";
701
739
  export const DECISIONS_NAME = "spine-decisions.jsonl";
702
-
703
- export function appendDecision(dir, record = {}, { protectPaths = [] } = {}) {
740
+ export const MAINTENANCE_NAME = "spine-maintenance.jsonl";
741
+ const CUTS_LOG_MAX_BYTES = 1024 * 1024;
742
+ const DECISIONS_LOG_MAX_BYTES = 1024 * 1024;
743
+ const MAINTENANCE_LOG_MAX_BYTES = 256 * 1024;
744
+
745
+ // The third argument remains accepted for callers that passed rotation protection.
746
+ export function appendDecision(dir, record = {}, _options = {}) {
747
+ if (!existsSync(dir)) return false;
704
748
  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;
749
+ const root = directoryIdentity(dir);
750
+ tightenShadow(dir, "dir");
751
+ const written = withCutStatsLock(dir, () => {
752
+ if (!root || directoryIdentity(dir) !== root) return false;
753
+ const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record, decisionWriteFailures });
754
+ return appendBoundedLog(join(dir, DECISIONS_NAME), `${line}\n`, DECISIONS_LOG_MAX_BYTES, true);
779
755
  });
780
- } catch {
781
- return false;
782
- }
756
+ if (written === true) return true;
757
+ } catch {}
758
+ decisionWriteFailures++;
759
+ return false;
783
760
  }
784
761
 
785
762
  export function readCutStats(dir) {
@@ -888,11 +865,161 @@ function acquireStatsLock(lock) {
888
865
  return null;
889
866
  }
890
867
 
868
+ function withCutStatsLock(dir, action) {
869
+ const lock = join(dir, "spine-stats.lock");
870
+ const fd = acquireStatsLock(lock);
871
+ if (fd === null) return null;
872
+ try {
873
+ return action();
874
+ } catch {
875
+ return null;
876
+ } finally {
877
+ try { closeSync(fd); } catch {}
878
+ try { unlinkSync(lock); } catch {}
879
+ }
880
+ }
881
+
882
+ function completeLogSuffix(bytes, discardFirst) {
883
+ const first = discardFirst ? bytes.indexOf(0x0a) + 1 : 0;
884
+ const end = bytes.lastIndexOf(0x0a) + 1;
885
+ if ((discardFirst && !first) || end <= first) return Buffer.alloc(0);
886
+ return bytes.subarray(first, end);
887
+ }
888
+
889
+ function logSuffix(fd, size, budget) {
890
+ // Include one byte before the retained range to recognize an exact line boundary.
891
+ const offset = Math.max(0, size - budget - 1);
892
+ const bytes = Buffer.alloc(size - offset);
893
+ let read = 0;
894
+ while (read < bytes.length) {
895
+ const count = readSync(fd, bytes, read, bytes.length - read, offset + read);
896
+ if (!count) break;
897
+ read += count;
898
+ }
899
+ return completeLogSuffix(bytes.subarray(0, read), size > budget);
900
+ }
901
+
902
+ function verifyLogFile(file, observed) {
903
+ const named = lstatSync(file, { bigint: true });
904
+ if (!named.isFile() || named.nlink !== 1n || !observed.isFile() || observed.nlink !== 1n ||
905
+ !accessIdentity(named) || accessIdentity(named) !== accessIdentity(observed) ||
906
+ named.size !== observed.size || named.mtimeNs !== observed.mtimeNs || named.ctimeNs !== observed.ctimeNs) {
907
+ throw new Error("spine: log identity changed");
908
+ }
909
+ }
910
+
911
+ function replaceLog(file, observed, retained, incoming, privateFile) {
912
+ const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
913
+ const fd = openSync(tmp, "wx", 0o600);
914
+ try {
915
+ try {
916
+ if (privateFile) tightenCreatedShadow(tmp, fd);
917
+ writeFileSync(fd, Buffer.concat([retained, incoming]));
918
+ fsyncSync(fd);
919
+ } finally {
920
+ closeSync(fd);
921
+ }
922
+ verifyLogFile(file, observed);
923
+ renameSync(tmp, file);
924
+ } finally {
925
+ try { unlinkSync(tmp); } catch {}
926
+ if (privateFile) releaseLockedFile(tmp);
927
+ }
928
+ }
929
+
930
+ function appendBoundedLog(file, body, maxBytes, privateFile = false) {
931
+ const bytes = Buffer.from(body);
932
+ const incoming = bytes.length <= maxBytes
933
+ ? bytes
934
+ : completeLogSuffix(bytes.subarray(bytes.length - maxBytes - 1), true);
935
+ let before;
936
+ try {
937
+ before = lstatSync(file, { bigint: true });
938
+ } catch (error) {
939
+ if (error?.code !== "ENOENT") throw error;
940
+ if (!incoming.length) return false;
941
+ if (!privateFile) writeFileSync(file, incoming, { flag: "wx", mode: 0o600 });
942
+ else {
943
+ const fd = openSync(file, "wx", 0o600);
944
+ try {
945
+ tightenCreatedShadow(file, fd);
946
+ writeFileSync(fd, incoming);
947
+ fsyncSync(fd);
948
+ } catch (error) {
949
+ if (shadowFileIdentity(file, fd)) try { unlinkSync(file); } catch {}
950
+ throw error;
951
+ } finally {
952
+ closeSync(fd);
953
+ }
954
+ }
955
+ return true;
956
+ }
957
+ if (!before.isFile() || before.nlink !== 1n) throw new Error("spine: unsupported log target");
958
+ const fd = openSync(file, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW ?? 0));
959
+ let observed;
960
+ let retained;
961
+ try {
962
+ observed = fstatSync(fd, { bigint: true });
963
+ verifyLogFile(file, before);
964
+ verifyLogFile(file, observed);
965
+ if (privateFile) {
966
+ const windows = process.platform === "win32";
967
+ if (windows) tightenShadow(file, "file");
968
+ tightenCreatedShadow(file, fd, {}, { skipRunner: windows });
969
+ observed = fstatSync(fd, { bigint: true });
970
+ verifyLogFile(file, observed);
971
+ }
972
+ const size = Number(observed.size);
973
+ if (!Number.isSafeInteger(size)) throw new Error("spine: invalid log size");
974
+ const last = Buffer.alloc(1);
975
+ const complete = size === 0 || (readSync(fd, last, 0, 1, size - 1) === 1 && last[0] === 0x0a);
976
+ if (complete && size + incoming.length <= maxBytes) {
977
+ if (incoming.length) {
978
+ writeFileSync(fd, incoming);
979
+ if (privateFile) fsyncSync(fd);
980
+ }
981
+ return incoming.length > 0;
982
+ }
983
+ retained = logSuffix(fd, size, maxBytes - incoming.length);
984
+ } finally {
985
+ closeSync(fd);
986
+ }
987
+ replaceLog(file, observed, retained, incoming, privateFile);
988
+ return incoming.length > 0;
989
+ }
990
+
991
+ export function appendMaintenanceStatus(dir, record) {
992
+ try {
993
+ if (!existsSync(dir)) return false;
994
+ const root = ensureShadowDirIdentity(dir);
995
+ return withCutStatsLock(dir, () => {
996
+ if (!root || directoryIdentity(dir) !== root) return false;
997
+ const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record, decisionWriteFailures });
998
+ appendBoundedLog(join(dir, MAINTENANCE_NAME), `${line}\n`, MAINTENANCE_LOG_MAX_BYTES);
999
+ return true;
1000
+ }) === true;
1001
+ } catch {
1002
+ return false;
1003
+ }
1004
+ }
1005
+
1006
+ function writeCutStats(dir, next) {
1007
+ const file = join(dir, STATS_NAME);
1008
+ const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
1009
+ try {
1010
+ writeFileSync(tmp, JSON.stringify(next));
1011
+ renameSync(tmp, file);
1012
+ return next;
1013
+ } finally {
1014
+ try { unlinkSync(tmp); } catch {}
1015
+ }
1016
+ }
1017
+
891
1018
  export function flushDrainStats(dir, notes, meta = {}) {
892
1019
  const cuts = (notes || []).filter((note) => note?.kind === "cut" && note.saved > 0);
893
1020
  const charged = drainRewrite(notes);
894
1021
  const saved = cuts.reduce((sum, note) => sum + note.saved, 0);
895
- if (cuts.length) recordDrainStats(dir, { cuts: cuts.length, saved, rewrite: charged });
1022
+ const firstCut = (notes || []).findIndex((note) => note?.kind === "cut");
896
1023
  const lines = (notes || []).map((note, index) => JSON.stringify({
897
1024
  v: 1,
898
1025
  ts: new Date().toISOString(),
@@ -901,7 +1028,7 @@ export function flushDrainStats(dir, notes, meta = {}) {
901
1028
  pass: index,
902
1029
  drain: meta.drain === true,
903
1030
  saved: note.saved || 0,
904
- rewriteCharged: note.kind === "cut" && index === (notes || []).findIndex((item) => item?.kind === "cut") ? charged : 0,
1031
+ rewriteCharged: index === firstCut ? charged : 0,
905
1032
  tailBeyondKept: note.tailBeyondKept || 0,
906
1033
  prefix: note.prefix || 0,
907
1034
  afterPrefix: note.afterPrefix || 0,
@@ -910,69 +1037,35 @@ export function flushDrainStats(dir, notes, meta = {}) {
910
1037
  gate: note.gate || "cut",
911
1038
  }));
912
1039
  if (!lines.length) return charged;
913
- try {
914
- appendFileSync(join(dir, CUTS_NAME), `${lines.join("\n")}\n`);
915
- } catch {}
916
- return charged;
917
- }
918
-
919
- function recordDrainStats(dir, { cuts = 0, saved = 0, rewrite = 0 } = {}) {
920
- if (!(cuts > 0) || !(saved > 0)) return null;
921
- try {
922
- const file = join(dir, STATS_NAME);
923
- const lock = join(dir, "spine-stats.lock");
924
- const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
925
- const fd = acquireStatsLock(lock);
926
- if (fd === null) return null;
927
- try {
928
- const prev = readCutStats(dir);
929
- const locked = {
930
- cuts: prev.cuts + cuts,
931
- savedTokens: prev.savedTokens + saved,
932
- rewriteTokens: prev.rewriteTokens + rewrite,
933
- drains: (Number(prev.drains) || 0) + 1,
934
- updatedAt: new Date().toISOString(),
935
- };
936
- writeFileSync(tmp, JSON.stringify(locked));
937
- renameSync(tmp, file);
938
- return locked;
939
- } finally {
940
- try { unlinkSync(tmp); } catch {}
941
- closeSync(fd);
942
- try { unlinkSync(lock); } catch {}
1040
+ withCutStatsLock(dir, () => {
1041
+ if (cuts.length) {
1042
+ try {
1043
+ const prev = readCutStats(dir);
1044
+ writeCutStats(dir, {
1045
+ cuts: prev.cuts + cuts.length,
1046
+ savedTokens: prev.savedTokens + saved,
1047
+ rewriteTokens: prev.rewriteTokens + charged,
1048
+ drains: prev.drains + 1,
1049
+ updatedAt: new Date().toISOString(),
1050
+ });
1051
+ } catch {}
943
1052
  }
944
- } catch {
945
- return null;
946
- }
1053
+ try { appendBoundedLog(join(dir, CUTS_NAME), `${lines.join("\n")}\n`, CUTS_LOG_MAX_BYTES); } catch {}
1054
+ });
1055
+ return charged;
947
1056
  }
948
1057
 
949
1058
  export function recordCutStats(dir, { saved = 0, rewrite = 0 } = {}) {
950
1059
  if (!(saved > 0)) return readCutStats(dir);
951
- try {
952
- const file = join(dir, STATS_NAME);
953
- const lock = join(dir, "spine-stats.lock");
954
- const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
955
- const fd = acquireStatsLock(lock);
956
- if (fd === null) return null;
957
- try {
958
- const prev = readCutStats(dir);
959
- const locked = {
960
- cuts: prev.cuts + 1,
961
- savedTokens: prev.savedTokens + saved,
962
- rewriteTokens: prev.rewriteTokens + rewrite,
963
- updatedAt: new Date().toISOString(),
964
- };
965
- writeFileSync(tmp, JSON.stringify(locked));
966
- renameSync(tmp, file);
967
- return locked;
968
- } finally {
969
- try { unlinkSync(tmp); } catch {}
970
- closeSync(fd);
971
- try { unlinkSync(lock); } catch {}
972
- }
973
- } catch {
974
- return null;
975
- }
1060
+ return withCutStatsLock(dir, () => {
1061
+ const prev = readCutStats(dir);
1062
+ return writeCutStats(dir, {
1063
+ cuts: prev.cuts + 1,
1064
+ savedTokens: prev.savedTokens + saved,
1065
+ rewriteTokens: prev.rewriteTokens + rewrite,
1066
+ updatedAt: new Date().toISOString(),
1067
+ });
1068
+ });
976
1069
  }
977
1070
 
978
1071
  function validWindowsSid(sid) {
@@ -1071,6 +1164,15 @@ export function shadowAccessPlan(platform = process.platform, userSid = "", kind
1071
1164
  };
1072
1165
  }
1073
1166
 
1167
+ function verifyPosixShadowMode(mode, expected, kind) {
1168
+ if ((mode & 0o777n) !== BigInt(expected)) {
1169
+ const actual = (mode & 0o777n).toString(8).padStart(4, "0");
1170
+ const error = new Error(`spine: shadow ${kind} mode ${actual} did not match ${expected.toString(8).padStart(4, "0")}`);
1171
+ error.step = `${kind}-mode`;
1172
+ throw error;
1173
+ }
1174
+ }
1175
+
1074
1176
  export function defaultShadowAccessRunner({
1075
1177
  path,
1076
1178
  kind,
@@ -1080,7 +1182,14 @@ export function defaultShadowAccessRunner({
1080
1182
  } = {}) {
1081
1183
  if (platform !== "win32") {
1082
1184
  const plan = shadowAccessPlan(platform);
1083
- chmodSync(path, kind === "dir" ? plan.dirMode : plan.fileMode);
1185
+ const expected = kind === "dir" ? plan.dirMode : plan.fileMode;
1186
+ const before = accessEntry(path, kind);
1187
+ chmodSync(before.canonical, expected);
1188
+ const after = accessEntry(path, kind);
1189
+ if (!sameAccessEntry(before, after)) {
1190
+ throw new Error("spine: shadow permission target identity changed");
1191
+ }
1192
+ verifyPosixShadowMode(after.mode, expected, kind);
1084
1193
  return true;
1085
1194
  }
1086
1195
 
@@ -1209,45 +1318,61 @@ export function ensureShadowDir(dir, access = {}) {
1209
1318
  return dir;
1210
1319
  }
1211
1320
 
1212
- export function tightenCreatedShadow(file, fd, access, { remember = true, skipRunner = false } = {}) {
1213
- if (skipRunner) {
1214
- try {
1215
- const entry = accessEntry(file);
1216
- const opened = fstatSync(fd, { bigint: true });
1217
- if (!entry.identity || entry.identity !== accessIdentity(opened) || opened.nlink !== 1n) {
1218
- throw new Error("spine: shadow published file identity changed");
1219
- }
1220
- if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
1221
- return;
1222
- } catch (cause) {
1223
- tripFuse();
1224
- const error = new Error("spine: shadow permission action failed; backup refused", { cause });
1225
- error.code = "ESHADOWACCESS";
1226
- error.step = "file";
1227
- throw error;
1228
- }
1321
+ export function ensureShadowDirIdentity(dir, access = {}) {
1322
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1323
+ const identity = directoryIdentity(dir);
1324
+ tightenShadow(dir, "dir", access);
1325
+ if (identity && directoryIdentity(dir) !== identity) {
1326
+ throw Object.assign(new Error("spine: shadow directory identity changed"), { code: "ESHADOWACCESS", step: "dir" });
1229
1327
  }
1230
- if ((access.platform ?? process.platform) === "win32" && !access.runner && !shadowAccessFused()) {
1231
- try {
1232
- if (shadowDirLocked(dirname(file))) {
1233
- const entry = accessEntry(file, "file");
1234
- const opened = fstatSync(fd, { bigint: true });
1235
- if (!entry.identity || entry.identity !== accessIdentity(opened) || opened.nlink !== 1n) {
1236
- throw new Error("spine: shadow created file identity changed");
1237
- }
1238
- // Only this wx-created object is known to inherit our confirmed DACL.
1239
- if (remember) rememberLockedEntry(lockedFiles, entry.canonical, entry);
1240
- return;
1241
- }
1242
- } catch (cause) {
1243
- tripFuse();
1244
- const error = new Error("spine: shadow permission action failed; backup refused", { cause });
1245
- error.code = "ESHADOWACCESS";
1246
- error.step = "file";
1247
- throw error;
1328
+ return identity;
1329
+ }
1330
+
1331
+ function openedShadowEntry(file, fd) {
1332
+ const entry = accessEntry(file, "file");
1333
+ const opened = fstatSync(fd, { bigint: true });
1334
+ if (!opened.isFile() || opened.nlink !== 1n || !entry.identity || entry.identity !== accessIdentity(opened)) {
1335
+ throw new Error("spine: shadow created file identity changed");
1336
+ }
1337
+ return { entry, mode: opened.mode };
1338
+ }
1339
+
1340
+ export function shadowFileIdentity(file, fd) {
1341
+ try {
1342
+ return fd === undefined ? accessEntry(file, "file").identity : openedShadowEntry(file, fd).entry.identity;
1343
+ } catch {
1344
+ return "";
1345
+ }
1346
+ }
1347
+
1348
+ export function tightenCreatedShadow(file, fd, access = {}, { remember = true, skipRunner = false } = {}) {
1349
+ const platform = access.platform ?? process.platform;
1350
+ const windows = platform === "win32" && !access.runner;
1351
+ const nativePosix = platform !== "win32" && !access.runner;
1352
+ try {
1353
+ // Only a file created under an already verified Windows parent inherits its DACL.
1354
+ const inherited = windows && !skipRunner && !shadowAccessFused() && shadowDirLocked(dirname(file));
1355
+ if (!skipRunner && !nativePosix && !inherited) tightenShadow(file, "file", access);
1356
+ const plan = nativePosix ? shadowAccessPlan(platform) : null;
1357
+ if (plan && !skipRunner) {
1358
+ openedShadowEntry(file, fd);
1359
+ fchmodSync(fd, plan.fileMode);
1248
1360
  }
1361
+ const { entry, mode } = openedShadowEntry(file, fd);
1362
+ if (plan) {
1363
+ verifyPosixShadowMode(mode, plan.fileMode, "file");
1364
+ verifyPosixShadowMode(accessEntry(dirname(file), "dir").mode, plan.dirMode, "dir");
1365
+ }
1366
+ if (remember && (skipRunner || inherited)) rememberLockedEntry(lockedFiles, entry.canonical, entry);
1367
+ return entry.identity;
1368
+ } catch (cause) {
1369
+ if (cause?.code === "ESHADOWACCESS") throw cause;
1370
+ if (windows) tripFuse();
1371
+ const error = new Error("spine: shadow permission action failed; backup refused", { cause });
1372
+ error.code = "ESHADOWACCESS";
1373
+ error.step = cause?.step || "file";
1374
+ throw error;
1249
1375
  }
1250
- tightenShadow(file, "file", access);
1251
1376
  }
1252
1377
 
1253
1378
  export function discardShadowFiles(files, cause, unlink = unlinkSync) {
@@ -1277,23 +1402,32 @@ export function discardShadowFiles(files, cause, unlink = unlinkSync) {
1277
1402
  }
1278
1403
  }
1279
1404
 
1405
+ class ShadowWriteRevoked extends Error {}
1406
+
1407
+ function checkShadowWrite(writeEpoch) {
1408
+ if (writeEpoch && Atomics.load(writeEpoch, 0) !== 0) {
1409
+ throw new ShadowWriteRevoked("spine: shadow write revoked");
1410
+ }
1411
+ }
1412
+
1280
1413
  export function writeShadowFile(
1281
1414
  file,
1282
1415
  body,
1283
1416
  access = {},
1284
- { exclusive = false, root, write = writeFileSync, unlink = unlinkSync } = {},
1417
+ { exclusive = false, root, write = writeFileSync, unlink = unlinkSync, writeEpoch } = {},
1285
1418
  ) {
1286
1419
  const dir = dirname(file);
1287
1420
  ensureShadowDir(dir, access);
1288
1421
  return withShadowRoot(root ?? shadowRootForDir(dir), () => {
1289
1422
  const path = scopedFile(file, rotationScope.root);
1290
1423
  if (!path) throw coordinationError(new Error("shadow file outside root scope"));
1291
- writeShadowFileLocked(path, body, access, { exclusive, write, unlink, accessPath: file });
1424
+ writeShadowFileLocked(path, body, access, { exclusive, write, unlink, accessPath: file, writeEpoch });
1292
1425
  return file;
1293
1426
  });
1294
1427
  }
1295
1428
 
1296
- function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, accessPath }) {
1429
+ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, accessPath, writeEpoch }) {
1430
+ checkShadowWrite(writeEpoch);
1297
1431
  const dir = dirname(file);
1298
1432
  const parentIdentity = rememberShadowParent(dir);
1299
1433
 
@@ -1320,6 +1454,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1320
1454
  }
1321
1455
  // Confirm ACL/mode before any secret bytes are written to the staged file.
1322
1456
  tightenCreatedShadow(target, fd, access);
1457
+ rememberShadowParent(dir);
1323
1458
  // Full replacement bytes are a conservative charge, even for overwrites,
1324
1459
  // partial writes and failed cleanup. Metadata/owner/stats are not capacity.
1325
1460
  if (shadowUsage && isPluginShadowName(basename(file))) {
@@ -1335,16 +1470,12 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1335
1470
  error.code = "EEXIST";
1336
1471
  throw error;
1337
1472
  }
1473
+ checkShadowWrite(writeEpoch);
1338
1474
  renameSync(target, file);
1339
1475
  protectedPath = file;
1340
1476
  // staging 临时名一次性且永不复用:发布后其锁表条目已成死重,随 rename 同步
1341
1477
  // 释放,避免每次保存向 lockedFiles 残留一个永不复用的条目。
1342
1478
  releaseLockedFile(target);
1343
- if (basename(file) !== DECISIONS_NAME) {
1344
- decisionRotationAt.delete(rotationScope.root);
1345
- decisionUsageBytes.delete(rotationScope.root);
1346
- decisionUsageMtime.delete(rotationScope.root);
1347
- }
1348
1479
 
1349
1480
  // Keep the caller's spelling for the permission cache/runner. The opened
1350
1481
  // descriptor and the final path now refer to the same published object.
@@ -1355,6 +1486,7 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1355
1486
  closeSync(opened);
1356
1487
  return file;
1357
1488
  } catch (error) {
1489
+ const identity = fd !== null ? shadowFileIdentity(protectedPath, fd) : "";
1358
1490
  if (fd !== null) {
1359
1491
  try {
1360
1492
  closeSync(fd);
@@ -1365,19 +1497,20 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
1365
1497
  // Do not unlink through a replacement directory after a failed write.
1366
1498
  let sameParent = false;
1367
1499
  try { sameParent = !parentIdentity || directoryIdentity(dir) === parentIdentity; } catch {}
1368
- if (sameParent) discardShadowFiles([protectedPath], error, unlink);
1369
- else shadowUsage = null;
1500
+ if (sameParent && identity && shadowFileIdentity(protectedPath) === identity) {
1501
+ discardShadowFiles([protectedPath], error, unlink);
1502
+ } else shadowUsage = null;
1370
1503
  }
1371
1504
  throw error;
1372
1505
  }
1373
1506
  }
1374
1507
 
1375
- export function writeShadowOwner(dir, access = {}, root) {
1508
+ export function writeShadowOwner(dir, access = {}, root, writeEpoch) {
1376
1509
  return writeShadowFile(
1377
1510
  join(dir, "owner"),
1378
1511
  String(process.pid),
1379
1512
  access,
1380
- { root },
1513
+ { root, writeEpoch },
1381
1514
  );
1382
1515
  }
1383
1516
 
@@ -1508,20 +1641,26 @@ export function saveShadowTransaction({
1508
1641
  cap,
1509
1642
  access = {},
1510
1643
  rotationIO = {},
1644
+ writeEpoch,
1511
1645
  } = {}) {
1646
+ const revoked = () => writeEpoch && Atomics.load(writeEpoch, 0) !== 0;
1647
+ const skipped = { ok: false, skipped: true, reason: "stand-down" };
1648
+ if (revoked()) return skipped;
1512
1649
  ensureShadowDir(shadow, access);
1513
1650
  const dir = sessionDir(shadow, sessionKey);
1514
- ensureShadowDir(dir, access);
1515
1651
  return withShadowRoot(shadow, () => {
1652
+ if (revoked()) return skipped;
1653
+ ensureShadowDir(dir, access);
1516
1654
  const owner = join(dir, "owner");
1517
1655
  const ownerExisted = existsSync(owner);
1518
1656
  let ownerWritten = false;
1519
1657
  try {
1520
- writeShadowOwner(dir, access, shadow);
1658
+ writeShadowOwner(dir, access, shadow, writeEpoch);
1521
1659
  ownerWritten = true;
1522
1660
  const incoming = Buffer.byteLength(body);
1523
1661
  const rotation = rotateShadow({
1524
1662
  ...rotationIO,
1663
+ writeEpoch,
1525
1664
  dir: shadow,
1526
1665
  incomingBytes: incoming,
1527
1666
  protectPath: file,
@@ -1529,6 +1668,7 @@ export function saveShadowTransaction({
1529
1668
  sessionKey,
1530
1669
  cap,
1531
1670
  });
1671
+ checkShadowWrite(writeEpoch);
1532
1672
  if (!rotation.ok) {
1533
1673
  if (rotation.reason) {
1534
1674
  const incomplete = rotation.reason === "scan-incomplete";
@@ -1543,11 +1683,15 @@ export function saveShadowTransaction({
1543
1683
  if (required) throw new Error("spine: shadow backup is full; leaving the span");
1544
1684
  return { ok: false, skipped: true, reason: "full", rotation };
1545
1685
  }
1546
- writeShadowFile(file, body, access, { root: shadow });
1686
+ writeShadowFile(file, body, access, { root: shadow, writeEpoch });
1547
1687
  if (!existsSync(file)) throw new Error("spine: shadow backup was not written");
1548
1688
  return { ok: true, file, rotation };
1549
1689
  } catch (error) {
1550
1690
  if (ownerWritten && !ownerExisted) discardShadowFiles([owner], error);
1691
+ if (error instanceof ShadowWriteRevoked) {
1692
+ shadowUsage = null;
1693
+ return skipped;
1694
+ }
1551
1695
  throw error;
1552
1696
  }
1553
1697
  });
@@ -1565,7 +1709,7 @@ function rotationTime(now) {
1565
1709
  function rotateShadowLocked({
1566
1710
  incomingBytes, protectPath, protectPaths = [], sessionKey, cap,
1567
1711
  unlink = unlinkSync, alive = processAlive, readdir = readdirSync, stat = statSync,
1568
- now = () => performance.now(),
1712
+ now = () => performance.now(), writeEpoch,
1569
1713
  }) {
1570
1714
  const { root, identity, exclusive } = rotationScope;
1571
1715
  const low = Math.floor(cap * 0.8);
@@ -1581,6 +1725,7 @@ function rotateShadowLocked({
1581
1725
  }
1582
1726
  shadowUsage = null;
1583
1727
  let complete = true;
1728
+ rotationScanCount++;
1584
1729
  const files = listShadowEntries(root, alive, { readdir, stat, onError() { complete = false; } });
1585
1730
  const protect = new Set([protectPath, ...protectPaths].filter(Boolean).map((path) => {
1586
1731
  try { return join(realDirectory(dirname(path)), basename(path)); } catch { return resolve(path); }
@@ -1625,6 +1770,7 @@ function rotateShadowLocked({
1625
1770
  let failed = false;
1626
1771
  for (const file of [...legacy, ...dead, ...mine]) {
1627
1772
  if (!oversize && used + incomingBytes <= low) break;
1773
+ checkShadowWrite(writeEpoch);
1628
1774
  try {
1629
1775
  unlink(file.path);
1630
1776
  } catch (error) {