@better-fs-tools/write 0.0.0-stage → 0.1.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 +442 -2
  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 +71 -0
  12. package/dist/bundle/create-fs-tools.js +125 -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 +55 -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 +211 -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 +9 -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 +9 -0
  52. package/dist/core/commit.js +111 -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 +207 -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 +36 -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 +115 -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 +147 -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 +285 -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 +13 -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 +76 -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 +16 -0
  118. package/dist/formatters/default.js +122 -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 +13 -0
  124. package/dist/guards/index.js +25 -0
  125. package/dist/guards/non-text.d.ts +3 -0
  126. package/dist/guards/non-text.js +46 -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 +11 -0
  160. package/dist/matchers/index.js +18 -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 +221 -0
  194. package/docs/hosts.md +95 -0
  195. package/docs/result-schema.md +268 -0
  196. package/package.json +54 -4
@@ -0,0 +1,29 @@
1
+ import type { Matcher } from "../contract/matcher.ts";
2
+ import type { PatchOperation } from "../contract/patch.ts";
3
+ import type { Loaded } from "./load.ts";
4
+ import type { Planned, ResolvedTarget } from "./planned.ts";
5
+ import type { PreconditionResult } from "./precondition.ts";
6
+ import type { MutationScope } from "./scope.ts";
7
+ export interface PatchTarget {
8
+ readonly op: PatchOperation;
9
+ readonly main: ResolvedTarget;
10
+ readonly dest: ResolvedTarget | null;
11
+ readonly loaded: Loaded | null;
12
+ readonly pre: PreconditionResult | null;
13
+ }
14
+ export interface PatchChange {
15
+ readonly planned: Planned;
16
+ readonly source: ResolvedTarget | null;
17
+ }
18
+ export interface PatchProblem {
19
+ readonly path: string;
20
+ readonly line: number;
21
+ readonly reason: "duplicate" | "unsupported" | "exists" | "not-found" | "move-exists" | "context-not-found" | "lines-not-found";
22
+ readonly message: string;
23
+ readonly hunk?: number;
24
+ }
25
+ export declare function planPatch<THost>(scope: MutationScope<THost>, matchers: readonly Matcher[], targets: readonly PatchTarget[], problems: PatchProblem[]): {
26
+ readonly changes: PatchChange[];
27
+ readonly unchanged: string[];
28
+ };
29
+ export declare function verifyFailure<THost>(scope: MutationScope<THost>, problems: readonly PatchProblem[]): import("./outcomes.ts").WriteStop;
@@ -0,0 +1,169 @@
1
+ import { exactMatcher } from "../matchers/exact.js";
2
+ import { unifiedDiff } from "./diff.js";
3
+ import { applyHunks } from "./patch-hunks.js";
4
+ import { plannedChange } from "./planned.js";
5
+ import { buildSnippets } from "./snippet.js";
6
+ const STALE_REMATCH_MATCHER = exactMatcher();
7
+ export function planPatch(scope, matchers, targets, problems) {
8
+ scope.enter("plan");
9
+ scope.checkAbort();
10
+ const { limits, messages } = scope.deps;
11
+ const changes = [];
12
+ const unchanged = [];
13
+ for (const target of targets) {
14
+ if (problems.length >= limits.maxPatchProblems)
15
+ break;
16
+ const { op, main, loaded } = target;
17
+ if (op.kind === "add") {
18
+ changes.push({ planned: planAdd(scope, main, op.content), source: null });
19
+ continue;
20
+ }
21
+ if (loaded === null || target.pre === null)
22
+ continue;
23
+ if (op.kind === "delete") {
24
+ // A delete has no hunk to show the model saw the changed file.
25
+ if (target.pre.mustRematch)
26
+ throw staleFailure(scope, main.requestedPath);
27
+ changes.push({ planned: planDelete(scope, main, loaded, target.pre), source: null });
28
+ continue;
29
+ }
30
+ const { pre } = target;
31
+ const outcome = applyHunks(scope, pre.mustRematch ? [STALE_REMATCH_MATCHER] : matchers, loaded.text, op.hunks);
32
+ if (!outcome.ok) {
33
+ if (pre.mustRematch)
34
+ throw staleFailure(scope, main.requestedPath, outcome.problem.hunk);
35
+ problems.push(hunkProblem(scope, main.requestedPath, op.line, outcome.problem));
36
+ continue;
37
+ }
38
+ const dest = target.dest;
39
+ if (dest === null && outcome.text === loaded.text) {
40
+ unchanged.push(main.displayPath);
41
+ continue;
42
+ }
43
+ const { change, diffTruncated, changed } = plannedChange("apply_patch", dest ?? main, loaded, outcome.text, loaded.style, outcome.fragments, limits.maxDiffLines, dest === null ? null : main);
44
+ changes.push({
45
+ planned: {
46
+ change,
47
+ diffTruncated,
48
+ target: dest ?? main,
49
+ loaded,
50
+ codec: loaded.codec,
51
+ style: loaded.style,
52
+ precondition: dest === null ? pre.precondition : { kind: "absent" },
53
+ createParents: dest !== null,
54
+ record: pre.record,
55
+ userModified: false,
56
+ rematchedAfterStale: pre.mustRematch,
57
+ matches: outcome.matches,
58
+ snippets: buildSnippets(outcome.text, changed, limits),
59
+ },
60
+ source: dest === null ? null : main,
61
+ });
62
+ if (pre.mustRematch) {
63
+ scope.notes.push({
64
+ code: "stale-rematched",
65
+ severity: "info",
66
+ message: messages.staleRematched({ path: main.displayPath }),
67
+ });
68
+ }
69
+ for (const match of outcome.matches) {
70
+ if (!match.fuzzy)
71
+ continue;
72
+ scope.notes.push({
73
+ code: "fuzzy-match",
74
+ severity: "info",
75
+ message: messages.patchFuzzyMatch({
76
+ path: main.displayPath,
77
+ hunk: match.index + 1,
78
+ matcher: match.matcher,
79
+ lines: match.lines,
80
+ }),
81
+ data: { path: main.displayPath, hunk: match.index, matcher: match.matcher },
82
+ });
83
+ }
84
+ }
85
+ if (problems.length > 0)
86
+ throw verifyFailure(scope, problems);
87
+ return { changes, unchanged };
88
+ }
89
+ export function verifyFailure(scope, problems) {
90
+ const { messages, limits } = scope.deps;
91
+ const shown = [...problems].sort((a, b) => a.line - b.line).slice(0, limits.maxPatchProblems);
92
+ const message = [messages.patchVerifyHeader(), ...shown.map((problem) => `- ${problem.message}`)];
93
+ const data = shown.map((problem) => ({
94
+ path: problem.path,
95
+ reason: problem.reason,
96
+ ...(problem.hunk === undefined ? {} : { hunk: problem.hunk }),
97
+ }));
98
+ return scope.stop("PATCH_VERIFY", message.join("\n"), { problems: data });
99
+ }
100
+ function staleFailure(scope, path, hunk) {
101
+ scope.enter("precondition");
102
+ const message = scope.deps.messages.stale({ tool: scope.tool, path });
103
+ return scope.stop("STALE", message, hunk === undefined ? { path } : { path, hunk });
104
+ }
105
+ function hunkProblem(scope, path, line, problem) {
106
+ const { messages } = scope.deps;
107
+ const hunk = problem.hunk + 1;
108
+ const message = problem.reason === "context-not-found"
109
+ ? messages.patchContextNotFound({ path, hunk, context: problem.context })
110
+ : messages.patchLinesNotFound({ path, hunk, lines: problem.lines });
111
+ return { path, line, reason: problem.reason, message, hunk: problem.hunk };
112
+ }
113
+ function planAdd(scope, target, content) {
114
+ const { codecs, limits } = scope.deps;
115
+ const codec = codecs[0];
116
+ const style = codec.newFileStyle;
117
+ const { change, diffTruncated } = plannedChange("apply_patch", target, null, content, style, [{ oldText: "", newText: content }], limits.maxDiffLines);
118
+ return {
119
+ change,
120
+ diffTruncated,
121
+ target,
122
+ loaded: null,
123
+ codec,
124
+ style,
125
+ precondition: { kind: "absent" },
126
+ createParents: true,
127
+ record: null,
128
+ userModified: false,
129
+ rematchedAfterStale: false,
130
+ matches: [],
131
+ snippets: [],
132
+ };
133
+ }
134
+ function planDelete(scope, target, loaded, pre) {
135
+ const diff = unifiedDiff(loaded.text, null, target.displayPath, scope.deps.limits.maxDiffLines);
136
+ return {
137
+ change: {
138
+ tool: "apply_patch",
139
+ kind: "delete",
140
+ requestedPath: target.requestedPath,
141
+ resolvedPath: target.resolvedPath,
142
+ displayPath: target.displayPath,
143
+ movedFrom: null,
144
+ before: {
145
+ text: loaded.text,
146
+ style: loaded.style,
147
+ contentId: loaded.contentId,
148
+ version: loaded.version,
149
+ },
150
+ after: null,
151
+ fragments: [],
152
+ linesAdded: diff.linesAdded,
153
+ linesRemoved: diff.linesRemoved,
154
+ diff: diff.text,
155
+ },
156
+ diffTruncated: diff.truncated,
157
+ target,
158
+ loaded,
159
+ codec: loaded.codec,
160
+ style: loaded.style,
161
+ precondition: pre.precondition,
162
+ createParents: false,
163
+ record: pre.record,
164
+ userModified: false,
165
+ rematchedAfterStale: pre.mustRematch,
166
+ matches: [],
167
+ snippets: [],
168
+ };
169
+ }
@@ -0,0 +1,6 @@
1
+ import type { WriteRequest } from "../contract/input.ts";
2
+ import type { Loaded } from "./load.ts";
3
+ import type { Planned, ResolvedTarget } from "./planned.ts";
4
+ import type { PreconditionResult } from "./precondition.ts";
5
+ import type { MutationScope } from "./scope.ts";
6
+ export declare function planWrite<THost>(scope: MutationScope<THost>, request: WriteRequest, target: ResolvedTarget, loaded: Loaded | null, pre: PreconditionResult): Planned | "no-change";
@@ -0,0 +1,27 @@
1
+ import { plannedChange, toTextSpace } from "./planned.js";
2
+ export function planWrite(scope, request, target, loaded, pre) {
3
+ scope.enter("plan");
4
+ scope.checkAbort();
5
+ const { codecs, limits } = scope.deps;
6
+ const codec = loaded?.codec ?? codecs[0];
7
+ const style = loaded?.style ?? codec.newFileStyle;
8
+ const text = toTextSpace(request.content, style);
9
+ if (loaded !== null && text === loaded.text)
10
+ return "no-change";
11
+ const { change, diffTruncated } = plannedChange("write", target, loaded, text, style, [{ oldText: loaded?.text ?? "", newText: text }], limits.maxDiffLines);
12
+ return {
13
+ change,
14
+ diffTruncated,
15
+ target,
16
+ loaded,
17
+ codec,
18
+ style,
19
+ precondition: pre.precondition,
20
+ createParents: loaded === null,
21
+ record: pre.record,
22
+ userModified: false,
23
+ rematchedAfterStale: false,
24
+ matches: [],
25
+ snippets: [],
26
+ };
27
+ }
@@ -0,0 +1,35 @@
1
+ import type { Precondition } from "@better-fs-tools/fs";
2
+ import type { ReadRecord } from "@better-fs-tools/read";
3
+ import type { Codec, TextStyle } from "../contract/codec.ts";
4
+ import type { WriteToolName } from "../contract/context.ts";
5
+ import type { ChangeFragment, PlannedChange } from "../contract/extensions.ts";
6
+ import type { WriteLimits } from "../contract/limits.ts";
7
+ import type { MatchInfo, Snippet } from "../contract/result.ts";
8
+ import type { Loaded } from "./load.ts";
9
+ export interface ResolvedTarget {
10
+ readonly requestedPath: string;
11
+ readonly resolvedPath: string;
12
+ readonly displayPath: string;
13
+ }
14
+ export interface Planned {
15
+ readonly change: PlannedChange;
16
+ readonly diffTruncated: boolean;
17
+ readonly target: ResolvedTarget;
18
+ readonly loaded: Loaded | null;
19
+ readonly codec: Codec;
20
+ readonly style: TextStyle;
21
+ readonly precondition: Precondition;
22
+ readonly createParents: boolean;
23
+ readonly record: ReadRecord | null;
24
+ readonly userModified: boolean;
25
+ readonly rematchedAfterStale: boolean;
26
+ readonly matches: readonly MatchInfo[];
27
+ readonly snippets: readonly Snippet[];
28
+ }
29
+ export declare function plannedChange(tool: WriteToolName, target: ResolvedTarget, loaded: Loaded | null, after: string, style: TextStyle, fragments: readonly ChangeFragment[], maxDiffLines: number, movedFrom?: ResolvedTarget | null): {
30
+ readonly change: PlannedChange;
31
+ readonly diffTruncated: boolean;
32
+ readonly changed: readonly (readonly [number, number])[];
33
+ };
34
+ export declare function toTextSpace(text: string, style: TextStyle): string;
35
+ export declare function withAuthorizerContent(planned: Planned, content: string, limits: Readonly<WriteLimits>): Planned;
@@ -0,0 +1,36 @@
1
+ import { unifiedDiff } from "./diff.js";
2
+ import { buildSnippets } from "./snippet.js";
3
+ export function plannedChange(tool, target, loaded, after, style, fragments, maxDiffLines, movedFrom = null) {
4
+ const diff = unifiedDiff(loaded?.text ?? null, after, target.displayPath, maxDiffLines, movedFrom?.displayPath);
5
+ const change = {
6
+ tool,
7
+ kind: movedFrom !== null ? "move" : loaded === null ? "create" : "update",
8
+ requestedPath: target.requestedPath,
9
+ resolvedPath: target.resolvedPath,
10
+ displayPath: target.displayPath,
11
+ movedFrom: movedFrom?.resolvedPath ?? null,
12
+ before: loaded === null
13
+ ? null
14
+ : {
15
+ text: loaded.text,
16
+ style: loaded.style,
17
+ contentId: loaded.contentId,
18
+ version: loaded.version,
19
+ },
20
+ after: { text: after, style, contentId: null, version: null },
21
+ fragments,
22
+ linesAdded: diff.linesAdded,
23
+ linesRemoved: diff.linesRemoved,
24
+ diff: diff.text,
25
+ };
26
+ return { change, diffTruncated: diff.truncated, changed: diff.changed };
27
+ }
28
+ export function toTextSpace(text, style) {
29
+ return style.eol === "crlf" ? text.replaceAll("\r\n", "\n") : text;
30
+ }
31
+ export function withAuthorizerContent(planned, content, limits) {
32
+ const text = toTextSpace(content, planned.style);
33
+ const { change, diffTruncated, changed } = plannedChange(planned.change.tool, planned.target, planned.loaded, text, planned.style, [{ oldText: planned.loaded?.text ?? "", newText: text }], limits.maxDiffLines);
34
+ const snippets = change.tool === "edit" ? buildSnippets(text, changed, limits) : [];
35
+ return { ...planned, change, diffTruncated, userModified: true, snippets };
36
+ }
@@ -0,0 +1,10 @@
1
+ import type { FileStat, Precondition, WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { ReadRecord } from "@better-fs-tools/read";
3
+ import type { Loaded } from "./load.ts";
4
+ import type { MutationScope } from "./scope.ts";
5
+ export interface PreconditionResult {
6
+ readonly precondition: Precondition;
7
+ readonly record: ReadRecord | null;
8
+ readonly mustRematch: boolean;
9
+ }
10
+ export declare function checkPrecondition<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, stat: FileStat, loaded: Loaded | null, requested: string): Promise<PreconditionResult>;
@@ -0,0 +1,76 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { isRecord } from "./input.js";
3
+ export async function checkPrecondition(scope, fs, stat, loaded, requested) {
4
+ scope.enter("precondition");
5
+ scope.checkAbort();
6
+ const { preconditions, messages, digest } = scope.deps;
7
+ const tool = scope.tool;
8
+ // Asked for early so a failing state factory stops the call before any commit.
9
+ const store = scope.deps.state === null ? null : scope.stateStore();
10
+ if (!stat.exists || loaded === null) {
11
+ return { precondition: { kind: "absent" }, record: null, mustRematch: false };
12
+ }
13
+ const version = { kind: "version", version: loaded.version };
14
+ if (preconditions.requireRead === "off")
15
+ return { precondition: version, record: null, mustRematch: false };
16
+ if (store === null) {
17
+ addReadBeforeWriteOffNote(scope, tool);
18
+ return { precondition: version, record: null, mustRematch: false };
19
+ }
20
+ const record = await getUsableRecord(scope, store, stat.resolvedPath, digest?.id ?? null);
21
+ if (record === null) {
22
+ throw scope.stop("NOT_READ", messages.notRead({ tool, path: requested, wholeFile: false }));
23
+ }
24
+ if (!record.wholeFileVisible && !partialAllowed(preconditions, tool)) {
25
+ throw scope.stop("NOT_READ", messages.notRead({ tool, path: requested, wholeFile: true }), {
26
+ wholeFile: true,
27
+ });
28
+ }
29
+ if (isFresh(record, loaded, fs.capabilities.identity)) {
30
+ return { precondition: version, record, mustRematch: false };
31
+ }
32
+ if (preconditions.onStale === "reject" || tool === "write") {
33
+ throw scope.stop("STALE", messages.stale({ tool, path: requested }));
34
+ }
35
+ return { precondition: version, record, mustRematch: true };
36
+ }
37
+ async function getUsableRecord(scope, store, key, digestId) {
38
+ let record;
39
+ try {
40
+ record = await scope.race(() => store.get(key));
41
+ }
42
+ catch (error) {
43
+ if (error instanceof AbortStop)
44
+ throw error;
45
+ // A store is a cache: its failure is a miss.
46
+ return null;
47
+ }
48
+ if (!isRecord(record) || record.schema !== 2)
49
+ return null;
50
+ if (digestId === null || record.digest !== digestId)
51
+ return null;
52
+ if (typeof record.wholeFileVisible !== "boolean")
53
+ return null;
54
+ return record;
55
+ }
56
+ function isFresh(record, loaded, identity) {
57
+ if (identity && record.version !== null && record.version === loaded.version)
58
+ return true;
59
+ return record.contentId !== null && record.contentId === loaded.contentId;
60
+ }
61
+ function partialAllowed(policy, tool) {
62
+ if (policy.partialRead === "always")
63
+ return true;
64
+ if (policy.partialRead === "never")
65
+ return false;
66
+ return tool === "edit" || tool === "apply_patch";
67
+ }
68
+ function addReadBeforeWriteOffNote(scope, tool) {
69
+ if (scope.notes.some((note) => note.code === "read-before-write-off"))
70
+ return;
71
+ scope.notes.push({
72
+ code: "read-before-write-off",
73
+ severity: "warning",
74
+ message: scope.deps.messages.readBeforeWriteOff({ tool }),
75
+ });
76
+ }
@@ -0,0 +1,3 @@
1
+ import type { Committed } from "./hooks.ts";
2
+ import type { MutationScope } from "./scope.ts";
3
+ export declare function recordCommitted<THost>(scope: MutationScope<THost>, committed: readonly Committed[]): Promise<void>;
@@ -0,0 +1,58 @@
1
+ export async function recordCommitted(scope, committed) {
2
+ const { digest, clock } = scope.deps;
3
+ if (digest === null || scope.deps.state === null)
4
+ return;
5
+ scope.enter("record");
6
+ let store;
7
+ try {
8
+ store = scope.stateStore();
9
+ }
10
+ catch {
11
+ return;
12
+ }
13
+ if (store === null)
14
+ return;
15
+ for (const file of committed) {
16
+ const { change } = file;
17
+ const key = change.resolvedPath;
18
+ try {
19
+ const movedFromPath = file.planned.change.movedFrom;
20
+ if (movedFromPath !== null)
21
+ await store.delete(movedFromPath);
22
+ const after = change.after;
23
+ if (!file.finalStateKnown || after === null) {
24
+ await store.delete(key);
25
+ continue;
26
+ }
27
+ const { version, contentId } = after;
28
+ // Built field by field so nothing from `call` reaches the store.
29
+ const record = {
30
+ schema: 2,
31
+ origin: "write",
32
+ observationId: digest.hash(JSON.stringify(["write", key, version, contentId])),
33
+ resolvedPath: key,
34
+ identity: file.identity,
35
+ version,
36
+ digest: digest.id,
37
+ contentId,
38
+ viewId: contentId ?? "",
39
+ observedAt: clock().toISOString(),
40
+ wholeFileVisible: wholeFileVisible(file),
41
+ totalsExact: true,
42
+ request: null,
43
+ };
44
+ await store.put(key, record);
45
+ }
46
+ catch {
47
+ // A store failure is not a write failure.
48
+ }
49
+ }
50
+ }
51
+ function wholeFileVisible(file) {
52
+ const { planned } = file;
53
+ if (planned.userModified || planned.rematchedAfterStale || file.rewrittenByHook)
54
+ return false;
55
+ if (planned.change.tool === "write" || planned.loaded === null)
56
+ return true;
57
+ return planned.record?.wholeFileVisible ?? false;
58
+ }
@@ -0,0 +1,3 @@
1
+ import type { WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { MutationScope } from "./scope.ts";
3
+ export declare function resolvePath<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, requested: string): Promise<string>;
@@ -0,0 +1,65 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { extensionId } from "./extension-error.js";
3
+ import { isPath, isRecord } from "./input.js";
4
+ import { isNote, messageOf } from "./outcomes.js";
5
+ // Matches the read tool's default maxDirectoryEntries.
6
+ const RESOLVER_LIST_LIMIT = 200;
7
+ export async function resolvePath(scope, fs, requested) {
8
+ const resolver = scope.deps.resolve;
9
+ if (resolver === null)
10
+ return requested;
11
+ scope.checkAbort();
12
+ let listed = false;
13
+ const ctx = {
14
+ ...scope.hookContext(),
15
+ paths: fs.paths,
16
+ list: async (dir) => {
17
+ if (listed)
18
+ return { ok: false, error: { reason: "denied", detail: "listing budget spent" } };
19
+ listed = true;
20
+ return listOnce(scope, fs, dir);
21
+ },
22
+ };
23
+ let outcome;
24
+ try {
25
+ outcome = await scope.race(() => resolver.resolve(requested, ctx));
26
+ }
27
+ catch (error) {
28
+ if (error instanceof AbortStop)
29
+ throw error;
30
+ throw scope.extensionFailure("resolve", extensionId(resolver, error));
31
+ }
32
+ const malformed = () => scope.extensionFailure("resolve", extensionId(resolver));
33
+ if (!isRecord(outcome))
34
+ throw malformed();
35
+ const { note } = outcome;
36
+ if (note !== undefined && !isNote(note))
37
+ throw malformed();
38
+ if (outcome.kind === "not-found") {
39
+ if (note !== undefined)
40
+ scope.notes.push(note);
41
+ const { messages } = scope.deps;
42
+ throw scope.stop("NOT_FOUND", messages.notFound({ tool: scope.tool, path: requested }));
43
+ }
44
+ const { path } = outcome;
45
+ if (outcome.kind !== "path" || !isPath(path))
46
+ throw malformed();
47
+ if (note !== undefined)
48
+ scope.notes.push(note);
49
+ return path;
50
+ }
51
+ // Not authorized: the path the resolver returns is authorized in the access stage.
52
+ async function listOnce(scope, fs, dir) {
53
+ if (typeof fs.list !== "function") {
54
+ return { ok: false, error: { reason: "unsupported", detail: "the backend cannot list" } };
55
+ }
56
+ const { signal } = scope;
57
+ try {
58
+ return await fs.list(dir, signal === undefined
59
+ ? { limit: RESOLVER_LIST_LIMIT }
60
+ : { limit: RESOLVER_LIST_LIMIT, signal });
61
+ }
62
+ catch (error) {
63
+ return { ok: false, error: { reason: "io", detail: messageOf(error) } };
64
+ }
65
+ }
@@ -0,0 +1,33 @@
1
+ import type { FileSystemError, MutationError, WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { JsonObject, Note, ReadStateStore, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { WriteDependencies } from "../contract/deps.ts";
4
+ import type { WriteHookContext } from "../contract/extensions.ts";
5
+ import type { MutationRequest } from "../contract/input.ts";
6
+ import type { WriteErrorCode, WritePhase } from "../contract/result.ts";
7
+ import { WriteStop } from "./outcomes.ts";
8
+ export declare class MutationScope<THost> {
9
+ readonly deps: WriteDependencies<THost>;
10
+ readonly request: MutationRequest;
11
+ readonly call: ToolCallContext<THost>;
12
+ phase: WritePhase;
13
+ readonly notes: Note[];
14
+ private commitStarted;
15
+ private resolvedFs;
16
+ private resolvedState;
17
+ private hook;
18
+ constructor(deps: WriteDependencies<THost>, request: MutationRequest, call: ToolCallContext<THost>);
19
+ get tool(): MutationRequest["tool"];
20
+ get signal(): AbortSignal | undefined;
21
+ enter(phase: WritePhase): void;
22
+ startCommit(): void;
23
+ checkAbort(): void;
24
+ race<T>(start: () => T | Promise<T>): Promise<T>;
25
+ fileSystem(): WritableFileSystem;
26
+ stateStore(): ReadStateStore | null;
27
+ hookContext(): WriteHookContext<THost>;
28
+ get path(): string | null;
29
+ stop(code: WriteErrorCode, message: string, data?: JsonObject): WriteStop;
30
+ stopWith(note: Note): WriteStop;
31
+ backendFailure(path: string, error: FileSystemError | MutationError): WriteStop;
32
+ extensionFailure(extension: string, id?: string | null): WriteStop;
33
+ }
@@ -0,0 +1,109 @@
1
+ import { AbortStop, raceAbort } from "./abort.js";
2
+ import { isFileSystem, isStateStore, isWritable } from "./deps.js";
3
+ import { WriteStop, backendErrorNote, errorNote, failure } from "./outcomes.js";
4
+ export class MutationScope {
5
+ deps;
6
+ request;
7
+ call;
8
+ phase = "input";
9
+ notes = [];
10
+ commitStarted = false;
11
+ resolvedFs = null;
12
+ resolvedState = undefined;
13
+ hook = null;
14
+ constructor(deps, request, call) {
15
+ this.deps = deps;
16
+ this.request = request;
17
+ this.call = call;
18
+ }
19
+ get tool() {
20
+ return this.request.tool;
21
+ }
22
+ get signal() {
23
+ return this.commitStarted ? undefined : this.call.signal;
24
+ }
25
+ enter(phase) {
26
+ this.phase = phase;
27
+ }
28
+ startCommit() {
29
+ this.commitStarted = true;
30
+ }
31
+ checkAbort() {
32
+ if (this.signal?.aborted)
33
+ throw new AbortStop();
34
+ }
35
+ race(start) {
36
+ return raceAbort(start, this.signal);
37
+ }
38
+ fileSystem() {
39
+ if (this.resolvedFs !== null)
40
+ return this.resolvedFs;
41
+ const { fs } = this.deps;
42
+ if (typeof fs !== "function")
43
+ return (this.resolvedFs = fs);
44
+ let produced;
45
+ try {
46
+ produced = fs(this.call);
47
+ }
48
+ catch {
49
+ throw this.extensionFailure("fs");
50
+ }
51
+ if (isWritable(produced))
52
+ return (this.resolvedFs = produced);
53
+ // A read-only backend is a configuration problem, not a host bug.
54
+ if (isFileSystem(produced)) {
55
+ throw this.backendFailure(this.path ?? "the patch", {
56
+ reason: "unsupported",
57
+ detail: "the filesystem has no write methods",
58
+ });
59
+ }
60
+ throw this.extensionFailure("fs");
61
+ }
62
+ stateStore() {
63
+ if (this.resolvedState !== undefined)
64
+ return this.resolvedState;
65
+ const { state } = this.deps;
66
+ if (typeof state !== "function")
67
+ return (this.resolvedState = state);
68
+ let produced;
69
+ try {
70
+ produced = state(this.call);
71
+ }
72
+ catch {
73
+ throw this.extensionFailure("state");
74
+ }
75
+ if (produced !== null && !isStateStore(produced))
76
+ throw this.extensionFailure("state");
77
+ return (this.resolvedState = produced);
78
+ }
79
+ hookContext() {
80
+ if (this.hook !== null)
81
+ return this.hook;
82
+ const { limits, messages, digest, clock } = this.deps;
83
+ return (this.hook = Object.freeze({
84
+ tool: this.request.tool,
85
+ request: this.request,
86
+ limits,
87
+ messages,
88
+ digest,
89
+ clock,
90
+ call: this.call,
91
+ }));
92
+ }
93
+ get path() {
94
+ return this.request.tool === "apply_patch" ? null : this.request.path;
95
+ }
96
+ stop(code, message, data) {
97
+ return this.stopWith(errorNote(code, message, data));
98
+ }
99
+ stopWith(note) {
100
+ return new WriteStop(failure(this.tool, this.phase, note));
101
+ }
102
+ backendFailure(path, error) {
103
+ return this.stopWith(backendErrorNote(this.deps.messages, this.tool, path, error, this.phase));
104
+ }
105
+ extensionFailure(extension, id = null) {
106
+ const { phase } = this;
107
+ return this.stop("EXTENSION_FAILED", this.deps.messages.extensionFailed({ path: this.path, extension, phase }), id === null ? { extension, phase } : { extension, phase, id });
108
+ }
109
+ }
@@ -0,0 +1,4 @@
1
+ import type { WriteLimits } from "../contract/limits.ts";
2
+ import type { Snippet } from "../contract/result.ts";
3
+ import { LineIndex } from "./line-index.ts";
4
+ export declare function buildSnippets(after: string | LineIndex, ranges: readonly (readonly [number, number])[], limits: Readonly<WriteLimits>): Snippet[];