@better-fs-tools/write 0.0.0-tegami-trusted-publish-setup → 0.2.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 (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +449 -6
  3. package/dist/authorize/ask-before-write.d.ts +11 -0
  4. package/dist/authorize/ask-before-write.js +49 -0
  5. package/dist/authorize/index.d.ts +3 -0
  6. package/dist/authorize/index.js +3 -0
  7. package/dist/authorize/protect-paths.d.ts +12 -0
  8. package/dist/authorize/protect-paths.js +74 -0
  9. package/dist/authorize/write-authorizers.d.ts +9 -0
  10. package/dist/authorize/write-authorizers.js +48 -0
  11. package/dist/bundle/create-fs-tools.d.ts +93 -0
  12. package/dist/bundle/create-fs-tools.js +130 -0
  13. package/dist/codecs/index.d.ts +1 -0
  14. package/dist/codecs/index.js +1 -0
  15. package/dist/codecs/utf8.d.ts +7 -0
  16. package/dist/codecs/utf8.js +61 -0
  17. package/dist/contract/codec.d.ts +26 -0
  18. package/dist/contract/codec.js +0 -0
  19. package/dist/contract/context.d.ts +14 -0
  20. package/dist/contract/context.js +0 -0
  21. package/dist/contract/deps.d.ts +63 -0
  22. package/dist/contract/deps.js +0 -0
  23. package/dist/contract/extensions.d.ts +103 -0
  24. package/dist/contract/extensions.js +0 -0
  25. package/dist/contract/format.d.ts +15 -0
  26. package/dist/contract/format.js +0 -0
  27. package/dist/contract/input.d.ts +35 -0
  28. package/dist/contract/input.js +0 -0
  29. package/dist/contract/limits.d.ts +26 -0
  30. package/dist/contract/limits.js +0 -0
  31. package/dist/contract/locks.d.ts +14 -0
  32. package/dist/contract/locks.js +0 -0
  33. package/dist/contract/matcher.d.ts +30 -0
  34. package/dist/contract/matcher.js +0 -0
  35. package/dist/contract/messages.d.ts +188 -0
  36. package/dist/contract/messages.js +0 -0
  37. package/dist/contract/patch.d.ts +50 -0
  38. package/dist/contract/patch.js +0 -0
  39. package/dist/contract/preconditions.d.ts +13 -0
  40. package/dist/contract/preconditions.js +5 -0
  41. package/dist/contract/result.d.ts +102 -0
  42. package/dist/contract/result.js +0 -0
  43. package/dist/core/abort.d.ts +4 -0
  44. package/dist/core/abort.js +23 -0
  45. package/dist/core/authorize.d.ts +9 -0
  46. package/dist/core/authorize.js +87 -0
  47. package/dist/core/bytes.d.ts +3 -0
  48. package/dist/core/bytes.js +14 -0
  49. package/dist/core/commit-patch.d.ts +20 -0
  50. package/dist/core/commit-patch.js +224 -0
  51. package/dist/core/commit.d.ts +8 -0
  52. package/dist/core/commit.js +77 -0
  53. package/dist/core/create-tools.d.ts +23 -0
  54. package/dist/core/create-tools.js +54 -0
  55. package/dist/core/deps.d.ts +11 -0
  56. package/dist/core/deps.js +210 -0
  57. package/dist/core/diff.d.ts +10 -0
  58. package/dist/core/diff.js +221 -0
  59. package/dist/core/encode.d.ts +3 -0
  60. package/dist/core/encode.js +26 -0
  61. package/dist/core/extension-error.d.ts +8 -0
  62. package/dist/core/extension-error.js +17 -0
  63. package/dist/core/format.d.ts +4 -0
  64. package/dist/core/format.js +22 -0
  65. package/dist/core/guards.d.ts +3 -0
  66. package/dist/core/guards.js +45 -0
  67. package/dist/core/hints.d.ts +14 -0
  68. package/dist/core/hints.js +75 -0
  69. package/dist/core/hooks.d.ts +15 -0
  70. package/dist/core/hooks.js +108 -0
  71. package/dist/core/input.d.ts +20 -0
  72. package/dist/core/input.js +91 -0
  73. package/dist/core/limits.d.ts +10 -0
  74. package/dist/core/limits.js +48 -0
  75. package/dist/core/line-index.d.ts +10 -0
  76. package/dist/core/line-index.js +38 -0
  77. package/dist/core/load.d.ts +14 -0
  78. package/dist/core/load.js +221 -0
  79. package/dist/core/lock.d.ts +2 -0
  80. package/dist/core/lock.js +56 -0
  81. package/dist/core/match.d.ts +15 -0
  82. package/dist/core/match.js +66 -0
  83. package/dist/core/messages.d.ts +8 -0
  84. package/dist/core/messages.js +140 -0
  85. package/dist/core/outcomes.d.ts +21 -0
  86. package/dist/core/outcomes.js +127 -0
  87. package/dist/core/parse-patch.d.ts +3 -0
  88. package/dist/core/parse-patch.js +64 -0
  89. package/dist/core/patch-hunks.d.ts +25 -0
  90. package/dist/core/patch-hunks.js +177 -0
  91. package/dist/core/patch-pipeline.d.ts +4 -0
  92. package/dist/core/patch-pipeline.js +284 -0
  93. package/dist/core/pipeline.d.ts +22 -0
  94. package/dist/core/pipeline.js +153 -0
  95. package/dist/core/plan-edit.d.ts +15 -0
  96. package/dist/core/plan-edit.js +215 -0
  97. package/dist/core/plan-patch.d.ts +29 -0
  98. package/dist/core/plan-patch.js +169 -0
  99. package/dist/core/plan-write.d.ts +6 -0
  100. package/dist/core/plan-write.js +27 -0
  101. package/dist/core/planned.d.ts +35 -0
  102. package/dist/core/planned.js +36 -0
  103. package/dist/core/precondition.d.ts +10 -0
  104. package/dist/core/precondition.js +65 -0
  105. package/dist/core/record.d.ts +3 -0
  106. package/dist/core/record.js +58 -0
  107. package/dist/core/resolve.d.ts +3 -0
  108. package/dist/core/resolve.js +65 -0
  109. package/dist/core/scope.d.ts +33 -0
  110. package/dist/core/scope.js +109 -0
  111. package/dist/core/snippet.d.ts +4 -0
  112. package/dist/core/snippet.js +36 -0
  113. package/dist/core/splice.d.ts +10 -0
  114. package/dist/core/splice.js +19 -0
  115. package/dist/core/target.d.ts +10 -0
  116. package/dist/core/target.js +46 -0
  117. package/dist/formatters/default.d.ts +22 -0
  118. package/dist/formatters/default.js +140 -0
  119. package/dist/formatters/index.d.ts +2 -0
  120. package/dist/formatters/index.js +1 -0
  121. package/dist/guards/generated-file.d.ts +10 -0
  122. package/dist/guards/generated-file.js +39 -0
  123. package/dist/guards/index.d.ts +19 -0
  124. package/dist/guards/index.js +33 -0
  125. package/dist/guards/non-text.d.ts +7 -0
  126. package/dist/guards/non-text.js +50 -0
  127. package/dist/guards/omission.d.ts +9 -0
  128. package/dist/guards/omission.js +48 -0
  129. package/dist/guards/read-prefix.d.ts +12 -0
  130. package/dist/guards/read-prefix.js +87 -0
  131. package/dist/guards/shared.d.ts +11 -0
  132. package/dist/guards/shared.js +46 -0
  133. package/dist/guards/syntax.d.ts +10 -0
  134. package/dist/guards/syntax.js +54 -0
  135. package/dist/guards/truncation-notice.d.ts +8 -0
  136. package/dist/guards/truncation-notice.js +32 -0
  137. package/dist/hooks/executable-shebang.d.ts +9 -0
  138. package/dist/hooks/executable-shebang.js +46 -0
  139. package/dist/hooks/index.d.ts +2 -0
  140. package/dist/hooks/index.js +2 -0
  141. package/dist/hooks/verify-write.d.ts +9 -0
  142. package/dist/hooks/verify-write.js +63 -0
  143. package/dist/index.d.ts +30 -0
  144. package/dist/index.js +15 -0
  145. package/dist/locks/index.d.ts +1 -0
  146. package/dist/locks/index.js +1 -0
  147. package/dist/locks/memory-locks.d.ts +9 -0
  148. package/dist/locks/memory-locks.js +94 -0
  149. package/dist/matchers/block-anchor.d.ts +9 -0
  150. package/dist/matchers/block-anchor.js +69 -0
  151. package/dist/matchers/escape.d.ts +6 -0
  152. package/dist/matchers/escape.js +32 -0
  153. package/dist/matchers/exact.d.ts +4 -0
  154. package/dist/matchers/exact.js +29 -0
  155. package/dist/matchers/fold.d.ts +11 -0
  156. package/dist/matchers/fold.js +144 -0
  157. package/dist/matchers/indentation.d.ts +3 -0
  158. package/dist/matchers/indentation.js +81 -0
  159. package/dist/matchers/index.d.ts +14 -0
  160. package/dist/matchers/index.js +20 -0
  161. package/dist/matchers/line-trimmed.d.ts +3 -0
  162. package/dist/matchers/line-trimmed.js +32 -0
  163. package/dist/matchers/lines.d.ts +24 -0
  164. package/dist/matchers/lines.js +74 -0
  165. package/dist/matchers/normalized.d.ts +7 -0
  166. package/dist/matchers/normalized.js +69 -0
  167. package/dist/patch/grammar.d.ts +5 -0
  168. package/dist/patch/grammar.js +24 -0
  169. package/dist/patch/index.d.ts +4 -0
  170. package/dist/patch/index.js +3 -0
  171. package/dist/patch/parse.d.ts +11 -0
  172. package/dist/patch/parse.js +209 -0
  173. package/dist/signature/contract.d.ts +8 -0
  174. package/dist/signature/contract.js +0 -0
  175. package/dist/signature/edit.d.ts +19 -0
  176. package/dist/signature/edit.js +158 -0
  177. package/dist/signature/index.d.ts +6 -0
  178. package/dist/signature/index.js +4 -0
  179. package/dist/signature/matching.d.ts +3 -0
  180. package/dist/signature/matching.js +25 -0
  181. package/dist/signature/messages.d.ts +4 -0
  182. package/dist/signature/messages.js +9 -0
  183. package/dist/signature/patch.d.ts +6 -0
  184. package/dist/signature/patch.js +55 -0
  185. package/dist/signature/schema.d.ts +19 -0
  186. package/dist/signature/schema.js +117 -0
  187. package/dist/signature/write.d.ts +9 -0
  188. package/dist/signature/write.js +52 -0
  189. package/dist/state/index.d.ts +2 -0
  190. package/dist/state/index.js +1 -0
  191. package/dist/state/invalidate.d.ts +29 -0
  192. package/dist/state/invalidate.js +37 -0
  193. package/docs/architecture.md +223 -0
  194. package/docs/hosts.md +96 -0
  195. package/docs/result-schema.md +261 -0
  196. package/package.json +53 -2
@@ -0,0 +1,9 @@
1
+ import type { SignatureDocs } from "@better-fs-tools/read";
2
+ import type { WriteSignature } from "./contract.ts";
3
+ /** write({ path, content }). */
4
+ export declare function defaultWriteSignature(options?: SignatureDocs<"path" | "content">): WriteSignature;
5
+ /**
6
+ * write_file({ file_path, content }). Claude Code. The same as
7
+ * defaultWriteSignature with another tool name and path name.
8
+ */
9
+ export declare function snakeCaseWriteSignature(options?: SignatureDocs<"file_path" | "content">): WriteSignature;
@@ -0,0 +1,52 @@
1
+ import { checkDocs, deepFreeze, objectSchema, pathSchema, readObject, readPath, readString, stringSchema, } from "./schema.js";
2
+ /** write({ path, content }). */
3
+ export function defaultWriteSignature(options = {}) {
4
+ return writeSignature(options, "defaultWriteSignature", "write", "path");
5
+ }
6
+ /**
7
+ * write_file({ file_path, content }). Claude Code. The same as
8
+ * defaultWriteSignature with another tool name and path name.
9
+ */
10
+ export function snakeCaseWriteSignature(options = {}) {
11
+ return writeSignature(options, "snakeCaseWriteSignature", "write_file", "file_path");
12
+ }
13
+ function writeSignature(options, label, name, presetPathName) {
14
+ const checked = checkDocs(options, label, [presetPathName, "content"]);
15
+ const { describe } = checked;
16
+ const pathName = checked.names[presetPathName] ?? presetPathName;
17
+ const contentName = checked.names.content ?? "content";
18
+ const keys = [pathName, contentName];
19
+ const schema = deepFreeze(objectSchema([
20
+ [
21
+ pathName,
22
+ pathSchema(describe[presetPathName] ??
23
+ "Path of the file to create or replace, relative to the working directory or absolute within an allowed root."),
24
+ ],
25
+ [
26
+ contentName,
27
+ stringSchema(describe.content ??
28
+ "The complete new content of the file. Nothing of the old content is kept."),
29
+ ],
30
+ ], keys));
31
+ const params = {
32
+ path: pathName,
33
+ content: contentName,
34
+ };
35
+ return Object.freeze({
36
+ name: options.name ?? name,
37
+ description: options.description ??
38
+ "Create a text file, or replace all of its content. Missing parent directories are " +
39
+ "created. To replace a file that exists, read all of it with the read tool first. " +
40
+ "To change part of a file, use the edit tool: it sends less text and keeps the rest " +
41
+ "of the file as it is.",
42
+ schema,
43
+ toInput(input) {
44
+ const record = readObject(input, "write input", keys, keys);
45
+ return {
46
+ path: readPath(record[pathName], pathName),
47
+ content: readString(record[contentName], contentName),
48
+ };
49
+ },
50
+ param: (canonical) => params[canonical] ?? canonical,
51
+ });
52
+ }
@@ -0,0 +1,2 @@
1
+ export { createInvalidator } from "./invalidate.ts";
2
+ export type { Invalidate, InvalidateOutcome } from "./invalidate.ts";
@@ -0,0 +1 @@
1
+ export { createInvalidator } from "./invalidate.js";
@@ -0,0 +1,29 @@
1
+ import type { FileSystemError, WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { ReadStateStore } from "@better-fs-tools/read";
3
+ /**
4
+ * What `invalidate(path)` did. `recorded` says whether a read record existed.
5
+ * On failure the record, if any, stays.
6
+ */
7
+ export type InvalidateOutcome = {
8
+ readonly ok: true;
9
+ readonly resolvedPath: string;
10
+ readonly recorded: boolean;
11
+ } | {
12
+ readonly ok: false;
13
+ readonly phase: "stat";
14
+ readonly error: FileSystemError;
15
+ } | {
16
+ readonly ok: false;
17
+ readonly phase: "state";
18
+ readonly detail: string;
19
+ };
20
+ export type Invalidate = (path: string) => Promise<InvalidateOutcome>;
21
+ /**
22
+ * Deletes the read record for a path, so the next edit or write needs a fresh
23
+ * read. Use it after a shell tool may have written the file. Never throws:
24
+ * every failure is returned as an outcome.
25
+ */
26
+ export declare function createInvalidator(deps: {
27
+ readonly fs: WritableFileSystem;
28
+ readonly state: ReadStateStore;
29
+ }): Invalidate;
@@ -0,0 +1,37 @@
1
+ import { isStateStore, isWritable } from "../core/deps.js";
2
+ import { messageOf } from "../core/outcomes.js";
3
+ /**
4
+ * Deletes the read record for a path, so the next edit or write needs a fresh
5
+ * read. Use it after a shell tool may have written the file. Never throws:
6
+ * every failure is returned as an outcome.
7
+ */
8
+ export function createInvalidator(deps) {
9
+ if (deps === null || typeof deps !== "object") {
10
+ throw new TypeError("createInvalidator takes { fs, state }");
11
+ }
12
+ const { fs, state } = deps;
13
+ if (!isWritable(fs))
14
+ throw new TypeError("fs must be a WritableFileSystem");
15
+ if (!isStateStore(state))
16
+ throw new TypeError("state must be a read state store");
17
+ return async (path) => {
18
+ let resolvedPath;
19
+ try {
20
+ const outcome = await fs.stat(path, {});
21
+ if (!outcome.ok)
22
+ return { ok: false, phase: "stat", error: outcome.error };
23
+ resolvedPath = outcome.stat.resolvedPath;
24
+ }
25
+ catch (error) {
26
+ return { ok: false, phase: "stat", error: { reason: "io", detail: messageOf(error) } };
27
+ }
28
+ try {
29
+ const recorded = (await state.get(resolvedPath)) !== null;
30
+ await state.delete(resolvedPath);
31
+ return { ok: true, resolvedPath, recorded };
32
+ }
33
+ catch (error) {
34
+ return { ok: false, phase: "state", detail: messageOf(error) };
35
+ }
36
+ };
37
+ }
@@ -0,0 +1,223 @@
1
+ # Architecture
2
+
3
+ This page explains how `@better-fs-tools/write` runs one `edit`, `write`, or `apply_patch` call, and why it is built this way. [result-schema.md](result-schema.md) describes the result. The [README](../README.md) shows how to configure each step.
4
+
5
+ ## The pipeline
6
+
7
+ The three tools share one core. They differ only in their input and their plan stage.
8
+
9
+ ```text
10
+ tool(input, ctx?)
11
+ │ parse*Input .............. strict canonical validation phase input
12
+ │ fs(call) ................. once; a WritableFileSystem or a factory phase resolve
13
+ ▼
14
+ request
15
+ │ resolve .................. every path, in input order phase resolve
16
+ │ fs.stat .................. roots, type check, resolvedPath phase stat
17
+ │ authorize (access) ....... change: null, before any content byte phase authorize
18
+ │ lock ..................... sorted resolvedPaths phase lock
19
+ │ fs.stat again ............ the stat that counts phase stat
20
+ │ load ..................... open, capped bytes, classify, codec, phase load
21
+ │ round trip, verify, contentId
22
+ │ precondition ............. the read-before-write table phase precondition
23
+ │ plan ..................... write content, matchers, or hunks phase plan
24
+ │ guards ................... every planned change phase guards
25
+ │ authorize (change) ....... with the diff; content for edit/write phase authorize
26
+ │ encode ................... codec.encode, size check phase encode
27
+ │ commit ................... fs.write, or stage + publish + remove phase commit
28
+ │ hooks .................... once for each changed file phase hooks
29
+ │ record ................... ReadRecord schema 2, origin "write" phase record
30
+ ▼
31
+ formatter.format(report, { mode: "model", call, ... }) ─▶ content
32
+ ▼
33
+ MutationResult
34
+ ```
35
+
36
+ | Stage | Dependency | What happens |
37
+ | ------------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
38
+ | Input | `limits` | `parseEditInput`, `parseWriteInput`, or `parseApplyPatchInput`. Unknown keys and blank paths are refused. `apply_patch` also parses the patch here |
39
+ | Filesystem | `fs` | A `WritableFileSystem`, or a factory of the call context. The factory runs once for each call |
40
+ | Resolve | `resolve` | The read tool's resolvers. Each path gets its own listing budget of one |
41
+ | Stat | `fs` | `fs.stat` on each resolved path. It gives the real path, the type, the version, and the missing parents. No content byte is read |
42
+ | Access | `authorize` | Each target with `change: null`. A denial ends the call before any content byte is read |
43
+ | Lock | `locks` | All real paths of the call, sorted, taken at once. A timeout gives `LOCK_TIMEOUT` |
44
+ | Stat again | `fs` | Under the lock. This stat decides. A real path that moved gives `STALE` |
45
+ | Load | `classifiers`, `codecs`, `digest` | Opens each file the call changes, reads at most `maxFileBytes`, refuses non-text, decodes, checks that encode gives the same bytes back, and hashes |
46
+ | Precondition | `state`, `preconditions` | Compares the load with the read record |
47
+ | Plan | `matchers`, `patchParser` | Builds the new text of each file, the diff, and the fragments |
48
+ | Guards | `guards` | Each guard sees each planned change. The first refusal ends the call |
49
+ | Change | `authorize` | Each planned change, with the whole plan. `edit` and `write` may get new content back |
50
+ | Encode | `codecs`, `limits` | Encodes in the loaded style: BOM, CRLF, and encoding stay. `maxWriteBytes` applies |
51
+ | Commit | `fs` | One `fs.write`, or the staged `apply_patch` commit |
52
+ | Hooks | `hooks` | Each hook sees each committed file. A failure is a warning note |
53
+ | Record | `state`, `digest`, `clock` | Stores a record for each committed file. A store failure does not fail the call |
54
+ | Format | `formatter`, `messages` | Turns the report into content parts |
55
+
56
+ Some stages cannot be removed by any dependency: input validation, the type check, the order of the access authorize before any content read, the lock, the load cap, the codec round trip, the precondition check when a store is set, the literal splice, the check of every change before the first commit, and the record after a commit. They are the reason the package exists. Everything else is a dependency.
57
+
58
+ ## Source layout
59
+
60
+ | Path | Role |
61
+ | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
62
+ | `src/contract/` | The public types, one file for each area. No runtime code |
63
+ | `src/core/create-tools.ts`, `core/deps.ts` | The three factories. They check and resolve the dependencies once, synchronously |
64
+ | `src/core/pipeline.ts` | The stage order for `edit` and `write`. `apply_patch` has its own order in `core/patch-pipeline.ts` |
65
+ | `src/core/scope.ts` | Per-call state: the call object, the phase, `fs(call)`, `state(call)`, notes, abort checks, and failures |
66
+ | `src/core/resolve.ts`, `target.ts`, `lock.ts`, `load.ts`, `precondition.ts` | Resolve, stat, lock, load, and the precondition table |
67
+ | `src/core/plan-write.ts`, `plan-edit.ts`, `plan-patch.ts`, `match.ts`, `hints.ts`, `splice.ts` | The three plan stages, the matcher chain, failure help, and the literal splice |
68
+ | `src/core/guards.ts`, `authorize.ts`, `encode.ts`, `commit.ts`, `commit-patch.ts` | Guards, both authorize stages, encode, the single-file commit, and the staged patch commit with rollback |
69
+ | `src/core/hooks.ts`, `record.ts`, `diff.ts`, `snippet.ts`, `outcomes.ts`, `format.ts` | Hooks, records, the unified diff, snippets, failures and the error map, and the formatter call |
70
+ | `src/matchers/`, `guards/`, `authorize/`, `codecs/`, `locks/`, `hooks/`, `formatters/`, `state/` | The built-in helpers, one file for each |
71
+ | `src/bundle/create-fs-tools.ts` | `createFsTools`: the four file tools, and bash when asked, over one store, digest, lock manager, and clock |
72
+ | `src/patch/`, `src/signature/` | The `./patch` and `./signature` subpaths |
73
+
74
+ ## One call, one context
75
+
76
+ A host passes `{ signal?, callId?, host }`, the read tool's `ToolCallContext`. The core passes this object by reference to every stage and every host function, as `ctx.call`. It never reads, copies, freezes, or stores `host`. `host` never appears in the result, a record, a note, or content.
77
+
78
+ A throw or a malformed return from host code gives `EXTENSION_FAILED` with `data: { extension, phase, id? }`. After the commit, hooks are the exception: the file is already written, so a hook failure adds no note and the status stays `ok`. A formatter failure is the other exception: when a formatter throws or returns neither a string nor an array, the default formatter formats the report and no note is added. The status, `changes`, and `commit` stay, so a committed change is never lost.
79
+
80
+ The signal is checked before each stage and raced against each host function and backend call. From the first commit call to the end of the call, the signal is ignored. A started commit finishes or rolls back, and the record is stored. A half-published patch would be worse than a late abort. Hooks after the commit are not raced against the signal either, so a hook that never settles holds the call open.
81
+
82
+ ## Two authorize stages
83
+
84
+ Read authorizes an open file before it reads a byte. The write tools keep that order. The access stage runs after `stat`, with `change: null`, so a path policy such as `denyPaths()` or `protectPaths()` refuses before a `NO_MATCH` hint could show any file text. The change stage runs after the guards, with the planned change and the whole plan, so a host can show the user every diff and ask once. `askBeforeWrite()` does that.
85
+
86
+ An allow decision in the change stage may carry `content` for `edit` and `write`. The core then diffs again, snippets again, and runs the guards again. There is no second authorize. `apply_patch` refuses `content` as `EXTENSION_FAILED`: one user text cannot stand for several files.
87
+
88
+ ## The lock and the second stat
89
+
90
+ The lock key is the real path, and only `stat` knows it. So the core stats, authorizes access, locks every real path of the call in sorted order, and stats again. The second stat decides: a file that appeared or vanished between the two stats is judged by it, and a real path that changed gives `STALE`.
91
+
92
+ `memoryLocks()` orders writers inside one process. The read tool takes no lock: it detects a change with `verify()`, and each write replaces the file in one step on a backend that can. `createFsTools()`, and the bundles that wrap it (`createNodeFsTools()`, `createPiFsTools()`, and `createAiSdkFsTools()`), share one lock manager across the three write tools.
93
+
94
+ ## Load
95
+
96
+ Each existing file that the call changes is opened once:
97
+
98
+ - `info.version` must equal the version from the second stat, else `STALE`.
99
+ - A file over `maxFileBytes` gives `TOO_LARGE` before any byte is read. Reading stops one byte past the cap.
100
+ - The first `sampleBytes` go to the read tool's classifiers. Anything but text gives `NOT_TEXT`.
101
+ - The first codec that accepts the sample decodes. `encode(decode(bytes))` must give the same bytes back, else `NOT_TEXT` with `ROUND_TRIP`. This check is what keeps every untouched byte the same.
102
+ - `verify()` must report no change.
103
+ - `contentId` is the digest of the loaded bytes, the same hash the read tool stores.
104
+
105
+ `utf8Codec()` keeps a BOM. When every LF in the file follows a CR, it works on LF text and encodes CRLF again. Any other mix of line endings is kept as it is.
106
+
107
+ ## Read before write
108
+
109
+ The precondition stage reads the record at the real path. A record of another schema, or with another digest id, counts as absent. A record is fresh when the backend has stable identity and its version equals the loaded version, or when its content hash equals the loaded content hash. So a backend with weak versions still catches a change through the hash.
110
+
111
+ | Case | `edit` | `write` | `apply_patch` Update, Delete |
112
+ | ----------------------------------- | --------------------------------------- | ---------- | --------------------------------------------------------------- |
113
+ | Target missing | `NOT_FOUND` | Create | Add and Move destination: create |
114
+ | `requireRead: "off"`, or no store | Go on. No store adds a note | Go on | Go on |
115
+ | No record | `NOT_READ` | `NOT_READ` | `NOT_READ` |
116
+ | Partial record, partial not allowed | `NOT_READ` (`wholeFile: true`) | same | same |
117
+ | Fresh | Go on | Go on | Go on |
118
+ | Not fresh, `onStale: "reject"` | `STALE` | `STALE` | `STALE` |
119
+ | Not fresh, `onStale: "rematch"` | Exact rematch of every pair, or `STALE` | `STALE` | Exact rematch of every hunk, or `STALE`. A Delete gives `STALE` |
120
+
121
+ `onStale` defaults to `"reject"`. `"rematch"` is opt-in.
122
+
123
+ The commit carries a precondition: `absent` for a create, and the loaded `version` for a replace or a remove. A backend that reports `compareAndSwap: true` checks it next to the publish. For a backend that does not, the core stats the target again just before the write and gives `STALE` or `EXISTS` itself. The window between that stat and the write stays.
124
+
125
+ ## Matching
126
+
127
+ `edit` runs the matcher chain for each pair against one snapshot of the file. The first matcher that finds a hit decides for that pair. One hit is the match. Several hits without `replaceAll` give `AMBIGUOUS_MATCH`. Several hits from a loose matcher with `replaceAll` give `MATCH_REFUSED`.
128
+
129
+ The core owns the rules on every hit:
130
+
131
+ - The splice is literal: `text.slice(0, start) + newText + text.slice(end)`. `String.prototype.replace` is never called, so `$&` and `$1` stay as written.
132
+ - A loose hit much longer than the old text (`span`), a hit that starts or ends inside a folded span (`boundary`), and a loose hit whose new text adds escape sequences the matched text does not have (`escape`) give `MATCH_REFUSED`.
133
+ - Ranges of different pairs must not overlap. Splices apply from the end.
134
+ - A result equal to the original gives `NO_CHANGE`, unless every pair is already applied.
135
+
136
+ A miss is `NO_MATCH`, with a trailing-newline hint when that is the only difference. With `recovery: true`, a miss gets more help: an `already-applied` note when the new text is in the file and the old text is not, the closest region with line numbers, and after three misses in a row on one file a `repeated-miss` note. The miss count lives in the tool instance, not in the store.
137
+
138
+ ## apply_patch
139
+
140
+ The order is parse, resolve, stat, access, lock, stat again, load, preconditions, verify every hunk, plan, guards, change authorize, encode, commit, hooks, record.
141
+
142
+ Verification collects every problem before anything changes: an Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, a missing `remove()` for a Delete or Move, and each hunk that does not match. Each hunk matches at the first place after the previous hunk (Codex). The chain runs on whole lines. A ` ` context line takes the file's own line, so its bytes stay the same.
143
+
144
+ The commit keeps a journal:
145
+
146
+ ```text
147
+ stage: when fs.stage exists, stage every create and update in patch order
148
+ a stage failure discards every staged write; no file changed
149
+ publish: in patch order, record each step
150
+ create, update: staged.publish(), or fs.write without stage()
151
+ move: publish the destination, then fs.remove(source, version)
152
+ delete: fs.remove(path, version)
153
+ rollback: on the first failed step, discard what was not published, then undo
154
+ the journal from the end
155
+ update: fs.write(original bytes, version after)
156
+ create: fs.remove(path, version after)
157
+ removed: fs.write(original bytes and mode, absent, createParents)
158
+ ```
159
+
160
+ When every undo step works, the result has the code of the failed step and `commit.rolledBack: true`. When an undo step fails, the code is `PARTIAL_COMMIT` and `commit.files` gives the state of each file. The journal lives in process memory. A crash during the commit leaves some files changed and no report. Undoing a create removes the file, not the parent folders it made. A stage failure does remove them, through `discard()`.
161
+
162
+ ## Guards and hooks
163
+
164
+ Guards run in order on each planned change, before the change-stage authorize. The first refusal gives `GUARD_REFUSED` with the guard's note, or the `guardRefused` catalog message when the guard gave none. Allow notes are kept. Every built-in guard lets its near miss through, so a guard does not refuse text that is already in the file.
165
+
166
+ Hooks run after the whole commit, once for each committed file, in order. `newFileMode()` is asked just before a create's commit. The first hook that returns a number sets the mode of the new file. A replace always keeps the file's mode, when the backend can. `afterWrite()` sees the `FileChange` and the call's filesystem. A hook that rewrote the file returns `rewrote: true`. The core then reads the file again, updates `changes[].after`, and adds a `hook-rewrote` note.
167
+
168
+ ## Records
169
+
170
+ After a commit, each committed file gets a record with `schema: 2`, `origin: "write"`, the new version, and the content hash of the written bytes. `request` is `null`, and `viewId` equals `contentId`. `wholeFileVisible` is true after a `write` and a patch Add. After an `edit` or a patch Update it keeps the previous record's value. It is false when an authorizer replaced the content, a hook rewrote the file, or an edit went ahead on a stale record: the model has not seen those bytes, so a later `write` needs a read. A move stores the destination and deletes the source key. A Delete deletes the key. `no-change` stores nothing.
171
+
172
+ `memoryStore()` keeps 1 000 records for 30 minutes. A read older than that needs a new read before an edit.
173
+
174
+ ## Errors
175
+
176
+ Every error result has exactly one warning note whose `code` is the error code in kebab case, plus the notes gathered before the failure. A host refusal keeps the host's message and data. Its own code moves to `data.source`. Backend reasons map to codes:
177
+
178
+ | Backend reason | Code |
179
+ | ----------------------- | ----------------------- |
180
+ | `not-found` | `NOT_FOUND` |
181
+ | `not-a-file` | `NOT_A_FILE` |
182
+ | `dangerous-path` | `DANGEROUS_PATH` |
183
+ | `outside-allowed-roots` | `OUTSIDE_ALLOWED_ROOTS` |
184
+ | `permission-denied` | `PERMISSION_DENIED` |
185
+ | `denied` | `DENIED` |
186
+ | `unsupported` | `UNSUPPORTED_BACKEND` |
187
+ | `aborted` | `ABORTED` |
188
+ | `io` | `IO_ERROR` |
189
+ | `changed` | `STALE` |
190
+ | `exists` | `EXISTS` |
191
+ | `read-only` | `READ_ONLY` |
192
+ | `no-space` | `NO_SPACE` |
193
+ | `too-large` | `TOO_LARGE` |
194
+
195
+ A backend method that throws gives `IO_ERROR`.
196
+
197
+ ## Writing a WritableFileSystem
198
+
199
+ A backend keeps the policy. The core never checks roots or symlinks itself. A writable adapter:
200
+
201
+ - applies the same roots, deny roots, and symlink rules in `stat`, `write`, `stage`, and `remove` as in `open`, and never throws for an expected failure;
202
+ - refuses directories, FIFOs, sockets, and devices as `not-a-file` before it touches their content;
203
+ - never replaces a symbolic link: it follows a link inside the roots to its real path, or refuses it;
204
+ - reports a `version` that changes with every change of the bytes, and the same token from `stat()` and from `open().info.version`;
205
+ - enforces `absent`, `version`, and `any`, and gives `exists` or `changed`;
206
+ - reports `writeCapabilities.compareAndSwap` honestly. When it is false, the core checks the precondition itself just before the write.
207
+
208
+ `runWritableFileSystemConformance(fs, { scratchDirectory })` from `@better-fs-tools/fs` checks these rules. The three virtual adapters show three ways to meet them with weaker backends:
209
+
210
+ | Adapter | Backend calls | How it meets the contract |
211
+ | -------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
212
+ | `cloudflareShellFileSystem()` | `writeFileBytes`, `mkdir`, `rm` | Walks the path with `lstat` first, because `writeFileBytes` creates parents and follows a leaf link. Passes the old mime type back. No modes |
213
+ | `cloudflareComputerFileSystem()` | `writeFile`, `mkdir`, `rm` | One transaction, so a replace is atomic. `exclusive: true` for a create. Passes the old mode back, because `writeFile` resets it |
214
+ | `justBashFileSystem()` | `writeFile`, `mkdir`, `rm`, `chmod`, `utimes` | `chmod` after a replace, because `InMemoryFs` resets the mode. Moves `mtime` on by 1 ms when a write left it the same, so the version changes |
215
+
216
+ None of them has `stage()`, so `apply_patch` writes each file in turn and undoes the journal on a failure.
217
+
218
+ ## Deliberate omissions
219
+
220
+ - No hashline edits, no LLM correction calls, no notebook or AST edits.
221
+ - No undo or checkpoints, no formatter or LSP runs in the core, no delete tool.
222
+ - POSIX paths only.
223
+ - No `rename` in the contract. A move is a write of the destination and a remove of the source.
package/docs/hosts.md ADDED
@@ -0,0 +1,96 @@
1
+ # Hosts and backends
2
+
3
+ This page helps you choose a host package and a filesystem backend. It lists what each one sets by default, and what each backend can do. The READMEs of the host and backend packages link here.
4
+
5
+ ## Choose a bundle
6
+
7
+ Every bundle builds `read`, `edit`, and `write` over one backend, and `apply_patch` when the host asks for it. The tools share one digest, one lock manager, and one clock. With `state`, they also share one read store, so `edit` and `write` know what the model has read. `createFsTools()` is the portable core. The other three wrap it.
8
+
9
+ | Bundle | Package | Use it when |
10
+ | ---------------------- | ------------------------- | ------------------------------------------------------------------------------------------- |
11
+ | `createFsTools()` | `@better-fs-tools/write` | You write your own host glue, or you run in a Worker with a Cloudflare or just-bash backend |
12
+ | `createNodeFsTools()` | `@better-fs-tools/node` | You run on Node or Bun and want the local filesystem |
13
+ | `createPiFsTools()` | `@better-fs-tools/pi` | You write a Pi coding agent extension |
14
+ | `createAiSdkFsTools()` | `@better-fs-tools/ai-sdk` | You pass the tools to AI SDK 7 `generateText` or `streamText`, with any backend |
15
+
16
+ The just-bash, Cloudflare Shell, and Cloudflare Computer packages are backends, not bundles. Pass their filesystem as `fs` to `createFsTools()` or `createAiSdkFsTools()`.
17
+
18
+ ## Bundle defaults
19
+
20
+ | Setting | `createFsTools()` | `createNodeFsTools()` | `createPiFsTools()` | `createAiSdkFsTools()` |
21
+ | --------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
22
+ | `fs` | required: a backend, or a factory of the call | `nodeFileSystem({ cwd, allowedRoots: [cwd] })`, `cwd` default `process.cwd()` | a `nodeFileSystem` rooted at `ctx.cwd` on each call. `fs`, `cwd`, and `allowedRoots` throw | required, as in `createFsTools()` |
23
+ | Tool input | canonical | canonical | the Pi signatures below | the AI SDK signatures below, `strict: true` |
24
+ | `state` | `null`: no read-before-write. `memoryStore({ clock })` turns it on | `null`, as `createFsTools()` | `null`, as `createFsTools()` | `null`, as `createFsTools()` |
25
+ | `applyPatch` | off. `true` or an options object adds `apply_patch` | off, as `createFsTools()` | off, as `createFsTools()`. The `pi.extensions` entry does not register it | off, as `createFsTools()`. When off, `tools` has no `apply_patch` key |
26
+ | `digest` | `sha256Digest()`, plain JavaScript | `nodeDigest()` | `nodeDigest()` | `sha256Digest()` |
27
+ | `locks` | `memoryLocks()` | `memoryLocks()` | `memoryLocks()` | `memoryLocks()` |
28
+ | `clock` | `() => new Date()` | `() => new Date()` | `() => new Date()` | `() => new Date()` |
29
+ | `bash` | off. An options object with `runner` and `env` adds it. `true` throws | off. `true` or an options object adds it | none. Register `createPiBashTool()` on its own | off. An options object with `runner` and `env` adds it. `true` throws |
30
+ | bash `runner` | required | `nodeCommandRunner({ cwd })` | `createPiBashTool()`: a Node runner at `ctx.cwd` | required |
31
+ | bash `env` | required | `shellEnv(() => process.env)` | `createPiBashTool()`: `shellEnv(() => process.env)` | required |
32
+ | New file and directory modes | the backend's | `0o666` and `0o777` less the process umask. `newFileMode` and `newDirectoryMode` set them exactly | as Node | the backend's |
33
+ | `symlinks`, `identity`, buffering | the backend's | `"follow-within-roots"`, `"required"`, streams | as Node | the backend's |
34
+ | `invalidate` | `(path, call?)` | `(path, call?)`, `call` ignored | `(path, call?)`, pass the call | `(path, call?)` |
35
+
36
+ In every bundle, a shared key (`fs`, `state`, `digest`, `locks`, `clock`) inside one tool's options throws `TypeError`, and so does an unknown option key. A bundle takes `state` as one store or `null`. The single tools also take a per-call store factory; a bundle does not, and throws a `TypeError` that names the bundle. The bash tool gets the bundle's digest and clock, so `ctx.digest` and `ctx.clock` in a bash hook match the file tools. The allowed roots never limit what a bash command touches.
37
+
38
+ ### Tool signatures
39
+
40
+ A signature is the model-facing shape of a tool. The core and Node tools take the canonical input and have no signature. Pi and the AI SDK each default to the shape their models know.
41
+
42
+ | Tool | Canonical input (core, Node) | Pi default | AI SDK default |
43
+ | ------------- | ------------------------------------------------------ | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
44
+ | `read` | `{ path, offset?, limit? }` | `defaultReadSignature({ name: "read" })`: `read({ path, offset?, limit? })` | `defaultReadSignature()`: `read({ path, offset?, limit? })` |
45
+ | `edit` | `{ path, edits: [{ oldText, newText, replaceAll? }] }` | `multiEditSignature()`: `edit({ path, edits: [{ oldText, newText }] })` | `defaultEditSignature()`: `edit({ path, old_string, new_string, replace_all? })` |
46
+ | `write` | `{ path, content }` | `defaultWriteSignature()`: `write({ path, content })` | `defaultWriteSignature()`: `write({ path, content })` |
47
+ | `apply_patch` | `{ patch }` | `freeformPatchSignature()`: `apply_patch({ patch })` plus the Codex grammar | `defaultPatchSignature()`: `apply_patch({ patch })` as JSON |
48
+ | `bash` | `{ command, timeoutMs?, cwd? }` | `createPiBashTool()`: `bash({ command, timeout? })`, seconds, no `cwd` | `defaultBashSignature({ runner, limits })`: `bash({ command, timeout?, cwd? })`, milliseconds |
49
+
50
+ Every preset takes `name`, `description`, `describe`, and `names`. `names` renames a parameter, keyed by the preset's own parameter names.
51
+
52
+ ### Single-tool factories
53
+
54
+ Each tool also has its own factory. A single factory shares nothing with another one: each write tool makes its own lock manager, and there is no read store unless you pass one. Use a bundle when a host installs more than one tool.
55
+
56
+ | Factory | `state` | `digest` | bash `env` |
57
+ | ------------------------------------------------------------------------------------- | ------- | ------------------------------------------- | ----------------------------- |
58
+ | `createReadTool()`, `createEditTool()`, `createWriteTool()`, `createApplyPatchTool()` | none | none. A `state` without a `digest` throws | none |
59
+ | `createBashTool()` | none | none | required |
60
+ | `createNodeReadTool()` and the Node write tools | none | `nodeDigest()`. `digest: null` turns it off | none |
61
+ | `createNodeBashTool()` | none | none | `shellEnv(() => process.env)` |
62
+ | `createPiReadTool()` and the Pi write tools | none | `nodeDigest()` | none |
63
+ | `createPiBashTool()` | none | none | `shellEnv(() => process.env)` |
64
+ | `createAiSdkReadTool()` and the AI SDK write tools | none | none. A `state` without a `digest` throws | none |
65
+ | `createAiSdkBashTool()` | none | none | required |
66
+
67
+ ## Backends
68
+
69
+ Every backend takes the shared `FileSystemRootOptions` from `@better-fs-tools/fs`. Its README has the option table and the write capability table.
70
+
71
+ | Backend | Package | Reads | Bytes fetched before `authorize` | `maxBufferedBytes` | `symlinks` | `identity` |
72
+ | -------------------------------- | -------------------------------------- | -------------------------- | ---------------------------------------------- | ------------------ | ------------------------------------- | -------------------------- |
73
+ | `nodeFileSystem()` | `@better-fs-tools/node` | stream | none | none | both, default `"follow-within-roots"` | `"required"` only |
74
+ | `memoryFileSystem()` | `@better-fs-tools/fs` | from memory | none: the bytes are already in memory | 16 MiB | links do not exist | both, default `"required"` |
75
+ | `justBashFileSystem()` | `@better-fs-tools/just-bash` | buffered in `open()` | the whole file | 16 MiB | both, default `"reject"` | both, default `"none"` |
76
+ | `cloudflareShellFileSystem()` | `@better-fs-tools/cloudflare-shell` | buffered in `open()` | the whole file | 16 MiB | `"reject"` only | `"none"` only |
77
+ | `cloudflareComputerFileSystem()` | `@better-fs-tools/cloudflare-computer` | stream, opened in `open()` | the read request is sent, but no chunk is read | none | `"reject"` only | `"none"` only |
78
+
79
+ | Backend | Several `allowedRoots` | `denyRoots` | `cwd` default | Write methods | `stage()` | `remove()` | New file mode |
80
+ | -------------------------------- | --------------------------------- | ------------------------------------- | ---------------------- | ------------------------------------- | --------- | ---------- | ------------------------ |
81
+ | `nodeFileSystem()` | yes | yes, added to `/dev`, `/proc`, `/sys` | `process.cwd()` | always | yes | yes | `0o666` less the umask |
82
+ | `memoryFileSystem()` | no, every absolute path is inside | yes | none | always. `readOnly: true` refuses them | yes | yes | `0o644` |
83
+ | `justBashFileSystem()` | yes | yes | `/` | checked at use | no | yes | `0o644` |
84
+ | `cloudflareShellFileSystem()` | yes | yes | the first allowed root | checked at use | no | yes | none: Shell has no modes |
85
+ | `cloudflareComputerFileSystem()` | yes | yes | the first allowed root | checked at use | no | yes | `0o644` |
86
+
87
+ - "Checked at use": the adapter builds over a backend object without its write methods. Reads work, and a write gives `unsupported`, which the write tools report as `UNSUPPORTED_BACKEND`.
88
+ - A deny root gives `dangerous-path` in every backend.
89
+ - A file over `maxBufferedBytes` gives `too-large`, which the tools report as `TOO_LARGE`.
90
+ - `readOnlyFileSystem(fs)` from `@better-fs-tools/fs` works over every backend. It keeps `open`, `list`, and the value members except `writeCapabilities`, such as `id`, `capabilities`, `paths`, and the root settings, so a read tool works and a write tool refuses it when it is built.
91
+
92
+ ### Buffered reads and authorization
93
+
94
+ The read tool calls `authorize` after `fs.open()` and before it reads any content byte. A buffered backend (just-bash and Cloudflare Shell) has already fetched the whole file inside `open()`, so those bytes have left the backend before `authorize` runs. Cloudflare Computer opens the read stream in `open()`: the request reaches the backend, but no chunk is read. In every backend, the core passes no content byte to a classifier, a converter, or the model until `authorize` allows it.
95
+
96
+ If a denied read must not reach the backend at all, refuse the path in the backend itself, with `denyRoots` or by leaving it out of `allowedRoots`. The write tools are not affected: they authorize after `stat`, before they open the file.