@openclaw/fs-safe 0.1.0 → 0.1.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 (114) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +23 -3
  3. package/dist/archive-staging.d.ts.map +1 -1
  4. package/dist/archive-staging.js +51 -7
  5. package/dist/archive.js +2 -2
  6. package/dist/file-store-boundary.d.ts +27 -0
  7. package/dist/file-store-boundary.d.ts.map +1 -0
  8. package/dist/file-store-boundary.js +164 -0
  9. package/dist/file-store.d.ts.map +1 -1
  10. package/dist/file-store.js +62 -72
  11. package/dist/path.d.ts +1 -0
  12. package/dist/path.d.ts.map +1 -1
  13. package/dist/path.js +6 -3
  14. package/dist/private-file-store.d.ts +5 -7
  15. package/dist/private-file-store.d.ts.map +1 -1
  16. package/dist/private-file-store.js +21 -34
  17. package/dist/root-context.d.ts +23 -0
  18. package/dist/root-context.d.ts.map +1 -0
  19. package/dist/root-context.js +62 -0
  20. package/dist/root-errors.d.ts +4 -0
  21. package/dist/root-errors.d.ts.map +1 -0
  22. package/dist/root-errors.js +21 -0
  23. package/dist/root-impl.d.ts +108 -0
  24. package/dist/root-impl.d.ts.map +1 -0
  25. package/dist/{safe-root.js → root-impl.js} +464 -251
  26. package/dist/root.d.ts +1 -107
  27. package/dist/root.d.ts.map +1 -1
  28. package/dist/root.js +1 -1332
  29. package/docs/advanced.md +100 -0
  30. package/docs/archive.md +199 -0
  31. package/docs/atomic.md +163 -0
  32. package/docs/config.md +65 -0
  33. package/docs/contributing.md +80 -0
  34. package/docs/errors.md +154 -0
  35. package/docs/file-store.md +213 -0
  36. package/docs/filename.md +0 -0
  37. package/docs/index.md +76 -0
  38. package/docs/install-path.md +167 -0
  39. package/docs/install.md +150 -0
  40. package/docs/json-store.md +200 -0
  41. package/docs/json.md +158 -0
  42. package/docs/local-roots.md +164 -0
  43. package/docs/path-scope.md +130 -0
  44. package/docs/path.md +191 -0
  45. package/docs/permissions.md +95 -0
  46. package/docs/private-file-store.md +45 -0
  47. package/docs/python-helper.md +103 -0
  48. package/docs/quickstart.md +147 -0
  49. package/docs/reading.md +174 -0
  50. package/docs/regular-file.md +175 -0
  51. package/docs/root.md +205 -0
  52. package/docs/secret-file.md +154 -0
  53. package/docs/secure-file.md +82 -0
  54. package/docs/security-model.md +99 -0
  55. package/docs/sidecar-lock.md +229 -0
  56. package/docs/store.md +44 -0
  57. package/docs/temp.md +276 -0
  58. package/docs/test-hooks.md +74 -0
  59. package/docs/testing.md +168 -0
  60. package/docs/timing.md +121 -0
  61. package/docs/types.md +155 -0
  62. package/docs/walk.md +63 -0
  63. package/docs/writing.md +222 -0
  64. package/package.json +5 -2
  65. package/dist/archive-utils.d.ts +0 -3
  66. package/dist/archive-utils.d.ts.map +0 -1
  67. package/dist/archive-utils.js +0 -26
  68. package/dist/boundary-file-read.d.ts +0 -44
  69. package/dist/boundary-file-read.d.ts.map +0 -1
  70. package/dist/boundary-file-read.js +0 -129
  71. package/dist/boundary-path.d.ts +0 -39
  72. package/dist/boundary-path.d.ts.map +0 -1
  73. package/dist/boundary-path.js +0 -598
  74. package/dist/fs-pinned-path-helper.d.ts +0 -7
  75. package/dist/fs-pinned-path-helper.d.ts.map +0 -1
  76. package/dist/fs-pinned-path-helper.js +0 -182
  77. package/dist/fs-pinned-write-helper.d.ts +0 -21
  78. package/dist/fs-pinned-write-helper.d.ts.map +0 -1
  79. package/dist/fs-pinned-write-helper.js +0 -263
  80. package/dist/hardlink-guards.d.ts +0 -7
  81. package/dist/hardlink-guards.d.ts.map +0 -1
  82. package/dist/hardlink-guards.js +0 -30
  83. package/dist/install-safe-path.d.ts +0 -20
  84. package/dist/install-safe-path.d.ts.map +0 -1
  85. package/dist/install-safe-path.js +0 -94
  86. package/dist/json-file.d.ts +0 -3
  87. package/dist/json-file.d.ts.map +0 -1
  88. package/dist/json-file.js +0 -123
  89. package/dist/json-files.d.ts +0 -20
  90. package/dist/json-files.d.ts.map +0 -1
  91. package/dist/json-files.js +0 -153
  92. package/dist/path-alias-guards.d.ts +0 -19
  93. package/dist/path-alias-guards.d.ts.map +0 -1
  94. package/dist/path-alias-guards.js +0 -21
  95. package/dist/path-guards.d.ts +0 -7
  96. package/dist/path-guards.d.ts.map +0 -1
  97. package/dist/path-guards.js +0 -49
  98. package/dist/path-safety.d.ts +0 -12
  99. package/dist/path-safety.d.ts.map +0 -1
  100. package/dist/path-safety.js +0 -50
  101. package/dist/safe-open-sync.d.ts +0 -24
  102. package/dist/safe-open-sync.d.ts.map +0 -1
  103. package/dist/safe-open-sync.js +0 -71
  104. package/dist/safe-root.d.ts +0 -123
  105. package/dist/safe-root.d.ts.map +0 -1
  106. package/dist/secure-temp-workspace.d.ts +0 -25
  107. package/dist/secure-temp-workspace.d.ts.map +0 -1
  108. package/dist/secure-temp-workspace.js +0 -136
  109. package/dist/sibling-temp-file.d.ts +0 -16
  110. package/dist/sibling-temp-file.d.ts.map +0 -1
  111. package/dist/sibling-temp-file.js +0 -73
  112. package/dist/sibling-temp-write.d.ts +0 -8
  113. package/dist/sibling-temp-write.d.ts.map +0 -1
  114. package/dist/sibling-temp-write.js +0 -40
@@ -0,0 +1,168 @@
1
+ # Testing
2
+
3
+ `@openclaw/fs-safe/test-hooks` exposes a small set of test-only injection points. They are inert in production: the hooks only activate when `process.env.NODE_ENV === "test"`. Outside test mode, calls to set hooks are no-ops, so leaking a test setup line into production is safe but ineffective.
4
+
5
+ ```ts
6
+ import {
7
+ __setFsSafeTestHooksForTest,
8
+ type FsSafeTestHooks,
9
+ } from "@openclaw/fs-safe/test-hooks";
10
+ ```
11
+
12
+ The double-underscore prefix is a deliberate "hands off" signal: production code should never import this module. ESLint or your equivalent linter should flag it.
13
+
14
+ ## When to reach for hooks
15
+
16
+ - Reproduce a TOCTOU race deterministically: simulate a symlink swap between resolve and open, or between write and rename.
17
+ - Force Node-only behavior without uninstalling Python from your runners.
18
+ - Inject latency to test cancellation/timeout paths.
19
+
20
+ If you don't need to inject a race, you don't need hooks — most tests should drive the library through normal calls and assert on observable behavior.
21
+
22
+ ## Hooks API
23
+
24
+ ```ts
25
+ type FsSafeTestHooks = {
26
+ afterPreOpenLstat?: (filePath: string) => Promise<void> | void;
27
+ beforeOpen?: (filePath: string, flags: number) => Promise<void> | void;
28
+ afterOpen?: (filePath: string, handle: import("node:fs/promises").FileHandle) => Promise<void> | void;
29
+ };
30
+
31
+ function __setFsSafeTestHooksForTest(hooks?: FsSafeTestHooks): void;
32
+ function getFsSafeTestHooks(): FsSafeTestHooks | undefined;
33
+ ```
34
+
35
+ Hooks are called at well-defined points in the library's hot paths:
36
+
37
+ - **`afterPreOpenLstat`** — runs after the pre-open `lstat`. A common use is to swap the path's target via `fs.symlink`/`fs.unlink` to drive a TOCTOU race.
38
+ - **`beforeOpen`** — runs before `fs.open` with the exact flags the root read path will use.
39
+ - **`afterOpen`** — runs after the file handle is opened. Useful to wrap handle methods or inject a size race before a stream is consumed.
40
+
41
+ `__setFsSafeTestHooksForTest(undefined)` clears all hooks. Always clean up between tests.
42
+
43
+ ## Example: simulate a TOCTOU swap
44
+
45
+ ```ts
46
+ import { describe, it, beforeEach, afterEach, expect } from "vitest";
47
+ import { mkdtemp, mkdir, rm, symlink, unlink, writeFile } from "node:fs/promises";
48
+ import os from "node:os";
49
+ import path from "node:path";
50
+ import { root, FsSafeError } from "@openclaw/fs-safe";
51
+ import { __setFsSafeTestHooksForTest } from "@openclaw/fs-safe/test-hooks";
52
+
53
+ let dir: string;
54
+ beforeEach(async () => {
55
+ dir = await mkdtemp(path.join(os.tmpdir(), "fs-safe-toctou-"));
56
+ await writeFile(path.join(dir, "real.txt"), "secret");
57
+ await writeFile(path.join(dir, "decoy.txt"), "decoy");
58
+ });
59
+ afterEach(async () => {
60
+ __setFsSafeTestHooksForTest(undefined);
61
+ await rm(dir, { recursive: true, force: true });
62
+ });
63
+
64
+ it("rejects a swap between resolve and open", async () => {
65
+ const fs = await root(dir, { symlinks: "reject" });
66
+
67
+ __setFsSafeTestHooksForTest({
68
+ afterPreOpenLstat: async (absPath) => {
69
+ // swap real.txt for a symlink to decoy.txt right before the open
70
+ await unlink(absPath);
71
+ await symlink(path.join(dir, "decoy.txt"), absPath);
72
+ },
73
+ });
74
+
75
+ await expect(fs.read("real.txt")).rejects.toMatchObject({
76
+ name: "FsSafeError",
77
+ code: expect.stringMatching(/symlink|path-mismatch/),
78
+ });
79
+ });
80
+ ```
81
+
82
+ The `code` may be `symlink` (caught at open by `O_NOFOLLOW`) or `path-mismatch` (caught by the post-open identity check) depending on platform — both are correct refusals.
83
+
84
+ ## Example: force Node-only fallback behavior
85
+
86
+ ```ts
87
+ import { configureFsSafePython } from "@openclaw/fs-safe/config";
88
+
89
+ beforeEach(() => {
90
+ configureFsSafePython({ mode: "off" });
91
+ });
92
+
93
+ afterEach(() => {
94
+ configureFsSafePython({ mode: "auto", pythonPath: undefined });
95
+ });
96
+
97
+ it("runs without the Python helper", async () => {
98
+ const fs = await root(dir);
99
+ await fs.write("file.txt", "ok");
100
+ await expect(fs.readText("file.txt")).resolves.toBe("ok");
101
+ });
102
+ ```
103
+
104
+ ## Cleanup is mandatory
105
+
106
+ Hooks set by `__setFsSafeTestHooksForTest` persist across tests until explicitly cleared. Always clear in `afterEach` (or your test framework's equivalent) — leaked hooks will silently change behavior in unrelated tests and cause maddening intermittent failures.
107
+
108
+ ```ts
109
+ import { afterEach } from "vitest";
110
+ import { __setFsSafeTestHooksForTest } from "@openclaw/fs-safe/test-hooks";
111
+
112
+ afterEach(() => {
113
+ __setFsSafeTestHooksForTest(undefined);
114
+ });
115
+ ```
116
+
117
+ A global hook clear in your test setup file is a good safety net.
118
+
119
+ ## Patterns for testing fs-safe-using code
120
+
121
+ You usually don't need hooks. Most tests follow this shape:
122
+
123
+ ```ts
124
+ import { mkdtemp, rm } from "node:fs/promises";
125
+ import os from "node:os";
126
+ import path from "node:path";
127
+ import { root } from "@openclaw/fs-safe";
128
+
129
+ let dir: string;
130
+ let fs: Awaited<ReturnType<typeof root>>;
131
+
132
+ beforeEach(async () => {
133
+ dir = await mkdtemp(path.join(os.tmpdir(), "my-feature-"));
134
+ fs = await root(dir, { symlinks: "reject", hardlinks: "reject", mkdir: true });
135
+ });
136
+ afterEach(async () => {
137
+ await rm(dir, { recursive: true, force: true });
138
+ });
139
+
140
+ it("writes and reads through the boundary", async () => {
141
+ await fs.write("notes/today.txt", "hello");
142
+ expect(await fs.readText("notes/today.txt")).toBe("hello");
143
+ });
144
+ ```
145
+
146
+ For tests that need a private temp workspace, [`withTempWorkspace`](temp.md) makes the setup-and-teardown story trivial.
147
+
148
+ ## Repo test shards
149
+
150
+ Run the full local gate before handoff:
151
+
152
+ ```sh
153
+ pnpm check
154
+ ```
155
+
156
+ Run only the security boundary corpus while iterating on root/path/archive/temp hardening:
157
+
158
+ ```sh
159
+ pnpm test:security
160
+ ```
161
+
162
+ `pnpm check` also runs `pnpm lint:file-size`. New source and test files should stay under 500 lines. Existing larger files have explicit budgets in `scripts/check-file-size.mjs`; do not increase those budgets as part of unrelated work.
163
+
164
+ ## See also
165
+
166
+ - [Security model](security-model.md) — what the boundary is supposed to defend; design tests around the same threats.
167
+ - [`root()`](root.md) — the surface most tests will exercise.
168
+ - [Temp workspaces](temp.md) — `withTempWorkspace` for cleanup-on-exit test directories.
package/docs/timing.md ADDED
@@ -0,0 +1,121 @@
1
+ # Timing
2
+
3
+ `withTimeout(promise, timeoutMs, labelOrOptions?)` is a small helper for putting a wall-clock ceiling on an async operation. It rejects with a synthetic timeout error after `timeoutMs` and clears its internal timer when the wrapped promise settles first.
4
+
5
+ ```ts
6
+ import { withTimeout } from "@openclaw/fs-safe/advanced";
7
+ ```
8
+
9
+ ## Signature
10
+
11
+ ```ts
12
+ function withTimeout<T>(
13
+ promise: Promise<T>,
14
+ timeoutMs: number,
15
+ labelOrOptions?: string | {
16
+ label?: string;
17
+ message?: string;
18
+ createError?: () => Error;
19
+ },
20
+ ): Promise<T>;
21
+ ```
22
+
23
+ If `timeoutMs` is `0`, negative, `Infinity`, or `NaN`, the helper is a no-op and simply awaits the original promise.
24
+
25
+ ## Examples
26
+
27
+ ### Simple ceiling
28
+
29
+ ```ts
30
+ import { withTimeout } from "@openclaw/fs-safe/advanced";
31
+
32
+ const buf = await withTimeout(
33
+ fs.readFile("/srv/big.bin"),
34
+ 5_000,
35
+ "read big.bin",
36
+ );
37
+ ```
38
+
39
+ If the read doesn't resolve within 5 seconds, the returned promise rejects with `Error: read big.bin timed out after 5000ms`. The underlying `fs.readFile` continues until Node finishes it — `withTimeout` does not cancel the wrapped work, only the wait.
40
+
41
+ ### Custom message
42
+
43
+ ```ts
44
+ await withTimeout(work(), 5_000, {
45
+ message: "build did not finish in time",
46
+ });
47
+ ```
48
+
49
+ ### Custom error factory
50
+
51
+ ```ts
52
+ class BuildTimeout extends Error {}
53
+
54
+ await withTimeout(work(), 5_000, {
55
+ createError: () => new BuildTimeout("build timeout (5s)"),
56
+ });
57
+ ```
58
+
59
+ `createError` is called when the timer fires; the returned error is what the promise rejects with. Use this when callers branch on `instanceof` or want a custom `cause`.
60
+
61
+ ## Cancellation
62
+
63
+ `withTimeout` does **not** abort the wrapped operation when the timer fires — it just stops waiting. If you need real cancellation, the wrapped operation must opt into an `AbortSignal` itself:
64
+
65
+ ```ts
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), 5_000);
68
+
69
+ try {
70
+ const res = await fetch(url, { signal: controller.signal });
71
+ // ...
72
+ } finally {
73
+ clearTimeout(timer);
74
+ }
75
+ ```
76
+
77
+ For the common "I want a deadline AND cancellation" shape, use `AbortSignal.timeout(ms)` directly — it's the standard library's answer and handles both at once.
78
+
79
+ ## Patterns
80
+
81
+ ### Bound a credential refresh
82
+
83
+ ```ts
84
+ const fresh = await withTimeout(
85
+ refreshToken(currentRefresh),
86
+ 5_000,
87
+ "refresh oauth token",
88
+ );
89
+ await writeSecretFileAtomic({ rootDir, filePath, content: JSON.stringify(fresh) });
90
+ ```
91
+
92
+ ### Compose with archive extraction
93
+
94
+ ```ts
95
+ import { extractArchive } from "@openclaw/fs-safe/archive";
96
+
97
+ await extractArchive({
98
+ archivePath,
99
+ destDir,
100
+ kind: "zip",
101
+ timeoutMs: 30_000,
102
+ });
103
+ ```
104
+
105
+ `extractArchive` already takes `timeoutMs` and uses `withTimeout` internally — you don't need to wrap it. Reach for `withTimeout` for operations that don't carry their own timeout knob.
106
+
107
+ ### Disable in tests
108
+
109
+ When unit-testing flaky code, you might want to disable the timeout. Pass `0`:
110
+
111
+ ```ts
112
+ await withTimeout(work(), process.env.NODE_ENV === "test" ? 0 : 5_000, "work");
113
+ ```
114
+
115
+ Better, gate it from the caller — `withTimeout(p, 0, ...)` returns the promise as-is.
116
+
117
+ ## See also
118
+
119
+ - [Archive extraction](archive.md) — `extractArchive` already takes `timeoutMs`.
120
+ - [File lock](sidecar-lock.md) — retry policy is a different form of bounded waiting.
121
+ - [`AbortSignal.timeout`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static) — standard-library cancellation when you need to *abort*, not just *give up*.
package/docs/types.md ADDED
@@ -0,0 +1,155 @@
1
+ # Types
2
+
3
+ The types most callers reach for. Shared data shapes are exported from `@openclaw/fs-safe/types`; method-specific option/result types live next to their subpath.
4
+
5
+ ```ts
6
+ import type {
7
+ BasePathOptions,
8
+ DirEntry,
9
+ FastPathMode,
10
+ PathStat,
11
+ SafeEncoding,
12
+ } from "@openclaw/fs-safe/types";
13
+ ```
14
+
15
+ ## `PathStat`
16
+
17
+ ```ts
18
+ type PathStat = {
19
+ kind: "file" | "directory" | "symlink" | "fifo" | "socket" | "blockDevice" | "characterDevice" | "unknown";
20
+ size: number; // bytes
21
+ mtimeMs: number; // milliseconds since epoch
22
+ mode: number; // POSIX mode bits
23
+ nlink: number; // hardlink count
24
+ };
25
+ ```
26
+
27
+ The shape returned by `Root.stat()`. A trimmed view of `node:fs.Stats` — only the fields the boundary cares about. Use `kind` instead of inspecting the various `is*` methods on a Node `Stats` object; it covers every case in one switchable string.
28
+
29
+ ## `DirEntry`
30
+
31
+ ```ts
32
+ type DirEntry = PathStat & {
33
+ name: string; // base name within the listed directory
34
+ };
35
+ ```
36
+
37
+ Returned by `Root.list(rel, { withFileTypes: true })`. Includes the same `kind`/`size`/etc as `PathStat`, plus the entry's `name`.
38
+
39
+ ## `BasePathOptions`
40
+
41
+ ```ts
42
+ type BasePathOptions = {
43
+ fastPathMode?: FastPathMode;
44
+ };
45
+
46
+ type FastPathMode = "auto" | "never" | "require";
47
+ ```
48
+
49
+ Options shared by helpers that can take a "fast path" (use cheaper syscalls when the input is already absolute and clearly inside scope). The default is `"auto"` — let the helper pick. Force `"never"` in tests if you want to exercise the slow path. Force `"require"` if you need to assert that the fast path is taken (the helper throws if it can't).
50
+
51
+ Most callers don't need to touch this.
52
+
53
+ ## `SafeEncoding`
54
+
55
+ ```ts
56
+ type SafeEncoding = BufferEncoding | null;
57
+ ```
58
+
59
+ Used by helpers that accept either an encoding (returning a string) or `null` (returning a `Buffer`). The Node `BufferEncoding` type is widened to include `null` for "give me bytes."
60
+
61
+ ## `OpenResult` / `ReadResult`
62
+
63
+ Returned by `Root.open()` and `Root.read()`:
64
+
65
+ ```ts
66
+ type OpenResult = {
67
+ handle: import("node:fs/promises").FileHandle;
68
+ realPath: string;
69
+ stat: import("node:fs").Stats;
70
+ };
71
+
72
+ type ReadResult = {
73
+ buffer: Buffer;
74
+ realPath: string;
75
+ stat: import("node:fs").Stats;
76
+ };
77
+ ```
78
+
79
+ `realPath` is the canonical real path the read or open landed on, after symlink resolution; `stat` is the verified `fstat` result.
80
+
81
+ ## `RootDefaults` / `RootOptions`
82
+
83
+ ```ts
84
+ type RootDefaults = {
85
+ hardlinks?: "reject" | "allow";
86
+ maxBytes?: number;
87
+ mkdir?: boolean;
88
+ mode?: number;
89
+ nonBlockingRead?: boolean;
90
+ symlinks?: "reject" | "follow-within-root";
91
+ };
92
+
93
+ type RootOptions = {
94
+ rootDir: string;
95
+ defaults?: RootDefaults;
96
+ };
97
+ ```
98
+
99
+ `RootDefaults` is what `root(rootDir, defaults)` accepts. See [`root()`](root.md) for the per-method options that override these.
100
+
101
+ ## `RootReadOptions` / `RootWriteOptions` / `RootCopyOptions`
102
+
103
+ ```ts
104
+ type RootReadOptions = Pick<RootDefaults, "hardlinks" | "maxBytes" | "nonBlockingRead" | "symlinks">;
105
+ type RootWriteOptions = Pick<RootDefaults, "mkdir" | "mode"> & {
106
+ encoding?: BufferEncoding;
107
+ overwrite?: boolean;
108
+ };
109
+ type RootCopyOptions = Pick<RootDefaults, "maxBytes" | "mkdir" | "mode"> & {
110
+ sourceHardlinks?: "reject" | "allow";
111
+ };
112
+ type RootOpenWritableOptions = Pick<RootDefaults, "mkdir" | "mode"> & {
113
+ writeMode?: "replace" | "append" | "update";
114
+ };
115
+ type RootWriteJsonOptions = RootWriteOptions & {
116
+ replacer?: Parameters<typeof JSON.stringify>[1];
117
+ space?: Parameters<typeof JSON.stringify>[2];
118
+ trailingNewline?: boolean;
119
+ };
120
+ type RootAppendOptions = RootWriteOptions & {
121
+ prependNewlineIfNeeded?: boolean;
122
+ };
123
+ ```
124
+
125
+ Per-method option shapes. Each picks the `RootDefaults` keys that apply, plus method-specific extras.
126
+
127
+ ## `SymlinkPolicy` / `HardlinkPolicy`
128
+
129
+ ```ts
130
+ type SymlinkPolicy = "reject" | "follow-within-root";
131
+ type HardlinkPolicy = "reject" | "allow";
132
+ ```
133
+
134
+ The two policy unions you'll see throughout. `"reject"` is conservative; `"follow-within-root"` allows symlinks whose final target is still inside the root; `"allow"` (hardlinks only) is permissive. Defaults for both symlinks and hardlinks are `"reject"`; switch hardlinks to `"allow"` only when you intentionally accept hardlink aliases.
135
+
136
+ ## `FsSafeErrorCode` / `FsSafeErrorCategory`
137
+
138
+ ```ts
139
+ type FsSafeErrorCode =
140
+ | "already-exists" | "hardlink" | "helper-failed" | "helper-unavailable"
141
+ | "insecure-permissions" | "invalid-path" | "not-empty" | "not-file"
142
+ | "not-found" | "not-owned" | "not-removable" | "outside-workspace"
143
+ | "path-alias" | "path-mismatch" | "permission-unverified"
144
+ | "symlink" | "timeout" | "too-large" | "unsupported-platform";
145
+ ```
146
+
147
+ Closed union you switch on. See the [Errors](errors.md) reference for what each one means.
148
+
149
+ `FsSafeError.category` is `"policy"` for unsafe input/target-state failures and `"operational"` for environment/runtime failures.
150
+
151
+ ## See also
152
+
153
+ - [`root()`](root.md) — how `RootDefaults` and `Root*Options` are used.
154
+ - [Errors](errors.md) — the closed code union in context.
155
+ - [Reading](reading.md), [Writing](writing.md) — option shapes per verb.
package/docs/walk.md ADDED
@@ -0,0 +1,63 @@
1
+ # Directory walking
2
+
3
+ `walkDirectory()` and `walkDirectorySync()` provide budget-bounded directory scans for callers that would otherwise hand-roll recursive `readdir()` loops. The bounds are `maxDepth` and `maxEntries`; this helper does not create a security boundary. Use [`root()`](root.md) when the path itself is caller-influenced.
4
+
5
+ ```ts
6
+ import { walkDirectory } from "@openclaw/fs-safe/walk";
7
+
8
+ const scan = await walkDirectory("/safe/workspace", {
9
+ maxDepth: 3,
10
+ maxEntries: 10_000,
11
+ symlinks: "skip",
12
+ include: (entry) => entry.kind === "file",
13
+ descend: (entry) => entry.name !== ".git",
14
+ });
15
+
16
+ if (scan.truncated) {
17
+ throw new Error("workspace scan exceeded entry budget");
18
+ }
19
+ ```
20
+
21
+ ## Result
22
+
23
+ ```ts
24
+ type WalkDirectoryResult = {
25
+ entries: WalkDirectoryEntry[];
26
+ scannedEntryCount: number;
27
+ truncated: boolean;
28
+ };
29
+
30
+ type WalkDirectoryEntry = {
31
+ name: string;
32
+ path: string;
33
+ relativePath: string;
34
+ depth: number;
35
+ kind: "file" | "directory" | "symlink" | "other";
36
+ dirent: import("node:fs").Dirent;
37
+ };
38
+ ```
39
+
40
+ `depth` starts at `1` for direct children of `rootDir`. `relativePath` is always relative to the supplied root. `scannedEntryCount` counts directory entries examined, including entries filtered out by `include`.
41
+
42
+ ## Options
43
+
44
+ ```ts
45
+ type WalkDirectoryOptions = {
46
+ maxDepth?: number;
47
+ maxEntries?: number;
48
+ symlinks?: "skip" | "follow" | "include";
49
+ include?: (entry: WalkDirectoryEntry) => boolean;
50
+ descend?: (entry: WalkDirectoryEntry) => boolean;
51
+ };
52
+ ```
53
+
54
+ `symlinks` defaults to `"skip"`. `"include"` returns symlink entries without following them. `"follow"` resolves symlinks with `stat()` and may descend into linked directories, so use it only when that is intentional. Already-visited real directories are skipped so symlink cycles do not recurse forever.
55
+
56
+ `include` controls which entries are returned. `descend` controls which directory entries are traversed. A skipped directory can still be returned if `include` accepts it.
57
+
58
+ Unreadable directories are skipped. This makes the helper suitable for best-effort inventories and pruning jobs; use a stricter root-bounded operation when every entry must be accounted for.
59
+
60
+ ## See also
61
+
62
+ - [`fileStore`](file-store.md) — managed stores use bounded walking for pruning.
63
+ - [Path scopes](path-scope.md) — boundary checks for known absolute paths.