# TP AI Development Playbook ## The TradyPerch Engineering Handbook ### Version 1.0 *The engineering operating system for every TradyPerch software project. Not project-specific. Not optional. This is how we build.* --- | Field | Value | |---|---| | **Document Name** | TP AI Development Playbook | | **Short Name** | The Playbook | | **Owner** | TradyPerch Engineering | | **Version** | 1.0 | | **Status** | **Active — binding on all projects from this date** | | **Classification** | Internal — Commercial Confidential | | **Scope** | Every TradyPerch software project, of every kind, built by humans, AI agents, or both | | **Supersedes** | All prior informal practice | | **Review Cadence** | Quarterly; amendments per §29 | | **First Governed Project** | TP Reviews Engine v1.0 | | **Document Date** | 2026-07-31 | --- ## 0.1 Why This Document Exists TradyPerch builds software with a small team and a large share of the implementation performed by AI coding agents. That combination is enormously productive and structurally fragile. It is productive because an agent can implement a well-specified module faster than a human can type. It is fragile because an agent will also implement a *badly* specified module at exactly the same speed, with the same confidence, and the defect will look like working code. The difference between those two outcomes is not the model. It is the process around it. This playbook is that process. It exists so that: | Without It | With It | |---|---| | Every project invents its own architecture | Architecture is chosen from a known set, with recorded reasons | | Every project invents its own quality bar | The quality bar is the same everywhere and is mechanically enforced | | Agent output quality depends on who wrote the prompt that day | Prompt structure, size, and context are standardised | | A defect found in project A recurs in project B | Standards absorb the lesson once | | "Done" means whatever the person saying it believes | "Done" is eleven conditions, all checkable | | Knowledge lives in one person's memory | Knowledge lives in documents that outlive the person | | Six months later, nobody can safely change the code | The code was written to be changed six months later | **The economic argument.** A defect caught in review costs minutes. The same defect caught in production costs hours and a customer's confidence. A defect caught *never* — a silent data corruption, a leaked secret, a wiped record — costs the business. Every rule in this handbook exists because the class of failure it prevents is more expensive than the discipline it demands. Where that stops being true, the rule is wrong and §29 explains how to change it. ## 0.2 What This Document Is Not | It Is Not | Because | |---|---| | A style guide | Formatting is delegated to automated formatters. This handbook governs decisions, not whitespace | | A technology mandate | It does not say "use React". It says how to *choose*, and how to record the choice | | A substitute for thinking | Every rule states its rationale. An engineer who understands the rationale can identify when the rule does not apply — and §29 tells them what to do about it | | Application code | This handbook contains no implementation. It contains process, standards, workflows, governance, and templates | | Optional | The rules marked **MUST** are binding. §30 lists the ones that have no waiver at all | ## 0.3 Audience and Conformance ### 0.3.1 Who Must Follow This | Audience | Obligation | |---|---| | **AI coding agents** — Claude Code, OpenAI Codex, Gemini CLI, Cursor, Windsurf, GitHub Copilot, and successors | Full conformance. §2, §3, §4, §13, §19, §25, §26 are written specifically for you | | **Human engineers** | Full conformance. You are additionally accountable for anything an agent produces under your name | | **Technical leads** | Full conformance, plus responsibility for the gates in §27 | | **Engineering managers** | Responsible for §5, §20, §22, §28, and for not asking anyone to skip §27 | | **Contractors and external contributors** | Full conformance on TradyPerch repositories | ### 0.3.2 Conformance Keywords RFC 2119 keywords. They are testable assertions, not emphasis. | Keyword | Meaning | Deviation Requires | |---|---|---| | **MUST / MUST NOT** | Absolute. Non-conformance blocks merge or release | A written waiver (§29.4), except for §30 rules which admit none | | **SHOULD / SHOULD NOT** | Strong default. Deviation is sometimes correct | One sentence of recorded rationale in the pull request | | **MAY** | Genuinely optional | Nothing | | **WILL** | A future commitment of this handbook | Nothing today | ### 0.3.3 Conformance Tiers by Project Class Not every project needs every control. **The tier is chosen at project inception (§5) and recorded in the PRD.** It cannot be lowered later without a waiver. | Tier | Applies To | Examples | Required Sections | |---|---|---|---| | **T1 — Throwaway** | Lives < 30 days, single user, no data, no secrets | A one-off migration script, a spike, a proof of concept | §1, §2, §8 (naming only), §24, §30 | | **T2 — Internal Tool** | Internal users, non-critical, recoverable failures | An internal CLI, a dashboard, a dev tool, a Chrome extension for internal use | T1 + §5 (light), §6, §7, §10, §11 (unit), §14 (README), §15 (secrets), §23 | | **T3 — Production Service** | External users or business-critical internal use | A SaaS platform, a customer-facing web app, a mobile app, a backend API | T2 + all of §5, §9, §11 (full), §12, §16, §17, §18, §22, §27, §28 | | **T4 — Critical** | Handles money, personal data, credentials, or writes to systems of record | Payments, auth, anything holding PII, anything with an irreversible write | T3 + mandatory security review (§15), mandatory chaos testing (§11), two-reviewer rule on the hazard modules, formal release gates | **Choosing a tier is a decision with consequences, and inflation is as harmful as deflation.** A T4 process applied to a two-day internal script wastes a week and teaches the team that the process is theatre. A T2 process applied to a payments integration is how a company ends up in the news. ### 0.3.4 The Tier Decision Tree ```mermaid flowchart TD START(["New project"]) --> Q1{"Does it touch money,
credentials, or personal data?"} Q1 -->|yes| T4["**T4 Critical**"] Q1 -->|no| Q2{"Does it write to a
system of record, or
perform irreversible actions?"} Q2 -->|yes| T4 Q2 -->|no| Q3{"Do people outside
TradyPerch depend on it?"} Q3 -->|yes| T3["**T3 Production**"] Q3 -->|no| Q4{"Will it live
longer than 30 days?"} Q4 -->|no| T1["**T1 Throwaway**"] Q4 -->|yes| Q5{"Would its failure
block someone's work
for more than an hour?"} Q5 -->|yes| T3 Q5 -->|no| T2["**T2 Internal Tool**"] style T4 stroke-width:3px ``` **When genuinely uncertain, choose the higher tier.** Downgrading later is a five-minute decision; discovering mid-project that the tier was too low means retrofitting tests, security review, and observability into a codebase that was not built for them. ## 0.4 How to Read This Handbook ### 0.4.1 Reading Paths | You are… | Read, in this order | Time | |---|---|---| | **An AI coding agent, first session on a project** | §30 (constitution) → §2 → §25 (workflow) → §3 → §4 → §24 (forbidden) → the section for your task | 90 min | | **A human engineer, first week** | §1 → §30 → §5 → §8 → §10 → §23 (checklists) → skim the rest | 4 h | | **A technical lead starting a project** | §5 → §6 → §0.3.3 (tier) → §20 → §27 → §22 | 3 h | | **An engineering manager** | §1 → §5 → §20 → §21 → §22 → §28 | 2 h | | **Reviewing someone's pull request** | §23.3 (before merge) → §10 → §24 | 15 min | | **In an incident** | §12 → §13 → §18.7 (rollback) → §17 | 20 min | | **Deciding whether to rewrite something** | §21 | 30 min | | **Anyone, ever, in doubt** | **§30** | 10 min | ### 0.4.2 The Standard Section Block Every one of the thirty sections follows this structure. It is defined here once and not repeated. | Field | Contains | |---|---| | **Purpose** | One paragraph: what this section is for and what goes wrong without it | | **Objectives** | The enumerated outcomes the section is trying to produce | | **Engineering Rationale** | *Why* these rules, not merely what they are. The part that lets a competent engineer know when a rule does not apply | | **Standards** | The normative content: MUST / SHOULD / MAY rules, tables, and thresholds | | **Real-World Examples** | Concrete situations, drawn from real project shapes, showing the rule in action | | **Common Mistakes** | What people and agents actually get wrong, with the symptom and the fix | | **Anti-Patterns** | Named failure shapes, so that a team can recognise one by name before it costs a quarter | | **Decision Tables** | Structured choices with criteria, so decisions are made once and recorded | | **Checklists** | Executable, in order, by someone who did not write the section | | **Risk Analysis** | What can still go wrong when the section is followed, and what bounds it | | **Future Improvements** | What this section will need as TradyPerch grows | ### 0.4.3 Notation | Convention | Meaning | |---|---| | **`RULE-nn`** | A numbered normative rule within a section. Cited in reviews as e.g. `SEC-15.4` | | **Rationale** | An explanation block. Not normative, but the reason the adjacent rule exists | | **Agent Note** | Aimed at AI coding agents; usually names a plausible-but-wrong action | | **Human Note** | Aimed at human engineers; usually names a discipline that automation cannot enforce | | **Anti-pattern:** *name* | A named failure shape | | **T1 / T2 / T3 / T4** | Conformance tier that the adjacent rule applies from | | ✅ / ❌ | Conformant / non-conformant example | ### 0.4.4 Identifier Families | Prefix | Meaning | Defined In | |---|---|---| | `§n` | A section of this handbook | — | | `RULE-` | A normative rule | Per section | | `AP-` | A named anti-pattern | §24 and throughout | | `GATE-` | A quality gate | §27 | | `KPI-` | An engineering metric | §28 | | `CONST-` | A constitutional rule — no waiver exists | §30 | | `TMPL-` | A prompt template | §26 | | `CHK-` | A checklist | §23 | | `ADR-` | An architecture decision record (per project) | §5 | | `WAIVER-` | An approved deviation | §29.4 | ## 0.5 The Handbook in One Page If everything else is lost, this page is the handbook. | # | Principle | Section | |---|---|---| | 1 | **Plan before you build.** Every project above T1 has a written PRD, architecture, and implementation plan before the first line of code | §5 | | 2 | **Simplicity is a feature.** The simplest design that satisfies the requirement wins, every time | §1 | | 3 | **AI writes; humans are accountable.** No agent output ships without a named human who has read it | §2 | | 4 | **One task, one prompt, one commit, one pull request** | §3, §25 | | 5 | **Tests ship with the code they test.** Not later. There is no later | §10, §11 | | 6 | **Silent failure is the worst failure.** Never swallow an error; never return an empty result on failure | §24 | | 7 | **Secrets never touch the repository.** Ever, in any form, in any branch, in any history | §15, §30 | | 8 | **The build is always green.** A broken main branch blocks everyone | §7, §27 | | 9 | **Every module has one responsibility and states what it does not do** | §9, §14 | | 10 | **If it cannot be diagnosed from logs and artifacts alone, it is not finished** | §17 | | 11 | **Every incident becomes a permanent test, in the same change that fixes it** | §12 | | 12 | **When something does not fit the spec, stop and ask. Never invent** | §2, §13 | | 13 | **Reversibility is a design goal.** Know the rollback before you ship | §18, §21 | | 14 | **Documentation is part of the work, not after it** | §14 | | 15 | **The rules apply under deadline pressure. That is when they are load-bearing** | §30 | ## 0.6 Section Map | § | Title | Part | Primary Audience | |---|---|---|---| | 1 | Engineering Philosophy | 1 | Everyone | | 2 | AI Coding Philosophy | 1 | Agents, leads | | 3 | Prompt Engineering Standards | 2 | Agents, engineers | | 4 | Context Management | 2 | Agents, engineers | | 5 | Planning Before Coding | 3 | Leads, managers | | 6 | Repository Standards | 4 | Engineers | | 7 | Git Standards | 4 | Engineers, agents | | 8 | Coding Standards | 5 | Engineers, agents | | 9 | Module Isolation Rules | 5 | Engineers, agents | | 10 | Definition of Done | 6 | Everyone | | 11 | Testing Standards | 6 | Engineers, QA | | 12 | Debugging Standards | 7 | Engineers | | 13 | AI Error Recovery | 7 | Agents, engineers | | 14 | Documentation Standards | 8 | Everyone | | 15 | Security Standards | 8 | Everyone | | 16 | Performance Standards | 9 | Engineers | | 17 | Observability | 9 | Engineers, SRE | | 18 | Deployment Standards | 10 | DevOps, engineers | | 19 | AI Agent Collaboration | 10 | Agents, leads | | 20 | Project Lifecycle | 11 | Managers, leads | | 21 | Decision Frameworks | 11 | Leads, architects | | 22 | Risk Management | 12 | Managers, leads | | 23 | Engineering Checklists | 12 | Everyone | | 24 | Forbidden Practices | 13 | Everyone | | 25 | AI Coding Workflow | 13 | Agents | | 26 | Prompt Library | 14 | Agents, engineers | | 27 | Quality Gates | 15 | Leads, managers | | 28 | Engineering KPIs | 15 | Managers | | 29 | Future Evolution | 16 | Everyone | | 30 | **The Engineering Constitution** | 16 | **Everyone** | ## 0.7 Relationship to Project Documents This handbook is the standing standard. Each project produces its own documents that instantiate it. ```mermaid flowchart TB PB["**TP AI Development Playbook**
permanent · cross-project
*how we build*"] subgraph PROJ["Per project"] PRD["PRD
*what and why, for users*"] SAD["SAD / Architecture
*what the system is*"] TRD["TRD
*how exactly it is built*"] IMPL["Implementation Plan
*in what order, verified how*"] end PB ==>|"governs"| PRD PB ==>|"governs"| SAD PB ==>|"governs"| TRD PB ==>|"governs"| IMPL PRD --> SAD --> TRD --> IMPL PB -.->|"a project may not
contradict the playbook
without a waiver"| PROJ style PB stroke-width:3px ``` | Rule | Statement | |---|---| | **P-1** | A project document MUST NOT contradict this handbook. Where it does, the handbook wins and the project document is defective | | **P-2** | A project MAY be *stricter* than the handbook without any approval | | **P-3** | A project MAY be *looser* only with a recorded waiver (§29.4) | | **P-4** | Where the handbook is silent, the project decides and records the decision as an ADR | | **P-5** | A pattern that three projects have independently adopted SHOULD be proposed as a handbook amendment | ## 0.8 Document Control ### 0.8.1 Revision History | Version | Date | Change | Approval | |---|---|---|---| | v0.1 | 2026-07-31 | Extracted from TP Reviews Engine practice; generalised | Draft | | **v1.0** | **2026-07-31** | **Baselined. Thirty sections, four conformance tiers, the Engineering Constitution.** | **Active** | ### 0.8.2 Ownership | Section Range | Owner | Review Cadence | |---|---|---| | §1–§2, §29–§30 | Head of Engineering | Annually, or on incident | | §3–§4, §13, §19, §25–§26 | AI Systems Architect | **Quarterly** — this is the fastest-moving area | | §5, §20–§22, §28 | Technical Program Management | Semi-annually | | §6–§9, §21 | Principal Engineer | Semi-annually | | §10–§12, §23, §27 | QA Lead | Quarterly | | §14 | Whoever last found the docs wrong | Continuous | | §15 | Security Architect | **Quarterly + on any incident** | | §16–§18 | Staff DevOps Engineer | Semi-annually | | §24 | Everyone. Additions are welcome from anyone who has been bitten | Continuous | ### 0.8.3 Binding Status This handbook is binding from its baseline date on all new projects, and on existing projects at their next major version. A pull request that contradicts a **MUST** rule is rejected. A pull request that contradicts a **SHOULD** rule without a recorded reason is rejected. Neither is a judgement about the author; both are how a standard stays a standard. **Code that drifts from this handbook is treated as a defect of the same severity as a failing test.** --- *End of front matter. Part 1 begins with Section 1, Engineering Philosophy.* --- # Part 1 — Philosophy *Sections 1 and 2. Everything else in this handbook is a consequence of these two sections. An engineer who internalises Part 1 will derive most of the remaining twenty-eight sections independently; an engineer who skips it will experience the rest as arbitrary bureaucracy.* --- # 1. Engineering Philosophy ## 1.1 Purpose To state what TradyPerch engineers value, so that the thousands of small decisions nobody reviews — the ones made alone, at speed, under pressure — trend in the same direction. Standards govern the decisions we anticipated. Philosophy governs the ones we did not. Without a shared philosophy, a team of three produces four architectures, every code review becomes a negotiation of first principles, and the codebase becomes a geological record of whoever was most opinionated in each quarter. ## 1.2 Objectives 1. Define the values that override local convenience. 2. Establish quality as a **precondition** of delivery, not a phase after it. 3. Make maintainability a first-class requirement with the same standing as functionality. 4. Establish that clarity beats cleverness, permanently and without exception. 5. Define what ownership means when much of the code is machine-written. 6. Establish documentation as part of the work rather than a tax on it. 7. Give every engineer a defensible answer to "why are we doing it this way?" ## 1.3 Engineering Rationale ### 1.3.1 The Constraint That Shapes Everything TradyPerch is a small engineering organisation building software intended to last years, with a large fraction of implementation performed by AI agents. Three consequences follow, and they are the root of nearly every rule in this handbook: | Constraint | Consequence | |---|---| | **Small team** | Nobody can be a full-time gatekeeper. Quality must be *mechanised* — in linters, tests, and CI — because it cannot be *supervised* | | **Long horizon** | The person maintaining this in three years will have no context. Code must explain itself, and documents must survive their authors | | **AI-heavy implementation** | Code volume is cheap; *correct* code volume is not. The scarce resource is verification, so everything is optimised for being easy to verify | **The third consequence is the one that is new**, and it inverts an old assumption. For decades, engineering process assumed that writing code was the expensive step and that reviewing it was cheap by comparison. With capable agents, generating a plausible 400-line module costs minutes. Confirming that it is correct costs the same as it always did. So the bottleneck has moved, and a process designed for the old bottleneck now optimises the wrong thing. **Everything in this handbook is designed to reduce the cost of verification.** Small modules, explicit contracts, pure functions, one-responsibility files, tests written with the code, standard structures, forbidden patterns — none of these make code faster to write. They make it faster to *check*, and checking is now the constraint. ### 1.3.2 Why Quality-First Is an Economic Position, Not a Moral One "Quality first" sounds like a slogan until it is quantified. The cost of a defect grows by roughly an order of magnitude at each stage it survives: | Caught At | Typical Cost | Who Pays | |---|---|---| | While writing | ~1 minute | The author | | In automated checks | ~5 minutes | The author | | In review | ~30 minutes | Author + reviewer | | In staging | ~2 hours | The team | | In production | ~1 day + trust | The team + users | | **Never (silent corruption)** | **Unbounded** | **The business** | Shipping faster by skipping the early stages does not save time. It **moves** time from a cheap stage to an expensive one, and adds risk. The only genuine way to ship faster is to make the early stages cheaper — which is what automation, small changes, and clear standards do. **Human Note.** The pressure to skip quality steps never arrives labelled as such. It arrives as "this one is simple", "we'll add the tests after the demo", or "the client is waiting". Those are the moments this section exists for. The correct response is not heroism; it is to reduce scope, which is a decision the person applying pressure is entitled to make. ### 1.3.3 Simplicity Is Not Aesthetic Preference A clever solution is one where the reader must reconstruct the author's reasoning to understand what happens. A simple solution is one where they do not. In a codebase read far more often than it is written — and maintained by people, and by agents, who lack the author's context — reconstruction cost is the dominant cost. Cleverness moves work from the author to every future reader, multiplied by every future reading. | The Clever Version | The Simple Version | What It Costs | |---|---|---| | A dense expression chaining five operations | Five named steps | Three lines. Buys instant comprehension and a precise stack trace | | A generic abstraction over one use case | The one use case, directly | Removes an indirection the reader must trace and a constraint on the next change | | Implicit behaviour via convention | Explicit behaviour, stated | Two lines. Removes "how did that happen?" from every future incident | | A configuration flag "for flexibility" | The one behaviour that is needed | Removes an untested code path | | Metaprogramming that generates handlers | Handlers, written out | Greppability. An identifier you cannot search for is an identifier nobody will find | **Rationale.** Every one of these trades a small, one-time authoring cost for a permanent reduction in reading cost. That is always the right trade in a long-lived codebase, and it is *especially* right when a substantial number of future readers are agents that reason locally from what is in front of them. ### 1.3.4 Maintainability Is a Requirement, Not a Virtue A feature that works and cannot be safely changed is a liability with a nice demo. TradyPerch treats maintainability as a functional requirement with acceptance criteria: | Property | Testable Statement | |---|---| | **Comprehensible** | A competent engineer unfamiliar with the module can state what it does after five minutes | | **Changeable** | A typical change touches one module and does not require understanding three others | | **Verifiable** | A change's correctness is established by tests, not by manual exploration | | **Diagnosable** | A production failure can be understood from logs and artifacts alone, without reproducing it locally | | **Reversible** | Any change can be undone in under fifteen minutes, and the procedure is written down before it is needed | | **Replaceable** | Any single module can be rewritten without rewriting its neighbours | **If a change cannot satisfy all six, it is not finished — regardless of whether it works.** ### 1.3.5 Reliability Is Designed, Not Achieved Reliable systems are not systems that do not fail. They are systems in which failure is anticipated, bounded, observable, and recoverable. | Property | What It Means in Practice | |---|---| | **Fail closed on permission and identity** | When authorisation is uncertain, deny. A system that grants access on error is worse than one that is down | | **Fail soft on data** | One malformed record must not take down the batch. Quarantine it, record it, continue | | **Never fail silently** | Every failure produces a classified, logged, attributable signal. Silence is the only truly unrecoverable failure mode | | **Degrade honestly** | If part of the system is unavailable, say so. Do not present stale data as fresh or partial data as complete | | **Preserve the last known good** | A failed update must never leave the system worse than before it started | | **Make recovery cheap** | If recovery requires improvisation, it will be improvised badly, at 3 a.m., by whoever is available | ### 1.3.6 Ownership in an AI-Assisted Team Ownership is the property that someone specific is accountable for a thing being right. AI agents cannot hold it — they have no continuity, no stake, and no ability to be answerable. | Ownership Rule | Statement | |---|---| | **OWN-1** | Every module has exactly one accountable human owner. Not a team; a person | | **OWN-2** | The person who merges a change owns it, regardless of who or what wrote it | | **OWN-3** | "The AI wrote it" is never an explanation for a defect. It is an admission that the owner did not verify it | | **OWN-4** | Ownership transfers explicitly, in writing, with a handover — never by attrition | | **OWN-5** | An unowned module is a defect in the project, and is assigned at the next review | **Rationale.** The single greatest risk of AI-assisted development is diffusion of responsibility: the agent generated it, the reviewer skimmed it, nobody actually understands it, and it works — until it does not, and then nobody can fix it. OWN-2 exists to make that impossible. If you merge it, you own it. If you are not willing to own it, do not merge it. ### 1.3.7 Documentation Culture Documentation is not a phase, a chore, or something written for an imaginary future reader. It is written for a specific, real person: **the engineer, or agent, who touches this next and does not have your context.** That person is frequently you, four months later. | Principle | Consequence | |---|---| | Documentation ships with the change | A pull request that changes behaviour and not the docs is incomplete | | Explain **why**, not what | The code says what. Only a human can record why the obvious alternative was rejected | | State what a module **does not** do | The most valuable line in a module header, because it prevents scope creep and misuse | | Record decisions when made | Reconstructing a decision six months later costs ten times more and loses the alternatives | | Delete stale docs aggressively | Wrong documentation is worse than none: it is trusted, and it lies | | Optimise for scanning | Tables and lists over paragraphs. Nobody reads documentation; they search it | ## 1.4 Standards | ID | Rule | Tier | |---|---|---| | **PHIL-01** | Simplicity MUST be preferred over cleverness. Where a reviewer judges a solution to be clever, the burden of justification is on the author | All | | **PHIL-02** | Maintainability MUST be treated as a functional requirement, assessed at review against §1.3.4's six properties | T2+ | | **PHIL-03** | Every module MUST have exactly one accountable human owner | T2+ | | **PHIL-04** | Failures MUST be explicit, classified, and logged. Silent failure is prohibited (§24) | All | | **PHIL-05** | Documentation MUST ship in the same change as the behaviour it describes | T2+ | | **PHIL-06** | Decisions with long-term consequences MUST be recorded as ADRs at the time they are made | T3+ | | **PHIL-07** | Quality checks MUST be mechanised wherever mechanisation is possible. A standard enforced only by review is a standard that erodes | T2+ | | **PHIL-08** | The conformance tier MUST be chosen at inception and recorded. It MUST NOT be lowered without a waiver | All | | **PHIL-09** | Scope MUST be the first thing cut under pressure. Quality gates MUST be the last | All | | **PHIL-10** | An engineer MUST be able to state the rationale for any standard they are applying, or MUST look it up before applying it | All | ## 1.5 Real-World Examples ### Example 1 — The Two-Hour Optimisation A dashboard endpoint takes 800 ms. An engineer spends two hours adding a caching layer with invalidation logic, reducing it to 40 ms. | Question | Answer | |---|---| | Did it work? | Yes | | Was it the right call? | **Almost certainly not** | | Why not? | The endpoint is called by four internal users a few times a day. 800 ms was invisible. The cache added an invalidation path — the classic source of "stale data" bugs — and a second source of truth | | What should have happened? | Measure the actual user impact first (§16). Record that it is acceptable. Move on | | What rule covers it? | PHIL-01, and §16's rule that optimisation requires a measured problem | ### Example 2 — The Silent Catch An agent implements a data import. When a row fails to parse, it catches the error and continues. The import reports success. Three weeks later a customer notices 12% of their records are missing. | Question | Answer | |---|---| | Did the code work? | It ran without crashing, which is not the same thing | | What was the actual defect? | The failure had no signal. Nobody could have known | | Cost of catching it in review | Thirty seconds — the reviewer asks "what happens to a bad row?" | | Cost of catching it in production | Three weeks of missing data, a customer escalation, and an audit of every other import | | What rule covers it? | PHIL-04, §24's prohibition on catch-and-continue, and §11's requirement that failure paths are tested | ### Example 3 — The Rewrite That Should Not Have Happened A five-year-old internal tool is "unmaintainable". An engineer proposes a rewrite: six weeks. The rewrite ships at eleven weeks, missing three behaviours nobody had documented because they were only visible in the old code. | Question | Answer | |---|---| | Was the old code bad? | Yes | | Was the rewrite justified? | Not on that evidence. §21's rewrite criteria were not applied | | What was actually missing? | Nobody had characterised the existing behaviour. The old code *was* the specification | | What should have happened? | Characterisation tests first, then incremental replacement behind the existing interface | | What rule covers it? | §21.4 (rewrite decision framework) | ### Example 4 — The Feature That Could Not Be Removed A SaaS product adds an integration for one customer. It is wired directly into the core request path with three conditionals on customer id. Two years later the customer leaves. Removing the integration takes a week because nobody can prove which conditionals are still load-bearing. | Question | Answer | |---|---| | What went wrong? | Customer-specific logic in shared code. §9's isolation rules would have made this an adapter | | Symptom to watch for | Any conditional keyed on a customer, tenant, or account identifier in shared code | | Cost at the time | Ten minutes saved | | Cost later | A week, plus permanent uncertainty | ## 1.6 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Treating quality as a phase | "We'll harden it after launch" | Quality is a per-change property. There is no hardening phase, and there never has been | | 2 | Optimising the writing step | Huge changes generated quickly, then stuck in review for days | Optimise the *verification* step. Small changes merge fast | | 3 | Confusing "it works" with "it is done" | Feature demos fine; breaks on the second edge case | §10's Definition of Done, all eleven conditions | | 4 | Building for imagined future needs | Configuration flags with one value; abstractions with one implementation | YAGNI (§8). Build for the requirement in front of you | | 5 | Documenting *what* instead of *why* | Comments that restate the line below them | Comments explain rejected alternatives and non-obvious constraints | | 6 | Diffused ownership | "I thought you owned that" | OWN-1: one named human per module | | 7 | Trusting agent output because it looks right | Plausible code that fails on the case nobody tested | §2's verification rules; §11's testing rules | | 8 | Cargo-culting this handbook | Applying T4 process to a T1 script | §0.3.3. The tier is a decision, and inflation is as harmful as deflation | ## 1.7 Anti-Patterns | ID | Anti-Pattern | Description | Why It Persists | Countermeasure | |---|---|---|---|---| | **AP-01** | **Hero Engineering** | One person heroically ships under pressure by bypassing process | It works, once, and gets praised | Praise the outcome, review the method. Recognise that the next attempt fails | | **AP-02** | **Resume-Driven Development** | Technology chosen for its interest rather than its fit | Learning is genuinely valuable, so it feels defensible | §21's decision matrices force stated criteria | | **AP-03** | **The Big Rewrite** | Replacing a working system wholesale rather than incrementally | The existing code is genuinely unpleasant | §21.4's five preconditions, all required | | **AP-04** | **Quality Theatre** | Process that produces artifacts nobody reads — checklists ticked without execution | It is visible and feels like rigour | Every check produces *evidence*, not a tick (§27) | | **AP-05** | **Premature Generalisation** | An abstraction built before a second use case exists | Feels forward-thinking | Two users minimum; three is often better | | **AP-06** | **The Knowledge Silo** | One person understands a critical component | Efficient in the short term | Two reviewers on hazard modules; docs as an exit criterion | | **AP-07** | **Deadline Amnesia** | Standards apply until the week they matter | Pressure is real | §30. The constitution is written specifically for that week | | **AP-08** | **The Zombie Feature** | Nobody uses it, nobody removes it, everybody maintains it | Removal feels risky | §20's retirement stage; usage measurement before renewal | ## 1.8 Decision Tables ### 1.8.1 Simplicity vs Capability | Situation | Choose Simple When | Choose Capable When | |---|---|---| | Data storage | One consumer, small volume, no complex queries | Multiple consumers, growth is measured not assumed | | Abstraction | One implementation exists | **Two implementations exist today** | | Configuration | The value has never changed | The value has changed at least once, or differs by environment | | Caching | The measured latency is acceptable | A measured problem exists and correctness is unaffected | | Async processing | The operation completes within the request budget | It does not, measurably | | Framework | The standard library suffices | You would write more than ~200 lines to replace it | **The pattern:** the "capable" column always requires *evidence in the present tense*. Anticipated need is not evidence. ### 1.8.2 What to Cut Under Pressure Cut in this order. Never invert it. | Order | Cut | Why It Is Safe | |---|---|---| | 1 | **Scope** — fewer features, fully done | The only genuinely safe cut. Recoverable in the next iteration | | 2 | **Polish** — visual refinement, minor ergonomics | Visible, cheap to add later | | 3 | **Non-essential integrations** | Isolated by design (§9), so removal is clean | | 4 | **Performance beyond the requirement** | Measurable, revisitable | | — | **═══ THE LINE ═══** | | | ✗ | Tests | The change becomes unverifiable and every later change becomes risky | | ✗ | Security controls | The failure is unbounded and often irreversible | | ✗ | Error handling | Converts a visible failure into a silent one | | ✗ | Observability | The system becomes undiagnosable exactly when it matters | | ✗ | Documentation of decisions | The rationale is lost permanently | | ✗ | Code review | Removes the only check on machine-generated code | ## 1.9 Checklists ### CHK-1.1 · Am I Making the Right Trade? (before any non-trivial decision) - [ ] Can I state the requirement this serves, in one sentence, without using the word "flexible"? - [ ] Is there a simpler option that satisfies it? Why did I reject it? - [ ] Will a stranger understand this in five minutes without asking me? - [ ] What is the reversal cost if this is wrong? - [ ] Does this create a second source of truth for anything? - [ ] Am I building for a need that exists today, or one I imagine? - [ ] If this fails in production at 3 a.m., what will the logs say? ### CHK-1.2 · Ownership Handover - [ ] The new owner has read the module and can state what it does **and does not** do - [ ] Known defects, workarounds, and sharp edges are written down, not spoken - [ ] Runbooks for its failure modes exist and have been read - [ ] Its tests pass and the new owner has run them - [ ] The ownership record is updated in the repository - [ ] The previous owner is available for questions for two weeks, and this is stated ## 1.10 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Philosophy is read once and never applied | High | High | Every later section restates its philosophical basis; reviews cite rules | Medium — requires leadership modelling | | "Simplicity" used to justify under-engineering | Medium | Medium | Simplicity means fewest concepts, not least work. §10's DoD is unaffected by it | Low | | Quality-first used to justify perfectionism | Medium | Medium | Tiers (§0.3.3) bound the process; DoD bounds the work | Low | | Ownership becomes a blame mechanism | Medium | High | Ownership is about *accountability for fixing*, not fault. Incident reviews are blameless (§12) | Medium — cultural, needs active management | | Standards ossify and stop matching reality | Medium | Medium | §29's amendment process, quarterly reviews, and the three-project rule (P-5) | Low | ## 1.11 Future Improvements | Item | When | Note | |---|---|---| | A short onboarding narrative version of §1 | When headcount exceeds ~8 | The handbook form is for reference, not for first contact | | Recorded worked examples from real TradyPerch incidents | Continuously | Real examples beat hypothetical ones; add one per incident | | A measured decision-quality retrospective | Annually | Sample twenty past decisions; assess which the philosophy got right | --- # 2. AI Coding Philosophy ## 2.1 Purpose To define how AI coding agents participate in TradyPerch engineering: what they are excellent at, what they are dangerous at, what they may never do, and how human accountability is preserved when most of the code is machine-written. Without this section, AI assistance produces a codebase that looks professional, passes superficial review, and contains a class of defect that traditional process was never designed to catch — because traditional process assumed that anyone who could produce plausible code understood the domain. ## 2.2 Objectives 1. Define the division of labour between agents and humans by *risk*, not by convenience. 2. Establish that human accountability is never transferred. 3. Define trust boundaries: what agent output may be relied upon without verification (almost nothing) and what must always be verified. 4. Establish a verification philosophy proportional to the cost of being wrong. 5. Name the specific failure modes agents exhibit, so they can be checked for by name. 6. Define supervision rules that scale as agent capability grows. ## 2.3 Engineering Rationale ### 2.3.1 What Agents Are Genuinely Excellent At Stated plainly, because under-using a capable tool is also a failure. | Strength | Why | Example Task | |---|---|---| | **Breadth of recall** | They have read more code and specification than any individual | Applying a 40-page specification consistently across 30 files | | **Tireless consistency** | The 200th test is written with the same care as the first | Exhaustive boundary tests; adversarial input corpora | | **Mechanical transformation** | Renaming, restructuring, transcribing a table into constants | Migrations, scaffolding, config generation | | **Draft velocity** | A first version in minutes | Getting a shape on the page for a human to critique | | **Pattern completion** | Extending an established pattern to a new case | The fifth adapter, given four | | **Documentation** | Turning a diff into a description | Changelogs, API docs, module headers | | **Enumeration** | Listing what a human would forget | "Which error classes can this produce?" | **The highest-value agent application at TradyPerch is exhaustive testing of a human-designed hazardous module.** That inverts the usual split and puts the agent where its recall is an asset and its confidence is not a liability. ### 2.3.2 What Agents Are Dangerous At — and Why The dangers are not random. They follow from how these systems work, which means they are predictable and therefore checkable. | Failure Mode | Mechanism | What It Looks Like | Where It Bites | |---|---|---|---| | **Confident fabrication** | Trained to produce plausible continuations, not to signal absence of knowledge | An API that does not exist, called correctly | Unfamiliar libraries, internal APIs | | **Plausible-but-wrong defaults** | Idiomatic patterns dominate the training distribution | A defaulted timestamp parameter; a broad catch returning empty | Purity, determinism, error handling | | **Specification drift under length** | Attention over a long context is not uniform | Rule 3 of 12 quietly not implemented | Long specifications, many-rule modules | | **Silent simplification** | Redundancy looks like a smell | Three near-identical branches collapsed into one | **Deliberate asymmetries and safety branches** | | **Local reasoning** | Optimises the visible file | A helper duplicated because the existing one was not in context | Cross-cutting concerns | | **Test-to-implementation fitting** | Tests written after code describe the code | Tests that pass against a wrong implementation | Post-hoc test writing | | **Instruction recency bias** | Later instructions dominate | An early constraint dropped after a long exchange | Long sessions, iterative refinement | | **Overreach** | Trained to be helpful | Unrequested refactoring bundled into a fix | Any task with an adjacent imperfection | **Rationale for the whole of §2:** every rule below targets one of these eight mechanisms. They are not generic caution; they are countermeasures. ### 2.3.3 The Asymmetry That Determines Everything > An agent's probability of being right is high. The cost of the cases where it is wrong is not uniformly distributed. An agent might be right 95% of the time across a project. If the 5% is spread evenly, that is an ordinary quality problem. It is not spread evenly. It concentrates in exactly the places where: - the correct behaviour is unusual (a deliberate asymmetry, a safety branch); - the failure is silent (data corruption rather than a crash); - the specification is subtle (ordering, purity, boundary conditions); - and the idiomatic pattern is *wrong for this codebase*. **Therefore verification effort is allocated by consequence, not by volume.** A 500-line scaffolding change may get a five-minute review. A 20-line change to a reconciliation branch gets two reviewers and a hand-trace. This is not distrust of the agent; it is correct allocation of the scarce resource. ### 2.3.4 The Trust Model **Trust is never granted to the agent. It is granted to the *verification*.** ```mermaid flowchart TB A["Agent output"] --> V{"Verification available?"} V -->|"Mechanical:
types, lint, tests, CI"| M["Trust the check,
not the code"] V -->|"Human review
against a spec"| H["Trust the reviewer
who read the spec"] V -->|"None"| N["**Do not merge**"] M --> SHIP(["Mergeable"]) H --> SHIP N --> STOP(["Blocked"]) style N stroke-width:3px ``` | Trust Level | What It Applies To | Verification Required | |---|---|---| | **T-A · Mechanically verified** | Anything a type checker, linter, test, or CI gate can confirm | The gate is the verification. A human need not re-derive it | | **T-B · Spec-verified** | Behaviour specified in a document the reviewer reads alongside the diff | Line-by-line comparison against the named specification | | **T-C · Judgement-verified** | Design decisions, naming, boundaries, trade-offs | Human judgement, recorded in review comments | | **T-D · Unverifiable as written** | "It should handle edge cases correctly" | **Not mergeable.** Make it verifiable or do not ship it | **T-D is the important row.** If nobody can state how they would know the code is right, the code does not merge. The response is to write the test, write the spec, or reduce the scope — not to approve it because it looks reasonable. ### 2.3.5 The Human Supervision Ladder Supervision intensity scales with the cost of being wrong, not with the size of the change. | Level | Applies To | Human Involvement | Merge Requirement | |---|---|---|---| | **S1 · Autonomous** | Formatting, docs, dependency-free scaffolding, generated boilerplate, test data builders | Read the diff | 1 approval | | **S2 · Reviewed** | Ordinary feature work with clear specs and good test coverage | Review against the spec | 1 approval | | **S3 · Verified** | Business logic, integrations, anything with non-obvious rules | **Line-by-line against the specification**, with the spec open | 1 approval, spec cited in the PR | | **S4 · Co-developed** | Security, auth, payments, data migration, concurrency, anything irreversible | Human designs and specifies; agent may implement; **two reviewers**, one uninvolved | 2 approvals | | **S5 · Human-led** | The hazard modules (§2.4.2) | **Human writes the implementation.** Agent may write tests, fixtures, and documentation | 2 approvals, one being the module owner | ### 2.3.6 Verification Philosophy Four principles, in priority order: | # | Principle | Consequence | |---|---|---| | **V-1** | **Verify the requirement, not the code** | Ask "does this do what was asked?" before "is this good code?" A beautifully written wrong thing is still wrong | | **V-2** | **Prefer mechanical verification** | Every rule that a test or linter can enforce, one should. Human attention is finite and degrades over a long diff | | **V-3** | **Verify the failure paths first** | Happy paths are where agents are strongest and where defects are cheapest. Failure paths are the inverse | | **V-4** | **Verify by attack, not by inspection** | Do not read code looking for bugs. Construct the input that would break it, then check | **V-4 in practice.** The most effective review technique for agent-generated code is to spend two minutes constructing three adversarial inputs *before* reading the implementation, then check each. This finds a category of defect that inspection reliably misses, because inspection follows the author's reasoning and adversarial construction does not. ### 2.3.7 Why "The AI Did It" Is Never an Explanation An agent is a tool with a very high output rate. A defect in its output that reaches production is a failure of the process that accepted it. Three consequences: 1. **The merging human is accountable.** Not the agent, not the prompt, not the model version. 2. **"I didn't read it closely" is a process finding**, and the process is amended (§29) or the change was too large (§3.4). 3. **Repeated defects of the same class are a standards gap**, not an agent problem. Fix the standard so the mechanical gate catches it next time. ## 2.4 Standards ### 2.4.1 What AI Agents MUST Do | ID | Rule | Tier | |---|---|---| | **AI-01** | An agent MUST work from a written specification — a task description, ticket, or plan entry. "Make it better" is not a task | All | | **AI-02** | An agent MUST implement one task per session and one task per pull request | All | | **AI-03** | An agent MUST write tests in the same change as the code they test | T2+ | | **AI-04** | An agent MUST state, in the pull request, which specification it implemented and how it verified the result | T2+ | | **AI-05** | An agent MUST stop and ask when the specification does not cover the case in front of it | All | | **AI-06** | An agent MUST re-read the governing specification after any context compaction or summarisation | All | | **AI-07** | An agent MUST run the full local verification suite before proposing a change | T2+ | | **AI-08** | An agent MUST declare uncertainty explicitly rather than choosing the most plausible option silently | All | | **AI-09** | An agent MUST keep changes within the size limits in §3.4 | All | | **AI-10** | An agent MUST follow the project's existing patterns rather than importing conventions from elsewhere | All | ### 2.4.2 What AI Agents MUST NOT Do | ID | Prohibition | Rationale | |---|---|---| | **AI-N1** | **MUST NOT invent an API, library, function, or configuration key.** If it is not in the codebase or the documentation provided, it does not exist — ask | Confident fabrication is the most common agent failure | | **AI-N2** | **MUST NOT weaken a test, threshold, or type to make a check pass** | The check is the requirement; the code is the attempt | | **AI-N3** | **MUST NOT swallow an error, return an empty result on failure, or catch broadly and continue** | Converts a visible failure into a silent one (§24) | | **AI-N4** | **MUST NOT simplify code that looks redundant** without confirming why the redundancy exists | Deliberate asymmetries and safety branches look like duplication | | **AI-N5** | **MUST NOT bundle refactoring with behaviour change** | The behaviour change hides in the diff | | **AI-N6** | **MUST NOT add a dependency** without explicit approval recorded in the change | Supply chain is a security boundary | | **AI-N7** | **MUST NOT write, log, print, or commit a secret, credential, token, or key** — including placeholders that look real | Irreversible in a repository | | **AI-N8** | **MUST NOT expand scope beyond the task**, however obviously beneficial the addition seems | Unreviewed scope is unowned scope | | **AI-N9** | **MUST NOT claim a change is tested, verified, or complete without having run the verification** | Reported outcomes must be true | | **AI-N10** | **MUST NOT proceed past an ambiguity by choosing the most likely interpretation** | Ask. The cost of asking is one message; the cost of guessing is a wrong implementation that looks right | | **AI-N11** | **MUST NOT modify the hazard modules' implementation** (below) unless explicitly instructed by the module owner | These are S5 by definition | | **AI-N12** | **MUST NOT disable, skip, or delete a failing test** to unblock progress | A failing test is information | ### 2.4.3 The Hazard Modules **Every project MUST designate its hazard modules at inception** and record them in the repository. They are S5: human-led implementation, agent-assisted testing only. The general test for a hazard module — any one of these is sufficient: | Criterion | Examples | |---|---| | Failure is **silent** and corrupts data | Merge/reconciliation logic, deduplication, migrations | | Failure is **irreversible** | Deletion, payment capture, external notifications, publishing | | It is a **security boundary** | Auth, session handling, input sanitisation, redaction, permission checks | | It enforces a **safety property** | Rate limiting, circuit breaking, publication gates, quota enforcement | | Correctness depends on a **deliberate asymmetry** | Anything where similar-looking branches must stay separate | | It defines a **public contract** | Payload schemas, API contracts, identifier derivation | **Agent Note.** If you are asked to modify a module and cannot tell whether it is a hazard module, **ask before writing**. The cost of asking is one message. The cost of being wrong is the category of defect this entire section exists to prevent. ### 2.4.4 Human Supervision Rules | ID | Rule | |---|---| | **SUP-1** | Every agent-produced change MUST be merged by a named human who has read it | | **SUP-2** | The reviewer MUST have the governing specification available and MUST cite it | | **SUP-3** | For S4/S5 changes, one reviewer MUST NOT have participated in producing the change | | **SUP-4** | A reviewer who cannot verify a change within a reasonable time MUST reject it as **too large**, not approve it provisionally | | **SUP-5** | A human MUST NOT approve a change they do not understand. "It passes CI" is not understanding | | **SUP-6** | Agent-produced test changes MUST be reviewed with **more** scrutiny than implementation changes, because a weakened test disables future verification permanently | **SUP-6 is counter-intuitive and important.** A wrong implementation fails visibly. A weakened test silently removes a guard forever, and nobody notices because the suite is green. ## 2.5 Real-World Examples ### Example 1 — Fabricated Configuration An agent is asked to add retry behaviour to an HTTP client. It produces well-structured code referencing a configuration option that the library does not have. Everything type-checks because the config object is loosely typed. The retry silently never happens. | | | |---|---| | Mechanism | Confident fabrication (§2.3.2) | | Why review missed it | The code looked idiomatic and the option name was plausible | | What would have caught it | A test asserting the retry *occurred* — V-3, verify failure paths | | Rule | AI-N1, AI-03 | ### Example 2 — The Helpful Simplification An agent is asked to fix a typo in a module that handles record removal. It fixes the typo and also merges two branches that "did the same thing". They did not: one applied only when the incoming data was complete. The change passes all existing tests, because no existing test exercised incomplete data. | | | |---|---| | Mechanism | Silent simplification + overreach | | Cost | Potential data loss under a condition that occurs occasionally | | What would have caught it | AI-N5 (no bundling), AI-N4 (no simplification), a property test over incomplete inputs | | Rule | AI-N4, AI-N5, AI-N8, and the module should have been designated a hazard module | ### Example 3 — Specification Drift at Length A twelve-rule validation specification is handed to an agent in one prompt. The implementation satisfies eleven rules. Rule 7 — the one in the middle, phrased differently from its neighbours — is not implemented. Tests were generated from the implementation, so they pass. | | | |---|---| | Mechanism | Specification drift + test-to-implementation fitting | | What would have caught it | One rule per task (§3.4); tests derived from the spec, not the code; a rule-to-test traceability table | | Rule | AI-02, AI-09, §11's traceability requirement | ### Example 4 — The Correct Use A team needs adversarial test coverage for an input-sanitisation module. A human writes the module and the property statement. An agent generates 60 adversarial inputs across eight categories — encodings, control characters, bidirectional overrides, emoji sequences, length boundaries — and the corresponding tests. Two genuine defects surface. | | | |---|---| | Why this works | Recall and tirelessness are assets; the human retained the judgement | | Supervision level | S5 implementation, S2 tests | | Result | Better coverage than either would have produced alone | ## 2.6 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Treating an agent as a junior engineer | Vague direction, expecting judgement | Agents have vast recall and no stake. Specify precisely; verify by consequence | | 2 | Treating an agent as a compiler | Assuming identical input gives identical output | Outputs vary. Verification is per change, not per prompt | | 3 | Reviewing agent code like human code | Scanning for style; missing fabricated APIs | V-4: attack it, do not read it | | 4 | Accepting large changes because they look complete | 900-line PR merged after a skim | SUP-4: reject as too large | | 5 | Letting the agent write the spec and the code | Circular verification | The specification is a human artifact (§5) | | 6 | Approving because CI is green | Green means "no known check failed" | SUP-5 | | 7 | Blaming the model for a process failure | "Claude got it wrong" | §2.3.7 | | 8 | Never using agents on hazardous modules **at all** | Slow, and forfeits their best application | S5 permits — and encourages — agent-written tests | | 9 | Prompting for the whole feature at once | Drift, unreviewable diff | §3.4's limits | | 10 | Letting a session run for hours | Early constraints dropped | §4's session rules | ## 2.7 Anti-Patterns | ID | Anti-Pattern | Description | Countermeasure | |---|---|---|---| | **AP-09** | **Vibe Merging** | Approving because the code "looks right" and CI is green | SUP-5; V-1; cite the spec in the review | | **AP-10** | **The Oracle Fallacy** | Treating agent output as authoritative on facts about the world | AI-N1; verify every external API against its documentation | | **AP-11** | **Prompt Roulette** | Re-prompting repeatedly until the output looks acceptable, without understanding why earlier attempts failed | If two attempts fail, the specification is the problem (§3.7) | | **AP-12** | **Context Hoarding** | Feeding the entire codebase into every prompt | §4.5. More context is not better context | | **AP-13** | **Agent Sprawl** | Multiple agents working the same area concurrently | §19's ownership and locking rules | | **AP-14** | **The Confident Refactor** | An agent restructures for readability and changes behaviour | AI-N5; refactor and behaviour change are separate changes | | **AP-15** | **Test Laundering** | Tests generated from the implementation, then cited as verification | Tests derive from the specification; every new test must fail against the previous commit | | **AP-16** | **Accountability Diffusion** | Nobody can say who is responsible for a module | OWN-1; SUP-1 | ## 2.8 Decision Tables ### 2.8.1 Choosing a Supervision Level | Question | If Yes | |---|---| | Does it touch auth, payments, personal data, or secrets? | **S5** | | Is any effect irreversible (delete, publish, notify, charge)? | **S5** | | Does it enforce a safety property or a public contract? | **S5** | | Does it change data in a way that could be silently wrong? | **S4** minimum | | Does it involve concurrency, ordering, or time? | **S4** minimum | | Is it an integration with an external system? | **S3** minimum | | Does it implement documented business rules? | **S3** | | Is it ordinary feature work with tests? | **S2** | | Is it formatting, docs, or scaffolding with no behaviour? | **S1** | **When two rows apply, the higher level wins.** ### 2.8.2 Agent or Human? | Task Shape | Prefer | Why | |---|---|---| | Exhaustive test cases from a stated property | **Agent** | Tireless enumeration | | Designing the property itself | **Human** | Requires judgement about what matters | | Applying a long spec across many files | **Agent** | Recall and consistency | | Deciding the architecture in that spec | **Human** | Trade-offs, context, consequences | | Mechanical refactor with tests as a safety net | **Agent** | Fast and checkable | | Refactor without test coverage | **Human first** — write characterisation tests | Nothing verifies the agent | | Reproducing a known bug as a test | **Agent** | Mechanical once the cause is known | | Diagnosing an unknown production incident | **Human-led**, agent-assisted | Requires hypotheses about the real world | | Writing a changelog from a diff | **Agent** | Summarisation | | Deciding whether to ship | **Human** | Not a technical judgement alone | ### 2.8.3 When an Agent Should Stop and Ask | Situation | Action | |---|---| | The specification does not cover this case | **Stop. Ask.** | | Two parts of the specification appear to conflict | **Stop. Ask.** Do not reconcile them yourself | | A test and a requirement disagree | **Stop. Ask.** Never change the test | | The task requires a new dependency | **Stop. Ask.** | | The obvious implementation violates a stated rule | **Stop. Ask.** The rule usually has a reason | | The change is growing past the size limit | **Stop.** Propose a split | | You are about to modify a hazard module | **Stop. Ask.** | | You cannot tell whether existing code is intentional | **Stop. Ask.** Especially if it looks redundant | | You need information not in the provided context | **Ask for it.** Do not infer it | ## 2.9 Checklists ### CHK-2.1 · Agent Self-Check Before Proposing a Change - [ ] I implemented exactly the task described — nothing more - [ ] Every API, function, and configuration key I used exists in the codebase or its documentation - [ ] I did not weaken any test, type, or threshold - [ ] No error is swallowed; no failure path returns an empty result - [ ] Tests are included and each fails against the previous commit - [ ] I ran the full local verification and it passed - [ ] Refactoring, if any, is in a separate commit from behaviour change - [ ] No secret, credential, or realistic-looking placeholder appears anywhere - [ ] I have listed every assumption I made - [ ] I have listed everything I was uncertain about - [ ] The change is within the size limit - [ ] The PR names the specification implemented and how I verified it ### CHK-2.2 · Human Review of Agent Output - [ ] I have the specification open and have compared it to the diff - [ ] I constructed three adversarial inputs **before** reading the implementation, and checked each - [ ] Every external API used is real — I verified at least the unfamiliar ones - [ ] The failure paths are handled and tested, not just the happy path - [ ] No test was weakened, skipped, or deleted - [ ] No unrequested change is bundled in - [ ] The supervision level matches §2.8.1, and the required reviewers are present - [ ] I understand this change well enough to fix it at 3 a.m. - [ ] If it is a hazard module, the owner has reviewed it - [ ] **I am willing to own this** ## 2.10 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Fabricated API reaches production | Medium | High | AI-N1; failure-path tests; unfamiliar APIs verified against docs | Low | | Silent simplification of a safety branch | **Medium** | **Critical** | AI-N4; hazard module designation; property tests; two reviewers | **Medium — the residual risk of the whole model** | | Reviewer fatigue on large diffs | High | High | §3.4 size limits; SUP-4 reject-as-too-large | Medium | | Weakened test disables a guard permanently | Medium | High | AI-N2, AI-N12, SUP-6 | Low | | Accountability diffuses | Medium | High | OWN-2, SUP-1 | Low | | Over-restriction wastes agent capability | Medium | Medium | Tiers and supervision levels are proportional; S1/S2 are genuinely autonomous | Low | | Agent capability outgrows these rules | High | Low | §29's quarterly review of §2, §3, §4, §13, §19, §25 | Low | **The second row is the honest one.** No process fully eliminates the risk that a subtle safety property is silently removed by an agent optimising for clarity. The controls reduce it substantially; they do not reduce it to zero. That residual is why hazard modules exist, why they get two reviewers, and why property-based tests are mandatory on them. ## 2.11 Future Improvements | Item | When | Note | |---|---|---| | Automated detection of weakened tests in a diff | v1.1 | A change that reduces assertion count or coverage should be flagged automatically | | A hazard-module registry with enforced review rules | v1.1 | Currently a per-project document; should be repository metadata that CI reads | | Agent-defect taxonomy with measured frequencies | v1.2 | Track which of the eight mechanisms actually bites, and re-weight the rules | | Per-model capability profiles | Continuous | Different agents have different failure profiles; §29's quarterly review should record them | | Automated spec-to-test traceability | v1.2 | Would mechanise the check that every rule has a test | --- *End of Part 1. Part 2 covers prompt engineering standards and context management — the two disciplines that determine whether §2's rules are achievable in practice.* --- # Part 2 — Prompting and Context *Sections 3 and 4. These two disciplines determine whether §2's safety rules are achievable in practice. A perfect verification culture applied to output produced from a bad prompt is expensive rework; a well-formed prompt with managed context removes most of the defects before they exist.* --- # 3. Prompt Engineering Standards ## 3.1 Purpose To make the quality of AI-generated code a function of a repeatable process rather than of who happened to write the prompt. A prompt is a specification handed to a very fast implementer with no memory and no stake in the outcome. Vague specifications produce confident, plausible, wrong implementations — and they produce them quickly enough that several land before anyone notices the pattern. ## 3.2 Objectives 1. Define a standard prompt structure that every task prompt follows. 2. Establish size limits for scope, input, and output, with rationale. 3. Define token and context budgeting so that specification detail is never crowded out. 4. Provide templates that make a good prompt the path of least effort. 5. Establish what a prompt must *never* contain. 6. Make the difference between good and bad prompts concrete through side-by-side examples. ## 3.3 Engineering Rationale ### 3.3.1 A Prompt Is a Specification, and It Is Reviewable The single most useful reframing: **the prompt is the requirements document for that change.** Everything true of a good requirements document is true of a good prompt. | Requirements Document Property | Prompt Equivalent | |---|---| | States the outcome, not the implementation | Say what must be true when done, not how to type it | | Bounded in scope | One task | | States acceptance criteria | "This is done when…" | | States constraints explicitly | Purity, error handling, dependency rules, patterns to follow | | Names the authority | The spec section, the file, the ticket | | States what is out of scope | Prevents overreach (AI-N8) | | Is reviewable by a second person | If a colleague could not implement from it, an agent cannot either | **The corollary is the most useful heuristic in this section:** *if you cannot write the prompt, you do not yet understand the task.* Time spent making the prompt precise is not overhead; it is the design work, done in the cheapest medium available. ### 3.3.2 Why Structure Beats Eloquence Agents respond to structure more reliably than to prose. A structured prompt: - makes omissions visible — an empty "Constraints" heading is obviously wrong, a missing sentence in a paragraph is not; - survives context compaction better, because headings are anchors; - is diffable, so a failed prompt can be improved rather than rewritten; - is reusable as a template; - and separates the immutable (constraints) from the variable (the task), which is what makes templates possible. ### 3.3.3 Why Size Limits Exist Three independent reasons, all of which bite at different sizes: | Reason | Bites At | Mechanism | |---|---|---| | **Specification drift** | Long specs in one prompt | Attention over a long context is not uniform; middle rules get dropped (§2.3.2) | | **Review capacity** | Large diffs | Reviewer attention degrades sharply past a few hundred lines; defect detection falls off a cliff | | **Blast radius** | Many files | A change touching many modules cannot be reverted cleanly, and its failure is harder to attribute | Note that these limits are not about model capability. A capable model can hold a large specification. The limits exist because **the human verification step cannot scale with the generation step**, and verification is the binding constraint (§1.3.1). ### 3.3.4 Context Is a Budget, Not a Container Every token of context competes with every other token. Filling a window with "helpful" background actively degrades output by: - diluting the specification that actually governs the task; - introducing patterns from unrelated modules that the agent may imitate; - increasing the chance of instruction-recency effects dropping an early constraint; - and raising cost and latency for no benefit. **The correct mental model is a budget with line items**, not a bucket to fill. ## 3.4 Standards ### 3.4.1 The Standard Prompt Structure Every task prompt MUST contain these seven blocks, in this order. Blocks may be brief; none may be absent. | # | Block | Contains | Why It Is Mandatory | |---|---|---|---| | 1 | **TASK** | One sentence: the outcome required | Forces scope to one thing | | 2 | **CONTEXT** | Where this fits: the module, the project, why it is needed | Prevents locally-correct, globally-wrong solutions | | 3 | **SPECIFICATION** | The authoritative rules, or a precise pointer to them | This is the requirement. Everything else is support | | 4 | **CONSTRAINTS** | Patterns to follow, patterns forbidden, dependency rules, purity, error handling | Where project-specific rules go; the block agents most need | | 5 | **ACCEPTANCE** | "This is done when…" — testable statements | Turns opinion into verification | | 6 | **OUT OF SCOPE** | Explicitly what not to touch | The direct countermeasure to overreach (AI-N8) | | 7 | **OUTPUT** | What to produce: which files, what tests, what the PR should say | Removes ambiguity about the deliverable | ### 3.4.2 Size Limits | Dimension | Limit | Hard Ceiling | Rationale | |---|---|---|---| | **Tasks per prompt** | **1** | 1 | Non-negotiable. Two tasks produce an unreviewable diff | | **Specification input** | One document section, or ≤ ~6 pages | 10 pages | Beyond this, drift risk rises sharply | | **Files provided as context** | ≤ 5, plus the target | 10 | More than this and the agent imitates rather than implements | | **Total context used** | **≤ 40% of the window** | 60% | Leaves room for iteration, tool output, and the agent's own reasoning | | **Expected output** | ≤ 400 lines of diff | 600 | Review capacity, not model capacity | | **Files touched** | ≤ 5 | 10 | Blast radius and revertability | | **New public interfaces** | ≤ 2 | 3 | More than this is a design task, not an implementation task | | **Session length** | ≤ 2 hours or one task | See §4 | Recency effects accumulate | | ID | Rule | |---|---| | **PRM-01** | One task per prompt. MUST. | | **PRM-02** | If the expected output exceeds 400 diff lines, the task MUST be split before starting, not after | | **PRM-03** | Context usage MUST stay under 60% of the window; above 40% the agent SHOULD flag it | | **PRM-04** | A prompt MUST cite its authority — a spec section, a ticket, a file. "As discussed" is not an authority | | **PRM-05** | A prompt MUST state acceptance criteria that are checkable without asking the author | | **PRM-06** | A prompt MUST state what is out of scope when adjacent code is imperfect | ### 3.4.3 What a Prompt Must Never Contain | ID | Prohibition | Why | |---|---|---| | **PRM-N1** | Real secrets, tokens, keys, credentials, or production connection strings | They may be logged, retained, or echoed. Treat every prompt as potentially recorded | | **PRM-N2** | Real customer personal data | Use synthetic data. Always | | **PRM-N3** | "Do whatever you think is best" for anything above S1 | Delegates judgement that cannot be delegated (§2) | | **PRM-N4** | "Make it production-ready" without defining what that means | Unverifiable, therefore unmergeable (T-D) | | **PRM-N5** | "Fix all the issues you find" | Unbounded scope; guarantees an unreviewable diff | | **PRM-N6** | Contradictory constraints | The agent will silently pick one. State the precedence instead | | **PRM-N7** | An entire codebase pasted as context | AP-12. Provide contracts, not implementations | | **PRM-N8** | Instructions to bypass a project rule "just this once" | If the rule is wrong, amend it (§29). If it is right, follow it | ### 3.4.4 Token Management | Line Item | Typical Share | Guidance | |---|---|---| | Standing project rules (constraints, conventions) | 10–15% | Keep in a project instructions file, not re-pasted each time | | Task specification | 20–30% | The largest single item. Never compress this to make room for something else | | Code context (target + direct contracts) | 15–25% | Contracts and signatures, not full implementations of dependencies | | Test context | 5–10% | The test file being satisfied, if it exists | | Working headroom | **≥ 40%** | Iteration, tool output, reasoning. **Do not consume this** | | ID | Rule | |---|---| | **TOK-01** | Standing rules SHOULD live in a project instructions file that the tool loads automatically, not in each prompt | | **TOK-02** | Dependencies SHOULD be provided as contracts (names, inputs, outputs, errors) rather than full source | | **TOK-03** | When headroom falls below 40%, the agent SHOULD finish the current step, summarise, and start a fresh session (§4) | | **TOK-04** | Specification detail MUST NOT be trimmed to fit. Split the task instead | **Rationale for TOK-04.** Trimming the spec to fit more code context is exactly backwards: it removes the requirement to make room for examples of unrelated requirements. ## 3.5 Prompt Templates Templates are numbered `TMPL-` and the full library is §26. Two canonical forms are given here because they are the shapes every other template varies. ### TMPL-CORE-1 · Implementation Task ``` TASK Implement . CONTEXT Project: · Tier: · Module: This module is responsible for . It sits between and . Related work already merged: SPECIFICATION Authority: §, which is provided in full below / attached. The rules that govern this task are: 1. … 2. … Ambiguities you must not resolve yourself: CONSTRAINTS - Follow the existing pattern in ; do not introduce a new one - - Errors: use . Never swallow, never return empty on failure - Dependencies: do not add any - Style: the project's formatter and linter are authoritative; do not hand-format - ACCEPTANCE This is done when: - - - Tests exist for , and each fails against the current commit - The full local verification suite passes OUT OF SCOPE - Do not refactor , even though it needs it - Do not change - Do not add logging beyond OUTPUT - Modify: - Add: - Tests: - Then: report what you changed, what you assumed, and what you were unsure about ``` ### TMPL-CORE-2 · Investigation Task (No Code) ``` TASK Investigate . Do not modify any file. CONTEXT WHAT I NEED - The mechanism, stated as a causal chain - The specific file and line where it originates - Evidence for the conclusion — not a plausible story - Whether other code paths share the same defect CONSTRAINTS - Read only. Propose no fix in this session - If the evidence is insufficient, say so and state what would settle it - Distinguish clearly between what you observed and what you inferred OUTPUT 1. Mechanism 2. Evidence 3. Blast radius 4. Confidence, and what would raise it ``` **The read-only investigation prompt is one of the highest-value patterns in this handbook.** Separating diagnosis from repair prevents the most common debugging failure: fixing the first plausible cause and shipping it (§12). ## 3.6 Real-World Examples: Good vs Bad ### Example 1 — Feature Implementation ❌ **Bad** > Add pagination to the users endpoint. Why it fails: no page size, no default, no maximum, no ordering, no cursor-vs-offset decision, no behaviour for an invalid page, no acceptance criteria. The agent will choose all of these. It will choose plausibly. It will be a coin flip whether each choice matches what the API already does elsewhere — and inconsistency across endpoints is a defect that survives for years. ✅ **Good** > **TASK** Add cursor pagination to the users list endpoint. > **CONTEXT** Module `api/users`. All other list endpoints in this service already use cursor pagination; follow `api/orders` exactly. > **SPECIFICATION** Default page size 25, maximum 100. Requests above the maximum are a validation error, not a silent clamp. Cursor is opaque to the client. Ordering is by creation time descending, ties broken by id. An invalid cursor is a 400 with error code `INVALID_CURSOR`. > **CONSTRAINTS** Reuse the existing pagination helper; do not write a new one. No new dependencies. Follow the existing error-response shape. > **ACCEPTANCE** Tests cover: default size, explicit size, size above maximum (rejects), invalid cursor, empty result, exactly-one-page result, and stable ordering across pages when a record is inserted mid-iteration. > **OUT OF SCOPE** Do not change the response schema of individual user objects. Do not add filtering. > **OUTPUT** Modify the users handler; add tests alongside the existing endpoint tests. The difference is not length. It is that every decision an implementer would otherwise make silently has been made explicitly by the person accountable for it. ### Example 2 — Bug Fix ❌ **Bad** > The export is broken, fix it. ✅ **Good** > **TASK** Fix: CSV export produces an empty file when the result set exceeds 10,000 rows. > **CONTEXT** Reported in ticket 412. Reproduces reliably at 10,001 rows; works at 9,999. Started after the streaming change in PR 388. > **SPECIFICATION** Export must stream and must succeed for result sets up to 1,000,000 rows within the existing timeout. > **CONSTRAINTS** Diagnose before fixing — tell me the mechanism first. Do not change the export format. Do not raise the row limit as a workaround. > **ACCEPTANCE** A regression test at the boundary (10,000 and 10,001 rows) fails before the fix and passes after. Memory stays bounded. > **OUT OF SCOPE** The unrelated timezone handling in the same file. ### Example 3 — Refactoring ❌ **Bad** > Clean up this file, it's messy. Why it fails: "messy" is not a specification, no boundary is set, no behaviour-preservation constraint is stated, and no verification exists. This prompt reliably produces a large diff mixing genuine improvements with behaviour changes that pass the existing tests because the existing tests were weak. ✅ **Good** > **TASK** Extract the three validation blocks in the order handler into named functions in the same file. Behaviour must not change. > **CONTEXT** The handler is 240 lines; the validation logic is inline and duplicated across two branches. > **CONSTRAINTS** **Pure refactor.** No behaviour change of any kind. No new files. No signature changes to the handler. If you find a bug while refactoring, **stop and report it — do not fix it in this change**. > **ACCEPTANCE** All existing tests pass unchanged. The diff contains no new conditional and no changed conditional. Each extracted function has a single responsibility named in its identifier. > **OUT OF SCOPE** Everything else in the file. **The bolded constraint is the important one.** "If you find a bug, report it, do not fix it" preserves the single most valuable property of a refactor: that a reviewer can confirm behaviour is unchanged without re-verifying business logic. ### Example 4 — Testing ❌ **Bad** > Write tests for the discount calculator. ✅ **Good** > **TASK** Write unit tests for the discount calculator against the specification below. Do not read the implementation. > **SPECIFICATION** > **CONSTRAINTS** Derive every test from the specification, not from the code. Use the existing test builders. One logical assertion per test. Full-sentence test names describing behaviour. Include boundary cases at every stated threshold. > **ACCEPTANCE** Every rule has at least one test that would fail if the rule were removed. Boundary values are tested exactly at, one below, and one above each threshold. > **OUTPUT** Tests only. If a rule is ambiguous, list it rather than guessing. **"Do not read the implementation" is the entire point.** It is the countermeasure for test laundering (AP-15) and it is unavailable in any other engineering context. ### Example 5 — Architecture Review ❌ **Bad** > Is this a good design? ✅ **Good** > **TASK** Review the proposed design below against the criteria listed. Do not propose a rewrite. > **CONTEXT** > **CRITERIA** (1) Where does this fail at 10× current load? (2) Which component's failure has the largest blast radius? (3) What is the hardest thing to change later? (4) Which decisions are reversible and which are not? (5) What would a reviewer with a bias toward simplicity delete? > **CONSTRAINTS** Assume the technology choices are fixed. Assume the team is three engineers. Judge against the stated constraints, not against best practice in the abstract. > **OUTPUT** One paragraph per criterion. End with the single change you would make if you could make only one. ## 3.7 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Prompting before understanding | Multiple attempts, each subtly wrong | Write the acceptance criteria first. If you cannot, you are still designing | | 2 | Bundling tasks | Large diff, mixed concerns | PRM-01 | | 3 | Omitting constraints | Correct logic, wrong patterns, new dependency | The CONSTRAINTS block is not optional | | 4 | Omitting out-of-scope | Unrequested refactoring bundled in | State what not to touch when adjacent code is imperfect | | 5 | Pasting whole files as context | Diluted spec, imitated patterns | Contracts, not implementations (TOK-02) | | 6 | Re-prompting without diagnosing | Prompt roulette (AP-11) | After two failures, fix the *prompt*, not the attempt | | 7 | Specifying implementation instead of outcome | Fragile output; you did the work anyway | Say what must be true, not what to type | | 8 | Unverifiable acceptance | "Handles edge cases properly" | Name the edge cases | | 9 | Letting standing rules drift into prompts | Inconsistency across sessions | TOK-01: project instructions file | | 10 | Asking for code when you needed a decision | An implementation of the wrong approach | Use the investigation or review template first | ## 3.8 Anti-Patterns | ID | Anti-Pattern | Description | Countermeasure | |---|---|---|---| | **AP-17** | **The Wish** | "Build me a dashboard" — a product brief handed over as a task | §5 first. A task prompt implements a plan; it does not replace one | | **AP-18** | **The Kitchen Sink** | Every file, every doc, every past message pasted in | TOK-02, PRM-N7 | | **AP-19** | **The Moving Target** | Requirements changed mid-session, incrementally, by conversation | Stop. Re-specify. Start a fresh session (§4.4) | | **AP-20** | **Implicit Convention** | Assuming the agent knows the house style | Constraints block; project instructions file | | **AP-21** | **The Rubber Stamp Prompt** | "Looks good, ship it" as the review step | §2's review checklist | | **AP-22** | **Spec-by-Correction** | The specification emerges from correcting successive wrong outputs | Expensive and incomplete. Write it up front | ## 3.9 Decision Tables ### 3.9.1 How Much Specification Detail? | Task Type | Detail Required | |---|---| | Formatting, renaming, mechanical transform | Minimal — the transformation rule | | Extending an established pattern | Point at the exemplar; state the differences | | New business logic | **Complete rules**, every branch, every boundary | | Integration with an external system | Complete: contract, auth, error responses, retry semantics, rate limits | | Anything with money, time, or identity | **Exhaustive**, including what must *not* happen | | Bug fix | Reproduction, expected behaviour, and the constraint to diagnose before fixing | | Test writing | The specification only — **never** the implementation | ### 3.9.2 Split or Not? | Signal | Action | |---|---| | Expected diff > 400 lines | **Split** | | More than 5 files touched | **Split** | | The task sentence needs "and" | **Split** | | Two distinct acceptance criteria that could ship separately | **Split** | | Two independent specification sections | **Split** | | A refactor plus a behaviour change | **Always split** | | Interface change plus implementations | Split: interface first, merged, then implementations | ### 3.9.3 Which Template? | Need | Template | §26 Reference | |---|---|---| | Build something specified | TMPL-CORE-1 | TMPL-IMPL-01 | | Understand a failure | TMPL-CORE-2 | TMPL-BUG-01 | | Fix a diagnosed failure | — | TMPL-BUG-02 | | Change structure, not behaviour | — | TMPL-REFACTOR-01 | | Add tests | — | TMPL-TEST-01 | | Write or update docs | — | TMPL-DOC-01 | | Evaluate a design | — | TMPL-ARCH-01 | | Security review | — | TMPL-SEC-01 | | Performance work | — | TMPL-PERF-01 | | Migrate or upgrade | — | TMPL-MIG-01 | ## 3.10 Checklists ### CHK-3.1 · Before Sending a Task Prompt - [ ] Exactly one task - [ ] All seven blocks present - [ ] The specification is attached or precisely cited — not "as we discussed" - [ ] Acceptance criteria are checkable by someone else - [ ] Constraints name the patterns to follow and the dependency rule - [ ] Out-of-scope names the adjacent things not to touch - [ ] Expected output is under 400 diff lines and 5 files - [ ] No secrets, no real personal data - [ ] Context is under 40% of the window - [ ] I could hand this prompt to a competent stranger and get the right thing ### CHK-3.2 · When Output Is Wrong - [ ] Which block of my prompt failed to prevent this? (Almost always CONSTRAINTS or SPECIFICATION) - [ ] Was the specification actually complete, or did I assume? - [ ] Was the task too large? - [ ] Was there a contradiction the agent silently resolved? - [ ] Fix the **prompt**, not the output — then start a fresh session (§4.4) - [ ] If the same failure occurs twice, add it to the project instructions file - [ ] If it occurs across projects, propose a handbook amendment (§29) ## 3.11 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Under-specified prompt yields plausible wrong code | High | High | Seven-block structure; acceptance criteria; §2's verification | Medium | | Over-long prompt causes rule drift | Medium | High | Size limits; one task per prompt | Low | | Secrets or personal data entered into a prompt | Low | **Critical** | PRM-N1/N2; synthetic data; training | Low — but irreversible if it occurs | | Templates followed mechanically without thought | Medium | Medium | Templates carry rationale; review catches empty blocks | Medium | | Prompt quality varies by author | High | Medium | Templates; project instructions file; §26 library | Low | | Standards outpaced by tooling changes | High | Low | Quarterly review of §3 (§0.8.2) | Low | ## 3.12 Future Improvements | Item | When | Note | |---|---|---| | Prompt linting in the tool chain | v1.1 | Detect missing blocks before sending | | Measured prompt-defect correlation | v1.2 | Which missing block correlates with which defect class | | Per-project instruction file template | v1.1 | Standardise what belongs in it vs in a prompt | | Shared prompt history for recurring tasks | v1.1 | Prompts that produced good results become templates | --- # 4. Context Management ## 4.1 Purpose To govern what an agent knows at any moment, so that the governing specification is present, competing information is absent, and nothing important is silently lost when a session grows long or is compacted. Context failures are insidious because the output remains fluent. An agent that has lost the third constraint does not say so; it produces confident code that satisfies constraints one, two, and four. ## 4.2 Objectives 1. Define when to start a new session and when to continue an existing one. 2. Define how to transfer context between sessions without loss. 3. Define what a project summary must contain to be usable as a cold start. 4. Establish practices that prevent silent context loss. 5. Define what belongs in persistent project instructions versus per-task prompts. 6. Establish recovery when context has already degraded. ## 4.3 Engineering Rationale ### 4.3.1 The Three Kinds of Context | Kind | Lifetime | Where It Belongs | Failure If Lost | |---|---|---|---| | **Standing** — house rules, conventions, architecture, forbidden patterns | Permanent | A project instructions file the tool loads automatically | Every output violates conventions | | **Project** — current architecture, module map, decisions, in-flight work | Weeks–months | Project documents (§5) and a maintained state summary | The agent re-derives decisions and contradicts earlier ones | | **Task** — this specification, this file, this test | Minutes–hours | The prompt (§3) | This change is wrong | **Most context problems are a category error:** standing context re-pasted every session (wasteful, inconsistent), or project context left in a chat thread (lost the moment the session ends). ### 4.3.2 Why Sessions Degrade | Mechanism | Effect | Onset | |---|---|---| | **Recency weighting** | Later instructions dominate earlier ones | After ~10 exchanges | | **Accumulated wrong turns** | Abandoned approaches remain in context and get referenced | After any correction cycle | | **Compaction** | Summarisation drops the exact numbers, which *are* the requirement | At the window limit | | **Topic drift** | The session covers three tasks; constraints from task one bleed into task three | Whenever PRM-01 is violated | | **Correction accumulation** | Each correction is a new instruction, and the original spec recedes | After ~3 corrections | **The practical consequence:** a session that has needed three corrections is producing worse output than a fresh session with a better prompt, and continuing to correct it is usually slower than restarting. ### 4.3.3 The Cost Asymmetry of Restarting Engineers resist restarting because the session "knows things". The arithmetic says otherwise: | | Continue a degraded session | Start fresh with an improved prompt | |---|---|---| | Setup cost | 0 | 5–10 minutes | | Probability of correct output | Falling with each correction | High | | Risk of an early constraint being dropped | **High** | Low | | Reviewer cost | Higher — must check everything again | Normal | | What you keep | Confused context | The **lesson**, encoded in the prompt | **Restarting is not throwing work away. It is converting a failed attempt into a better specification** — which is the only durable output of a failed attempt anyway. ## 4.4 Standards ### 4.4.1 When to Start a New Session | ID | Rule | |---|---| | **CTX-01** | Start a new session for each task. MUST for T3+; SHOULD for all | | **CTX-02** | Start a new session after **three** corrections on the same task. The prompt is the problem | | **CTX-03** | Start a new session when switching modules or subsystems | | **CTX-04** | Start a new session after any compaction, unless the task is nearly complete | | **CTX-05** | Start a new session when the approach changes fundamentally — the abandoned approach is still in context | | **CTX-06** | Start a new session when context usage exceeds 60% mid-task | | **CTX-07** | Start a new session after a break longer than a working day | ### 4.4.2 When to Continue an Existing Session | Situation | Continue? | Note | |---|---|---| | Iterating on the same task, ≤ 3 corrections | ✅ Yes | The context is still an asset | | Adding tests to code just written in this session | ✅ Yes | Directly relevant context | | Fixing a review comment on this session's work | ✅ Yes | If small | | A closely related follow-up in the same module | ⚠️ Only if the first task is fully merged | Otherwise two unmerged changes share a context | | A new task in the same module | ❌ No | CTX-01 | | Same project, different module | ❌ No | CTX-03 | | After compaction | ❌ No | CTX-04 | | "It already understands the codebase" | ❌ **No** | This is the reasoning that causes the failure | ### 4.4.3 Context Transfer Between Sessions When a task genuinely spans sessions, transfer MUST be explicit and written. A handover MUST contain: | # | Element | Why | |---|---|---| | 1 | **Task statement** — restated, not referenced | The next session cannot follow a reference to a lost message | | 2 | **Specification pointer** — document and section | The authority | | 3 | **What is done** — with file paths | Prevents redoing merged work | | 4 | **What remains** — as concrete steps | The plan | | 5 | **Decisions made and why** | Prevents contradicting them | | 6 | **Approaches tried and rejected, with reasons** | Prevents re-trying them — the most commonly omitted item | | 7 | **Open questions** | Prevents silently resolving them | | 8 | **Current state** — branch, tests passing/failing, uncommitted work | Where to resume | | ID | Rule | |---|---| | **CTX-08** | A handover MUST be written to a file, not left in a chat. Chats are not durable | | **CTX-09** | Item 6 (rejected approaches) MUST be included. Omitting it causes the next session to repeat the loop | | **CTX-10** | The handover MUST be produced **before** the session ends, not reconstructed afterwards | ### 4.4.4 Project Summaries Every T2+ project MUST maintain a project state summary — a single document that lets a cold session become useful in one read. | Section | Contents | Update Cadence | |---|---|---| | What this project is | Two paragraphs, plain language | On scope change | | Conformance tier and why | T1–T4 (§0.3.3) | At inception | | Architecture in one diagram | The component map | On architectural change | | Module map | Path → responsibility → owner | On any new module | | **Hazard modules** | The S5 list (§2.4.3) | On any change | | Key decisions | ADR index with one-line summaries | On each ADR | | Conventions specific to this project | What differs from the handbook, and why | On change | | Current state | What works, what is in progress, what is known broken | **Weekly** | | Known sharp edges | The things that surprise newcomers | Continuously | | Where the specifications live | Document paths | On change | | ID | Rule | |---|---| | **CTX-11** | The project summary MUST be current within one week for active projects | | **CTX-12** | The summary MUST fit in roughly 10% of a typical context window. If it does not, it is a document, not a summary | | **CTX-13** | An agent starting cold on a project MUST read the summary first | | **CTX-14** | The summary MUST list the hazard modules. This is the single most important line for agent safety | ### 4.4.5 Preventing Context Loss | ID | Practice | Prevents | |---|---|---| | **CTX-15** | Persist decisions to files as they are made — never leave them only in a session | Total loss at session end | | **CTX-16** | Re-state critical constraints in each prompt even if they are in standing context | Recency displacement | | **CTX-17** | After compaction, **re-read the specification before continuing** | Summarised requirements have lost their numbers | | **CTX-18** | Commit working intermediate states on the task branch | Loss of work when a session fails | | **CTX-19** | Write the handover before you need it — at natural boundaries, not at the end | Reconstruction cost and omission | | **CTX-20** | Keep an explicit list of open questions in a file, not in the conversation | Silent resolution of ambiguity | **Agent Note on CTX-17.** After compaction you may feel you still understand the task. What has typically been lost is precision: the exact threshold, the exact ordering, the exact error class. Those are the requirement. Re-read. ### 4.4.6 Standing vs Task Context | Belongs in Standing (project instructions file) | Belongs in the Prompt | |---|---| | Language, runtime, and framework conventions | This task's specification | | Directory structure and what may live where | This task's acceptance criteria | | Error-handling mechanism | This task's out-of-scope list | | Testing conventions and locations | The specific files to modify | | Forbidden patterns (§24) | Task-specific constraints | | Commit and PR format | The exemplar file to follow | | Hazard module list | — | | Dependency policy | — | | ID | Rule | |---|---| | **CTX-21** | Standing context MUST live in a file the tool loads automatically, MUST be version-controlled, and MUST be reviewed like code | | **CTX-22** | Standing context SHOULD be under two pages. Beyond that it is not read reliably — by anyone | ## 4.5 Real-World Examples ### Example 1 — The Long Session An engineer spends four hours in one session implementing three related features. The first is excellent. The second is good. The third violates a convention stated at the start, imports a dependency that was forbidden in message two, and duplicates a helper written in the first hour. | | | |---|---| | Mechanism | Recency weighting and topic drift | | The tell | Quality degrading across a session is *always* a context problem, never a model problem | | Correct process | Three sessions, three prompts, three PRs (CTX-01) | ### Example 2 — Compaction Loss A session implementing a rules engine is compacted at the 80% mark. Afterwards the agent continues confidently. Two of eleven rules are now implemented with wrong thresholds — the summary preserved "validates against thresholds" and lost the numbers. | | | |---|---| | Mechanism | Summarisation loses precision | | What would have caught it | CTX-17 (re-read after compaction); CTX-04 (restart); tests derived from the spec | | The general lesson | **Numbers are the requirement. Prose about numbers is not** | ### Example 3 — The Undocumented Handover An engineer finishes for the day mid-task, intending to continue tomorrow. The next day, in a new session, the agent re-tries an approach that was already rejected — because the rejection existed only in yesterday's conversation. Two hours lost. | | | |---|---| | Mechanism | No handover; rejected approaches not recorded | | Rule | CTX-08, CTX-09, CTX-19 | ### Example 4 — Effective Cold Start A new agent session opens on a nine-month-old project. It reads the project summary (module map, hazard modules, conventions, current state, sharp edges), then the task's specification section. It produces a correct change in one pass. | | | |---|---| | Why it worked | Project context was in a file, not a conversation | | Cost of maintaining that file | ~15 minutes per week | | Value | Every cold start, for every agent and every new engineer, indefinitely | ## 4.6 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Treating the session as project memory | Knowledge vanishes when the session ends | CTX-15: persist to files | | 2 | Continuing because "it understands the codebase" | Quality degrades; conventions drift | CTX-01 | | 3 | Correcting five times instead of restarting once | Compounding confusion | CTX-02 | | 4 | Continuing after compaction without re-reading | Precision silently lost | CTX-04, CTX-17 | | 5 | Handover written from memory next morning | Rejected approaches omitted | CTX-19 | | 6 | Project summary written once, never updated | Confidently wrong context — worse than none | CTX-11 | | 7 | Standing rules pasted into every prompt | Inconsistency, wasted budget | CTX-21 | | 8 | Standing context grown to fifteen pages | Nobody reads it, including the agent | CTX-22 | | 9 | Open questions resolved in conversation, not recorded | The decision is lost | CTX-20 | | 10 | Multiple agents sharing one session | Interleaved, contradictory context | §19 | ## 4.7 Anti-Patterns | ID | Anti-Pattern | Description | Countermeasure | |---|---|---|---| | **AP-23** | **The Eternal Session** | One session for a whole project | CTX-01 | | **AP-24** | **Context Archaeology** | Scrolling back through a long chat to find a decision | CTX-15 | | **AP-25** | **Summary Rot** | A project summary that describes the system as it was | CTX-11; weekly update | | **AP-26** | **The Verbal Handover** | Context transferred by conversation between people | CTX-08 | | **AP-27** | **Instruction Sprawl** | Standing context grown until nobody reads it | CTX-22 | | **AP-28** | **The Lost Constraint** | An early rule silently dropped mid-session | CTX-16; restart | ## 4.8 Decision Tables ### 4.8.1 New Session or Continue? | Signal | Decision | |---|---| | New task | **New** | | Different module | **New** | | Third correction on the same task | **New** | | Context compacted | **New** | | Approach changed fundamentally | **New** | | Context above 60% | **New** | | More than a day since the last message | **New** | | Small iteration on the current task | Continue | | Adding tests to code just written | Continue | | Addressing a review comment on this work | Continue | ### 4.8.2 Where Does This Information Live? | Information | Location | Lifetime | |---|---|---| | "We use X pattern for Y" | Project instructions file | Permanent | | "This module must stay pure" | Project instructions + restated in the prompt | Permanent | | "We rejected approach Z because…" | ADR | Permanent | | "The current sprint is doing A" | Project summary, current state | Weeks | | "This task requires B" | Prompt | Minutes | | "I tried C and it failed because D" | Handover file, then discarded | Hours | | "This threshold is 0.92" | **Specification document** | Permanent | | "The build is broken on main" | Team channel | Hours | ## 4.9 Checklists ### CHK-4.1 · Starting a Session on an Existing Project - [ ] Read the project summary - [ ] Note the hazard modules - [ ] Read the specification section for this task - [ ] Confirm which conventions differ from the handbook - [ ] Confirm the branch and current state - [ ] Confirm the task is the only task for this session ### CHK-4.2 · Ending a Session Mid-Task - [ ] Handover file written, containing all eight elements (§4.4.3) - [ ] **Rejected approaches recorded with reasons** - [ ] Open questions recorded in a file - [ ] Work-in-progress committed to the task branch - [ ] Decisions made are persisted to the right documents, not just the handover - [ ] Test state noted: what passes, what fails, what is not yet written ### CHK-4.3 · Weekly Project Summary Maintenance - [ ] Current state reflects reality as of today - [ ] New modules added to the module map with owners - [ ] Hazard module list still correct - [ ] New ADRs indexed - [ ] Newly discovered sharp edges recorded - [ ] Still under the size limit (CTX-12) ## 4.10 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Silent constraint loss mid-session | **High** | High | CTX-01, CTX-16, restart discipline | Medium | | Precision lost at compaction | High | High | CTX-04, CTX-17 | Low | | Project summary rots and misleads | Medium | High | CTX-11, weekly checklist | Medium | | Handover omits rejected approaches | High | Medium | CTX-09 as an explicit element | Low | | Standing context grows unread | Medium | Medium | CTX-22 size limit; reviewed like code | Low | | Engineers resist restarting sessions | High | Medium | §4.3.3's arithmetic; make it normal, not a failure | Medium | ## 4.11 Future Improvements | Item | When | Note | |---|---|---| | Automated project summary staleness warning | v1.1 | Flag when the summary predates the last N commits | | Handover template as a repository file | v1.1 | Reduce the cost of CTX-08 to near zero | | Context usage telemetry | v1.2 | Correlate degradation with measured usage rather than intuition | | Standing-context linting | v1.2 | Detect contradictions between the instructions file and the handbook | --- *End of Part 2. Part 3 covers what must exist before any of this begins: the planning documents.* --- # Part 3 — Planning Before Coding *Section 5. The single highest-leverage section in this handbook. Every hour spent here saves between five and fifty hours later, and the multiplier rises with the amount of AI-assisted implementation, because an agent will implement a bad plan flawlessly and at speed.* --- # 5. Planning Before Coding ## 5.1 Purpose To ensure that before implementation begins, someone has decided *what* is being built, *why*, *how*, and *in what order* — and written it down in a form that a human or an agent can implement from without asking a clarifying question. The failure this prevents is specific and expensive: a team builds the wrong thing correctly. Nothing in code review, testing, or deployment catches that. Only planning does. ## 5.2 Objectives 1. Define the mandatory planning documents per conformance tier. 2. Define what each document answers, and what it must not contain. 3. Establish the sequence and the gates between documents. 4. Make the documents *implementable* — precise enough for an agent, short enough to be read. 5. Establish risk assessment as a planning output, not a retrospective activity. 6. Define the project-level Definition of Done before work begins, not after. 7. Prevent both under-planning (the common failure) and over-planning (the reaction to it). ## 5.3 Engineering Rationale ### 5.3.1 Why Planning Matters More With AI, Not Less The intuitive argument is that agents make planning less necessary — they can figure things out. The opposite is true, for four reasons: | Reason | Mechanism | |---|---| | **Implementation is no longer the bottleneck** | When coding was slow, planning competed with it for time. It no longer does. The bottleneck is deciding correctly and verifying | | **Agents do not push back** | A human handed a contradictory spec asks a question. An agent resolves it silently and plausibly | | **Wrong work is produced faster** | Three days of wrong implementation now takes three hours, but still takes three days to unwind | | **Verification requires a reference** | You cannot check output against a specification that does not exist. Without a plan, review degrades to "does this look reasonable?" — AP-09 | **The sharpest formulation:** *an agent is a machine that turns specifications into code. If the specification is in someone's head, the machine cannot reach it, and what it produces instead is a guess with good grammar.* ### 5.3.2 The Four Questions, and Why They Are Separate Documents | Document | Question | Author | Changes When | |---|---|---|---| | **PRD** | *What are we building, for whom, and why?* | Product / EM | The user need changes | | **SAD** | *What is the system, and why is it shaped that way?* | Architect | The architecture changes | | **TRD** | *How exactly is it built?* | Lead engineer | The implementation approach changes | | **Implementation Plan** | *In what order, by when, verified how?* | Lead / TPM | The schedule or sequence changes | They are separate because they have **different authors, different audiences, different change rates, and different review cycles.** Merging them produces a document that is simultaneously too detailed for stakeholders and too vague for implementers, and that must be re-approved by everyone whenever anything changes. ```mermaid flowchart LR IDEA(["Idea"]) --> PRD["**PRD**
what & why
*users, outcomes*"] PRD -->|"gate: is this worth building?"| SAD["**SAD**
what the system is
*components, decisions*"] SAD -->|"gate: is this the right shape?"| TRD["**TRD**
how exactly
*files, contracts, rules*"] TRD -->|"gate: is this implementable?"| IMPL["**Impl Plan**
order, dates, gates
*tasks, milestones*"] IMPL -->|"gate: can we commit?"| BUILD(["Build"]) RISK["**Risk Assessment**"] -.-> PRD RISK -.-> SAD RISK -.-> IMPL DOD["**Definition of Done**"] -.-> IMPL style PRD stroke-width:2px style SAD stroke-width:2px ``` ### 5.3.3 The Cost Curve of Deciding Late | Decision Changed At | Relative Cost | Why | |---|---|---| | In the PRD | **1×** | Editing a paragraph | | In the SAD | **5×** | Redrawing a component boundary | | In the TRD | **20×** | Re-specifying contracts and rules | | During implementation | **100×** | Rewriting code and its tests | | After release | **1,000×+** | Migration, compatibility, communication, trust | **This curve is why planning gates exist and why they are worth defending.** It is also why the correct response to "we don't have time to plan" is: "then we have decided to pay 20× for the decisions we are about to make." ### 5.3.4 The Over-Planning Failure Under-planning is the common failure; over-planning is the over-correction, and it is also expensive. Symptoms: | Symptom | Diagnosis | |---|---| | The plan specifies things nobody has evidence about | Speculative design. Cut it | | The document is written for approval rather than for implementation | Ceremony. Ask who will read it while typing | | Every section is filled because the template has it | Template compliance. Empty sections are legitimate | | Planning has exceeded 15% of the estimated build effort (T3) | Diminishing returns | | The plan is being refined rather than tested against reality | Build a spike; learn something real | **The test that distinguishes them:** *will an implementer read this section while working?* If yes, it earns its place. If it exists to demonstrate diligence, delete it. ### 5.3.5 Planning Depth by Tier | Tier | PRD | Architecture | TRD | Impl Plan | Risk | Typical Planning Effort | |---|---|---|---|---|---|---| | **T1** | ❌ | ❌ | ❌ | ❌ | ❌ | A sentence in the commit | | **T2** | **1 page** | **1 diagram + 1 page** | ❌ (folded into the plan) | **1 page: ordered task list** | Top 3 risks | ~half a day | | **T3** | **Full** | **Full** | **Full or folded**, by complexity | **Full** | **Full register** | 5–15% of build effort | | **T4** | **Full** | **Full + threat model** | **Full** | **Full + gates** | **Full + security review** | 15–25% of build effort | **Agent Note.** If you are asked to implement something at T2 or above and the corresponding documents do not exist, **say so and stop**. Producing code against an absent specification is the failure this whole section prevents. Offer to help write the plan instead — that is a legitimate and valuable use of an agent. ## 5.4 Standards — The Documents ### 5.4.1 PRD — Product Requirements Document **Answers:** what are we building, for whom, why, and how will we know it worked? | Section | Contents | Notes | |---|---|---| | Problem | The problem, in the user's language, with evidence | If there is no evidence, say so explicitly | | Users | Who, and what they are trying to accomplish | Roles, not demographics | | Goals | 3–5 outcomes, each measurable | "Fast" is not a goal; "p95 under 300 ms" is | | Non-goals | **What this deliberately does not do** | The most valuable section; prevents scope creep for the project's whole life | | Requirements | Numbered, testable, prioritised | Each one testable, or it is a wish | | Success metrics | How we will know, and when we will check | With the threshold that would mean failure | | Constraints | Budget, deadline, compliance, platform | Real constraints only | | Open questions | With owners and dates | Better recorded than resolved by assumption | | **Conformance tier** | T1–T4 with justification | §0.3.3. Drives everything downstream | | ID | Rule | |---|---| | **PLAN-01** | Every requirement MUST be testable. If nobody can say how it would be verified, it is not a requirement | | **PLAN-02** | The non-goals section MUST NOT be empty for T3+ | | **PLAN-03** | The PRD MUST NOT specify implementation. "Uses a queue" belongs in the SAD | | **PLAN-04** | The conformance tier MUST be recorded here and MUST NOT be lowered later without a waiver | ### 5.4.2 SAD — Software Architecture Document **Answers:** what is the system, what are its parts, and why is it shaped this way? | Section | Contents | |---|---| | Context | The system's boundary: what is inside, what is outside, who talks to it | | Quality attributes | Ranked. Reliability vs latency vs cost vs simplicity — **ranked, because they conflict** | | Architecture overview | The component map; one diagram that fits on a screen | | Components | Each: responsibility, dependencies, and **what it explicitly does not do** | | Data model | The entities and their relationships; the durable ones | | Key flows | 3–5 sequences that show how the parts cooperate | | **Decisions (ADRs)** | Each with alternatives considered and the reason each was rejected | | **Invariants** | The properties that must always hold, with the mechanism enforcing each | | Non-functional design | How reliability, security, and performance are achieved structurally | | Risks | Architectural risks and their mitigations | | Out of scope | What the architecture deliberately does not address | | ID | Rule | |---|---| | **PLAN-05** | Quality attributes MUST be **ranked**, not listed. An unranked list is not a decision | | **PLAN-06** | Every significant decision MUST be an ADR recording the **rejected alternatives and why** | | **PLAN-07** | T3+ MUST state system invariants and, for each, the mechanism that enforces it | | **PLAN-08** | Every component MUST state what it does **not** do | | **PLAN-09** | The architecture MUST be expressible in one diagram that fits on one screen. If it cannot, it is too complex or insufficiently understood | **Rationale for PLAN-07.** An invariant without an enforcing mechanism is a hope. Stating both turns architecture into something testable: for each invariant, there is a test, and the traceability from invariant to test is the audit trail that the system is actually safe rather than believed safe. **Rationale for PLAN-06.** The rejected alternatives are the valuable part. Six months later, someone will propose the alternative. Without the record, the team re-litigates it from scratch; with it, the conversation is thirty seconds long — or, if circumstances have genuinely changed, a well-informed reversal. ### 5.4.3 TRD — Technical Requirements Document **Answers:** how exactly is this built? The level at which an implementer needs no clarification. | Section | Contents | |---|---| | Folder structure | Complete, normative. Where every kind of file lives | | File responsibilities | Per file: what it owns, what it does not, its purity, its verification | | Interfaces / contracts | Inputs, outputs, errors, side effects, idempotence — as **tables**, not signatures | | Data schemas | The authoritative shapes, versioned | | Algorithms | Step-numbered where order is normative | | Configuration | Every key, type, default, ceiling, and meaning | | Error taxonomy | Every failure class with severity, scope, and handling policy | | Validation rules | Every rule, with its threshold and the behaviour at the boundary | | Testing requirements | What must be tested and to what standard | | Environment | Runtime, dependencies, and their justification | | ID | Rule | |---|---| | **PLAN-10** | Contracts MUST be specified as tables (name, inputs, outputs, errors, purity, idempotence), not as code | | **PLAN-11** | Every threshold MUST state its exact value and the boundary behaviour | | **PLAN-12** | Every error class MUST be enumerated with severity and handling policy | | **PLAN-13** | Where order is normative, it MUST be stated as normative, with the reason | | **PLAN-14** | The TRD MUST NOT contain application code. Data, schemas, and configuration instances are specification artifacts; logic is not | **Rationale for PLAN-14.** Code in a specification becomes the implementation by copy-paste, and then the specification and the code drift as one is updated and the other is not. Contract tables cannot be copy-pasted into a codebase, which forces the implementer to *understand* rather than transcribe — and understanding is what verification depends on. **Rationale for PLAN-13.** Ordering constraints are invisible in code. An implementer who does not know that step 3 must precede step 5 will reorder them for readability, and the resulting defect passes every test that was written by someone with the same misunderstanding. ### 5.4.4 Implementation Plan **Answers:** in what order, by when, verified how, and abandoned how? | Section | Contents | |---|---| | Build order | Phases, dependency-ordered, with the reason for the order | | Dependency graph | What blocks what | | Milestones | Each independently demonstrable, with a demo command | | Task breakdown | Each with ID, description, dependencies, estimate, acceptance, verification, rollback | | Quality gates | What must be green before each phase closes | | Risk register | Execution risks with owners and triggers | | Critical path | The chain that sets the end date | | Decision gates | Scheduled go/no-go points with chairs | | Rollback | Per phase: how to undo it | | ID | Rule | |---|---| | **PLAN-15** | The build order MUST be dependency-ordered, and the ordering rationale MUST be recorded | | **PLAN-16** | Every milestone MUST be independently demonstrable | | **PLAN-17** | Every task MUST have acceptance criteria and a verification step | | **PLAN-18** | Every phase MUST state its rollback strategy **before** it starts | | **PLAN-19** | Safety mechanisms MUST be built before the things they guard | **Rationale for PLAN-19.** This is the most consequential sequencing rule in the handbook. If the validator is built after the thing that produces data, the producer's tests are written against unvalidated output, and the validator is retrofitted into a system that already works without it — at which point it is a formality rather than a gate. Build the thing that says *no* first. ### 5.4.5 Risk Assessment Produced during planning, maintained through the project. Not a document written once. | Column | Contents | |---|---| | ID | Stable identifier | | Risk | One sentence, stated as a thing that could happen | | Category | Technical / business / security / operational / dependency / people | | Likelihood | 1–5 | | Impact | 1–5 | | Exposure | L × I | | Mitigation | What reduces likelihood or impact — **structural if possible** | | **Trigger** | The observable event that means this is happening | | Contingency | What we do when the trigger fires | | Owner | A person | | ID | Rule | |---|---| | **PLAN-20** | Every risk MUST have a named owner and an observable trigger. A risk without a trigger is a worry | | **PLAN-21** | Risks MUST be re-scored at each milestone, not merely re-read | | **PLAN-22** | Structural mitigations MUST be preferred over procedural ones | | **PLAN-23** | T4 projects MUST include a threat model (§15) in the risk assessment | **Rationale for PLAN-22.** "We will be careful" is a procedural mitigation and it degrades under pressure. "The alerting job has no write permission to data" is structural: it holds when everyone is tired. Whenever a risk can be eliminated by structure rather than discipline, that is the correct mitigation. ### 5.4.6 Definition of Done — Project Level Written **before** implementation begins. §10 governs the per-change DoD; this is the project's completion definition. | Dimension | Example Criterion | |---|---| | Functional | Every P0 requirement demonstrably met | | Quality | Coverage thresholds met; all gates green | | Performance | Stated budgets met under stated load | | Security | Review complete; no unresolved high findings | | Documentation | README, architecture, runbooks, API docs complete | | Operational | Monitoring, alerts, health checks live; runbooks drilled | | Deployment | Deployed via the standard pipeline; rollback tested | | Handover | An owner exists; someone else has run the runbooks | | ID | Rule | |---|---| | **PLAN-24** | The project DoD MUST be written before implementation and MUST NOT be weakened afterwards | | **PLAN-25** | Every DoD criterion MUST be objectively checkable | | **PLAN-26** | "Rollback tested" MUST mean executed at least once, not documented | ## 5.5 Standards — The Process ### 5.5.1 The Planning Sequence and Its Gates | # | Step | Output | Gate | Who Decides | |---|---|---|---|---| | 1 | Frame the problem | Problem statement, evidence, tier | Is this worth solving? | EM | | 2 | Write the PRD | PRD | Are the requirements testable and bounded? | EM + lead | | 3 | Explore approaches | 2–3 options with trade-offs | Have we considered a genuinely simpler option? | Architect | | 4 | Write the architecture | SAD + ADRs | Is this the simplest shape that meets the quality attributes? | Architect | | 5 | Assess risk | Risk register | Are the top risks mitigated structurally? | Lead + EM | | 6 | Write the TRD | TRD | Could an implementer build this without asking a question? | Lead | | 7 | Plan implementation | Impl plan | Is the order dependency-correct and are gates defined? | Lead + TPM | | 8 | Define done | Project DoD | Is every criterion checkable? | EM + lead | | 9 | **Commit** | Baseline | Can we commit to this? | EM | | ID | Rule | |---|---| | **PLAN-27** | Step 3 MUST produce at least two options. A single option is a preference, not a decision | | **PLAN-28** | Documents MUST be baselined at step 9. After baseline, changes go through change control | | **PLAN-29** | Implementation MUST NOT begin before step 9 for T3+ | | **PLAN-30** | A spike MAY precede any step to reduce uncertainty, and MUST be time-boxed and thrown away | **Rationale for PLAN-30.** Spikes are the correct answer to "we cannot plan this because we do not know X". A time-boxed, disposable spike converts an unknown into a fact for a bounded cost. The rule that it is thrown away is what stops a spike from becoming the implementation — which is how unplanned code enters a planned project. ### 5.5.2 Baselining and Change Control | ID | Rule | |---|---| | **PLAN-31** | Baselined documents MUST be version-controlled alongside the code | | **PLAN-32** | A change to a baselined document MUST record what changed, why, and the impact | | **PLAN-33** | Where a document and the code disagree, **stop**. One of them is wrong, and deciding which is a decision, not an assumption | | **PLAN-34** | An implementer who finds a specification gap MUST raise it, not fill it (§2, AI-05) | ## 5.6 Real-World Examples ### Example 1 — The Missing Non-Goal A team builds an internal analytics tool. The PRD lists what it does. Six months later it has grown export, scheduling, alerting, and user management, because each was "a small addition" and nothing said it should not. | | | |---|---| | Root cause | No non-goals section | | Cost | The tool is now a product with no product owner and no roadmap | | Rule | PLAN-02 | | The fix that would have worked | One line: "This does not send notifications and does not manage users." | ### Example 2 — The Unranked Quality Attributes An architecture lists "fast, reliable, cheap, simple" as goals. During implementation, every trade-off becomes an argument, because all four are equally sanctioned and they conflict pairwise. | | | |---|---| | Root cause | Attributes listed, not ranked | | Symptom | Repeated design debates that end in whoever argues longest | | Rule | PLAN-05 | | The fix | "Reliability > simplicity > cost > latency." Now every trade-off has an answer | ### Example 3 — The Specification That Was Not Implementable A TRD says the system should "validate input appropriately and handle errors gracefully". Three engineers implement three different validation regimes. An agent implements a fourth. All four pass review, because there is nothing to review against. | | | |---|---| | Root cause | Unfalsifiable requirements | | Rule | PLAN-01, PLAN-11, PLAN-12 | | The test that would have caught it | "Could an implementer build this without asking a question?" — step 6's gate | ### Example 4 — The Order That Was Wrong A project builds its data ingestion, storage, and API. The validation layer is planned last, "once we know what the data looks like". By the time it is built, three modules already depend on unvalidated data shapes and two of them work around known-bad records. | | | |---|---| | Root cause | The safety mechanism was built after the things it guards | | Rule | PLAN-19 | | Cost | Retrofitting validation required changing three modules and re-deriving all test fixtures | ### Example 5 — Planning That Paid For Itself A project spends two weeks on architecture and specification before writing code. The specification names ten invariants, each with an enforcing test, and the build order puts the safety mechanisms first. Implementation proceeds with almost no clarifying questions, and agents implement most of the mechanical work correctly on the first pass. | | | |---|---| | Why it worked | The agent had a specification to implement rather than a goal to interpret | | Measured effect | Rework was concentrated in the two modules whose specifications were weakest — which is exactly what the theory predicts | | The lesson | Specification quality determines agent output quality more than any other single factor | ## 5.7 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Starting with code because it feels productive | Three rewrites of the same module | The first version is a spike; time-box it and throw it away (PLAN-30) | | 2 | Merging PRD and TRD | Stakeholders confused; implementers under-served | Separate documents, separate audiences | | 3 | Requirements that are not testable | Endless "is this done?" | PLAN-01 | | 4 | Skipping alternatives | Fragile design, no defence when challenged | PLAN-27 | | 5 | Planning to completeness before starting | Weeks of documentation, no learning | §5.3.4's test; spikes for unknowns | | 6 | Risks listed, never triggered | Risk register as decoration | PLAN-20's observable trigger | | 7 | DoD written at the end | It describes what was built | PLAN-24 | | 8 | Documents that live outside version control | Drift, no history, no review | PLAN-31 | | 9 | Filling every template section | Ceremony | Empty sections are legitimate; delete them | | 10 | Not re-planning when reality changes | The plan becomes fiction; people stop reading it | Change control (PLAN-32), not abandonment | ## 5.8 Anti-Patterns | ID | Anti-Pattern | Description | Countermeasure | |---|---|---|---| | **AP-29** | **Plan-Shaped Prose** | A document that reads like a plan and specifies nothing checkable | Every statement must be verifiable | | **AP-30** | **The Big Design Up Front** | Every detail specified before any learning | Spikes; tier-appropriate depth | | **AP-31** | **The Retro-Spec** | Documentation written after implementation to satisfy process | It records what was built, not what should have been. Worthless as a check | | **AP-32** | **Requirements by Ticket** | The specification is fifty tickets with no coherent whole | Tickets are tasks, not specifications | | **AP-33** | **The Immutable Plan** | Reality changed; the plan did not | Change control, not abandonment | | **AP-34** | **Estimate as Commitment** | An estimate hardens into a deadline without scope adjustment | Estimates have confidence bands; scope is the variable | | **AP-35** | **The Absent Owner** | Documents with no named owner | Every document names one | ## 5.9 Decision Tables ### 5.9.1 Which Documents Does This Project Need? | Question | If Yes | |---|---| | Will it live less than 30 days and touch nothing durable? | T1 — a commit message | | Is it internal, small, and recoverable? | T2 — 1-page PRD, 1 diagram, ordered task list | | Do external users depend on it? | T3 — full set | | Does it touch money, credentials, or personal data? | T4 — full set + threat model + security review | | Is it a rewrite of something that exists? | Full set **plus** characterisation of current behaviour (§21) | | Is it a spike? | None — time-box it, write findings, throw the code away | ### 5.9.2 How Detailed Should the Specification Be? | Factor | More Detail | Less Detail | |---|---|---| | Implementer | An agent, or someone new | The author, in the next hour | | Failure mode | Silent or irreversible | Loud and cheap | | Domain rules | Many, subtle, interacting | Few and obvious | | Reversibility | Hard to change later | Easy | | Longevity | Years | Weeks | | Coupling | Many dependents | Isolated | **When the implementer is an agent, always move one step toward more detail.** Agents do not ask the clarifying question a human would. ### 5.9.3 Build, Buy, or Do Without? | Criterion | Build | Buy / Adopt | Do Without | |---|---|---|---| | Is it core to what makes TradyPerch valuable? | ✅ | ❌ | — | | Is a good, maintained option available? | — | ✅ | — | | Would building it take under ~200 lines? | ✅ | ❌ | — | | Does it introduce a dependency on an external party's roadmap? | ✅ prefer build | ⚠️ weigh it | — | | Does the requirement have evidence behind it? | — | — | ❌ if no evidence | | Is there a recurring cost? | ✅ prefer build | ⚠️ | — | | Does it handle credentials or personal data? | ⚠️ raise to T4 | ⚠️ due diligence | — | ## 5.10 Checklists ### CHK-5.1 · Before Writing Any Code (T2+) - [ ] The problem is written down and someone other than the author agrees with it - [ ] The conformance tier is chosen and recorded - [ ] Requirements exist and every one is testable - [ ] Non-goals are written down - [ ] At least two approaches were considered, and the rejection reasons are recorded - [ ] The architecture fits in one diagram - [ ] Invariants are stated, each with an enforcing mechanism (T3+) - [ ] Hazard modules are identified (§2.4.3) - [ ] The build order is dependency-correct and **safety mechanisms come first** - [ ] Every task has acceptance criteria - [ ] The top risks have owners and observable triggers - [ ] The project DoD is written - [ ] Rollback is defined for each phase - [ ] Documents are in version control ### CHK-5.2 · Specification Quality Review - [ ] Could an implementer build this without asking a question? - [ ] Is every threshold a number with stated boundary behaviour? - [ ] Is every error case enumerated? - [ ] Is every ordering constraint stated as normative, with its reason? - [ ] Does every component state what it does **not** do? - [ ] Are there any unfalsifiable statements ("appropriately", "gracefully", "as needed")? Remove them - [ ] Are there contradictions between sections? - [ ] Is there anything specified that has no evidence of being needed? ### CHK-5.3 · Planning Gate (step 9) - [ ] All tier-required documents exist and are baselined - [ ] Open questions have owners and dates, or are resolved - [ ] The estimate has a stated confidence band - [ ] The critical path is identified - [ ] Decision gates are scheduled with named chairs - [ ] The cut list is written **before** pressure exists - [ ] Someone who did not write the plan has read it and could implement from it ## 5.11 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Planning skipped under time pressure | **High** | **High** | Tier requirements; the cost curve in §5.3.3; gates | Medium | | Documents written for approval, not implementation | Medium | High | CHK-5.2's first question; empty sections permitted | Medium | | Over-planning delays learning | Medium | Medium | Spikes; tier-appropriate depth; the 15% guideline | Low | | Documents drift from the code | High | Medium | Version control; PLAN-33 stop rule; docs ship with changes | Medium | | Requirements unfalsifiable | Medium | High | PLAN-01; review checklist | Low | | Risk register becomes decoration | High | Medium | Observable triggers; re-scoring at milestones | Medium | | Plan treated as immutable | Medium | Medium | Change control process | Low | ## 5.12 Future Improvements | Item | When | Note | |---|---|---| | Document templates in a repository | v1.1 | Reduce the cost of doing it right to near zero | | Automated specification linting | v1.2 | Detect unfalsifiable language ("appropriately", "as needed") | | Planning-effort telemetry | v1.2 | Measure actual planning share vs rework, per tier | | A worked example set from real TradyPerch projects | Continuous | The most useful teaching artifact; add one per project | | Spec-to-test traceability tooling | v1.2 | Mechanise the check that every requirement has a test | --- *End of Part 3. Part 4 covers repository and Git standards — the substrate everything else is built on.* --- # Part 4 — Repository and Git Standards *Sections 6 and 7. The substrate. Every other standard in this handbook is enforced through, or recorded in, the repository. A repository that is inconsistent, unnavigable, or has an untrustworthy history makes every downstream discipline harder — and makes agent contributions markedly worse, because an agent's first act on any project is to infer conventions from what it sees.* --- # 6. Repository Standards ## 6.1 Purpose To make every TradyPerch repository navigable by someone — human or agent — who has never seen it, within minutes, and to make the location of any given kind of file predictable without asking. ## 6.2 Objectives 1. Standardise repository naming so that a repository's purpose is evident from its name. 2. Standardise folder hierarchy so that "where does this file go?" has one answer. 3. Give a decision framework for monorepo versus polyrepo, rather than a default that is applied thoughtlessly. 4. Standardise the README so that the first ninety seconds in a repository are productive. 5. Define versioning so that consumers can reason about compatibility. 6. Make convention discoverable, because agents infer conventions from structure far more strongly than from documentation. ## 6.3 Engineering Rationale ### 6.3.1 Structure Is the Highest-Bandwidth Documentation A newcomer forms a model of a codebase from its directory tree before reading a line of prose. That model determines where they look, what they assume, and where they put new code. This is even more true of agents, which reason strongly from the immediate structural context. **Consequences:** - A consistent tree across projects means the model transfers between them. - A directory whose name states a rule (`domain/`, `adapters/`, `internal/`) enforces that rule better than a paragraph in a document nobody opens. - A misplaced file teaches the next person — and the next agent — that placement is arbitrary, and the structure decays from there. ### 6.3.2 Why Naming Deserves Rules Repository names are permanent in practice: they appear in URLs, CI configuration, deployment targets, documentation, and bookmarks. Renaming is possible and always more disruptive than expected. Ten minutes of thought at creation is worth it. A name should answer: *what is this, and what kind of thing is it?* Nothing else. ### 6.3.3 Monorepo vs Polyrepo Is a Coupling Decision The debate is usually conducted as a matter of taste. It is not; it is a question about **coupling and release cadence**. | If… | Then | |---|---| | Components must change together and release together | **Monorepo.** Atomic cross-component changes are the whole point | | Components release independently at different cadences | **Polyrepo.** A shared repository forces coordination that does not otherwise exist | | Components share substantial code | Monorepo, or a published shared package | | Components have different access requirements | **Polyrepo.** Access control is per repository | | The team is small and the components are few | Monorepo — less overhead, less duplication of tooling | | Components have genuinely different lifecycles or owners | Polyrepo | **The failure mode of each:** a monorepo that grows until CI takes twenty minutes for a one-line change and nobody can tell what a change affects; a polyrepo set where a single logical change requires five coordinated pull requests and a release dance. **Default at TradyPerch's current scale: one repository per deployable product**, with a monorepo when a product genuinely has multiple deployables that release together. ### 6.3.4 Versioning Is a Promise A version number is a compatibility statement to consumers. Semantic versioning is used not because it is fashionable but because it makes that statement machine-readable: a consumer can decide whether an upgrade is safe without reading a changelog. The discipline that makes it work is honesty about what constitutes a breaking change — which is broader than most teams assume (§6.4.6). ## 6.4 Standards ### 6.4.1 Repository Naming | ID | Rule | |---|---| | **REPO-01** | Names MUST be lowercase kebab-case, ASCII, ≤ 40 characters | | **REPO-02** | Names MUST describe the thing, not the technology. `tp-invoicing`, not `tp-react-invoicing` | | **REPO-03** | Product repositories MUST carry the `tp-` prefix | | **REPO-04** | Names MUST NOT contain a version, a year, a person, or a status word (`new`, `v2`, `final`, `temp`) | | **REPO-05** | The name MUST be decided at creation and MUST NOT be changed casually | | Kind | Pattern | Example | |---|---|---| | Product | `tp-` | `tp-reviews-engine` | | Service | `tp--service` | `tp-billing-service` | | Library | `tp-` | `tp-http-client` | | CLI | `tp--cli` | `tp-deploy-cli` | | Extension | `tp--extension` | `tp-clipper-extension` | | Mobile app | `tp--mobile` | `tp-fieldwork-mobile` | | Infrastructure | `tp-infra-` | `tp-infra-core` | | Internal tool | `tp-tool-` | `tp-tool-onboarding` | | Documentation | `tp-docs-` | `tp-docs-engineering` | | Template | `tp-template-` | `tp-template-service` | ### 6.4.2 Root Structure Every TradyPerch repository has a predictable root. Items marked **required** apply at T2+. | Item | Required | Purpose | |---|---|---| | `README.md` | **Yes** | The first ninety seconds | | `LICENSE` | **Yes** | Legal clarity, even internally | | `CHANGELOG.md` | T3+ | What changed, per release | | `CONTRIBUTING.md` | T3+ | How to work here | | `SECURITY.md` | T3+ | How to report a vulnerability | | `.gitignore` | **Yes** | Never commit build output, dependencies, or secrets | | `.gitattributes` | **Yes** | Line endings and binary declarations | | `.editorconfig` | **Yes** | Editor defaults | | `.env.example` | If env vars are used | Documented template, no real values | | `AGENTS.md` or equivalent | **Yes** | Standing context for AI agents (§4.4.6) | | `docs/` | T2+ | Architecture, decisions, runbooks | | `src/` | **Yes** | Source. Nothing executable at the root | | `tests/` | T2+ | Tests, mirroring `src/` | | `scripts/` | As needed | Maintenance and tooling | | CI configuration | T2+ | The automated gates | | ID | Rule | |---|---| | **REPO-06** | The repository root MUST NOT contain source files. Everything executable lives under `src/` or `scripts/` | | **REPO-07** | `.gitattributes` MUST enforce LF line endings for text files | | **REPO-08** | `.gitignore` MUST exclude dependencies, build output, environment files, and local state — **before the first commit** | | **REPO-09** | An agent standing-context file MUST exist and MUST be version-controlled and reviewed like code | **Rationale for REPO-07.** Line endings are not a style question wherever content is hashed, signed, or byte-compared. A CRLF checkout on one developer's machine produces different bytes from everyone else's, which silently breaks content-addressed comparison, inflates diffs, and produces "changed" files that contain no change. **Rationale for REPO-08.** `.gitignore` must be correct before the first commit, because the first thing a mistake here does is commit a secret or a 200 MB dependency tree — and both are permanent in history. ### 6.4.3 Folder Hierarchy The internal shape depends on the project type, but three rules are universal: | ID | Rule | |---|---| | **REPO-10** | Organise by **layer or domain**, never by file type. `features/billing/` not `controllers/`, `models/`, `views/` | | **REPO-11** | Every directory whose contents are governed by a rule MUST contain a README stating that rule in one paragraph | | **REPO-12** | Nesting SHOULD NOT exceed four levels below `src/` | **Rationale for REPO-10.** Type-based organisation scatters every feature across the tree, so a single change touches five directories and no directory tells you what the system does. Domain-based organisation co-locates what changes together, which is the property that matters. It also matters more for agents: an agent given `features/billing/` has the whole feature in view; an agent given `controllers/` has a third of five features. **Rationale for REPO-11.** A rule stated where the work happens is read; the same rule in a handbook is not. This single practice does more to preserve architecture than any amount of documentation elsewhere. **Reference shapes by project type** — adapt, do not invent from scratch: | Project Type | Top-level under `src/` | |---|---| | Backend service | `api/` (transport), `domain/` (logic, pure), `data/` (persistence), `integrations/` (external), `platform/` (cross-cutting) | | Web application | `app/` (routes/pages), `features/` (by domain), `components/` (shared UI), `lib/` (utilities), `styles/` | | CLI | `cli/` (commands, parsing), `core/` (logic, pure), `adapters/` (I/O), `config/` | | Library | `src/` by capability, one public entry point | | Mobile app | `screens/`, `features/`, `components/`, `services/`, `store/` | | Browser extension | `background/`, `content/`, `popup/`, `options/`, `shared/` | | Automation system | `pipelines/`, `steps/`, `adapters/`, `config/` | | Desktop app | `main/` (process), `renderer/` (UI), `shared/` (IPC contracts) | **One invariant across all shapes: business logic is separated from I/O.** Whatever the names, there is a part that can be tested without the network, the filesystem, the clock, or a UI. That separation is the single highest-value structural decision in any codebase (§9). ### 6.4.4 Naming Conventions Within a Repository | Element | Convention | Rationale | |---|---|---| | Directories | `kebab-case` | Case-insensitive filesystems make mixed case a portability hazard | | Source files | `kebab-case` matching the primary export | Predictable, greppable | | Test files | `..test.` | Location and name both indicate the subject | | Configuration files | Tool convention | Do not fight tooling defaults | | Documentation | `kebab-case.md` | Consistency | | Environment variables | `SCREAMING_SNAKE_CASE`, project prefix | Namespacing prevents collisions | | Feature flags | `SCREAMING_SNAKE_CASE`, verb-shaped | `ENABLE_X`, not `X_FLAG` | | ID | Rule | |---|---| | **REPO-13** | A file's name MUST match its primary export | | **REPO-14** | Test files MUST mirror the structure of what they test | | **REPO-15** | Environment variables MUST carry a project prefix | ### 6.4.5 README Standard The README is read more than any other document. It has ninety seconds to be useful. | # | Section | Answers | Required | |---|---|---|---| | 1 | **What this is** — two sentences | "Am I in the right place?" | **Yes** | | 2 | **Status** — active/maintenance/deprecated, owner | "Should I use this?" | **Yes** | | 3 | **Quick start** — clone to running | "How do I run it?" | **Yes** | | 4 | **How it works** — one paragraph + one diagram | "What is the shape?" | T2+ | | 5 | **Common tasks** — the five things people do | "How do I do the thing?" | T2+ | | 6 | **Configuration** — or a pointer | "What can I change?" | T2+ | | 7 | **Testing** — how to run them | "How do I verify?" | T2+ | | 8 | **Deployment** — or a pointer | "How does it ship?" | T3+ | | 9 | **Documentation index** | "Where is the detail?" | T2+ | | 10 | **Getting help** — who to ask | "I'm stuck" | **Yes** | | ID | Rule | |---|---| | **REPO-16** | The quick start MUST work on a clean machine. It MUST be verified at least quarterly | | **REPO-17** | The README MUST state the current owner | | **REPO-18** | The README MUST NOT duplicate detail available elsewhere — it links | | **REPO-19** | A deprecated repository's README MUST say so in the first line, and name the replacement | **Rationale for REPO-16.** A broken quick start is the most common documentation defect and the most expensive: it fails at the exact moment someone is forming their opinion of the codebase, and it costs them an hour of debugging something that is not their problem. ### 6.4.6 Versioning | ID | Rule | |---|---| | **VER-01** | Semantic versioning: `MAJOR.MINOR.PATCH` | | **VER-02** | MAJOR for any breaking change to a public contract | | **VER-03** | MINOR for backward-compatible additions | | **VER-04** | PATCH for backward-compatible fixes | | **VER-05** | Pre-1.0 (`0.x`) means the contract is unstable; MINOR may break | | **VER-06** | Every release MUST have a git tag and a changelog entry | | **VER-07** | Data and API schemas MUST be versioned independently of the software | **What counts as breaking — broader than most teams assume:** | Change | Breaking? | |---|---| | Removing or renaming a public function, field, endpoint, or CLI flag | **Yes** | | Adding a required parameter or field | **Yes** | | Changing a default value | **Yes** — behaviour changes for existing users | | Narrowing accepted input | **Yes** | | Widening returned output | Usually no; **yes** if consumers validate strictly | | Changing an error code, type, or message that consumers match on | **Yes** | | Changing observable ordering | **Yes** if anyone depends on it — and someone always does | | Changing timing or performance characteristics materially | Sometimes; announce it | | Adding an optional parameter with a safe default | No | | Fixing a bug that some consumer depends on | **Treat as breaking** and announce | **Rationale for the last row.** "It was a bug" is a true statement that does not help a consumer whose system stops working. Hyrum's observation applies: with enough users, every observable behaviour of a system is depended upon by somebody. The correct handling is to announce, not to argue. ## 6.5 Real-World Examples ### Example 1 — The Name That Lied A repository named `tp-api` was created for one service. Three services later, `tp-api` holds one of them, and every new engineer assumes it is the API gateway. Renaming would break deployment configuration in four places, so it stays. | | | |---|---| | Root cause | A name describing a category rather than a thing | | Rule | REPO-02 | | Cost | Permanent low-grade confusion, indefinitely | ### Example 2 — Organisation by File Type A web application organised as `components/`, `hooks/`, `utils/`, `pages/`. Adding one feature touches all four directories. Removing a feature requires finding its pieces in all four, and two of them are shared with another feature — but nobody can tell which parts. | | | |---|---| | Root cause | Type-based organisation | | Rule | REPO-10 | | Symptom to watch for | "Where does this file go?" having more than one plausible answer | ### Example 3 — The Quick Start That Never Worked A README's setup instructions were written during initial development and never re-run. Two dependencies changed names, one step is now unnecessary, and a required environment variable is undocumented. Every new engineer loses an hour. | | | |---|---| | Root cause | Documentation that is never executed | | Rule | REPO-16 | | Fix that works | Have the newest team member follow it verbatim, quarterly, and fix what fails | ### Example 4 — The Undeclared Breaking Change A library changes a default timeout from 30 s to 5 s in a PATCH release, reasoning that "it's just a default". Four downstream services begin timing out under load. The release notes say "improved timeout handling". | | | |---|---| | Root cause | Default change not recognised as breaking | | Rule | VER-02, and the breaking-change table | | Correct handling | MAJOR bump, or MINOR with an explicit announcement and a migration note | ## 6.6 Common Mistakes | # | Mistake | Symptom | Fix | |---|---|---|---| | 1 | Technology in the repository name | The name is wrong after a migration | REPO-02 | | 2 | Organising by file type | Every change touches every directory | REPO-10 | | 3 | Deep nesting | Six-level paths; nobody can remember where anything is | REPO-12 | | 4 | README written once | Confidently wrong instructions | REPO-16, quarterly verification | | 5 | Committing build output or dependencies | Enormous repository, painful diffs | REPO-08, before the first commit | | 6 | No `.gitattributes` | Line-ending churn; false diffs | REPO-07 | | 7 | Treating a default change as non-breaking | Silent downstream failures | The breaking-change table | | 8 | Monorepo by default without a coupling reason | Slow CI, unclear ownership | §6.3.3's decision table | | 9 | Polyrepo by default | Five coordinated PRs for one change | §6.3.3 | | 10 | No standing-context file for agents | Every agent session re-derives conventions, inconsistently | REPO-09 | ## 6.7 Anti-Patterns | ID | Anti-Pattern | Description | Countermeasure | |---|---|---|---| | **AP-36** | **The Junk Drawer** | `utils/`, `helpers/`, `common/`, `misc/` growing without bound | Name by responsibility. If it cannot be named, it does not belong together | | **AP-37** | **The Ghost Repository** | Nobody knows if it is used; nobody dares delete it | REPO-17 owner; §20's retirement stage | | **AP-38** | **Structure by Accident** | The tree reflects the order features were added | Periodic structural review; REPO-10 | | **AP-39** | **The Undocumented Prerequisite** | Setup works only if you already have something installed | REPO-16 on a clean machine | | **AP-40** | **Version Theatre** | Version numbers incremented without meaning | VER-02; consumers must be able to rely on it | | **AP-41** | **The Copy-Paste Repository** | A new project created by copying an old one, inheriting its cruft | Templates (`tp-template-*`), maintained deliberately | ## 6.8 Decision Tables ### 6.8.1 New Repository or Existing? | Question | New Repository | Existing | |---|---|---| | Does it deploy independently? | ✅ | — | | Does it have a different owner? | ✅ | — | | Does it have different access requirements? | ✅ | — | | Does it release on a different cadence? | ✅ | — | | Does it share substantial code with an existing product? | — | ✅ | | Does it change together with an existing product? | — | ✅ | | Is it a genuinely separate product? | ✅ | — | | Are you unsure? | — | ✅ Start inside; splitting later is easier than merging | ### 6.8.2 Where Does This File Go? | The file… | Goes in | |---|---| | Contains business rules with no I/O | The pure/domain layer | | Talks to a database, network, filesystem, or clock | The adapter/integration layer | | Handles HTTP, CLI arguments, or UI events | The transport/entry layer | | Is used by exactly one feature | Inside that feature | | Is used by three or more features and is domain-agnostic | The shared/platform layer | | Is used by two features | **Leave it duplicated** until a third appears | | Configures a tool | The root, per tool convention | | Is a one-off script | `scripts/`, with a header explaining when to run it | **The two-user rule is deliberate.** Extracting a shared abstraction from two uses is premature more often than not: the two uses have not yet revealed which parts are genuinely common. The third use is where the real shape becomes visible. ## 6.9 Checklists ### CHK-6.1 · New Repository - [ ] Name follows REPO-01…REPO-05 and describes the thing, not the technology - [ ] `.gitignore` and `.gitattributes` are the **first** commit - [ ] README covers all required sections for the tier - [ ] Owner is named in the README - [ ] LICENSE present - [ ] Standing-context file for agents present - [ ] Directory structure follows a reference shape for the project type - [ ] Directory READMEs exist wherever a rule governs contents - [ ] CI configured and green on the first commit - [ ] Branch protection enabled before the second commit - [ ] Secret scanning enabled - [ ] Conformance tier recorded ### CHK-6.2 · Quarterly Repository Health - [ ] Quick start executed on a clean machine and works - [ ] Owner still correct and still here - [ ] Dependencies audited - [ ] Dead code and dead directories removed - [ ] Structure still matches how the system actually works - [ ] Standing-context file still accurate - [ ] README's "common tasks" still the common tasks ## 6.10 Risk Analysis | Risk | Likelihood | Impact | Mitigation | Residual | |---|---|---|---|---| | Structure decays as features are added | High | Medium | Directory READMEs; quarterly review; REPO-10 | Medium | | Secret committed to history | Low | **Critical** | `.gitignore` first; secret scanning; §15 | Low — irreversible if it occurs | | Quick start rots | High | Medium | Quarterly verification | Low | | Repository sprawl | Medium | Medium | §6.8.1; ownership; retirement (§20) | Medium | | Breaking change shipped as PATCH | Medium | High | The breaking-change table; release checklist | Low | | Agent infers wrong conventions from inconsistent structure | Medium | Medium | Consistency; standing-context file; directory READMEs | Low | ## 6.11 Future Improvements | Item | When | Note | |---|---|---| | Maintained repository templates per project type | v1.1 | Removes the copy-paste anti-pattern (AP-41) | | Automated structure conformance check | v1.2 | Assert the tree against a declared manifest | | Repository inventory with owners and status | v1.1 | Prevents ghost repositories | | Automated quick-start verification in CI | v1.2 | Run the README's steps in a clean container weekly | --- # 7. Git Standards ## 7.1 Purpose To keep history readable, changes small and revertible, and the main branch always releasable — so that history is a usable engineering tool rather than a record of how the code came to be. ## 7.2 Objectives 1. Define one branching model that fits every TradyPerch project. 2. Standardise commit messages so history is scannable and machine-parseable. 3. Keep changes small enough to review properly. 4. Define pull request standards that make review effective rather than ceremonial. 5. Define release tagging and rollback so that reverting is routine. 6. Make history an asset for debugging (§12) rather than noise. ## 7.3 Engineering Rationale ### 7.3.1 Why Trunk-Based Long-lived branches accumulate three costs simultaneously: merge conflict risk grows with time and change volume; the branch diverges from reality so its tests prove less each day; and the eventual merge is large, which is exactly the condition under which review fails. Trunk-based development — short branches, merged within about two days — trades a small ongoing coordination cost for the elimination of a large, unpredictable one. It also directly serves §1.3.1's central point: small changes are cheap to verify, and verification is the bottleneck. **The specific interaction with AI-assisted work:** an agent can produce a week's worth of change in an afternoon. Without a merge-frequency rule, that becomes a 3,000-line pull request that nobody can review, which is then approved on trust — AP-09. The 48-hour rule is what prevents generation speed from converting directly into review debt. ### 7.3.2 Why Commit Format Matters Commit messages are read in exactly three situations, all of them stressful: bisecting a regression, writing release notes, and answering "why is this code like this?" during an incident. A message written for those readers is worth thirty seconds; one written as "fix stuff" costs someone an hour later. A structured format additionally makes history machine-parseable, which is what allows changelog generation, release automation, and per-area change analysis without anyone maintaining a separate record. ### 7.3.3 Main Is Always Releasable This is not an aspiration; it is a property that must hold at every commit. Its value is that it removes an entire class of coordination: - Any commit can be released, so releasing is not an event. - A revert is always safe, so rollback is not risky. - A broken build blocks everyone, so it is fixed immediately rather than accumulating. - Nobody has to ask "is main good right now?" **The cost is that CI must be fast and reliable.** A slow or flaky pipeline makes this rule unenforceable, which is why §18 treats pipeline speed as a first-class requirement rather than an optimisation. ## 7.4 Standards ### 7.4.1 Branching Model | Branch | Purpose | Lifetime | Protected | |---|---|---|---| | `main` | Always releasable | Permanent | **Yes** | | `/-` | One task | **≤ 48 hours** | No | | `release/` | Only when a release must be stabilised while `main` advances | Days | Yes | | `hotfix/-` | Urgent production fix | Hours | No | | Type prefix | Use | |---|---| | `feat/` | New capability | | `fix/` | Defect repair | | `refactor/` | Structure only, no behaviour change | | `test/` | Tests only | | `docs/` | Documentation only | | `chore/` | Tooling, dependencies, housekeeping | | `perf/` | Performance work | | ID | Rule | |---|---| | **GIT-01** | `main` MUST be protected: review required, CI required, no force-push | | **GIT-02** | Branches MUST be short-lived — merged or closed within 48 hours | | **GIT-03** | One branch per task. A branch that needs "and" in its description is two branches | | **GIT-04** | Branches MUST be rebased or updated from `main` before merge | | **GIT-05** | Long-lived feature branches MUST NOT be used. Incomplete work merges **unreachable** instead (§7.4.6) | | **GIT-06** | Direct commits to `main` MUST NOT be possible for anyone, including repository owners | ### 7.4.2 Commit Messages Conventional Commits. Format: ``` ():