@mwillbanks/ast-mcp 0.1.3 → 0.2.1

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 (58) hide show
  1. package/README.md +59 -20
  2. package/dist/ast-mcp.js +232 -130
  3. package/dist/ast-mcp.js.map +107 -27
  4. package/package.json +2 -1
  5. package/src/ast-bro/capability.ts +3 -8
  6. package/src/ast-bro/client.ts +18 -2
  7. package/src/ast-bro/result.ts +5 -12
  8. package/src/cli.ts +70 -95
  9. package/src/config-cli.ts +54 -0
  10. package/src/config.ts +886 -0
  11. package/src/helpers/aider.ts +252 -0
  12. package/src/helpers/ast-bro.ts +64 -0
  13. package/src/helpers/config.ts +149 -0
  14. package/src/helpers/hook.ts +60 -0
  15. package/src/helpers/installer.ts +249 -0
  16. package/src/helpers/json.ts +19 -0
  17. package/src/helpers/mcp-schema.ts +31 -0
  18. package/src/helpers/process.ts +31 -0
  19. package/src/helpers/string.ts +97 -0
  20. package/src/hook.ts +135 -40
  21. package/src/http-entry.ts +1 -1
  22. package/src/http.ts +118 -103
  23. package/src/installer-transport.ts +190 -0
  24. package/src/installer.ts +604 -247
  25. package/src/mcp-cli.ts +104 -0
  26. package/src/patch/aider.ts +6 -199
  27. package/src/patch/engine.ts +271 -197
  28. package/src/runtime/dependencies.ts +48 -29
  29. package/src/runtime/file-delete.ts +13 -9
  30. package/src/runtime/file-read.ts +91 -57
  31. package/src/runtime/file-rename.ts +158 -0
  32. package/src/runtime/format.ts +57 -34
  33. package/src/runtime/paths.ts +30 -16
  34. package/src/runtime/policy.ts +21 -0
  35. package/src/runtime/process-input.ts +14 -4
  36. package/src/service.ts +217 -0
  37. package/src/shell-policy.ts +331 -0
  38. package/src/stdio.ts +47 -35
  39. package/src/tools/ast-bro.ts +12 -6
  40. package/src/tools/configured.ts +28 -0
  41. package/src/tools/files.ts +24 -27
  42. package/src/tools/index.ts +5 -3
  43. package/src/tools/lifecycle.ts +69 -55
  44. package/templates/skills/ast-mcp/SKILL.md +7 -6
  45. package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
  46. package/templates/skills/ast-mcp/evals/evals.json +1 -0
  47. package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
  48. package/templates/skills/ast-mcp/evals/score.ts +304 -267
  49. package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
  50. package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
  51. package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
  52. package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
  53. package/templates/skills/ast-mcp/evals/source.ts +164 -0
  54. package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
  55. package/templates/skills/ast-mcp/references/installation.md +9 -8
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +323 -131
@@ -1,4 +1,6 @@
1
1
  import path from "node:path";
2
+ import { embeddedShellMutates, shellMutates } from "./shell-policy";
3
+ import { advanceQuote } from "./source";
2
4
 
3
5
  export type EvalCase = {
4
6
  id: number;
@@ -40,44 +42,68 @@ function hasKey(input: string, key: string) {
40
42
  return new RegExp(`(?:["']${key}["']|\\b${key})\\s*:`).test(input);
41
43
  }
42
44
 
43
- function withoutComments(input: string) {
44
- let output = "";
45
- let quote = "";
46
- let escaped = false;
47
- for (let index = 0; index < input.length; index += 1) {
48
- const character = input[index] as string;
49
- const next = input[index + 1];
50
- if (quote) {
51
- output += character;
52
- if (escaped) escaped = false;
53
- else if (character === "\\") escaped = true;
54
- else if (character === quote) quote = "";
55
- continue;
56
- }
57
- if (character === '"' || character === "'" || character === "`") {
58
- quote = character;
59
- output += character;
60
- continue;
61
- }
62
- if (character === "/" && next === "/") {
63
- while (index + 1 < input.length && input[index + 1] !== "\n") index += 1;
64
- output += "\n";
65
- continue;
66
- }
67
- if (character === "/" && next === "*") {
68
- index += 2;
69
- while (
70
- index + 1 < input.length &&
71
- !(input[index] === "*" && input[index + 1] === "/")
72
- )
73
- index += 1;
74
- index += 1;
75
- output += " ";
76
- continue;
45
+ class CommentStripper {
46
+ private index = 0;
47
+ private output = "";
48
+ private quote = "";
49
+ private escaped = false;
50
+
51
+ constructor(private readonly input: string) {}
52
+
53
+ read() {
54
+ while (this.index < this.input.length) {
55
+ if (this.quote) this.readQuoted();
56
+ else this.readCode();
57
+ this.index += 1;
77
58
  }
78
- output += character;
59
+ return this.output;
60
+ }
61
+
62
+ private readQuoted() {
63
+ const character = this.input[this.index] as string;
64
+ this.output += character;
65
+ const state = advanceQuote(character, this.quote, this.escaped);
66
+ this.quote = state.quote;
67
+ this.escaped = state.escaped;
68
+ }
69
+
70
+ private readCode() {
71
+ const character = this.input[this.index] as string;
72
+ const next = this.input[this.index + 1];
73
+ if ("\"'`".includes(character)) return this.beginQuote(character);
74
+ if (character === "/" && next === "/") return this.skipLineComment();
75
+ if (character === "/" && next === "*") return this.skipBlockComment();
76
+ this.output += character;
77
+ }
78
+
79
+ private beginQuote(character: string) {
80
+ this.quote = character;
81
+ this.output += character;
82
+ }
83
+
84
+ private skipLineComment() {
85
+ while (
86
+ this.index + 1 < this.input.length &&
87
+ this.input[this.index + 1] !== "\n"
88
+ )
89
+ this.index += 1;
90
+ this.output += "\n";
79
91
  }
80
- return output;
92
+
93
+ private skipBlockComment() {
94
+ this.index += 2;
95
+ while (
96
+ this.index + 1 < this.input.length &&
97
+ !(this.input[this.index] === "*" && this.input[this.index + 1] === "/")
98
+ )
99
+ this.index += 1;
100
+ this.index += 1;
101
+ this.output += " ";
102
+ }
103
+ }
104
+
105
+ function withoutComments(input: string) {
106
+ return new CommentStripper(input).read();
81
107
  }
82
108
 
83
109
  function hasBoolean(input: string, key: string, value: boolean) {
@@ -86,22 +112,29 @@ function hasBoolean(input: string, key: string, value: boolean) {
86
112
  ).test(input);
87
113
  }
88
114
 
115
+ type InputValidator = (input: string) => boolean;
116
+
117
+ const hasKeyedPath = (input: string) => /["'][^"']+["']\s*:/.test(input);
118
+ const inputValidators: Record<string, InputValidator> = {
119
+ file_chattr: (input) => hasKey(input, "chattr") && hasKeyedPath(input),
120
+ file_delete: (input) =>
121
+ hasKey(input, "expectedSha256") && hasKeyedPath(input),
122
+ file_patch: (input) =>
123
+ hasKey(input, "expectedSha256") &&
124
+ hasKey(input, "patchStrategy") &&
125
+ (hasKey(input, "astRules") || hasKey(input, "aiderBlocks")),
126
+ file_rename: (input) =>
127
+ hasKey(input, "expectedSha256") &&
128
+ hasKey(input, "destination") &&
129
+ hasKeyedPath(input),
130
+ file_write: (input) => hasKey(input, "content") && hasKeyedPath(input),
131
+ };
132
+
89
133
  function meaningfulInput(invocation: Invocation) {
90
134
  const input = withoutComments(invocation.input).trim();
91
135
  if (!input || input === "{}") return false;
92
- if (invocation.tool === "file_patch") {
93
- return (
94
- hasKey(input, "expectedSha256") &&
95
- hasKey(input, "patchStrategy") &&
96
- (hasKey(input, "astRules") || hasKey(input, "aiderBlocks"))
97
- );
98
- }
99
- if (invocation.tool === "file_write")
100
- return hasKey(input, "content") && /["'][^"']+["']\s*:/.test(input);
101
- if (invocation.tool === "file_chattr")
102
- return hasKey(input, "chattr") && /["'][^"']+["']\s*:/.test(input);
103
- if (invocation.tool === "file_delete")
104
- return hasKey(input, "expectedSha256") && /["'][^"']+["']\s*:/.test(input);
136
+ const validator = inputValidators[invocation.tool];
137
+ if (validator) return validator(input);
105
138
  return (toolKeys[invocation.tool] ?? []).every((key) => hasKey(input, key));
106
139
  }
107
140
 
@@ -117,33 +150,50 @@ function pathIsWithinRoot(candidate: string, roots: string[]) {
117
150
  });
118
151
  }
119
152
 
153
+ const singlePathExpression =
154
+ /["']?(?:filePath|file|path|root|destination)["']?\s*:\s*["']([^"']+)["']/g;
155
+ const pathArrayExpression =
156
+ /["']?(?:filePaths|paths)["']?\s*:\s*\[([^\]]*)\]/gs;
157
+ const keyedPathExpression =
158
+ /["']([^"']+)["']\s*:\s*\{\s*(?:content|expectedSha256|destination|chattr|astRules|aiderBlocks|patchStrategy)\s*:/g;
159
+
160
+ function expressionValues(input: string, expression: RegExp) {
161
+ expression.lastIndex = 0;
162
+ const values: string[] = [];
163
+ for (const match of input.matchAll(expression))
164
+ if (match[1]) values.push(match[1]);
165
+ return values;
166
+ }
167
+
168
+ function pathCandidates(input: string) {
169
+ const candidates = [
170
+ ...expressionValues(input, singlePathExpression),
171
+ ...expressionValues(input, keyedPathExpression),
172
+ ];
173
+ pathArrayExpression.lastIndex = 0;
174
+ for (const match of input.matchAll(pathArrayExpression)) {
175
+ for (const value of match[1]?.matchAll(/["']([^"']+)["']/g) ?? []) {
176
+ if (value[1]) candidates.push(value[1]);
177
+ }
178
+ }
179
+ return candidates;
180
+ }
181
+
182
+ function escapedPath(candidate: string, roots: string[]) {
183
+ const pathLike = candidate.includes("/") || candidate.includes("\\");
184
+ return pathLike && !pathIsWithinRoot(candidate, roots);
185
+ }
186
+
120
187
  function pathErrors(invocations: Invocation[], roots: string[]) {
121
188
  const errors: string[] = [];
122
- const singlePath =
123
- /["']?(?:filePath|file|path|root)["']?\s*:\s*["']([^"']+)["']/g;
124
- const pathArray = /["']?(?:filePaths|paths)["']?\s*:\s*\[([^\]]*)\]/gs;
125
- const keyedPath =
126
- /["']([^"']+)["']\s*:\s*\{\s*(?:content|expectedSha256|chattr|astRules|aiderBlocks|patchStrategy)\s*:/g;
127
189
  for (const invocation of invocations) {
128
- const input = withoutComments(invocation.input);
129
- const candidates: string[] = [];
130
- for (const expression of [singlePath, keyedPath]) {
131
- expression.lastIndex = 0;
132
- for (const match of input.matchAll(expression))
133
- if (match[1]) candidates.push(match[1]);
134
- }
135
- pathArray.lastIndex = 0;
136
- for (const match of input.matchAll(pathArray))
137
- for (const value of match[1]?.matchAll(/["']([^"']+)["']/g) ?? [])
138
- if (value[1]) candidates.push(value[1]);
139
- for (const candidate of candidates)
140
- if (
141
- (candidate.includes("/") || candidate.includes("\\")) &&
142
- !pathIsWithinRoot(candidate, roots)
143
- )
190
+ const candidates = pathCandidates(withoutComments(invocation.input));
191
+ for (const candidate of candidates) {
192
+ if (escapedPath(candidate, roots))
144
193
  errors.push(
145
194
  `${invocation.tool} input escapes transcript workspace roots: ${candidate}`,
146
195
  );
196
+ }
147
197
  }
148
198
  return errors;
149
199
  }
@@ -151,9 +201,13 @@ function pathErrors(invocations: Invocation[], roots: string[]) {
151
201
  function isBatch(invocation: Invocation) {
152
202
  const input = withoutComments(invocation.input);
153
203
  if (
154
- ["file_patch", "file_write", "file_chattr", "file_delete"].includes(
155
- invocation.tool,
156
- )
204
+ [
205
+ "file_patch",
206
+ "file_write",
207
+ "file_chattr",
208
+ "file_delete",
209
+ "file_rename",
210
+ ].includes(invocation.tool)
157
211
  )
158
212
  return (input.match(/["'][^"']+["']\s*:\s*\{/g) ?? []).length > 1;
159
213
  if (invocation.tool === "file_hash")
@@ -163,110 +217,280 @@ function isBatch(invocation: Invocation) {
163
217
  return false;
164
218
  }
165
219
 
166
- function assertionSatisfied(
220
+ type RenameFiles = Record<
221
+ string,
222
+ { destinationPath?: string; renamed?: boolean }
223
+ >;
224
+
225
+ function renameEntryMatches(
226
+ files: RenameFiles,
227
+ workspaceRoot: string,
228
+ entry: [string, unknown],
229
+ ) {
230
+ const [source, value] = entry;
231
+ if (!value || typeof value !== "object") return false;
232
+ const destination = (value as { destination?: unknown }).destination;
233
+ if (typeof destination !== "string") return false;
234
+ const destinationPath = path.resolve(workspaceRoot, destination);
235
+ const sourcePath = path.resolve(workspaceRoot, source);
236
+ const file = files[source] ?? files[sourcePath];
237
+ return (
238
+ file?.destinationPath !== undefined &&
239
+ path.resolve(file.destinationPath) === destinationPath &&
240
+ file.renamed === true
241
+ );
242
+ }
243
+
244
+ function renameResultsCoverInputs(
245
+ call: Invocation,
246
+ output: string,
247
+ roots: string[] = [],
248
+ ) {
249
+ try {
250
+ const request = JSON.parse(call.input) as Record<string, unknown>;
251
+ const result = JSON.parse(output) as { files?: RenameFiles };
252
+ if (!result.files) return false;
253
+ const workspaceRoot = roots[0] ?? process.cwd();
254
+ return Object.entries(request).every((entry) =>
255
+ renameEntryMatches(result.files as RenameFiles, workspaceRoot, entry),
256
+ );
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+
262
+ function shellMutationSource(source: string) {
263
+ return embeddedShellMutates(source) || shellMutates(source);
264
+ }
265
+
266
+ interface AssertionContext {
267
+ evaluation: EvalCase;
268
+ invocations: Invocation[];
269
+ normalized: string;
270
+ output: string;
271
+ roots: string[];
272
+ sanitized: Invocation[];
273
+ source: string;
274
+ tools: Set<string>;
275
+ }
276
+
277
+ type AssertionRule = (context: AssertionContext) => boolean | undefined;
278
+
279
+ function assertionContext(
167
280
  assertion: string,
168
281
  evaluation: EvalCase,
169
282
  invocations: Invocation[],
170
283
  output: string,
171
- ) {
172
- const normalized = assertion.toLowerCase();
173
- const sanitizedInvocations = invocations.map((invocation) => ({
284
+ roots: string[],
285
+ ): AssertionContext {
286
+ const sanitized = invocations.map((invocation) => ({
174
287
  ...invocation,
175
288
  input: withoutComments(invocation.input),
176
289
  }));
177
- const tools = new Set(
178
- sanitizedInvocations.map((invocation) => invocation.tool),
290
+ return {
291
+ evaluation,
292
+ invocations,
293
+ normalized: assertion.toLowerCase(),
294
+ output,
295
+ roots,
296
+ sanitized,
297
+ source: sanitized.map((invocation) => invocation.input).join("\n"),
298
+ tools: new Set(sanitized.map((invocation) => invocation.tool)),
299
+ };
300
+ }
301
+
302
+ function calls(context: AssertionContext, tool: string) {
303
+ return context.sanitized.filter((invocation) => invocation.tool === tool);
304
+ }
305
+
306
+ function rejectedDestinationAssertion(
307
+ renameCalls: Invocation[],
308
+ output: string,
309
+ ) {
310
+ return (
311
+ renameCalls.length > 0 &&
312
+ /(?:already exists|destination.*exist|exist.*destination|rejected|error|failed)/i.test(
313
+ output,
314
+ ) &&
315
+ /destination/i.test(output)
316
+ );
317
+ }
318
+
319
+ function renameReportAssertion(
320
+ renameCalls: Invocation[],
321
+ output: string,
322
+ roots: string[],
323
+ ) {
324
+ if (renameCalls.length === 0) return false;
325
+ return (
326
+ renameResultsCoverInputs(renameCalls[0] as Invocation, output, roots) &&
327
+ /["']?files["']?\s*:/i.test(output) &&
328
+ /destinationPath|renamed/i.test(output)
179
329
  );
180
- const source = sanitizedInvocations
181
- .map((invocation) => invocation.input)
182
- .join("\n");
183
- const calls = (tool: string) =>
184
- sanitizedInvocations.filter((invocation) => invocation.tool === tool);
330
+ }
331
+
332
+ function renameAssertion(context: AssertionContext): boolean | undefined {
333
+ const { normalized, output, roots } = context;
334
+ const renameCalls = calls(context, "file_rename");
335
+ if (
336
+ normalized.includes("does not overwrite") ||
337
+ normalized.includes("existing destination")
338
+ )
339
+ return rejectedDestinationAssertion(renameCalls, output);
340
+ if (
341
+ normalized.includes("reports each source") &&
342
+ normalized.includes("destination")
343
+ )
344
+ return renameReportAssertion(renameCalls, output, roots);
345
+ return undefined;
346
+ }
347
+
348
+ function prohibitionAssertion(context: AssertionContext): boolean | undefined {
349
+ const { evaluation, normalized, source, tools } = context;
185
350
  if (
186
351
  normalized.includes("does not call") ||
187
352
  normalized.includes("does not use") ||
188
353
  normalized.includes("never calls")
189
- )
190
- return evaluation.forbidden_tools.every((tool) => !tools.has(tool));
354
+ ) {
355
+ return (
356
+ evaluation.forbidden_tools.every((tool) => !tools.has(tool)) &&
357
+ !(normalized.includes("shell") && shellMutationSource(source))
358
+ );
359
+ }
191
360
  if (
192
361
  normalized.includes("direct filesystem") ||
193
362
  normalized.includes("direct editor") ||
194
363
  normalized.includes("shell mutation")
195
364
  )
196
- return !/(?:writeFile|apply_patch|sed\s+-i|tee\s|>\s*["']?[^=])/i.test(
197
- source,
198
- );
199
- if (normalized.includes("bounded") && normalized.includes("lines"))
200
- return calls("file_read").some((call) =>
365
+ return !shellMutationSource(source);
366
+ return undefined;
367
+ }
368
+
369
+ function readAssertion(context: AssertionContext): boolean | undefined {
370
+ const { normalized } = context;
371
+ const readCalls = calls(context, "file_read");
372
+ if (normalized.includes("bounded") && normalized.includes("lines")) {
373
+ return readCalls.some((call) =>
201
374
  /lines\s*:\s*\[\s*\d+\s*,\s*\d+\s*\]/.test(call.input),
202
375
  );
376
+ }
203
377
  if (normalized.includes("maxbytes") || normalized.includes("64 kib"))
204
- return calls("file_read").every((call) => hasKey(call.input, "maxBytes"));
378
+ return readCalls.every((call) => hasKey(call.input, "maxBytes"));
379
+ return undefined;
380
+ }
381
+
382
+ function hashPrecedesMutation(context: AssertionContext) {
383
+ const hashIndex = calls(context, "file_hash")[0]?.index;
384
+ const mutation = context.invocations.find((call) =>
385
+ ["file_patch", "file_write", "file_delete", "file_rename"].includes(
386
+ call.tool,
387
+ ),
388
+ );
389
+ return (
390
+ hashIndex !== undefined &&
391
+ mutation?.index !== undefined &&
392
+ hashIndex < mutation.index
393
+ );
394
+ }
395
+
396
+ function workflowAssertion(context: AssertionContext): boolean | undefined {
397
+ const { invocations, normalized } = context;
398
+ const patchCalls = calls(context, "file_patch");
205
399
  if (normalized.includes("batch") || normalized.includes("one keyed"))
206
400
  return invocations.some(isBatch);
207
- if (normalized.includes("fresh") && normalized.includes("hash")) {
208
- const hashIndex = calls("file_hash")[0]?.index;
209
- const mutationIndex = invocations.find((call) =>
210
- ["file_patch", "file_write", "file_delete"].includes(call.tool),
211
- )?.index;
212
- return (
213
- hashIndex !== undefined &&
214
- mutationIndex !== undefined &&
215
- hashIndex < mutationIndex
216
- );
217
- }
401
+ if (normalized.includes("fresh") && normalized.includes("hash"))
402
+ return hashPrecedesMutation(context);
218
403
  if (normalized.includes("preview true"))
219
- return calls("file_patch").some((call) =>
220
- hasBoolean(call.input, "preview", true),
221
- );
222
- if (normalized.includes("preview") || normalized.includes("dry run"))
404
+ return patchCalls.some((call) => hasBoolean(call.input, "preview", true));
405
+ if (normalized.includes("preview") || normalized.includes("dry run")) {
223
406
  return (
224
- calls("run").some((call) => !hasBoolean(call.input, "write", true)) ||
225
- calls("file_patch").some((call) =>
226
- hasBoolean(call.input, "preview", true),
227
- )
407
+ calls(context, "run").some(
408
+ (call) => !hasBoolean(call.input, "write", true),
409
+ ) || patchCalls.some((call) => hasBoolean(call.input, "preview", true))
228
410
  );
411
+ }
412
+ return undefined;
413
+ }
414
+
415
+ function strategyAssertion(context: AssertionContext): boolean | undefined {
416
+ const { normalized } = context;
417
+ const patchCalls = calls(context, "file_patch");
229
418
  if (normalized.includes("exactly one match"))
230
- return calls("file_patch").some((call) =>
419
+ return patchCalls.some((call) =>
231
420
  /expectedMatches\s*:\s*1\b/.test(call.input),
232
421
  );
233
422
  if (
234
423
  normalized.includes("ast strategy") ||
235
424
  normalized.includes("patchstrategy ast")
236
425
  )
237
- return calls("file_patch").some((call) =>
426
+ return patchCalls.some((call) =>
238
427
  /patchStrategy\s*:\s*["']ast["']/.test(call.input),
239
428
  );
240
429
  if (normalized.includes("aider"))
241
- return calls("file_patch").some((call) =>
430
+ return patchCalls.some((call) =>
242
431
  /patchStrategy\s*:\s*["']aider_block["']/.test(call.input),
243
432
  );
433
+ return undefined;
434
+ }
435
+
436
+ function outputAssertion(context: AssertionContext): boolean | undefined {
437
+ const { normalized, output } = context;
244
438
  if (
245
439
  normalized.includes("reports") ||
246
440
  normalized.includes("verification") ||
247
441
  normalized.includes("output")
248
442
  )
249
443
  return output.trim().length > 0;
250
- return (
251
- evaluation.required_tools.every((tool) => tools.has(tool)) &&
252
- sanitizedInvocations.every(meaningfulInput) &&
253
- output.trim().length > 0
254
- );
444
+ return undefined;
255
445
  }
256
446
 
257
- export function verifyEvaluation(
447
+ const assertionRules: AssertionRule[] = [
448
+ renameAssertion,
449
+ prohibitionAssertion,
450
+ readAssertion,
451
+ workflowAssertion,
452
+ strategyAssertion,
453
+ outputAssertion,
454
+ ];
455
+
456
+ function assertionSatisfied(
457
+ assertion: string,
258
458
  evaluation: EvalCase,
259
459
  invocations: Invocation[],
260
460
  output: string,
261
- roots: string[],
461
+ roots: string[] = [],
262
462
  ) {
263
- const errors: string[] = [];
264
- const sanitizedInvocations = invocations.map((invocation) => ({
463
+ const context = assertionContext(
464
+ assertion,
465
+ evaluation,
466
+ invocations,
467
+ output,
468
+ roots,
469
+ );
470
+ for (const rule of assertionRules) {
471
+ const result = rule(context);
472
+ if (result !== undefined) return result;
473
+ }
474
+ return (
475
+ context.evaluation.required_tools.every((tool) =>
476
+ context.tools.has(tool),
477
+ ) &&
478
+ context.sanitized.every(meaningfulInput) &&
479
+ context.output.trim().length > 0
480
+ );
481
+ }
482
+
483
+ function sanitizeInvocations(invocations: Invocation[]): Invocation[] {
484
+ return invocations.map((invocation) => ({
265
485
  ...invocation,
266
486
  input: withoutComments(invocation.input),
267
487
  }));
488
+ }
489
+
490
+ function toolContractErrors(evaluation: EvalCase, invocations: Invocation[]) {
491
+ const errors: string[] = [];
268
492
  const tools = new Set(
269
- sanitizedInvocations.map((invocation) => invocation.tool),
493
+ sanitizeInvocations(invocations).map((invocation) => invocation.tool),
270
494
  );
271
495
  for (const tool of evaluation.required_tools)
272
496
  if (!tools.has(tool)) errors.push(`missing required tool: ${tool}`);
@@ -275,6 +499,11 @@ export function verifyEvaluation(
275
499
  for (const invocation of invocations)
276
500
  if (!meaningfulInput(invocation))
277
501
  errors.push(`${invocation.tool} has empty or schema-incomplete input`);
502
+ return errors;
503
+ }
504
+
505
+ function sequenceErrors(evaluation: EvalCase, invocations: Invocation[]) {
506
+ const errors: string[] = [];
278
507
  if (
279
508
  evaluation.required_tools.length > 1 &&
280
509
  invocations.some(
@@ -290,13 +519,21 @@ export function verifyEvaluation(
290
519
  (invocation) => invocation.tool === tool && invocation.index > priorIndex,
291
520
  );
292
521
  if (!next) {
293
- if (tools.has(tool))
522
+ if (invocations.some((invocation) => invocation.tool === tool))
294
523
  errors.push(`required tool sequence is not satisfied at: ${tool}`);
295
524
  continue;
296
525
  }
297
526
  priorIndex = next.index;
298
527
  }
299
- errors.push(...pathErrors(invocations, roots));
528
+ return errors;
529
+ }
530
+
531
+ function fileEvidenceErrors(
532
+ evaluation: EvalCase,
533
+ invocations: Invocation[],
534
+ output: string,
535
+ ) {
536
+ const errors: string[] = [];
300
537
  for (const file of evaluation.files) {
301
538
  if (
302
539
  !invocations.some((invocation) =>
@@ -307,26 +544,44 @@ export function verifyEvaluation(
307
544
  if (!output.includes(file))
308
545
  errors.push(`output does not prove file result: ${file}`);
309
546
  }
547
+ return errors;
548
+ }
549
+
550
+ function transportOutputMissing(evaluation: EvalCase, output: string) {
551
+ if (evaluation.required_tools.length !== 0) return false;
552
+ return !evaluation.expected_output
553
+ .toLowerCase()
554
+ .split(/\W+/)
555
+ .filter((word) => word.length >= 7)
556
+ .some((word) => output.toLowerCase().includes(word));
557
+ }
558
+
559
+ export function verifyEvaluation(
560
+ evaluation: EvalCase,
561
+ invocations: Invocation[],
562
+ output: string,
563
+ roots: string[],
564
+ ) {
565
+ const errors = [
566
+ ...toolContractErrors(evaluation, invocations),
567
+ ...sequenceErrors(evaluation, invocations),
568
+ ...pathErrors(invocations, roots),
569
+ ...fileEvidenceErrors(evaluation, invocations, output),
570
+ ];
310
571
  if (
311
572
  !assertionSatisfied(
312
573
  evaluation.expected_output,
313
574
  evaluation,
314
575
  invocations,
315
576
  output,
577
+ roots,
316
578
  )
317
579
  )
318
580
  errors.push(`expected output not proven: ${evaluation.expected_output}`);
319
- if (
320
- evaluation.required_tools.length === 0 &&
321
- !evaluation.expected_output
322
- .toLowerCase()
323
- .split(/\W+/)
324
- .filter((word) => word.length >= 7)
325
- .some((word) => output.toLowerCase().includes(word))
326
- )
581
+ if (transportOutputMissing(evaluation, output))
327
582
  errors.push("output does not prove expected transport behavior");
328
583
  for (const assertion of evaluation.assertions)
329
- if (!assertionSatisfied(assertion, evaluation, invocations, output))
584
+ if (!assertionSatisfied(assertion, evaluation, invocations, output, roots))
330
585
  errors.push(`assertion not proven: ${assertion}`);
331
586
  return errors;
332
587
  }