@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,284 @@
1
+ import { authorizeAccess, authorizeChanges } from "./authorize.js";
2
+ import { fileChange } from "./commit.js";
3
+ import { commitPatch, deleteChange } from "./commit-patch.js";
4
+ import { encodePlanned } from "./encode.js";
5
+ import { formatResult } from "./format.js";
6
+ import { runGuards } from "./guards.js";
7
+ import { committedFile, newFileMode, runWriteHooks } from "./hooks.js";
8
+ import { parseApplyPatchInput } from "./input.js";
9
+ import { loadFile } from "./load.js";
10
+ import { acquireLocks } from "./lock.js";
11
+ import { WriteStop } from "./outcomes.js";
12
+ import { parsePatchText } from "./parse-patch.js";
13
+ import { invalidInput, noChange, stopped } from "./pipeline.js";
14
+ import { planPatch, verifyFailure } from "./plan-patch.js";
15
+ import { checkPrecondition } from "./precondition.js";
16
+ import { recordCommitted } from "./record.js";
17
+ import { resolvePath } from "./resolve.js";
18
+ import { MutationScope } from "./scope.js";
19
+ import { statAgain, statTarget } from "./target.js";
20
+ export async function runApplyPatch(deps, input, call) {
21
+ let request;
22
+ try {
23
+ request = parseApplyPatchInput(input, deps.limits);
24
+ }
25
+ catch (error) {
26
+ return formatResult(deps, call, invalidInput(deps, "apply_patch", input, error));
27
+ }
28
+ const scope = new MutationScope(deps, request, call);
29
+ let report;
30
+ try {
31
+ report = await patchStages(scope, deps, request);
32
+ }
33
+ catch (error) {
34
+ const failed = stopped(scope, error);
35
+ report = { ...failed, notes: [...failed.notes, ...scope.notes] };
36
+ }
37
+ return formatResult(deps, call, report);
38
+ }
39
+ async function patchStages(scope, deps, request) {
40
+ const operations = parsePatchText(scope, deps.patchParser, request.patch);
41
+ scope.checkAbort();
42
+ scope.enter("resolve");
43
+ const fs = scope.fileSystem();
44
+ const slots = [];
45
+ for (const op of operations) {
46
+ const main = { requestedPath: op.path, path: await resolvePath(scope, fs, op.path) };
47
+ const moveTo = op.kind === "update" ? op.moveTo : null;
48
+ const dest = moveTo === null
49
+ ? null
50
+ : { requestedPath: moveTo, path: await resolvePath(scope, fs, moveTo) };
51
+ slots.push({ op, main, dest });
52
+ }
53
+ const targets = slots.flatMap((slot) => slot.dest === null ? [slot.main] : [slot.main, slot.dest]);
54
+ const first = new Map();
55
+ for (const target of targets)
56
+ first.set(target, await statTarget(scope, fs, target));
57
+ const early = earlyProblems(scope, fs, slots, first);
58
+ if (early.length > 0)
59
+ throw verifyFailure(scope, early);
60
+ await authorizeAccess(scope, accessRequests(slots, first));
61
+ const keys = targets.map((target) => first.get(target).resolvedPath);
62
+ const release = await acquireLocks(scope, keys, targets.map((target) => target.requestedPath));
63
+ try {
64
+ const stats = new Map();
65
+ for (const target of targets) {
66
+ stats.set(target, await statAgain(scope, fs, target, first.get(target)));
67
+ }
68
+ const problems = existenceProblems(scope, slots, stats);
69
+ const loaded = await loadAll(scope, fs, slots, stats);
70
+ const { changes, unchanged } = planPatch(scope, deps.matchers, loaded, problems);
71
+ if (changes.length === 0)
72
+ return noChange(scope, ...unchanged);
73
+ const planned = changes.map((change) => change.planned.change);
74
+ await runGuards(scope, planned);
75
+ await authorizeChanges(scope, planned);
76
+ const steps = encodeSteps(scope, changes);
77
+ if (steps.length === 0)
78
+ return noChange(scope, ...unchanged, ...changes.map(displayOf));
79
+ const published = await commitPatch(scope, fs, steps, patchFiles(slots, stats));
80
+ const committed = published.map(({ step, file }) => {
81
+ const { planned: plannedStep, source } = step.change;
82
+ if (file === null) {
83
+ const change = deleteChange(plannedStep, plannedStep.target);
84
+ return {
85
+ planned: plannedStep,
86
+ change,
87
+ identity: null,
88
+ finalStateKnown: true,
89
+ rewrittenByHook: false,
90
+ };
91
+ }
92
+ const base = fileChange(scope, plannedStep, step.bytes, file);
93
+ const change = source === null ? base : { ...base, movedFrom: source.displayPath };
94
+ return committedFile(scope, plannedStep, change, file);
95
+ });
96
+ await runWriteHooks(scope, fs, committed);
97
+ await recordCommitted(scope, committed);
98
+ return {
99
+ tool: scope.tool,
100
+ status: "ok",
101
+ changes: committed.map((file) => file.change),
102
+ unchanged: [],
103
+ notes: [...scope.notes],
104
+ commit: null,
105
+ };
106
+ }
107
+ finally {
108
+ release();
109
+ }
110
+ }
111
+ function earlyProblems(scope, fs, slots, first) {
112
+ const problems = duplicateTargetProblems(scope, slots, first);
113
+ if (typeof fs.remove === "function")
114
+ return problems;
115
+ return [...problems, ...removeUnsupportedProblems(scope, slots)];
116
+ }
117
+ function duplicateTargetProblems(scope, slots, first) {
118
+ const { messages } = scope.deps;
119
+ const problems = [];
120
+ const seen = new Set();
121
+ const reported = new Set();
122
+ for (const { op, main, dest } of slots) {
123
+ for (const target of dest === null ? [main] : [main, dest]) {
124
+ const key = first.get(target).resolvedPath;
125
+ if (!seen.has(key)) {
126
+ seen.add(key);
127
+ continue;
128
+ }
129
+ if (reported.has(key))
130
+ continue;
131
+ reported.add(key);
132
+ const path = target.requestedPath;
133
+ const message = messages.patchDuplicateTarget({ path });
134
+ problems.push({ path, line: op.line, reason: "duplicate", message });
135
+ }
136
+ }
137
+ return problems;
138
+ }
139
+ function removeUnsupportedProblems(scope, slots) {
140
+ const { messages } = scope.deps;
141
+ const problems = [];
142
+ for (const { op, dest } of slots) {
143
+ if (op.kind !== "delete" && dest === null)
144
+ continue;
145
+ const path = op.path;
146
+ const detail = "the backend cannot remove files";
147
+ const message = messages.unsupportedBackend({ path, detail });
148
+ problems.push({ path, line: op.line, reason: "unsupported", message });
149
+ }
150
+ return problems;
151
+ }
152
+ function accessRequests(slots, first) {
153
+ const requests = [];
154
+ for (const { op, main, dest } of slots) {
155
+ const target = resolvedOf(main, first);
156
+ if (op.kind === "add")
157
+ requests.push({ action: "create", target });
158
+ else if (op.kind === "delete")
159
+ requests.push({ action: "delete", target });
160
+ else if (dest === null)
161
+ requests.push({ action: "update", target });
162
+ else {
163
+ requests.push({ action: "move", target });
164
+ requests.push({ action: "create", target: resolvedOf(dest, first) });
165
+ }
166
+ }
167
+ return requests;
168
+ }
169
+ function existenceProblems(scope, slots, stats) {
170
+ const { messages } = scope.deps;
171
+ const problems = [];
172
+ for (const { op, main, dest } of slots) {
173
+ const exists = stats.get(main).exists;
174
+ const path = main.requestedPath;
175
+ if (op.kind === "add" && exists) {
176
+ problems.push({
177
+ path,
178
+ line: op.line,
179
+ reason: "exists",
180
+ message: messages.exists({ tool: "apply_patch", path }),
181
+ });
182
+ }
183
+ if (op.kind !== "add" && !exists) {
184
+ problems.push({
185
+ path,
186
+ line: op.line,
187
+ reason: "not-found",
188
+ message: messages.patchNotFound({ path, operation: op.kind }),
189
+ });
190
+ }
191
+ if (dest !== null && stats.get(dest).exists) {
192
+ const to = dest.requestedPath;
193
+ problems.push({
194
+ path: to,
195
+ line: op.line,
196
+ reason: "move-exists",
197
+ message: messages.patchMoveExists({ path: to, from: path }),
198
+ });
199
+ }
200
+ }
201
+ return problems;
202
+ }
203
+ async function loadAll(scope, fs, slots, stats) {
204
+ const targets = [];
205
+ const failures = [];
206
+ for (const { op, main, dest } of slots) {
207
+ const stat = stats.get(main);
208
+ let loaded = null;
209
+ let pre = null;
210
+ if (stat.exists && op.kind !== "add")
211
+ loaded = await loadFile(scope, fs, stat, main.requestedPath);
212
+ if (loaded !== null || (op.kind === "add" && !stat.exists)) {
213
+ try {
214
+ pre = await checkPrecondition(scope, fs, stat, loaded, main.requestedPath);
215
+ }
216
+ catch (error) {
217
+ const code = error instanceof WriteStop ? error.report.error.code : null;
218
+ if (code !== "NOT_READ" && code !== "STALE")
219
+ throw error;
220
+ failures.push({ path: main.requestedPath, stop: error });
221
+ }
222
+ }
223
+ const destination = dest === null ? null : resolvedOf(dest, stats);
224
+ targets.push({ op, main: resolvedOf(main, stats), dest: destination, loaded, pre });
225
+ }
226
+ if (failures.length > 0)
227
+ throw preconditionFailure(scope, failures);
228
+ return targets;
229
+ }
230
+ function preconditionFailure(scope, failures) {
231
+ const [first] = failures;
232
+ if (first === undefined || failures.length === 1)
233
+ return first.stop;
234
+ const code = first.stop.report.error.code;
235
+ const message = failures.map(({ stop }) => stop.report.error.message).join("\n");
236
+ const listed = failures.map(({ path, stop }) => ({
237
+ path,
238
+ code: stop.report.error.code,
239
+ ...stop.report.error.data,
240
+ }));
241
+ scope.enter("precondition");
242
+ return scope.stop(code, message, { failures: listed });
243
+ }
244
+ function encodeSteps(scope, changes) {
245
+ const encoded = [];
246
+ for (const change of changes) {
247
+ const { planned, source } = change;
248
+ if (planned.change.kind === "delete") {
249
+ encoded.push({ change, bytes: null });
250
+ continue;
251
+ }
252
+ const bytes = encodePlanned(scope, planned);
253
+ if (bytes !== "same")
254
+ encoded.push({ change, bytes });
255
+ else if (source !== null)
256
+ encoded.push({ change, bytes: planned.loaded.bytes });
257
+ }
258
+ scope.enter("commit");
259
+ return encoded.map(({ change, bytes }) => {
260
+ const { planned, source } = change;
261
+ if (planned.precondition.kind !== "absent")
262
+ return { change, bytes, mode: null };
263
+ const asked = newFileMode(scope, planned.change);
264
+ const mode = asked ?? (source === null ? null : (planned.loaded?.mode ?? null));
265
+ return { change, bytes, mode };
266
+ });
267
+ }
268
+ function patchFiles(slots, stats) {
269
+ return slots.flatMap(({ main, dest }) => (dest === null ? [main] : [main, dest]).map((target) => {
270
+ const stat = stats.get(target);
271
+ return { path: stat.displayPath, resolvedPath: stat.resolvedPath };
272
+ }));
273
+ }
274
+ function displayOf(change) {
275
+ return change.planned.target.displayPath;
276
+ }
277
+ function resolvedOf(target, stats) {
278
+ const stat = stats.get(target);
279
+ return {
280
+ requestedPath: target.requestedPath,
281
+ resolvedPath: stat.resolvedPath,
282
+ displayPath: stat.displayPath,
283
+ };
284
+ }
@@ -0,0 +1,22 @@
1
+ import type { ToolCallContext } from "@better-fs-tools/read";
2
+ import type { EditDependencies, WriteDependencies } from "../contract/deps.ts";
3
+ import type { MutationRequest } from "../contract/input.ts";
4
+ import type { MutationReport, MutationResult } from "../contract/result.ts";
5
+ import type { MissCounter } from "./hints.ts";
6
+ import type { Loaded } from "./load.ts";
7
+ import type { Planned, ResolvedTarget } from "./planned.ts";
8
+ import type { PreconditionResult } from "./precondition.ts";
9
+ import { MutationScope } from "./scope.ts";
10
+ export declare function runWrite<THost>(deps: WriteDependencies<THost>, input: unknown, call: ToolCallContext<THost>): Promise<MutationResult>;
11
+ export declare function runEdit<THost>(deps: EditDependencies<THost>, input: unknown, call: ToolCallContext<THost>, misses: MissCounter): Promise<MutationResult>;
12
+ export interface SingleFilePlan<THost> {
13
+ readonly whenMissing: "create" | "not-found";
14
+ readonly plan: (scope: MutationScope<THost>, target: ResolvedTarget, loaded: Loaded | null, pre: PreconditionResult) => Planned | "no-change";
15
+ readonly whenSameBytes: "no-change" | "error";
16
+ }
17
+ export declare function runSingleFile<THost>(deps: WriteDependencies<THost>, request: Extract<MutationRequest, {
18
+ readonly path: string;
19
+ }>, call: ToolCallContext<THost>, tool: SingleFilePlan<THost>): Promise<MutationReport>;
20
+ export declare function noChange<THost>(scope: MutationScope<THost>, ...paths: readonly string[]): MutationReport;
21
+ export declare function stopped<THost>(scope: MutationScope<THost>, error: unknown): MutationReport;
22
+ export declare function invalidInput<THost>(deps: WriteDependencies<THost>, tool: MutationRequest["tool"], input: unknown, error: unknown): MutationReport;
@@ -0,0 +1,153 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { authorizeAccess, authorizeChanges } from "./authorize.js";
3
+ import { commitOne, fileChange } from "./commit.js";
4
+ import { encodePlanned } from "./encode.js";
5
+ import { formatResult } from "./format.js";
6
+ import { runGuards } from "./guards.js";
7
+ import { committedFile, runWriteHooks } from "./hooks.js";
8
+ import { isRecord, parseEditInput, parseWriteInput } from "./input.js";
9
+ import { loadFile } from "./load.js";
10
+ import { acquireLocks } from "./lock.js";
11
+ import { WriteStop, errorNote, failure, messageOf } from "./outcomes.js";
12
+ import { planEdit } from "./plan-edit.js";
13
+ import { planWrite } from "./plan-write.js";
14
+ import { withAuthorizerContent } from "./planned.js";
15
+ import { checkPrecondition } from "./precondition.js";
16
+ import { recordCommitted } from "./record.js";
17
+ import { resolvePath } from "./resolve.js";
18
+ import { MutationScope } from "./scope.js";
19
+ import { statAgain, statTarget } from "./target.js";
20
+ export async function runWrite(deps, input, call) {
21
+ let request;
22
+ try {
23
+ request = parseWriteInput(input, deps.limits);
24
+ }
25
+ catch (error) {
26
+ return formatResult(deps, call, invalidInput(deps, "write", input, error));
27
+ }
28
+ const report = await runSingleFile(deps, request, call, {
29
+ whenMissing: "create",
30
+ plan: (scope, target, loaded, pre) => planWrite(scope, request, target, loaded, pre),
31
+ whenSameBytes: "no-change",
32
+ });
33
+ return formatResult(deps, call, report);
34
+ }
35
+ export async function runEdit(deps, input, call, misses) {
36
+ let request;
37
+ try {
38
+ request = parseEditInput(input, deps.limits);
39
+ }
40
+ catch (error) {
41
+ return formatResult(deps, call, invalidInput(deps, "edit", input, error));
42
+ }
43
+ const { matchers, recovery } = deps;
44
+ const report = await runSingleFile(deps, request, call, {
45
+ whenMissing: "not-found",
46
+ plan: (scope, target, loaded, pre) => planEdit(scope, { request, matchers, recovery, misses }, target, loaded, pre),
47
+ whenSameBytes: "error",
48
+ });
49
+ return formatResult(deps, call, report);
50
+ }
51
+ export async function runSingleFile(deps, request, call, tool) {
52
+ const scope = new MutationScope(deps, request, call);
53
+ try {
54
+ return await singleFileStages(scope, request.path, tool);
55
+ }
56
+ catch (error) {
57
+ const report = stopped(scope, error);
58
+ return { ...report, notes: [...report.notes, ...scope.notes] };
59
+ }
60
+ }
61
+ async function singleFileStages(scope, requested, tool) {
62
+ const { messages, limits } = scope.deps;
63
+ scope.checkAbort();
64
+ scope.enter("resolve");
65
+ const fs = scope.fileSystem();
66
+ const path = await resolvePath(scope, fs, requested);
67
+ const target = { requestedPath: requested, path };
68
+ const notFound = () => scope.stop("NOT_FOUND", messages.notFound({ tool: scope.tool, path: requested }));
69
+ const first = await statTarget(scope, fs, target);
70
+ if (!first.exists && tool.whenMissing === "not-found")
71
+ throw notFound();
72
+ await authorizeAccess(scope, [
73
+ { action: first.exists ? "update" : "create", target: resolved(requested, first) },
74
+ ]);
75
+ const release = await acquireLocks(scope, [first.resolvedPath], [requested]);
76
+ try {
77
+ const stat = await statAgain(scope, fs, target, first);
78
+ if (!stat.exists && tool.whenMissing === "not-found")
79
+ throw notFound();
80
+ const loaded = stat.exists ? await loadFile(scope, fs, stat, requested) : null;
81
+ const pre = await checkPrecondition(scope, fs, stat, loaded, requested);
82
+ const resolvedTarget = resolved(requested, stat);
83
+ let planned = tool.plan(scope, resolvedTarget, loaded, pre);
84
+ if (planned === "no-change")
85
+ return noChange(scope, resolvedTarget.displayPath);
86
+ await runGuards(scope, [planned.change]);
87
+ const [content] = await authorizeChanges(scope, [planned.change]);
88
+ if (content !== null && content !== undefined) {
89
+ scope.enter("plan");
90
+ planned = withAuthorizerContent(planned, content, limits);
91
+ scope.notes.push({
92
+ code: "user-modified",
93
+ severity: "warning",
94
+ message: messages.userModified({ path: resolvedTarget.displayPath }),
95
+ });
96
+ await runGuards(scope, [planned.change]);
97
+ }
98
+ const bytes = encodePlanned(scope, planned);
99
+ if (bytes === "same") {
100
+ if (tool.whenSameBytes === "no-change")
101
+ return noChange(scope, resolvedTarget.displayPath);
102
+ throw scope.stop("NO_CHANGE", messages.noChange({ path: requested }));
103
+ }
104
+ const mutated = await commitOne(scope, fs, planned, bytes);
105
+ const committed = [
106
+ committedFile(scope, planned, fileChange(scope, planned, bytes, mutated), mutated),
107
+ ];
108
+ await runWriteHooks(scope, fs, committed);
109
+ await recordCommitted(scope, committed);
110
+ return {
111
+ tool: scope.tool,
112
+ status: "ok",
113
+ changes: committed.map((file) => file.change),
114
+ unchanged: [],
115
+ notes: [...scope.notes],
116
+ commit: null,
117
+ };
118
+ }
119
+ finally {
120
+ release();
121
+ }
122
+ }
123
+ function resolved(requestedPath, stat) {
124
+ return { requestedPath, resolvedPath: stat.resolvedPath, displayPath: stat.displayPath };
125
+ }
126
+ export function noChange(scope, ...paths) {
127
+ return {
128
+ tool: scope.tool,
129
+ status: "no-change",
130
+ changes: [],
131
+ unchanged: [...paths],
132
+ notes: [...scope.notes],
133
+ commit: null,
134
+ };
135
+ }
136
+ export function stopped(scope, error) {
137
+ if (error instanceof WriteStop)
138
+ return error.report;
139
+ const { messages } = scope.deps;
140
+ if (error instanceof AbortStop) {
141
+ const { phase } = scope;
142
+ return failure(scope.tool, phase, errorNote("ABORTED", messages.aborted({ phase }), { phase }));
143
+ }
144
+ const note = errorNote("IO_ERROR", messages.ioError({ path: scope.path }), {
145
+ detail: messageOf(error),
146
+ });
147
+ return failure(scope.tool, scope.phase, note);
148
+ }
149
+ export function invalidInput(deps, tool, input, error) {
150
+ const path = isRecord(input) && typeof input.path === "string" ? input.path : "";
151
+ const note = errorNote("INVALID_INPUT", deps.messages.invalidInput({ tool, detail: messageOf(error) }), path === "" ? undefined : { path });
152
+ return failure(tool, "input", note);
153
+ }
@@ -0,0 +1,15 @@
1
+ import type { EditRequest } from "../contract/input.ts";
2
+ import type { Matcher } from "../contract/matcher.ts";
3
+ import type { MissCounter } from "./hints.ts";
4
+ import type { Loaded } from "./load.ts";
5
+ import type { Planned, ResolvedTarget } from "./planned.ts";
6
+ import type { PreconditionResult } from "./precondition.ts";
7
+ import type { MutationScope } from "./scope.ts";
8
+ export interface EditPlanInput {
9
+ readonly request: EditRequest;
10
+ readonly matchers: readonly Matcher[];
11
+ /** Turns on already-applied, the closest-region hint, and the repeated-miss note. */
12
+ readonly recovery: boolean;
13
+ readonly misses: MissCounter;
14
+ }
15
+ export declare function planEdit<THost>(scope: MutationScope<THost>, input: EditPlanInput, target: ResolvedTarget, loaded: Loaded | null, pre: PreconditionResult): Planned | "no-change";
@@ -0,0 +1,215 @@
1
+ import { exactMatcher } from "../matchers/exact.js";
2
+ import { closestRegion, isAlreadyApplied, trailingNewline } from "./hints.js";
3
+ import { LineIndex } from "./line-index.js";
4
+ import { REPLACE_ALL_CAP, adaptFor, escapeDrift, findWith, runChain, tooWide } from "./match.js";
5
+ import { plannedChange, toTextSpace } from "./planned.js";
6
+ import { buildSnippets } from "./snippet.js";
7
+ import { placed, spliceAll } from "./splice.js";
8
+ const STALE_REMATCH_MATCHER = exactMatcher();
9
+ export function planEdit(scope, input, target, loaded, pre) {
10
+ scope.enter("plan");
11
+ scope.checkAbort();
12
+ const { messages, limits } = scope.deps;
13
+ const path = target.requestedPath;
14
+ if (loaded === null)
15
+ throw scope.stop("NOT_FOUND", messages.notFound({ tool: "edit", path }));
16
+ const { text, style } = loaded;
17
+ const found = [];
18
+ for (const [index, given] of input.request.edits.entries()) {
19
+ const pair = {
20
+ oldText: toTextSpace(given.oldText, style),
21
+ newText: toTextSpace(given.newText, style),
22
+ replaceAll: given.replaceAll,
23
+ };
24
+ const result = pre.mustRematch
25
+ ? rematchAfterStale(scope, text, pair, index, path)
26
+ : matchPair(scope, input, target, text, pair, index);
27
+ if (result !== "applied") {
28
+ found.push(result);
29
+ continue;
30
+ }
31
+ scope.notes.push({
32
+ code: "already-applied",
33
+ severity: "info",
34
+ message: messages.alreadyApplied({ path: target.displayPath, index }),
35
+ data: { index },
36
+ });
37
+ }
38
+ input.misses.reset(target.resolvedPath);
39
+ if (found.length === 0)
40
+ return "no-change";
41
+ const hits = found
42
+ .flatMap((pair) => pair.hits.map((hit) => ({ ...hit, index: pair.index })))
43
+ .sort((a, b) => a.start - b.start);
44
+ for (let at = 1; at < hits.length; at += 1) {
45
+ const previous = hits[at - 1];
46
+ const current = hits[at];
47
+ if (previous.end <= current.start)
48
+ continue;
49
+ const first = Math.min(previous.index, current.index);
50
+ const second = Math.max(previous.index, current.index);
51
+ throw scope.stop("OVERLAP", messages.overlap({ path, first, second }), { first, second });
52
+ }
53
+ const after = spliceAll(text, hits);
54
+ if (after === text)
55
+ throw scope.stop("NO_CHANGE", messages.noChange({ path }));
56
+ if (pre.mustRematch) {
57
+ scope.notes.push({
58
+ code: "stale-rematched",
59
+ severity: "info",
60
+ message: messages.staleRematched({ path: target.displayPath }),
61
+ });
62
+ }
63
+ const before = new LineIndex(text);
64
+ const afterIndex = new LineIndex(after);
65
+ const spans = placed(hits).map(({ start, end }) => afterIndex.span(start, end));
66
+ const byPair = new Map();
67
+ for (const [at, span] of spans.entries()) {
68
+ const index = hits[at].index;
69
+ const list = byPair.get(index) ?? [];
70
+ if (list.length < limits.maxListedMatches)
71
+ list.push(span);
72
+ byPair.set(index, list);
73
+ }
74
+ const matches = found.map((pair) => {
75
+ const first = pair.hits[0];
76
+ return {
77
+ index: pair.index,
78
+ matcher: pair.matcher.id,
79
+ fuzzy: pair.matcher.fuzzy,
80
+ lines: before.span(first.start, first.end),
81
+ count: pair.hits.length,
82
+ replaced: byPair.get(pair.index) ?? [],
83
+ };
84
+ });
85
+ for (const match of matches) {
86
+ if (!match.fuzzy)
87
+ continue;
88
+ scope.notes.push({
89
+ code: "fuzzy-match",
90
+ severity: "info",
91
+ message: messages.fuzzyMatch({
92
+ path: target.displayPath,
93
+ index: match.index,
94
+ matcher: match.matcher,
95
+ lines: match.lines,
96
+ }),
97
+ data: { index: match.index, matcher: match.matcher, lines: [...match.lines] },
98
+ });
99
+ }
100
+ const fragments = found.map((pair) => {
101
+ const first = pair.hits[0];
102
+ return { oldText: text.slice(first.start, first.end), newText: first.text };
103
+ });
104
+ const { change, diffTruncated } = plannedChange("edit", target, loaded, after, style, fragments, limits.maxDiffLines);
105
+ return {
106
+ change,
107
+ diffTruncated,
108
+ target,
109
+ loaded,
110
+ codec: loaded.codec,
111
+ style,
112
+ precondition: pre.precondition,
113
+ createParents: false,
114
+ record: pre.record,
115
+ userModified: false,
116
+ rematchedAfterStale: pre.mustRematch,
117
+ matches,
118
+ snippets: buildSnippets(afterIndex, spans, limits),
119
+ };
120
+ }
121
+ function matchPair(scope, input, target, text, pair, index) {
122
+ const { messages, limits } = scope.deps;
123
+ const path = target.requestedPath;
124
+ const listed = limits.maxListedMatches;
125
+ const maxMatches = pair.replaceAll ? REPLACE_ALL_CAP + 1 : listed + 1;
126
+ const chain = runChain(scope, input.matchers, text, pair.oldText, {
127
+ mode: "text",
128
+ from: 0,
129
+ maxMatches,
130
+ });
131
+ if (chain === null) {
132
+ if (input.recovery && isAlreadyApplied(text, pair.newText))
133
+ return "applied";
134
+ throw noMatchFailure(scope, input, target, text, pair, index);
135
+ }
136
+ const { matcher, ranges } = chain;
137
+ const refuse = (reason) => scope.stop("MATCH_REFUSED", messages.matchRefused({ path, index, matcher: matcher.id, reason }), {
138
+ index,
139
+ matcher: matcher.id,
140
+ reason,
141
+ });
142
+ if (ranges.length > 1 && !pair.replaceAll) {
143
+ const total = ranges.length > listed
144
+ ? findWith(scope, matcher, text, pair.oldText, {
145
+ mode: "text",
146
+ from: 0,
147
+ maxMatches: REPLACE_ALL_CAP,
148
+ }).length
149
+ : ranges.length;
150
+ const lines = new LineIndex(text);
151
+ const shown = ranges.slice(0, listed).map((range) => lines.lineOf(range.start));
152
+ throw scope.stop("AMBIGUOUS_MATCH", messages.ambiguousMatch({ path, index, lines: shown, total }), {
153
+ index,
154
+ lines: shown,
155
+ total,
156
+ });
157
+ }
158
+ if (ranges.length > 1 && matcher.fuzzy)
159
+ throw refuse("fuzzy-replace-all");
160
+ if (ranges.length > REPLACE_ALL_CAP)
161
+ throw refuse("too-many");
162
+ const hits = ranges.map((range) => {
163
+ if (range.refused === "boundary")
164
+ throw refuse("boundary");
165
+ if (matcher.fuzzy && tooWide(range, pair.oldText))
166
+ throw refuse("span");
167
+ const replacement = adaptFor(scope, matcher, pair.newText, {
168
+ haystack: text,
169
+ needle: pair.oldText,
170
+ range,
171
+ });
172
+ if (matcher.fuzzy && escapeDrift(replacement, text.slice(range.start, range.end))) {
173
+ throw refuse("escape");
174
+ }
175
+ return { start: range.start, end: range.end, text: replacement };
176
+ });
177
+ return { index, matcher, hits };
178
+ }
179
+ function rematchAfterStale(scope, text, pair, index, path) {
180
+ const ranges = findWith(scope, STALE_REMATCH_MATCHER, text, pair.oldText, {
181
+ mode: "text",
182
+ from: 0,
183
+ maxMatches: pair.replaceAll ? REPLACE_ALL_CAP + 1 : 2,
184
+ });
185
+ const once = pair.replaceAll ? ranges.length <= REPLACE_ALL_CAP : ranges.length === 1;
186
+ if (ranges.length === 0 || !once) {
187
+ scope.enter("precondition");
188
+ throw scope.stop("STALE", scope.deps.messages.stale({ tool: "edit", path }), { index });
189
+ }
190
+ return {
191
+ index,
192
+ matcher: STALE_REMATCH_MATCHER,
193
+ hits: ranges.map((range) => ({ start: range.start, end: range.end, text: pair.newText })),
194
+ };
195
+ }
196
+ function noMatchFailure(scope, input, target, text, pair, index) {
197
+ const { messages, limits } = scope.deps;
198
+ const path = target.requestedPath;
199
+ const newline = trailingNewline(text, pair.oldText);
200
+ const closest = input.recovery ? closestRegion(text, pair.oldText, limits.maxHintLines) : null;
201
+ const misses = input.recovery ? input.misses.miss(target.resolvedPath) : 0;
202
+ if (misses >= 3) {
203
+ scope.notes.push({
204
+ code: "repeated-miss",
205
+ severity: "info",
206
+ message: messages.repeatedMiss({ path, misses }),
207
+ data: { misses },
208
+ });
209
+ }
210
+ return scope.stop("NO_MATCH", messages.noMatch({ path, index, closest: closest?.text ?? null, trailingNewline: newline }), {
211
+ index,
212
+ ...(newline === null ? {} : { trailingNewline: newline }),
213
+ ...(closest === null ? {} : { closest: [...closest.lines] }),
214
+ });
215
+ }