@openclaw/matrix 2026.11.11 → 2026.12.1-beta.2

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.
Files changed (192) hide show
  1. package/dist/.setup/{approval-handler.runtime-CCGCnRgz.mjs → approval-handler.runtime-BfY586xJ.mjs} +4 -4
  2. package/dist/.setup/{channel-BEgolhUJ.mjs → channel-Cc7auxIF.mjs} +8 -8
  3. package/dist/.setup/{channel.runtime-_NMfiRJl.mjs → channel.runtime-B6ZmWLDZ.mjs} +5 -5
  4. package/dist/.setup/{channel.setup-B7r4NCcE.mjs → channel.setup-D9-chyNP.mjs} +2 -2
  5. package/dist/.setup/{cli-CyjnAIzU.mjs → cli-BrTpL9JI.mjs} +7 -7
  6. package/dist/.setup/{cli-metadata-DNeLBXHC.mjs → cli-metadata-R7WyIFzA.mjs} +1 -1
  7. package/dist/.setup/{client-BVgnwwz0.mjs → client-BmxOI9-U.mjs} +2 -2
  8. package/dist/.setup/{client-gch0wggI.mjs → client-DOb_5cJm.mjs} +2 -2
  9. package/dist/.setup/{client-bootstrap-CHs5OQ1Z.mjs → client-bootstrap-BwDbzw5i.mjs} +1 -1
  10. package/dist/.setup/{create-client-mnjEWdZV.mjs → create-client-BQpMgtl2.mjs} +2 -2
  11. package/dist/.setup/{crypto-runtime-tZ95jwNO.mjs → crypto-runtime-CStae6zK.mjs} +1 -1
  12. package/dist/.setup/{direct-management-D59C1WO-.mjs → direct-management-Bm4vd-k1.mjs} +1 -1
  13. package/dist/.setup/{directory-live-CQNKUJJx.mjs → directory-live-DRGF3zFp.mjs} +1 -1
  14. package/dist/.setup/{draft-stream-DI_6HWy4.mjs → draft-stream-DpSefQTK.mjs} +2 -2
  15. package/dist/.setup/{exec-approvals-B23spbVI.mjs → exec-approvals-CTkGLt3Z.mjs} +2 -2
  16. package/dist/.setup/{messages-VnZ4u4iq.mjs → messages-DjmI7l5t.mjs} +3 -3
  17. package/dist/.setup/{monitor-wbUkxHXK.mjs → monitor-HjyjGlys.mjs} +18 -18
  18. package/dist/.setup/{onboarding-B51d5a6R.mjs → onboarding-BPkKv4dw.mjs} +3 -3
  19. package/dist/.setup/{outbound-D8rgFTRa.mjs → outbound-CthMgcxZ.mjs} +2 -2
  20. package/dist/.setup/{profile-update-DAQFPf4L.mjs → profile-update-myTQ_w_e.mjs} +3 -3
  21. package/dist/.setup/{reaction-events-CZlbNkx_.mjs → reaction-events-C22fpTeK.mjs} +5 -5
  22. package/dist/.setup/{resolve-targets-B3NLls5a.mjs → resolve-targets-3B6QJQUf.mjs} +1 -1
  23. package/dist/.setup/{room-info-Cw-BH1CA.mjs → room-info-7ER9IkzT.mjs} +3 -3
  24. package/dist/.setup/{sdk-Bzp2OIxv.mjs → sdk-DphkoEH1.mjs} +32 -33
  25. package/dist/.setup/{send-CK8h-x83.mjs → send-CAfHI3Oi.mjs} +18 -13
  26. package/dist/.setup/{send-currentness-D1x6YP9O.mjs → send-currentness-Zv5Z-1_t.mjs} +9 -5
  27. package/dist/.setup/{setup-bootstrap-DsHa4swp.mjs → setup-bootstrap-COKlzUTV.mjs} +2 -2
  28. package/dist/.setup/{setup-core-B3MI_zz4.mjs → setup-core-B1dRvn1h.mjs} +1 -1
  29. package/dist/.setup/setup-plugin-api-BGpOj2cE.mjs +2 -0
  30. package/dist/.setup/{thread-bindings-C_SHelhg.mjs → thread-bindings-DFF_4WP3.mjs} +1 -1
  31. package/dist/.setup/{tool-actions-nhsof0wb.mjs → tool-actions-Cal-116X.mjs} +11 -11
  32. package/dist/.setup/{verification-BZqaSKCW.mjs → verification-2flsiwT7.mjs} +1 -1
  33. package/dist/.source-module-urls/1cd4d4ff8d44e1c8b830932b44d7cf8a7f3350e09e169910e1d7a85e131b7bea.json +1 -1
  34. package/dist/api.js +4 -4
  35. package/dist/channel-plugin-api.js +1 -1
  36. package/dist/cli-metadata.js +1 -1
  37. package/dist/contract-api.js +2 -2
  38. package/dist/index.js +1 -1
  39. package/dist/plugin-entry.handlers.runtime.js +2 -2
  40. package/dist/session-binding-contract-api.js +1 -1
  41. package/dist/setup-entry.js +1 -1
  42. package/dist/setup-plugin-api.js +1 -1
  43. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +57 -0
  44. package/node_modules/@openclaw/fs-safe/README.md +6 -0
  45. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  46. package/node_modules/@openclaw/fs-safe/dist/atomic-io.d.ts +1 -0
  47. package/node_modules/@openclaw/fs-safe/dist/atomic-io.js +10 -0
  48. package/node_modules/@openclaw/fs-safe/dist/bounded-read.d.ts +1 -1
  49. package/node_modules/@openclaw/fs-safe/dist/bounded-read.js +15 -4
  50. package/node_modules/@openclaw/fs-safe/dist/directory-guard.js +11 -2
  51. package/node_modules/@openclaw/fs-safe/dist/drvfs-parent.d.ts +6 -0
  52. package/node_modules/@openclaw/fs-safe/dist/drvfs-parent.js +38 -0
  53. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-acquisition.d.ts +1 -1
  54. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-acquisition.js +2 -2
  55. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +13 -8
  56. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-io.js +13 -0
  57. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-mutation.d.ts +2 -2
  58. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-mutation.js +34 -24
  59. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-stale-admission.js +7 -2
  60. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync.js +20 -20
  61. package/node_modules/@openclaw/fs-safe/dist/file-observation.d.ts +13 -2
  62. package/node_modules/@openclaw/fs-safe/dist/file-observation.js +8 -4
  63. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.d.ts +1 -0
  64. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.js +11 -1
  65. package/node_modules/@openclaw/fs-safe/dist/file-store-write-options.d.ts +2 -0
  66. package/node_modules/@openclaw/fs-safe/dist/file-store-write-options.js +17 -0
  67. package/node_modules/@openclaw/fs-safe/dist/file-store.d.ts +2 -1
  68. package/node_modules/@openclaw/fs-safe/dist/file-store.js +12 -16
  69. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +1 -1
  70. package/node_modules/@openclaw/fs-safe/dist/guest.js +3 -4
  71. package/node_modules/@openclaw/fs-safe/dist/json-document-store.d.ts +2 -0
  72. package/node_modules/@openclaw/fs-safe/dist/json-document-store.js +1 -0
  73. package/node_modules/@openclaw/fs-safe/dist/json-store.js +1 -0
  74. package/node_modules/@openclaw/fs-safe/dist/json.d.ts +5 -2
  75. package/node_modules/@openclaw/fs-safe/dist/json.js +6 -2
  76. package/node_modules/@openclaw/fs-safe/dist/local-file-descriptor.js +16 -10
  77. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +6 -0
  78. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.js +4 -0
  79. package/node_modules/@openclaw/fs-safe/dist/native-staged-file-metadata.d.ts +20 -0
  80. package/node_modules/@openclaw/fs-safe/dist/native-staged-file-metadata.js +18 -0
  81. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.d.ts +3 -18
  82. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +48 -24
  83. package/node_modules/@openclaw/fs-safe/dist/opened-file-failure.js +19 -7
  84. package/node_modules/@openclaw/fs-safe/dist/output.d.ts +1 -0
  85. package/node_modules/@openclaw/fs-safe/dist/output.js +3 -0
  86. package/node_modules/@openclaw/fs-safe/dist/path-policy.js +4 -1
  87. package/node_modules/@openclaw/fs-safe/dist/permissions-windows.js +35 -10
  88. package/node_modules/@openclaw/fs-safe/dist/pinned-open.d.ts +9 -2
  89. package/node_modules/@openclaw/fs-safe/dist/pinned-open.js +42 -23
  90. package/node_modules/@openclaw/fs-safe/dist/pinned-write-staged.js +85 -34
  91. package/node_modules/@openclaw/fs-safe/dist/pinned-write-types.d.ts +3 -0
  92. package/node_modules/@openclaw/fs-safe/dist/pinned-write.js +4 -0
  93. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.d.ts +1 -0
  94. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.js +1 -1
  95. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -2
  96. package/node_modules/@openclaw/fs-safe/dist/publication-recovery.d.ts +24 -0
  97. package/node_modules/@openclaw/fs-safe/dist/publication-recovery.js +151 -0
  98. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.d.ts +1 -0
  99. package/node_modules/@openclaw/fs-safe/dist/publish-copy-stage.js +2 -1
  100. package/node_modules/@openclaw/fs-safe/dist/realpath.d.ts +1 -1
  101. package/node_modules/@openclaw/fs-safe/dist/realpath.js +22 -11
  102. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.d.ts +1 -0
  103. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +5 -0
  104. package/node_modules/@openclaw/fs-safe/dist/replace-file-temp-owner.d.ts +7 -0
  105. package/node_modules/@openclaw/fs-safe/dist/replace-file-temp-owner.js +75 -2
  106. package/node_modules/@openclaw/fs-safe/dist/replace-file-types.d.ts +2 -0
  107. package/node_modules/@openclaw/fs-safe/dist/replace-file.js +14 -10
  108. package/node_modules/@openclaw/fs-safe/dist/root-context.js +28 -12
  109. package/node_modules/@openclaw/fs-safe/dist/root-copy.js +1 -0
  110. package/node_modules/@openclaw/fs-safe/dist/root-create-input.js +2 -2
  111. package/node_modules/@openclaw/fs-safe/dist/root-file-final-admission.d.ts +4 -0
  112. package/node_modules/@openclaw/fs-safe/dist/root-file-final-admission.js +53 -36
  113. package/node_modules/@openclaw/fs-safe/dist/root-file-open-batch-sync.js +3 -1
  114. package/node_modules/@openclaw/fs-safe/dist/root-file.d.ts +2 -1
  115. package/node_modules/@openclaw/fs-safe/dist/root-file.js +24 -13
  116. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +17 -1
  117. package/node_modules/@openclaw/fs-safe/dist/root-options.d.ts +4 -2
  118. package/node_modules/@openclaw/fs-safe/dist/root-path.d.ts +1 -1
  119. package/node_modules/@openclaw/fs-safe/dist/root-path.js +2 -1
  120. package/node_modules/@openclaw/fs-safe/dist/root-read-admission.js +31 -9
  121. package/node_modules/@openclaw/fs-safe/dist/root-write-admission.js +6 -2
  122. package/node_modules/@openclaw/fs-safe/dist/secret-file.d.ts +1 -0
  123. package/node_modules/@openclaw/fs-safe/dist/secret-file.js +2 -0
  124. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.d.ts +1 -0
  125. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.js +84 -4
  126. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.d.ts +1 -0
  127. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.js +2 -0
  128. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-acquire.js +22 -15
  129. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-publication.d.ts +22 -0
  130. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-publication.js +303 -0
  131. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-reclaim.d.ts +2 -0
  132. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-reclaim.js +9 -1
  133. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-root.d.ts +8 -0
  134. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-root.js +37 -3
  135. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-staging.d.ts +14 -0
  136. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-staging.js +155 -0
  137. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-stale-admission.js +7 -2
  138. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-write.d.ts +10 -0
  139. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-write.js +143 -0
  140. package/node_modules/@openclaw/fs-safe/dist/temp-target.js +28 -7
  141. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.d.ts +2 -2
  142. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.js +34 -18
  143. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.d.ts +1 -1
  144. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.js +13 -3
  145. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-ownership.js +1 -1
  146. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-types.d.ts +9 -0
  147. package/node_modules/@openclaw/fs-safe/dist/test-hooks.d.ts +6 -0
  148. package/node_modules/@openclaw/fs-safe/dist/text-atomic.d.ts +1 -1
  149. package/node_modules/@openclaw/fs-safe/dist/text-atomic.js +1 -0
  150. package/node_modules/@openclaw/fs-safe/dist/windows-owner.d.ts +1 -0
  151. package/node_modules/@openclaw/fs-safe/dist/windows-owner.js +2 -1
  152. package/node_modules/@openclaw/fs-safe/dist/windows-security-helper.exe +0 -0
  153. package/node_modules/@openclaw/fs-safe/docs/advanced.md +6 -1
  154. package/node_modules/@openclaw/fs-safe/docs/atomic.md +64 -0
  155. package/node_modules/@openclaw/fs-safe/docs/contributing.md +69 -0
  156. package/node_modules/@openclaw/fs-safe/docs/file-store.md +2 -0
  157. package/node_modules/@openclaw/fs-safe/docs/json-store.md +2 -0
  158. package/node_modules/@openclaw/fs-safe/docs/json.md +2 -0
  159. package/node_modules/@openclaw/fs-safe/docs/output.md +2 -0
  160. package/node_modules/@openclaw/fs-safe/docs/permissions.md +20 -7
  161. package/node_modules/@openclaw/fs-safe/docs/reading.md +24 -9
  162. package/node_modules/@openclaw/fs-safe/docs/root.md +2 -0
  163. package/node_modules/@openclaw/fs-safe/docs/security-model.md +2 -0
  164. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +12 -7
  165. package/node_modules/@openclaw/fs-safe/docs/staged-file.md +2 -0
  166. package/node_modules/@openclaw/fs-safe/docs/temp-isolation-reference.md +73 -0
  167. package/node_modules/@openclaw/fs-safe/docs/temp.md +65 -0
  168. package/node_modules/@openclaw/fs-safe/docs/testing.md +1 -0
  169. package/node_modules/@openclaw/fs-safe/docs/writing.md +2 -0
  170. package/node_modules/@openclaw/fs-safe/package.json +25 -20
  171. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  172. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  173. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  174. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  175. package/node_modules/@openclaw/fs-safe-freebsd-arm64/fs-safe-native.node +0 -0
  176. package/node_modules/@openclaw/fs-safe-freebsd-arm64/package.json +1 -1
  177. package/node_modules/@openclaw/fs-safe-freebsd-x64/fs-safe-native.node +0 -0
  178. package/node_modules/@openclaw/fs-safe-freebsd-x64/package.json +1 -1
  179. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  180. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  181. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  182. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  183. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  184. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  185. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  186. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  187. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/fs-safe-native.node +0 -0
  188. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/package.json +1 -1
  189. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  190. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  191. package/package.json +5 -5
  192. package/dist/.setup/setup-plugin-api-D6-D6LLj.mjs +0 -2
@@ -1,9 +1,31 @@
1
1
  import path from "node:path";
2
+ import { cleanupSidecarStages, sidecarPublicationPending } from "./sidecar-lock-staging.js";
3
+ import { admitFileLockSyncRootPath, assertFileLockSyncRootMutationAllowed, assertFileLockSyncRootPathsCurrent, assertFileLockSyncRootResolvedPathCurrent, captureFileLockSyncRootAuthority } from "./file-lock-sync-root.js";
4
+ import { assertRetainedParentCurrent, observeDirectory } from "./file-lock-sync-root-io.js";
2
5
  import { inspectDirectoryIdentity } from "./directory-guard.js";
3
6
  import { FsSafeError } from "./errors.js";
4
7
  import { fileObservation } from "./file-observation.js";
5
8
  import { isNotFoundPathError } from "./path.js";
6
9
  import { resolveRootPath } from "./root-path.js";
10
+ export async function rootSidecarPublicationPending(lockRoot, relative, options = {}) {
11
+ const resolved = await lockRoot.resolve(relative);
12
+ const parent = path.dirname(resolved);
13
+ const identity = await inspectDirectoryIdentity(parent);
14
+ if (options.cleanAbandoned) {
15
+ const admitted = admitFileLockSyncRootPath(captureFileLockSyncRootAuthority(lockRoot), resolved);
16
+ const receipt = observeDirectory(path.dirname(admitted.path));
17
+ cleanupSidecarStages(admitted.path, candidate => {
18
+ assertFileLockSyncRootPathsCurrent([admitted]);
19
+ assertFileLockSyncRootResolvedPathCurrent(admitted);
20
+ assertRetainedParentCurrent(admitted, receipt);
21
+ if (candidate)
22
+ assertFileLockSyncRootMutationAllowed(candidate, admitted.authority.denyMutations);
23
+ });
24
+ }
25
+ const pending = sidecarPublicationPending(resolved, undefined, options);
26
+ await inspectDirectoryIdentity(parent, identity);
27
+ return pending && await lockRoot.resolve(relative) === resolved;
28
+ }
7
29
  export async function openSidecarRoot(lockRoot, relative, discardObservation, onOpenFailure) {
8
30
  const resolved = await lockRoot.resolve(relative);
9
31
  const canonicalPath = async () => (await resolveRootPath({
@@ -32,7 +54,10 @@ export async function openSidecarRoot(lockRoot, relative, discardObservation, on
32
54
  break;
33
55
  }
34
56
  }
35
- const observation = fileObservation();
57
+ const observation = fileObservation({
58
+ publicationPending: async (candidate, identity) => discardObservation === "changed" && candidate === resolved &&
59
+ await rootSidecarPublicationPending(lockRoot, relative, { requireStage: true, identity }),
60
+ });
36
61
  try {
37
62
  const opened = await observation.run(() => lockRoot.open(relative));
38
63
  if (opened.realPath !== expectedRealPath) {
@@ -42,6 +67,9 @@ export async function openSidecarRoot(lockRoot, relative, discardObservation, on
42
67
  return opened;
43
68
  }
44
69
  catch (error) {
70
+ if (discardObservation && error instanceof FsSafeError && error.code === "hardlink" &&
71
+ await rootSidecarPublicationPending(lockRoot, relative))
72
+ return null;
45
73
  const openFailed = observation.has(error, `open:${resolved}`);
46
74
  if (openFailed)
47
75
  onOpenFailure?.(error);
@@ -50,13 +78,19 @@ export async function openSidecarRoot(lockRoot, relative, discardObservation, on
50
78
  return null;
51
79
  const discardable = observation.has(error, `unlinked:${resolved}`) ||
52
80
  (discardObservation === "changed" && observation.has(error, `changed:${resolved}`));
53
- if (!discardObservation || (!missing && (!completeParents || !discardable)))
81
+ const linkedChange = discardObservation === "changed" && observation.has(error, `linked-change:${resolved}`);
82
+ if (!discardObservation || (!missing && (!completeParents || (!discardable && !linkedChange))))
54
83
  throw error;
55
84
  try {
85
+ // Linked-change receipts already proved a matching stage while the exact
86
+ // descriptor was open; retained ancestry and the current path still fence it.
56
87
  const probe = fileObservation();
57
88
  try {
58
89
  const current = await probe.run(() => lockRoot.stat(relative));
59
- if (!current.isFile || current.isSymbolicLink || current.nlink !== 1)
90
+ // A successor can still hold its matching publication-stage link.
91
+ // Discard only the old read; retained ancestry is revalidated below.
92
+ if (!current.isFile || current.isSymbolicLink || (current.nlink !== 1 &&
93
+ !(current.nlink === 2 && await rootSidecarPublicationPending(lockRoot, relative))))
60
94
  throw error;
61
95
  }
62
96
  catch (probeError) {
@@ -0,0 +1,14 @@
1
+ import fs from "node:fs";
2
+ import type { NativeWriteParent } from "./pinned-write-types.js";
3
+ export declare function sidecarStagingPath(target: string): string;
4
+ export declare function cleanupSidecarStages(target: string, assertCurrent: (candidate?: string) => void, native?: NativeWriteParent, onlyStage?: {
5
+ name: string;
6
+ identity: fs.BigIntStats;
7
+ }): void;
8
+ export declare function sidecarPublicationPending(target: string, onStage?: (name: string, identity: fs.BigIntStats) => void, options?: {
9
+ requireStage?: boolean;
10
+ identity?: {
11
+ dev: bigint;
12
+ ino: bigint;
13
+ };
14
+ }): boolean;
@@ -0,0 +1,155 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { randomUUID } from "node:crypto";
5
+ import { sameFileIdentityForCleanup, sha256Hex } from "./file-identity.js";
6
+ function stagingPrefix(target) {
7
+ return `.fs-safe-lock-${sha256Hex(`${os.hostname()}\0${path.basename(target)}`).slice(0, 16)}-`;
8
+ }
9
+ export function sidecarStagingPath(target) {
10
+ return path.join(path.dirname(target), `${stagingPrefix(target)}${process.pid}-${randomUUID()}.tmp`);
11
+ }
12
+ function ownerAbsent(pid) {
13
+ try {
14
+ process.kill(pid, 0);
15
+ }
16
+ catch (error) {
17
+ return error.code === "ESRCH";
18
+ }
19
+ return false;
20
+ }
21
+ // Bound opportunistic cleanup to 64 entries plus one exact publication link.
22
+ // Never remove the final lock, live owners, or unverifiable identities.
23
+ export function cleanupSidecarStages(target, assertCurrent, native, onlyStage) {
24
+ const directory = path.dirname(target), prefix = stagingPrefix(target);
25
+ let entries;
26
+ let authorityFailure;
27
+ const assertAuthority = (candidate) => {
28
+ try {
29
+ assertCurrent(candidate);
30
+ }
31
+ catch (error) {
32
+ authorityFailure = { error };
33
+ throw error;
34
+ }
35
+ };
36
+ try {
37
+ assertAuthority();
38
+ if (!onlyStage)
39
+ entries = fs.opendirSync(directory);
40
+ for (let count = 0; count < (onlyStage ? 1 : 64); count++) {
41
+ const entry = onlyStage ?? entries.readSync();
42
+ if (!entry)
43
+ break;
44
+ if (!entry.name.startsWith(prefix))
45
+ continue;
46
+ const suffix = entry.name.slice(prefix.length);
47
+ const match = /^([1-9]\d*)-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\.tmp$/.exec(suffix);
48
+ if (!match)
49
+ continue;
50
+ const pid = Number(match[1]);
51
+ if (!Number.isSafeInteger(pid) || !ownerAbsent(pid))
52
+ continue;
53
+ const candidate = path.join(directory, entry.name);
54
+ let fd;
55
+ try {
56
+ assertAuthority(candidate);
57
+ const before = fs.lstatSync(candidate, { bigint: true });
58
+ if (onlyStage && !sameFileIdentityForCleanup(before, onlyStage.identity))
59
+ continue;
60
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink > 2n ||
61
+ (process.getuid && before.uid !== BigInt(process.getuid())))
62
+ continue;
63
+ fd = fs.openSync(candidate, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
64
+ const held = fs.fstatSync(fd, { bigint: true });
65
+ if (!sameFileIdentityForCleanup(before, held))
66
+ continue;
67
+ assertAuthority(candidate);
68
+ const current = fs.lstatSync(candidate, { bigint: true });
69
+ if (!sameFileIdentityForCleanup(current, held) || !ownerAbsent(pid))
70
+ continue;
71
+ if (native?.binding.removeStagedFile)
72
+ native.binding.removeStagedFile(native.fd, entry.name, fd);
73
+ else
74
+ fs.unlinkSync(candidate);
75
+ }
76
+ catch {
77
+ if (authorityFailure)
78
+ throw authorityFailure.error;
79
+ // Cleanup is optional; the unique new stage does not depend on it.
80
+ }
81
+ finally {
82
+ if (fd !== undefined)
83
+ try {
84
+ fs.closeSync(fd);
85
+ }
86
+ catch { /* Best effort. */ }
87
+ }
88
+ }
89
+ }
90
+ catch {
91
+ if (authorityFailure)
92
+ throw authorityFailure.error;
93
+ // Denied enumeration must not turn a working exclusive create into a failure.
94
+ }
95
+ finally {
96
+ try {
97
+ entries?.closeSync();
98
+ }
99
+ catch { /* Best effort. */ }
100
+ }
101
+ if (!onlyStage)
102
+ sidecarPublicationPending(target, (name, identity) => cleanupSidecarStages(target, assertCurrent, native, { name, identity }));
103
+ }
104
+ // Readers reject the linked record and retry. Authorized cleanup may handle
105
+ // the one matching stage; recognition streams past the opportunistic budget.
106
+ export function sidecarPublicationPending(target, onStage, options = {}) {
107
+ let entries;
108
+ let callbackFailure;
109
+ try {
110
+ const current = fs.lstatSync(target, { bigint: true, throwIfNoEntry: false });
111
+ if (!current)
112
+ return !options.requireStage;
113
+ if (options.identity && !sameFileIdentityForCleanup(current, options.identity))
114
+ return false;
115
+ if (!current.isFile() || current.isSymbolicLink())
116
+ return false;
117
+ if (current.nlink === 1n)
118
+ return !options.requireStage;
119
+ if (current.nlink !== 2n)
120
+ return false;
121
+ const prefix = stagingPrefix(target);
122
+ entries = fs.opendirSync(path.dirname(target));
123
+ for (;;) {
124
+ const entry = entries.readSync();
125
+ if (!entry)
126
+ break;
127
+ if (!entry.name.startsWith(prefix) || !/^[1-9]\d*-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\.tmp$/.test(entry.name.slice(prefix.length)))
128
+ continue;
129
+ const stage = fs.lstatSync(path.join(path.dirname(target), entry.name), { bigint: true, throwIfNoEntry: false });
130
+ if (stage?.isFile() && !stage.isSymbolicLink() && sameFileIdentityForCleanup(stage, current)) {
131
+ try {
132
+ onStage?.(entry.name, current);
133
+ }
134
+ catch (error) {
135
+ callbackFailure = { error };
136
+ throw error;
137
+ }
138
+ return true;
139
+ }
140
+ }
141
+ const after = fs.lstatSync(target, { bigint: true, throwIfNoEntry: false });
142
+ return !options.requireStage && (!after || !sameFileIdentityForCleanup(after, current) || after.nlink === 1n);
143
+ }
144
+ catch {
145
+ if (callbackFailure)
146
+ throw callbackFailure.error;
147
+ return false;
148
+ }
149
+ finally {
150
+ try {
151
+ entries?.closeSync();
152
+ }
153
+ catch { /* Observation remains inconclusive. */ }
154
+ }
155
+ }
@@ -1,5 +1,5 @@
1
1
  import { defaultSidecarLockShouldReclaim, isTransientLockFileDenial, sidecarLockStale } from "./sidecar-lock-policy.js";
2
- import { readSidecarLockRawSnapshot, removeStaleSidecarLockIfAllowed, sidecarLockSnapshotStillPresent, tryAcquireSidecarReclaimGuard, } from "./sidecar-lock-reclaim.js";
2
+ import { isIncompleteSidecarLockRecord, readSidecarLockRawSnapshot, removeStaleSidecarLockIfAllowed, sidecarLockSnapshotStillPresent, tryAcquireSidecarReclaimGuard, } from "./sidecar-lock-reclaim.js";
3
3
  import { observeSidecarLockParser, parseSidecarLockSnapshotUnderAdmission, scopedSidecarLockParser, } from "./sidecar-lock-admission-parser.js";
4
4
  /** Handle one historical EEXIST attempt while its canonical admission is held. */
5
5
  export async function handleStaleSidecarAdmission(params) {
@@ -65,10 +65,12 @@ export async function handleStaleSidecarAdmission(params) {
65
65
  return;
66
66
  throw error;
67
67
  }
68
+ // An incomplete owner can still be writing; age is not liveness evidence.
68
69
  if (!snapshot) {
69
70
  await params.waitForRetry();
70
71
  return;
71
72
  }
73
+ const incomplete = (!params.parserState.parser && snapshot.payload === null) || isIncompleteSidecarLockRecord(snapshot.raw);
72
74
  const staleOptions = params.staleOptionsState;
73
75
  try {
74
76
  if (!staleOptions.shouldReclaimObserved) {
@@ -104,7 +106,7 @@ export async function handleStaleSidecarAdmission(params) {
104
106
  assertUnheld();
105
107
  try {
106
108
  if (!shouldReclaim)
107
- return defaultSidecarLockShouldReclaim(snapshot, params.staleMs, Date.now());
109
+ return !incomplete && defaultSidecarLockShouldReclaim(snapshot, params.staleMs, Date.now());
108
110
  return await Reflect.apply(shouldReclaim, undefined, [{
109
111
  lockPath,
110
112
  normalizedTargetPath,
@@ -150,6 +152,9 @@ export async function handleStaleSidecarAdmission(params) {
150
152
  await params.waitForRetry();
151
153
  return;
152
154
  }
155
+ // Policy may diagnose an incomplete record, but can never authorize its removal.
156
+ if (incomplete)
157
+ throw sidecarLockStale(lockPath, normalizedTargetPath);
153
158
  if ((staleOptions.staleRecovery ?? "fail-closed") === "remove-if-unchanged") {
154
159
  const acquiredGuard = await admission.run(() => tryAcquireSidecarReclaimGuard(params.reclaimGuards, params.reclaimGuardPath, params.lockRoot));
155
160
  if (acquiredGuard)
@@ -0,0 +1,10 @@
1
+ import { type AnyAsyncDirectoryGuard } from "./directory-guard.js";
2
+ import type { NativeWriteParent, PinnedWriteParams } from "./pinned-write-types.js";
3
+ export declare class SidecarFallbackWriteError extends Error {
4
+ readonly failure: unknown;
5
+ constructor(failure: unknown);
6
+ }
7
+ export declare function writeSidecarAtParent(params: PinnedWriteParams, parent: AnyAsyncDirectoryGuard, native?: NativeWriteParent): Promise<{
8
+ dev: bigint;
9
+ ino: bigint;
10
+ }>;
@@ -0,0 +1,143 @@
1
+ import fs from "node:fs";
2
+ import promises from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { assertSyncDirectoryGuard } from "./directory-guard.js";
5
+ import { createSuppressedError } from "./suppressed-error.js";
6
+ import { FsSafeError } from "./errors.js";
7
+ import { annotateReadOnlyOpenError } from "./file-open-error.js";
8
+ import { recordFileObservationFailure } from "./file-observation.js";
9
+ import { captureNativeFdClose } from "./native-binding.js";
10
+ import { nativeOpenFlags } from "./native-operations.js";
11
+ import { writePinnedInput } from "./pinned-write-input.js";
12
+ import { cleanupPinnedFilePath } from "./file-cleanup.js";
13
+ import { createSidecarFile } from "./sidecar-lock-publication.js";
14
+ import { isTransientLockFileDenial } from "./sidecar-lock-policy.js";
15
+ export class SidecarFallbackWriteError extends Error {
16
+ failure;
17
+ constructor(failure) {
18
+ super("sidecar fallback failed");
19
+ this.failure = failure;
20
+ }
21
+ }
22
+ export async function writeSidecarAtParent(params, parent, native) {
23
+ try {
24
+ return await writeAtParent(params, parent, native);
25
+ }
26
+ catch (error) {
27
+ if (!native)
28
+ throw new SidecarFallbackWriteError(error);
29
+ throw error;
30
+ }
31
+ }
32
+ /** The admitted Root parent stays owned by the caller until verification ends. */
33
+ async function writeAtParent(params, parent, native) {
34
+ if (params.input.kind !== "buffer")
35
+ throw new TypeError("sidecar payload must be buffered");
36
+ const target = path.join(parent.realPath, params.basename);
37
+ const raw = Buffer.isBuffer(params.input.data)
38
+ ? params.input.data.toString(params.input.encoding ?? "utf8") : params.input.data;
39
+ const assertCurrent = () => {
40
+ params.assertBeforeMutation?.();
41
+ assertSyncDirectoryGuard(parent);
42
+ };
43
+ const onConflict = (error) => {
44
+ recordFileObservationFailure(error, `exclusive-create:${target}`);
45
+ if (error.code === "EEXIST") {
46
+ throw new FsSafeError("already-exists", "file already exists", { cause: error });
47
+ }
48
+ };
49
+ const created = await createSidecarFile(target, raw, async (pathname) => {
50
+ assertCurrent();
51
+ const failedOpen = (error) => {
52
+ if (native)
53
+ annotateReadOnlyOpenError(error, pathname);
54
+ if (isTransientLockFileDenial(error, pathname))
55
+ recordFileObservationFailure(error, `sidecar-create-denial:${target}`);
56
+ if (pathname === target)
57
+ onConflict(error);
58
+ throw error;
59
+ };
60
+ if (!native) {
61
+ let handle;
62
+ try {
63
+ handle = await promises.open(pathname, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL |
64
+ (process.platform !== "win32" ? fs.constants.O_NOFOLLOW ?? 0 : 0), params.mode);
65
+ }
66
+ catch (error) {
67
+ return failedOpen(error);
68
+ }
69
+ return {
70
+ fd: handle.fd,
71
+ close: () => handle.close(),
72
+ writeFile: async (data, encoding) => await writePinnedInput(handle, { kind: "buffer", data, encoding }),
73
+ };
74
+ }
75
+ const close = captureNativeFdClose(native.binding);
76
+ let open = true;
77
+ let fd;
78
+ try {
79
+ fd = native.binding.createStagedFile && process.platform !== "win32"
80
+ ? await native.binding.createStagedFile(native.fd, path.basename(pathname))
81
+ : native.binding.openBeneath(native.fd, path.basename(pathname), nativeOpenFlags(fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_EXCL)).fd;
82
+ }
83
+ catch (error) {
84
+ const failure = error;
85
+ if (process.platform === "win32" && failure?.code === "EPERM" && failure.path === undefined) {
86
+ try {
87
+ failure.path = pathname;
88
+ }
89
+ catch { /* Keep immutable native diagnostics. */ }
90
+ }
91
+ return failedOpen(error);
92
+ }
93
+ return {
94
+ fd,
95
+ async close() { if (open) {
96
+ open = false;
97
+ close(fd);
98
+ } },
99
+ async writeFile(data, encoding) {
100
+ await writePinnedInput(fd, { kind: "buffer", data, encoding });
101
+ },
102
+ };
103
+ }, {
104
+ nativeParent: native, assertCurrent, assertCleanupCandidate: params.assertSidecarCleanupCandidate,
105
+ onConflict, prepare: fd => fs.fchmodSync(fd, params.mode), requireExactIdentity: true,
106
+ });
107
+ const handle = created.handle;
108
+ let failure;
109
+ try {
110
+ const identity = created.identity;
111
+ try {
112
+ assertCurrent();
113
+ await params.verifyPublished?.(handle.fd, identity, parent, native);
114
+ }
115
+ catch (error) {
116
+ if (!native) {
117
+ try {
118
+ assertCurrent();
119
+ await cleanupPinnedFilePath({ pathname: target, handle, identity, parentGuard: parent, throwOnCleanupError: true });
120
+ }
121
+ catch (cleanupError) {
122
+ throw createSuppressedError(cleanupError, error, "sidecar verification and cleanup both failed");
123
+ }
124
+ }
125
+ throw error;
126
+ }
127
+ return { dev: identity.dev, ino: identity.ino };
128
+ }
129
+ catch (error) {
130
+ failure = { error };
131
+ throw error;
132
+ }
133
+ finally {
134
+ try {
135
+ await handle.close();
136
+ }
137
+ catch (closeError) {
138
+ if (failure)
139
+ throw createSuppressedError(closeError, failure.error, "sidecar write and close both failed");
140
+ throw closeError;
141
+ }
142
+ }
143
+ }
@@ -2,9 +2,9 @@ import crypto from "node:crypto";
2
2
  import fsSync from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
- import { suffixWindowsReservedDeviceName } from "./filename.js";
5
+ import { fitFileNameToPortableComponent, suffixWindowsReservedDeviceName } from "./filename.js";
6
6
  import { sameFileIdentityForCleanup } from "./file-identity.js";
7
- import { assertSafePathSegment, isSafePathSegment, normalizeSafePathSegment, trimHyphenEdges, } from "./safe-path-segment.js";
7
+ import { assertSafePathSegment, trimHyphenEdges, } from "./safe-path-segment.js";
8
8
  import { resolveSecureTempRoot } from "./secure-temp-dir.js";
9
9
  import { hasNodeErrorCode } from "./path.js";
10
10
  import { registerTempPathForExit } from "./temp-cleanup.js";
@@ -60,10 +60,25 @@ function sanitizeExtension(extension) {
60
60
  return token ? `.${token}` : "";
61
61
  }
62
62
  export function sanitizeTempFileName(fileName) {
63
+ // Keep Unicode filenames, but retain the historical ASCII punctuation filtering.
64
+ const normalized = trimHyphenEdges(path.basename(fileName).trim()
65
+ .replace(/\0/g, "")
66
+ // Some Unicode symbols decompose into characters forbidden on Windows.
67
+ .replace(/[\u0080-\u{10ffff}]/gu, (character) => /[<>:"/\\|?*]/u.test(character.normalize("NFD")) ? "-" : character)
68
+ .replace(/(?:[^A-Za-z0-9._\-\u0080-\u{10ffff}]|[\p{Cc}\p{Cf}\p{Cs}\s])+/gu, "-"));
69
+ if (!normalized || normalized === "." || normalized === "..")
70
+ return "download.bin";
63
71
  // Suffix reserved stems before admission so CON.txt stays CON_.txt.
64
- const suffixed = suffixWindowsReservedDeviceName(normalizeSafePathSegment(path.basename(fileName)));
65
- // The suffix only inserts "_", so this value is already normalized.
66
- return isSafePathSegment(suffixed, { allowDotPrefix: true }) ? suffixed : "download.bin";
72
+ const fitted = trimHyphenEdges(fitFileNameToPortableComponent({
73
+ prefix: "",
74
+ fileName: suffixWindowsReservedDeviceName(normalized),
75
+ suffix: "",
76
+ }));
77
+ // Truncation must not expose a device name or a parent/current-directory token.
78
+ return fitted && fitted !== "." && fitted !== ".." &&
79
+ suffixWindowsReservedDeviceName(fitted) === fitted
80
+ ? fitted
81
+ : "download.bin";
67
82
  }
68
83
  export function buildRandomTempFilePath(params) {
69
84
  const rootDir = resolveTempRoot(params.rootDir);
@@ -111,6 +126,12 @@ function resolveTempFileCleanupSafety(value) {
111
126
  return value;
112
127
  throw new TypeError("cleanupSafety must be compatible or require-bounded");
113
128
  }
129
+ async function makeTempDirectory(prefix) {
130
+ // Only the OS call receives an extended Windows path. Keep the admitted
131
+ // namespace for alias, ancestry, identity and cleanup checks.
132
+ const created = await fs.mkdtemp(path.toNamespacedPath(prefix));
133
+ return path.join(path.dirname(prefix), path.basename(created));
134
+ }
114
135
  export async function createOwnedTempFile(params) {
115
136
  const cleanupSafety = resolveTempFileCleanupSafety(params.cleanupSafety);
116
137
  const rootDir = resolveTempRoot(params.rootDir);
@@ -136,7 +157,7 @@ export async function createOwnedTempFile(params) {
136
157
  let unregisterTempDir;
137
158
  try {
138
159
  capability.prepareChildCreation();
139
- dir = await fs.mkdtemp(childPrefix);
160
+ dir = await makeTempDirectory(childPrefix);
140
161
  assertNoWindowsPathAlias(dir, "filesystem", "temp directory uses a Windows filesystem namespace alias");
141
162
  initialPath = path.join(dir, initialFileName);
142
163
  assertNoWindowsPathAlias(initialPath, "filesystem", "temp file path uses a Windows filesystem namespace alias");
@@ -192,7 +213,7 @@ export async function createOwnedTempFile(params) {
192
213
  identity,
193
214
  };
194
215
  }
195
- const dir = await fs.mkdtemp(path.join(rootDir, prefix));
216
+ const dir = await makeTempDirectory(path.join(rootDir, prefix));
196
217
  assertNoWindowsPathAlias(dir, "filesystem", "temp directory uses a Windows filesystem namespace alias");
197
218
  // Windows file indexes can exceed Number.MAX_SAFE_INTEGER. Cleanup receipts
198
219
  // must retain the exact identity or adjacent directories can compare equal.
@@ -10,5 +10,5 @@ export type TempWorkspaceRootAdmission = {
10
10
  associateAncestry(descriptorFd: number): void;
11
11
  };
12
12
  export declare function admitExistingTempWorkspaceRoot(rootDir: string): TempWorkspaceRootAdmission;
13
- export declare function admitTempWorkspaceRoot(rootDir: string): Promise<TempWorkspaceRootAdmission>;
14
- export declare function admitTempWorkspaceRootSync(rootDir: string): TempWorkspaceRootAdmission;
13
+ export declare function admitTempWorkspaceRoot(rootDir: string, trustedWritableAncestors?: readonly string[]): Promise<TempWorkspaceRootAdmission>;
14
+ export declare function admitTempWorkspaceRootSync(rootDir: string, trustedWritableAncestors?: readonly string[]): TempWorkspaceRootAdmission;
@@ -42,15 +42,15 @@ function copyExactDirectoryObservation(stat) {
42
42
  symbolicLink: stat.isSymbolicLink(),
43
43
  });
44
44
  }
45
- function snapshotFromExactObservation(dir, uid, realPath, stat, privateDirectory = false) {
45
+ function snapshotFromExactObservation(dir, uid, realPath, stat, privateDirectory = false, allowWritableAncestor = false) {
46
46
  if (stat.symbolicLink || !stat.directory) {
47
47
  throw new FsSafeError("not-file", "temp workspace root component must be a real directory");
48
48
  }
49
- assertTrustedTempWorkspaceDirectory(stat, uid, privateDirectory, dir);
49
+ assertTrustedTempWorkspaceDirectory(stat, uid, privateDirectory, dir, allowWritableAncestor);
50
50
  const identity = Object.freeze({ dev: stat.dev, ino: stat.ino });
51
51
  // Retain copied immutable scalars, never a mutable Stats object supplied by
52
52
  // an observation hook. Every later permission check uses a fresh snapshot.
53
- return Object.freeze({ dir, identity, numericIdentity: safeNumericIdentity(stat), realPath, privateDirectory });
53
+ return Object.freeze({ dir, identity, numericIdentity: safeNumericIdentity(stat), realPath, privateDirectory, allowWritableAncestor });
54
54
  }
55
55
  function canonicalTempWorkspacePath(dir) {
56
56
  assertNoWindowsPathAlias(dir, "filesystem");
@@ -58,10 +58,10 @@ function canonicalTempWorkspacePath(dir) {
58
58
  assertNoWindowsPathAlias(canonical, "filesystem");
59
59
  return canonical;
60
60
  }
61
- function snapshot(dir, uid, realPath = canonicalTempWorkspacePath(dir), privateDirectory = false) {
61
+ function snapshot(dir, uid, realPath = canonicalTempWorkspacePath(dir), privateDirectory = false, allowWritableAncestor = false) {
62
62
  const stat = inspectDirectoryIdentitySync(dir);
63
63
  const observation = copyExactDirectoryObservation(stat);
64
- return { entry: snapshotFromExactObservation(dir, uid, realPath, observation, privateDirectory), stat };
64
+ return { entry: snapshotFromExactObservation(dir, uid, realPath, observation, privateDirectory, allowWritableAncestor), stat };
65
65
  }
66
66
  function hasCompleteExactIdentity(stat) {
67
67
  return typeof stat.dev === "bigint" && typeof stat.ino === "bigint" &&
@@ -106,7 +106,7 @@ function inspectSnapshotIdentity(entry) {
106
106
  }
107
107
  function assertSnapshot(entry, uid) {
108
108
  const stat = inspectSnapshotIdentity(entry);
109
- assertTrustedTempWorkspaceDirectory(stat, uid, entry.privateDirectory, entry.dir);
109
+ assertTrustedTempWorkspaceDirectory(stat, uid, entry.privateDirectory, entry.dir, entry.allowWritableAncestor);
110
110
  assertCanonicalRoot(entry);
111
111
  }
112
112
  function snapshotMissingRootComponent(parent, dir, ownerUid, privateDirectory) {
@@ -115,7 +115,7 @@ function snapshotMissingRootComponent(parent, dir, ownerUid, privateDirectory) {
115
115
  return snapshot(dir, ownerUid, undefined, privateDirectory);
116
116
  }
117
117
  const current = inspectSnapshotIdentity(parent);
118
- assertTrustedTempWorkspaceDirectory(current, ownerUid, parent.privateDirectory, parent.dir);
118
+ assertTrustedTempWorkspaceDirectory(current, ownerUid, parent.privateDirectory, parent.dir, parent.allowWritableAncestor);
119
119
  let realPath;
120
120
  try {
121
121
  realPath = canonicalTempWorkspacePath(dir);
@@ -136,7 +136,7 @@ function snapshotMissingRootComponent(parent, dir, ownerUid, privateDirectory) {
136
136
  function assertChain(chain, uid) {
137
137
  for (const entry of chain) {
138
138
  const current = inspectSnapshotIdentity(entry);
139
- assertTrustedTempWorkspaceDirectory(current, uid, entry.privateDirectory, entry.dir);
139
+ assertTrustedTempWorkspaceDirectory(current, uid, entry.privateDirectory, entry.dir, entry.allowWritableAncestor);
140
140
  }
141
141
  const last = chain[chain.length - 1];
142
142
  assertCanonicalRoot(last);
@@ -159,7 +159,7 @@ function associateTempWorkspaceRoot(entry, ownerUid, descriptorFd) {
159
159
  if (stat.isSymbolicLink() || !stat.isDirectory()) {
160
160
  throw new FsSafeError("not-file", "temp workspace cleanup parent must be a real directory");
161
161
  }
162
- assertTrustedTempWorkspaceDirectory(stat, ownerUid, entry.privateDirectory, entry.dir);
162
+ assertTrustedTempWorkspaceDirectory(stat, ownerUid, entry.privateDirectory, entry.dir, entry.allowWritableAncestor);
163
163
  }
164
164
  function discoverMissingTempWorkspaceAncestor(ancestor, missing, missingError) {
165
165
  // The caller already classified the first ENOENT. Keep this handoff out of
@@ -197,8 +197,24 @@ function discoverMissingTempWorkspaceAncestor(ancestor, missing, missingError) {
197
197
  }
198
198
  }
199
199
  }
200
- function rootPlan(rootDir) {
200
+ function trustedAncestorPaths(values) {
201
+ if (values === undefined)
202
+ return new Set();
203
+ if (!Array.isArray(values))
204
+ throw new TypeError("trustedWritableAncestors must be an array of canonical absolute paths");
205
+ const paths = new Set();
206
+ for (const value of values) {
207
+ if (typeof value !== "string" || !path.isAbsolute(value) ||
208
+ path.normalize(value) !== value || canonicalTempWorkspacePath(value) !== value) {
209
+ throw new TypeError("trustedWritableAncestors must contain canonical absolute paths");
210
+ }
211
+ paths.add(value);
212
+ }
213
+ return paths;
214
+ }
215
+ function rootPlan(rootDir, trustedWritableAncestors) {
201
216
  assertNoWindowsPathAlias(rootDir, "filesystem");
217
+ const trusted = trustedAncestorPaths(trustedWritableAncestors);
202
218
  const ownerUid = effectiveOwner();
203
219
  let ancestor = resolvePathPreservingWindowsRoot(rootDir);
204
220
  assertNoWindowsPathAlias(ancestor, "filesystem");
@@ -222,12 +238,12 @@ function rootPlan(rootDir) {
222
238
  if (existingCanonicalRoot) {
223
239
  const discovery = snapshotFromExactObservation(ancestor, ownerUid, ancestor, initial, true);
224
240
  return {
225
- admission: canonicalRootAdmission(discovery, ownerUid),
241
+ admission: canonicalRootAdmission(discovery, ownerUid, trusted),
226
242
  missing,
227
243
  ownerUid,
228
244
  };
229
245
  }
230
- const chain = canonicalAncestry(ancestor).map((dir) => snapshot(dir, ownerUid, dir, missing.length === 0 && dir === ancestor).entry);
246
+ const chain = canonicalAncestry(ancestor).map((dir) => snapshot(dir, ownerUid, dir, missing.length === 0 && dir === ancestor, trusted.has(dir)).entry);
231
247
  // Missing-component creation needs a replay before its first mutation. When
232
248
  // the complete root already exists through an alias, retain the historical
233
249
  // guarded route because discovery and mutation use different path spellings.
@@ -261,7 +277,7 @@ function rootAdmission(chain, ownerUid) {
261
277
  },
262
278
  };
263
279
  }
264
- function canonicalRootAdmission(discovery, ownerUid) {
280
+ function canonicalRootAdmission(discovery, ownerUid, trusted) {
265
281
  let admittedChain;
266
282
  const chain = () => {
267
283
  if (!admittedChain) {
@@ -287,7 +303,7 @@ function canonicalRootAdmission(discovery, ownerUid) {
287
303
  const ancestry = canonicalAncestry(discovery.dir);
288
304
  const candidate = ancestry.map((dir, index) => {
289
305
  if (!TEMP_WORKSPACE_NUMERIC_IDENTITY_REPLAY || index !== ancestry.length - 1) {
290
- return snapshot(dir, ownerUid, dir, index === ancestry.length - 1 && discovery.privateDirectory).entry;
306
+ return snapshot(dir, ownerUid, dir, index === ancestry.length - 1 && discovery.privateDirectory, trusted.has(dir)).entry;
291
307
  }
292
308
  const current = inspectSnapshotIdentity(discovery);
293
309
  assertTrustedTempWorkspaceDirectory(current, ownerUid, discovery.privateDirectory, discovery.dir);
@@ -328,8 +344,8 @@ export function admitExistingTempWorkspaceRoot(rootDir) {
328
344
  }
329
345
  return admission ?? rootAdmission(chain, ownerUid);
330
346
  }
331
- export async function admitTempWorkspaceRoot(rootDir) {
332
- const { admission, chain, missing, ownerUid } = rootPlan(rootDir);
347
+ export async function admitTempWorkspaceRoot(rootDir, trustedWritableAncestors) {
348
+ const { admission, chain, missing, ownerUid } = rootPlan(rootDir, trustedWritableAncestors);
333
349
  if (admission)
334
350
  return admission;
335
351
  const guardedChain = chain;
@@ -358,8 +374,8 @@ export async function admitTempWorkspaceRoot(rootDir) {
358
374
  }
359
375
  return rootAdmission(guardedChain, ownerUid);
360
376
  }
361
- export function admitTempWorkspaceRootSync(rootDir) {
362
- const { admission, chain, missing, ownerUid } = rootPlan(rootDir);
377
+ export function admitTempWorkspaceRootSync(rootDir, trustedWritableAncestors) {
378
+ const { admission, chain, missing, ownerUid } = rootPlan(rootDir, trustedWritableAncestors);
363
379
  if (admission)
364
380
  return admission;
365
381
  const guardedChain = chain;