@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
@@ -15,43 +15,55 @@ Treat ast-mcp as the only code-intelligence and filesystem boundary. Do not call
15
15
 
16
16
  ## Explore before editing
17
17
 
18
- - AST-capable files must be inspected with AST intelligence, never `file_read`: start unfamiliar work with `digest`, use `map` for one file's shape, and use `show` for exact symbols.
18
+ - Start unfamiliar work with `digest`, use `map` for one file's shape, and use `show` for exact symbols. When a file workflow is uncertain, call `file_capabilities` once for all relevant paths; `file_read`, `run`, and `file_patch` enforce that same result.
19
19
  - Use `search` when names are unknown and `find_related` for code similar to a known location.
20
20
  - Use `context` for a symbol plus nearby calls; use `impact` before changing a public or shared symbol.
21
21
  - Use `deps`, `reverse_deps`, `graph`, or `cycles` for module relationships.
22
22
  - Use `callers`, `callees`, or `trace` for execution flow; use `implements` for type hierarchies.
23
23
  - Use `surface` for exported API shape, `index` for search-index maintenance, and `squeeze` only for repetitive logs or text.
24
- - Use `file_read` only for unsupported non-AST content. Request explicit zero-based, end-exclusive line slices, accept the default `[0, 100]` only when sufficient, and batch multiple files in one call.
24
+ - `file_read` accepts an agent-selected `mode`: `ast` returns a source map/requested symbols or RFC 6901-selected structured-document values, `text` returns a bounded zero-based end-exclusive slice, and `auto` prefers AST when supported. Use `symbols` for source and `selectors` for JSON, JSONC, TOML, or YAML. Text mode remains available for AST-capable files when exact source text is necessary. Batch multiple files in one call.
25
25
  - Use ast-mcp intelligence as the primary repository search route. Never invoke `ast-grep` directly and never use `sed` for repository reads or edits. `rg` is permitted only as a discouraged fallback for exact literals, identifiers, non-AST formats, or discovery unavailable through ast-mcp; external transcript analysis, Git metadata, validation, and live-runtime reproduction are exceptions.
26
26
 
27
27
  Read [tool-catalog.md](references/tool-catalog.md) for exact arguments and combinations.
28
28
 
29
- ## Mutate through keyed file_patch and file_write
30
-
31
- 1. Inspect AST-capable targets with `map`, `show`, `context`, or a bounded `run` search. For unsupported content, use one batched `file_read({ files: [...] })` call with narrow line ranges.
32
- 2. Preview every AST rule with `run({ pattern, paths: [filePath], lang?, json: true })`; inspect all matches and reject capped output before mutation. For a contract-level dry run, send the same keyed `file_patch` entry with `preview: true`; it returns the formatted bounded diff and never commits.
33
- 3. Call one batched `file_hash({ filePaths: [...] })` immediately before guarded edits. Keep one returned hash per keyed path. The runtime can make hashes optional through `safety.require_hash = false`, but the normal agent workflow should still supply them whenever current-state protection matters.
34
- 4. Use one path-keyed `file_patch` batch for one or more files:
35
- - AST targets: `{ expectedSha256, patchStrategy: "ast", astRules: [{ pattern, fix, expectedMatches: 1 }], preview?: boolean }`
36
- - Unsupported targets: `{ expectedSha256, patchStrategy: "aider_block", aiderBlocks: [{ search, replace }], preview?: boolean }`
37
- Operations in each array run in order under one file lock; preview returns without committing and normal mode commits atomically.
38
- 5. Use one path-keyed `file_write` batch for new files or SHA-guarded replacement of existing non-structurally-rewritable files. Supply the shared `chattr` object when chmod/chown metadata is required; missing parents are created only after a guarded `ENOENT` write and path revalidation.
39
- 6. Use one path-keyed `file_rename` batch for hash-guarded, root-bounded file moves; validate every source and destination, reject existing destinations, and use no-replace moves. Ordinary failures roll back completed entries when possible; the operation is not crash-atomic.
40
- 7. Use `file_chattr` for metadata-only changes. Use hash-guarded `file_delete` for deletion; it preflights all targets and AST import references before any deletion, requires an explicit `forceReferences` override for referenced source, and removes empty ancestor directories after lock release.
41
- 8. Use direct `run` with `rewrite` and `write: true` only for an intentionally bounded lower-level rewrite; it is not the normal agent patch route and still rewrites only the first match per file.
42
- 9. Verify keyed results with `show`, `map`, `run`, or bounded `file_read` slices, then run repository validation.
29
+ ## Batch and parallelize safely
30
+
31
+ - Batch paths, symbols, selectors, and keyed files into one call whenever the tool schema supports them. Prefer one bounded multi-target call over repeated single-target calls.
32
+ - Issue independent read-only calls in the same model turn or host executor, and return all parallel results together when the host protocol requires it.
33
+ - Keep each AST intelligence request within one project root. Split cross-root work into root-specific calls; independent read-only calls may run in parallel.
34
+ - Keep dependent and overlapping work sequential: inspect, preview, hash, then mutate. Never parallelize writes that can touch the same path, configuration generation, or dependency chain.
35
+ - Call `config_status` before the first mutation when formatter selection, path policy, configuration health, or generation is uncertain. Use `policy_check` to preflight read, write, and delete decisions without side effects.
36
+ - Use `document_query` for bounded JSON, JSONC, TOML, and YAML inspection instead of attempting whole-file reads of structured manifests.
37
+
38
+ ## Mutate through declared file batches
39
+
40
+ 1. Inspect with `map`, `show`, `context`, a bounded `run`, or `file_read`. Call `file_capabilities` before choosing a read or patch method when intrinsic support or effective configuration is uncertain.
41
+ 2. Select `file_read.mode` explicitly when intent matters. Use `ast` with `symbols` for source structure or with RFC 6901 `selectors` for structured documents; use `text` for a bounded exact slice. `auto` is suitable when AST-first behavior is desired.
42
+ 3. Select `file_patch.patchStrategy` per file. Prefer `ast` for semantic, repeated, or structurally anchored changes; prefer `aider_block` for a small exact text replacement with unique context. Both remain selectable for parseable source whenever `file_capabilities` reports them, and configuration may narrow the effective choices.
43
+ 4. Preview every AST rule with `run({ pattern, paths: [filePath], lang?, json: true })`; inspect all matches and reject capped output before mutation. For a contract-level dry run of either strategy, send the same `file_patch` file entry with `preview: true`.
44
+ 5. Call one batched `file_hash({ filePaths: [...] })` immediately before guarded edits. Keep one returned hash per file. The runtime can make hashes optional through `safety.require_hash = false`, but the normal agent workflow should still supply them whenever current-state protection matters.
45
+ 6. Mutation tools accept a declared `files` property whose value is a path-keyed object. Use one `file_patch({ files: { ... } })` call for one or more files with exactly one explicit strategy and its matching ordered operations. Each path runs under one lock; preview never commits and normal mode commits atomically.
46
+ 7. Use one `file_write({ files: { ... } })` batch for new files or permitted SHA-guarded whole-file replacement. Supply the shared `chattr` object when chmod/chown metadata is required. The complete batch policy preflight finishes first; in-place formatter staging may transiently create, revalidate, and remove missing parents before the guarded commit recreates them, without writing the live target.
47
+ 8. Use one `file_rename({ files: { ... } })` batch for hash-guarded moves; validate every source and destination, reject existing destinations, and use no-replace moves. Ordinary failures roll back completed entries when possible; the operation is not crash-atomic.
48
+ 9. Use `file_chattr({ files: { ... } })` for metadata-only changes. Use hash-guarded `file_delete({ files: { ... } })` for deletion; it preflights all targets and AST import references before any deletion, requires an explicit `forceReferences` override for referenced source, and removes empty ancestor directories after lock release.
49
+ 10. Use direct `run` with `rewrite` and `write: true` only for an intentionally bounded lower-level rewrite; it is not the normal agent patch route and still rewrites only the first match per file.
50
+ 11. Verify results with `show`, `map`, `run`, or bounded `file_read` slices, then run repository validation.
51
+
52
+ Version 2 grants no implicit OS-temporary access. Express every exception through the narrowest top-level `[[paths]]` rule; `request` access must be approved through the host and model arguments can never bypass policy. Legacy v1 booleans remain readable only for compatibility and should be migrated with `ast-mcp config migrate`.
43
53
 
44
54
  Example batched AST patch:
45
55
 
46
56
  ```json
47
57
  file_patch({
48
- "/repo/src/service.ts": {
49
- "expectedSha256": "<from file_hash>",
50
- "patchStrategy": "ast",
51
- "astRules": [
52
- { "pattern": "oldName($$$ARGS)", "fix": "newName($$$ARGS)", "expectedMatches": 1 },
53
- { "pattern": "oldFlag", "fix": "newFlag", "expectedMatches": 1 }
54
- ]
58
+ "files": {
59
+ "/repo/src/service.ts": {
60
+ "expectedSha256": "<from file_hash>",
61
+ "patchStrategy": "ast",
62
+ "astRules": [
63
+ { "pattern": "oldName($$$ARGS)", "fix": "newName($$$ARGS)", "expectedMatches": 1 },
64
+ { "pattern": "oldFlag", "fix": "newFlag", "expectedMatches": 1 }
65
+ ]
66
+ }
55
67
  }
56
68
  })
57
69
  ```
@@ -60,10 +72,12 @@ Example batched Aider patch:
60
72
 
61
73
  ```json
62
74
  file_patch({
63
- "/repo/notes.md": {
64
- "expectedSha256": "<from file_hash>",
65
- "patchStrategy": "aider_block",
66
- "aiderBlocks": [{ "search": "old paragraph", "replace": "new paragraph" }]
75
+ "files": {
76
+ "/repo/notes.md": {
77
+ "expectedSha256": "<from file_hash>",
78
+ "patchStrategy": "aider_block",
79
+ "aiderBlocks": [{ "search": "old paragraph", "replace": "new paragraph" }]
80
+ }
67
81
  }
68
82
  })
69
83
  ```
@@ -72,8 +86,10 @@ Example batched file write:
72
86
 
73
87
  ```json
74
88
  file_write({
75
- "/repo/new-a.txt": { "content": "alpha\\n" },
76
- "/repo/existing.txt": { "content": "beta\\n", "expectedSha256": "<from file_hash>" }
89
+ "files": {
90
+ "/repo/new-a.txt": { "content": "alpha\\n" },
91
+ "/repo/existing.txt": { "content": "beta\\n", "expectedSha256": "<from file_hash>" }
92
+ }
77
93
  })
78
94
  ```
79
95
 
@@ -83,15 +99,15 @@ Read [patch-state-machine.md](references/patch-state-machine.md) for routing and
83
99
 
84
100
  ## Recover safely
85
101
 
86
- - Stale SHA: refresh `file_hash`, re-inspect through AST or a bounded unsupported-content slice, and rebuild the patch.
87
- - Zero or excess matches: narrow each AST rule; every astRules item must match exactly one node because ast-bro rewrites the first match per file, while ordered arrays let one keyed file_patch apply multiple reviewed operations.
102
+ - Stale SHA: refresh `file_hash`, re-inspect with the selected AST or text mode, and rebuild the patch.
103
+ - Zero or excess matches: narrow each AST rule; every astRules item must match exactly one node because ast-bro rewrites the first match per file, while ordered arrays let one declared `file_patch.files` entry apply multiple reviewed operations.
88
104
  - Capped direct preview: narrow paths, glob, or pattern before writing.
89
- - Aider ambiguity: request a larger bounded slice and expand the search block with unique surrounding context.
90
- - Formatter preflight failure: inspect the active `[formatting]` policy. Do not write until the matching external formatter or dprint fallback succeeds; `enabled = false` deliberately skips formatting.
105
+ - Unavailable method: call `file_capabilities` and select a reported read or patch method. Aider ambiguity or a disabled matcher is a safe stop; request a larger `mode: "text"` slice and expand the search block with unique surrounding context.
106
+ - Formatter preflight failure: call `config_status`, inspect the selected formatter and fallback, and do not write until stdout or staged in-place formatting succeeds. A v2 `preserve` fallback deliberately keeps unmatched content unchanged.
91
107
  - MCP loss mid-task: stop writing, restore the server, then re-inspect touched and pending files through their correct AST or non-AST routes.
92
108
 
93
109
  ## Completion check
94
110
 
95
111
  Confirm the old structure is absent through AST search, callers are correct, touched files were verified through their proper route, configured formatter-backed writes succeeded (or formatting is explicitly disabled), repository validation passes, and no direct-write or whole-file-read bypass was used.
96
112
 
97
- Use `evals:check` for fixture-matrix integrity. `evals:measure` inventories direct MCP transcript records and statically visible `tools.mcp__ast_mcp__*` calls inside top-level Codex `exec` source. Put exactly one `ast-mcp-eval:<id>` marker in the user evaluation prompt, or in a direct record input supplied by an evaluation harness, to associate the following direct MCP records with that case. An outer `exec` result cannot prove each nested call, so marked nested calls and multi-marker evidence fail closed. Scoring validates schema-relevant inputs, transcript workspace roots, required order, expected output evidence, assertions, and successful per-call outputs. Use `evals:score --strict` only for a complete marked matrix; transcript scoring is matched task-execution evidence, not a blanket agent-quality claim.
113
+ Use `evals:check` for fixture-matrix integrity. `evals:measure` inventories batch density, parallel read-only execution, validation-error codes, calls per recorded model-tool turn, direct MCP transcript records and statically visible `tools.mcp__ast_mcp__*` calls inside top-level Codex `exec` source. Put exactly one `ast-mcp-eval:<id>` marker in the user evaluation prompt, or in a direct record input supplied by an evaluation harness, to associate the following direct MCP records with that case. An outer `exec` result cannot prove each nested call, so marked nested calls and multi-marker evidence fail closed. Scoring validates schema-relevant inputs, transcript workspace roots, required order, expected output evidence, assertions, and successful per-call outputs. When the measured run used non-default file safety, pass the validated scorer options `--allow-any-path` and/or `--no-temp-directory`; the scorer does not infer layered project configuration from a transcript. Use `evals:score --strict` only for a complete marked matrix; transcript scoring is matched task-execution evidence, not a blanket agent-quality claim.
@@ -1,12 +1,12 @@
1
1
  [
2
2
  {
3
3
  "assertions": [
4
- "Uses one keyed batch instead of one call per file.",
4
+ "Uses one declared files batch instead of one call per file.",
5
5
  "Uses schema-valid content values keyed by file path.",
6
6
  "Reports each created file for verification."
7
7
  ],
8
8
  "category": "positive",
9
- "expected_output": "Uses one path-keyed file_write object whose values contain content and reports every created file.",
9
+ "expected_output": "Uses one file_write object with a declared files property whose path-keyed values contain content and reports every created file.",
10
10
  "files": ["notes/one.txt", "notes/two.txt", "notes/three.txt"],
11
11
  "forbidden_tools": ["file_patch"],
12
12
  "id": 74,
@@ -22,7 +22,7 @@
22
22
  "Does not route either operation through file_patch."
23
23
  ],
24
24
  "category": "variant",
25
- "expected_output": "Uses one keyed file_write batch and includes expectedSha256 only for the existing file.",
25
+ "expected_output": "Uses one declared file_write.files batch and includes expectedSha256 only for the existing file.",
26
26
  "files": [],
27
27
  "forbidden_tools": ["file_patch"],
28
28
  "id": 75,
@@ -54,7 +54,7 @@
54
54
  "Uses run only to preview or verify and sends the mutation through file_patch."
55
55
  ],
56
56
  "category": "positive",
57
- "expected_output": "Uses one path-keyed file_patch object with ordered astRules arrays and one expectedSha256 per file; run is used only for preview and verification.",
57
+ "expected_output": "Uses one file_patch object with a declared files property, ordered astRules arrays, and one expectedSha256 per file; run is used only for preview and verification.",
58
58
  "files": [],
59
59
  "forbidden_tools": ["file_write"],
60
60
  "id": 77,
@@ -70,7 +70,7 @@
70
70
  "Preserves Aider ambiguity and atomic-commit safeguards."
71
71
  ],
72
72
  "category": "variant",
73
- "expected_output": "Uses one path-keyed file_patch entry with patchStrategy aider_block and an ordered aiderBlocks array.",
73
+ "expected_output": "Uses one declared file_patch.files entry with patchStrategy aider_block and an ordered aiderBlocks array.",
74
74
  "files": [],
75
75
  "forbidden_tools": ["file_write"],
76
76
  "id": 78,
@@ -99,10 +99,10 @@
99
99
  "assertions": [
100
100
  "Does not use run with write:true for a normal agent mutation.",
101
101
  "Uses file_patch with patchStrategy ast for the reviewed edit.",
102
- "Previews exact AST matches before the keyed file_patch mutation."
102
+ "Previews exact AST matches before the declared file_patch.files mutation."
103
103
  ],
104
104
  "category": "negative",
105
- "expected_output": "Uses run only for preview or verification and routes the mutation through keyed file_patch with astRules.",
105
+ "expected_output": "Uses run only for preview or verification and routes the mutation through declared file_patch.files entries with astRules.",
106
106
  "files": [],
107
107
  "forbidden_tools": ["file_write"],
108
108
  "id": 81,
@@ -166,7 +166,7 @@
166
166
  "Does not treat a preview result as a committed change."
167
167
  ],
168
168
  "category": "variant",
169
- "expected_output": "Uses the same keyed file_patch entry with preview true, a fresh hash, and the appropriate ordered astRules or aiderBlocks; it verifies the bounded diff and then sends the guarded mutation.",
169
+ "expected_output": "Uses the same declared file_patch.files entry with preview true, a fresh hash, and the appropriate ordered astRules or aiderBlocks; it verifies the bounded diff and then sends the guarded mutation.",
170
170
  "files": [],
171
171
  "forbidden_tools": ["run"],
172
172
  "id": 83,
@@ -273,7 +273,7 @@
273
273
  },
274
274
  {
275
275
  "assertions": [
276
- "Uses one path-keyed file_rename batch.",
276
+ "Uses one declared file_rename.files batch.",
277
277
  "Obtains a fresh source hash before renaming.",
278
278
  "Reports each source and destination result."
279
279
  ],
@@ -34,19 +34,19 @@
34
34
  },
35
35
  {
36
36
  "assertions": [
37
- "Does not call file_read for AST-capable source.",
38
- "Uses map for shape and show for the named implementation.",
39
- "Avoids whole-file content reads."
37
+ "Uses file_read with mode ast for AST-capable source.",
38
+ "Requests the named symbol instead of retrieving whole-file text.",
39
+ "Reports resolved mode, capabilities, and whole-file hash."
40
40
  ],
41
- "category": "negative",
42
- "expected_output": "Uses AST intelligence for the TypeScript file and never calls file_read.",
41
+ "category": "variant",
42
+ "expected_output": "Uses file_read AST mode with the createServer symbol.",
43
43
  "files": [],
44
- "forbidden_tools": ["file_read"],
44
+ "forbidden_tools": [],
45
45
  "id": 3,
46
- "prompt": "Inspect the declarations and implementation of createServer in src/server.ts.",
47
- "required_tools": ["map", "show"],
46
+ "prompt": "Inspect the declarations and implementation of createServer in src/server.ts through file_read AST mode.",
47
+ "required_tools": ["file_read"],
48
48
  "surface": "file_read",
49
- "variant": "ast-capable-near-miss"
49
+ "variant": "ast-mode"
50
50
  },
51
51
  {
52
52
  "assertions": [
@@ -1175,9 +1175,221 @@
1175
1175
  "required_tools": [],
1176
1176
  "surface": "skill",
1177
1177
  "variant": "trigger-negative"
1178
+ },
1179
+ {
1180
+ "assertions": [
1181
+ "Uses one file_capabilities call for the target.",
1182
+ "Reports intrinsic and configuration-filtered read, patch, and search methods.",
1183
+ "Performs no mutation."
1184
+ ],
1185
+ "category": "positive",
1186
+ "expected_output": "Batches capability inspection and reports intrinsic and effective methods.",
1187
+ "files": [],
1188
+ "forbidden_tools": [],
1189
+ "id": 180,
1190
+ "prompt": "Report whether package.json supports AST or text reads and AST or Aider patches before editing it.",
1191
+ "required_tools": ["file_capabilities"],
1192
+ "surface": "file_capabilities",
1193
+ "variant": "primary"
1194
+ },
1195
+ {
1196
+ "assertions": [
1197
+ "Batches all three paths in one call.",
1198
+ "Distinguishes intrinsic support from effective configuration.",
1199
+ "Uses the result to recommend a valid agent-selected strategy."
1200
+ ],
1201
+ "category": "variant",
1202
+ "expected_output": "Uses one batched capability call and explains method differences.",
1203
+ "files": [],
1204
+ "forbidden_tools": [],
1205
+ "id": 181,
1206
+ "prompt": "Compare supported read and patch methods for a TypeScript file, Markdown file, and TOML file.",
1207
+ "required_tools": ["file_capabilities"],
1208
+ "surface": "file_capabilities",
1209
+ "variant": "batch"
1210
+ },
1211
+ {
1212
+ "assertions": [
1213
+ "Uses file_hash rather than file_capabilities.",
1214
+ "Does not retrieve content.",
1215
+ "Performs no mutation."
1216
+ ],
1217
+ "category": "negative",
1218
+ "expected_output": "Uses file_hash directly.",
1219
+ "files": [],
1220
+ "forbidden_tools": ["file_capabilities"],
1221
+ "id": 182,
1222
+ "prompt": "Return the SHA-256 for README.md without inspecting its contents.",
1223
+ "required_tools": ["file_hash"],
1224
+ "surface": "file_capabilities",
1225
+ "variant": "near-miss"
1226
+ },
1227
+ {
1228
+ "assertions": [
1229
+ "Uses config_status before mutation when policy or formatting is uncertain.",
1230
+ "Reports the effective generation, health, and configuration provenance.",
1231
+ "Does not mutate files or manually reread configuration sources."
1232
+ ],
1233
+ "category": "positive",
1234
+ "expected_output": "Inspects the effective configuration generation and provenance.",
1235
+ "files": [],
1236
+ "forbidden_tools": [],
1237
+ "id": 171,
1238
+ "prompt": "Check the effective AST MCP configuration before editing.",
1239
+ "required_tools": ["config_status"],
1240
+ "surface": "config_status",
1241
+ "variant": "primary"
1242
+ },
1243
+ {
1244
+ "assertions": [
1245
+ "Uses one read-only status call and reports formatter selection order.",
1246
+ "Reports the global formatting enabled value and explicit fallback.",
1247
+ "Preserves first-match ordering and per-formatter enabled overrides."
1248
+ ],
1249
+ "category": "variant",
1250
+ "expected_output": "Reports formatting fallback and formatter selection.",
1251
+ "files": [],
1252
+ "forbidden_tools": [],
1253
+ "id": 172,
1254
+ "prompt": "Which formatter would AST MCP use for this project?",
1255
+ "required_tools": ["config_status"],
1256
+ "surface": "config_status",
1257
+ "variant": "formatting"
1258
+ },
1259
+ {
1260
+ "assertions": [
1261
+ "Does not inspect repository configuration for an unrelated prose request.",
1262
+ "Makes no MCP or filesystem tool call.",
1263
+ "Answers only from the supplied prose."
1264
+ ],
1265
+ "category": "negative",
1266
+ "expected_output": "Answers without tool use.",
1267
+ "files": [],
1268
+ "forbidden_tools": ["config_status"],
1269
+ "id": 173,
1270
+ "prompt": "Rewrite this sentence more concisely.",
1271
+ "required_tools": [],
1272
+ "surface": "config_status",
1273
+ "variant": "unrelated"
1274
+ },
1275
+ {
1276
+ "assertions": [
1277
+ "Batches multiple path decisions in one policy_check call.",
1278
+ "Includes canonical path, operation, tool, and matched rule evidence.",
1279
+ "Performs no mutation while explaining each decision."
1280
+ ],
1281
+ "category": "positive",
1282
+ "expected_output": "Explains read, write, and delete decisions without mutation.",
1283
+ "files": [],
1284
+ "forbidden_tools": [],
1285
+ "id": 174,
1286
+ "prompt": "Preflight read, write, and delete policy for three paths.",
1287
+ "required_tools": ["policy_check"],
1288
+ "surface": "policy_check",
1289
+ "variant": "primary"
1290
+ },
1291
+ {
1292
+ "assertions": [
1293
+ "Checks all independent paths in one batch.",
1294
+ "Reports matched rule source and specificity for every destination.",
1295
+ "Distinguishes allow, request, and deny without granting approval."
1296
+ ],
1297
+ "category": "variant",
1298
+ "expected_output": "Returns matched rules and provenance for each path.",
1299
+ "files": [],
1300
+ "forbidden_tools": [],
1301
+ "id": 175,
1302
+ "prompt": "Explain which safety rules match two external destinations.",
1303
+ "required_tools": ["policy_check"],
1304
+ "surface": "policy_check",
1305
+ "variant": "external"
1306
+ },
1307
+ {
1308
+ "assertions": [
1309
+ "Uses file_hash rather than policy_check when only a digest is requested.",
1310
+ "Uses one bounded hash call for the requested path.",
1311
+ "Does not retrieve file contents or invoke policy_check."
1312
+ ],
1313
+ "category": "negative",
1314
+ "expected_output": "Hashes the file directly.",
1315
+ "files": [],
1316
+ "forbidden_tools": ["policy_check"],
1317
+ "id": 176,
1318
+ "prompt": "Return the SHA-256 for README.md.",
1319
+ "required_tools": ["file_hash"],
1320
+ "surface": "policy_check",
1321
+ "variant": "hash-near-miss"
1322
+ },
1323
+ {
1324
+ "assertions": [
1325
+ "Uses RFC 6901 selectors and returns a whole-file hash.",
1326
+ "Batches both selectors in one document_query call.",
1327
+ "Returns bounded values and source locations without whole-file content."
1328
+ ],
1329
+ "category": "positive",
1330
+ "expected_output": "Queries bounded values from a TOML manifest.",
1331
+ "files": [],
1332
+ "forbidden_tools": [],
1333
+ "id": 177,
1334
+ "prompt": "Read /version and /formatting/fallback from ast-mcp.toml.",
1335
+ "required_tools": ["document_query"],
1336
+ "surface": "document_query",
1337
+ "variant": "primary"
1338
+ },
1339
+ {
1340
+ "assertions": [
1341
+ "Batches multiple selectors in one document_query call.",
1342
+ "Uses RFC 6901 escaping and selector semantics.",
1343
+ "Reports selected values, source locations, and the whole-file hash."
1344
+ ],
1345
+ "category": "variant",
1346
+ "expected_output": "Returns selected JSONC values and locations.",
1347
+ "files": [],
1348
+ "forbidden_tools": [],
1349
+ "id": 178,
1350
+ "prompt": "Inspect three keys from a JSONC manifest without reading the entire file.",
1351
+ "required_tools": ["document_query"],
1352
+ "surface": "document_query",
1353
+ "variant": "jsonc-batch"
1354
+ },
1355
+ {
1356
+ "assertions": [
1357
+ "Uses AST intelligence rather than document_query for TypeScript source.",
1358
+ "Uses show for the requested createServer implementation.",
1359
+ "Does not read the whole source file or invoke document_query."
1360
+ ],
1361
+ "category": "negative",
1362
+ "expected_output": "Routes source inspection to show.",
1363
+ "files": [],
1364
+ "forbidden_tools": ["document_query"],
1365
+ "id": 179,
1366
+ "prompt": "Show the createServer implementation in src/server.ts.",
1367
+ "required_tools": ["show"],
1368
+ "surface": "document_query",
1369
+ "variant": "ast-near-miss"
1370
+ },
1371
+ {
1372
+ "assertions": [
1373
+ "Uses file_hash when only a whole-file digest is requested.",
1374
+ "Does not retrieve source, document values, or bounded text.",
1375
+ "Performs no mutation."
1376
+ ],
1377
+ "category": "negative",
1378
+ "expected_output": "Routes hash-only inspection directly to file_hash.",
1379
+ "files": [],
1380
+ "forbidden_tools": ["file_read"],
1381
+ "id": 183,
1382
+ "prompt": "Return the SHA-256 for src/server.ts without reading its contents.",
1383
+ "required_tools": ["file_hash"],
1384
+ "surface": "file_read",
1385
+ "variant": "hash-only-near-miss"
1178
1386
  }
1179
1387
  ],
1180
1388
  "mcp_tools": [
1389
+ "config_status",
1390
+ "document_query",
1391
+ "file_capabilities",
1392
+ "policy_check",
1181
1393
  "file_chattr",
1182
1394
  "file_delete",
1183
1395
  "file_rename",
@@ -1,18 +1,41 @@
1
1
  import { scoreTranscript } from "./score";
2
2
 
3
3
  const args = process.argv.slice(2);
4
- const strict = args[0] === "--strict";
5
- const sessionPaths = strict ? args.slice(1) : args;
4
+ const strict = args.includes("--strict");
5
+ const sessionPaths = args.filter((argument) => !argument.startsWith("--"));
6
+ const knownOptions = new Set([
7
+ "--allow-any-path",
8
+ "--no-temp-directory",
9
+ "--strict",
10
+ ]);
11
+ const requestedOptions = new Set(
12
+ args.filter((argument) => argument.startsWith("--")),
13
+ );
14
+ const unknownOption = [...requestedOptions].find(
15
+ (option) => !knownOptions.has(option),
16
+ );
17
+ if (unknownOption) {
18
+ console.error(`Unknown option: ${unknownOption}`);
19
+ process.exit(2);
20
+ }
21
+ const fileOperationPolicy = {
22
+ allowAnyPath: requestedOptions.has("--allow-any-path"),
23
+ allowTempDirectory: !requestedOptions.has("--no-temp-directory"),
24
+ };
6
25
 
7
26
  if (sessionPaths.length === 0) {
8
27
  console.error(
9
- "Usage: bun run templates/skills/ast-mcp/evals/measure.ts <session.jsonl> [...session.jsonl]",
28
+ "Usage: bun run templates/skills/ast-mcp/evals/measure.ts [--strict] [--allow-any-path] [--no-temp-directory] <session.jsonl> [...session.jsonl]",
10
29
  );
11
30
  process.exit(2);
12
31
  }
13
32
 
14
33
  for (const sessionPath of sessionPaths) {
15
- const result = await scoreTranscript(sessionPath, strict);
34
+ const result = await scoreTranscript(
35
+ sessionPath,
36
+ strict,
37
+ fileOperationPolicy,
38
+ );
16
39
  console.log(JSON.stringify(result));
17
40
  if (!result.passed) process.exitCode = 1;
18
41
  }
@@ -1,9 +1,52 @@
1
1
  import { afterEach, expect, test } from "bun:test";
2
2
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
3
+ import os, { tmpdir } from "node:os";
4
+ import path, { join } from "node:path";
5
5
  import { scoreTranscript } from "./score";
6
6
 
7
+ test("threads file-operation policy through transcript scoring", async () => {
8
+ const temporaryPath = path.join(os.tmpdir(), "ast-mcp-score-policy.ts");
9
+ const { sessionPath } = await transcript([
10
+ record("turn_context", {
11
+ cwd: "/workspace",
12
+ workspace_roots: ["/workspace"],
13
+ }),
14
+ record("response_item", {
15
+ call_id: "policy-hash",
16
+ input: `// ast-mcp-eval:71\n${JSON.stringify({ filePaths: [temporaryPath] })}`,
17
+ name: "mcp__ast_mcp__file_hash",
18
+ type: "custom_tool_call",
19
+ }),
20
+ record("response_item", {
21
+ call_id: "policy-hash",
22
+ output: [
23
+ {
24
+ text: JSON.stringify({
25
+ filePath: temporaryPath,
26
+ sha256: "abc",
27
+ size: 1,
28
+ }),
29
+ },
30
+ ],
31
+ type: "custom_tool_call_output",
32
+ }),
33
+ ]);
34
+
35
+ const protectedScore = await scoreTranscript(sessionPath, false, {
36
+ allowTempDirectory: false,
37
+ });
38
+ expect(protectedScore.errors).toContain(
39
+ `eval 71 file_hash input escapes transcript file-operation roots: ${temporaryPath}`,
40
+ );
41
+ const unrestrictedScore = await scoreTranscript(sessionPath, false, {
42
+ allowAnyPath: true,
43
+ allowTempDirectory: false,
44
+ });
45
+ expect(unrestrictedScore.errors).not.toContain(
46
+ `eval 71 file_hash input escapes transcript file-operation roots: ${temporaryPath}`,
47
+ );
48
+ });
49
+
7
50
  const directories: string[] = [];
8
51
 
9
52
  afterEach(async () => {
@@ -78,7 +121,7 @@ test("binds direct calls to their marker and counts tool output", async () => {
78
121
  });
79
122
 
80
123
  test("rejects nested exec evidence and duplicate identifiers", async () => {
81
- const source = `// ast-mcp-eval:91\ntext(await tools.mcp__ast_mcp__file_rename({"a.ts":{"expectedSha256":"abc","destination":"b.ts"}}));`;
124
+ const source = `// ast-mcp-eval:91\ntext(await tools.mcp__ast_mcp__file_rename({files:{"a.ts":{"expectedSha256":"abc","destination":"b.ts"}}}));`;
82
125
  const { sessionPath } = await transcript([
83
126
  record("response_item", {
84
127
  call_id: "nested",