@rickycourtes/mdtest 0.0.0-stage → 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/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - Markdown test files: headings with sub-headings are suites, leaf headings
8
+ are tests, with `skip:`, `only:` and `todo:` prefixes.
9
+ - Each test is checked by Claude through the Claude Agent SDK, read-only,
10
+ with a structured verdict (pass, reason, evidence).
11
+ - `--fix` lets Claude change code until tests pass.
12
+ - A `tests/` folder by convention, plus `*.test.md` / `*.spec.md` anywhere.
13
+ - `tests/setup.md` (or any `setupFiles`) as context for every test.
14
+ - Config in `mdtest.config.{js,mjs,json}`, `package.json` `"mdtest"`, or
15
+ `--config`, with a JSON schema, and per-file frontmatter overrides.
16
+ - `mdtest init` scaffolds the folder, config and npm script.
17
+ - Jest-style terminal output and JSON results.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ricky Courtes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,296 @@
1
- # Temporary Holding Version
1
+ # mdtest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tests written in Markdown and checked by Claude. You describe behaviour in
4
+ plain language, and Claude reads the code, runs commands and decides whether
5
+ each test passes. The output looks like Jest's. You write no test code and no
6
+ fixtures, and it works on any project in any language.
7
+
8
+ ```md
9
+ # Cart
10
+
11
+ The `Cart` class lives in `src/cart.js`.
12
+
13
+ ## totals
14
+
15
+ ### sums price times quantity
16
+
17
+ A cart with 2 × apple at 50 and 1 × pear at 120 totals 220.
18
+
19
+ ### applies a discount code
20
+
21
+ `total('SAVE10')` takes 10% off the total, rounded down to whole cents.
22
+ ```
23
+
24
+ Running `npx mdtest` gives output like this:
25
+
26
+ ```
27
+ FAIL tests/cart.md (9.8 s)
28
+ Cart
29
+ totals
30
+ ✓ sums price times quantity (4.1 s)
31
+ ✕ applies a discount code (5.7 s)
32
+
33
+ ● Cart › totals › applies a discount code
34
+
35
+ total() takes no arguments and applies no discount.
36
+
37
+ src/cart.js:19 total() { return this.items.reduce(...) }
38
+
39
+ at tests/cart.md:12
40
+
41
+ Test Suites: 1 failed, 1 total
42
+ Tests: 1 failed, 1 passed, 2 total
43
+ Time: 9.8 s
44
+ Cost: $0.0312
45
+ ```
46
+
47
+ Then `npx mdtest --fix` has Claude change the code until the failing tests
48
+ pass. The Markdown is the spec.
49
+
50
+ - [Quick start](#quick-start)
51
+ - [Project layout](#project-layout)
52
+ - [Writing tests](#writing-tests)
53
+ - [Configuration](#configuration)
54
+ - [CLI](#cli)
55
+ - [How a test is checked](#how-a-test-is-checked)
56
+ - [CI](#ci)
57
+ - [Cost and speed](#cost-and-speed)
58
+ - [Library](#library)
59
+
60
+ ## Quick start
61
+
62
+ ```bash
63
+ npm i -D @rickycourtes/mdtest
64
+ npx mdtest init # tests/ folder, mdtest.config.json, an npm script
65
+ npx mdtest --list # shows the tests it found (free, no Claude calls)
66
+ npx mdtest # checks them
67
+ ```
68
+
69
+ Requirements:
70
+
71
+ - Node 20.3 or later.
72
+ - A Claude credential: `ANTHROPIC_API_KEY` in the environment, or a one-time
73
+ sign-in with the [Claude Code](https://code.claude.com) CLI.
74
+
75
+ mdtest runs Claude through the
76
+ [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk), which installs
77
+ with it. Your project doesn't need to be JavaScript: `npx` works anywhere,
78
+ and Claude runs whatever commands your project uses.
79
+
80
+ ## Project layout
81
+
82
+ ```
83
+ your-project/
84
+ ├── mdtest.config.json # optional; created by `mdtest init`
85
+ ├── tests/
86
+ │ ├── setup.md # context for every test: never run as a test
87
+ │ ├── cart.md # a test file
88
+ │ ├── checkout/
89
+ │ │ └── payments.md # folders nest freely
90
+ │ └── README.md # ignored, so you can document your tests
91
+ └── src/
92
+ └── cart.test.md # *.test.md / *.spec.md also work next to the code
93
+ ```
94
+
95
+ - **`tests/`**: every `.md` file in it is a test file, except `README.md` and
96
+ setup files. Change the folder with `testDir`.
97
+ - **`tests/setup.md`**: Markdown that Claude reads before every test. Say what
98
+ the project is, where code lives and how to run it, for example "Run the
99
+ server with `npm start`; it listens on port 3000". This makes every test
100
+ shorter, cheaper and more reliable. Add more files with `setupFiles`.
101
+ - **`*.test.md` and `*.spec.md`** are picked up anywhere, if you'd rather keep
102
+ tests next to the code.
103
+
104
+ ## Writing tests
105
+
106
+ | Markdown | Jest equivalent |
107
+ | -------------------------------- | ------------------------------------------ |
108
+ | Heading with sub-headings | `describe` |
109
+ | Heading with no sub-headings | `it` / `test`: its text is the test |
110
+ | Text under a `describe` heading | Shared context for every test below it |
111
+ | Text before the first heading | Context for every test in the file |
112
+ | `## skip: name` | `it.skip` (on a suite: skips all inside) |
113
+ | `## only: name` | `it.only` (skips the rest of the file) |
114
+ | `## todo: name`, or no text | `it.todo` |
115
+ | `<!-- comment -->` | A note for people; never sent to Claude |
116
+ | A file with no headings | One test, named after the file |
117
+ | `tests/setup.md` | `setupFiles` |
118
+
119
+ Headings inside code fences are ignored, so you can put shell snippets and
120
+ sample output in a test.
121
+
122
+ What makes a good test:
123
+
124
+ - **One behaviour per heading.** Each leaf is checked on its own, so a failure
125
+ points at one thing.
126
+ - **Concrete expectations.** "`add('a', 50, 0)` throws" beats "validates
127
+ quantities".
128
+ - **Say where to look**, in `setup.md` or a suite's context. Claude finds
129
+ things faster and spends less.
130
+ - **Ask for a run** when that is the real check: "`npm run build` succeeds and
131
+ writes `dist/index.js`", or "`GET /health` on the dev server returns 200".
132
+
133
+ ## Configuration
134
+
135
+ `mdtest init` writes `mdtest.config.json`. mdtest looks for config in this
136
+ order:
137
+
138
+ 1. the file passed with `--config path`
139
+ 2. `mdtest.config.js` or `mdtest.config.mjs` (`export default { ... }`, or a
140
+ function that returns the config)
141
+ 3. `mdtest.config.json`
142
+ 4. an `"mdtest"` key in `package.json`
143
+
144
+ ```json
145
+ {
146
+ "$schema": "./node_modules/@rickycourtes/mdtest/schema.json",
147
+ "testDir": "tests",
148
+ "setupFiles": ["tests/setup.md"],
149
+ "model": "claude-opus-5-5",
150
+ "effort": "medium",
151
+ "concurrency": 4,
152
+ "timeout": 300000,
153
+ "maxBudgetUsd": 0.5
154
+ }
155
+ ```
156
+
157
+ The `$schema` line gives you autocomplete and checking in your editor.
158
+ Unknown keys are an error, so a typo doesn't silently do nothing.
159
+
160
+ | Option | Default | What it does |
161
+ | ------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |
162
+ | `rootDir` | the config file's folder | Project directory Claude works in |
163
+ | `testDir` | `"tests"` | Folder of Markdown tests |
164
+ | `testMatch` | `["<testDir>/**/*.md", "**/*.test.md", "**/*.spec.md"]` | Globs that find test files |
165
+ | `testPathIgnorePatterns` | `["/node_modules/", "/\\.git/", "/README\\.md$"]` | Regexes for paths to skip |
166
+ | `setupFiles` | `["<testDir>/setup.md"]` | Markdown context for every test. The default may be missing; a configured file must exist |
167
+ | `model` | Claude Code's default | Claude model ID |
168
+ | `effort` | model default | `low`, `medium`, `high`, `xhigh` or `max` |
169
+ | `concurrency` | `4` | Tests checked at once (fix mode: 1) |
170
+ | `timeout` | `300000` | Per-test timeout, in ms |
171
+ | `maxTurns` | `40` | Most agent turns per test |
172
+ | `maxBudgetUsd` | none | Per-test spending cap |
173
+ | `tools` | `["Read", "Grep", "Glob", "Bash"]` | Claude Code tools while checking (fix mode adds `Edit`, `Write`) |
174
+ | `retries` | `0` | Retries for a test that ended without a verdict |
175
+
176
+ A test file can override `model`, `effort`, `timeout`, `maxTurns`,
177
+ `maxBudgetUsd`, `tools` and `retries` in frontmatter:
178
+
179
+ ```md
180
+ ---
181
+ model: claude-haiku-5-5
182
+ timeout: 60000
183
+ tools: [Read, Grep]
184
+ ---
185
+ # Docs
186
+ ...
187
+ ```
188
+
189
+ ## CLI
190
+
191
+ ```
192
+ mdtest [pattern...] [options] Run the tests
193
+ mdtest init [--testDir dir] [--force] Add a tests folder, config file and npm script
194
+
195
+ -c, --config <path> Config file (default: mdtest.config.{js,mjs,json})
196
+ -t, --testNamePattern <re> Run only tests whose full name matches
197
+ --fix Let Claude change code until tests pass
198
+ --list List the tests without running them (free)
199
+ -b, --bail Stop after the first failing test
200
+ -j, --concurrency <n> Tests checked at once (default 4; fix mode: 1)
201
+ -m, --model <id> Claude model, e.g. claude-opus-5-5
202
+ -e, --effort <level> low | medium | high | xhigh | max
203
+ --timeout <ms> Per-test timeout (default 300000)
204
+ --maxBudgetUsd <usd> Per-test spending cap
205
+ --retries <n> Retry a test that ended without a verdict
206
+ --json Print results as JSON (Jest-like shape)
207
+ --outputFile <path> Write JSON results to a file
208
+ --rootDir <dir> Project directory (default: cwd)
209
+ --testDir <dir> Test folder (default: tests)
210
+ -v, --verbose Stream Claude's tool calls as it works
211
+ --version Print the version
212
+ ```
213
+
214
+ Patterns are regexes matched against test file paths, as in Jest, or paths to
215
+ test files: `npx mdtest checkout`, `npx mdtest tests/cart.md`. The exit code
216
+ is 1 when any test fails.
217
+
218
+ `mdtest init` never overwrites a file unless you pass `--force`. It adds a
219
+ `test` script to `package.json`, or `test:md` if `test` is already taken.
220
+
221
+ ## How a test is checked
222
+
223
+ Each test runs in a fresh Claude session in the project directory, with the
224
+ `Read`, `Grep`, `Glob` and `Bash` tools. Claude is told to investigate, never
225
+ change project files, and return a structured verdict: `pass`, a one-line
226
+ `reason`, and `evidence` as `file:line` references or commands with their
227
+ output. A test passes only when every expectation in it holds. An
228
+ expectation that can't be checked fails.
229
+
230
+ The project's `CLAUDE.md` and `.claude/settings.json` are loaded, so project
231
+ conventions and permission rules apply.
232
+
233
+ With `--fix`, Claude can also use `Edit` and `Write`. It makes the smallest
234
+ change that makes the test true and must not edit Markdown test files. Fix
235
+ mode runs one test at a time and lists the files it changed under each test.
236
+ Commit before running it, so you can review the diff.
237
+
238
+ Retries apply only when Claude ends without a verdict (a timeout, an API
239
+ error). A failing verdict is never re-rolled.
240
+
241
+ ## CI
242
+
243
+ ```yaml
244
+ # .github/workflows/mdtest.yml
245
+ name: mdtest
246
+ on: [pull_request]
247
+ jobs:
248
+ mdtest:
249
+ runs-on: ubuntu-latest
250
+ steps:
251
+ - uses: actions/checkout@v4
252
+ - uses: actions/setup-node@v4
253
+ with: { node-version: 22 }
254
+ - run: npm ci
255
+ - run: npx mdtest --outputFile mdtest-results.json
256
+ env:
257
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
258
+ ```
259
+
260
+ ## Cost and speed
261
+
262
+ Every test is a Claude session, so a run costs money and takes seconds per
263
+ test. The summary prints the total cost. To keep it down:
264
+
265
+ - Use `--list` (free) while writing tests.
266
+ - Run a slice with `-t` or a file pattern.
267
+ - Use a lower `effort` or a smaller `model` for simple checks.
268
+ - Set `maxBudgetUsd` as a per-test cap.
269
+ - Keep `setup.md` specific, so Claude doesn't have to search for things.
270
+
271
+ ## Library
272
+
273
+ ```js
274
+ import { run, collect, parse, defaultReporter } from '@rickycourtes/mdtest';
275
+
276
+ const summary = await run({ rootDir: '.', reporter: defaultReporter() });
277
+ process.exitCode = summary.success ? 0 : 1;
278
+ ```
279
+
280
+ `run` accepts a `verify(test, options)` function in place of Claude. That's
281
+ how this package tests itself without API calls (`npm test`).
282
+
283
+ ## Try the example
284
+
285
+ ```bash
286
+ git clone https://github.com/rickycourtes/mdtest && cd mdtest && npm i
287
+ npm run example # checks example/tests/cart.md
288
+ npm run example -- --fix # Claude implements the discount code
289
+ ```
290
+
291
+ `applies a discount code` fails on purpose. `--fix` makes it pass by
292
+ editing `example/src/cart.js`.
293
+
294
+ ## License
295
+
296
+ MIT
package/bin/mdtest.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (err) => {
9
+ console.error(err instanceof Error ? err.message : err);
10
+ process.exitCode = 2;
11
+ },
12
+ );
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@rickycourtes/mdtest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Tests written in Markdown, checked by Claude. A Jest-style runner with no test code: describe behaviour in plain language and Claude verifies it against your project.",
5
+ "type": "module",
6
+ "bin": {
7
+ "mdtest": "bin/mdtest.js"
8
+ },
9
+ "exports": {
10
+ ".": "./src/index.js",
11
+ "./schema.json": "./schema.json",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "src",
17
+ "schema.json",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test/*.test.js",
22
+ "example": "node bin/mdtest.js --rootDir example",
23
+ "prepublishOnly": "npm test"
24
+ },
25
+ "engines": {
26
+ "node": ">=20.3"
27
+ },
28
+ "dependencies": {
29
+ "@anthropic-ai/claude-agent-sdk": "^0.3.332"
30
+ },
31
+ "keywords": [
32
+ "test",
33
+ "testing",
34
+ "test-runner",
35
+ "markdown",
36
+ "claude",
37
+ "anthropic",
38
+ "ai",
39
+ "llm",
40
+ "jest",
41
+ "spec",
42
+ "bdd",
43
+ "tdd"
44
+ ],
45
+ "author": "Ricky Courtes",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/rickycourtes/mdtest.git"
49
+ },
50
+ "homepage": "https://github.com/rickycourtes/mdtest#readme",
51
+ "bugs": "https://github.com/rickycourtes/mdtest/issues",
52
+ "license": "MIT",
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }
package/schema.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "mdtest config",
4
+ "description": "Configuration for mdtest, Markdown tests checked by Claude. Save as mdtest.config.json.",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "properties": {
8
+ "$schema": { "type": "string" },
9
+ "rootDir": {
10
+ "type": "string",
11
+ "description": "Project directory, relative to this file. Default: the folder holding this file."
12
+ },
13
+ "testDir": {
14
+ "type": "string",
15
+ "default": "tests",
16
+ "description": "Folder that holds the Markdown tests. Every .md file in it is a test file, except README.md and setup files."
17
+ },
18
+ "testMatch": {
19
+ "type": "array",
20
+ "items": { "type": "string" },
21
+ "default": ["<testDir>/**/*.md", "**/*.test.md", "**/*.spec.md"],
22
+ "description": "Globs, relative to rootDir, that find test files. <testDir> is replaced with testDir."
23
+ },
24
+ "testPathIgnorePatterns": {
25
+ "type": "array",
26
+ "items": { "type": "string" },
27
+ "default": ["/node_modules/", "/\\.git/", "/README\\.md$"],
28
+ "description": "Regexes tested against \"/\" + each relative path. Matching files and folders are skipped."
29
+ },
30
+ "setupFiles": {
31
+ "type": "array",
32
+ "items": { "type": "string" },
33
+ "default": ["<testDir>/setup.md"],
34
+ "description": "Markdown files whose text is context for every test (where code lives, how to run it). Never run as tests."
35
+ },
36
+ "model": {
37
+ "type": "string",
38
+ "description": "Claude model ID, e.g. claude-opus-5-5. Default: Claude Code's default model."
39
+ },
40
+ "effort": {
41
+ "enum": ["low", "medium", "high", "xhigh", "max"],
42
+ "description": "How hard Claude thinks per test. Lower is faster and cheaper."
43
+ },
44
+ "concurrency": {
45
+ "type": "integer",
46
+ "minimum": 1,
47
+ "default": 4,
48
+ "description": "Tests checked at once. Fix mode always runs one at a time."
49
+ },
50
+ "timeout": {
51
+ "type": "integer",
52
+ "minimum": 1000,
53
+ "default": 300000,
54
+ "description": "Per-test timeout in milliseconds."
55
+ },
56
+ "maxTurns": {
57
+ "type": "integer",
58
+ "minimum": 1,
59
+ "default": 40,
60
+ "description": "Most agent turns Claude may take on one test."
61
+ },
62
+ "maxBudgetUsd": {
63
+ "type": "number",
64
+ "exclusiveMinimum": 0,
65
+ "description": "Per-test spending cap in US dollars."
66
+ },
67
+ "tools": {
68
+ "type": "array",
69
+ "items": { "type": "string" },
70
+ "default": ["Read", "Grep", "Glob", "Bash"],
71
+ "description": "Claude Code tools available while checking a test. Fix mode adds Edit and Write."
72
+ },
73
+ "retries": {
74
+ "type": "integer",
75
+ "minimum": 0,
76
+ "default": 0,
77
+ "description": "Retries for a test that ended without a verdict (timeout, API error). Failing verdicts are never retried."
78
+ }
79
+ }
80
+ }
package/src/claude.js ADDED
@@ -0,0 +1,161 @@
1
+ // The assertion engine: hands one Markdown test to Claude (through the Claude
2
+ // Agent SDK, so it can read files, search and run commands in the project)
3
+ // and gets back a structured verdict.
4
+
5
+ const VERDICT_SCHEMA = {
6
+ type: 'object',
7
+ additionalProperties: false,
8
+ required: ['pass', 'reason', 'evidence'],
9
+ properties: {
10
+ pass: { type: 'boolean', description: 'true only if every expectation in the test holds' },
11
+ reason: { type: 'string', description: 'One or two sentences: why it passed or failed' },
12
+ evidence: {
13
+ type: 'array',
14
+ items: { type: 'string' },
15
+ description: 'file:line references or commands run with their key output',
16
+ },
17
+ changes: {
18
+ type: 'array',
19
+ items: { type: 'string' },
20
+ description: 'Fix mode only: the files changed and what changed in each',
21
+ },
22
+ },
23
+ };
24
+
25
+ const VERIFY_SYSTEM = `You are the assertion engine of a test runner. Each test is written in Markdown, in plain language, instead of code. Your job is to decide whether one test passes against the project in your working directory.
26
+
27
+ - Check the real project. Read and search its files, and run its commands (scripts, builds, its own test suites, a quick node -e) when running something is the surest way to know.
28
+ - Do not create, change or delete any file in the project. If you need a scratch file, put it in the system temp directory.
29
+ - Judge exactly what the test states, no more and no less. It passes only when every expectation in it holds. If any expectation fails, or cannot be checked, it fails.
30
+ - Context sections apply to the test as background and setup; the test section holds the expectations.
31
+ - Be quick: stop investigating once the answer is certain.
32
+ - The reason is one or two plain sentences. Evidence is file:line references, or a command and the part of its output that decided it.`;
33
+
34
+ const FIX_SYSTEM = `You are a developer working test-first. Each test is written in Markdown, in plain language, instead of code. Your job is to make one test pass by changing the project in your working directory, then confirm that it passes.
35
+
36
+ - First check whether it already passes. If it does, change nothing.
37
+ - Make the smallest change in the project's own code that makes the test true, in the style the code already uses.
38
+ - Never edit, rename or delete Markdown test files (*.test.md, *.spec.md, __tests__/). The test is the specification.
39
+ - After changing code, verify the result: read it back, and run the project's commands when that is the surest check.
40
+ - pass is true only if the test holds after your changes. List each file you changed in changes.
41
+ - The reason is one or two plain sentences. Evidence is file:line references, or a command and the part of its output that decided it.`;
42
+
43
+ /**
44
+ * @typedef {{ pass: boolean, reason: string, evidence: string[], changes?: string[] }} Verdict
45
+ * @typedef {{
46
+ * verdict?: Verdict, error?: string, costUsd: number, turns: number, durationMs: number,
47
+ * }} VerifyResult
48
+ * @typedef {{
49
+ * cwd: string, model?: string, effort?: string, tools: string[], maxTurns: number,
50
+ * maxBudgetUsd?: number, fix?: boolean, signal?: AbortSignal,
51
+ * onEvent?: (e: { kind: 'tool' | 'text', text: string }) => void,
52
+ * }} VerifyOptions
53
+ * @typedef {(test: import('./parse.js').TestCase, options: VerifyOptions) => Promise<VerifyResult>} Verifier
54
+ */
55
+
56
+ /**
57
+ * Builds the user prompt for one test.
58
+ * @param {import('./parse.js').TestCase} test
59
+ * @param {boolean} [fix]
60
+ */
61
+ export function buildPrompt(test, fix = false) {
62
+ const parts = [`Test file: ${test.file}:${test.line}`, `Test: ${test.fullName}`];
63
+ if (test.context.length) {
64
+ parts.push(`<context>\n${test.context.join('\n\n')}\n</context>`);
65
+ }
66
+ parts.push(`<test>\n${test.body}\n</test>`);
67
+ parts.push(fix ? 'Make this test pass, then report the verdict.' : 'Does this test pass? Report the verdict.');
68
+ return parts.join('\n\n');
69
+ }
70
+
71
+ /** @type {Verifier} */
72
+ export async function verifyWithClaude(test, options) {
73
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
74
+ const started = Date.now();
75
+ const tools = options.fix ? [...new Set([...options.tools, 'Edit', 'Write'])] : options.tools;
76
+ const abortController = new AbortController();
77
+ const onAbort = () => abortController.abort();
78
+ options.signal?.addEventListener('abort', onAbort, { once: true });
79
+
80
+ /** @type {VerifyResult} */
81
+ const out = { costUsd: 0, turns: 0, durationMs: 0 };
82
+ try {
83
+ const stream = query({
84
+ prompt: buildPrompt(test, options.fix),
85
+ options: {
86
+ cwd: options.cwd,
87
+ model: options.model,
88
+ effort: /** @type {any} */ (options.effort),
89
+ systemPrompt: options.fix ? FIX_SYSTEM : VERIFY_SYSTEM,
90
+ tools,
91
+ allowedTools: tools,
92
+ disallowedTools: options.fix ? [] : ['Edit', 'Write', 'NotebookEdit'],
93
+ permissionMode: 'dontAsk',
94
+ settingSources: ['project'],
95
+ persistSession: false,
96
+ maxTurns: options.maxTurns,
97
+ maxBudgetUsd: options.maxBudgetUsd,
98
+ outputFormat: { type: 'json_schema', schema: VERDICT_SCHEMA },
99
+ abortController,
100
+ },
101
+ });
102
+ for await (const message of stream) {
103
+ if (message.type === 'assistant' && options.onEvent) {
104
+ for (const block of message.message.content) {
105
+ if (block.type === 'tool_use') options.onEvent({ kind: 'tool', text: describeTool(block) });
106
+ else if (block.type === 'text' && block.text.trim()) options.onEvent({ kind: 'text', text: block.text.trim() });
107
+ }
108
+ }
109
+ if (message.type === 'result') {
110
+ out.costUsd = message.total_cost_usd ?? 0;
111
+ out.turns = message.num_turns ?? 0;
112
+ if (message.subtype === 'success' && !message.is_error) {
113
+ out.verdict = toVerdict(message.structured_output ?? message.result);
114
+ if (!out.verdict) out.error = `Claude did not return a verdict: ${String(message.result).slice(0, 500)}`;
115
+ } else {
116
+ const errors = 'errors' in message && message.errors?.length ? `: ${message.errors.join('; ')}` : '';
117
+ out.error = `Claude stopped (${message.subtype})${errors}`;
118
+ }
119
+ }
120
+ }
121
+ if (!out.verdict && !out.error) out.error = 'Claude ended without a result';
122
+ } catch (err) {
123
+ out.error = options.signal?.aborted ? 'Aborted' : err instanceof Error ? err.message : String(err);
124
+ } finally {
125
+ if (out.error && /not logged in|authentication|api key/i.test(out.error)) {
126
+ out.error += '\nSet ANTHROPIC_API_KEY, or sign in once with the Claude Code CLI (`claude`, then /login).';
127
+ }
128
+ options.signal?.removeEventListener('abort', onAbort);
129
+ out.durationMs = Date.now() - started;
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /** @param {unknown} value @returns {Verdict | undefined} */
135
+ function toVerdict(value) {
136
+ let v = value;
137
+ if (typeof v === 'string') {
138
+ const json = /\{[\s\S]*\}/.exec(v);
139
+ if (!json) return undefined;
140
+ try {
141
+ v = JSON.parse(json[0]);
142
+ } catch {
143
+ return undefined;
144
+ }
145
+ }
146
+ if (!v || typeof v !== 'object' || typeof (/** @type {any} */ (v).pass) !== 'boolean') return undefined;
147
+ const o = /** @type {any} */ (v);
148
+ return {
149
+ pass: o.pass,
150
+ reason: String(o.reason ?? ''),
151
+ evidence: Array.isArray(o.evidence) ? o.evidence.map(String) : [],
152
+ ...(Array.isArray(o.changes) ? { changes: o.changes.map(String) } : {}),
153
+ };
154
+ }
155
+
156
+ /** @param {{ name: string, input: any }} block */
157
+ function describeTool(block) {
158
+ const i = block.input ?? {};
159
+ const arg = i.command ?? i.file_path ?? i.pattern ?? i.path ?? '';
160
+ return `${block.name}${arg ? ` ${String(arg).split('\n')[0].slice(0, 100)}` : ''}`;
161
+ }