The Engineering Harness
Compiling engineering doctrine from a disciplined agent-written codebase — dependency-contract boundaries, generation counters, graceful degradation, and a testable pure core, as enforceable harness rules.
The instruction file tells the agent how to behave — workflow, git etiquette, when to ask. Almost none of them tell the agent what code to write. The result is agents that follow process impeccably while making architectural decisions by vibes: a new HTTP client here, an async runtime there, error handling that panics in one module and swallows in the next. The engineering harness is the missing payload: a compact, enforceable doctrine of code-level decisions, compiled into the same instruction file the workflow rules live in.
This chapter derives one from a real specimen — not a style guide written from first principles, but doctrine extracted by auditing an unusually disciplined agent-written codebase and asking, for each pattern: what rule, stated in advance, would reproduce this?
The Specimen
The codebase is lgtm, an open-source native code-review app in Rust (~10,200 lines, GPUI). Its README states: “This is 100% vibe coded. I have not read the code.” That claim is what makes it useful evidence. An audit finds not slop but consistent, layered discipline — the same eight decisions applied everywhere, including places no human reviewed. Whatever harness produced it, the doctrine below is what its output implies.
The audit matters for a second reason: doctrine compiled from good output closes a loop. You audit what the agent built, extract the patterns worth keeping as rules, and feed them back as harness text. The next session starts where the best previous session ended. This is the code-level analog of the memory chapter’s compaction-resident state — except what persists is judgment, not context.
The Doctrine
Eight rules. Each is stated as the imperative you would put in the harness, followed by why it earns its tokens.
1. Boundaries are dependency contracts
Split modules by what they are allowed to depend on, not by size. State the contract in the module’s first line.
The specimen is a six-crate workspace where each crate’s opening doc-comment declares its boundary: the diff engine is “UI-free”; the syntax crate has “no gpui dependencies — mapping tokens to colors is the app’s job.” The compiler then enforces what the comment promises — a dependency that violates the contract fails to build. For an agent, this is the cheapest architecture guard that exists: the rule is checkable by grep over manifest files, and the agent can verify its own compliance without judgment.
2. Integrate through credentials the user already has
Prefer the thinnest integration that inherits existing auth. Wrap the CLI the user has already logged into before reaching for an SDK, an HTTP client, or an OAuth flow.
The specimen talks to GitHub by shelling out to gh, to git via git, and to Claude via the claude CLI — zero auth code, zero token storage, zero credential lifecycle surface. Every wrapper is the same ten-line shape: run the subprocess, and on failure return an error carrying the subprocess’s stderr. Agents default to importing clients because training data does; this rule inverts the default and deletes an entire class of security review.
3. Make illegal states unrepresentable
Model state machines as sum types with payloads. If two fields can contradict each other, merge them into one enum.
Loading / Ready(data) / Failed(message) instead of three booleans and an optional. The specimen applies this to every piece of UI state — palette steps, fetch lifecycles, streaming events — and pairs it with an intermediate representation: semantic model in, flat display list out, one renderer. The rule survives translation to any typed language, and it is the single highest-leverage reviewer shortcut: a reviewer who sees a bool is_loaded next to an Option<Data> knows the doctrine was not applied.
4. Solve async races with generation counters and stable ids
Every spawn that can be invalidated captures a generation number; results that return with a stale generation are dropped. Background results re-find their target by stable id, never by index.
The specimen has four independent generation counters (refresh, palette, composer, review dialog) and zero locks, zero cancellation tokens, zero async frameworks. Bump the counter on every state transition; compare on landing. Items carry an id: u64, and every callback re-finds items.find(|i| i.id == id) so a closed tab cannot receive a stale result. This is the entire race-condition doctrine in two sentences, and it is mechanical enough for an agent to apply without design taste. A companion rule for streams: batch high-frequency events into throttled UI updates — the specimen drains streaming tokens every 50ms into one update, “never one update per token.”
5. Degrade, don’t fail — and name every cap
Option/null means “degrade gracefully”; errors are reserved for failures the user must see. Every unbounded input gets a named constant cap with a comment stating the rationale. Never truncate silently.
In the specimen, a file that is binary, oversized, or 404 simply keeps its lower-fidelity view — Ok(None), not an error. A refresh failure keeps stale-but-useful data and shows a note. And every place unbounded input enters the system has a named guardrail: max line tokens, max blob bytes, max files upgraded per batch, each with a one-line why (“if more than this fraction of a line changed, highlighting it all is noise”). Agents are systematically bad at inventing caps unprompted — this rule makes the cap a required artifact of the code shape, so its absence is visible in review.
6. Extract the pure core; label what you verified by hand
Anything with logic becomes a free function over plain data, and gets a test. What genuinely cannot be unit-tested is marked “verified manually” in a doc comment — never silently untested.
Roughly a fifth of the specimen’s app code is tests, achievable only because selection math, tree building, span merging, and layout precomputation are all pure functions extracted for testability. The mouse-coordinate arithmetic that can’t be unit-tested says so, in the doc comment. Two test idioms are worth mandating by name: pinned-value tests (assert the exact hash/format that on-disk compatibility depends on, with a comment saying what breaking it silently costs) and real-fixture tests (deserialize captured production payloads, including the fields you ignore). This is the dev-lifecycle Verify phase pushed down into code shape.
7. Comments record constraints, not narration
A comment must state something the code cannot: an invariant, a cross-system requirement, a rejected alternative, a lifecycle rule. Delete any comment that narrates the next line.
The specimen’s comments are almost exclusively load-bearing: “w_full is load-bearing: without a definite row width the flex halves collapse”; “-F, not -f: line must be a JSON integer”; struct fields document what survives a refresh versus a view toggle. For agent-written code this rule does double duty — constraint comments are exactly the context a future agent session needs to avoid re-breaking what the comment guards, making them harness memory embedded in the artifact itself.
8. Hand-roll what fits in twenty lines
Before adding a dependency, estimate the hand-rolled size. Under ~20 lines with a test, write it; state the budget so the agent doesn’t relitigate it per call site.
The specimen parses ISO-8601, percent-encodes URLs, soft-wraps text, and computes date ages by hand — and its non-GUI dependency list is five small crates. Agents reach for dependencies because the training distribution does; an explicit budget flips the default and shrinks the supply-chain and audit surface. The rule needs its escape hatch stated too: cryptography, parsing untrusted formats, and anything correctness-critical stays on maintained libraries.
Enforcement Mapping
Doctrine stated only as prose is a guideline — probabilistic, as the enforcement chapter frames it. Most of these rules can be pushed at least one tier right:
| Rule | Guideline (instruction file) | Rule (hook / lint) | Gate (CI) |
|---|---|---|---|
| Dependency-contract boundaries | Contract stated in module header | Import-linter / cargo deny on manifest edits | Dependency-graph check blocks merge |
| Subprocess-first integration | Stated with the auth rationale | PreToolUse hook flags new HTTP/SDK deps | Dependency review on lockfile diffs |
| Illegal states unrepresentable | Stated with the enum-vs-booleans example | Lint for adjacent bool + Option state | — |
| Generation counters | Stated as the required spawn shape | — | Race-focused review checklist on async diffs |
| Named caps, no silent truncation | Stated as a required artifact | Grep-able MAX_ constant convention | — |
| Pure-core testing | Stated with the “verified manually” escape | PostToolUse hook runs scoped tests | Coverage floor on non-UI modules |
| Constraint-only comments | Stated with delete examples | — | — |
| Dependency budget | Stated with the 20-line threshold | Lockfile-diff hook posts a justification prompt | Dependency review requires rationale |
The pattern from the enforcement chapter holds: guidelines cover most of it, and the two rules that most often fail silently — new dependencies and missing caps — are the ones worth deterministic checks.
The Drop-In Block
The compiled artifact, sized for an instruction file. It deliberately keeps the why clauses: rationale is what lets a model generalize a rule to a case the rule didn’t anticipate, and it costs ~200 tokens.
## Engineering doctrine
- Boundaries: split modules by what they may depend on; state the contract
in the module's first line. The build must enforce what the comment says.
- Integration: wrap the CLI the user is already authenticated to before
adding an SDK/HTTP client. Subprocess errors carry the child's stderr.
- State: model lifecycles as enums with payloads (Loading/Ready/Failed).
Two fields that can contradict each other become one sum type.
- Async: every invalidatable spawn captures a generation counter; stale
results are dropped on landing. Find targets by stable id, never index.
Batch streaming events into throttled updates (~50ms), never per-token.
- Degradation: Option/null = degrade gracefully; Err = the user must see it.
Every unbounded input gets a named MAX_* cap + one-line rationale.
Never truncate silently — log what was dropped.
- Tests: extract logic into pure functions over plain data and test those.
Pin exact values that on-disk/wire compatibility depends on. Mark what
is only manually verified as such in a doc comment.
- Comments: constraints, invariants, and cross-system requirements only.
Never narrate the next line. Document field lifecycles (what survives
refresh vs toggle vs restart).
- Dependencies: hand-roll anything under ~20 lines + a test. Exceptions:
crypto, untrusted-format parsing, correctness-critical code.
Why This Works
Three properties make a doctrine like this survive contact with a real agent session.
Every rule is checkable without taste. “Write clean code” is not enforceable; “results returning with a stale generation are dropped” is visible in a diff. The rules were selected from the audit precisely because their presence or absence is mechanical to detect — which is also what makes the anti-patterns chapter’s failure modes detectable: most of them are one of these rules, negated.
The rationale rides along. A rule stated with its why compresses better under summarization than a bare imperative, and a model that has lost the exact wording can re-derive the behavior from the reason. This mirrors the instruction-file principle that constraints should explain themselves.
It was compiled from output, not aspiration. A style guide written from first principles encodes what its author believes; a harness compiled from an audited codebase encodes what demonstrably shipped. The compile loop — build, audit, extract, feed back — is repeatable on your own repositories, and the second iteration is cheaper than the first: the agent doing the audit is following the previous doctrine while extracting the next one.