@mwillbanks/ast-mcp 0.2.1 → 0.3.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 (59) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -14
  3. package/dist/ast-mcp.js +183 -137
  4. package/dist/ast-mcp.js.map +58 -42
  5. package/package.json +17 -11
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/tools.json +22 -2
  8. package/src/cli.ts +10 -7
  9. package/src/config-cli.ts +166 -19
  10. package/src/config-migrate.ts +223 -0
  11. package/src/config-registry.ts +321 -0
  12. package/src/config-schema-common.ts +81 -0
  13. package/src/config-v2-schema.ts +97 -0
  14. package/src/config.ts +375 -149
  15. package/src/helpers/ast-bro.ts +1 -7
  16. package/src/helpers/config.ts +12 -3
  17. package/src/helpers/installer.ts +8 -0
  18. package/src/helpers/mcp-schema.ts +105 -4
  19. package/src/host-smoke.ts +182 -0
  20. package/src/http.ts +8 -3
  21. package/src/installer-transport.ts +6 -4
  22. package/src/installer.ts +192 -51
  23. package/src/patch/engine.ts +555 -279
  24. package/src/patch/languages.ts +9 -0
  25. package/src/patch/strategy/aiderBlock.ts +110 -0
  26. package/src/patch/strategy/ast.ts +170 -0
  27. package/src/patch/strategy.ts +61 -0
  28. package/src/runtime/approval.ts +438 -0
  29. package/src/runtime/dependencies.ts +1 -1
  30. package/src/runtime/document-inspection.ts +78 -0
  31. package/src/runtime/file-capabilities.ts +250 -0
  32. package/src/runtime/file-delete.ts +122 -20
  33. package/src/runtime/file-read.ts +142 -14
  34. package/src/runtime/file-rename.ts +7 -6
  35. package/src/runtime/format.ts +65 -27
  36. package/src/runtime/path-policy.ts +557 -0
  37. package/src/runtime/path-utils.ts +40 -0
  38. package/src/runtime/paths.ts +204 -43
  39. package/src/server.ts +2 -1
  40. package/src/tools/ast-bro.ts +197 -76
  41. package/src/tools/configuration.ts +450 -0
  42. package/src/tools/configured.ts +49 -21
  43. package/src/tools/files.ts +177 -73
  44. package/src/tools/index.ts +2 -0
  45. package/src/tools/lifecycle.ts +89 -45
  46. package/templates/AGENTS.md +15 -17
  47. package/templates/skills/ast-mcp/SKILL.md +50 -34
  48. package/templates/skills/ast-mcp/evals/batch.evals.json +9 -9
  49. package/templates/skills/ast-mcp/evals/evals.json +221 -9
  50. package/templates/skills/ast-mcp/evals/measure.ts +27 -4
  51. package/templates/skills/ast-mcp/evals/score.test.ts +46 -3
  52. package/templates/skills/ast-mcp/evals/score.ts +87 -0
  53. package/templates/skills/ast-mcp/evals/semantic.test.ts +209 -28
  54. package/templates/skills/ast-mcp/evals/semantic.ts +151 -37
  55. package/templates/skills/ast-mcp/references/installation.md +12 -12
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +16 -10
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +8 -17
  59. package/src/ast-bro/rewrite-capability.ts +0 -9
@@ -5,37 +5,38 @@ import {
5
5
  mkdir,
6
6
  readFile,
7
7
  rename,
8
+ rmdir,
8
9
  unlink,
9
10
  writeFile,
10
11
  } from "node:fs/promises";
11
12
  import path from "node:path";
12
- import { callAstBro } from "../ast-bro/client";
13
- import { parseAstBroJson } from "../ast-bro/result";
14
- import { astRewritable } from "../ast-bro/rewrite-capability";
13
+ import { currentConfig } from "../config";
14
+ import { approvalSessionId } from "../runtime/approval";
15
15
  import {
16
16
  applyFileChattr,
17
17
  type FileChattr,
18
18
  resultingFileChattr,
19
+ validateFileChattr,
19
20
  } from "../runtime/attributes";
21
+ import {
22
+ type FileCapabilities,
23
+ inspectFileCapabilities,
24
+ validateStructuredCandidate,
25
+ } from "../runtime/file-capabilities";
20
26
  import { FILE_READ_MAX_BATCH } from "../runtime/file-read";
21
27
  import { formatContent } from "../runtime/format";
22
28
  import { sha256 } from "../runtime/hash";
23
- import { withFileLock } from "../runtime/locks";
29
+ import { withFileLock, withFileLocks } from "../runtime/locks";
24
30
  import { resolveWritablePath } from "../runtime/paths";
25
31
  import { requireExpectedHash, verifyExpectedHash } from "../runtime/policy";
32
+ import {
33
+ type AiderBlock,
34
+ type AstRule,
35
+ type PatchStrategyContext,
36
+ type PatchStrategyMetadata,
37
+ patchStrategyAdapter,
38
+ } from "./strategy";
26
39
 
27
- import { applyAiderBlock } from "./aider";
28
- import { detectAstLanguage } from "./languages";
29
-
30
- export interface AstRule {
31
- expectedMatches?: number;
32
- fix: string;
33
- pattern: string;
34
- }
35
- export interface AiderBlock {
36
- replace: string;
37
- search: string;
38
- }
39
40
  export interface PatchRequest {
40
41
  aiderBlock?: AiderBlock;
41
42
  astRule?: AstRule;
@@ -50,8 +51,9 @@ export interface PatchBatchRequest {
50
51
  astRules?: AstRule[];
51
52
  chattr?: FileChattr;
52
53
  expectedSha256?: string;
53
- patchStrategy: "ast" | "aider_block";
54
+ patchStrategy?: "ast" | "aider_block";
54
55
  preview?: boolean;
56
+ previewReceipt?: string;
55
57
  }
56
58
 
57
59
  export type PatchBatch = Record<string, PatchBatchRequest>;
@@ -95,26 +97,46 @@ async function ensureParent(filePath: string): Promise<string[]> {
95
97
  return created;
96
98
  }
97
99
 
100
+ async function ignoreFailure(operation: Promise<unknown>): Promise<void> {
101
+ try {
102
+ await operation;
103
+ } catch {}
104
+ }
105
+
106
+ async function removeCreatedDirectories(directories: string[]): Promise<void> {
107
+ for (const directory of [...directories].reverse())
108
+ await ignoreFailure(rmdir(directory));
109
+ }
110
+
98
111
  async function commit(
99
112
  filePath: string,
100
113
  content: string,
101
114
  mode?: number,
102
115
  expectedSha256?: string,
103
116
  chattr?: FileChattr,
104
- ): Promise<string[]> {
117
+ alreadyFormatted = false,
118
+ ): Promise<{
119
+ chattr: Awaited<ReturnType<typeof resultingFileChattr>>;
120
+ createdDirectories: string[];
121
+ sha256: string;
122
+ }> {
105
123
  const next = temporary(filePath);
106
124
  let createdDirectories: string[] = [];
125
+ let committed = false;
107
126
  try {
108
- const formatted = await formatContent(filePath, content);
109
- try {
110
- await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
111
- } catch (error) {
112
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
113
- createdDirectories = await ensureParent(filePath);
114
- await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
115
- }
127
+ const parentExists = await lstat(path.dirname(filePath)).then(
128
+ () => true,
129
+ () => false,
130
+ );
131
+ createdDirectories = parentExists ? [] : await ensureParent(filePath);
132
+ const formatted = alreadyFormatted
133
+ ? content
134
+ : await formatContent(filePath, content);
135
+ await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
116
136
  if (mode !== undefined) await chmod(next, mode);
117
137
  await applyFileChattr(next, chattr);
138
+ const committedChattr = await resultingFileChattr(next);
139
+ const committedSha256 = sha256(formatted);
118
140
  if (expectedSha256) {
119
141
  const current = await readFile(filePath, "utf8");
120
142
  const actual = sha256(current);
@@ -124,9 +146,15 @@ async function commit(
124
146
  );
125
147
  }
126
148
  await rename(next, filePath);
127
- return createdDirectories;
149
+ committed = true;
150
+ return {
151
+ chattr: committedChattr,
152
+ createdDirectories,
153
+ sha256: committedSha256,
154
+ };
128
155
  } finally {
129
156
  await removeTemporary(next);
157
+ if (!committed) await removeCreatedDirectories(createdDirectories);
130
158
  }
131
159
  }
132
160
  function previewDiff(filePath: string, before: string, after: string): string {
@@ -162,22 +190,112 @@ function previewDiff(filePath: string, before: string, after: string): string {
162
190
  : lines.join("\n");
163
191
  }
164
192
 
165
- interface PatchContext {
193
+ interface PatchContext extends PatchStrategyContext {
166
194
  actual: string;
167
- aiderBlocks: AiderBlock[];
168
- astRules: AstRule[];
169
- filePath: string;
170
- language: ReturnType<typeof detectAstLanguage>;
171
- original: string;
195
+ capabilities: FileCapabilities;
172
196
  request: PatchBatchRequest;
173
- rewritable: boolean;
174
197
  }
175
198
 
176
- interface PreviewMetadata {
177
- matches?: number;
178
- matchMethods?: string[];
179
- operations: number;
180
- strategy: "ast" | "aider_block";
199
+ type PreviewMetadata = PatchStrategyMetadata;
200
+
201
+ interface PreviewReceipt {
202
+ candidate: string;
203
+ candidateSha256: string;
204
+ chattr?: FileChattr;
205
+ configurationIdentity: string;
206
+ expiresAt: number;
207
+ expiryTimer: ReturnType<typeof setTimeout>;
208
+ filePath: string;
209
+ generation: number;
210
+ metadata: PreviewMetadata;
211
+ normalizedOperations: Pick<
212
+ PatchBatchRequest,
213
+ "aiderBlocks" | "astRules" | "chattr" | "patchStrategy"
214
+ >;
215
+ payloadBytes: number;
216
+ sessionId: string;
217
+ sourceSha256: string;
218
+ }
219
+
220
+ const PREVIEW_RECEIPT_TTL_MS = 5 * 60 * 1000;
221
+ const previewConfigurationIdentity = (
222
+ config: Awaited<ReturnType<typeof currentConfig>>,
223
+ ) =>
224
+ sha256(
225
+ JSON.stringify({
226
+ dependencies: config.dependencies,
227
+ formatting: config.formatting,
228
+ projectRoot: config.projectRoot,
229
+ safety: config.safety,
230
+ sources: config.sources,
231
+ trustedRoots: config.trustedRoots,
232
+ version: config.version,
233
+ workspace: config.workspace,
234
+ }),
235
+ );
236
+ const MAX_PREVIEW_CANDIDATE_BYTES = 4 * 1024 * 1024;
237
+ const MAX_PREVIEW_SESSION_BYTES = 16 * 1024 * 1024;
238
+ const MAX_PREVIEW_SESSION_RECEIPTS = 32;
239
+ const previewReceipts = new Map<string, PreviewReceipt>();
240
+
241
+ function previewPayloadBytes(
242
+ sessionId: string,
243
+ candidate: string,
244
+ operations: PreviewReceipt["normalizedOperations"],
245
+ ): number {
246
+ const candidateBytes = Buffer.byteLength(candidate);
247
+ const payloadBytes =
248
+ candidateBytes + Buffer.byteLength(JSON.stringify(operations));
249
+ const outstanding = [...previewReceipts.values()].filter(
250
+ (receipt) => receipt.sessionId === sessionId,
251
+ );
252
+ const retainedBytes = outstanding.reduce(
253
+ (total, receipt) => total + receipt.payloadBytes,
254
+ 0,
255
+ );
256
+ if (
257
+ candidateBytes > MAX_PREVIEW_CANDIDATE_BYTES ||
258
+ outstanding.length >= MAX_PREVIEW_SESSION_RECEIPTS ||
259
+ retainedBytes + payloadBytes > MAX_PREVIEW_SESSION_BYTES
260
+ )
261
+ throw Object.assign(
262
+ new Error(
263
+ "Preview receipt storage limit exceeded; narrow the patch or commit/discard outstanding previews",
264
+ ),
265
+ { code: "preview_receipt_limit", retryable: true },
266
+ );
267
+ return payloadBytes;
268
+ }
269
+
270
+ async function validatePreviewReceipt(filePath: string, token: string) {
271
+ const receipt = previewReceipts.get(token);
272
+ if (!receipt)
273
+ throw new Error("Preview receipt is unknown or has already been used");
274
+ if (receipt.expiresAt < Date.now()) {
275
+ previewReceipts.delete(token);
276
+ clearTimeout(receipt.expiryTimer);
277
+ throw new Error("Preview receipt has expired; preview the patch again");
278
+ }
279
+ if (receipt.filePath !== filePath)
280
+ throw new Error("Preview receipt does not belong to this file");
281
+ if (receipt.sessionId !== approvalSessionId())
282
+ throw new Error("Preview receipt belongs to a different MCP session");
283
+ const config = await currentConfig();
284
+ if (
285
+ receipt.generation !== config.generation ||
286
+ receipt.configurationIdentity !== previewConfigurationIdentity(config)
287
+ )
288
+ throw new Error("Preview receipt is stale because configuration changed");
289
+ await resolveWritablePath(filePath);
290
+ const source = await readFile(filePath, "utf8");
291
+ const actual = sha256(source);
292
+ if (actual !== receipt.sourceSha256)
293
+ throw new Error(
294
+ `Stale file context: expected ${receipt.sourceSha256}, found ${actual}`,
295
+ );
296
+ if (sha256(receipt.candidate) !== receipt.candidateSha256)
297
+ throw new Error("Preview receipt candidate integrity check failed");
298
+ return receipt;
181
299
  }
182
300
 
183
301
  async function createPatchContext(
@@ -188,25 +306,60 @@ async function createPatchContext(
188
306
  const actual = sha256(original);
189
307
  await requireExpectedHash(request.expectedSha256, "file_patch");
190
308
  verifyExpectedHash(request.expectedSha256, actual);
191
- const language = detectAstLanguage(filePath);
309
+ const capabilities = await inspectFileCapabilities(filePath);
192
310
  return {
193
311
  actual,
194
312
  aiderBlocks: request.aiderBlocks ?? [],
195
313
  astRules: request.astRules ?? [],
314
+ capabilities,
196
315
  filePath,
197
- language,
316
+ language: capabilities.language,
317
+ mode: (await lstat(filePath)).mode,
198
318
  original,
199
319
  request,
200
- rewritable: await astRewritable(filePath, language),
201
320
  };
202
321
  }
203
322
 
204
323
  async function patchPreview(
205
324
  context: PatchContext,
206
- candidate: string,
325
+ formatted: string,
207
326
  metadata: PreviewMetadata,
208
327
  ) {
209
- const formatted = await formatContent(context.filePath, candidate);
328
+ const config = await currentConfig();
329
+ const receipt = randomUUID();
330
+ const expiresAt = Date.now() + PREVIEW_RECEIPT_TTL_MS;
331
+ const sessionId = approvalSessionId();
332
+ const normalizedOperations = {
333
+ aiderBlocks: context.request.aiderBlocks,
334
+ astRules: context.request.astRules,
335
+ chattr: context.request.chattr,
336
+ patchStrategy: context.request.patchStrategy,
337
+ };
338
+ const payloadBytes = previewPayloadBytes(
339
+ sessionId,
340
+ formatted,
341
+ normalizedOperations,
342
+ );
343
+ const expiryTimer = setTimeout(
344
+ previewReceipts.delete.bind(previewReceipts, receipt),
345
+ PREVIEW_RECEIPT_TTL_MS,
346
+ );
347
+ expiryTimer.unref?.();
348
+ previewReceipts.set(receipt, {
349
+ candidate: formatted,
350
+ candidateSha256: sha256(formatted),
351
+ chattr: context.request.chattr,
352
+ configurationIdentity: previewConfigurationIdentity(config),
353
+ expiresAt,
354
+ expiryTimer,
355
+ filePath: context.filePath,
356
+ generation: config.generation,
357
+ metadata,
358
+ normalizedOperations,
359
+ payloadBytes,
360
+ sessionId,
361
+ sourceSha256: context.actual,
362
+ });
210
363
  return {
211
364
  changed: formatted !== context.original,
212
365
  diff: previewDiff(context.filePath, context.original, formatted),
@@ -215,250 +368,400 @@ async function patchPreview(
215
368
  matchMethods: metadata.matchMethods,
216
369
  operations: metadata.operations,
217
370
  preview: true,
371
+ previewReceipt: receipt,
372
+ receiptExpiresAt: new Date(expiresAt).toISOString(),
218
373
  sha256: sha256(formatted),
219
374
  strategy: metadata.strategy,
220
375
  };
221
376
  }
222
377
 
223
- function validateAstStrategy(
224
- context: PatchContext,
225
- ): asserts context is PatchContext & {
226
- language: NonNullable<PatchContext["language"]>;
227
- } {
228
- if (!context.rewritable || !context.language)
229
- throw new Error(
230
- "REJECTED: non-structurally-rewritable files require patchStrategy 'aider_block' with aiderBlocks",
231
- );
232
- if (context.astRules.length === 0 || context.aiderBlocks.length > 0)
233
- throw new Error(
234
- "REJECTED: patchStrategy 'ast' requires astRules and no aiderBlocks",
378
+ async function prepareFormattedStrategyPatch(context: PatchContext) {
379
+ const prepared = await patchStrategyAdapter(
380
+ context.request.patchStrategy,
381
+ ).prepare(context);
382
+ const candidate = await formatContent(context.filePath, prepared.candidate);
383
+ await validateStructuredCandidate(context.capabilities, candidate);
384
+ return { candidate, metadata: prepared.metadata };
385
+ }
386
+
387
+ async function applyLockedPatch(filePath: string, request: PatchBatchRequest) {
388
+ if (request.previewReceipt)
389
+ return applyPreparedPatch(
390
+ filePath,
391
+ request,
392
+ await preflightPatchBatch(filePath, request),
235
393
  );
394
+ const context = await createPatchContext(filePath, request);
395
+ const prepared = await prepareFormattedStrategyPatch(context);
396
+ if (request.preview)
397
+ return patchPreview(context, prepared.candidate, prepared.metadata);
398
+ await commit(
399
+ filePath,
400
+ prepared.candidate,
401
+ context.mode,
402
+ context.actual,
403
+ request.chattr,
404
+ true,
405
+ );
406
+ return {
407
+ ...prepared.metadata,
408
+ filePath,
409
+ preview: false,
410
+ sha256: sha256(prepared.candidate),
411
+ };
236
412
  }
237
413
 
238
- type AstPatchContext = PatchContext & {
239
- language: NonNullable<PatchContext["language"]>;
240
- };
414
+ async function applyPatchBatch(
415
+ filePath: string,
416
+ request: PatchBatchRequest,
417
+ ): Promise<Record<string, unknown>> {
418
+ return withFileLock(filePath, () => applyLockedPatch(filePath, request));
419
+ }
241
420
 
242
- async function previewAstRule(
243
- context: AstPatchContext,
244
- next: string,
245
- rule: AstRule,
246
- ) {
247
- const preview = parseAstBroJson(
248
- await callAstBro(
249
- "run",
250
- {
251
- json: true,
252
- lang: context.language,
253
- paths: [next],
254
- pattern: rule.pattern,
255
- },
256
- path.dirname(context.filePath),
257
- ),
258
- );
259
- if (preview.error_count)
260
- throw new Error(
261
- `ast-bro preview failed with ${preview.error_count} errors`,
262
- );
263
- const matches = Array.isArray(preview.matches) ? preview.matches.length : 0;
264
- const expected = rule.expectedMatches ?? 1;
265
- if (matches !== expected)
266
- throw new Error(`AST rule matched ${matches} nodes; expected ${expected}`);
267
- if (expected !== 1)
268
- throw new Error(
269
- "ast-bro run rewrites only the first match per file; narrow the AST rule to exactly one node",
270
- );
271
- return matches;
421
+ export async function patchFile(
422
+ request: PatchRequest,
423
+ ): Promise<Record<string, unknown>> {
424
+ return applyPatchBatch(await resolveWritablePath(request.filePath), {
425
+ aiderBlocks: request.aiderBlock ? [request.aiderBlock] : undefined,
426
+ astRules: request.astRule ? [request.astRule] : undefined,
427
+ expectedSha256: request.expectedSha256,
428
+ patchStrategy: request.patchStrategy,
429
+ preview: request.preview,
430
+ });
272
431
  }
273
432
 
274
- async function rewriteAstRule(
275
- context: AstPatchContext,
276
- next: string,
277
- rule: AstRule,
278
- ) {
279
- const rewritten = parseAstBroJson(
280
- await callAstBro(
281
- "run",
282
- {
283
- json: true,
284
- lang: context.language,
285
- paths: [next],
286
- pattern: rule.pattern,
287
- rewrite: rule.fix,
288
- write: true,
289
- },
290
- path.dirname(context.filePath),
291
- ),
292
- );
293
- if (
294
- rewritten.error_count ||
295
- rewritten.rewrite_count !== 1 ||
296
- rewritten.files?.[0]?.status !== "rewritten"
297
- )
298
- throw new Error("ast-bro run did not rewrite exactly one file");
433
+ interface PreparedPatch {
434
+ candidate?: string;
435
+ chattr?: FileChattr;
436
+ mode?: number;
437
+ previewResult?: Record<string, unknown>;
438
+ receiptToken?: string;
439
+ result?: Record<string, unknown>;
440
+ sourceSha256?: string;
299
441
  }
300
442
 
301
- async function applyAstRules(context: AstPatchContext, next: string) {
302
- let totalMatches = 0;
303
- for (const rule of context.astRules) {
304
- totalMatches += await previewAstRule(context, next, rule);
305
- await rewriteAstRule(context, next, rule);
443
+ async function preflightPatchBatch(
444
+ filePath: string,
445
+ request: PatchBatchRequest,
446
+ ): Promise<PreparedPatch> {
447
+ if (request.preview)
448
+ return { previewResult: await applyLockedPatch(filePath, request) };
449
+ if (request.previewReceipt) {
450
+ const receipt = await validatePreviewReceipt(
451
+ filePath,
452
+ request.previewReceipt,
453
+ );
454
+ return {
455
+ candidate: receipt.candidate,
456
+ chattr: receipt.chattr,
457
+ mode: (await lstat(filePath)).mode,
458
+ receiptToken: request.previewReceipt,
459
+ result: {
460
+ filePath,
461
+ matches: receipt.metadata.matches,
462
+ matchMethods: receipt.metadata.matchMethods,
463
+ operations: receipt.metadata.operations,
464
+ preview: false,
465
+ receiptCommitted: true,
466
+ sha256: receipt.candidateSha256,
467
+ strategy: receipt.metadata.strategy,
468
+ },
469
+ sourceSha256: receipt.sourceSha256,
470
+ };
306
471
  }
307
- return totalMatches;
472
+
473
+ const context = await createPatchContext(filePath, request);
474
+ const prepared = await prepareFormattedStrategyPatch(context);
475
+ return {
476
+ candidate: prepared.candidate,
477
+ chattr: request.chattr,
478
+ mode: context.mode,
479
+ result: {
480
+ ...prepared.metadata,
481
+ filePath,
482
+ preview: false,
483
+ sha256: sha256(prepared.candidate),
484
+ },
485
+ sourceSha256: context.actual,
486
+ };
308
487
  }
309
488
 
310
- async function astPatchResult(
311
- context: AstPatchContext,
312
- candidate: string,
313
- mode: number,
314
- totalMatches: number,
315
- ) {
316
- if (context.request.preview)
317
- return patchPreview(context, candidate, {
318
- matches: totalMatches,
319
- operations: context.astRules.length,
320
- strategy: "ast",
321
- });
489
+ async function applyPreparedPatch(
490
+ filePath: string,
491
+ _request: PatchBatchRequest,
492
+ prepared: PreparedPatch,
493
+ ): Promise<Record<string, unknown>> {
494
+ if (prepared.previewResult) return prepared.previewResult;
495
+ if (
496
+ prepared.candidate === undefined ||
497
+ prepared.mode === undefined ||
498
+ !prepared.result ||
499
+ prepared.sourceSha256 === undefined
500
+ )
501
+ throw new Error("Patch batch preflight did not produce a commit candidate");
502
+ if (prepared.receiptToken) {
503
+ const receipt = previewReceipts.get(prepared.receiptToken);
504
+ if (receipt) clearTimeout(receipt.expiryTimer);
505
+ previewReceipts.delete(prepared.receiptToken);
506
+ }
322
507
  await commit(
323
- context.filePath,
324
- candidate,
325
- mode,
326
- context.actual,
327
- context.request.chattr,
508
+ filePath,
509
+ prepared.candidate,
510
+ prepared.mode,
511
+ prepared.sourceSha256,
512
+ prepared.chattr,
513
+ true,
328
514
  );
329
- const updated = await readFile(context.filePath, "utf8");
330
- return {
331
- engine: "ast-bro.run",
332
- filePath: context.filePath,
333
- matches: totalMatches,
334
- operations: context.astRules.length,
335
- preview: false,
336
- sha256: sha256(updated),
337
- strategy: "ast",
338
- };
515
+ return prepared.result;
516
+ }
517
+
518
+ interface PreparedWrite {
519
+ actual?: string;
520
+ content: string;
521
+ existing: boolean;
522
+ mode?: number;
339
523
  }
340
524
 
341
- async function applyAstPatch(context: PatchContext) {
342
- validateAstStrategy(context);
343
- const next = temporary(context.filePath);
344
- const metadata = await lstat(context.filePath);
525
+ async function preflightFileWrite(
526
+ filePath: string,
527
+ request: FileWriteRequest,
528
+ ): Promise<PreparedWrite> {
529
+ validateFileChattr(request.chattr);
530
+ const existing = await readFile(filePath, "utf8").catch(() => undefined);
531
+ let actual: string | undefined;
532
+ let mode: number | undefined;
533
+ if (existing !== undefined) {
534
+ await requireExpectedHash(request.expectedSha256, "file_write overwrite");
535
+ actual = sha256(existing);
536
+ verifyExpectedHash(request.expectedSha256, actual);
537
+ const capabilities = await inspectFileCapabilities(filePath);
538
+ if (capabilities.effective.patch.includes("ast"))
539
+ throw new Error(
540
+ "REJECTED: structurally rewritable existing files require file_patch with patchStrategy 'ast'",
541
+ );
542
+ mode = (await lstat(filePath)).mode;
543
+ }
544
+ const parentExists = await lstat(path.dirname(filePath)).then(
545
+ () => true,
546
+ () => false,
547
+ );
548
+ const createdDirectories = parentExists ? [] : await ensureParent(filePath);
345
549
  try {
346
- await writeFile(next, context.original, {
347
- encoding: "utf8",
348
- flag: "wx",
349
- mode: metadata.mode,
350
- });
351
- const totalMatches = await applyAstRules(context, next);
352
- const candidate = await readFile(next, "utf8");
353
- return await astPatchResult(
354
- context,
355
- candidate,
356
- metadata.mode,
357
- totalMatches,
358
- );
550
+ return {
551
+ actual,
552
+ content: await formatContent(filePath, request.content),
553
+ existing: existing !== undefined,
554
+ mode,
555
+ };
359
556
  } finally {
360
- await removeTemporary(next);
557
+ await removeCreatedDirectories(createdDirectories);
361
558
  }
362
559
  }
363
560
 
364
- function validateAiderStrategy(context: PatchContext) {
365
- if (context.rewritable)
366
- throw new Error(
367
- "REJECTED: structurally rewritable files require patchStrategy 'ast' with astRules",
368
- );
369
- if (context.aiderBlocks.length === 0 || context.astRules.length > 0)
370
- throw new Error(
371
- "REJECTED: patchStrategy 'aider_block' requires aiderBlocks and no astRules",
372
- );
561
+ interface ResolvedBatchEntry<T> {
562
+ inputPath: string;
563
+ request: T;
564
+ resolvedPath: string;
565
+ }
566
+
567
+ type BatchFileSnapshot =
568
+ | undefined
569
+ | {
570
+ chattr: Awaited<ReturnType<typeof resultingFileChattr>>;
571
+ content: string;
572
+ mode: number;
573
+ };
574
+
575
+ interface CommittedBatchEntry {
576
+ resolvedPath: string;
577
+ result: Record<string, unknown>;
373
578
  }
374
579
 
375
- function applyAiderBlocks(content: string, blocks: AiderBlock[]) {
376
- const methods: string[] = [];
377
- for (const block of blocks) {
378
- const result = applyAiderBlock(content, block.search, block.replace);
379
- content = result.content;
380
- methods.push(result.method);
580
+ async function optionalContent(filePath: string): Promise<string | undefined> {
581
+ try {
582
+ return await readFile(filePath, "utf8");
583
+ } catch {
584
+ return undefined;
381
585
  }
382
- return { content, methods };
383
586
  }
384
587
 
385
- async function applyAiderPatch(context: PatchContext) {
386
- validateAiderStrategy(context);
387
- const { content, methods } = applyAiderBlocks(
388
- context.original,
389
- context.aiderBlocks,
390
- );
391
- if (context.request.preview)
392
- return patchPreview(context, content, {
393
- matchMethods: methods,
394
- operations: context.aiderBlocks.length,
395
- strategy: "aider_block",
396
- });
397
- await commit(
398
- context.filePath,
399
- content,
400
- (await lstat(context.filePath)).mode,
401
- context.actual,
402
- context.request.chattr,
403
- );
404
- const updated = await readFile(context.filePath, "utf8");
405
- return {
406
- filePath: context.filePath,
407
- matchMethods: methods,
408
- operations: context.aiderBlocks.length,
409
- preview: false,
410
- sha256: sha256(updated),
411
- strategy: "aider_block",
412
- };
588
+ async function captureBatchSnapshots<T>(
589
+ entries: ResolvedBatchEntry<T>[],
590
+ ): Promise<Map<string, BatchFileSnapshot>> {
591
+ const snapshots = new Map<string, BatchFileSnapshot>();
592
+ for (const { resolvedPath } of entries) {
593
+ const content = await optionalContent(resolvedPath);
594
+ snapshots.set(
595
+ resolvedPath,
596
+ content === undefined
597
+ ? undefined
598
+ : {
599
+ chattr: await resultingFileChattr(resolvedPath),
600
+ content,
601
+ mode: (await lstat(resolvedPath)).mode,
602
+ },
603
+ );
604
+ }
605
+ return snapshots;
413
606
  }
414
607
 
415
- async function applyLockedPatch(filePath: string, request: PatchBatchRequest) {
416
- const context = await createPatchContext(filePath, request);
417
- return request.patchStrategy === "ast"
418
- ? applyAstPatch(context)
419
- : applyAiderPatch(context);
608
+ function discardPreparedPreviews<Prepared>(prepared: Prepared[]): void {
609
+ for (const item of prepared) {
610
+ const token = (item as PreparedPatch).previewResult?.previewReceipt;
611
+ if (typeof token !== "string") continue;
612
+ const receipt = previewReceipts.get(token);
613
+ if (receipt) clearTimeout(receipt.expiryTimer);
614
+ previewReceipts.delete(token);
615
+ }
420
616
  }
421
617
 
422
- async function applyPatchBatch(
423
- inputPath: string,
424
- request: PatchBatchRequest,
425
- ): Promise<Record<string, unknown>> {
426
- const filePath = await resolveWritablePath(inputPath);
427
- return withFileLock(filePath, () => applyLockedPatch(filePath, request));
618
+ async function prepareFileBatch<T, Prepared>(
619
+ entries: ResolvedBatchEntry<T>[],
620
+ preflight: (filePath: string, request: T) => Promise<Prepared>,
621
+ ): Promise<Prepared[]> {
622
+ const prepared: Prepared[] = [];
623
+ try {
624
+ for (const { request, resolvedPath } of entries)
625
+ prepared.push(await preflight(resolvedPath, request));
626
+ return prepared;
627
+ } catch (error) {
628
+ discardPreparedPreviews(prepared);
629
+ throw error;
630
+ }
428
631
  }
429
632
 
430
- export async function patchFile(
431
- request: PatchRequest,
633
+ async function rollbackFileBatch(
634
+ committed: CommittedBatchEntry[],
635
+ snapshots: Map<string, BatchFileSnapshot>,
636
+ ): Promise<void> {
637
+ for (const { resolvedPath, result } of committed.reverse()) {
638
+ const snapshot = snapshots.get(resolvedPath);
639
+ if (snapshot) {
640
+ await ignoreFailure(
641
+ commit(
642
+ resolvedPath,
643
+ snapshot.content,
644
+ snapshot.mode,
645
+ undefined,
646
+ snapshot.chattr,
647
+ true,
648
+ ),
649
+ );
650
+ continue;
651
+ }
652
+ await ignoreFailure(unlink(resolvedPath));
653
+ const createdDirectories = result.createdDirectories;
654
+ if (Array.isArray(createdDirectories))
655
+ await removeCreatedDirectories(
656
+ createdDirectories.filter(
657
+ (value): value is string => typeof value === "string",
658
+ ),
659
+ );
660
+ }
661
+ }
662
+
663
+ async function executePreparedFileBatch<T, Prepared>(
664
+ entries: ResolvedBatchEntry<T>[],
665
+ handler: (
666
+ filePath: string,
667
+ request: T,
668
+ prepared: Prepared,
669
+ ) => Promise<Record<string, unknown>>,
670
+ preflight: (filePath: string, request: T) => Promise<Prepared>,
671
+ mutates: (request: T) => boolean,
432
672
  ): Promise<Record<string, unknown>> {
433
- return applyPatchBatch(request.filePath, {
434
- aiderBlocks: request.aiderBlock ? [request.aiderBlock] : undefined,
435
- astRules: request.astRule ? [request.astRule] : undefined,
436
- expectedSha256: request.expectedSha256,
437
- patchStrategy: request.patchStrategy,
438
- preview: request.preview,
439
- });
673
+ const snapshots = await captureBatchSnapshots(entries);
674
+ const prepared = await prepareFileBatch(entries, preflight);
675
+ const files: Record<string, unknown> = {};
676
+ const committed: CommittedBatchEntry[] = [];
677
+ try {
678
+ for (const [
679
+ index,
680
+ { inputPath, request, resolvedPath },
681
+ ] of entries.entries()) {
682
+ const result = await handler(
683
+ resolvedPath,
684
+ request,
685
+ prepared[index] as Prepared,
686
+ );
687
+ files[inputPath] = result;
688
+ if (mutates(request)) committed.push({ resolvedPath, result });
689
+ }
690
+ return { files };
691
+ } catch (error) {
692
+ discardPreparedPreviews(prepared);
693
+ await rollbackFileBatch(committed, snapshots);
694
+ throw error;
695
+ }
440
696
  }
441
697
 
442
- async function processFileBatch<T>(
698
+ async function processFileBatch<T, Prepared>(
443
699
  tool: "file_patch" | "file_write",
444
700
  requests: Record<string, T>,
445
- handler: (filePath: string, request: T) => Promise<Record<string, unknown>>,
701
+ handler: (
702
+ filePath: string,
703
+ request: T,
704
+ prepared: Prepared,
705
+ ) => Promise<Record<string, unknown>>,
706
+ preflight: (filePath: string, request: T) => Promise<Prepared>,
707
+ mutates: (request: T) => boolean,
446
708
  ): Promise<Record<string, unknown>> {
447
709
  const entries = Object.entries(requests);
448
710
  if (entries.length < 1 || entries.length > FILE_READ_MAX_BATCH)
449
711
  throw new Error(
450
712
  `${tool} requires between 1 and ${FILE_READ_MAX_BATCH} files`,
451
713
  );
452
- const files: Record<string, unknown> = {};
453
- for (const [filePath, request] of entries)
454
- files[filePath] = await handler(filePath, request);
455
- return { files };
714
+ const resolvedEntries = await Promise.all(
715
+ entries.map(async ([inputPath, request]) => ({
716
+ inputPath,
717
+ request,
718
+ resolvedPath: await resolveWritablePath(inputPath),
719
+ })),
720
+ );
721
+ return withFileLocks(
722
+ resolvedEntries.map(({ resolvedPath }) => resolvedPath),
723
+ () =>
724
+ executePreparedFileBatch(resolvedEntries, handler, preflight, mutates),
725
+ );
456
726
  }
457
727
 
458
728
  export async function patchFiles(
459
729
  requests: PatchBatch,
460
730
  ): Promise<Record<string, unknown>> {
461
- return processFileBatch("file_patch", requests, applyPatchBatch);
731
+ return processFileBatch(
732
+ "file_patch",
733
+ requests,
734
+ applyPreparedPatch,
735
+ preflightPatchBatch,
736
+ (request) => request.preview !== true,
737
+ );
738
+ }
739
+
740
+ async function writeFileResolved(
741
+ args: {
742
+ chattr?: FileChattr;
743
+ filePath: string;
744
+ content: string;
745
+ expectedSha256?: string;
746
+ },
747
+ prepared?: PreparedWrite,
748
+ ): Promise<Record<string, unknown>> {
749
+ const candidate = prepared ?? (await preflightFileWrite(args.filePath, args));
750
+ const committed = await commit(
751
+ args.filePath,
752
+ candidate.content,
753
+ candidate.mode,
754
+ candidate.actual,
755
+ args.chattr,
756
+ true,
757
+ );
758
+ return {
759
+ chattr: committed.chattr,
760
+ created: !candidate.existing,
761
+ createdDirectories: committed.createdDirectories,
762
+ filePath: args.filePath,
763
+ sha256: committed.sha256,
764
+ };
462
765
  }
463
766
 
464
767
  export async function writeFileSafely(args: {
@@ -468,53 +771,26 @@ export async function writeFileSafely(args: {
468
771
  expectedSha256?: string;
469
772
  }): Promise<Record<string, unknown>> {
470
773
  const filePath = await resolveWritablePath(args.filePath);
471
- return withFileLock(filePath, async () => {
472
- const existing = await readFile(filePath, "utf8").catch(() => undefined);
473
- let createdDirectories: string[];
474
- if (existing !== undefined) {
475
- await requireExpectedHash(args.expectedSha256, "file_write overwrite");
476
- const actual = sha256(existing);
477
- verifyExpectedHash(args.expectedSha256, actual);
478
- const language = detectAstLanguage(filePath);
479
- if (await astRewritable(filePath, language))
480
- throw new Error(
481
- "REJECTED: structurally rewritable existing files require file_patch with patchStrategy 'ast'",
482
- );
483
- createdDirectories = await commit(
484
- filePath,
485
- args.content,
486
- (await lstat(filePath)).mode,
487
- actual,
488
- args.chattr,
489
- );
490
- } else
491
- createdDirectories = await commit(
492
- filePath,
493
- args.content,
494
- undefined,
495
- undefined,
496
- args.chattr,
497
- );
498
- const updated = await readFile(filePath, "utf8");
499
- return {
500
- chattr: await resultingFileChattr(filePath),
501
- created: existing === undefined,
502
- createdDirectories,
503
- filePath,
504
- sha256: sha256(updated),
505
- };
506
- });
774
+ return withFileLock(filePath, () => writeFileResolved({ ...args, filePath }));
507
775
  }
508
776
 
509
777
  export async function writeFilesSafely(
510
778
  requests: FileWriteBatch,
511
779
  ): Promise<Record<string, unknown>> {
512
- return processFileBatch("file_write", requests, (filePath, request) =>
513
- writeFileSafely({
514
- chattr: request.chattr,
515
- content: request.content,
516
- expectedSha256: request.expectedSha256,
517
- filePath,
518
- }),
780
+ return processFileBatch(
781
+ "file_write",
782
+ requests,
783
+ (filePath, request, prepared) =>
784
+ writeFileResolved(
785
+ {
786
+ chattr: request.chattr,
787
+ content: request.content,
788
+ expectedSha256: request.expectedSha256,
789
+ filePath,
790
+ },
791
+ prepared,
792
+ ),
793
+ preflightFileWrite,
794
+ () => true,
519
795
  );
520
796
  }