SLOPSHOPPER

tdd-mod

Blocks file writes that break Red-Green-Refactor on coding tasks (port of probity's enforceTdd).

guardcommandstatuspromptmodeltimer
★ 4v0.5.2MITupdated 2026-10-22koslowskyj/tdd-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · tdd-mod
› fix the failing auth test and add an audit log call ● tdd-mod: tdd-mod: task coding: fix the failing auth test and add an audit log call ● tdd-mod: tdd-mod: violation (first opinion) /work/app/src/auth.ts — could not parse verdict from validator output: OK ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Edit(/work/app/src/auth.ts) ⎿ Denied by tdd-mod: tdd-mod: could not parse verdict from validator output: OK Next: write a failing test f ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /tdd-eval ● tdd-mod: tdd-mod: violation (second opinion) /work/app/src/auth.ts — could not parse verdict from validator output: OK ● tdd-mod: tdd-mod: blocked prompt /work/app/src/auth.ts part 1/3: ## Role You are a TDD validator. Judge whether the pending write follows test-driven development. ## Inputs You will see these inputs: 1. "Recent session" — a chronological log of the agent's recent prompts and tool actions. Each entry shows what the agent did and what it observed back. Use this to find evidence of a failing test that the pending write would address. 2. "Current file content" — what's on disk right now at the file the agent is about to write. May be a parenthesized marker (e.g. `(file does not exist)`) when content cannot be shown. 3. "Pending action" — what the agent is about to write. Content may be raw file text or a patch/diff in any common format. 4. "Last test run" — the latest test command the agent ran in this session, whether it was red or green, and its output, even when it is older than the recent session, or that no test has run yet. A failure shown there is observed: production code that addresses it is the green step. ## What you judge Judge the change this write makes (the difference between the current file content and the pending action), not the resulting file as a whole. A transient file state is never itself a violation, however broken the file looks: an unresolved symbol, a dead or unused definition, a duplicated declaration, a reference to a removed name, a half-finished multi-step change. Whether the file is internally consistent or runs after the write is checked when the agent next runs the tests, not by you. This allowance is about structure; it does not excuse skipping a failing test or over-implementing, which the rules below still catch. A block or denial message recorded earlier in the session is a past verdict, not a rule. Re-derive your judgment from the rules below as if it had not been issued; never block only because a previous attempt was blocked. Your judgment is not the final word. When the user tells you in the session to let this change through, treat it as authoritative and pass, even on a change you would otherwise block. ## Multi-step changes A phase may span multiple writes, each fine on its own. For example: - Add an import in one write, then change the calling code in the next. - Move a function in two writes (remove from one location, add at another). - Add a function signature in one write, then its body in the next. - Remove a function in one write, then its call sites in the next. ## TDD rules The TDD cycle is Red -> Green -> Refactor. Each phase has its own rules. ### Across all phases Deleting code, tests, or helpers never requires a failing test to drive it, even when the removed code was used or test-covered. ### Red phase: write a failing test first In red you add one test that drives new behavior and expect it to fail when the suite runs. A single write should add at most one new test. Compare current file content with pending action to count newly added tests; existing tests do not count. Restructuring existing tests is not "adding". - Adding a test is the red step itself; it is allowed and does not require observing it fail first, unless the prior green left a refactor unmade (see "Enforcing the refactor phase"). - A test added to drive new behavior must be observed failing for the right reason (an assertion, not a syntax or import error) in a prior test run before production code may be written to satisfy it. - A test added to capture existing behavior is allowed to pass immediately and must not be blocked for not failing first. Examples: characterization tests pinning current implementation, tests at a new layer (e.g. an e2e covering code already exercised by units), pinning tests added before a refactor pulls a seam out from under them. - Tes ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ tdd-mod: TDD on
README

tdd-mod

CI

Production-tested. tdd-mod enforces test-driven development on the main agent and on its subagents alike, and has been used to build several production services.

A Claude Code mod that keeps the agent to Red → Green → Refactor. Before each file write on a coding task, a judge model checks the write against the TDD rules and blocks it, with the reason, when it skips a failing test or implements more than the failing test needs. The agent reads the reason and corrects course.

The TDD rules and the judging approach are ported from probity's enforceTdd rule (MIT). Probity runs as an external PreToolUse command; tdd-mod runs in-process as a Claude Code function-hooks plugin (a "mod"), so it needs no extra install, API key or process per write.

What it does

  • Judges every write to a source file: Write, Edit and NotebookEdit. The judge sees the last 10 prompts and tool calls of the session, the file as it is, and the file as the write would leave it, and answers pass or violation. What it sees is capped, however long the session or large the file: each tool output at 6000 characters, each tool input at 1500, and each file at 20000, cut to the changed region with 2000 characters around it.
  • Judges the writes of one response together. When the agent sends several Write/Edit calls in one response (a method and its call, a signature and its caller in another file), the judge sees every file as they leave it together, once; each write of the batch gets that one verdict. Claude Code starts running a response's tools before the response has finished streaming, so the first write waits for the rest of it, up to 8 s, and is judged alone if it takes longer. The wait counts against the hook's 10 s budget; the judge's model calls do not.
  • The judge sees the last test run, however long ago: its command, whether it was red or green, and its output. So a fix for a failure the agent has already seen is judged as the green step it is.
  • Refactors pass while green. When the last test run was green, the judge is told that this may be the refactor step: extracting a helper from existing code, inlining, renaming, or removing unused code passes without a new failing test, unless the change adds behaviour.
  • Only on coding tasks. Each prompt you type is labelled coding (adds, changes or fixes behaviour) or other (moving or renaming code, extracting, formatting, docs, config, questions, git). On other nothing is blocked. The status line shows TDD on or TDD off (not coding), after the mod's version (tdd-mod: (<version>) · TDD on).
  • Subagents get their own label. A subagent (the Agent tool) is labelled from the brief it was spawned with, not from your last prompt: one briefed to implement or fix something is judged even when you asked a question or told the agent to delegate; one briefed to explore or review is not. While coding subagents run, the status line adds · judging 1 subagent (or 2 subagents). A subagent spawned before the mod reloaded (a /config change) has no label yet: at its first write it is labelled from its brief, read back from its own transcript, and counted on the status line from then on.
  • Blocks shell writes to source files (cat > file, >>, tee, sed -i, cp, inline Python/Node writes) and tells the agent to use Write or Edit, so every change can be judged. Moving files (mv, git mv) is allowed, and so are shell writes to test files, like Write and Edit. A path is read from the folder an earlier cd in the command moved to, so cd src/test/java/x && sed -i … Helper.java is a test write. A heredoc written to a file (cat > f <<EOF) is that file's content: paths named in it are not writes.
  • Leaves files outside the project alone. A write to an absolute path outside the project root, such as a scratch script in /tmp, is not judged.
  • Passes every write to a test file without asking the model (Write, Edit and NotebookEdit): writing a test is the red step itself. A test file is one in a test/, tests/ or __tests__/ folder (so src/test/ too), or named *.test.*, *.spec.*, *Test.java/.kt, *IT.java/.kt, test_*.py, *_test.py or *_test.go.
  • Passes a write that adds exactly one test to any other file (in-source tests, a Rust #[test] module) without asking the model.
  • Asks a second time before blocking, and blocks only when both answers agree. If the judge can't be reached, the write is blocked (fail-closed). Both are asked at once, so a block comes as soon as the slower answer does; the first pass lets the write through and cuts the other call short.
  • Says what to do next. A block gives the judge's reason, then one fixed next step chosen from the last test run: write and run a failing test, write only a stub after a compile or import error, or change only what the failing assertion needs.
  • Gives an identical retry the same verdict. A write to the same file, from the same content to the same content, gets the verdict it got before, without a model call, as long as there is no new evidence: no new test run and no new prompt from you. After new evidence it is judged again; a retry whose verdict flips is logged as verdict reversed on retry (violation → pass) in the debug log. A block because the judge gave no answer is not kept: the retry asks the judge again.
  • Respects an explicit override. Tell the agent "I'm overriding the TDD guard for this write; let it through." and the judge lets that write pass.

Requirements

  • Claude Code with function-hooks plugins (built and tested on 2.1.288).
  • Nothing else: the mod uses the session's own model access.

Quick start

Install it from this repository's marketplace, in Claude Code:

/plugin marketplace add koslowskyj/tdd-mod
/plugin install tdd-mod@tdd-mod

Or run it from a clone, for one session:

git clone https://github.com/koslowskyj/tdd-mod.git ~/tdd-mod
cd your-project
claude --plugin-dir ~/tdd-mod

Then give the agent a coding task. Each blocked write shows up as a tool error starting with tdd-mod:. Every decision on a write, passes included, also shows as a dim line in the transcript (the model does not see it), with how it was reached, how long the write waited for it (the wait for the rest of its response included), and the judge's tokens:

tdd-mod: pass src/cart.ts (first opinion, 2140 ms, 17210 in / 46 out tokens)
tdd-mod: pass src/cart.test.ts (test file, 0 ms)
tdd-mod: violation src/total.ts (second opinion, 4310 ms, 17480 in / 92 out tokens)

To see every verdict with its reason, start with --debug and follow the debug log:

claude --plugin-dir ~/tdd-mod --debug
tail -f "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/debug/latest" | grep --line-buffered "tdd-mod: "

Lines look like tdd-mod: pass (first opinion) src/cart.ts — Green phase: …, tdd-mod: violation (second opinion) …, tdd-mod: task other: … or tdd-mod: subagent <agentId> task coding: … (… labelled late (coding): … for one spawned before a reload). For every blocked write, the full judge prompt follows in numbered parts (blocked prompt … part 1/3), so the verdict can be replayed exactly.

It helps to tell the agent, in your project's CLAUDE.md, to work test-first and to change files with Write and Edit only.

Settings

Change them in /config, with /plugin configure tdd-mod@tdd-mod, or under pluginConfigs in settings.json. Installed from the marketplace the plugin is keyed tdd-mod@tdd-mod; loaded with --plugin-dir, tdd-mod (or tdd-mod@inline):

{
  "pluginConfigs": {
    "tdd-mod@tdd-mod": { "options": { "judgeModel": "sonnet" } }
  }
}
SettingDefaultWhat it does
enabledtrueOff, the mod does nothing.
judgeModelhaikuThe model that judges each write on a coding task. It writes no code; the session's own model does. Haiku is the default because it scored best in /tdd-eval.
classifierModelhaikuThe model that labels each typed prompt and each subagent's brief coding or other.
classifyTaskstrueOff, every task counts as coding and every write is judged.
fastPathtruePass a write that adds exactly one test without a model call. Faster, but a new test no longer checks for a refactor left unmade.
secondOpiniontrueBlock only when a second judge call agrees.
parallelOpinionstrueAsk both judge calls at once: a block comes about 5 s sooner, at about twice the judge's input tokens. Off, the second is asked only after a violation.
extensionsts, tsx, mts, cts, js, jsx, mjs, cjs, py, go, rs, java, kt, kts, scala, rb, php, cs, fs, swift, c, cc, cpp, h, hpp, ex, exs, erl, clj, dart, lua, ipynb, vue, svelteComma-separated extensions of the files judged.
ignore/node_modules/, /dist/, /build/, /vendor/, /.git/, /.claude/Comma-separated globs of paths never judged.
testPatterns(empty: built-in patterns)How the fast path recognises a test declaration, per extension. A JSON object from comma-separated extensions to a regex; see below.

A change in /config reloads the mod with the new values.

Judging SQL, YAML and JSON

.sql, .yaml, .yml and .json are not judged by default. Most writes to them are configuration (package.json, tsconfig.json, CI workflows, settings files), which the guard leaves alone on purpose: judging them would block config changes for want of a failing test. That is the kind of false positive that costs the most time. Golden files under a test folder count as tests and pass anyway.

Where such files carry behaviour, such as a Flyway migration or an openapi.yaml the code is generated from, add them to extensions. Then every write to them is judged like source, config files included, unless an ignore glob leaves those out:

{
  "pluginConfigs": {
    "tdd-mod@tdd-mod": {
      "options": {
        "extensions": "ts,tsx,js,java,kt,py,go,sql,yaml,yml,json",
        "ignore": "**/node_modules/**,**/.git/**,**/.claude/**,**/package.json,**/tsconfig.json,**/.github/**"
      }
    }
  }
}

Test patterns

The fast path counts test declarations with a regex per file extension. The built-in patterns cover it(/test( in JS/TS, def test_ in Python, func Test in Go, @Test in Java/Kotlin, #[test] in Rust, it "/def test_ in Ruby and [Fact]/[Test] in C#. testPatterns replaces or adds patterns per extension; an empty regex turns the fast path off for those extensions:

{
  "pluginConfigs": {
    "tdd-mod@tdd-mod": {
      "options": {
        "testPatterns": "{\"ts,js\": \"\\\\bscenario\\\\(\", \"ex,exs\": \"^\\\\s*test \\\"\", \"go\": \"\"}"
      }
    }
  }
}

That is the JSON object {"ts,js": "\\bscenario\\(", "ex,exs": "^\\s*test \"", "go": ""} written as a string. The regexes run with the g and m flags, so ^ matches at each line. An invalid value is reported in the transcript when the session starts, and the built-in patterns stay in place.

Measuring the judge: /tdd-eval

eval/ holds a small regression set built from kata runs and a guarded implementation run: 23 labelled writes (verdicts.json) and 15 labelled prompts (tasks.json). /tdd-eval [runs] replays them through exactly the decisions a session makes, with the configured models, and reports the hit rate per case:

claude -p "/tdd-eval 3" --plugin-dir ~/tdd-mod

Results with 0.3.0's prompt (the last test run, refactors under green), 3 runs per case:

Judge modelWrites that should passWrites that should be blockedTotal
haiku (default)57/5712/1269/69

On the earlier set of 20 cases and the earlier prompt:

Judge modelWrites that should passWrites that should be blockedTotal
haiku (default)51/519/960/60
opus51/512/953/60
sonnet51/510/951/60

The classifier (haiku) labelled all 45 prompts correctly. The set is small (four distinct violations), so treat these numbers as a direction, not a benchmark. Add a case whenever the judge gets a real write wrong. The cases replay single writes through the judge; test files, batches and the verdict cache are covered by claude plugin test ..

Development

claude plugin validate .claude-plugin/plugin.json        # manifest and hooks, as the engine reads them
claude plugin validate .claude-plugin/marketplace.json   # the marketplace entry
claude plugin test .       # unit and hook tests (test/*.test.ts)
npx -p typescript@5 tsc -p .

tsconfig.json extends .claude-plugin/types/tsconfig.json, which Claude Code writes when it loads the mod. Load it once (claude --plugin-dir .) before type-checking.

GitHub Actions (.github/workflows/ci.yml) runs these checks on every push to main and on pull requests, against the pinned Claude Code version. None of them needs credentials. /tdd-eval is not part of CI: it calls the models.

Releases

Every push to main that passes the checks is released. The release job bumps the version in .claude-plugin/plugin.json from the commit messages since the last tag, commits it, tags vX.Y.Z and creates a GitHub release:

Commits since the last releaseBump
feat!: or BREAKING CHANGEmajor
feat:minor
anything elsepatch

Installed copies get the new version with /plugin marketplace update tdd-mod (or Claude Code's marketplace auto-update). The official Anthropic marketplace takes third-party plugins only through its submission form, so that step is manual.

FileWhat it holds
.claude-plugin/plugin.jsonThe plugin manifest: name, version, settings
.claude-plugin/marketplace.jsonMakes this repository a marketplace that lists the plugin
hooks/hooks.jsonPoints Claude Code at src/register.ts
src/register.tsThe hooks: prompt and subagent-brief classification, response batches, the write and Bash guards, the verdict cache, /tdd-eval
src/guard.tsThe two decisions: task kind, and pass/violation for a write
src/prompt.tsThe judge's TDD rules, ported from probity
src/tdd.tsPrompt building, session history, the last test run, applying an Edit, the one-new-test check
src/batch.tsWhich writes of a response form a batch, and the files they leave
src/task.tsThe task classifier prompt and the guard-override rule
src/bash.tsWhich source files a shell command would write
src/config.tsSettings, globs, which files are in scope, which are tests
src/eval.tsThe /tdd-eval runner
test/Unit and hook tests, run by claude plugin test .
eval/The regression cases

Known limits

  • The task label holds for the whole turn. If a "move this class" turn also changes behaviour, nothing judges it.
  • After a non-coding prompt, "continue" keeps the guard off. Name the coding task ("now add …") to switch it back on.
  • A subagent's label holds for its whole life. A message sent to it later (SendMessage, a resumed agent, a teammate's next task) does not relabel it, and a resumed coding subagent whose label was kept is judged but not counted in the status line.
  • A subagent with no label is labelled from the first message with text in its transcript. That is its brief, unless the transcript has outgrown the newest 4096 messages the session reads back. A transcript the session cannot read (a workflow's agents) or without such a message leaves the subagent on the main session's label; the debug log says subagent <agentId> has no brief to label. If the classifier fails, the subagent is judged as coding and the debug log says not classified.
  • Each subagent spawn waits for one classifier call before the subagent starts; a subagent labelled late waits for it at its first write.
  • Shell writes are caught by pattern. A script file that is written and then run, or a path built at runtime, gets through.
  • Judges disagree. Stronger models are more lenient on the current prompt; see the eval table above.
  • Test files are never judged. Adding two tests at once, or a new test while the last green left a refactor unmade, goes through in a test file. Fixtures and helpers under a test folder count as tests too. A shell write to a test file passes too.
  • One new test always passes, so the check for a refactor left unmade after green is skipped (turn off fastPath to get it back).
  • Only one response is a batch. A change the agent spreads over consecutive responses (the method now, its call next turn) is still judged one write at a time. Test files in a response are not part of its batch; they pass on their own.
  • Only identical retries are stable. Two equivalent edits to sibling files are judged separately and can still get opposite verdicts. The verdict cache starts over when the mod reloads.
  • A test run is recognised by its command: a runner's test subcommand (npm test, go test, cargo test, claude plugin test, …), a runner by name (vitest, jest, pytest, …) or a Maven/Gradle build. A project script (./check_all.sh) is not one. It counts as red when the command failed or its output reads like a failure (FAIL, 1 failed, Failures: 2, AssertionError, panicked), green otherwise.

Credits

The TDD rules in src/prompt.ts are from probity by Nizar Selander, MIT License.

License

MIT, see LICENSE.

Source 9 files
src/register.ts 436 lines
1import type { EngineInterface, Register, SessionMessage, TurnStepToolUse } from 'claude-code'
2import { bashWriteTargets } from './bash.ts'
3import { applyCalls, batchFor, filesOf, type WriteCall } from './batch.ts'
4import { isInProject, isInScope, isTestFile, readConfig, type Config } from './config.ts'
5import { runEval } from './eval.ts'
6import { classifyTask, decide, type Complete, type Pending, type Usage } from './guard.ts'
7import { isGuardInstruction, type TaskKind } from './task.ts'
8import { evidenceOf, lastTestRun, nextStep, toHistory, type Change, type FileContent, type HistoryEvent, type Verdict } from './tdd.ts'
9
10// $.ui.log refuses a line over 4096 characters; leave room for the header.
11const LOG_CHUNK = 3800
12// The engine runs a tool while the rest of its response still streams in; a
13// write waits this long for the whole response, so it is judged with the
14// writes sent beside it. The wait counts against the hook's 10 s budget (the
15// `$` calls before it and the model calls after it do not), and a hook past
16// it is skipped, its write let through: 8 s leaves 2 s for the hook's own code.
17const BATCH_WAIT_MS = 8000
18
19/**
20 * `byEvidence`: verdicts by write and evidence, so an identical retry with
21 * nothing new gets the same answer; `byWrite`: the latest verdict per write,
22 * to log a retry that reverses it.
23 */
24type Verdicts = { byEvidence: Map<string, Verdict>; byWrite: Map<string, Verdict['kind']> }
25
26/** The task labels writes are judged by: the main session's, and each subagent's from its brief. */
27type Labels = {
28  main: () => TaskKind
29  agents: ReadonlyMap<string, TaskKind>
30  late: Map<string, Promise<TaskKind | undefined>>
31  running: Set<string>
32  status: () => string
33}
34
35/** One model response: the tool calls it asked for once whole, and the verdict on the writes it batches. */
36type Step = { uses: readonly TurnStepToolUse[]; ended: boolean; whole: Promise<void>; end: () => void; verdict?: Promise<Verdict> }
37
38function startStep(): Step {
39  let resolve = () => {}
40  const whole = new Promise<void>(r => (resolve = r))
41  const step: Step = {
42    uses: [],
43    ended: false,
44    whole,
45    end: () => {
46      step.ended = true
47      resolve()
48    },
49  }
50  return step
51}
52
53export const register: Register = (on, options) => {
54  const config = readConfig(options)
55  if (!config.enabled) return
56  const inScope = (path: string, root: string) => isInScope(path, config) && isInProject(path, root)
57  // The writes the judge sees: source files of the project that are not tests.
58  const judgedIn = (root: string) => (path: string) => inScope(path, root) && !isTestFile(path, root)
59
60  // The main session's task kind, from the latest typed prompt. Starts as
61  // coding, also after a reload, so the guard is on until a prompt says otherwise.
62  let task: TaskKind = 'coding'
63  // Each subagent's own kind, from its brief, by agentId. One spawned before a
64  // reload has none and is labelled late, at its first write (labels.late).
65  const agents = new Map<string, TaskKind>()
66  // The coding subagents whose run has not ended, for the status line.
67  const running = new Set<string>()
68  // The version in plugin.json, read at session start; none if it is unreadable.
69  let version: string | undefined
70  const status = () => {
71    const kind = task === 'coding' ? 'TDD on' : 'TDD off (not coding)'
72    // The engine puts "tdd-mod:" in front of the line, so the version follows bare.
73    const main = version === undefined ? kind : `(${version}) · ${kind}`
74    const n = running.size
75    return n === 0 ? main : `${main} · judging ${n} subagent${n === 1 ? '' : 's'}`
76  }
77  const labels: Labels = { main: () => task, agents, late: new Map(), running, status }
78  const verdicts: Verdicts = { byEvidence: new Map(), byWrite: new Map() }
79  // The latest model response of each loop (main: ''), whose tool calls are running now.
80  const steps = new Map<string, Step>()
81
82  on('session.start', async ($, e, next) => {
83    for (const problem of config.problems) $.ui.log(`tdd-mod: ${problem}`)
84    version = await readVersion($)
85    // The guard is on from here, also after a reload; say so before any prompt.
86    $.ui.status(status())
87    await $.command.register({
88      name: 'tdd-eval',
89      description: 'Replays the tdd-mod regression cases through the configured models.',
90      argumentHint: '[runs per case]',
91    })
92    return next(e)
93  })
94
95  on('command.run', { command: 'tdd-eval' }, async ($, e) => {
96    const runs = Math.max(1, Math.min(10, Number.parseInt(e.args, 10) || 3))
97    const complete: Complete = (request, options) => $.model.complete(request, options)
98    const root = $.plugin.root
99    const text = await runEval(complete, file => $.fs.read(`${root}/eval/${file}`), config, runs)
100    return { text }
101  })
102
103  // Only what the person types changes the task; notifications and messages
104  // from other agents arrive as prompts too, and keep it.
105  on('prompt.submit', async ($, e, next) => {
106    if (!config.classifyTasks || e.origin.kind !== 'composer' || isGuardInstruction(e.text)) return next(e)
107    task = await classifyTask(request => $.model.complete(request), config, e.text, task)
108    $.ui.status(status())
109    $.ui.log(`tdd-mod: task ${task}: ${excerpt(e.text)}`, { to: 'debug' })
110    return next(e)
111  })
112
113  // A subagent's task is its brief, not the prompt the person last typed.
114  on('agent.spawn', async ($, e, next) => {
115    if (!config.classifyTasks) return next(e)
116    const kind = await classifyTask(request => $.model.complete(request), config, e.prompt, 'coding')
117    const spawned = await next(e)
118    const { agentId } = spawned
119    if (agentId === undefined) return spawned
120    agents.set(agentId, kind)
121    if (kind === 'coding') running.add(agentId)
122    $.ui.status(status())
123    $.ui.log(`tdd-mod: subagent ${agentId} task ${kind}: ${excerpt(e.prompt)}`, { to: 'debug' })
124    return spawned
125  })
126
127  on('turn.complete', ($, e, next) => {
128    if (e.agentId !== undefined && running.delete(e.agentId)) $.ui.status(status())
129    return next(e)
130  })
131
132  // Remembers which tool calls each response asked for, so the writes sent
133  // in one response can be judged together.
134  on('turn.step', async function* ($, e, next) {
135    const step = startStep()
136    steps.set(e.agentId ?? '', step)
137    try {
138      const response = yield* next(e)
139      step.uses = response.toolUses
140      return response
141    } finally {
142      step.end()
143    }
144  })
145
146  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
147    const root = await projectRoot($)
148    if (!inScope(e.file_path, root) || !(await judging($, config, labels, e.agentId))) return next(e)
149    if (isTestFile(e.file_path, root)) {
150      await shown($, await now($), 'pass', e.file_path, 'test file')
151      return next(e)
152    }
153    const call: WriteCall = { tool: 'Write', file_path: e.file_path, content: e.content }
154    const verdict = await judgeCall($, config, verdicts, steps.get(e.agentId ?? ''), judgedIn(root), e.agentId, call)
155    return verdict?.kind === 'violation' ? { deny: denial(verdict) } : next(e)
156  })
157
158  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
159    const root = await projectRoot($)
160    if (!inScope(e.file_path, root) || !(await judging($, config, labels, e.agentId))) return next(e)
161    if (isTestFile(e.file_path, root)) {
162      await shown($, await now($), 'pass', e.file_path, 'test file')
163      return next(e)
164    }
165    const call: WriteCall = { tool: 'Edit', file_path: e.file_path, old_string: e.old_string, new_string: e.new_string, replace_all: e.replace_all }
166    const verdict = await judgeCall($, config, verdicts, steps.get(e.agentId ?? ''), judgedIn(root), e.agentId, call)
167    return verdict?.kind === 'violation' ? { deny: denial(verdict) } : next(e)
168  })
169
170  // Shell writes bypass the TDD check: send them through Write/Edit instead.
171  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
172    const targets = bashWriteTargets(e.command, judgedIn(await projectRoot($)))
173    if (targets.length === 0 || !(await judging($, config, labels, e.agentId))) return next(e)
174    $.ui.log(`tdd-mod: violation (bash write) ${targets.join(', ')}`, { to: 'debug' })
175    return {
176      deny:
177        `tdd-mod: this command writes to ${targets.join(', ')}. Create and change ` +
178        'source files with the Write or Edit tool, so the TDD check can judge the change.',
179    }
180  })
181
182  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
183    const root = await projectRoot($)
184    if (!inScope(e.notebook_path, root) || !(await judging($, config, labels, e.agentId))) return next(e)
185    if (isTestFile(e.notebook_path, root)) {
186      await shown($, await now($), 'pass', e.notebook_path, 'test file')
187      return next(e)
188    }
189    const started = await now($)
190    const before = await readBefore($, e.notebook_path)
191    const mode = e.edit_mode ?? 'replace'
192    const content =
193      `Notebook cell edit (${mode}) on cell ${e.cell_id ?? '(first)'}` +
194      `${e.cell_type ? `, type ${e.cell_type}` : ''}. New cell source:\n\n${e.new_source}`
195    const verdict = await judgeWrite($, config, verdicts, started, e.agentId, before, { path: e.notebook_path, content })
196    return verdict.kind === 'pass' ? next(e) : { deny: denial(verdict) }
197  })
198}
199
200/** Whether the writes of `agentId`'s loop are judged; absent, the main session's. */
201async function judging($: EngineInterface, config: Config, labels: Labels, agentId: string | undefined): Promise<boolean> {
202  if (agentId === undefined) return labels.main() === 'coding'
203  const kind = labels.agents.get(agentId) ?? (await labelLateOnce($, config, labels, agentId))
204  return (kind ?? labels.main()) === 'coding'
205}
206
207/** The version plugin.json names, or undefined when it cannot be read. */
208async function readVersion($: EngineInterface): Promise<string | undefined> {
209  try {
210    const { version } = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: unknown }
211    return typeof version === 'string' ? version : undefined
212  } catch {
213    return undefined
214  }
215}
216
217/** labelLate, once per agent: the pending label is stored, so writes racing in classify its brief once. */
218function labelLateOnce($: EngineInterface, config: Config, labels: Labels, agentId: string): Promise<TaskKind | undefined> {
219  let label = labels.late.get(agentId)
220  if (label === undefined) labels.late.set(agentId, (label = labelLate($, config, labels, agentId)))
221  return label
222}
223
224/**
225 * A subagent no agent.spawn hook saw (spawned before a reload) is labelled
226 * from its brief, read back from its own transcript; undefined follows the
227 * main session.
228 */
229async function labelLate($: EngineInterface, config: Config, labels: Labels, agentId: string): Promise<TaskKind | undefined> {
230  if (!config.classifyTasks) return undefined
231  const brief = briefOf(await $.session.messages({ agentId }))
232  if (brief === undefined) {
233    $.ui.log(`tdd-mod: subagent ${agentId} has no brief to label; it follows the main task`, { to: 'debug' })
234    return undefined
235  }
236  // A failed call counts as coding, as classifyTask has it; a refused one too,
237  // instead of failing the hook, which would let the write through unjudged.
238  const failed = (why: string) => $.ui.log(`tdd-mod: subagent ${agentId} not classified (${why}); judged as coding`, { to: 'debug' })
239  const complete: Complete = async request => {
240    const reply = await $.model.complete(request)
241    if (!reply.isAnswered) failed(reply.reason)
242    return reply
243  }
244  const kind = await classifyTask(complete, config, brief, 'coding').catch((error: unknown) => {
245    failed(error instanceof Error ? error.message : String(error))
246    return 'coding' as const
247  })
248  $.ui.log(`tdd-mod: subagent ${agentId} labelled late (${kind}): ${excerpt(brief)}`, { to: 'debug' })
249  if (kind === 'coding') {
250    labels.running.add(agentId)
251    $.ui.status(labels.status())
252  }
253  return kind
254}
255
256/** A subagent's brief: the first user message with text in its transcript; undefined when unreadable or none. */
257function briefOf(messages: readonly SessionMessage[] | { deny: string }): string | undefined {
258  return Array.isArray(messages) ? messages.find(m => m.role === 'user' && m.text.trim() !== '')?.text : undefined
259}
260
261async function readBefore($: EngineInterface, path: string): Promise<FileContent> {
262  try {
263    if (!(await $.fs.exists(path))) return { kind: 'absent' }
264    return { kind: 'present', content: await $.fs.read(path) }
265  } catch {
266    return { kind: 'unknown' }
267  }
268}
269
270/** The project root, so a test folder is told apart from the folder the checkout lives in; '' when unknown. */
271async function projectRoot($: EngineInterface): Promise<string> {
272  try {
273    return await $.session.root()
274  } catch {
275    return ''
276  }
277}
278
279/**
280 * Judges a Write or Edit together with the other judged writes of the same
281 * model response, on the files they leave together: the first of them is
282 * judged, the rest get its verdict. Undefined when the write cannot apply;
283 * the tool itself then reports that.
284 */
285async function judgeCall(
286  $: EngineInterface,
287  config: Config,
288  verdicts: Verdicts,
289  step: Step | undefined,
290  judged: (path: string) => boolean,
291  agentId: string | undefined,
292  call: WriteCall,
293): Promise<Verdict | undefined> {
294  // From the write's call, so the wait for its response counts in the logged latency.
295  const started = await now($)
296  const batch = step && (await wholeResponse($, step)) ? batchFor(step.uses, call, judged) : [call]
297  if (batch.length > 1 && step?.verdict) {
298    const verdict = await step.verdict
299    await shown($, started, verdict.kind, call.file_path, `batch of ${batch.length}`)
300    return verdict
301  }
302  const together = batch.length > 1 ? await changesOf($, batch, call) : undefined
303  // A batch that no longer applies (one of its writes already ran unjudged): this write alone.
304  const changes = together ?? (await changesOf($, [call], call))
305  const [main, ...also] = changes ?? []
306  if (main === undefined) return undefined
307  const verdict = judgeWrite($, config, verdicts, started, agentId, main.before, { path: main.path, content: main.content }, also)
308  if (together && step) step.verdict = verdict
309  return verdict
310}
311
312/**
313 * Each file `batch` writes, as it is and as the batch leaves it, `call`'s
314 * file first; undefined when one of the writes cannot apply.
315 */
316async function changesOf($: EngineInterface, batch: readonly WriteCall[], call: WriteCall): Promise<Change[] | undefined> {
317  const changes: Change[] = []
318  for (const path of [call.file_path, ...filesOf(batch).filter(p => p !== call.file_path)]) {
319    const before = await readBefore($, path)
320    const content = applyCalls(path, before, batch)
321    if (content === undefined) return undefined
322    changes.push({ path, before, content })
323  }
324  return changes
325}
326
327/** Whether `step`'s response is whole, waiting up to BATCH_WAIT_MS for it. */
328async function wholeResponse($: EngineInterface, step: Step): Promise<boolean> {
329  if (step.ended) return true
330  let timer: { cancel: () => void } | undefined
331  const timeout = new Promise<void>(resolve => {
332    try {
333      timer = $.clock.after(BATCH_WAIT_MS, resolve)
334    } catch {
335      resolve()
336    }
337  })
338  await Promise.race([step.whole, timeout])
339  timer?.cancel()
340  return step.ended
341}
342
343async function judgeWrite(
344  $: EngineInterface,
345  config: Config,
346  verdicts: Verdicts,
347  started: number,
348  agentId: string | undefined,
349  before: FileContent,
350  pending: Pending,
351  also: readonly Change[] = [],
352): Promise<Verdict> {
353  const history = await recentHistory($, agentId)
354  // The write (who, where, from what to what), and that write with the evidence its verdict rests on.
355  const write = `${pending.path} ${hash(JSON.stringify([agentId ?? null, before, pending.content, also]))}`
356  const key = `${write} ${hash(evidenceOf(history))}`
357  const cached = verdicts.byEvidence.get(key)
358  if (cached) {
359    await shown($, started, cached.kind, pending.path, 'cached')
360    return cached
361  }
362  const complete: Complete = (request, options) => $.model.complete(request, options)
363  const decision = await decide(complete, config, async () => history, before, pending, also)
364  const which = (i: number) => (decision.fastPath ? 'fast path: one new test' : i === 0 ? 'first opinion' : 'second opinion')
365  decision.opinions.forEach((verdict, i) => log($, verdict, pending, which(i)))
366  if (decision.verdict.kind === 'violation' && decision.prompt) logPrompt($, decision.prompt, pending)
367  await shown($, started, decision.verdict.kind, pending.path, which(decision.opinions.length - 1), decision.usage)
368  const previous = verdicts.byWrite.get(write)
369  if (previous !== undefined && previous !== decision.verdict.kind) {
370    $.ui.log(`tdd-mod: verdict reversed on retry (${previous} → ${decision.verdict.kind}) ${pending.path}`, { to: 'debug' })
371  }
372  // A block the judge answered says what to do next; a missing answer already says retry.
373  const verdict = decision.verdict.kind === 'violation' && !decision.verdict.unanswered ? { ...decision.verdict, next: nextStep(lastTestRun(history)) } : decision.verdict
374  if (!verdict.unanswered) verdicts.byEvidence.set(key, verdict)
375  verdicts.byWrite.set(write, verdict.kind)
376  return verdict
377}
378
379/** cyrb53: a fast 53-bit string hash, so the verdict cache keeps no file contents. */
380function hash(text: string): number {
381  let h1 = 0xdeadbeef
382  let h2 = 0x41c6ce57
383  for (let i = 0; i < text.length; i++) {
384    const c = text.charCodeAt(i)
385    h1 = Math.imul(h1 ^ c, 2654435761)
386    h2 = Math.imul(h2 ^ c, 1597334677)
387  }
388  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
389  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
390  return 4294967296 * (2097151 & h2) + (h1 >>> 0)
391}
392
393/** One transcript line per decision, passes included, with how it was reached and how long it took. */
394async function shown($: EngineInterface, started: number, kind: Verdict['kind'], path: string, how: string, usage?: Usage): Promise<void> {
395  const tokens = usage && usage.input + usage.output > 0 ? `, ${usage.input} in / ${usage.output} out tokens` : ''
396  $.ui.log(`tdd-mod: ${kind} ${path} (${how}, ${(await now($)) - started} ms${tokens})`)
397}
398
399/** The host's time, the one the batch wait runs on; the process's when the host has none. */
400async function now($: EngineInterface): Promise<number> {
401  try {
402    return await $.clock.now()
403  } catch {
404    return Date.now()
405  }
406}
407
408/** The agent's whole session: buildPrompt shows its recent part and its last test run. */
409async function recentHistory($: EngineInterface, agentId: string | undefined): Promise<HistoryEvent[]> {
410  const messages = await $.session.messages(agentId === undefined ? {} : { agentId })
411  return Array.isArray(messages) ? toHistory(messages) : []
412}
413
414function log($: EngineInterface, verdict: Verdict, pending: Pending, which: string): void {
415  const reason = verdict.reason ? ` — ${verdict.reason}` : ''
416  $.ui.log(`tdd-mod: ${verdict.kind} (${which}) ${pending.path}${reason}`, { to: 'debug' })
417}
418
419/** The blocked write's prompt, in numbered parts, so it can be replayed exactly. */
420function logPrompt($: EngineInterface, prompt: string, pending: Pending): void {
421  const parts = Math.ceil(prompt.length / LOG_CHUNK)
422  for (let i = 0; i < parts; i++) {
423    const part = prompt.slice(i * LOG_CHUNK, (i + 1) * LOG_CHUNK)
424    $.ui.log(`tdd-mod: blocked prompt ${pending.path} part ${i + 1}/${parts}:\n${part}`, { to: 'debug' })
425  }
426}
427
428/** The start of a prompt, on one line, for the debug log. */
429function excerpt(text: string): string {
430  return text.slice(0, 80).replace(/\s+/g, ' ')
431}
432
433function denial(verdict: Verdict): string {
434  return verdict.next ? `tdd-mod: ${verdict.reason}\n${verdict.next}` : `tdd-mod: ${verdict.reason}`
435}
436
src/bash.ts 129 lines
1// Finds the source files a Bash command would write, so the guard can send
2// those writes through Write/Edit where the TDD check judges them. A
3// best-effort shell reading, not a parser: it covers the ways agents write
4// files from a shell (redirects, tee, sed -i, cp, dd, inline scripts). A
5// move (mv, git mv) keeps the code as it is, so it is no write here.
6
7// `<<EOF`, `<<-EOF`, `<<'EOF'`, `<<"EOF"`, then the body up to the line that ends it.
8const HEREDOC = /<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n[ \t]*\2[ \t]*(?=\n|$)/g
9// `>`, `>>`, `>|`, `2>`, `&>` followed by a target; not `>&2` and not `->`/`=>`.
10const REDIRECT = /(?:^|[^-=<>])(?:\d|&)?>[>|]?(?!&)\s*(['"]?)([^\s;|&<>'"()]+)\1/g
11// Inline interpreters: Python open(..., 'w'|'a'), write_text/write_bytes, Node writeFile(Sync).
12const SCRIPT_WRITE = /open\([^)]*['"][wax]\+?b?['"]|\.write_(?:text|bytes)\(|writeFile(?:Sync)?\(|appendFile(?:Sync)?\(/
13const PATH_LITERAL = /['"`]([^'"`\s]+\.\w+)['"`]/g
14// A command that runs a script, as `python3 -`, `/usr/bin/node -e`, `uv run python`: not `cat > f <<EOF`.
15const INTERPRETER = /(?:^|\/)(?:python[\d.]*|node(?:js)?|deno|bun|tsx|ts-node|ruby|perl|php)$/
16
17/** A simple command's words, where it starts in the shell text, and the directory a `cd` before it left (undefined: unknown). */
18type Command = { words: string[]; at: number; dir: string | undefined }
19
20/** `path` as seen from `dir`, `.` and `..` folded; unchanged when it is absolute or the directory is unknown. */
21function resolveIn(dir: string | undefined, path: string): string {
22  if (dir === undefined || /^[/$~]/.test(path)) return path
23  const parts: string[] = []
24  for (const part of (dir === '' ? path : `${dir}/${path}`).split('/')) {
25    if (part === '.' || (part === '' && parts.length > 0)) continue
26    if (part === '..' && parts.length > 0 && parts[parts.length - 1] !== '..') {
27      if (parts[parts.length - 1] !== '') parts.pop()
28    } else parts.push(part)
29  }
30  return parts.join('/')
31}
32
33/**
34 * The simple commands of `shell` as words, split on unquoted `;`, `|`, `&`
35 * and newlines, quotes removed: `sed -i 's/a;b/c/' f` stays one command.
36 * Each carries the directory the `cd`s before it left, relative to where the
37 * shell started ('' there), so a relative path can be read from where it runs.
38 */
39function commands(shell: string): Command[] {
40  const result: Command[] = []
41  let dir: string | undefined = ''
42  let words: string[] = []
43  let word = ''
44  let at = 0
45  let quote: string | undefined
46  const endWord = () => {
47    if (word !== '') words.push(word)
48    word = ''
49  }
50  const endCommand = () => {
51    endWord()
52    if (words[0]?.startsWith('(')) words[0] = words[0].slice(1)
53    if (words.length > 0) result.push({ words, at, dir })
54    if (words[0] === 'cd') dir = words.length === 2 && !/^[-$~]/.test(words[1] ?? '') ? resolveIn(dir, words[1] ?? '') : undefined
55    words = []
56  }
57  for (let i = 0; i < shell.length; i++) {
58    const c = shell[i] ?? ''
59    if (words.length === 0 && word === '') at = i
60    if (quote !== undefined) {
61      if (c === quote) quote = undefined
62      else if (c === '\\' && quote === '"') word += shell[++i] ?? ''
63      else word += c
64    } else if (c === "'" || c === '"') quote = c
65    else if (c === '\\') word += shell[++i] ?? ''
66    else if (c === ';' || c === '|' || c === '&' || c === '\n') endCommand()
67    else if (c === ' ' || c === '\t') endWord()
68    else word += c
69  }
70  endCommand()
71  return result
72}
73
74/** The source files `command` would write that `inScope` accepts, deduplicated, in order of appearance. */
75export function bashWriteTargets(command: string, inScope: (path: string) => boolean): string[] {
76  const targets: string[] = []
77  // The command without its heredoc bodies, and each body with where it stood.
78  const heredocs: { at: number; body: string }[] = []
79  let shell = ''
80  let last = 0
81  for (const m of command.matchAll(HEREDOC)) {
82    shell += command.slice(last, m.index)
83    heredocs.push({ at: shell.length, body: m[0] })
84    shell += m[0].slice(0, m[0].indexOf('\n'))
85    last = m.index + m[0].length
86  }
87  shell += command.slice(last)
88
89  const parsed = commands(shell)
90  const dirAt = (offset: number) => parsed.findLast(c => c.at <= offset)?.dir ?? ''
91
92  for (const m of shell.matchAll(REDIRECT)) targets.push(resolveIn(dirAt(m.index), m[2] ?? ''))
93
94  for (const { words: [cmd, ...args], dir } of parsed) {
95    const operands = args.filter(a => !a.startsWith('-'))
96    const written: string[] = []
97    switch (cmd) {
98      case 'tee':
99        written.push(...operands)
100        break
101      case 'sed':
102      case 'perl':
103        if (args.some(a => /^-[a-zA-Z]*i/.test(a) || a.startsWith('--in-place'))) written.push(...operands)
104        break
105      case 'cp':
106      case 'install':
107        if (operands.length > 0) written.push(operands[operands.length - 1] ?? '')
108        break
109      case 'dd':
110        written.push(...args.filter(a => a.startsWith('of=')).map(a => a.slice(3)))
111        break
112    }
113    targets.push(...written.map(path => resolveIn(dir, path)))
114  }
115
116  // An inline script that writes files and names a source file: its target is
117  // often a variable, so every source path it names counts, read from where
118  // the command that runs it stands. A heredoc fed to `cat > f` is content.
119  parsed.forEach(({ words, at, dir }, i) => {
120    if (!words.some(w => INTERPRETER.test(w))) return
121    const end = parsed[i + 1]?.at ?? Infinity
122    const script = [words.join(' '), ...heredocs.filter(h => h.at >= at && h.at < end).map(h => h.body)].join('\n')
123    if (!SCRIPT_WRITE.test(script)) return
124    for (const m of script.matchAll(PATH_LITERAL)) targets.push(resolveIn(dir, m[1] ?? ''))
125  })
126
127  return [...new Set(targets.filter(inScope))]
128}
129
src/batch.ts 60 lines
1// Writes the model asks for in one response land together: the guard judges
2// them on the file state they leave together, not one at a time, so a method
3// and its call, or a signature and its caller, are not each denied as
4// incomplete. Pure: the hooks module reads the files and the response.
5import type { TurnStepToolUse } from 'claude-code'
6import { applyEdit, type FileContent } from './tdd.ts'
7
8/** A Write or Edit, as `tool.call` carries it and a model response lists it. */
9export type WriteCall = {
10  tool: string
11  file_path: string
12  content?: string
13  old_string?: string
14  new_string?: string
15  replace_all?: boolean
16}
17
18/** The Write or Edit a response lists, or undefined for any other tool call. */
19export function asWriteCall(use: TurnStepToolUse): WriteCall | undefined {
20  if (use.name !== 'Write' && use.name !== 'Edit') return undefined
21  const input = use.input as Partial<WriteCall> | null
22  return typeof input?.file_path === 'string' ? { ...input, tool: use.name, file_path: input.file_path } : undefined
23}
24
25export function sameCall(a: WriteCall, b: WriteCall): boolean {
26  return (
27    a.tool === b.tool && a.file_path === b.file_path && a.content === b.content &&
28    a.old_string === b.old_string && a.new_string === b.new_string
29  )
30}
31
32/**
33 * The writes of `uses` the guard judges, in order, when `call` is one of
34 * them; else `call` alone.
35 */
36export function batchFor(uses: readonly TurnStepToolUse[], call: WriteCall, judged: (path: string) => boolean): WriteCall[] {
37  const calls = uses.flatMap(use => asWriteCall(use) ?? []).filter(c => judged(c.file_path))
38  return calls.some(c => sameCall(c, call)) ? calls : [call]
39}
40
41/** The files a batch writes, in the order it first writes them. */
42export function filesOf(batch: readonly WriteCall[]): string[] {
43  return [...new Set(batch.map(c => c.file_path))]
44}
45
46/**
47 * The file after the batch's writes to `path` in order, or undefined when one
48 * of them cannot apply (the tool then reports it).
49 */
50export function applyCalls(path: string, before: FileContent, batch: readonly WriteCall[]): string | undefined {
51  let content = before.kind === 'present' ? before.content : undefined
52  for (const call of batch) {
53    if (call.file_path !== path) continue
54    if (call.tool === 'Write') content = call.content ?? ''
55    else if (content !== undefined) content = applyEdit(content, call.old_string ?? '', call.new_string ?? '', call.replace_all)
56    if (content === undefined) return undefined
57  }
58  return content
59}
60
src/config.ts 143 lines
1// The plugin's settings (plugin.json `userConfig`) as the hooks use them.
2import type { PluginOptions } from 'claude-code'
3import { DEFAULT_TEST_PATTERNS, type TestPatterns } from './tdd.ts'
4
5export type Config = {
6  enabled: boolean
7  judgeModel: string
8  classifierModel: string
9  classifyTasks: boolean
10  fastPath: boolean
11  secondOpinion: boolean
12  parallelOpinions: boolean
13  extensions: ReadonlySet<string>
14  ignore: readonly RegExp[]
15  testPatterns: TestPatterns
16  /** Settings that could not be used, each with what was wrong; the mod shows them at session start. */
17  problems: readonly string[]
18}
19
20function list(value: unknown): string[] {
21  return typeof value === 'string' ? value.split(',').map(s => s.trim()).filter(Boolean) : []
22}
23
24function text(value: unknown, fallback: string): string {
25  return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback
26}
27
28function flag(value: unknown, fallback: boolean): boolean {
29  return typeof value === 'boolean' ? value : fallback
30}
31
32/** `**` any run of folders, `*` any part of one name, `?` one character. */
33export function globToRegExp(glob: string): RegExp {
34  let source = ''
35  for (let i = 0; i < glob.length; i++) {
36    const c = glob[i] ?? ''
37    if (c === '*' && glob[i + 1] === '*') {
38      const slash = glob[i + 2] === '/'
39      source += slash ? '(?:.*/)?' : '.*'
40      i += slash ? 2 : 1
41    } else if (c === '*') source += '[^/]*'
42    else if (c === '?') source += '[^/]'
43    else source += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
44  }
45  return new RegExp(`^${source}$`)
46}
47
48/**
49 * The built-in test patterns with the `testPatterns` setting applied: a JSON
50 * object from comma-separated extensions to a regex source, e.g.
51 * `{"ts,js": "\\bscenario\\(", "py": "^\\s*def should_"}`. Each entry replaces
52 * the built-in pattern for its extensions; an empty string removes it.
53 */
54export function readTestPatterns(value: unknown): { patterns: TestPatterns; problems: string[] } {
55  const patterns: Record<string, RegExp> = { ...DEFAULT_TEST_PATTERNS }
56  const problems: string[] = []
57  if (typeof value !== 'string' || value.trim() === '') return { patterns, problems }
58  let entries: unknown
59  try {
60    entries = JSON.parse(value)
61  } catch (error) {
62    problems.push(`testPatterns is not valid JSON (${(error as Error).message}); using the built-in patterns`)
63    return { patterns, problems }
64  }
65  if (typeof entries !== 'object' || entries === null || Array.isArray(entries)) {
66    problems.push('testPatterns must be a JSON object like {"ts,js": "regex"}; using the built-in patterns')
67    return { patterns, problems }
68  }
69  for (const [keys, source] of Object.entries(entries)) {
70    const extensions = list(keys).map(e => e.replace(/^\./, '').toLowerCase())
71    if (typeof source !== 'string') {
72      problems.push(`testPatterns["${keys}"] is not a string; kept the built-in pattern`)
73      continue
74    }
75    if (source === '') {
76      for (const ext of extensions) delete patterns[ext]
77      continue
78    }
79    try {
80      // g: count every declaration; m: ^ and $ match per line.
81      const pattern = new RegExp(source, 'gm')
82      for (const ext of extensions) patterns[ext] = pattern
83    } catch (error) {
84      problems.push(`testPatterns["${keys}"] is not a valid regex (${(error as Error).message}); kept the built-in pattern`)
85    }
86  }
87  return { patterns, problems }
88}
89
90/** The engine fills in the manifest's defaults; the fallbacks cover a test or a hand-edited value. */
91export function readConfig(options: PluginOptions): Config {
92  const tests = readTestPatterns(options.testPatterns)
93  return {
94    enabled: flag(options.enabled, true),
95    judgeModel: text(options.judgeModel, 'haiku'),
96    classifierModel: text(options.classifierModel, 'haiku'),
97    classifyTasks: flag(options.classifyTasks, true),
98    fastPath: flag(options.fastPath, true),
99    secondOpinion: flag(options.secondOpinion, true),
100    parallelOpinions: flag(options.parallelOpinions, true),
101    extensions: new Set(list(options.extensions).map(e => e.replace(/^\./, '').toLowerCase())),
102    ignore: list(options.ignore).map(globToRegExp),
103    testPatterns: tests.patterns,
104    problems: tests.problems,
105  }
106}
107
108// A test folder (test/, tests/, __tests__/, so src/test/ too) or a test file name:
109// *.test.*, *.spec.*, *Test.java|kt, *IT.java|kt, test_*.py, *_test.py, *_test.go.
110const TEST_FILE =
111  /(?:^|\/)(?:tests?|__tests__)\/|\.(?:test|spec)\.\w+$|[a-z0-9](?:Test|IT)\.(?:java|kt)$|(?:^|\/)test_\w+\.py$|_test\.(?:py|go)$/
112
113/**
114 * Whether `path` is a test file: writing one is the red step, never judged.
115 * Only the part below the project `root` counts, so a checkout that lives in
116 * a folder named test is not all tests.
117 */
118export function isTestFile(path: string, root = ''): boolean {
119  const posix = path.replace(/\\/g, '/')
120  const base = root.replace(/\\/g, '/').replace(/\/$/, '')
121  return TEST_FILE.test(base !== '' && posix.startsWith(`${base}/`) ? posix.slice(base.length + 1) : posix)
122}
123
124/**
125 * Whether `path` lies in the project at `root`: a relative path does, an
126 * absolute one only below the root. A scratch script in /tmp is no project
127 * code. With no root known, every path does.
128 */
129export function isInProject(path: string, root: string): boolean {
130  const posix = path.replace(/\\/g, '/')
131  const base = root.replace(/\\/g, '/').replace(/\/$/, '')
132  return base === '' || !posix.startsWith('/') || posix.startsWith(`${base}/`)
133}
134
135/** Source files the guard judges: a listed extension, outside every ignored path. */
136export function isInScope(path: string, config: Config): boolean {
137  const posix = path.replace(/\\/g, '/')
138  if (config.ignore.some(glob => glob.test(posix))) return false
139  const name = posix.slice(posix.lastIndexOf('/') + 1)
140  const dot = name.lastIndexOf('.')
141  return dot > 0 && config.extensions.has(name.slice(dot + 1).toLowerCase())
142}
143
src/eval.ts 84 lines
1// /tdd-eval: replays the regression cases in eval/ through the same decisions
2// a session makes, with the configured models, and reports the hit rate.
3import type { Config } from './config.ts'
4import { classifyTask, decide, type Complete, type Pending } from './guard.ts'
5import { isGuardInstruction, type TaskKind } from './task.ts'
6import type { FileContent, HistoryEvent } from './tdd.ts'
7
8export type VerdictCase = {
9  name: string
10  expect: 'pass' | 'violation'
11  /** Why this is the right verdict, for whoever reads a failure. */
12  why: string
13  history: HistoryEvent[]
14  before: FileContent
15  pending: Pending
16}
17
18export type TaskCase = { text: string; previous: TaskKind; expect: TaskKind }
19
20const CONCURRENCY = 6
21
22async function pool<T>(jobs: (() => Promise<T>)[], size: number): Promise<T[]> {
23  const results: T[] = []
24  let next = 0
25  const worker = async () => {
26    while (next < jobs.length) {
27      const i = next++
28      results[i] = await (jobs[i] as () => Promise<T>)()
29    }
30  }
31  await Promise.all(Array.from({ length: Math.min(size, jobs.length) }, worker))
32  return results
33}
34
35/** Reads a file of eval/ by name; the hooks module passes `$.fs.read` in. */
36export type ReadEvalFile = (file: string) => Promise<string>
37
38function row(hits: number, runs: number, label: string): string {
39  return `${hits === runs ? '✓' : '✗'} ${hits}/${runs}  ${label}`
40}
41
42export async function runEval(complete: Complete, read: ReadEvalFile, config: Config, runs: number): Promise<string> {
43  const verdictCases = JSON.parse(await read('verdicts.json')) as VerdictCase[]
44  const taskCases = JSON.parse(await read('tasks.json')) as TaskCase[]
45  const lines: string[] = []
46
47  const verdictJobs = verdictCases.flatMap(c =>
48    Array.from({ length: runs }, () => () => decide(complete, config, async () => c.history, c.before, c.pending)),
49  )
50  const decisions = await pool(verdictJobs, CONCURRENCY)
51  let verdictHits = 0
52  lines.push(
53    `Verdicts — model ${config.judgeModel}, fast path ${config.fastPath ? 'on' : 'off'}, ` +
54      `second opinion ${config.secondOpinion ? 'on' : 'off'}, ${runs} runs each`,
55  )
56  verdictCases.forEach((c, i) => {
57    const mine = decisions.slice(i * runs, (i + 1) * runs)
58    const hits = mine.filter(d => d.verdict.kind === c.expect).length
59    verdictHits += hits
60    lines.push(row(hits, runs, `expect ${c.expect.padEnd(9)} ${c.name}`))
61    const miss = mine.find(d => d.verdict.kind !== c.expect)
62    if (miss) lines.push(`         got ${miss.verdict.kind}: ${miss.verdict.reason.slice(0, 160)}`)
63  })
64
65  const taskJobs = taskCases.flatMap(c =>
66    Array.from({ length: runs }, () => async () =>
67      isGuardInstruction(c.text) ? c.previous : classifyTask(complete, config, c.text, c.previous),
68    ),
69  )
70  const kinds = await pool(taskJobs, CONCURRENCY)
71  let taskHits = 0
72  lines.push('', `Tasks — model ${config.classifierModel}, ${runs} runs each`)
73  taskCases.forEach((c, i) => {
74    const hits = kinds.slice(i * runs, (i + 1) * runs).filter(k => k === c.expect).length
75    taskHits += hits
76    lines.push(row(hits, runs, `expect ${c.expect.padEnd(6)} (after ${c.previous}) ${c.text.slice(0, 70)}`))
77  })
78
79  const verdictTotal = verdictCases.length * runs
80  const taskTotal = taskCases.length * runs
81  lines.push('', `Verdicts ${verdictHits}/${verdictTotal}, tasks ${taskHits}/${taskTotal}`)
82  return lines.join('\n')
83}
84
src/guard.ts 103 lines
1// The guard's two decisions, shared by the session's hooks and /tdd-eval:
2// which kind of task a prompt starts, and whether a write follows TDD.
3import type { ModelCompleteRequest, ModelCompleteResult } from 'claude-code'
4import type { Config } from './config.ts'
5import { buildTaskPrompt, parseTaskKind, type TaskKind } from './task.ts'
6import { addsExactlyOneTest, buildPrompt, parseVerdict, type Change, type FileContent, type HistoryEvent, type Verdict } from './tdd.ts'
7
8const TIMEOUT_MS = 120_000
9
10export type Pending = { path: string; content: string }
11
12/** A model call; the hooks module passes `$.model.complete` in, since `$` cannot cross an import. */
13export type Complete = (request: ModelCompleteRequest, options?: { signal?: AbortSignal }) => Promise<ModelCompleteResult>
14
15/** The task kind after `text`; a failed call counts as coding, so the guard stays on. */
16export async function classifyTask(
17  complete: Complete,
18  config: Config,
19  text: string,
20  previous: TaskKind,
21): Promise<TaskKind> {
22  const reply = await complete({
23    model: config.classifierModel,
24    prompt: buildTaskPrompt(text, previous),
25    maxTokens: 10,
26    timeoutMs: TIMEOUT_MS,
27  })
28  return reply.isAnswered ? parseTaskKind(reply.text) : 'coding'
29}
30
31export type Decision = {
32  verdict: Verdict
33  /** Every verdict in order: the fast path's pass alone, or one or two model verdicts. */
34  opinions: Verdict[]
35  fastPath: boolean
36  prompt?: string
37  /** The judge's tokens over the calls that returned before the decision did; a call cut short may add more later. */
38  usage: Usage
39}
40
41export type Usage = { input: number; output: number }
42
43/**
44 * The guard's decision on one write, as a session makes it and /tdd-eval
45 * replays it: the fast path, then the verdict model, then a second opinion.
46 * `also`: the other files the write's batch changes, judged with it.
47 */
48export async function decide(
49  complete: Complete,
50  config: Config,
51  history: () => Promise<HistoryEvent[]>,
52  before: FileContent,
53  pending: Pending,
54  also: readonly Change[] = [],
55): Promise<Decision> {
56  // Adding one test is the red step itself.
57  if (also.length === 0 && config.fastPath && addsExactlyOneTest(pending.path, before, pending.content, config.testPatterns)) {
58    const verdict: Verdict = { kind: 'pass', reason: '' }
59    return { verdict, opinions: [verdict], fastPath: true, usage: { input: 0, output: 0 } }
60  }
61  const prompt = buildPrompt(await history(), before, pending, also)
62  const usage: Usage = { input: 0, output: 0 }
63  const judge: Complete = async (request, options) => {
64    const reply = await complete(request, options)
65    usage.input += reply.usage?.input_tokens ?? 0
66    usage.output += reply.usage?.output_tokens ?? 0
67    return reply
68  }
69  // A single validator call misfires now and then: block only when a second
70  // opinion agrees. Still fail-closed: two failed calls block.
71  if (config.secondOpinion && config.parallelOpinions) return { ...(await bothOpinions(judge, config, prompt)), fastPath: false, prompt, usage }
72  const first = await ask(judge, config, prompt)
73  if (first.kind === 'pass' || !config.secondOpinion) return { verdict: first, opinions: [first], fastPath: false, prompt, usage }
74  const second = await ask(judge, config, prompt)
75  return { verdict: second, opinions: [first, second], fastPath: false, prompt, usage }
76}
77
78/**
79 * Both opinions asked at once, so a block waits for the slower call rather
80 * than for one after the other: the first pass settles it and cuts the other
81 * call short; a violation waits for the other opinion.
82 */
83async function bothOpinions(complete: Complete, config: Config, prompt: string): Promise<Pick<Decision, 'verdict' | 'opinions'>> {
84  const stops = [new AbortController(), new AbortController()]
85  const asks = stops.map(stop => ask(complete, config, prompt, stop.signal))
86  const first = await Promise.race(asks.map((verdict, i) => verdict.then(v => ({ v, other: 1 - i }))))
87  if (first.v.kind === 'pass') {
88    stops[first.other]?.abort()
89    return { verdict: first.v, opinions: [first.v] }
90  }
91  const second = (await asks[first.other]) ?? first.v
92  return { verdict: second, opinions: [first.v, second] }
93}
94
95async function ask(complete: Complete, config: Config, prompt: string, signal?: AbortSignal): Promise<Verdict> {
96  const reply = await complete({ model: config.judgeModel, prompt, timeoutMs: TIMEOUT_MS }, { signal })
97  // Fail-closed: no answer from the validator counts as a violation.
98  return reply.isAnswered
99    ? parseVerdict(reply.text)
100    : { kind: 'violation', reason: `the TDD validator gave no answer (${reply.reason}); retry the write.`, unanswered: true }
101}
102
103
src/task.ts 48 lines
1// Which kind of task a prompt asks for. The guard judges writes only while
2// the task is coding; for anything else (moving or renaming code, docs,
3// config, questions) nothing is blocked.
4
5export type TaskKind = 'coding' | 'other'
6
7const MAX_PROMPT_CHARS = 4000
8
9/** The classifier prompt; `previous` decides a follow-up like "continue". */
10export function buildTaskPrompt(prompt: string, previous: TaskKind): string {
11  const text = prompt.length > MAX_PROMPT_CHARS ? `${prompt.slice(0, MAX_PROMPT_CHARS)}\n[truncated]` : prompt
12  return `Classify a request a developer gave a coding agent. Answer with exactly one label:
13
14coding: adds, changes or fixes behaviour — a feature, a bug fix, a kata or exercise
15  step, implementing something, writing tests for new behaviour.
16other: anything else — moving or renaming files, classes or functions, extracting or
17  inlining code, reorganising folders, formatting, dependencies, config, docs,
18  questions, reviews, git work.
19
20When a request mixes coding with other work, answer coding.
21The previous request was labelled ${previous}. A follow-up that names no task of its
22own gets the previous label: ${previous}. Follow-ups are "continue", "go on", "retry",
23"yes" and answers to the agent's question.
24
25Request:
26<request>
27${text}
28</request>
29
30Label:`
31}
32
33// Overriding the guard ("let it through", "I'm overriding the TDD check") is
34// about the task at hand, not a new one; haiku labels it other, which would
35// switch the guard off until the next coding request.
36const GUARD_OVERRIDE = /\boverrid(?:e|es|ing)\b|\blet (?:it|this|that|the \w+) through\b|\b(?:tdd|guard)\b/i
37
38/** Whether `prompt` speaks to the guard, so the task kind stays as it is. */
39export function isGuardInstruction(prompt: string): boolean {
40  return GUARD_OVERRIDE.test(prompt)
41}
42
43/** The kind the reply names; an unclear reply counts as coding, so the guard stays on when in doubt. */
44export function parseTaskKind(reply: string): TaskKind {
45  const match = /\b(coding|other)\b/i.exec(reply)
46  return match?.[1]?.toLowerCase() === 'other' ? 'other' : 'coding'
47}
48
src/tdd.ts 328 lines
1// Pure logic for the TDD guard: no `$`, so the tests can drive it directly.
2// Shapes follow probity's enforceTdd, trimHistory, applyEdit and toVerdict.
3import type { SessionMessage } from 'claude-code'
4import { DEFAULT_TDD_RULES, PROCESS_INSTRUCTIONS, RESPONSE_SPEC } from './prompt.ts'
5
6export const MAX_EVENTS = 10
7export const MAX_CONTENT_CHARS = 6000
8// A tool call's input (a Write carries the whole file) and a file shown to the judge.
9const MAX_INPUT_CHARS = 1500
10const MAX_FILE_CHARS = 20_000
11const CONTEXT_CHARS = 2000
12
13export type FileContent =
14  | { kind: 'present'; content: string }
15  | { kind: 'absent' }
16  | { kind: 'unknown' }
17
18export type HistoryEvent =
19  | { kind: 'prompt'; text: string }
20  | { kind: 'tool'; tool: string; input: unknown; output: string; isError?: true }
21
22/** The latest test command the agent ran, what it printed, and whether it failed. */
23export type TestRun = { command: string; output: string; red: boolean }
24
25// A command that runs tests: a runner's test subcommand, a test runner by name
26// (not a file named after one, like jest.config.js), or a Maven/Gradle build.
27const TEST_COMMAND = new RegExp(
28  [
29    String.raw`\b(?:npm|pnpm|yarn|bun|deno|go|cargo|dotnet|mix|swift|make|plugin)\s+(?:run\s+)?test\b`,
30    String.raw`\b(?:vitest|jest|pytest|mocha|rspec|phpunit|unittest)(?![\w./-])`,
31    String.raw`\b(?:mvnw?|gradlew?)\b.*\b(?:test|verify|install|check|build)\b`,
32  ].join('|'),
33)
34// What a failing run prints, also when a pipe (`| tail`) hid its exit code.
35const RED_OUTPUT =
36  /^Exit code [1-9]|\bFAIL|\b[1-9]\d* (?:fail|failed|failing|failures?|errors?)\b|\b(?:Failures|Errors): [1-9]|^# fail [1-9]|^not ok \d|\bAssertionError\b|\bpanicked\b/m
37
38export function lastTestRun(events: readonly HistoryEvent[]): TestRun | undefined {
39  for (let i = events.length - 1; i >= 0; i--) {
40    const event = events[i]
41    if (event?.kind !== 'tool' || event.tool !== 'Bash') continue
42    const command = (event.input as { command?: unknown } | null)?.command
43    if (typeof command !== 'string' || !TEST_COMMAND.test(command)) continue
44    return { command, output: event.output, red: event.isError === true || RED_OUTPUT.test(event.output) }
45  }
46  return undefined
47}
48
49/**
50 * What a verdict rests on besides the write: the last test run and the person's
51 * latest prompt. A retry of the same write with the same evidence gets the same
52 * verdict; a new test run or an override is new evidence.
53 */
54export function evidenceOf(events: readonly HistoryEvent[]): string {
55  const prompt = events.findLast(event => event.kind === 'prompt')
56  return JSON.stringify([lastTestRun(events) ?? null, prompt?.kind === 'prompt' ? prompt.text : null])
57}
58
59// A red that reached an assertion, not a compile or import error.
60const ASSERTION_FAILED = /\bAssertion(?:Failed)?Error\b|\bComparisonFailure\b|\bExpected:|\bexpected\b[^\n]*\b(?:received|but (?:was|got)|to (?:be|equal))\b|\bassert(?:ion)? failed\b/i
61
62/**
63 * What a blocked agent does next, from the last test run: one fixed line, so
64 * a block does not end in a retry of the same write.
65 */
66export function nextStep(run: TestRun | undefined): string {
67  const step = !run
68    ? 'Next: write a failing test for this change and run it, then make the smallest change that passes it.'
69    : !run.red
70      ? 'Next: write and run a failing test for the new behaviour first; a refactor under green must not change behaviour.'
71      : ASSERTION_FAILED.test(run.output)
72        ? 'Next: change only what the failing assertion needs, or run the test this change is for.'
73        : 'Next: write only a placeholder stub that lets the test compile or import, and rerun the tests to see its assertion fail.'
74  return `${step} The same write is blocked again until a new test run.`
75}
76
77/**
78 * `unanswered`: a violation only because the validator gave no answer, so it is no evidence to cache.
79 * `next`: what to do after a block, from the last test run.
80 */
81export type Verdict = { kind: 'pass' | 'violation'; reason: string; unanswered?: true; next?: string }
82
83// Test declarations per language, by extension. A regex stand-in for
84// probity's ast-grep matchers: the module has no Node to run ast-grep.
85// The `testPatterns` setting overrides or extends them per extension.
86export type TestPatterns = Readonly<Record<string, RegExp>>
87
88const JS_TEST = /\b(?:it|test)(?:\.(?:only|skip|todo|concurrent))?\s*\(\s*['"`]/g
89export const DEFAULT_TEST_PATTERNS: TestPatterns = {
90  ts: JS_TEST, tsx: JS_TEST, mts: JS_TEST, cts: JS_TEST,
91  js: JS_TEST, jsx: JS_TEST, mjs: JS_TEST, cjs: JS_TEST,
92  py: /^[ \t]*(?:async[ \t]+)?def[ \t]+test\w*[ \t]*\(/gm,
93  go: /^func[ \t]+Test\w*[ \t]*\(/gm,
94  java: /@Test\b/g, kt: /@Test\b/g, kts: /@Test\b/g,
95  rs: /#\[(?:tokio::)?test\]/g,
96  rb: /^[ \t]*(?:it[ \t]+['"]|def[ \t]+test_)/gm,
97  cs: /\[(?:Fact|Theory|Test|TestMethod)\b/g,
98}
99
100function countTests(pattern: RegExp, text: string): number {
101  return text.match(pattern)?.length ?? 0
102}
103
104/**
105 * The fast path: a write that adds exactly one test declaration is the red
106 * step itself and passes without a model call. Undefined content before the
107 * write, or a language without a pattern, never qualifies.
108 */
109export function addsExactlyOneTest(
110  path: string,
111  before: FileContent,
112  after: string,
113  patterns: TestPatterns = DEFAULT_TEST_PATTERNS,
114): boolean {
115  if (before.kind === 'unknown') return false
116  const pattern = patterns[path.slice(path.lastIndexOf('.') + 1).toLowerCase()]
117  if (pattern === undefined) return false
118  const beforeText = before.kind === 'present' ? before.content : ''
119  return countTests(pattern, after) - countTests(pattern, beforeText) === 1
120}
121
122/**
123 * The file as the Edit leaves it, or undefined when the edit cannot apply
124 * (the Edit tool itself then reports the miss).
125 */
126export function applyEdit(
127  current: string,
128  oldString: string,
129  newString: string,
130  replaceAll = false,
131): string | undefined {
132  const occurrences = current.split(oldString).length - 1
133  if (oldString === '' || occurrences === 0) return undefined
134  if (occurrences > 1 && !replaceAll) return undefined
135  // A replacer keeps $&, $$ and friends in newString literal.
136  const replacer = () => newString
137  return replaceAll
138    ? current.replaceAll(oldString, replacer)
139    : current.replace(oldString, replacer)
140}
141
142/** Prompts and answered tool calls, oldest first, as the validator reads them. */
143export function toHistory(messages: readonly SessionMessage[]): HistoryEvent[] {
144  const events: HistoryEvent[] = []
145  for (const message of messages) {
146    if (message.role === 'user' && message.text.trim() !== '') {
147      events.push({ kind: 'prompt', text: message.text })
148    }
149    for (const use of message.toolUses) {
150      if (use.text === undefined) continue
151      events.push({ kind: 'tool', tool: use.tool, input: use.input, output: use.text, ...(use.isError && { isError: true }) })
152    }
153  }
154  return events
155}
156
157export function trimHistory(
158  events: readonly HistoryEvent[],
159  maxEvents = MAX_EVENTS,
160  maxContentChars = MAX_CONTENT_CHARS,
161): HistoryEvent[] {
162  return events.slice(-maxEvents).map(event =>
163    event.kind === 'prompt'
164      ? { ...event, text: clip(event.text, maxContentChars) }
165      : { ...event, output: clip(event.output, maxContentChars) },
166  )
167}
168
169function clip(s: string, max: number): string {
170  if (s.length <= max) return s
171  const half = Math.floor(max / 2)
172  const omitted = s.length - 2 * half
173  return `${s.slice(0, half)}\n[${omitted} more characters truncated]\n${s.slice(s.length - half)}`
174}
175
176function formatEvent(event: HistoryEvent): string {
177  if (event.kind === 'prompt') return `User: ${event.text}`
178  const input = typeof event.input === 'string' ? event.input : JSON.stringify(event.input)
179  return `${event.tool}(${clip(input, MAX_INPUT_CHARS)}) → ${event.output}`
180}
181
182/**
183 * A file's before and after, cut for the judge: the changed region with some
184 * unchanged characters around it, each side at most MAX_FILE_CHARS. A file
185 * within the cap is left whole.
186 */
187function windowChange(before: FileContent, after: string): { before: FileContent; content: string } {
188  if (before.kind !== 'present') return { before, content: clip(after, MAX_FILE_CHARS) }
189  const old = before.content
190  if (old.length <= MAX_FILE_CHARS && after.length <= MAX_FILE_CHARS) return { before, content: after }
191  const shortest = Math.min(old.length, after.length)
192  let head = 0
193  while (head < shortest && old[head] === after[head]) head++
194  let tail = 0
195  while (tail < shortest - head && old[old.length - 1 - tail] === after[after.length - 1 - tail]) tail++
196  const skipHead = Math.max(0, head - CONTEXT_CHARS)
197  const skipTail = Math.max(0, tail - CONTEXT_CHARS)
198  const note = (n: number) => `[${n} unchanged characters omitted]`
199  const view = (text: string) =>
200    clip(
201      `${skipHead > 0 ? `${note(skipHead)}\n` : ''}${text.slice(skipHead, text.length - skipTail)}${skipTail > 0 ? `\n${note(skipTail)}` : ''}`,
202      MAX_FILE_CHARS,
203    )
204  return { before: { kind: 'present', content: view(old) }, content: view(after) }
205}
206
207function formatBefore(before: FileContent): string {
208  switch (before.kind) {
209    case 'present':
210      return before.content
211    case 'absent':
212      return '(file does not exist)'
213    case 'unknown':
214      return '(current file content unavailable)'
215  }
216}
217
218// Under green the judge denied an unused field's removal and a helper
219// extraction; say outright that such changes are the refactor step.
220const GREEN_REFACTOR =
221  'The tests are green, so this may be the refactor step. A change that keeps ' +
222  'behaviour passes without a new failing test: extracting a helper from code ' +
223  'that already exists, inlining, renaming, restructuring, or removing unused ' +
224  'code (a field, an import, a function nothing calls). Block it only when it ' +
225  'adds behaviour that no test drove.'
226
227// Left unsaid, the judge assumed a test it could not see and passed a stub
228// written before any test (/tdd-eval "stub before any test").
229const NO_TEST_RUN = '## Last test run\n\nNo test has run in this session yet, so no failure has been observed.'
230
231function formatTestRun(run: TestRun): string {
232  const result = run.red ? 'red: a test failed' : 'green: every test passed'
233  const output = `## Last test run\n\n\`${clip(run.command, MAX_INPUT_CHARS)}\` was ${result}. Its output:\n\n${clip(run.output, MAX_CONTENT_CHARS)}`
234  return run.red ? output : `${output}\n\n${GREEN_REFACTOR}`
235}
236
237/** The judge's prompt; `history` is the whole session, of which it shows the recent part and the last test run. */
238export function buildPrompt(
239  history: readonly HistoryEvent[],
240  before: FileContent,
241  action: { path: string; content: string },
242  also: readonly Change[] = [],
243): string {
244  const sections = [PROCESS_INSTRUCTIONS, DEFAULT_TDD_RULES]
245  const recent = trimHistory(history)
246  if (recent.length > 0) {
247    sections.push(`## Recent session\n\n${recent.map(formatEvent).join('\n')}`)
248  }
249  const run = lastTestRun(history)
250  sections.push(run ? formatTestRun(run) : NO_TEST_RUN)
251  const main = { ...action, ...windowChange(before, action.content) }
252  if (also.length === 0) {
253    sections.push(`## Current file content\n\n${formatBefore(main.before)}`)
254    sections.push(`## Pending action\n\nFile: ${main.path}\n\n${main.content}`)
255  } else {
256    const changes = [main, ...also.map(c => ({ ...c, ...windowChange(c.before, c.content) }))]
257    sections.push(`## Current file content\n\n${changes.map(c => `File: ${c.path}\n\n${formatBefore(c.before)}`).join('\n\n')}`)
258    sections.push(
259      `## Pending action\n\n${BATCH_NOTE}\n\n${changes.map(c => `File: ${c.path}\n\n${c.content}`).join('\n\n')}`,
260    )
261  }
262  sections.push(RESPONSE_SPEC)
263  return sections.join('\n\n')
264}
265
266/** One file a write of a batch changes: as it is, and as the batch leaves it. */
267export type Change = { path: string; before: FileContent; content: string }
268
269const BATCH_NOTE =
270  'These writes were sent together in one response and land together: judge them as one change, ' +
271  'on the files they leave together. The verdict applies to all of them.'
272
273/** Fail-closed: anything but a well-formed verdict is a violation. */
274export function parseVerdict(text: string): Verdict {
275  const parsed = safeParse(text.trim()) ?? safeParse(stripFence(text)) ?? findEmbeddedObject(text)
276  if (
277    typeof parsed === 'object' && parsed !== null &&
278    'kind' in parsed && (parsed.kind === 'pass' || parsed.kind === 'violation') &&
279    'reason' in parsed && typeof parsed.reason === 'string'
280  ) {
281    return { kind: parsed.kind, reason: parsed.reason }
282  }
283  return {
284    kind: 'violation',
285    reason: `could not parse verdict from validator output: ${text.slice(0, 500)}`,
286  }
287}
288
289function safeParse(text: string): unknown {
290  try {
291    return JSON.parse(text)
292  } catch {
293    return undefined
294  }
295}
296
297function stripFence(text: string): string {
298  return text.replace(/^\s*```(?:json)?\s*/, '').replace(/\s*```\s*$/, '').trim()
299}
300
301/** The last balanced `{...}` that parses: models sometimes reason before answering. */
302function findEmbeddedObject(text: string): unknown {
303  for (let start = text.lastIndexOf('{'); start >= 0; start = text.lastIndexOf('{', start - 1)) {
304    const span = scanBalanced(text, start)
305    const parsed = span === undefined ? undefined : safeParse(span)
306    if (parsed !== undefined) return parsed
307    if (start === 0) break
308  }
309  return undefined
310}
311
312function scanBalanced(text: string, start: number): string | undefined {
313  let depth = 0
314  let inString = false
315  let escape = false
316  for (let i = start; i < text.length; i++) {
317    const c = text[i]
318    if (escape) escape = false
319    else if (inString) {
320      if (c === '\\') escape = true
321      else if (c === '"') inString = false
322    } else if (c === '"') inString = true
323    else if (c === '{') depth++
324    else if (c === '}' && --depth === 0) return text.slice(start, i + 1)
325  }
326  return undefined
327}
328
src/prompt.ts 168 lines
1// The validator prompt is ported verbatim from probity's enforceTdd rule
2// (https://github.com/nizos/probity, src/rules/enforce-tdd.ts).
3// Copyright (c) Nizar Selander, MIT License.
4// Changed here: RESPONSE_SPEC asks for a reason on "pass" too, so every
5// verdict in the debug log says why; the inputs add "Last test run".
6
7export const PROCESS_INSTRUCTIONS = `## Role
8
9You are a TDD validator. Judge whether the pending write follows
10test-driven development.
11
12## Inputs
13
14You will see these inputs:
15
161. "Recent session" — a chronological log of the agent's recent prompts
17   and tool actions. Each entry shows what the agent did and what it
18   observed back. Use this to find evidence of a failing test that the
19   pending write would address.
202. "Current file content" — what's on disk right now at the file the
21   agent is about to write. May be a parenthesized marker (e.g.
22   \`(file does not exist)\`) when content cannot be shown.
233. "Pending action" — what the agent is about to write. Content may be
24   raw file text or a patch/diff in any common format.
254. "Last test run" — the latest test command the agent ran in this
26   session, whether it was red or green, and its output, even when it
27   is older than the recent session, or that no test has run yet.
28   A failure shown there is observed: production code that addresses
29   it is the green step.
30
31## What you judge
32
33Judge the change this write makes (the difference between the current
34file content and the pending action), not the resulting file as a
35whole.
36
37A transient file state is never itself a violation, however broken the
38file looks: an unresolved symbol, a dead or unused definition, a
39duplicated declaration, a reference to a removed name, a half-finished
40multi-step change. Whether the file is internally consistent or runs
41after the write is checked when the agent next runs the tests, not by
42you. This allowance is about structure; it does not excuse skipping a
43failing test or over-implementing, which the rules below still catch.
44
45A block or denial message recorded earlier in the session is a past
46verdict, not a rule. Re-derive your judgment from the rules below as
47if it had not been issued; never block only because a previous attempt
48was blocked.
49
50Your judgment is not the final word. When the user tells you in the
51session to let this change through, treat it as authoritative and pass,
52even on a change you would otherwise block.
53
54## Multi-step changes
55
56A phase may span multiple writes, each fine on its own. For example:
57
58  - Add an import in one write, then change the calling code in the
59    next.
60  - Move a function in two writes (remove from one location, add at
61    another).
62  - Add a function signature in one write, then its body in the next.
63  - Remove a function in one write, then its call sites in the next.`
64
65export const DEFAULT_TDD_RULES = `## TDD rules
66
67The TDD cycle is Red -> Green -> Refactor. Each phase has its own rules.
68
69### Across all phases
70
71Deleting code, tests, or helpers never requires a failing test to drive
72it, even when the removed code was used or test-covered.
73
74### Red phase: write a failing test first
75
76In red you add one test that drives new behavior and expect it to
77fail when the suite runs.
78
79A single write should add at most one new test. Compare current file
80content with pending action to count newly added tests; existing
81tests do not count. Restructuring existing tests is not "adding".
82
83  - Adding a test is the red step itself; it is allowed and does not
84    require observing it fail first, unless the prior green left a
85    refactor unmade (see "Enforcing the refactor phase").
86  - A test added to drive new behavior must be observed failing for
87    the right reason (an assertion, not a syntax or import error) in
88    a prior test run before production code may be written to satisfy
89    it.
90  - A test added to capture existing behavior is allowed to pass
91    immediately and must not be blocked for not failing first.
92    Examples: characterization tests pinning current implementation,
93    tests at a new layer (e.g. an e2e covering code already exercised
94    by units), pinning tests added before a refactor pulls a seam out
95    from under them.
96  - Test-file scaffolding edits (imports, helpers, fixtures) need no
97    failing test on their own.
98
99#### Reaching a clean red
100
101A test can fail before reaching an assertion (import unresolved,
102signature mismatch). The agent may resolve these without violating TDD:
103
104  - Import or symbol unresolved -> create a placeholder stub: a body
105    that makes the symbol exist but does not implement the behavior the
106    test asserts. Returning a literal that contradicts the assertion
107    (e.g. \`=> 0\` when the test expects \`1\`) or throwing
108    \`not implemented\` are both valid stubs; they exist solely to
109    surface a real assertion failure on the next test run.
110  - Signature mismatch -> adjust signature; keep the body as a
111    placeholder stub per the rule above.
112  - Assertion failure -> implement minimal logic to pass.
113
114A stub-resolution step must not implement the test's asserted behavior.
115Returning a literal that the assertion will reject IS a stub.
116
117### Green phase: minimum to pass
118
119The implementation must not exceed the minimum needed to make the
120observed failing test pass. Functions, classes, or branches not
121required by the currently failing test are over-implementation. An
122import or other scaffolding awaiting a later write in the same change
123is a transient state, not over-implementation.
124
125### Refactor phase: improve structure under green
126
127Refactoring does not require a failing test to drive it. Production
128and test edits that preserve observable behavior are allowed when
129the relevant tests were passing before the refactor began. Examples:
130
131  - Extracting helpers whose behavior already lives elsewhere (covered
132    by existing tests). Extracting a helper whose behavior appears
133    nowhere else is net new and requires a failing test first.
134  - Lifting test setup (fixtures, builders, factories) into a
135    dedicated or reusable helper. The helper is exercised by the tests
136    that call it; no separate test for the helper is required.
137  - Adding type declarations, interfaces, or constant literals
138    (no runtime behavior by construction).
139  - Renaming, restructuring control flow, removing dead code.
140  - Reorganizing or deleting redundant tests, or splitting/combining
141    existing tests. The one-new-test rule is about intent to add
142    behavior, not surface diff count.
143
144#### Enforcing the refactor phase
145
146Writing the next test crosses the green->red boundary, so judge a new
147red here too, not only production writes. Refactor is part of the cycle:
148when the prior green left one that is unmistakable and clearly without
149downside, block and name it. The bar is high because forcing a refactor
150risks needless abstraction, indirection, or breaking conventions the
151agent can see and you cannot, so when the win is not clear-cut, let green
152stand.
153
154## Validator behavior
155
156### Block messages
157
158Name the violation and say why it breaks TDD. Do not dictate edit
159order, require the file to be complete or runnable, or demand other
160steps be bundled into this write.`
161
162export const RESPONSE_SPEC = `## Response format
163
164Respond with a single JSON object of exactly this shape:
165{"kind":"pass"|"violation","reason":"<short explanation>"}
166Always give a one-sentence reason, on "pass" too: which TDD step this write is and why it is allowed.
167Return JSON only. No prose, no code fences.`
168