@openclaw/fs-safe 0.20.0 → 0.21.0

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 (69) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +9 -1
  3. package/dist/advanced.d.ts +2 -0
  4. package/dist/advanced.js +1 -0
  5. package/dist/atomic.d.ts +1 -1
  6. package/dist/native-binding.d.ts +22 -0
  7. package/dist/replace-file-buffer.d.ts +4 -0
  8. package/dist/replace-file-buffer.js +36 -0
  9. package/dist/replace-file-copy-fallback.d.ts +2 -0
  10. package/dist/replace-file-copy-fallback.js +66 -38
  11. package/dist/replace-file-descriptor.d.ts +4 -0
  12. package/dist/replace-file-descriptor.js +9 -1
  13. package/dist/replace-file-destination.d.ts +17 -0
  14. package/dist/replace-file-destination.js +61 -0
  15. package/dist/replace-file-mutation.d.ts +26 -0
  16. package/dist/replace-file-mutation.js +47 -0
  17. package/dist/replace-file-temp-owner.d.ts +2 -2
  18. package/dist/replace-file-temp-owner.js +16 -4
  19. package/dist/replace-file-types.d.ts +55 -0
  20. package/dist/replace-file-types.js +1 -0
  21. package/dist/replace-file.d.ts +3 -55
  22. package/dist/replace-file.js +29 -10
  23. package/dist/retained-file-types.d.ts +61 -0
  24. package/dist/retained-file-types.js +1 -0
  25. package/dist/retained-file.d.ts +3 -0
  26. package/dist/retained-file.js +121 -0
  27. package/dist/root-directory-entry.d.ts +9 -0
  28. package/dist/root-directory-entry.js +28 -0
  29. package/dist/root-directory-list.d.ts +7 -1
  30. package/dist/root-directory-list.js +48 -23
  31. package/dist/root-handle-context.d.ts +4 -0
  32. package/dist/root-handle-context.js +12 -0
  33. package/dist/root-impl.d.ts +3 -3
  34. package/dist/root-impl.js +8 -2
  35. package/dist/root-walk.d.ts +19 -12
  36. package/dist/root-walk.js +49 -18
  37. package/dist/temp-target.js +3 -2
  38. package/dist/temp-workspace-admission.js +22 -21
  39. package/dist/temp-workspace-child-admission.d.ts +1 -1
  40. package/dist/temp-workspace-child-admission.js +14 -9
  41. package/dist/temp-workspace-ownership.d.ts +8 -0
  42. package/dist/temp-workspace-ownership.js +52 -0
  43. package/dist/test-hooks.d.ts +3 -0
  44. package/dist/watch-alias.d.ts +6 -0
  45. package/dist/watch-alias.js +80 -0
  46. package/dist/watch-hints.d.ts +8 -0
  47. package/dist/watch-hints.js +77 -0
  48. package/dist/watch-native.d.ts +32 -0
  49. package/dist/watch-native.js +56 -0
  50. package/dist/watch-scan.d.ts +24 -0
  51. package/dist/watch-scan.js +269 -0
  52. package/dist/watch-types.d.ts +58 -0
  53. package/dist/watch-types.js +1 -0
  54. package/dist/watch.d.ts +5 -0
  55. package/dist/watch.js +502 -0
  56. package/docs/advanced.md +1 -0
  57. package/docs/atomic.md +61 -0
  58. package/docs/contributing.md +5 -0
  59. package/docs/durability.md +7 -0
  60. package/docs/index.md +1 -0
  61. package/docs/native-helper.md +9 -0
  62. package/docs/retained-file.md +113 -0
  63. package/docs/root.md +6 -1
  64. package/docs/temp.md +24 -4
  65. package/docs/testing.md +60 -0
  66. package/docs/types.md +6 -0
  67. package/docs/walk.md +22 -1
  68. package/docs/watch.md +184 -0
  69. package/package.json +12 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.21.0 - 2026-09-26
6
+
7
+ ### Highlights
8
+
9
+ - **Guarded filesystem observation:** `@openclaw/fs-safe/watch` observes literal entry and tree scopes beneath an admitted Root and delivers bounded advisory invalidations; guarded scans stay authoritative. One shared Rust event thread per process uses inotify, FSEvents and ReadDirectoryChangesW on Linux, macOS and Windows, sleeps while idle, and falls back to portable polling under `mode: "auto"`. Subscriptions become ready after one baseline scan, stay available under sustained writes, fence stale generations on `setScopes()`, join native work on `close()`, and support `persistent: false` so one-shot Node commands can exit. Thanks @vincentkoc. ([#690](https://github.com/openclaw/fs-safe/pull/690), [#695](https://github.com/openclaw/fs-safe/pull/695), [#697](https://github.com/openclaw/fs-safe/pull/697), [#703](https://github.com/openclaw/fs-safe/pull/703), [#707](https://github.com/openclaw/fs-safe/pull/707))
10
+ - **Linux user namespaces:** private temp workspaces now work beneath unmapped ancestors, including systemd user services with `PrivateUsers=true`, while UID/GID mappings and ancestor permissions are still rechecked. ([#693](https://github.com/openclaw/fs-safe/pull/693))
11
+
12
+ ### Features
13
+
14
+ - **Revocable atomic writes:** atomic replacement can recheck caller authority before new effects and report retained destination identities for partial writes and publication, without treating receipts as permission to roll back. ([#694](https://github.com/openclaw/fs-safe/pull/694))
15
+ - **Root walking:** `symlinkPolicy: "include"` reports links without following their targets, preserving sorted traversal, entry budgets, and the existing skip/follow result types. Directory-to-symlink substitutions fail before descent. ([#692](https://github.com/openclaw/fs-safe/pull/692))
16
+ - **Windows file retirement:** the advanced surface can retire existing NTFS files through a retained handle, with exact producer identity, current authority, and separate disposition and settlement facts. There is no persistence guarantee. ([#706](https://github.com/openclaw/fs-safe/pull/706))
17
+
18
+ ### Performance
19
+
20
+ - **Temporary filename sanitization:** skip duplicate normalization after reserved-device suffixing while preserving filename admission and fallback rules. ([#689](https://github.com/openclaw/fs-safe/pull/689))
21
+
22
+ ### Compatibility
23
+
24
+ - Supplied temp workspace roots must be owned by the effective user and must not be group- or world-writable; use a private per-user root instead of shared `/tmp`. A one-time warning reports host ownership that cannot be verified. ([#693](https://github.com/openclaw/fs-safe/pull/693))
25
+ - On Windows, an events-mode watch holds one handle on each watched Root, so the Root's own ancestor directories cannot be renamed while it is open; renaming inside the Root is unaffected. Use `mode: "poll"` where that matters. ([#697](https://github.com/openclaw/fs-safe/pull/697))
26
+ - `watch()` requires an explicit `mode` (`"auto"`, `"events"` or `"poll"`); `"events"` fails readiness with `helper-unavailable` when no native backend is available, and Bun currently selects polling under `"auto"`. ([#690](https://github.com/openclaw/fs-safe/pull/690))
27
+
5
28
  ## 0.20.0 - 2026-09-25
6
29
 
7
30
  ### Highlights
package/README.md CHANGED
@@ -279,6 +279,7 @@ contract. Low-level helpers that OpenClaw needs to compose higher-level APIs are
279
279
  | `@openclaw/fs-safe/secure-file` | fd-pinned absolute file reads with owner, mode, ACL, trusted-dir, size, and timeout checks |
280
280
  | `@openclaw/fs-safe/file-lock` | async/sync sidecar locks, root-bounded sidecars, ownership verification, and stale policy |
281
281
  | `@openclaw/fs-safe/permissions` | POSIX mode and Windows ACL inspection, raw owner/ACE facts, private-directory creation, and remediation helpers |
282
+ | [`@openclaw/fs-safe/watch`](docs/watch.md) | Guarded observation with native event hints, bounded scans, and joined close |
282
283
  | `@openclaw/fs-safe/walk` | budget-bounded directory walking with symlink policy, filters, and truncation accounting; not root-bounded |
283
284
  | `@openclaw/fs-safe/copy` | directory copying with `clone: "auto"`, `"always"`, or `"never"`; native APFS, Btrfs, ReFS, XFS, and ZFS cloning, portable byte copying, and clone metadata; see [directory copying](docs/copy.md) |
284
285
  | `@openclaw/fs-safe/archive` | policy-driven ZIP/TAR extraction, clamp/filter policy, metadata/path-depth limits, gzip/zstd/bzip2 support, and bounded entry reads |
@@ -368,6 +369,12 @@ await replaceFileAtomic({
368
369
 
369
370
  `replaceFileAtomicSync()` covers the synchronous case with the same options shape. Both accept an injectable `fileSystem` for tests. Async adapters use `chmod()` on the `FileHandle` returned by their required `open()` operation; custom sync adapters using `mode` or `preserveExistingMode` provide the optional descriptor-bound `fchmodSync` operation.
370
371
 
372
+ Both variants accept `assertBeforeMutation` for revocable caller authority and
373
+ `onDestinationState` for observed removal, partial-write, and publication facts.
374
+ The observer receives exact bigint identities from retained descriptors, including
375
+ when later completion fails. These facts do not authorize rollback; the caller
376
+ still owns current authority and content checks. See [atomic write authority](docs/atomic.md#atomic-write-authority-and-destination-state).
377
+
371
378
  ## External outputs
372
379
 
373
380
  Use `writeExternalFileWithinRoot()` when a browser download, renderer, media
@@ -559,7 +566,8 @@ Check `scan.truncated` before treating the result as complete, and `scan.failedD
559
566
  `walkDirectory()` accepts asynchronous `include` and `descend` callbacks through `AsyncWalkDirectoryOptions`, so a marker lookup can prune a directory before its children are read. Decisions remain serial and retain the options object as their `this` receiver; `walkDirectorySync()` and its options remain synchronous. See [Directory walking](docs/walk.md) for callback timing, JavaScript result compatibility, and error handling.
560
567
 
561
568
  For caller-controlled paths, `Root.walk()` is the root-bounded async iterator.
562
- It supports entry/depth budgets, in-root symlink following, cancellation, and a
569
+ It supports entry/depth budgets, including links without following their targets,
570
+ in-root symlink following, cancellation, and a
563
571
  truncation marker (or typed error) when a budget is reached. Its `entryFilter`
564
572
  accepts `"include"`, `"skip"`, or `"skip-subtree"`, directly or through a Promise.
565
573
  After an awaited decision resolves, the walk rechecks cancellation and the
@@ -37,3 +37,5 @@ export { buildRandomTempFilePath, sanitizeTempFileName, type TempFile, tempFile,
37
37
  export { writeSiblingTempFile, writeViaSiblingTempPath, type WriteSiblingTempFileOptions, type WriteSiblingTempFileResult, } from "./sibling-temp.js";
38
38
  export { createIcaclsResetCommand, formatIcaclsResetCommand, formatWindowsAclSummary, inspectWindowsAcl, parseIcaclsOutput, resolveWindowsUserPrincipal, summarizeWindowsAcl, type IcaclsResetCommandOptions, type PermissionExec, type WindowsAclEntry, type WindowsAclSummary, } from "./permissions-windows.js";
39
39
  export type { PermissionCommandFailure } from "./permission-exec.js";
40
+ export { retainFileInDirectory } from "./retained-file.js";
41
+ export type { RetainedFile, RetainedFileAdmission, RetainedFileExpected, RetainedFileIssue, RetainedFileReceipt, RetainedFileResult, RetainFileInDirectoryOptions, } from "./retained-file-types.js";
package/dist/advanced.js CHANGED
@@ -37,3 +37,4 @@ export { appendRegularFile, appendRegularFileSync, readRegularFile, readRegularF
37
37
  export { buildRandomTempFilePath, sanitizeTempFileName, tempFile, withTempFile, } from "./temp-target.js";
38
38
  export { writeSiblingTempFile, writeViaSiblingTempPath, } from "./sibling-temp.js";
39
39
  export { createIcaclsResetCommand, formatIcaclsResetCommand, formatWindowsAclSummary, inspectWindowsAcl, parseIcaclsOutput, resolveWindowsUserPrincipal, summarizeWindowsAcl, } from "./permissions-windows.js";
40
+ export { retainFileInDirectory } from "./retained-file.js";
package/dist/atomic.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { replaceFileAtomic, replaceFileAtomicSync, type ReplaceFileAtomicFileSystem, type ReplaceFileAtomicOptions, type ReplaceFileAtomicResult, type ReplaceFileAtomicSyncFileSystem, type ReplaceFileAtomicSyncOptions, } from "./replace-file.js";
1
+ export { replaceFileAtomic, replaceFileAtomicSync, type ReplaceFileAtomicFileSystem, type ReplaceFileAtomicOptions, type ReplaceFileAtomicResult, type ReplaceFileAtomicDestinationState, type ReplaceFileAtomicSyncFileSystem, type ReplaceFileAtomicSyncOptions, } from "./replace-file.js";
2
2
  export type { RenameIdentityPolicy } from "./pinned-write-types.js";
3
3
  export type { ReplaceFileAtomicRestoreCleanup, ReplaceFileAtomicRestoreFailureDetails, ReplaceFileCopyFallbackRestorePolicy, ReplaceFileDestinationHardlinkPolicy, } from "./replace-file-copy-fallback.js";
4
4
  export { writeTextAtomic, type WriteTextAtomicOptions } from "./text-atomic.js";
@@ -1,3 +1,11 @@
1
+ import type { RetainedFileResult } from "./retained-file-types.js";
2
+ export interface NativeRetainedFile {
3
+ readonly admission: RetainedFileResult | {
4
+ status: "retained";
5
+ identity: string;
6
+ };
7
+ settle(remove: boolean): RetainedFileResult;
8
+ }
1
9
  import type { TarMeterLimits } from "./archive-limits.js";
2
10
  import type { ArchiveMemberKind } from "./archive-plan.js";
3
11
  import type { CopyCloneMode } from "./copy-policy.js";
@@ -95,6 +103,20 @@ type NativeTwoPathArgs = [
95
103
  targetRelPath: string
96
104
  ];
97
105
  export interface NativeBinding {
106
+ /** Windows-only, private handle custody; no borrowed/runtime descriptors. */
107
+ retainWindowsFile?(directory: string, basename: string, parentDev: bigint, parentIno: bigint, dev: bigint, ino: bigint, size: bigint, mtimeNs: bigint, ctimeNs: bigint, sha256: string, maxBytes: number): NativeRetainedFile;
108
+ watchRegister?(root: string, limit: number, callback: (batch: import("./watch-native.js").NativeWatchWireBatch) => void, persistent: boolean): number;
109
+ watchAdd?(id: number, directory: {
110
+ root: string;
111
+ relative: string;
112
+ rootDev: bigint;
113
+ rootIno: bigint;
114
+ dev: bigint;
115
+ ino: bigint;
116
+ }): void;
117
+ watchTestEvent?(id: number, path: string, flags: number): void;
118
+ watchUnregister?(id: number): void;
119
+ watchThreadCount?(): number;
98
120
  /** Internal: consumes only a descriptor returned by this binding. */
99
121
  closeOwnedFd(fd: number): void;
100
122
  /** Internal Darwin-only synchronous inspection; the caller retains its fd. */
@@ -0,0 +1,4 @@
1
+ import type syncFs from "node:fs";
2
+ import type { FileHandle } from "node:fs/promises";
3
+ export declare function writeAtomicDestination(handle: FileHandle, data: Buffer, beforeWrite?: () => Promise<void>, assertBeforeMutation?: () => void, onWriting?: () => void): Promise<void>;
4
+ export declare function writeAtomicDestinationSync(fsModule: Pick<typeof syncFs, "ftruncateSync" | "writeSync">, fd: number, data: Buffer, beforeWrite?: () => void, onWriting?: () => void): void;
@@ -0,0 +1,36 @@
1
+ export async function writeAtomicDestination(handle, data, beforeWrite, assertBeforeMutation, onWriting) {
2
+ if (beforeWrite)
3
+ await beforeWrite();
4
+ assertBeforeMutation?.();
5
+ await handle.truncate(0);
6
+ onWriting?.();
7
+ let written = 0;
8
+ while (written < data.length) {
9
+ if (beforeWrite)
10
+ await beforeWrite();
11
+ assertBeforeMutation?.();
12
+ const result = await handle.write(data, written, data.length - written, written);
13
+ if (result.bytesWritten === 0)
14
+ throw new Error("Copy fallback write made no progress");
15
+ written += result.bytesWritten;
16
+ }
17
+ if (beforeWrite)
18
+ await beforeWrite();
19
+ assertBeforeMutation?.();
20
+ await handle.truncate(data.length);
21
+ }
22
+ export function writeAtomicDestinationSync(fsModule, fd, data, beforeWrite, onWriting) {
23
+ beforeWrite?.();
24
+ fsModule.ftruncateSync(fd, 0);
25
+ onWriting?.();
26
+ let written = 0;
27
+ while (written < data.length) {
28
+ beforeWrite?.();
29
+ const bytesWritten = fsModule.writeSync(fd, data, written, data.length - written, written);
30
+ if (bytesWritten === 0)
31
+ throw new Error("Copy fallback write made no progress");
32
+ written += bytesWritten;
33
+ }
34
+ beforeWrite?.();
35
+ fsModule.ftruncateSync(fd, data.length);
36
+ }
@@ -1,4 +1,5 @@
1
1
  import syncFs, { type BigIntStats } from "node:fs";
2
+ import { AtomicMutation } from "./replace-file-mutation.js";
2
3
  export type ReplaceFileDestinationHardlinkPolicy = "reject";
3
4
  export type ReplaceFileCopyFallbackRestorePolicy = "restore-original" | "none";
4
5
  export type ReplaceFileAtomicRestoreCleanup = "restored" | "restore-failed";
@@ -22,6 +23,7 @@ export declare function copyFallbackReplace(params: {
22
23
  maxRestoreBytes?: number;
23
24
  expectedSourceIdentity?: BigIntStats;
24
25
  sync: boolean;
26
+ mutation?: AtomicMutation;
25
27
  }): Promise<void>;
26
28
  export declare function copyFallbackReplaceSync(params: Omit<Parameters<typeof copyFallbackReplace>[0], "fsModule"> & {
27
29
  fsModule: SyncFallbackFs;
@@ -6,6 +6,9 @@ import { inspectFileIdentity, inspectFileIdentitySync } from "./strict-file-iden
6
6
  import { readOwnedCopySource, readOwnedCopySourceSync } from "./replace-file-copy-source.js";
7
7
  import { resolveReadOpenFlags } from "./read-open-flags.js";
8
8
  import { hasErrorCode } from "./file-cleanup.js";
9
+ import { writeAtomicDestination, writeAtomicDestinationSync } from "./replace-file-buffer.js";
10
+ import { AtomicMutation } from "./replace-file-mutation.js";
11
+ import { captureAtomicDestination, captureAtomicDestinationSync } from "./replace-file-destination.js";
9
12
  const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in syncFs.constants;
10
13
  const NOFOLLOW = SUPPORTS_NOFOLLOW ? syncFs.constants.O_NOFOLLOW : 0;
11
14
  const OPEN_READ_FLAGS = resolveReadOpenFlags();
@@ -44,7 +47,7 @@ function inspectPinnedDestinationSync(fsModule, fd, dest, admission, hardlinks)
44
47
  inspectFileIdentitySync(() => admitDestinationKind(fsModule.lstatSync(dest, { bigint: true }), opened, dest, admission), opened);
45
48
  assertDestinationLinks(opened, dest, admission, hardlinks);
46
49
  }
47
- async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
50
+ async function openPinnedDestination(fsModule, dest, admission, hardlinks, mutation) {
48
51
  let preview;
49
52
  try {
50
53
  preview = fsModule === fs ? syncFs.lstatSync(dest) : await fsModule.lstat(dest);
@@ -61,6 +64,7 @@ async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
61
64
  if (admission === "restore" && preview.isSymbolicLink()) {
62
65
  throw new FsSafeError("symlink", `Refusing copy fallback through symlink destination: ${dest}`);
63
66
  }
67
+ mutation?.assert();
64
68
  const handle = await fsModule.open(dest, admission === "restore" ? OPEN_READ_WRITE_FLAGS : OPEN_READ_FLAGS);
65
69
  try {
66
70
  if (fsModule === fs)
@@ -82,7 +86,7 @@ async function openPinnedDestination(fsModule, dest, admission, hardlinks) {
82
86
  throw error;
83
87
  }
84
88
  }
85
- function openPinnedDestinationSync(fsModule, dest, admission, hardlinks) {
89
+ function openPinnedDestinationSync(fsModule, dest, admission, hardlinks, mutation) {
86
90
  let preview;
87
91
  try {
88
92
  preview = fsModule.lstatSync(dest);
@@ -97,6 +101,7 @@ function openPinnedDestinationSync(fsModule, dest, admission, hardlinks) {
97
101
  if (admission === "restore" && preview.isSymbolicLink()) {
98
102
  throw new FsSafeError("symlink", `Refusing copy fallback through symlink destination: ${dest}`);
99
103
  }
104
+ mutation?.assert();
100
105
  const fd = fsModule.openSync(dest, admission === "restore" ? OPEN_READ_WRITE_FLAGS : OPEN_READ_FLAGS);
101
106
  try {
102
107
  inspectPinnedDestinationSync(fsModule, fd, dest, admission, hardlinks);
@@ -148,28 +153,6 @@ function readRestoreSnapshotSync(fsModule, fd, maxBytes, stat) {
148
153
  return bytesRead;
149
154
  }, restoreReadOptions(stat, maxBytes));
150
155
  }
151
- async function writeAll(handle, data) {
152
- await handle.truncate(0);
153
- let written = 0;
154
- while (written < data.length) {
155
- const result = await handle.write(data, written, data.length - written, written);
156
- if (result.bytesWritten === 0)
157
- throw new Error("Copy fallback write made no progress");
158
- written += result.bytesWritten;
159
- }
160
- await handle.truncate(data.length);
161
- }
162
- function writeAllSync(fsModule, fd, data) {
163
- fsModule.ftruncateSync(fd, 0);
164
- let written = 0;
165
- while (written < data.length) {
166
- const bytesWritten = fsModule.writeSync(fd, data, written, data.length - written, written);
167
- if (bytesWritten === 0)
168
- throw new Error("Copy fallback write made no progress");
169
- written += bytesWritten;
170
- }
171
- fsModule.ftruncateSync(fd, data.length);
172
- }
173
156
  function restoreFailure(writeError, cleanup, restoreError) {
174
157
  const primary = writeError instanceof Error ? writeError : new Error(String(writeError));
175
158
  const details = { cleanup };
@@ -180,23 +163,29 @@ function restoreFailure(writeError, cleanup, restoreError) {
180
163
  ? `Atomic copy fallback failed; original destination restored: ${primary.message}`
181
164
  : `Atomic copy fallback failed and original restoration failed: ${primary.message}`, { cause, details });
182
165
  }
183
- async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestoreBytes, replacementMode) {
166
+ async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestoreBytes, replacementMode, destination, mutation) {
184
167
  const originalStat = fsModule === fs ? syncFs.fstatSync(handle.fd) : await handle.stat();
185
168
  const originalMode = originalStat.mode;
186
169
  const original = await readRestoreSnapshot(handle, maxRestoreBytes, originalStat);
187
170
  try {
188
- await writeAll(handle, replacement);
171
+ await writeAtomicDestination(handle, replacement, destination?.beforeWrite, destination?.assertBeforeMutation, destination?.writing);
172
+ if (destination)
173
+ await destination.verify();
189
174
  await handle.chmod(replacementMode);
190
175
  await handle.sync();
191
176
  }
192
177
  catch (writeError) {
178
+ mutation.rethrowRefusal();
193
179
  try {
194
- await writeAll(handle, original);
180
+ await writeAtomicDestination(handle, original, destination?.beforeWrite, destination?.assertBeforeMutation, destination?.writing);
181
+ if (destination)
182
+ await destination.verify();
195
183
  await handle.chmod(originalMode);
196
184
  await handle.sync();
197
185
  throw restoreFailure(writeError, "restored");
198
186
  }
199
187
  catch (restoreError) {
188
+ mutation.rethrowRefusal();
200
189
  if (restoreError instanceof FsSafeError && restoreError.details?.cleanup === "restored") {
201
190
  throw restoreError;
202
191
  }
@@ -204,23 +193,27 @@ async function replacePinnedWithRestore(fsModule, handle, replacement, maxRestor
204
193
  }
205
194
  }
206
195
  }
207
- function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes, replacementMode, fchmodSync) {
196
+ function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes, replacementMode, fchmodSync, destination, mutation) {
208
197
  const originalStat = fsModule.fstatSync(fd);
209
198
  const originalMode = originalStat.mode;
210
199
  const original = readRestoreSnapshotSync(fsModule, fd, maxRestoreBytes, originalStat);
211
200
  try {
212
- writeAllSync(fsModule, fd, replacement);
201
+ writeAtomicDestinationSync(fsModule, fd, replacement, destination?.beforeWrite, destination?.writing);
202
+ destination?.verify();
213
203
  fchmodSync?.(fd, replacementMode);
214
204
  fsModule.fsyncSync(fd);
215
205
  }
216
206
  catch (writeError) {
207
+ mutation?.rethrowRefusal();
217
208
  try {
218
- writeAllSync(fsModule, fd, original);
209
+ writeAtomicDestinationSync(fsModule, fd, original, destination?.beforeWrite, destination?.writing);
210
+ destination?.verify();
219
211
  fchmodSync?.(fd, originalMode);
220
212
  fsModule.fsyncSync(fd);
221
213
  throw restoreFailure(writeError, "restored");
222
214
  }
223
215
  catch (restoreError) {
216
+ mutation?.rethrowRefusal();
224
217
  if (restoreError instanceof FsSafeError && restoreError.details?.cleanup === "restored") {
225
218
  throw restoreError;
226
219
  }
@@ -229,6 +222,7 @@ function replacePinnedWithRestoreSync(fsModule, fd, replacement, maxRestoreBytes
229
222
  }
230
223
  }
231
224
  export async function copyFallbackReplace(params) {
225
+ const mutation = params.mutation ?? new AtomicMutation({});
232
226
  const source = await readOwnedCopySource({
233
227
  fsModule: params.fsModule,
234
228
  src: params.src,
@@ -237,12 +231,16 @@ export async function copyFallbackReplace(params) {
237
231
  const { replacement } = source;
238
232
  let destHandle = null;
239
233
  let closeRequiredForSuccess = false;
234
+ let completed = false;
235
+ let destination;
240
236
  try {
241
237
  if (params.restore === "restore-original") {
242
- const pinned = await openPinnedDestination(params.fsModule, params.dest, "restore", params.destinationHardlinks);
238
+ const pinned = await openPinnedDestination(params.fsModule, params.dest, "restore", params.destinationHardlinks, mutation);
243
239
  if (pinned) {
244
240
  destHandle = pinned;
245
- await replacePinnedWithRestore(params.fsModule, destHandle, replacement, params.maxRestoreBytes, source.mode);
241
+ if (mutation.active)
242
+ destination = await captureAtomicDestination(params.fsModule, pinned, params.dest, mutation, params.destinationHardlinks === "reject");
243
+ await replacePinnedWithRestore(params.fsModule, destHandle, replacement, params.maxRestoreBytes, source.mode, destination, mutation);
246
244
  }
247
245
  }
248
246
  if (!destHandle) {
@@ -260,16 +258,31 @@ export async function copyFallbackReplace(params) {
260
258
  }
261
259
  if (destStat) {
262
260
  await assertDestinationHardlinkPolicy(params.fsModule, params.dest, params.destinationHardlinks);
261
+ mutation.assert();
263
262
  await params.fsModule.rm(params.dest, { force: true });
263
+ mutation.removed(params.dest);
264
264
  }
265
+ mutation.assert();
265
266
  destHandle = await params.fsModule.open(params.dest, OPEN_WRITE_EXCLUSIVE_FLAGS, source.mode & 0o777);
266
- await destHandle.writeFile(replacement);
267
+ if (mutation.active) {
268
+ destination = await captureAtomicDestination(params.fsModule, destHandle, params.dest, mutation, params.destinationHardlinks === "reject");
269
+ destination.writing();
270
+ await writeAtomicDestination(destHandle, replacement, destination.beforeWrite, destination.assertBeforeMutation);
271
+ await destination.verify();
272
+ }
273
+ else {
274
+ await destHandle.writeFile(replacement);
275
+ }
267
276
  await destHandle.chmod(source.mode);
268
277
  if (params.sync) {
269
278
  await destHandle.sync();
270
279
  }
271
280
  closeRequiredForSuccess = !params.sync;
272
281
  }
282
+ if (destination)
283
+ await destination.verify();
284
+ destination?.published();
285
+ completed = true;
273
286
  }
274
287
  finally {
275
288
  if (destHandle) {
@@ -277,7 +290,7 @@ export async function copyFallbackReplace(params) {
277
290
  await destHandle.close();
278
291
  }
279
292
  catch (closeError) {
280
- if (closeRequiredForSuccess) {
293
+ if (closeRequiredForSuccess && completed) {
281
294
  throw closeError;
282
295
  }
283
296
  }
@@ -285,6 +298,7 @@ export async function copyFallbackReplace(params) {
285
298
  }
286
299
  }
287
300
  export function copyFallbackReplaceSync(params) {
301
+ const mutation = params.mutation ?? new AtomicMutation({});
288
302
  const source = readOwnedCopySourceSync({
289
303
  fsModule: params.fsModule,
290
304
  src: params.src,
@@ -293,12 +307,16 @@ export function copyFallbackReplaceSync(params) {
293
307
  const { replacement } = source;
294
308
  let destFd;
295
309
  let closeRequiredForSuccess = false;
310
+ let completed = false;
311
+ let destination;
296
312
  try {
297
313
  if (params.restore === "restore-original") {
298
- const pinned = openPinnedDestinationSync(params.fsModule, params.dest, "restore", params.destinationHardlinks);
314
+ const pinned = openPinnedDestinationSync(params.fsModule, params.dest, "restore", params.destinationHardlinks, mutation);
299
315
  if (pinned !== null) {
300
316
  destFd = pinned;
301
- replacePinnedWithRestoreSync(params.fsModule, destFd, replacement, params.maxRestoreBytes, source.mode, params.fchmodSync);
317
+ if (mutation.active)
318
+ destination = captureAtomicDestinationSync(params.fsModule, pinned, params.dest, mutation, params.destinationHardlinks === "reject");
319
+ replacePinnedWithRestoreSync(params.fsModule, destFd, replacement, params.maxRestoreBytes, source.mode, params.fchmodSync, destination, mutation);
302
320
  }
303
321
  }
304
322
  if (destFd === undefined) {
@@ -315,16 +333,26 @@ export function copyFallbackReplaceSync(params) {
315
333
  }
316
334
  if (destStat) {
317
335
  assertDestinationHardlinkPolicySync(params.fsModule, params.dest, params.destinationHardlinks);
336
+ mutation.assert();
318
337
  params.fsModule.rmSync(params.dest, { force: true });
338
+ mutation.removed(params.dest);
319
339
  }
340
+ mutation.assert();
320
341
  destFd = params.fsModule.openSync(params.dest, OPEN_WRITE_EXCLUSIVE_FLAGS, source.mode & 0o777);
321
- writeAllSync(params.fsModule, destFd, replacement);
342
+ if (mutation.active)
343
+ destination = captureAtomicDestinationSync(params.fsModule, destFd, params.dest, mutation, params.destinationHardlinks === "reject");
344
+ destination?.writing();
345
+ writeAtomicDestinationSync(params.fsModule, destFd, replacement, destination?.beforeWrite);
346
+ destination?.verify();
322
347
  params.fchmodSync?.(destFd, source.mode);
323
348
  if (params.sync) {
324
349
  params.fsModule.fsyncSync(destFd);
325
350
  }
326
351
  closeRequiredForSuccess = !params.sync;
327
352
  }
353
+ destination?.verify();
354
+ destination?.published();
355
+ completed = true;
328
356
  }
329
357
  finally {
330
358
  if (destFd !== undefined) {
@@ -332,7 +360,7 @@ export function copyFallbackReplaceSync(params) {
332
360
  params.fsModule.closeSync(destFd);
333
361
  }
334
362
  catch (closeError) {
335
- if (closeRequiredForSuccess) {
363
+ if (closeRequiredForSuccess && completed) {
336
364
  throw closeError;
337
365
  }
338
366
  }
@@ -1,6 +1,7 @@
1
1
  import syncFs, { type BigIntStats } from "node:fs";
2
2
  import fs, { type FileHandle } from "node:fs/promises";
3
3
  import { type DirectoryModeOwner } from "./directory-mode-node.js";
4
+ import type { AtomicMutation } from "./replace-file-mutation.js";
4
5
  type AsyncTempFileSystem = Pick<typeof fs, "lstat" | "open" | "writeFile">;
5
6
  type SyncTempFileSystem = Pick<typeof syncFs, "closeSync" | "fstatSync" | "fsyncSync" | "lstatSync" | "openSync" | "writeFileSync">;
6
7
  export type SyncFchmod = (fd: number, mode: number) => void;
@@ -11,6 +12,7 @@ export declare function pinDirectoryForMode(params: {
11
12
  dirPath: string;
12
13
  /** Compatibility for best-effort directory modes; admission and close still fail closed. */
13
14
  ignoreChmodError?: boolean;
15
+ mutation?: AtomicMutation;
14
16
  }): Promise<DirectoryModeOwner | undefined>;
15
17
  export declare function applyDirectoryMode(params: Parameters<typeof pinDirectoryForMode>[0] & {
16
18
  mode: number;
@@ -20,6 +22,7 @@ export declare function applyDirectoryModeSync(params: {
20
22
  dirPath: string;
21
23
  mode: number;
22
24
  fchmodSync?: SyncFchmod;
25
+ mutation?: AtomicMutation;
23
26
  }): void;
24
27
  export declare function writeTempFile(params: {
25
28
  fsModule: AsyncTempFileSystem;
@@ -28,6 +31,7 @@ export declare function writeTempFile(params: {
28
31
  mode: number;
29
32
  sync: boolean;
30
33
  onIdentity?: (identity: BigIntStats) => void;
34
+ mutation?: AtomicMutation;
31
35
  }): Promise<{
32
36
  handle: FileHandle;
33
37
  identity: BigIntStats;
@@ -73,7 +73,10 @@ export async function pinDirectoryForMode(params) {
73
73
  : await inspectFileIdentity(async () => assertDirectory(await handle.stat({ bigint: true }), params.dirPath), expected);
74
74
  return Number(opened.mode & 4095n);
75
75
  },
76
- chmod: (mode) => handle.chmod(mode),
76
+ chmod: (mode) => {
77
+ params.mutation?.assert();
78
+ return handle.chmod(mode);
79
+ },
77
80
  close: () => handle.close(),
78
81
  ignoreChmodError: params.ignoreChmodError,
79
82
  });
@@ -103,6 +106,7 @@ export function applyDirectoryModeSync(params) {
103
106
  try {
104
107
  inspectFileIdentitySync(() => assertDirectory(params.fsModule.fstatSync(fd, { bigint: true }), params.dirPath), expected);
105
108
  // chmod ignores file-type bits; mask so raw stat modes are tolerated.
109
+ params.mutation?.assert();
106
110
  params.fchmodSync?.(fd, params.mode & 0o7777);
107
111
  }
108
112
  finally {
@@ -110,6 +114,7 @@ export function applyDirectoryModeSync(params) {
110
114
  }
111
115
  }
112
116
  export async function writeTempFile(params) {
117
+ params.mutation?.assert();
113
118
  const handle = await params.fsModule.open(params.tempPath, "wx", params.mode);
114
119
  try {
115
120
  // Custom adapters retain their async-only metadata contract.
@@ -117,6 +122,7 @@ export async function writeTempFile(params) {
117
122
  ? syncFs.fstatSync(handle.fd, { bigint: true }) : handle.stat({ bigint: true });
118
123
  const identity = await inspectFileIdentity(inspect);
119
124
  params.onIdentity?.(identity);
125
+ params.mutation?.assert();
120
126
  await params.fsModule.writeFile(handle, params.content);
121
127
  await handle.chmod(params.mode);
122
128
  if (params.sync) {
@@ -136,10 +142,12 @@ export async function writeTempFile(params) {
136
142
  }
137
143
  }
138
144
  export function writeTempFileSync(params) {
145
+ params.mutation?.assert();
139
146
  const fd = params.fsModule.openSync(params.tempPath, "wx", params.mode);
140
147
  try {
141
148
  const identity = inspectFileIdentitySync(() => params.fsModule.fstatSync(fd, { bigint: true }));
142
149
  params.onIdentity?.(identity);
150
+ params.mutation?.assert();
143
151
  params.fsModule.writeFileSync(fd, params.content);
144
152
  params.fchmodSync?.(fd, params.mode);
145
153
  if (params.sync) {
@@ -0,0 +1,17 @@
1
+ import fsSync from "node:fs";
2
+ import fs, { type FileHandle } from "node:fs/promises";
3
+ import type { AtomicMutation } from "./replace-file-mutation.js";
4
+ /** Borrow the writer's descriptor; never adopt an identity from a later pathname open. */
5
+ export declare function captureAtomicDestination(fsModule: Pick<typeof fs, "lstat">, handle: FileHandle, pathname: string, mutation: AtomicMutation, rejectHardlinks: boolean): Promise<{
6
+ verify: () => Promise<void>;
7
+ writing: () => void;
8
+ beforeWrite: () => Promise<void>;
9
+ assertBeforeMutation: () => void;
10
+ published: () => void;
11
+ }>;
12
+ export declare function captureAtomicDestinationSync(fsModule: Pick<typeof fsSync, "lstatSync" | "fstatSync">, fd: number, pathname: string, mutation: AtomicMutation, rejectHardlinks: boolean): {
13
+ verify: () => void;
14
+ writing: () => void;
15
+ beforeWrite: () => void;
16
+ published: () => void;
17
+ };
@@ -0,0 +1,61 @@
1
+ import fsSync, {} from "node:fs";
2
+ import fs, {} from "node:fs/promises";
3
+ import { FsSafeError } from "./errors.js";
4
+ import { inspectFileIdentity, inspectFileIdentitySync } from "./strict-file-identity.js";
5
+ function regular(stat, pathname, rejectHardlinks) {
6
+ if (stat.isSymbolicLink() || !stat.isFile()) {
7
+ throw new FsSafeError("path-mismatch", `Atomic replace destination changed: ${pathname}`);
8
+ }
9
+ if (rejectHardlinks && stat.nlink !== 1n) {
10
+ throw new FsSafeError("hardlink", `Hardlinked atomic replace destination not allowed: ${pathname}`);
11
+ }
12
+ return stat;
13
+ }
14
+ /** Borrow the writer's descriptor; never adopt an identity from a later pathname open. */
15
+ export async function captureAtomicDestination(fsModule, handle, pathname, mutation, rejectHardlinks) {
16
+ const inspect = () => fsModule === fs
17
+ ? fsSync.fstatSync(handle.fd, { bigint: true }) : handle.stat({ bigint: true });
18
+ const identity = await inspectFileIdentity(inspect);
19
+ regular(identity, pathname, rejectHardlinks);
20
+ const verify = async () => {
21
+ try {
22
+ await inspectFileIdentity(async () => regular(await inspect(), pathname, rejectHardlinks), identity);
23
+ await inspectFileIdentity(async () => regular(await fsModule.lstat(pathname, { bigint: true }), pathname, rejectHardlinks), identity);
24
+ }
25
+ catch (error) {
26
+ mutation.refuse(error);
27
+ }
28
+ };
29
+ return {
30
+ verify,
31
+ writing: () => mutation.destination("writing", pathname, identity),
32
+ beforeWrite: async () => {
33
+ mutation.assert();
34
+ await verify();
35
+ },
36
+ assertBeforeMutation: () => mutation.assert(),
37
+ published: () => mutation.destination("published", pathname, identity),
38
+ };
39
+ }
40
+ export function captureAtomicDestinationSync(fsModule, fd, pathname, mutation, rejectHardlinks) {
41
+ const identity = inspectFileIdentitySync(() => fsModule.fstatSync(fd, { bigint: true }));
42
+ regular(identity, pathname, rejectHardlinks);
43
+ const verify = () => {
44
+ try {
45
+ inspectFileIdentitySync(() => regular(fsModule.fstatSync(fd, { bigint: true }), pathname, rejectHardlinks), identity);
46
+ inspectFileIdentitySync(() => regular(fsModule.lstatSync(pathname, { bigint: true }), pathname, rejectHardlinks), identity);
47
+ }
48
+ catch (error) {
49
+ mutation.refuse(error);
50
+ }
51
+ };
52
+ return {
53
+ verify,
54
+ writing: () => mutation.destination("writing", pathname, identity),
55
+ beforeWrite: () => {
56
+ mutation.assert();
57
+ verify();
58
+ },
59
+ published: () => mutation.destination("published", pathname, identity),
60
+ };
61
+ }
@@ -0,0 +1,26 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ export type ReplaceFileAtomicDestinationState = Readonly<{
3
+ state: "removed";
4
+ path: string;
5
+ }> | Readonly<{
6
+ state: "writing" | "published";
7
+ path: string;
8
+ dev: bigint;
9
+ ino: bigint;
10
+ }>;
11
+ export type AtomicMutationOptions = {
12
+ /** Recheck live authority before new effects; retained descriptor completion may settle. */
13
+ assertBeforeMutation?: () => void;
14
+ /** Retain observed destination facts even when later completion fails. */
15
+ onDestinationState?: (state: ReplaceFileAtomicDestinationState) => void;
16
+ };
17
+ export declare class AtomicMutation {
18
+ #private;
19
+ readonly active: boolean;
20
+ constructor(options: AtomicMutationOptions);
21
+ rethrowRefusal(): void;
22
+ refuse(error: unknown): never;
23
+ assert(): void;
24
+ destination(state: "writing" | "published", path: string, identity: BigIntStats): void;
25
+ removed(path: string): void;
26
+ }