article · agentic engineering
Pedro's Law: Specifications First, Code Second
Use as many rich, iterative prompts as you need to create the specifications.
Then with ONE prompt: generate the code and associated unit tests.
Introduction
When code is cheap to generate, the specification becomes the scarce artifact. Pedro's Law is the specification-first discipline for engineers who work on the loop, not in it. Working on the loop is not simply using an AI coding assistant more often. It is a different way of organizing engineering work.
Yes, I named it after myself, so that nobody else gets the blame.
On the loop, agents perform complex, multi-step workflows. They inspect repositories, consult tools, create implementation plans, write code, generate tests, run verification, review changes, and iterate within defined quality gates. Humans decide what work to initiate, define the intended outcome, approve important boundaries, and remain accountable for the result.
The central shift is:
Engineers spend less time directing individual code changes and more time designing the specifications, constraints, evaluation mechanisms, and agent workflows that produce reliable code.
Put shortly: engineers move from in the loop to on the loop.
How far they can move is not set by the model. Agents already generate more code than any team can check. What sets the limit is how much of that code the repository and the runtime can verify without a person: autonomy is bounded by verification capacity, not by generation capacity. Everything in this law raises that capacity.
In the loop, a person approves each change before it merges. On the loop, the agent runs the full workflow end to end, and people supervise the system that approves the changes: they own the specification, the checks, and the gates, and they step in where the risk is high. Out of the loop, nobody reads the code. This law is about working on the loop.
In, on, or out of the loop
There is no industry-standard ladder for how much of the work an agent does, and the published ones number their levels differently. DORA, the closest thing the industry has to a shared reference for delivery performance, defines capabilities that make AI pay off, and calls AI an amplifier, but defines no levels. So I do not describe the destination with a number. I describe it by where the people are.
- In the loop: a person approves each change before it merges. Every pull request is read.
- On the loop: people own the specification, the checks, and the gates, supervise the stream of changes, and step in where the risk is high. Most changes merge on evidence.
- Out of the loop: no person reads the code. Some call it the dark factory.
If you think in one of the published ladders, this is where "on the loop" sits:
| Ladder | Its levels | Where "on the loop" sits |
|---|---|---|
| Dan Shapiro, The Five Levels | 0 to 5, modelled on driving automation; Level 5 is the "dark factory" | Level 4: you write and argue the specification, and review plans and test results, not code. His Level 3, where you review every diff, is still in the loop. |
| Agentic Engineering Framework | L1 Assisted, L2 Supervised, L3 Autonomous, L4 Autonomous Software Engineering | Between its L3, where a human reviews every pull request, and its L4, where nobody does. Risk tiers decide which changes a person reviews. |
| Addy Osmani, Agentic Autonomy Levels | 0 to 5, on two axes: agency and orchestration | Varies by task, which is how risk tiers work here. |
| Steve Yegge, Welcome to Gas Town | 8 stages; the first four in the IDE, the last four with agents | Around stages 5 and 6. |
| Thoughtworks Technology Radar | No levels. Harnesses, feedforward and feedback controls, and "human on the loop" | The same term, used the same way. |
| DORA AI Capabilities Model | No levels. Seven capabilities that amplify AI's effect | The capabilities are preconditions, not a level. |
The numbers disagree from one ladder to the next. Who is in the loop does not.
The law
Teams MUST create durable specifications. Teams MAY use rich, iterative prompting to create them. The depth of the specification MUST be proportional to the risk and complexity of the change. The risk tiers below set the minimum specification for each change.
Teams MUST refine specifications in thin vertical slices instead of designing the whole system upfront.
After a human approves a slice, that human gives the implementation agent one implementation prompt. The agent then plans the change and generates the code and associated unit tests. The agent MUST run the quality gates, the approved checks that include the oracle (the human-approved acceptance tests and fitness functions, which are automated architecture checks). The agent MAY iterate autonomously until the checks pass.
The rule is not a count of messages. The implementation prompt and its autonomous loop MUST NOT introduce new requirements or design decisions. If a new requirement or design decision is needed, the agent MUST stop and escalate it for specification work.
Corrective prompts are not forbidden. Each human prompt after the implementation prompt shows that the specification or the repository context failed. Teams count these prompts and fix the specification.
Risk tiers
Each slice MUST meet the minimum specification for its risk tier. If a change matches more than one tier, use the highest tier. Teams MAY adapt these tiers, but they MUST record their tiers in repository guidance.
Low
Typical changes: internal refactoring, copy changes, or an isolated bug fix with no contract, data, or security impact.
Minimum specification:
- Behavior, scope, and non-scope
- Boundaries that the change touches
- Acceptance tests
Medium
Typical changes: a new feature or endpoint in one service, a change to an internal contract, or a new dependency.
Minimum specification: everything in Low, plus:
- Interface or API contract
- Error and edge cases
- Fitness checks
- An ADR for each architecture decision
High
Typical changes: public contracts, data schemas, security controls, sensitive data, infrastructure, cross-service or cross-team changes, or significant cost or capacity changes.
Minimum specification: everything in Medium, plus:
- Architecture and ADRs
- Security, privacy, and compliance requirements
- Observability requirements
- Deployment, rollback, and recovery
- A named human approver
What belongs in the specification
Depending on risk, specifications MAY include:
- Functional and non-functional requirements
- Scope and non-scope
- Logical and physical architecture
- System, service, data, and team boundaries
- Architecture Decision Records
- Security, privacy, and compliance requirements
- Observability and operational expectations
- Deployment, rollback, and recovery expectations
- Milestones and implementation sequencing
- Acceptance, end-to-end, contract, and fitness tests
- Failure scenarios and measurable quality thresholds
Prompts are valuable for exploring the problem, researching the repository, comparing architecture options, challenging assumptions, generating diagrams, drafting ADRs, defining tests, identifying risks, and finding contradictions.
Teams MUST move the resulting decisions into durable artifacts, for example:
- Requirements, diagrams, and ADRs
- Repository guidance and security policies
- Test specifications, acceptance criteria, and fitness functions
- Configuration, runbooks, evaluation datasets, and review checklists
If a prompt contains a decision that matters after the current session, move that decision into a durable specification or executable check.
Prompt-local knowledge
Teams sometimes use many prompts to generate or change code directly. Important knowledge can then stay only in these places:
- Conversation context or an agent session
- Tool output or an agent transcript
- Uncommitted changes or generated code
- Review comments
Knowledge in these places is prompt-local knowledge: knowledge that influenced the implementation but cannot reliably be recovered, evaluated, or reused.
For example, an early prompt can establish that a service must use a repository abstraction rather than call a database directly. A later prompt can bypass that boundary to fix a failing test. If the original decision existed only in the conversation, the architectural knowledge can be lost or contradicted.
Ask:
If this prompt disappears, where is the knowledge it introduced?
If the answer is nowhere durable, the team has not finished engineering the decision. Prompts are useful for thinking, but they are not a sufficient system of record.
The controlled implementation loop
The implementation agent receives the approved specification, repository context, and read-only quality gates. It then:
- Reads the approved specification.
- Inspects the repository and relevant systems.
- Produces an implementation plan.
- Generates the code and associated unit tests.
- Runs the required checks.
- Compares the result with the approved acceptance criteria.
- Corrects implementation defects within the approved design.
- Repeats until the quality gates pass.
- Opens a change for human review.
The human gives one implementation prompt. The agent MAY perform multiple autonomous iterations inside that prompt. Those iterations are not new design conversations.
Read-only specifications and escalation
The implementation agent MUST NOT modify the approved requirements, acceptance tests, fitness functions, security boundaries, or architectural decisions in order to make the implementation pass.
Teams MUST enforce read-only status with mechanisms, not only with prompt instructions. Teams SHOULD use an appropriate combination of:
- Protected paths and CODEOWNERS (the file that names who must approve changes to a path) for specifications and oracle files
- CI checks that fail when an implementation change modifies protected specification or oracle files
- Agent sandbox permissions that remove write access to those paths
- Separate repositories or branches for approved specifications where appropriate
- Human approval gates for changes to requirements, acceptance tests, fitness functions, or ADRs
If the agent suspects that the specification is contradictory, incomplete, impossible, or unsafe, it MUST stop and escalate.
The escalation MUST use one format, which the team records in its repository guidance. At minimum, the agent MUST:
- Stop work on the change and not request a merge.
- Open a draft pull request, or add a comment to the linked ticket, with the label
spec-question. - Notify the specification owner.
- Include the specification ID and version.
- Quote the conflicting, missing, or unsafe clauses.
- Attach the evidence, such as a failing check, test output, or a repository constraint.
- List the options that the agent found and the effect of each option.
- State whether the agent considers the issue an implementation failure or a specification failure.
The agent's classification is a proposal only. A human MUST classify the issue and either:
- Confirm that the specification is correct and direct the agent to fix the implementation, or
- Revise and version the specification, then restart or regenerate the change.
The agent MUST NOT weaken a test, bypass a boundary, or silently reinterpret a requirement.
Implementation failure versus specification failure
Implementation failure
The specification is correct, but the generated implementation does not satisfy it. Examples include incorrect control flow, missing error handling, a bug exposed by a test, violation of a repository pattern, or failure to meet a defined threshold. The agent MUST correct the implementation within the approved specification.
Specification failure
The implementation exposes a problem in the requirements or design. Examples include contradictory requirements, an architecture that cannot support the required scale, ambiguous acceptance criteria, an omitted security boundary, or an impossible operational expectation. The agent MUST stop and escalate. The team MUST revise and version the specification before regenerating the change.
Regenerable implementation
Generated implementation is regenerable, not immutable. The code is disposable output of a versioned specification and a controlled generation process.
For an unmerged change, regeneration MUST follow this process:
- Identify the specification version and repository baseline.
- Record any human review edits that are not already represented in the specification.
- Discard the branch or change set for the affected slice.
- Update and approve the revised specification, if required.
- Regenerate the change set from the approved specification version.
- Re-run the quality gates and review the resulting diff.
Before regeneration, the team MUST add each human review edit to the specification, or record it as an approved manual change. Regeneration does not replace an approved manual change.
The scope of regeneration SHOULD be the affected change set or thin vertical slice, not the entire product or repository. If other changes have merged on top, the team MUST rebase or recreate the branch from the new baseline and regenerate only the impacted slice.
If the original change is already merged into main, regeneration does not rewrite history. It creates a new change set on top of the existing code, linked to the revised specification version and the earlier change.
The regenerated output does not need to be identical. Regeneration success means that the new change passes the same approved quality gates and remains traceable to the specification. It does not mean that the generated code is textually identical.
Testing: the oracle is not the generated unit test
The human-approved acceptance tests and fitness functions are the oracle. Generated unit tests support the implementation and provide regression protection, but passing generated unit tests is not evidence that the feature satisfies the acceptance criteria.
Generated unit tests MUST NOT contradict the approved acceptance tests or fitness functions. The team MUST evaluate the implementation against the approved behavioral oracle separately.
This is compatible with test-first engineering when the team defines acceptance and fitness tests before implementation. The agent MAY generate unit tests after or alongside the code, but it MUST NOT change the oracle merely because the generated implementation fails it.
Worked example: a fully specified slice
Approved specification
- ID and version
orders-api/list-open-orders@v5- Risk tier
- High. The endpoint enforces authentication and returns a customer's order data.
- Goal
- Add a read-only endpoint that returns the authenticated customer's open orders.
- Path
GET /v1/customers/me/orders- Authentication
- A valid customer identity is required. Missing or invalid authentication returns 401 using the service's standard error schema:
{ "code": "UNAUTHENTICATED", "message": "..." }. - Open definition
- An order is open when
status = OPEN. Orders with any other status are excluded. - Ownership
- The service derives the customer ID from the authenticated identity. There is no customer ID in the path, so another customer's orders cannot be requested through this endpoint.
- No orders
- Return 200 with an empty
itemsarray. - Response
- Return 200 with
{ "items": [{ "id": "...", "name": "...", "status": "OPEN" }], "nextCursor": null }. - Order
- Sort results in ascending order by
id. This order is stable across pages. - Pagination
- Accept optional
limitandcursorquery parameters. Use the service's documented pagination defaults and cursor conventions. On the last page,nextCursoris null. Return 400 using the standard error schema for invalid pagination parameters. - Boundary
- The API MUST use the existing
OrderRepository. It MUST NOT access the database directly or introduce a new database dependency in the API layer. SeeADR-20261009T1530Z-order-repository-boundary. - Security and privacy
- Order data is personal data. The response contains only the authenticated customer's orders. Logs MUST NOT contain order contents or customer identifiers.
- Observability
- Emit request count, error rate, and p95 latency for the endpoint. Alert when the 5xx rate exceeds 1% for 5 minutes.
- Deployment and rollback
- Release behind a feature flag. To roll back, turn the flag off. The endpoint is read-only, so rollback needs no data migration.
- Approver
- The service owner, named in the specification.
Acceptance tests
- An authenticated customer receives only that customer's open orders.
- Orders that are not open are excluded.
- No orders returns 200 with
items: []. - Missing or invalid authentication returns 401 with the standard error shape.
- Valid pagination returns the next page in ascending
idorder, with anextCursorthat follows the service's documented cursor conventions. - The last page returns
nextCursor: null. - Invalid pagination returns 400 with the standard error shape.
Fitness checks
- The endpoint has no direct database import or database client construction.
- The endpoint uses
OrderRepository. - Protected specification and oracle files are unchanged by the implementation change.
Controlled implementation prompt
Implement orders-api/list-open-orders@v5 in the current repository from the
approved specification and repository context. Generate the production code and
associated unit tests. Run the approved acceptance and fitness checks. You MAY
correct implementation defects, but you MUST NOT add requirements, change the
acceptance tests or fitness functions, bypass the repository boundary, or make
new architecture decisions. Stop and escalate if the specification is
incomplete, contradictory, or cannot be implemented safely.
The prompt is deliberately small because the design decisions already exist in the specification. The agent can iterate internally, but it cannot turn implementation feedback into an unapproved design change.
Traceability and reproducibility
Every generated change MUST be traceable to a concrete location. The team's pull request template MUST include, at minimum:
Spec: orders-api/list-open-orders@v5
ADR: ADR-20261009T1530Z-order-repository-boundary (required when an ADR applies)
Prompt: <prompt template ID@version>
Baseline: <repository commit>
Agent: <agent/tool version>
Model: <model version>
Generated: <UTC timestamp>
Evaluation: <link to evaluation report>
Each pull request MUST link to the specification commit. When an ADR applies, the pull request MUST also link to the ADR ID. The evaluation report SHOULD be attached to the pull request or stored with the change record.
Reproducibility means that another run can use the recorded specification, baseline, prompt template, model, and agent metadata to reproduce the evaluation process and determine whether the same quality gates pass. It does not require identical generated code.
Identifiers
Specification and ADR identifiers MUST be unique without coordination between branches. Teams MUST NOT use sequential numbers as the unique part of an identifier. When two branches or parallel agents each create a record, both take the next free number, and the second merge produces a conflict or a duplicate ID.
Use one of these formats:
- ADRs: a UTC timestamp and a slug, for example
ADR-20261009T1530Z-order-repository-boundary. The timestamp keeps the records in chronological order. - Specifications: a domain path and a slug, for example
orders-api/list-open-orders, with the version appended as@vN.
The @vN version suffix is different: it is a sequence inside one specification. A version conflict occurs only when two branches
change the same specification. That is a real design conflict, and a human MUST resolve it.
Teams SHOULD generate ADR and specification indexes in CI and SHOULD NOT edit them by hand, because a shared index file also causes merge conflicts.
Team workflow and focus
Teams SHOULD use this workflow:
- Frame the outcome: define the goal, scope, boundaries, risks, and success measures.
- Specify a thin slice: use agents to research, challenge assumptions, draft requirements and architecture, define the oracle, and resolve contradictions. Humans approve the specification.
- Generate and evaluate: give the agent one implementation prompt. Let it generate, test, iterate, and produce evidence within the approved design.
- Review and deliver: humans review the change and evidence, resolve escalations, and approve merge or deployment at the appropriate risk boundary.
- Improve the system: record newly discovered decisions, update repository guidance, improve quality gates, and remove recurring manual steps.
This is what being on the loop, rather than in it, looks like day to day. The team's scarce human time belongs primarily in the specs loop:
- Clarifying outcomes and boundaries
- Making architecture and security decisions
- Defining the behavioral oracle
- Creating reliable repository context
- Establishing enforcement and approval gates
- Learning from implementation failures and improving the workflow
Parallelization on the loop
Working on the loop lets engineers coordinate agents that work in parallel. The agents can:
- Research architecture and draft ADRs
- Identify security requirements and propose test scenarios
- Investigate dependencies and prepare implementation plans
- Generate implementations and evaluate changes
Parallelization works only when agents share durable specifications, contracts, and evaluation criteria. Otherwise, multiple agents create inconsistent interpretations of the problem.
Adoption and health metrics
Teams SHOULD start with these primary metrics:
- Specification traceability
- Percentage of implementation pull requests linked to a specification version.
- Human corrective prompts
- Number of human prompts per pull request after the implementation prompt. Each corrective prompt shows that the specification or the repository context failed.
- Regeneration success
- Percentage of regenerated change sets that pass the same approved quality gates.
- Post-merge defects
- Defects found after merge or deployment that the specification or quality gates did not catch.
Teams MAY add these diagnostic metrics:
- Autonomous iterations per pull request
- Escalations per specification
- Specification revisions caused by implementation failures
- Review rework
- Time from specification approval to reviewed change
- Reproducibility of the evaluation record
Autonomous iterations are a normal part of the loop and are not a health signal on their own. Metrics exist to improve the system, not to reward teams for minimizing prompts at the expense of quality.
Independent confirmation
In October 2026, Google open-sourced the Elephant-Goldfish Model, a plugin that thousands of its engineers use to design software with AI agents. A long-running "elephant" agent holds the project context and drafts the specification. Stateless "goldfish" reviewers, with none of the earlier conversation, stress-test it for unstated assumptions and gaps. A human resolves the trade-offs and approves the design before any code is written.
That is the specs loop, arrived at independently and used at scale. It is a good sign that the idea is worth pursuing: when generation gets cheap, the leverage moves to the specification.
The two approaches cover different halves of the work. The Elephant-Goldfish Model strengthens how a specification is written and challenged. Pedro's Law governs what happens after approval: one controlled implementation prompt, an oracle the agent cannot edit, escalation instead of improvisation, and code that can be regenerated from the versioned specification. They fit together.
What next: the production loop
Pedro's Law has two loops. Humans own the specs loop: they write and approve the specification. The agent owns the implementation loop: it generates, evaluates, and fixes the implementation inside one implementation prompt.
The production loop is the third loop. CI/CD ships the merged change. Live evaluation watches it against SLOs (service level objectives). A rollback, triggered automatically on a breach or manually by a human, redeploys the previous stable version through CI/CD. The root cause then always goes back to the specs loop, never straight to the implementation loop. If a defect reached production, the specification and its evaluations missed it. The team fixes the specification first, then regenerates the change. A low-risk change can also skip human review on the way to merge.
A fourth path closes the system. The stable version produces telemetry and business events. Together they form its operational and analytical data. A mining agent reads this data and proposes spec changes, back into the specs loop.
This is the next step. The two loops govern how code is generated from an approved specification. The production loop adds how the running system is observed, protected, and improved. Some frameworks take humans out of the active development loop altogether at this point. Under Pedro's Law, humans stay on the loop: they still approve every change to the specification.
Takeaway
Use as many rich, iterative prompts as you need to create the specifications.
Then with only ONE prompt: generate the code and associated unit tests.
Normative language
This article uses the following keywords as described in RFC 2119 and RFC 8174. The keywords have these meanings only when, and only when, they appear in all capitals, as shown here. Lowercase words such as "must" or "may" have their ordinary English meaning.
- MUST and MUST NOT are mandatory rules.
- SHOULD and SHOULD NOT are recommendations. Exceptions require an explicit, documented reason.
- MAY indicates permission or an available option.
Resources
- Understanding Spec-Driven-Development: Kiro, spec-kit, and Tessl
- Is Spec-Driven Development a Step Forward or Back?, Yuval Yeret
- Augmented Coding Patterns
- The Phoenix Architecture, Chad Fowler
- Maturity path (L1–L4), Agentic Engineering Framework
- The Five Levels: from Spicy Autocomplete to the Dark Factory, Dan Shapiro
- Agentic Autonomy Levels, Addy Osmani
- Cybernetics and human-on-the-loop in agentic coding, Thoughtworks
- DORA AI Capabilities Model, DORA
- Introducing the Elephant-Goldfish Model plugin, Google Open Source Blog
- What changes and where to start · The AI-native SDLC playbook, Claude Academy
How this was written: I used AI heavily to draft, edit, and polish this article. The ideas are mine, and so is the responsibility for every word. Why I am unapologetic about it.
Want to bring this way of working to your teams?
Let's talk