@mwillbanks/ast-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +60 -0
- package/LICENSE +21 -0
- package/README.md +109 -0
- package/dist/ast-mcp-hook.js +7 -0
- package/dist/ast-mcp-hook.js.map +11 -0
- package/dist/ast-mcp-install.js +22 -0
- package/dist/ast-mcp-install.js.map +12 -0
- package/dist/ast-mcp.js +115 -0
- package/dist/ast-mcp.js.map +89 -0
- package/dprint.json +37 -0
- package/logo.svg +1 -0
- package/package.json +89 -0
- package/src/ast-bro/capability.ts +21 -0
- package/src/ast-bro/client.ts +47 -0
- package/src/ast-bro/result.ts +42 -0
- package/src/ast-bro/rewrite-capability.ts +9 -0
- package/src/ast-bro/tools.json +603 -0
- package/src/hook.ts +79 -0
- package/src/http-entry.ts +3 -0
- package/src/http.ts +138 -0
- package/src/index.ts +8 -0
- package/src/installer.ts +501 -0
- package/src/lifecycle.ts +10 -0
- package/src/managed-hook.ts +4 -0
- package/src/patch/aider.ts +224 -0
- package/src/patch/engine.ts +446 -0
- package/src/patch/languages.ts +36 -0
- package/src/runtime/atomic.ts +26 -0
- package/src/runtime/attributes.ts +70 -0
- package/src/runtime/file-delete.ts +96 -0
- package/src/runtime/file-read.ts +178 -0
- package/src/runtime/format.ts +56 -0
- package/src/runtime/hash.ts +11 -0
- package/src/runtime/locks.ts +87 -0
- package/src/runtime/paths.ts +73 -0
- package/src/runtime/process-input.ts +25 -0
- package/src/runtime/signals.ts +47 -0
- package/src/server.ts +13 -0
- package/src/stdio.ts +154 -0
- package/src/tools/ast-bro.ts +172 -0
- package/src/tools/files.ts +173 -0
- package/src/tools/index.ts +11 -0
- package/src/tools/lifecycle.ts +124 -0
- package/templates/AGENTS.md +56 -0
- package/templates/skills/ast-mcp/SKILL.md +96 -0
- package/templates/skills/ast-mcp/agents/openai.yaml +4 -0
- package/templates/skills/ast-mcp/evals/batch.evals.json +274 -0
- package/templates/skills/ast-mcp/evals/evals.json +1209 -0
- package/templates/skills/ast-mcp/evals/file-hash.evals.json +50 -0
- package/templates/skills/ast-mcp/evals/measure.ts +18 -0
- package/templates/skills/ast-mcp/evals/results.md +17 -0
- package/templates/skills/ast-mcp/evals/score.ts +417 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +332 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +22 -0
- package/templates/skills/ast-mcp/evals/validate.ts +99 -0
- package/templates/skills/ast-mcp/references/installation.md +40 -0
- package/templates/skills/ast-mcp/references/managed-hook.ts +3 -0
- package/templates/skills/ast-mcp/references/patch-state-machine.md +39 -0
- package/templates/skills/ast-mcp/references/tool-catalog.md +46 -0
- package/templates/skills/ast-mcp/scripts/check-install.ts +269 -0
- package/templates/skills/ast-mcp/scripts/managed-hook.ts +22 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { DiffMatchPatch } from "diff-match-patch-ts";
|
|
2
|
+
|
|
3
|
+
export interface SearchReplaceBlock {
|
|
4
|
+
filename: string;
|
|
5
|
+
replace: string;
|
|
6
|
+
search: string;
|
|
7
|
+
}
|
|
8
|
+
export interface AiderReplacement {
|
|
9
|
+
content: string;
|
|
10
|
+
method:
|
|
11
|
+
| "append"
|
|
12
|
+
| "exact"
|
|
13
|
+
| "whitespace"
|
|
14
|
+
| "relative-indentation"
|
|
15
|
+
| "diff-match-patch";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function parseAiderBlocks(output: string): SearchReplaceBlock[] {
|
|
19
|
+
const blocks: SearchReplaceBlock[] = [];
|
|
20
|
+
const lines = output.split(/\r?\n/);
|
|
21
|
+
let filename = "";
|
|
22
|
+
let mode: "outside" | "search" | "replace" = "outside";
|
|
23
|
+
let search: string[] = [];
|
|
24
|
+
let replace: string[] = [];
|
|
25
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
26
|
+
const line = lines[index];
|
|
27
|
+
if (line.startsWith("<<<<<<< SEARCH")) {
|
|
28
|
+
const prior = lines[index - 1]?.trim();
|
|
29
|
+
if (prior && !prior.includes("```"))
|
|
30
|
+
filename = prior.replace(/[:`*]/g, "").trim();
|
|
31
|
+
search = [];
|
|
32
|
+
replace = [];
|
|
33
|
+
mode = "search";
|
|
34
|
+
} else if (line.startsWith("=======")) mode = "replace";
|
|
35
|
+
else if (line.startsWith(">>>>>>>")) {
|
|
36
|
+
if (mode !== "replace")
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Malformed Aider block: replacement terminator arrived out of order",
|
|
39
|
+
);
|
|
40
|
+
blocks.push({
|
|
41
|
+
filename,
|
|
42
|
+
replace: replace.join("\n"),
|
|
43
|
+
search: search.join("\n"),
|
|
44
|
+
});
|
|
45
|
+
mode = "outside";
|
|
46
|
+
} else if (mode === "search") search.push(line);
|
|
47
|
+
else if (mode === "replace") replace.push(line);
|
|
48
|
+
}
|
|
49
|
+
if (mode !== "outside")
|
|
50
|
+
throw new Error("Malformed Aider block: unterminated SEARCH/REPLACE block");
|
|
51
|
+
return blocks;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function replaceLines(
|
|
55
|
+
contentLines: string[],
|
|
56
|
+
start: number,
|
|
57
|
+
count: number,
|
|
58
|
+
replacement: string,
|
|
59
|
+
): string {
|
|
60
|
+
const before = contentLines.slice(0, start).join("\n");
|
|
61
|
+
const after = contentLines.slice(start + count).join("\n");
|
|
62
|
+
return (
|
|
63
|
+
before + (before ? "\n" : "") + replacement + (after ? "\n" : "") + after
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function applyAiderBlock(
|
|
68
|
+
fileContent: string,
|
|
69
|
+
searchInput: string,
|
|
70
|
+
replaceInput: string,
|
|
71
|
+
): AiderReplacement {
|
|
72
|
+
const content = fileContent.replace(/\r\n/g, "\n");
|
|
73
|
+
const search = searchInput.replace(/\r\n/g, "\n");
|
|
74
|
+
const replace = replaceInput.replace(/\r\n/g, "\n");
|
|
75
|
+
if (!search.trim() && replace.trim())
|
|
76
|
+
return {
|
|
77
|
+
content: content + (content.endsWith("\n") ? "" : "\n") + replace,
|
|
78
|
+
method: "append",
|
|
79
|
+
};
|
|
80
|
+
if (!search)
|
|
81
|
+
throw new Error(
|
|
82
|
+
"Aider SEARCH block must not be empty when replacement is empty",
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const exact = content.split(search).length - 1;
|
|
86
|
+
if (exact === 1)
|
|
87
|
+
return { content: content.replace(search, () => replace), method: "exact" };
|
|
88
|
+
if (exact > 1) throw new Error("Aider exact match is ambiguous");
|
|
89
|
+
|
|
90
|
+
const normalize = (value: string) => {
|
|
91
|
+
const indent = value.match(/^[ \t]*/)?.[0] ?? "";
|
|
92
|
+
return (
|
|
93
|
+
indent.replace(/\t/g, " ") +
|
|
94
|
+
value
|
|
95
|
+
.slice(indent.length)
|
|
96
|
+
.replace(/[ \t]+/g, " ")
|
|
97
|
+
.trimEnd()
|
|
98
|
+
);
|
|
99
|
+
};
|
|
100
|
+
const contentLines = content.split("\n");
|
|
101
|
+
const searchLines = search.split("\n");
|
|
102
|
+
const whitespaceMatches: number[] = [];
|
|
103
|
+
for (
|
|
104
|
+
let start = 0;
|
|
105
|
+
start <= contentLines.length - searchLines.length;
|
|
106
|
+
start += 1
|
|
107
|
+
) {
|
|
108
|
+
if (
|
|
109
|
+
searchLines.every(
|
|
110
|
+
(line, offset) =>
|
|
111
|
+
normalize(contentLines[start + offset]) === normalize(line),
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
whitespaceMatches.push(start);
|
|
115
|
+
}
|
|
116
|
+
if (whitespaceMatches.length === 1)
|
|
117
|
+
return {
|
|
118
|
+
content: replaceLines(
|
|
119
|
+
contentLines,
|
|
120
|
+
whitespaceMatches[0],
|
|
121
|
+
searchLines.length,
|
|
122
|
+
replace,
|
|
123
|
+
),
|
|
124
|
+
method: "whitespace",
|
|
125
|
+
};
|
|
126
|
+
if (whitespaceMatches.length > 1)
|
|
127
|
+
throw new Error("Aider whitespace match is ambiguous");
|
|
128
|
+
|
|
129
|
+
const sample = searchLines.find((line) => line.trim());
|
|
130
|
+
if (sample) {
|
|
131
|
+
const searchIndent = sample.match(/^[ \t]*/)?.[0] ?? "";
|
|
132
|
+
const shiftedMatches: Array<{ index: number; length: number }> = [];
|
|
133
|
+
for (const line of contentLines) {
|
|
134
|
+
if (line.trim() !== sample.trim()) continue;
|
|
135
|
+
const fileIndent = line.match(/^[ \t]*/)?.[0] ?? "";
|
|
136
|
+
if (fileIndent === searchIndent) continue;
|
|
137
|
+
const shifted = searchLines
|
|
138
|
+
.map((item) =>
|
|
139
|
+
item.startsWith(searchIndent)
|
|
140
|
+
? fileIndent + item.slice(searchIndent.length)
|
|
141
|
+
: item,
|
|
142
|
+
)
|
|
143
|
+
.join("\n");
|
|
144
|
+
const index = content.indexOf(shifted);
|
|
145
|
+
if (index >= 0 && content.indexOf(shifted, index + 1) < 0)
|
|
146
|
+
shiftedMatches.push({ index, length: shifted.length });
|
|
147
|
+
}
|
|
148
|
+
if (shiftedMatches.length === 1) {
|
|
149
|
+
const match = shiftedMatches[0];
|
|
150
|
+
return {
|
|
151
|
+
content:
|
|
152
|
+
content.slice(0, match.index) +
|
|
153
|
+
replace +
|
|
154
|
+
content.slice(match.index + match.length),
|
|
155
|
+
method: "relative-indentation",
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
if (shiftedMatches.length > 1)
|
|
159
|
+
throw new Error("Aider indentation match is ambiguous");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Tier 4 (git cherry-pick) is deliberately omitted: this engine never spawns git or Python.
|
|
163
|
+
const dmp = new DiffMatchPatch();
|
|
164
|
+
dmp.Match_Distance = Math.max(1000, content.length);
|
|
165
|
+
dmp.Match_Threshold = 0.5;
|
|
166
|
+
const anchor = search.slice(0, dmp.Match_MaxBits);
|
|
167
|
+
const locations: number[] = [];
|
|
168
|
+
for (
|
|
169
|
+
let location = content.indexOf(anchor);
|
|
170
|
+
location >= 0;
|
|
171
|
+
location = content.indexOf(anchor, location + 1)
|
|
172
|
+
)
|
|
173
|
+
locations.push(location);
|
|
174
|
+
if (!locations.length) {
|
|
175
|
+
const matcher = dmp as unknown as {
|
|
176
|
+
match_main(text: string, pattern: string, location: number): number;
|
|
177
|
+
};
|
|
178
|
+
const location = matcher.match_main(content, anchor, 0);
|
|
179
|
+
if (location >= 0) locations.push(location);
|
|
180
|
+
}
|
|
181
|
+
const adjustment = Math.min(64, Math.max(4, Math.ceil(search.length * 0.2)));
|
|
182
|
+
const candidates: Array<{ index: number; length: number; ratio: number }> =
|
|
183
|
+
[];
|
|
184
|
+
for (const index of locations) {
|
|
185
|
+
const minimum = Math.max(1, search.length - adjustment);
|
|
186
|
+
const maximum = Math.min(
|
|
187
|
+
content.length - index,
|
|
188
|
+
search.length + adjustment,
|
|
189
|
+
);
|
|
190
|
+
let best: { index: number; length: number; ratio: number } | undefined;
|
|
191
|
+
for (let length = minimum; length <= maximum; length += 1) {
|
|
192
|
+
const candidate = content.slice(index, index + length);
|
|
193
|
+
const edits = dmp.diff_levenshtein(dmp.diff_main(search, candidate));
|
|
194
|
+
const ratio = edits / Math.max(search.length, length);
|
|
195
|
+
if (
|
|
196
|
+
!best ||
|
|
197
|
+
ratio < best.ratio ||
|
|
198
|
+
(ratio === best.ratio &&
|
|
199
|
+
Math.abs(length - search.length) <
|
|
200
|
+
Math.abs(best.length - search.length))
|
|
201
|
+
)
|
|
202
|
+
best = { index, length, ratio };
|
|
203
|
+
}
|
|
204
|
+
if (best) candidates.push(best);
|
|
205
|
+
}
|
|
206
|
+
candidates.sort((left, right) => left.ratio - right.ratio);
|
|
207
|
+
const best = candidates[0];
|
|
208
|
+
if (!best || best.ratio > 0.5)
|
|
209
|
+
throw new Error(
|
|
210
|
+
"Aider cascade match failed: SEARCH block was not found with sufficient confidence",
|
|
211
|
+
);
|
|
212
|
+
if (
|
|
213
|
+
candidates[1] &&
|
|
214
|
+
Math.abs(candidates[1].ratio - best.ratio) < Number.EPSILON
|
|
215
|
+
)
|
|
216
|
+
throw new Error("Aider diff-match-patch match is ambiguous");
|
|
217
|
+
return {
|
|
218
|
+
content:
|
|
219
|
+
content.slice(0, best.index) +
|
|
220
|
+
replace +
|
|
221
|
+
content.slice(best.index + best.length),
|
|
222
|
+
method: "diff-match-patch",
|
|
223
|
+
};
|
|
224
|
+
}
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
chmod,
|
|
4
|
+
lstat,
|
|
5
|
+
mkdir,
|
|
6
|
+
readFile,
|
|
7
|
+
rename,
|
|
8
|
+
unlink,
|
|
9
|
+
writeFile,
|
|
10
|
+
} from "node:fs/promises";
|
|
11
|
+
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";
|
|
15
|
+
import {
|
|
16
|
+
applyFileChattr,
|
|
17
|
+
type FileChattr,
|
|
18
|
+
resultingFileChattr,
|
|
19
|
+
} from "../runtime/attributes";
|
|
20
|
+
import { FILE_READ_MAX_BATCH } from "../runtime/file-read";
|
|
21
|
+
import { formatContent } from "../runtime/format";
|
|
22
|
+
import { sha256 } from "../runtime/hash";
|
|
23
|
+
import { withFileLock } from "../runtime/locks";
|
|
24
|
+
import { resolveWritablePath } from "../runtime/paths";
|
|
25
|
+
|
|
26
|
+
import { applyAiderBlock } from "./aider";
|
|
27
|
+
import { detectAstLanguage } from "./languages";
|
|
28
|
+
|
|
29
|
+
export interface AstRule {
|
|
30
|
+
expectedMatches?: number;
|
|
31
|
+
fix: string;
|
|
32
|
+
pattern: string;
|
|
33
|
+
}
|
|
34
|
+
export interface AiderBlock {
|
|
35
|
+
replace: string;
|
|
36
|
+
search: string;
|
|
37
|
+
}
|
|
38
|
+
export interface PatchRequest {
|
|
39
|
+
aiderBlock?: AiderBlock;
|
|
40
|
+
astRule?: AstRule;
|
|
41
|
+
expectedSha256: string;
|
|
42
|
+
filePath: string;
|
|
43
|
+
patchStrategy: "ast" | "aider_block";
|
|
44
|
+
preview?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface PatchBatchRequest {
|
|
48
|
+
aiderBlocks?: AiderBlock[];
|
|
49
|
+
astRules?: AstRule[];
|
|
50
|
+
chattr?: FileChattr;
|
|
51
|
+
expectedSha256: string;
|
|
52
|
+
patchStrategy: "ast" | "aider_block";
|
|
53
|
+
preview?: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type PatchBatch = Record<string, PatchBatchRequest>;
|
|
57
|
+
|
|
58
|
+
export interface FileWriteRequest {
|
|
59
|
+
chattr?: FileChattr;
|
|
60
|
+
content: string;
|
|
61
|
+
expectedSha256?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type FileWriteBatch = Record<string, FileWriteRequest>;
|
|
65
|
+
|
|
66
|
+
function temporary(filePath: string): string {
|
|
67
|
+
const extension = path.extname(filePath);
|
|
68
|
+
return path.join(
|
|
69
|
+
path.dirname(filePath),
|
|
70
|
+
`${path.basename(filePath, extension)}.ast-mcp-${randomUUID()}${extension}`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function removeTemporary(filePath: string) {
|
|
75
|
+
try {
|
|
76
|
+
await unlink(filePath);
|
|
77
|
+
} catch {}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function ensureParent(filePath: string): Promise<string[]> {
|
|
81
|
+
const parent = path.dirname(filePath);
|
|
82
|
+
const first = await mkdir(parent, { recursive: true });
|
|
83
|
+
const revalidated = await resolveWritablePath(filePath);
|
|
84
|
+
if (revalidated !== filePath)
|
|
85
|
+
throw new Error("Parent creation changed the resolved write path");
|
|
86
|
+
if (!first) return [];
|
|
87
|
+
const created = [first];
|
|
88
|
+
let current = first;
|
|
89
|
+
for (const segment of path.relative(first, parent).split(path.sep)) {
|
|
90
|
+
if (!segment) continue;
|
|
91
|
+
current = path.join(current, segment);
|
|
92
|
+
created.push(current);
|
|
93
|
+
}
|
|
94
|
+
return created;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function commit(
|
|
98
|
+
filePath: string,
|
|
99
|
+
content: string,
|
|
100
|
+
mode?: number,
|
|
101
|
+
expectedSha256?: string,
|
|
102
|
+
chattr?: FileChattr,
|
|
103
|
+
): Promise<string[]> {
|
|
104
|
+
const next = temporary(filePath);
|
|
105
|
+
let createdDirectories: string[] = [];
|
|
106
|
+
try {
|
|
107
|
+
const formatted = await formatContent(filePath, content);
|
|
108
|
+
try {
|
|
109
|
+
await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
112
|
+
createdDirectories = await ensureParent(filePath);
|
|
113
|
+
await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
|
|
114
|
+
}
|
|
115
|
+
if (mode !== undefined) await chmod(next, mode);
|
|
116
|
+
await applyFileChattr(next, chattr);
|
|
117
|
+
if (expectedSha256) {
|
|
118
|
+
const current = await readFile(filePath, "utf8");
|
|
119
|
+
const actual = sha256(current);
|
|
120
|
+
if (actual !== expectedSha256)
|
|
121
|
+
throw new Error(
|
|
122
|
+
`Stale file context: expected ${expectedSha256}, found ${actual}`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
await rename(next, filePath);
|
|
126
|
+
return createdDirectories;
|
|
127
|
+
} finally {
|
|
128
|
+
await removeTemporary(next);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function previewDiff(filePath: string, before: string, after: string): string {
|
|
132
|
+
if (before === after) return "";
|
|
133
|
+
const beforeLines = before.split("\n");
|
|
134
|
+
const afterLines = after.split("\n");
|
|
135
|
+
let start = 0;
|
|
136
|
+
while (
|
|
137
|
+
start < beforeLines.length &&
|
|
138
|
+
start < afterLines.length &&
|
|
139
|
+
beforeLines[start] === afterLines[start]
|
|
140
|
+
)
|
|
141
|
+
start += 1;
|
|
142
|
+
let beforeEnd = beforeLines.length;
|
|
143
|
+
let afterEnd = afterLines.length;
|
|
144
|
+
while (
|
|
145
|
+
beforeEnd > start &&
|
|
146
|
+
afterEnd > start &&
|
|
147
|
+
beforeLines[beforeEnd - 1] === afterLines[afterEnd - 1]
|
|
148
|
+
) {
|
|
149
|
+
beforeEnd -= 1;
|
|
150
|
+
afterEnd -= 1;
|
|
151
|
+
}
|
|
152
|
+
const lines = [
|
|
153
|
+
`--- ${filePath}`,
|
|
154
|
+
`+++ ${filePath}`,
|
|
155
|
+
`@@ -${start + 1},${beforeEnd - start} +${start + 1},${afterEnd - start} @@`,
|
|
156
|
+
...beforeLines.slice(start, beforeEnd).map((line) => `-${line}`),
|
|
157
|
+
...afterLines.slice(start, afterEnd).map((line) => `+${line}`),
|
|
158
|
+
];
|
|
159
|
+
return lines.length > 200
|
|
160
|
+
? [...lines.slice(0, 199), "... diff truncated"].join("\n")
|
|
161
|
+
: lines.join("\n");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function applyPatchBatch(
|
|
165
|
+
inputPath: string,
|
|
166
|
+
request: PatchBatchRequest,
|
|
167
|
+
): Promise<Record<string, unknown>> {
|
|
168
|
+
const filePath = await resolveWritablePath(inputPath);
|
|
169
|
+
return withFileLock(filePath, async () => {
|
|
170
|
+
const original = await readFile(filePath, "utf8");
|
|
171
|
+
const actual = sha256(original);
|
|
172
|
+
if (actual !== request.expectedSha256)
|
|
173
|
+
throw new Error(
|
|
174
|
+
"Stale file context: expected " +
|
|
175
|
+
request.expectedSha256 +
|
|
176
|
+
", found " +
|
|
177
|
+
actual,
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
const astRules = request.astRules ?? [];
|
|
181
|
+
const aiderBlocks = request.aiderBlocks ?? [];
|
|
182
|
+
const language = detectAstLanguage(filePath);
|
|
183
|
+
const rewritable = await astRewritable(filePath, language);
|
|
184
|
+
const previewResult = async (
|
|
185
|
+
candidate: string,
|
|
186
|
+
metadata: {
|
|
187
|
+
operations: number;
|
|
188
|
+
strategy: "ast" | "aider_block";
|
|
189
|
+
matches?: number;
|
|
190
|
+
matchMethods?: string[];
|
|
191
|
+
},
|
|
192
|
+
) => {
|
|
193
|
+
const formatted = await formatContent(filePath, candidate);
|
|
194
|
+
return {
|
|
195
|
+
changed: formatted !== original,
|
|
196
|
+
diff: previewDiff(filePath, original, formatted),
|
|
197
|
+
filePath,
|
|
198
|
+
matches: metadata.matches,
|
|
199
|
+
matchMethods: metadata.matchMethods,
|
|
200
|
+
operations: metadata.operations,
|
|
201
|
+
preview: true,
|
|
202
|
+
sha256: sha256(formatted),
|
|
203
|
+
strategy: metadata.strategy,
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
if (request.patchStrategy === "ast") {
|
|
208
|
+
if (!rewritable || !language)
|
|
209
|
+
throw new Error(
|
|
210
|
+
"REJECTED: non-structurally-rewritable files require patchStrategy 'aider_block' with aiderBlocks",
|
|
211
|
+
);
|
|
212
|
+
if (astRules.length === 0 || aiderBlocks.length > 0)
|
|
213
|
+
throw new Error(
|
|
214
|
+
"REJECTED: patchStrategy 'ast' requires astRules and no aiderBlocks",
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
const next = temporary(filePath);
|
|
218
|
+
const metadata = await lstat(filePath);
|
|
219
|
+
try {
|
|
220
|
+
await writeFile(next, original, {
|
|
221
|
+
encoding: "utf8",
|
|
222
|
+
flag: "wx",
|
|
223
|
+
mode: metadata.mode,
|
|
224
|
+
});
|
|
225
|
+
let totalMatches = 0;
|
|
226
|
+
for (const rule of astRules) {
|
|
227
|
+
const preview = parseAstBroJson(
|
|
228
|
+
await callAstBro(
|
|
229
|
+
"run",
|
|
230
|
+
{
|
|
231
|
+
json: true,
|
|
232
|
+
lang: language,
|
|
233
|
+
paths: [next],
|
|
234
|
+
pattern: rule.pattern,
|
|
235
|
+
},
|
|
236
|
+
path.dirname(filePath),
|
|
237
|
+
),
|
|
238
|
+
);
|
|
239
|
+
if (preview.error_count)
|
|
240
|
+
throw new Error(
|
|
241
|
+
`ast-bro preview failed with ${preview.error_count} errors`,
|
|
242
|
+
);
|
|
243
|
+
const matches = Array.isArray(preview.matches)
|
|
244
|
+
? preview.matches.length
|
|
245
|
+
: 0;
|
|
246
|
+
const expected = rule.expectedMatches ?? 1;
|
|
247
|
+
if (matches !== expected)
|
|
248
|
+
throw new Error(
|
|
249
|
+
`AST rule matched ${matches} nodes; expected ${expected}`,
|
|
250
|
+
);
|
|
251
|
+
if (expected !== 1)
|
|
252
|
+
throw new Error(
|
|
253
|
+
"ast-bro run rewrites only the first match per file; narrow the AST rule to exactly one node",
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
const rewritten = parseAstBroJson(
|
|
257
|
+
await callAstBro(
|
|
258
|
+
"run",
|
|
259
|
+
{
|
|
260
|
+
json: true,
|
|
261
|
+
lang: language,
|
|
262
|
+
paths: [next],
|
|
263
|
+
pattern: rule.pattern,
|
|
264
|
+
rewrite: rule.fix,
|
|
265
|
+
write: true,
|
|
266
|
+
},
|
|
267
|
+
path.dirname(filePath),
|
|
268
|
+
),
|
|
269
|
+
);
|
|
270
|
+
if (
|
|
271
|
+
rewritten.error_count ||
|
|
272
|
+
rewritten.rewrite_count !== 1 ||
|
|
273
|
+
rewritten.files?.[0]?.status !== "rewritten"
|
|
274
|
+
)
|
|
275
|
+
throw new Error("ast-bro run did not rewrite exactly one file");
|
|
276
|
+
totalMatches += matches;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const candidate = await readFile(next, "utf8");
|
|
280
|
+
if (request.preview)
|
|
281
|
+
return previewResult(candidate, {
|
|
282
|
+
matches: totalMatches,
|
|
283
|
+
operations: astRules.length,
|
|
284
|
+
strategy: "ast",
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
await commit(
|
|
288
|
+
filePath,
|
|
289
|
+
candidate,
|
|
290
|
+
metadata.mode,
|
|
291
|
+
actual,
|
|
292
|
+
request.chattr,
|
|
293
|
+
);
|
|
294
|
+
const updated = await readFile(filePath, "utf8");
|
|
295
|
+
return {
|
|
296
|
+
engine: "ast-bro.run",
|
|
297
|
+
filePath,
|
|
298
|
+
matches: totalMatches,
|
|
299
|
+
operations: astRules.length,
|
|
300
|
+
preview: false,
|
|
301
|
+
sha256: sha256(updated),
|
|
302
|
+
strategy: "ast",
|
|
303
|
+
};
|
|
304
|
+
} finally {
|
|
305
|
+
await removeTemporary(next);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (rewritable)
|
|
310
|
+
throw new Error(
|
|
311
|
+
"REJECTED: structurally rewritable files require patchStrategy 'ast' with astRules",
|
|
312
|
+
);
|
|
313
|
+
if (aiderBlocks.length === 0 || astRules.length > 0)
|
|
314
|
+
throw new Error(
|
|
315
|
+
"REJECTED: patchStrategy 'aider_block' requires aiderBlocks and no astRules",
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
let content = original;
|
|
319
|
+
const methods: string[] = [];
|
|
320
|
+
for (const block of aiderBlocks) {
|
|
321
|
+
const result = applyAiderBlock(content, block.search, block.replace);
|
|
322
|
+
content = result.content;
|
|
323
|
+
methods.push(result.method);
|
|
324
|
+
}
|
|
325
|
+
if (request.preview)
|
|
326
|
+
return previewResult(content, {
|
|
327
|
+
matchMethods: methods,
|
|
328
|
+
operations: aiderBlocks.length,
|
|
329
|
+
strategy: "aider_block",
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
await commit(
|
|
333
|
+
filePath,
|
|
334
|
+
content,
|
|
335
|
+
(await lstat(filePath)).mode,
|
|
336
|
+
actual,
|
|
337
|
+
request.chattr,
|
|
338
|
+
);
|
|
339
|
+
const updated = await readFile(filePath, "utf8");
|
|
340
|
+
return {
|
|
341
|
+
filePath,
|
|
342
|
+
matchMethods: methods,
|
|
343
|
+
operations: aiderBlocks.length,
|
|
344
|
+
preview: false,
|
|
345
|
+
sha256: sha256(updated),
|
|
346
|
+
strategy: "aider_block",
|
|
347
|
+
};
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export async function patchFile(
|
|
352
|
+
request: PatchRequest,
|
|
353
|
+
): Promise<Record<string, unknown>> {
|
|
354
|
+
return applyPatchBatch(request.filePath, {
|
|
355
|
+
aiderBlocks: request.aiderBlock ? [request.aiderBlock] : undefined,
|
|
356
|
+
astRules: request.astRule ? [request.astRule] : undefined,
|
|
357
|
+
expectedSha256: request.expectedSha256,
|
|
358
|
+
patchStrategy: request.patchStrategy,
|
|
359
|
+
preview: request.preview,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export async function patchFiles(
|
|
364
|
+
requests: PatchBatch,
|
|
365
|
+
): Promise<Record<string, unknown>> {
|
|
366
|
+
const entries = Object.entries(requests);
|
|
367
|
+
if (entries.length < 1 || entries.length > FILE_READ_MAX_BATCH)
|
|
368
|
+
throw new Error(
|
|
369
|
+
`file_patch requires between 1 and ${FILE_READ_MAX_BATCH} files`,
|
|
370
|
+
);
|
|
371
|
+
const files: Record<string, unknown> = {};
|
|
372
|
+
for (const [filePath, request] of entries)
|
|
373
|
+
files[filePath] = await applyPatchBatch(filePath, request);
|
|
374
|
+
return { files };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export async function writeFileSafely(args: {
|
|
378
|
+
chattr?: FileChattr;
|
|
379
|
+
filePath: string;
|
|
380
|
+
content: string;
|
|
381
|
+
expectedSha256?: string;
|
|
382
|
+
}): Promise<Record<string, unknown>> {
|
|
383
|
+
const filePath = await resolveWritablePath(args.filePath);
|
|
384
|
+
return withFileLock(filePath, async () => {
|
|
385
|
+
const existing = await readFile(filePath, "utf8").catch(() => undefined);
|
|
386
|
+
let createdDirectories: string[];
|
|
387
|
+
if (existing !== undefined) {
|
|
388
|
+
if (!args.expectedSha256)
|
|
389
|
+
throw new Error("Overwriting an existing file requires expectedSha256");
|
|
390
|
+
const actual = sha256(existing);
|
|
391
|
+
if (actual !== args.expectedSha256)
|
|
392
|
+
throw new Error(
|
|
393
|
+
"Stale file context: expected " +
|
|
394
|
+
args.expectedSha256 +
|
|
395
|
+
", found " +
|
|
396
|
+
actual,
|
|
397
|
+
);
|
|
398
|
+
const language = detectAstLanguage(filePath);
|
|
399
|
+
if (await astRewritable(filePath, language))
|
|
400
|
+
throw new Error(
|
|
401
|
+
"REJECTED: structurally rewritable existing files require file_patch with patchStrategy 'ast'",
|
|
402
|
+
);
|
|
403
|
+
createdDirectories = await commit(
|
|
404
|
+
filePath,
|
|
405
|
+
args.content,
|
|
406
|
+
(await lstat(filePath)).mode,
|
|
407
|
+
actual,
|
|
408
|
+
args.chattr,
|
|
409
|
+
);
|
|
410
|
+
} else
|
|
411
|
+
createdDirectories = await commit(
|
|
412
|
+
filePath,
|
|
413
|
+
args.content,
|
|
414
|
+
undefined,
|
|
415
|
+
undefined,
|
|
416
|
+
args.chattr,
|
|
417
|
+
);
|
|
418
|
+
const updated = await readFile(filePath, "utf8");
|
|
419
|
+
return {
|
|
420
|
+
chattr: await resultingFileChattr(filePath),
|
|
421
|
+
created: existing === undefined,
|
|
422
|
+
createdDirectories,
|
|
423
|
+
filePath,
|
|
424
|
+
sha256: sha256(updated),
|
|
425
|
+
};
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export async function writeFilesSafely(
|
|
430
|
+
requests: FileWriteBatch,
|
|
431
|
+
): Promise<Record<string, unknown>> {
|
|
432
|
+
const entries = Object.entries(requests);
|
|
433
|
+
if (entries.length < 1 || entries.length > FILE_READ_MAX_BATCH)
|
|
434
|
+
throw new Error(
|
|
435
|
+
`file_write requires between 1 and ${FILE_READ_MAX_BATCH} files`,
|
|
436
|
+
);
|
|
437
|
+
const files: Record<string, unknown> = {};
|
|
438
|
+
for (const [filePath, request] of entries)
|
|
439
|
+
files[filePath] = await writeFileSafely({
|
|
440
|
+
chattr: request.chattr,
|
|
441
|
+
content: request.content,
|
|
442
|
+
expectedSha256: request.expectedSha256,
|
|
443
|
+
filePath,
|
|
444
|
+
});
|
|
445
|
+
return { files };
|
|
446
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
const languages: Record<string, string> = {
|
|
4
|
+
".cc": "cpp",
|
|
5
|
+
".cjs": "javascript",
|
|
6
|
+
".cpp": "cpp",
|
|
7
|
+
".cs": "csharp",
|
|
8
|
+
".cxx": "cpp",
|
|
9
|
+
".ddl": "sql",
|
|
10
|
+
".dml": "sql",
|
|
11
|
+
".go": "go",
|
|
12
|
+
".hh": "cpp",
|
|
13
|
+
".hpp": "cpp",
|
|
14
|
+
".java": "java",
|
|
15
|
+
".js": "javascript",
|
|
16
|
+
".jsx": "javascript",
|
|
17
|
+
".kt": "kotlin",
|
|
18
|
+
".kts": "kotlin",
|
|
19
|
+
".markdown": "markdown",
|
|
20
|
+
".md": "markdown",
|
|
21
|
+
".mdown": "markdown",
|
|
22
|
+
".mdx": "markdown",
|
|
23
|
+
".mjs": "javascript",
|
|
24
|
+
".php": "php",
|
|
25
|
+
".py": "python",
|
|
26
|
+
".pyi": "python",
|
|
27
|
+
".rb": "ruby",
|
|
28
|
+
".rs": "rust",
|
|
29
|
+
".scala": "scala",
|
|
30
|
+
".sql": "sql",
|
|
31
|
+
".ts": "typescript",
|
|
32
|
+
".tsx": "tsx",
|
|
33
|
+
};
|
|
34
|
+
export function detectAstLanguage(filePath: string): string | undefined {
|
|
35
|
+
return languages[path.extname(filePath).toLowerCase()];
|
|
36
|
+
}
|