@mwillbanks/ast-mcp 0.3.0 → 0.4.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 (36) hide show
  1. package/README.md +5 -5
  2. package/dist/ast-mcp.js +172 -156
  3. package/dist/ast-mcp.js.map +35 -31
  4. package/package.json +11 -11
  5. package/src/ast-bro/client.ts +12 -6
  6. package/src/ast-bro/result.ts +79 -0
  7. package/src/ast-bro/tools.json +7 -2
  8. package/src/config-edit.ts +236 -0
  9. package/src/config-migrate.ts +3 -20
  10. package/src/config-registry.ts +8 -0
  11. package/src/config-schema-common.ts +8 -1
  12. package/src/config-v2-schema.ts +12 -0
  13. package/src/config.ts +194 -39
  14. package/src/helpers/config.ts +9 -3
  15. package/src/installer.ts +61 -14
  16. package/src/patch/engine.ts +36 -17
  17. package/src/runtime/config-write.ts +327 -0
  18. package/src/runtime/dependencies.ts +14 -78
  19. package/src/runtime/file-read.ts +4 -13
  20. package/src/runtime/format.ts +27 -5
  21. package/src/runtime/git-worktrees.ts +179 -0
  22. package/src/runtime/path-policy.ts +131 -45
  23. package/src/runtime/path-utils.ts +40 -0
  24. package/src/runtime/paths.ts +29 -3
  25. package/src/tools/ast-bro.ts +106 -8
  26. package/src/tools/configuration.ts +218 -0
  27. package/src/tools/files.ts +1 -1
  28. package/templates/AGENTS.md +5 -1
  29. package/templates/skills/ast-mcp/SKILL.md +30 -1
  30. package/templates/skills/ast-mcp/evals/evals.json +98 -0
  31. package/templates/skills/ast-mcp/references/installation.md +2 -2
  32. package/templates/skills/ast-mcp/references/patch-state-machine.md +2 -2
  33. package/templates/skills/ast-mcp/references/tool-catalog.md +8 -4
  34. package/templates/skills/ast-mcp/scripts/binary-resolution.ts +112 -0
  35. package/templates/skills/ast-mcp/scripts/check-install.ts +162 -39
  36. package/templates/skills/ast-mcp/scripts/managed-hook.ts +34 -2
package/src/config.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { stat } from "node:fs/promises";
2
+ import { realpath, stat } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -9,6 +9,7 @@ import {
9
9
  createHookSchema,
10
10
  dependenciesSchema,
11
11
  httpSchema,
12
+ type WorktreesMode,
12
13
  workspaceSchema,
13
14
  } from "./config-schema-common";
14
15
  import {
@@ -17,8 +18,14 @@ import {
17
18
  type PathRuleV2,
18
19
  } from "./config-v2-schema";
19
20
  import { collectRequestPaths, normalizeConfigLayer } from "./helpers/config";
21
+ import {
22
+ clearGitWorktreeCache,
23
+ linkedWorktrees,
24
+ } from "./runtime/git-worktrees";
20
25
  import { canonicalizePath } from "./runtime/path-utils";
21
26
 
27
+ export type { WorktreesMode };
28
+
22
29
  const schemaVersion = 1 as const;
23
30
  const hookSchema = createHookSchema(64);
24
31
 
@@ -88,6 +95,9 @@ export interface ResolvedConfig {
88
95
  sessionTimeoutMs: number;
89
96
  sessionSweepIntervalMs: number;
90
97
  };
98
+ mcp: {
99
+ configuration: { enabled: boolean; requireApproval: boolean };
100
+ };
91
101
  paths: Array<{
92
102
  excludes: string[];
93
103
  followSymlinks: boolean;
@@ -110,7 +120,11 @@ export interface ResolvedConfig {
110
120
  sources: { project?: string; global?: string; environment: string[] };
111
121
  trustedRoots: string[];
112
122
  version: 1 | 2;
113
- workspace: { roots: string[] };
123
+ workspace: {
124
+ linkedWorktrees: string[];
125
+ roots: string[];
126
+ worktrees: WorktreesMode;
127
+ };
114
128
  }
115
129
 
116
130
  export interface ResolveConfigOptions {
@@ -160,6 +174,9 @@ interface InternalConfig {
160
174
  session_timeout_ms?: number;
161
175
  session_sweep_interval_ms?: number;
162
176
  };
177
+ mcp?: {
178
+ configuration?: { enabled?: boolean; require_approval?: boolean };
179
+ };
163
180
  paths?: Array<{
164
181
  excludes?: string[];
165
182
  follow_symlinks?: boolean;
@@ -181,7 +198,7 @@ interface InternalConfig {
181
198
  require_hash?: boolean;
182
199
  };
183
200
  version?: 1 | 2;
184
- workspace?: { roots?: string[] };
201
+ workspace?: { roots?: string[]; worktrees?: WorktreesMode };
185
202
  }
186
203
 
187
204
  class ConfigurationError extends Error {
@@ -535,6 +552,9 @@ function environmentLayer(
535
552
  const leaves = [
536
553
  "version",
537
554
  "workspace.roots",
555
+ "workspace.worktrees",
556
+ "mcp.configuration.enabled",
557
+ "mcp.configuration.require_approval",
538
558
  "paths",
539
559
  "safety.allow_any_path",
540
560
  "safety.allow_external_roots",
@@ -578,6 +598,7 @@ const mergeSections = [
578
598
  "formatting",
579
599
  "dependencies",
580
600
  "http",
601
+ "mcp",
581
602
  ] as const;
582
603
 
583
604
  type MergeSection = (typeof mergeSections)[number];
@@ -615,6 +636,20 @@ function mergeFileMethods(
615
636
  };
616
637
  }
617
638
 
639
+ function mergeMcpConfiguration(
640
+ result: InternalConfig,
641
+ incoming: InternalConfig["mcp"],
642
+ previous: InternalConfig["mcp"],
643
+ ): void {
644
+ if (!incoming?.configuration) return;
645
+ result.mcp = {
646
+ configuration: {
647
+ ...previous?.configuration,
648
+ ...definedProperties(incoming.configuration),
649
+ },
650
+ };
651
+ }
652
+
618
653
  function mergeSection(
619
654
  result: InternalConfig,
620
655
  layer: InternalConfig,
@@ -624,6 +659,7 @@ function mergeSection(
624
659
  if (!incoming) return;
625
660
  const previousHook = result.safety?.hook;
626
661
  const previousFiles = result.files;
662
+ const previousMcp = result.mcp;
627
663
  result[section] = {
628
664
  ...(result[section] as object | undefined),
629
665
  ...definedProperties(incoming),
@@ -636,6 +672,12 @@ function mergeSection(
636
672
  incoming as InternalConfig["files"],
637
673
  previousFiles,
638
674
  );
675
+ if (section === "mcp")
676
+ mergeMcpConfiguration(
677
+ result,
678
+ incoming as InternalConfig["mcp"],
679
+ previousMcp,
680
+ );
639
681
  }
640
682
 
641
683
  function merge(...layers: InternalConfig[]): InternalConfig {
@@ -717,12 +759,15 @@ function defaultInternalConfig(candidates: string[]): InternalConfig {
717
759
  session_sweep_interval_ms: 60 * 1000,
718
760
  session_timeout_ms: 30 * 60 * 1000,
719
761
  },
762
+ mcp: {
763
+ configuration: { enabled: true, require_approval: true },
764
+ },
720
765
  safety: {
721
766
  hook: { allow_tools: [], block_tools: [], enabled: true },
722
767
  require_hash: true,
723
768
  },
724
769
  version: 1,
725
- workspace: { roots: candidates },
770
+ workspace: { roots: candidates, worktrees: "include" },
726
771
  };
727
772
  }
728
773
 
@@ -826,6 +871,56 @@ function layerPathRules(
826
871
  return (layer.value.paths ?? []).map((rule) => ({ rule, source }));
827
872
  }
828
873
 
874
+ function resolvedMcp(value: InternalConfig): ResolvedConfig["mcp"] {
875
+ return {
876
+ configuration: {
877
+ enabled: value.mcp?.configuration?.enabled ?? true,
878
+ requireApproval: value.mcp?.configuration?.require_approval ?? true,
879
+ },
880
+ };
881
+ }
882
+
883
+ function resolvedPathEntries(
884
+ pathRules: ReturnType<typeof layerPathRules>,
885
+ ): ResolvedConfig["paths"] {
886
+ return pathRules.map(({ rule, source }) => ({
887
+ excludes: rule.excludes ?? [],
888
+ followSymlinks: rule.follow_symlinks ?? false,
889
+ id: rule.id,
890
+ includes: rule.includes ?? ["**/*"],
891
+ path: rule.path,
892
+ policies: {
893
+ delete: rule.policies.delete ?? rule.policies.write,
894
+ read: rule.policies.read,
895
+ write: rule.policies.write,
896
+ },
897
+ source,
898
+ }));
899
+ }
900
+
901
+ function resolvedSources(
902
+ environment: ReturnType<typeof environmentLayer>,
903
+ global: LoadedLayer,
904
+ project: LoadedLayer,
905
+ ): ResolvedConfig["sources"] {
906
+ return {
907
+ environment: environment.names,
908
+ global: global.value ? global.path : undefined,
909
+ project: project.value ? project.path : undefined,
910
+ };
911
+ }
912
+
913
+ function resolvedWorkspace(
914
+ value: InternalConfig,
915
+ candidates: string[],
916
+ ): ResolvedConfig["workspace"] {
917
+ return {
918
+ linkedWorktrees: [],
919
+ roots: value.workspace?.roots ?? candidates,
920
+ worktrees: value.workspace?.worktrees ?? "include",
921
+ };
922
+ }
923
+
829
924
  function resolvedConfiguration(args: {
830
925
  candidates: string[];
831
926
  dprintConfig: string;
@@ -848,10 +943,6 @@ function resolvedConfiguration(args: {
848
943
  trustedRoots,
849
944
  value,
850
945
  } = args;
851
- const pathRules = [
852
- ...layerPathRules(global, "global"),
853
- ...layerPathRules(project, "project"),
854
- ];
855
946
  return {
856
947
  dependencies: {
857
948
  astBroBinary: value.dependencies?.ast_bro_binary,
@@ -861,30 +952,18 @@ function resolvedConfiguration(args: {
861
952
  formatting: resolvedFormatting(value, dprintConfig),
862
953
  generation: 0,
863
954
  http: resolvedHttp(value),
864
- paths: pathRules.map(({ rule, source }) => ({
865
- excludes: rule.excludes ?? [],
866
- followSymlinks: rule.follow_symlinks ?? false,
867
- id: rule.id,
868
- includes: rule.includes ?? ["**/*"],
869
- path: rule.path,
870
- policies: {
871
- delete: rule.policies.delete ?? rule.policies.write,
872
- read: rule.policies.read,
873
- write: rule.policies.write,
874
- },
875
- source,
876
- })),
955
+ mcp: resolvedMcp(value),
956
+ paths: resolvedPathEntries([
957
+ ...layerPathRules(global, "global"),
958
+ ...layerPathRules(project, "project"),
959
+ ]),
877
960
  projectRoot,
878
961
  provenance,
879
962
  safety: resolvedSafety(value),
880
- sources: {
881
- environment: environment.names,
882
- global: global.value ? global.path : undefined,
883
- project: project.value ? project.path : undefined,
884
- },
963
+ sources: resolvedSources(environment, global, project),
885
964
  trustedRoots,
886
965
  version: value.version ?? 1,
887
- workspace: { roots: value.workspace?.roots ?? candidates },
966
+ workspace: resolvedWorkspace(value, candidates),
888
967
  };
889
968
  }
890
969
 
@@ -943,6 +1022,71 @@ function resolutionCacheKey(args: {
943
1022
  });
944
1023
  }
945
1024
 
1025
+ async function sameResolvedPath(left: string, right: string): Promise<boolean> {
1026
+ if (path.resolve(left) === path.resolve(right)) return true;
1027
+ try {
1028
+ return (await realpath(left)) === (await realpath(right));
1029
+ } catch {
1030
+ return false;
1031
+ }
1032
+ }
1033
+
1034
+ async function appendUniqueRoots(
1035
+ existing: string[],
1036
+ candidates: string[],
1037
+ ): Promise<string[]> {
1038
+ const result = [...existing];
1039
+ for (const candidate of candidates) {
1040
+ let found = false;
1041
+ for (const item of result) {
1042
+ if (await sameResolvedPath(item, candidate)) {
1043
+ found = true;
1044
+ break;
1045
+ }
1046
+ }
1047
+ if (!found) result.push(candidate);
1048
+ }
1049
+ return result;
1050
+ }
1051
+
1052
+ async function discoveredLinkedWorktrees(
1053
+ projectRoot: string,
1054
+ candidates: string[],
1055
+ trustedRoots: string[],
1056
+ ): Promise<string[]> {
1057
+ const sources = [...new Set([projectRoot, ...candidates, ...trustedRoots])];
1058
+ return [
1059
+ ...new Set(
1060
+ (await Promise.all(sources.map((root) => linkedWorktrees(root)))).flat(),
1061
+ ),
1062
+ ];
1063
+ }
1064
+
1065
+ async function applyLinkedWorktrees(
1066
+ config: ResolvedConfig,
1067
+ linked: string[],
1068
+ ): Promise<ResolvedConfig> {
1069
+ const workspace = { ...config.workspace, linkedWorktrees: linked };
1070
+ if (config.workspace.worktrees === "ignore") return { ...config, workspace };
1071
+ const workspaceLinked = [
1072
+ ...new Set(
1073
+ (
1074
+ await Promise.all(
1075
+ config.workspace.roots.map((root) => linkedWorktrees(root)),
1076
+ )
1077
+ ).flat(),
1078
+ ),
1079
+ ];
1080
+ return {
1081
+ ...config,
1082
+ trustedRoots: await appendUniqueRoots(config.trustedRoots, linked),
1083
+ workspace: {
1084
+ ...workspace,
1085
+ roots: await appendUniqueRoots(config.workspace.roots, workspaceLinked),
1086
+ },
1087
+ };
1088
+ }
1089
+
946
1090
  async function resolveForProject(
947
1091
  projectRoot: string,
948
1092
  candidates: string[],
@@ -980,20 +1124,28 @@ async function resolveForProject(
980
1124
  projectRoot,
981
1125
  trustedRoots,
982
1126
  });
983
- const fingerprint = `${global.fingerprint}|${project.fingerprint}|${dprint.fingerprint}`;
984
- const cached = resolvedCache.get(key);
985
- if (cached?.fingerprint === fingerprint) return cached.value;
986
- const resolved = resolvedConfiguration({
987
- candidates,
988
- dprintConfig: dprint.config,
989
- environment,
990
- global,
991
- project,
1127
+ const linked = await discoveredLinkedWorktrees(
992
1128
  projectRoot,
993
- provenance: configProvenance(layers),
1129
+ candidates,
994
1130
  trustedRoots,
995
- value,
996
- });
1131
+ );
1132
+ const fingerprint = `${global.fingerprint}|${project.fingerprint}|${dprint.fingerprint}|${linked.join("\0")}`;
1133
+ const cached = resolvedCache.get(key);
1134
+ if (cached?.fingerprint === fingerprint) return cached.value;
1135
+ const resolved = await applyLinkedWorktrees(
1136
+ resolvedConfiguration({
1137
+ candidates,
1138
+ dprintConfig: dprint.config,
1139
+ environment,
1140
+ global,
1141
+ project,
1142
+ projectRoot,
1143
+ provenance: configProvenance(layers),
1144
+ trustedRoots,
1145
+ value,
1146
+ }),
1147
+ linked,
1148
+ );
997
1149
  resolvedCache.set(key, { fingerprint, value: resolved });
998
1150
  return resolved;
999
1151
  }
@@ -1019,7 +1171,9 @@ function policy(config: ResolvedConfig) {
1019
1171
  dependencies: config.dependencies,
1020
1172
  files: config.files,
1021
1173
  formatting: config.formatting,
1174
+ mcp: config.mcp.configuration,
1022
1175
  safety: config.safety,
1176
+ worktrees: config.workspace.worktrees,
1023
1177
  });
1024
1178
  }
1025
1179
 
@@ -1106,6 +1260,7 @@ export async function withResolvedConfig<T>(
1106
1260
  }
1107
1261
 
1108
1262
  export function clearConfigCache() {
1263
+ clearGitWorktreeCache();
1109
1264
  dprintConfigCache.clear();
1110
1265
  layerCache.clear();
1111
1266
  resolvedCache.clear();
@@ -16,7 +16,10 @@ type ConfigLayer = {
16
16
  };
17
17
  paths?: Array<{ path: string; [key: string]: unknown }>;
18
18
  safety?: { [key: string]: unknown };
19
- workspace?: { roots?: string[] };
19
+ workspace?: {
20
+ roots?: string[];
21
+ worktrees?: "include" | "request" | "ignore";
22
+ };
20
23
  [key: string]: unknown;
21
24
  };
22
25
 
@@ -80,8 +83,11 @@ export function normalizeConfigLayer<T extends ConfigLayer>(
80
83
  path: resolvedPath(rule.path, base),
81
84
  })),
82
85
  safety: value.safety,
83
- workspace: value.workspace?.roots
84
- ? { roots: value.workspace.roots.map((item) => resolvedPath(item, base)) }
86
+ workspace: value.workspace
87
+ ? {
88
+ ...value.workspace,
89
+ roots: value.workspace.roots?.map((item) => resolvedPath(item, base)),
90
+ }
85
91
  : value.workspace,
86
92
  } as T;
87
93
  }
package/src/installer.ts CHANGED
@@ -27,7 +27,12 @@ import {
27
27
  transports,
28
28
  } from "./installer-transport";
29
29
  import { isManagedHook } from "./managed-hook";
30
- import { AST_BRO_BINARY, assertAstBroAvailable } from "./runtime/dependencies";
30
+ import {
31
+ AST_BRO_BINARY,
32
+ assertAstBroAvailable,
33
+ globalBinDirectories,
34
+ resolveGlobalBinaryAlias,
35
+ } from "./runtime/dependencies";
31
36
  import {
32
37
  createServicePlan,
33
38
  installService,
@@ -39,16 +44,57 @@ import {
39
44
  const packageRoot = path.resolve(import.meta.dir, "..");
40
45
  const cliEntry = path.join(packageRoot, "dist/ast-mcp.js");
41
46
  const installerRuntime = new AsyncLocalStorage<{ cliEntry: string }>();
47
+ function stableGlobalCliEntry(
48
+ value: string | undefined,
49
+ directories: string[],
50
+ platform: NodeJS.Platform,
51
+ ) {
52
+ if (!value) return undefined;
53
+ const resolved = path.resolve(value);
54
+ const basename = path.basename(resolved).toLowerCase();
55
+ const astMcpNames =
56
+ platform === "win32"
57
+ ? ["ast-mcp", "ast-mcp.cmd", "ast-mcp.exe"]
58
+ : ["ast-mcp"];
59
+ if (!astMcpNames.includes(basename)) return undefined;
60
+ const candidateDirectory = path.dirname(resolved);
61
+ const normalize = (entry: string) =>
62
+ platform === "win32"
63
+ ? path.resolve(entry).toLowerCase()
64
+ : path.resolve(entry);
65
+ if (
66
+ !directories.some(
67
+ (directory) => normalize(directory) === normalize(candidateDirectory),
68
+ )
69
+ )
70
+ return undefined;
71
+ return resolveGlobalBinaryAlias("ast-mcp", {
72
+ globalBinDirectories: [candidateDirectory],
73
+ platform,
74
+ });
75
+ }
76
+
42
77
  function configuredCliEntry(
43
78
  options: InstallOptions,
44
79
  root: string,
45
80
  home: string,
46
81
  ) {
47
- return options.cliEntry
48
- ? path.resolve(options.cliEntry)
49
- : options.scope === "local"
50
- ? path.join(root, "node_modules/.bin/ast-mcp")
51
- : path.join(home, ".bun/bin/ast-mcp");
82
+ if (options.scope === "local")
83
+ return path.join(root, "node_modules/.bin/ast-mcp");
84
+ const platform = options.platform ?? process.platform;
85
+ const directories =
86
+ options.globalBinDirectories ??
87
+ globalBinDirectories("ast-mcp", platform, home);
88
+ const resolved =
89
+ stableGlobalCliEntry(options.cliEntry, directories, platform) ??
90
+ resolveGlobalBinaryAlias("ast-mcp", {
91
+ globalBinDirectories: directories,
92
+ platform,
93
+ });
94
+ if (resolved) return resolved;
95
+ throw new Error(
96
+ "No executable global ast-mcp package-manager alias was found. Install @mwillbanks/ast-mcp globally with Bun, npm, pnpm, or Yarn, then rerun the installer.",
97
+ );
52
98
  }
53
99
  function cliEntryFor(root: string | undefined, _home: string) {
54
100
  const entry = installerRuntime.getStore()?.cliEntry ?? cliEntry;
@@ -162,10 +208,8 @@ async function hook(
162
208
  value.hooks ??= {};
163
209
  const prior = Array.isArray(value.hooks[event]) ? value.hooks[event] : [];
164
210
  const command = `${JSON.stringify(commandPath)} hook`;
165
- const managedCommands = [command, `bun ${JSON.stringify(cliEntry)} hook`];
166
211
  const kept = prior.filter(
167
- (item: unknown) =>
168
- !managedCommands.some((managed) => isManagedHook(item, event, managed)),
212
+ (item: unknown) => !isManagedHook(item, event, command),
169
213
  );
170
214
  const item =
171
215
  event === "preToolUse"
@@ -313,6 +357,7 @@ export interface InstallOptions {
313
357
  astBroBinary?: string;
314
358
  cliEntry?: string;
315
359
  deprecatedRoot?: boolean;
360
+ globalBinDirectories?: string[];
316
361
  home?: string;
317
362
  host?: string;
318
363
  platform?: NodeJS.Platform;
@@ -653,6 +698,10 @@ function installerConfigSeed(local: boolean) {
653
698
  "port = 3768",
654
699
  "session_timeout_ms = 1800000",
655
700
  "session_sweep_interval_ms = 60000",
701
+ "",
702
+ "[mcp.configuration]",
703
+ "enabled = true",
704
+ "require_approval = true",
656
705
  ];
657
706
  if (!local) return `${common.join("\n")}\n`;
658
707
  return `${[
@@ -660,6 +709,7 @@ function installerConfigSeed(local: boolean) {
660
709
  "",
661
710
  "[workspace]",
662
711
  'roots = ["."]',
712
+ 'worktrees = "include"',
663
713
  "",
664
714
  ...common.slice(2),
665
715
  "",
@@ -815,8 +865,8 @@ async function reconcile(
815
865
  });
816
866
  await preflightService(serviceConfiguration(options, endpoint));
817
867
  }
818
- await ensureInstallerConfig(options, root, home);
819
868
  assertAstBroAvailable(await installerAstBroBinary(options));
869
+ await ensureInstallerConfig(options, root, home);
820
870
  const endpoint = await reconcileEndpoint(options, transport, root, home);
821
871
  for (const target of options.targets)
822
872
  await installTarget(target, global, root, home, transport, endpoint);
@@ -959,10 +1009,7 @@ export async function runInstallerCli(
959
1009
  args,
960
1010
  process.cwd(),
961
1011
  );
962
- const options: InstallOptions = {
963
- ...parsedOptions,
964
- cliEntry: process.argv[1],
965
- };
1012
+ const options: InstallOptions = parsedOptions;
966
1013
  if (options.deprecatedRoot)
967
1014
  process.stderr.write(
968
1015
  "ast-mcp: --root is deprecated; run this command from the project root.\n",
@@ -322,7 +322,7 @@ async function createPatchContext(
322
322
 
323
323
  async function patchPreview(
324
324
  context: PatchContext,
325
- formatted: string,
325
+ candidate: string,
326
326
  metadata: PreviewMetadata,
327
327
  ) {
328
328
  const config = await currentConfig();
@@ -337,7 +337,7 @@ async function patchPreview(
337
337
  };
338
338
  const payloadBytes = previewPayloadBytes(
339
339
  sessionId,
340
- formatted,
340
+ candidate,
341
341
  normalizedOperations,
342
342
  );
343
343
  const expiryTimer = setTimeout(
@@ -346,8 +346,8 @@ async function patchPreview(
346
346
  );
347
347
  expiryTimer.unref?.();
348
348
  previewReceipts.set(receipt, {
349
- candidate: formatted,
350
- candidateSha256: sha256(formatted),
349
+ candidate,
350
+ candidateSha256: sha256(candidate),
351
351
  chattr: context.request.chattr,
352
352
  configurationIdentity: previewConfigurationIdentity(config),
353
353
  expiresAt,
@@ -361,8 +361,8 @@ async function patchPreview(
361
361
  sourceSha256: context.actual,
362
362
  });
363
363
  return {
364
- changed: formatted !== context.original,
365
- diff: previewDiff(context.filePath, context.original, formatted),
364
+ changed: candidate !== context.original,
365
+ diff: previewDiff(context.filePath, context.original, candidate),
366
366
  filePath: context.filePath,
367
367
  matches: metadata.matches,
368
368
  matchMethods: metadata.matchMethods,
@@ -370,18 +370,27 @@ async function patchPreview(
370
370
  preview: true,
371
371
  previewReceipt: receipt,
372
372
  receiptExpiresAt: new Date(expiresAt).toISOString(),
373
- sha256: sha256(formatted),
373
+ sha256: sha256(candidate),
374
374
  strategy: metadata.strategy,
375
375
  };
376
376
  }
377
377
 
378
- async function prepareFormattedStrategyPatch(context: PatchContext) {
378
+ async function prepareStrategyPatch(context: PatchContext) {
379
379
  const prepared = await patchStrategyAdapter(
380
380
  context.request.patchStrategy,
381
381
  ).prepare(context);
382
- const candidate = await formatContent(context.filePath, prepared.candidate);
383
- await validateStructuredCandidate(context.capabilities, candidate);
384
- return { candidate, metadata: prepared.metadata };
382
+ await validateStructuredCandidate(context.capabilities, prepared.candidate);
383
+ return { candidate: prepared.candidate, metadata: prepared.metadata };
384
+ }
385
+
386
+ async function formatCandidate(
387
+ filePath: string,
388
+ candidate: string,
389
+ capabilities: FileCapabilities,
390
+ ) {
391
+ const formatted = await formatContent(filePath, candidate);
392
+ await validateStructuredCandidate(capabilities, formatted);
393
+ return formatted;
385
394
  }
386
395
 
387
396
  async function applyLockedPatch(filePath: string, request: PatchBatchRequest) {
@@ -392,12 +401,17 @@ async function applyLockedPatch(filePath: string, request: PatchBatchRequest) {
392
401
  await preflightPatchBatch(filePath, request),
393
402
  );
394
403
  const context = await createPatchContext(filePath, request);
395
- const prepared = await prepareFormattedStrategyPatch(context);
404
+ const prepared = await prepareStrategyPatch(context);
396
405
  if (request.preview)
397
406
  return patchPreview(context, prepared.candidate, prepared.metadata);
398
- await commit(
407
+ const candidate = await formatCandidate(
399
408
  filePath,
400
409
  prepared.candidate,
410
+ context.capabilities,
411
+ );
412
+ await commit(
413
+ filePath,
414
+ candidate,
401
415
  context.mode,
402
416
  context.actual,
403
417
  request.chattr,
@@ -407,7 +421,7 @@ async function applyLockedPatch(filePath: string, request: PatchBatchRequest) {
407
421
  ...prepared.metadata,
408
422
  filePath,
409
423
  preview: false,
410
- sha256: sha256(prepared.candidate),
424
+ sha256: sha256(candidate),
411
425
  };
412
426
  }
413
427
 
@@ -471,7 +485,7 @@ async function preflightPatchBatch(
471
485
  }
472
486
 
473
487
  const context = await createPatchContext(filePath, request);
474
- const prepared = await prepareFormattedStrategyPatch(context);
488
+ const prepared = await prepareStrategyPatch(context);
475
489
  return {
476
490
  candidate: prepared.candidate,
477
491
  chattr: request.chattr,
@@ -499,6 +513,11 @@ async function applyPreparedPatch(
499
513
  prepared.sourceSha256 === undefined
500
514
  )
501
515
  throw new Error("Patch batch preflight did not produce a commit candidate");
516
+ const candidate = await formatCandidate(
517
+ filePath,
518
+ prepared.candidate,
519
+ await inspectFileCapabilities(filePath),
520
+ );
502
521
  if (prepared.receiptToken) {
503
522
  const receipt = previewReceipts.get(prepared.receiptToken);
504
523
  if (receipt) clearTimeout(receipt.expiryTimer);
@@ -506,13 +525,13 @@ async function applyPreparedPatch(
506
525
  }
507
526
  await commit(
508
527
  filePath,
509
- prepared.candidate,
528
+ candidate,
510
529
  prepared.mode,
511
530
  prepared.sourceSha256,
512
531
  prepared.chattr,
513
532
  true,
514
533
  );
515
- return prepared.result;
534
+ return { ...prepared.result, sha256: sha256(candidate) };
516
535
  }
517
536
 
518
537
  interface PreparedWrite {