# Level 4: You Write the Specs

URL: https://developertoolkit.ai/en/ladder/level-4-write-specs/
Description: Level 4 of the autonomy ladder: specifications, pre-written test oracles, deterministic Stop hooks, and verifying multi-hour unattended runs.

Level 4 of the autonomy ladder is the stage where a developer authors the specification, a protected test oracle, and a machine-checkable stop condition, allowing an agent to run unattended for hours while the human judges the result on evidence rather than reading every diff. Level 4 holds only while the run cannot edit the checks defining done.

You launch a large migration at six in the evening. At eight the next morning, the agent reports "all tests pass"—and one of those green tests is the assertion it loosened at three in the morning. This guide gives developers moving past [Level 3](/en/ladder/level-3-review-diffs/) the four pre-run artifacts and hook invariants that prevent that failure, and gives tech leads and CTOs the exact four metrics that prove Level 4 is real.

## Are you at Level 4? The four-point test

Dan Shapiro (*The Five Levels*, 23 January 2026) sums up Level 4 plainly: write a spec, *"leave for 12 hours, and check to see if the tests pass."* A loop operates at Level 4 when all four conditions hold:

1. **You author specs and finish lines rather than implementation code.** Your primary output is clear intent and acceptance criteria.
2. **Runs outlast live supervision.** The agent iterates across turns without interactive babysitting.
3. **Deterministic checks decide completion.** Tests, type checks, linters, and domain validators—never the agent's prose summary—prove done.
4. **The oracle is outside the agent's write reach.** Test suites, CI workflows, and hook scripts cannot be weakened silently by the same run.

If item 4 fails, the agent grades its own homework—leaving you at Level 3 with the reviewer removed.

## Four artifacts required before starting a Level 4 run

Write these four artifacts in strict sequence before letting an agent run unattended:

1. **Authoritative spec (`spec.md`).** States target behavior, constraints, non-goals, and edge cases in one file the run reads ([spec-driven development](/en/workflows/plan/spec-driven-development/), [acceptance criteria](/en/workflows/plan/acceptance-criteria/)).
2. **Reviewed plan.** Drafted by the agent in read-only plan mode and verified by you upfront. Catching a flawed design on a one-page plan saves hours of compute and review.
3. **Independent oracle.** Failing acceptance tests, contract checks, and static rules written or reviewed **before** implementation. At Level 4, [test-driven development](/en/method/principles/test-driven-development/) is about provenance: a test written before the run cannot be engineered after the fact to fit buggy code ([oracle strength](/en/workflows/test/oracle-strength/)).
4. **Bounded stop condition.** Explicit shell commands that must exit 0, forbidden paths, a structured checkpoint log, and a hard retry or turn cap. Stripe's production Minions enforce a strict ceiling of **at most two rounds of CI** before escalating back to a human (Stripe engineering blog, 9 February 2026).

**Copy-paste prompt: draft and red-team a stop condition**

```text
Read spec.md and our approved plan. Draft a bounded stop condition with five parts:
1. Objective: one sentence naming the single finish line.
2. Reference files: exact files defining correct behavior and one existing pattern to mirror.
3. Done when: exact commands that must exit 0 (tests, typecheck, lint, migration check),
   with real command output required in the final report.
4. Protected paths (never touch): test files forming the oracle, CI configs, hooks, and lint rules.
5. Budget: one checkpoint line per round plus a hard turn/retry limit to stop and report blockers.

Now attack your own draft: list every loophole an agent could exploit (weakening assertions,
skipping tests, claiming success without execution), patch each loophole, and output only the hardened version.
```

## Deterministic Stop hooks and tool-level loop controls

A model evaluating its own finish line can mistake a plausible narrative for a passing suite. Deterministic lifecycle hooks close that gap by executing real shell checks whenever the agent attempts to stop:

| Tool | Goal & loop control | Deterministic guardrail | Official docs |
| --- | --- | --- | --- |
| **Claude Code** | Goal-directed runs & headless mode | Lifecycle hooks (`PreToolUse`, `PostToolUse`, `Stop`, plus org-enforced managed hooks). Check `stop_hook_active` inside `Stop` hooks to prevent infinite continuation loops, and block test-path edits with `PreToolUse` | [Claude Code docs](https://code.claude.com/docs) |
| **Codex** | Goal-directed runs, worktrees, and cloud environments | Separate `sandbox_mode` (`workspace-write` / `read-only`) from `approval_policy` (`on-request`, `never`, `granular`; note legacy `untrusted` was retired) alongside `Stop` hooks and admin `requirements.toml` | [OpenAI Codex docs](https://developers.openai.com/codex) |
| **Cursor** | Plan Mode, Cloud/Background Agents, and automations | Hooks observing or blocking agent stages, `.cursor/rules/*.mdc`, plus Bugbot with `.cursor/BUGBOT.md` on the pull request | [Cursor docs](https://cursor.com/docs) |

Keep the core Stop-hook invariant identical across tools:

1. Record the starting commit SHA before launching the long run.
2. When the agent tries to finish, check the recursion guard (e.g., `stop_hook_active` in Claude Code) and a retry counter so the loop always terminates cleanly on hard blockers.
3. Fail closed if `git diff` against the starting commit touched any protected test, snapshot, hook, or CI path.
4. Execute the repository's unified test, typecheck, and lint command directly and return failing stderr to the agent only when exit status is non-zero.

Because repository-local hook configs can still be modified by a compromised or misconfigured session, always duplicate oracle-integrity and test checks in CI outside the agent's write scope ([agent hooks](/en/workflows/harness/agent-hooks/), [protecting the oracle](/en/workflows/test/protect-the-oracle/)).

## The morning verification protocol

Never review a twelve-hour run by scrolling through 2,000 lines of diff. Verify six artifacts in order:

1. **Re-run the oracle independently** in CI or locally—never trust the agent's transcript alone.
2. **Confirm oracle integrity:** verify zero unapproved changes to tests, snapshots, fixtures, hooks, or CI workflows since the run's base commit.
3. **Compare the spec delta** against `spec.md` to confirm every acceptance criterion maps to an executed test and no unrequested behavior crept in.
4. **Inspect turning points in the run log.** Long autonomous trajectories decay structurally: SlopCodeBench (Orlanski et al., arXiv, 25 March 2026) evaluated 15 agents across 196 checkpoints and found no agent solved any problem end to end, with the best passing 14.8% amid compounding structural erosion. Repeated failed retries signal a broken design that needs splitting.
5. **Read source code strictly for escalation classes** (auth, billing, schemas, data migrations, and uncovered paths) as defined in [reading evidence instead of code](/en/ladder/evidence-not-diffs/).
6. **Sign off on the [evidence bundle](/en/workflows/ship/evidence-bundle/) or return with a tighter spec.**

## Four metrics leaders track at Level 4

Run `npx @wondelai/harness-audit` ([Harness Audit](/en/harness-audit/)) to verify repository station readiness, and track four operational metrics per change class:

| Metric | Definition | Warning signal |
| --- | --- | --- |
| **Run acceptance rate** | Unattended runs merging without rework divided by total runs started | Drops as run duration grows |
| **Oracle-edit rate** | Runs whose diff modified tests, CI, or hooks without explicit spec approval | **Any non-zero trend**—demote immediately |
| **Escaped defects per class** | Production bugs traced to evidence-approved merges | Sends that class back to Level 3 |
| **Budget overrun rate** | Runs hitting turn or retry limits before satisfying the stop condition | Vague specs or unreachable stop conditions |

## Six ways an unattended Level 4 run fails while reporting green

- **Silent oracle edits.** Tests pass because assertions were weakened. Recovery: revert test edits, enforce `CODEOWNERS` and `PreToolUse`/CI path blocks on test and CI directories.
- **Unexecuted claims.** The agent summarizes passing checks without running the final command. Recovery: require deterministic `Stop` hooks and mandatory CI runs before review.
- **Thrashing and architectural drift.** The run log repeats the same failed patch three ways. Recovery: reset to the last clean checkpoint, narrow the spec, and provide one concrete existing module as a reference pattern.
- **Unbounded loops burning budget.** A vague stop condition exhausts turns. Recovery: prove the check passes on a minimal manual baseline first and enforce strict turn/CI round bounds.
- **Hooks silently bypassed.** Unverified folders or disabled hook configs skip local gates. Recovery: treat local hooks as fast feedback and CI workflows pinned to the default branch as the authoritative gate.
- **Green checks with broken user behavior.** The oracle is too weak for that risk class. Recovery: add a failing regression test, strengthen mutation/behavior coverage, and return the class to code review until the upgraded checks catch real faults.

## When a change class is ready for Level 5

A class earns promotion toward [Level 5](/en/ladder/level-5-run-the-factory/) only when unattended runs sustain high acceptance rates, oracle-edit rate sits at zero, escaped defects stay flat, and every finished run feeds lessons back into rules, skills, or fitness functions. Intent, taste, and escalation paths always remain [the human's job](/en/ladder/the-humans-job/).

## Next steps

- [Level 5: You Run the Software Factory](/en/ladder/level-5-run-the-factory/) — Six stations and the autonomy ledger for queued, unattended loops
- [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Lock tests, CI workflows, and holdout checks outside agent reach
- [Agent hooks across tools](/en/workflows/harness/agent-hooks/) — Deterministic PreToolUse, PostToolUse, and Stop guardrails
- [Spec-driven development](/en/workflows/plan/spec-driven-development/) — Keep one authoritative spec as the primary unit of human review
