Chapter 2: The Self-Improving Repository¶
Building the Repository That Holds Your Three Structures¶
1. The Repository as the Hero, Built¶
Key Focus: What a self-improving repository actually looks like β the four layers, the documentation contract, and the difference between a control plane and an application repository.
Chapter 1 ended with a promise and a chain. The promise: the three structures β Prompt, Engineering, and Workflow β live in the repository, not in a tool. The chain: a repository exists to move the driver β the purpose the work serves β through a delivery plan to an outcome that is proven in operations. This chapter builds that repository, file by file, and shows where each link in the chain lives: the rules that govern AI, the context it reasons over, the ledger of work that carries the driver, and the operational layer that proves the outcome.
π― What You'll Learn¶
- The Four-Layer Repository β Content, Validation, Intelligence, and Automation, and which files belong to each
- The Documentation Contract β the layered set of documents that makes a repository readable by humans and AI alike
- The Day-One Experience β why
clone β help β start workingis the acceptance test of a well-built repository - Control Plane vs. Application β the difference between the repository that governs many repos and the repos it governs
ποΈ Software Architecture First, AI as the Enhancer¶
Before the first file, one principle governs this chapter's design: the repository is built with timeless software architecture, platform engineering, and DevOps practice β not with AI novelty. AI agents are powerful tools that leverage this foundation; they never replace it.
The impedance mismatch. Good software design β modularity, clear boundaries, idempotency, reuse, and strict testability β is precisely what prevents friction with AI. A well-structured repository gives an agent clean seams to work inside. A messy one gives the agent nothing but mess to automate: ask an assistant to work inside a tangle of one-off scripts and it will happily generate more tangle, faster. This is Chapter 1's platform-engineering insight applied to the repository itself: build the road well, and the vehicle β human or AI β stays on it.
π The Repository That Stores Code vs. The Repository That Directs AI¶
Most repositories are passive: they store code and wait for someone to read them. A self-improving repository is active β it directs how work happens, because it holds the rules, the context, the commands, and the gates that every contributor (human or AI) must follow.
| Passive Repository | Self-Improving Repository |
|---|---|
| Stores whatever was committed | Holds rules that shape what gets committed |
| Each contributor remembers the conventions | The repository documents and enforces them |
| Tools own the workflow | Stable commands own the workflow; tools plug in underneath |
| Quality depends on who reviewed what | Gates run on every change, automatically |
| Knowledge lives in people's heads | Knowledge lives in version-controlled documents |
The acceptance test: clone the repository, run
make help, and be productive without asking anyone. If the repository cannot explain itself, it is not yet a self-improving repository.
π The Four Layers¶
Every self-improving repository has four layers. They are not a suggestion β they are the minimum structure that makes AI output reliable, because each layer answers one question an AI assistant (or a new engineer) will ask:
| Layer | Question It Answers | What Lives There |
|---|---|---|
| Content Layer | "What is the actual work?" | Code, infrastructure definitions, documentation |
| Validation Layer | "How do I know it is correct?" | Quality gates, security scans, test suites |
| Intelligence Layer | "What are the rules and the context?" | AGENTS.md (the Law) and AI_CONTEXT.md (the Map) |
| Automation Layer | "How do I run the workflow?" | The command surface: a Makefile of thin targets plus the scripts they delegate to β surfaced through a lightweight CLI where that helps |
The Intelligence layer deserves the most attention, because it is the layer AI assistants read first β and the layer most repositories get wrong. The next section covers it in depth.
π‘ The Documentation Contract¶
The "four files" framing that most guides teach (AGENTS.md, AI_CONTEXT.md, validate.sh, Makefile) under-counts what a production repository actually needs. In practice, a self-improving repository ships a documentation contract β a layered set of documents, each a role that every reader (human or AI) can find by name:
| Layer | File | Role | The Question It Answers |
|---|---|---|---|
| Front Door | README.md |
The entry point β overview, quick-start, and explicit links routing humans and AI to the governance files | "Where do I start, and what is this repository for?" |
| Core Blueprint | architecture.md |
The source of truth for structural design β components, data flow, constraints | "How is this system designed, and what may not change?" |
| Governance | AGENTS.md |
The Law β symbolic constraints and non-negotiable rules | "What must I always do, and what must I never do?" |
| Governance | AI_CONTEXT.md |
The Map β current state, conventions, environmental context | "How is this built today, and where are the conventions?" |
| Governance | PLAYBOOK.md |
The Playbook β step-by-step procedural tasks, each with a human approval gate | "How exactly do I perform this procedure safely?" |
| Product & Business | docs/features.md |
The Cockpit β the roadmap: planned and released work, each with a lifecycle | "What are we building, and where does each item stand?" |
| Product & Business | docs/capabilities.md |
The Driver β the business outcomes and strategic value behind the work | "Why does this repository exist, and what outcome does it serve?" |
| Operational | observability.md |
The Mirror β human-facing operational signals (compliance, inventory, execution), distinct from any application dashboard | "Is the system healthy right now, by evidence?" |
| Operational | operations.md |
The Runbook β maintenance, incident response, troubleshooting | "When something breaks, what do I do?" |
| Records | CHANGELOG.md |
The Record β what changed and why, per release | "What has this repository changed, and why?" |
The Law and the Map are the two files that govern AI behaviour directly. The Playbook turns procedures into repeatable, gated steps. The Product & Business layer keeps the work honest about why it exists and what it is delivering. The Operational layer proves the whole thing holds in production. Together they form the repository's permanent memory β the same way a good engineering team keeps its decisions in version control instead of in tribal knowledge.
Beyond the everyday contract lie the append-only records β the change log, the prompt-regression log (Section 11), and the AI execution log (Section 8) β evidence written by the loop and read on demand, not loaded by default.
π§ Key Insight β Chapter 1's chain, made concrete. Every file above carries one link of Chapter 1's chain:
docs/capabilities.mdnames the driver;docs/features.mdis the delivery plan; the governance trio (AGENTS.md,AI_CONTEXT.md,PLAYBOOK.md) holds the three structures β the Law for Prompt structure, the Map plusarchitecture.mdfor Engineering structure, the Playbook plus the gates for Workflow structure; andobservability.mdwithoperations.mdhold the outcome. Chapter 1 said the repository moves the driver to the outcome β this contract is how.
π§ Control Plane vs. Application Repository¶
One repository holds the three structures for a single project. A control plane holds them for an entire organisation. The distinction matters because the control plane is where the self-improving loop gets its leverage:
graph TB
CP["Control Plane<br>(governs the org)"]
APP1["App Repo 1"]
APP2["App Repo 2"]
APP3["App Repo N"]
CP -->|"shared foundation<br>(rolled out)"| APP1
CP -->|"shared foundation"| APP2
CP -->|"shared foundation"| APP3
APP1 -->|"evidence + feedback"| CP
APP2 -->|"evidence + feedback"| CP
APP3 -->|"evidence + feedback"| CP
style CP fill:#e3f2fd
style APP1 fill:#f3e5f5
style APP2 fill:#f3e5f5
style APP3 fill:#f3e5f5
The control plane holds a single source of truth β a description of every repository, its role, its permissions, and its capabilities β and rolls the shared foundation out to each one, collecting evidence as it goes. This chapter builds the application repository: the unit every control plane governs. Section 11 returns to the control-plane idea, and Part Three shows how that machinery is built. This chapter deliberately stays with one repository so the foundation is solid before it is ever multiplied.
The Day-One Experience¶
The repository's README states its day-one experience in one line: "Clone this repo β see the commands β start working." That is not marketing β it is the acceptance test of the whole design.
git clone <repository-url>
cd <repository>
make help # every command, self-documented
make setup # verify required tooling is present
Three properties make this possible, and every self-improving repository should aim for them:
| Property | What It Means | How It Is Achieved |
|---|---|---|
| Self-documenting | The command surface explains itself | help renders every command and its intent |
| Self-sufficient | Setup is one idempotent command | setup verifies tooling in a single step |
| Consistent | The same verbs work in every repository you touch | Shared command names β same intent, same command |
π‘ Key Insight: If a new machine, a new human, or a new AI tool can reach "productive" in one command, the repository's structure is doing its job. If it cannot, no amount of AI will fix the gap β the structure is the fix.
2. The Intelligence Layer: Law and Map¶
Key Focus: Why the Law and the Map are separated β and the discipline that keeps their reusable content identical across many repositories.
Two files govern AI behavior, and they serve fundamentally different purposes. Getting this separation right is the single highest-leverage decision in the repository, because it mirrors how AI models process context.
π Law vs. Map: When to Use Which¶
Use AGENTS.md (The Law) |
Use AI_CONTEXT.md (The Map) |
|---|---|
| "Never commit secrets or API keys" | "Our services are written in Python with typed request models" |
| "Always run validation before commit" | "Database migrations live under migrations/" |
| "Follow the repository's formatting rules" | "Authentication uses signed tokens with expiring sessions" |
| "Every automation must be safe to re-run" | "Webhooks are handled in scripts/handlers/" |
The rule: AGENTS.md contains rules that do not change based on what you are working on. AI_CONTEXT.md contains facts that vary by project, service, or component.
Why the separation matters. When you ask an AI assistant to "add a new endpoint," it needs two things at once:
- Behavioral constraints (from the Law): validate input, follow conventions, never commit secrets
- Architectural context (from the Map): the service is Python, endpoints live in
routes/, migrations use Alembic
Without the separation, the AI either follows rules but lacks context β writes perfect Python for a Node.js service β or has context but ignores rules β knows the structure, but commits secrets. With it, the AI has both guardrails and situational awareness.
π§ Reusable Building Blocks: The Same Law and Map, Many Repositories¶
The evidence from real multi-repo work adds a second split that most guides miss: inside each governance file, reusable content and repository-specific content live side by side. The reusable part β the rules and context that apply to every repository β should stay identical wherever it appears; the specific part belongs to that repository alone.
The classification rule. When a new rule or fact is written, classify it first: does it apply to every repository, or only this one? A repository-specific layout rule drifting into the reusable part is the classic failure β it silently makes the shared block non-reusable. The same discipline applies to the Map, to scripts, and to commands: shared building blocks stay generic, and the specific implementation lives where it is used. Reuse without duplication β the oldest rule in software, applied to governance.
π§ Key Insight: A shared block is a living artifact, not a memory. It improves in one place and is consumed everywhere β one source of truth, many consumers. How the sharing is mechanised β a template directory, a scaffold command, a roll-out step β is an implementation detail this book deliberately leaves to Part Three. The principle is timeless: keep the reusable block reusable, and let nothing repository-specific drift into it.
The Alignment With How AI Models Process Information¶
This separation is not an arbitrary convention β it maps to how AI systems actually process input:
| AI Layer | Function | Repository Equivalent |
|---|---|---|
| System/Instruction Layer | Behavior, constraints, guardrails β loaded first, minimal size | AGENTS.md (the Law) |
| Context/Knowledge Layer | Specific knowledge, patterns, architecture β loaded as needed | AI_CONTEXT.md (the Map) |
| Session/Interaction Layer | Current conversation, temporary state | Chat history, temporary files |
The repository structure mirrors the model architecture, which is why the pattern survives model changes: any model, today or tomorrow, still needs behavioral constraints, contextual knowledge, and temporary state. Structure the repository for that permanence and you stop re-architecting every time a new model ships.
The Context Economy: Why the Split Pays¶
The layered structure is also economical to load, and context is never free. The Law is small and static β cheap to include on every request and friendly to caching. The Map is larger and task-dependent β read only when the task touches that part of the system. Keep the Law small and static, keep the Map organised by area so a reader can pull only the relevant section, and every interaction stays focused.
π‘ Deferred, not ignored. The economics of models and routing β what each tier costs, when to escalate, how to meter usage β matter, and Part Two considers them properly. The design principle here stands on its own: load little, load the right thing, and the size of the bill follows the size of the context.
The Law and the Map are the substrate, not the whole system. The six sections that follow are the capabilities a repository builds on top of them: routing the context an agent loads, carrying work across sessions, composing multi-step work safely, bounding when an agent must stop, economizing what enters the prompt, and auditing what the agent actually did. Each is a repository pattern β the same in every repository, regardless of which assistant reads it.
3. Context Routing: Progressive Disclosure and Reference Mapping¶
Key Focus: How a repository declares which parts of the Map a task loads β and why precise loading, rather than more loading, is what makes an agent accurate.
Section 2 established the split: the Law is small and static, the Map is large and task-dependent. This section turns that split into an instruction. Progressive Disclosure means loading the smallest part of the Map that makes the current task correct. Reference Mapping is the declared table that says which part is which: a task type in, a set of Map sections out.
π The Routing Rule: Task Type to Map Sections¶
The mechanism is a table, declared once and read by every agent:
| Task type | Load from the Map | Why that slice |
|---|---|---|
| Documentation change | Conventions, terminology, chapter format | Prose is governed by voice, not architecture |
| Service or component change | Components, data flow, test boundaries | A change must respect the blueprint it lands in |
| Infrastructure change | Environments, deployment, secrets handling | The blast radius is environmental |
| Pipeline change | Build, release, runners, gates | The failure mode is an unguarded pipeline |
| Governance change | The Law and the feature ledger | It alters the rules every other reader follows |
The table stays small deliberately. A routing table that needs its own lookup has already failed.
π§ The Obligation Lives in the Law; the Mapping Lives in the Map¶
The obligation β classify the task, load only the routed sections, never guess at relevance β is timeless, so it belongs in the Law. The mapping is a fact about one repository's Map, so it belongs beside the sections it names. Put the mapping in the Law and the Law turns repository-specific β exactly the drift Section 2 warned about.
β οΈ What Breaks Without It¶
Context bloat is the common failure: every task loads every section, because loading is easy and deciding relevance is not. The agent reasons across a Map far larger than its problem, paying in focus and tokens for material that cannot affect the answer.
The opposite failure is subtler β routing that is stale or wrong, so the agent loads a plausible slice that omits the constraint that mattered. Neither failure produces caution; both produce confident guessing.
π οΈ Implementing It¶
Declare the mapping as a named section of the Map, and state the obligation once in the Law.
## Task Routing
| Task type | Load from this Map |
|:---|:---|
| Documentation change | Β§Conventions, Β§Terminology |
| Infrastructure change | Β§Environments, Β§Deployment, Β§Secrets |
| Pipeline change | Β§Build, Β§Release, Β§Gates |
The Law's half is one sentence: classify the task first, load only the routed sections, and state which sections you loaded.
β Validating It¶
Give an agent a task, then read its Context and Action Summary (Section 8). The sections it read must match the routing table for that task type.
π§ Key Insight: A repository that declares its own routing needs no retrieval feature from any tool: the Map is the index, the Law states the obligation, and any reader can fetch precisely.
4. Session Continuity: The Gitignored Session Artifact¶
Key Focus: Why the handoff between agent sessions belongs in a disposable repository artifact, not in any tool's memory.
Every assistant keeps some notion of a session, and every one of those notions is private to that assistant. Switch tools, and the working state β what was read, what changed, what was decided, what comes next β is gone, even though the work is not finished. Session Continuity is the repository-level answer: one disposable, human-readable artifact that any reader can pick up.
The artifact is a baton, not a record: it lets the next reader β another agent, another model, or the orchestrator returning after lunch β resume without being re-briefed.
π The Handoff Between Tools¶
sequenceDiagram
participant A as Agent A
participant S as Session artifact
participant B as Agent B
A->>S: write task, decisions, next step
A-->>A: session ends mid-task
B->>S: read the artifact
S-->>B: task, files touched, gate status
B->>B: continue from the next step
The sequence is unremarkable by design: no tool knows about another; both know about the artifact. Continuity lives in the repository, so it survives every change of reader.
β οΈ What Breaks Without It¶
Without an artifact, continuity is replaced by re-briefing: the orchestrator re-explains the task to the next tool, which re-reads files it has already read and re-derives decisions already made. The sharper failure is silent loss β a session ends mid-task with an edit half-applied and no note of where it stopped.
π οΈ Implementing It¶
Keep the schema minimal:
| Field | Purpose |
|---|---|
task |
One line describing the work in flight |
status |
in-progress / blocked / awaiting-approval / complete |
files-read |
What this session has read β the routing evidence |
files-modified |
What this session has changed β never guess at this |
decisions |
Each key decision and its reason, one line each |
next-step |
The exact next action, written for a different reader |
gate-status |
The last gate run and its observed result |
Add the artifact's location to .gitignore. It is derived state, never a second source of truth: if it disagrees with Git, Git wins.
β Validating It¶
Start a task in one tool, stop deliberately mid-task, then open a second tool and ask it to continue. It should read the artifact, state the next step correctly, and resume without being told what happened. Then confirm git status does not mention the artifact.
π§ Key Insight: Sessions belong to tools; continuity belongs to the repository. A short artifact any reader can parse buys the freedom to change tools mid-task β the only way "tools are transient" survives a real deadline.
5. Workflow Orchestration: Safe Multi-Step Composition¶
Key Focus: How the Playbook turns a multi-step change into named, gated procedures β so an agent can chain work across files without compounding its own mistakes.
Single edits are easy to review. Sequences are where agents go wrong: five files changed, one validation at the end, and a failure that could have come from any of them. Safe Multi-Step Composition is the rule that makes chaining safe β every step ends in a gate, and every gate passes before the next step begins.
The home for these sequences already exists in the documentation contract: the Playbook. A procedure is a named, repeatable sequence with declared gates and declared approval points.
π The Anatomy of a Procedure¶
Each step carries four things, and omitting any one of them is how procedures rot:
| Element | What it declares | Why it is required |
|---|---|---|
| Action | What this step does | A step that cannot be described cannot be reviewed |
| Gate | The command that proves the step worked | Validation between steps is what stops error compounding |
| Approval | Human or automatic | The steps needing judgment are named, not assumed |
| Stop condition | When to abort the sequence | Prevents pushing through a broken premise |
A procedure without gates is a to-do list. A procedure without a stop condition is a trap.
β οΈ What Breaks Without It¶
The signature failure is compounded error: an agent chains edits without validating between them, each built on the previous step's unverified assumption, until the final gate fails and the whole sequence must be unpicked by hand. Gating each step keeps the failure surface at one change β the gate ladder of Section 10 applied across time instead of across a diff.
π οΈ Implementing It¶
Every procedure is named, triggered, and gated:
## Procedure: <name>
**Trigger:** <when this procedure is the right one>
**Steps:**
1. <action> β gate: <command> β approval: <human|automatic>
2. <action> β gate: <command> β approval: <human|automatic>
**Stop condition:** <the observation that aborts the sequence>
**Rollback:** <how to return to the last known-good state>
Write one procedure before writing ten; the first proves the pattern.
β Validating It¶
Run a procedure end to end and watch the boundaries, not the output. Every gate must execute, and every approval: human step must halt and wait. Then break step one on purpose: the procedure must stop rather than improvise around it.
π§ Key Insight: Composition is not dangerous because agents are careless; it is dangerous because it hides the moment a wrong assumption entered. A gate between steps keeps that moment visible β exactly when it is still cheap to fix.
6. Escalation Boundaries: Enforcing Human Authority¶
Key Focus: How a repository converts "the human decides" from a principle into stop conditions an agent can actually apply β and what it must do when one fires.
Section 12 states the authority: AI may read, run, and propose; only the human may write, commit, and release. But a principle that lives only in a paragraph is interpreted differently by every reader. Escalation Boundaries are the declared conditions under which an agent must stop and report instead of proceeding β and they are the reason a sensible orchestrator can let an agent run at all.
π The Conditions, and the Required Response¶
| Condition | The agent must | The agent must not |
|---|---|---|
| Requirements are ambiguous | Report the ambiguity and options | Pick an interpretation and proceed |
| Several approaches exist, the choice architectural | Present the options with trade-offs | Choose silently |
| The change would alter the Law or the Map | Propose the change and stop | Edit governance on its own authority |
| The work touches secrets or production | Stop and hand over | Read, copy, or transmit it |
| A gate fails and iterate-to-green cannot clear it in N attempts | Report the failure and the command | Loosen the gate or call it blocked-and-fine |
| The task requires a file outside the declared scope | Report the scope violation | Widen its own scope |
The threshold N is a repository decision, and it should be chosen once and stated. An unstated limit is not a limit.
β οΈ What Breaks Without It¶
Three failures appear in real work, and all three are the same failure in different clothes β an agent deciding something that was never delegated to it.
The agent that fixes what it was not asked to fix sees an unrelated wart, improves it, and hands over a change nobody reviewed. The agent that quietly edits the Law resolves a conflict by rewriting the rule, and the guardrail it weakened is now invisible. The agent that commits because the task said "proceed" treats an instruction to continue as an instruction to ship.
π οΈ Implementing It¶
Declare the conditions in the Law, where they cannot vary by task:
## Escalation Conditions
Stop and report to the human when:
- Requirements are ambiguous or contradictory
- Several valid approaches exist and the choice is architectural
- The change would alter the Law or the Map
- The work touches secrets or production
- A gate fails and iterate-to-green cannot resolve it within N attempts
- The task requires a file outside the declared scope
Reporting has a shape, which keeps it honest: the condition that fired, the evidence, the options considered, and the decision being requested.
β Validating It¶
Trigger one condition deliberately β hand an agent an ambiguous requirement, or ask it to change a rule. It must stop and report, without making the edit. If it proceeds, the boundary is prose rather than a boundary.
π§ Key Insight: Boundaries exist because good intentions are not enforcement. Declaring where your authority begins in advance is what makes granting an agent autonomy safe rather than merely hopeful.
7. Context Economy: Context Budgeting by Task Scope¶
Key Focus: How routing turns cost into a governance property β because the repository controls what enters the prompt, even though it does not control what the model charges.
Section 2 explained why the Law/Map split pays. This section makes that economy governable: Context Budgeting is sizing what enters the prompt to the scope of the task, not to the size of the repository. The repository owns one side of the cost equation, and it is the side you can actually change β what enters the prompt is a decision you make today; what the model charges is a market you observe.
π Scope Determines the Budget¶
| Task scope | The Law | Map sections | Relative context cost |
|---|---|---|---|
| One-line fix | Full β it is small | The one area the file belongs to | Lowest |
| Single-component change | Full | That component, its interfaces, its tests | Low |
| Cross-cutting change | Full | Several areas plus the conventions | Moderate |
| Architectural change | Full | The blueprint, the conventions, the ledger | Highest |
The Law is loaded on every task, and that is affordable because it is small. The Map is loaded by scope, because it is organised to be read in slices.
β οΈ What Breaks Without Budgeting¶
The obvious failure is loading everything for a small task: the whole Map enters the prompt to change one line, and the agent pays for context that cannot affect the result. Cost rises while accuracy does not.
π° Cost Check: Context Budgeting Loading an entire Map for a small change is the most common avoidable token cost in a governed repository β and it compounds, because every retry re-sends the same oversized context. The Fix: route by task scope first (Section 3), then choose the tier. Escalation is for reasoning difficulty, not for context volume.
π οΈ Implementing It¶
Budgeting needs no dashboard and no metering β only three rules, all declared in files you already have:
## Context Budget
- The Law is always loaded; keep it small enough that this stays cheap.
- The Map is loaded by task scope; never load a section the task cannot touch.
- State which sections were loaded, so the budget is reviewable.
Tier pricing, escalation thresholds, and metering are Part Two's material β deferred, not ignored. This chapter owns the input side of the equation: right-sized input, chosen deliberately, and recorded.
β Validating It¶
Compare the Context and Action Summaries (Section 8) of a small task and a large one. The context each loaded should be proportional to its scope. If both loaded the same sections, routing is not being applied β and the cost is paid on every task.
π§ Key Insight: Cost discipline is a governance property, not a tool setting. A repository that declares what loads when has made its own spending predictable β with no dashboard, no meter, and no per-tool configuration.
8. Execution Transparency: The Context and Action Summary¶
Key Focus: The lightweight audit trail that proves the other capabilities were applied β what the agent read, which rules governed it, what it decided, and what it ran.
Governance you cannot observe is governance you cannot trust. Sections 3 through 7 ask an agent to route its context, resume from an artifact, follow procedures, respect boundaries, and budget what it loads β none of it verifiable unless the agent says what it did. The Context and Action Summary is that statement: a structured, append-only entry recording the files read, the rules applied, the decisions made, the gates run, and the outcome. It is the agent-side artifact that keeps the loop's structured-feedback chain (Section 11) intact.
π What Each Field Proves¶
| Field | What it proves |
|---|---|
timestamp |
When the work happened, comparably recorded |
task |
What the agent understood it was asked to do |
files-read |
That routing (Section 3) was followed, not improvised |
rules-applied |
Which rules of the Law governed the work |
decisions |
Why the change looks as it does |
gates-run |
That validation happened, with results |
outcome |
green, blocked, or escalated |
next-step |
What the next reader should do, or what is requested |
A summary whose files-read list does not match the routing table is a finding, not a formality.
β οΈ What Breaks Without It¶
Without a summary, the first question after any agent task β why did it change this? β has one answer: read the whole diff and guess. Worse, governance becomes unverifiable: an orchestrator who cannot see which sections were read cannot tell whether routing was applied or whether boundaries held.
π οΈ Implementing It¶
Keep the log tracked, append-only, and required:
## AI Execution Log
| timestamp | task | files-read | rules-applied | decisions | gates-run | outcome | next-step |
|:---|:---|:---|:---|:---|:---|:---|:---|
| 2026-01-14T09:20Z | Fix broken internal link | Β§Conventions | Truthful docs | Replaced dead link target | make validate β
| green | none |
Whether it is appended directly or summarized from the session artifact is an implementation choice; what matters is that it is durable, structured, and readable without the conversation that produced it.
β Validating It¶
After any agent task, read the entry. Every field must be present, and the outcome must match what the gates actually reported β a summary claiming green where the gate failed is worse than no summary, because it looks like evidence.
π§ Key Insight: Transparency turns the other capabilities from intentions into observed behaviour. Routing, budgeting, and boundaries are all claims until an agent records the evidence β and a recorded claim can be checked by anyone, at any time.
9. The Command Surface Contract¶
Key Focus: The durable abstraction β stable commands over pluggable implementations β and how a Makefile concept, assisted by a lightweight CLI, becomes the repository's stable interface without becoming a dumping ground for logic.
Chapter 1 introduced the command surface contract: quality commands, improvement commands, evolution commands β a stable interface with pluggable implementation. This section shows how a real repository implements that contract with time-tested developer tools β a Makefile of thin targets, optionally surfaced through a lightweight CLI β and where the line between "shared" and "repository-owned" sits. Commands are shown here as Make targets; a repository that surfaces the same verbs through its own thin CLI keeps the identical contract β the verb is the contract, not the wrapper.
The Senior Engineer's Insight¶
A stable command surface is the abstraction layer. It shields you from tool churn.
The pattern separates three things:
| Layer | Purpose | Example |
|---|---|---|
| Command | What you type | make validate, make commit |
| Interface | The stable contract | A thin Makefile target |
| Implementation | The pluggable backend | A script that can be rewritten without changing the command |
The command stays the same. The implementation underneath changes. When the AI tool changes β today's assistant, tomorrow's harness, next year's something else β the commands you type and the documentation that references them do not.
π Thin Targets, Real Logic¶
The rule that keeps the abstraction honest: the Makefile stays thin; all logic lives in scripts. A target is a one-line delegation, never a shell script embedded in the Makefile.
## validate β the structural gate: script syntax, help render,
## configuration consistency, tooling smoke tests.
validate:
@./scripts/validate.sh
Why this matters for AI: an AI assistant reading the repository sees a stable surface β a small set of named commands with documented intent. The complexity hides behind the interface, where it can be reviewed, tested, and improved without changing the contract.
ποΈ Shared Building Blocks vs. Repository-Owned Surface¶
The most common mistake is putting everything in one place. A production implementation splits the surface into shared building blocks and repository-owned parts:
| Surface | Owned By | What Lives There |
|---|---|---|
| Shared blocks | The reusable foundation (a control plane, where one exists) | Commands identical in every repository: the version-control and release verbs β status, sync, log, diff, diff-staged, last, branches, commit, unstage, release |
| Repository-owned | Each repository's own files | help, setup, and the gates β validate, security-scan, check-staged β plus anything specific to what that repository builds |
The shared blocks are identical everywhere β the same commands, the same behavior, in every repository. The gates and repository-specific targets live in the repository's own files, because validation depends on what is being built. The shared surface defines no gates β a repository's own gates are its own promise to keep.
β οΈ Pitfall β the duplicated block: if a repository redefines something the shared surface already provides (its own
commit, its ownstatus), that is a duplicate. The shared surface never overwrites a repository's own definitions β the duplicate wins (with warnings) until it is removed by hand. Keeping shared blocks genuinely shared is a discipline, not a mechanism.
Same Intent, Same Command¶
The command surface contract only pays off if it is consistent across repositories. The rule of thumb: same intent β same command. Before adding a new target, check whether another repository already does that intent under a different name β if so, align to the existing name. A repo-specific spelling is only justified when the intent itself is repo-specific.
| Intent | Standard Command |
|---|---|
| One-time environment setup | make setup |
| Local preview / dev server | make dev |
| Quality gates | make validate / make security-scan / make check-staged / make ci |
| Staged commit / release | make commit / make release [TAG=...] |
The payoff: the orchestrator never has to remember two commands for the same thing, and an AI assistant can move between repositories without re-learning the surface.
π€ One Surface for Humans and Agents¶
The command surface has two audiences, and both are first-class. Humans want readable output; agents need structure they can parse. The resolution is not two surfaces β it is one surface with two output modes.
| Audience | Default Experience | What It Needs |
|---|---|---|
| Human | Formatted tables, clear logs, colour-coded status | Commands that feel familiar and explain themselves |
| AI agent | Machine-readable output (--output json), predictable exit codes |
Idempotent commands, self-documenting help, parseable results |
The rule: every command a human can run, an agent can run β and vice versa. There are no "human-only" or "agent-only" verbs. A human developer can run the exact command the agent used and see the same result in the format they prefer.
π§ Key Insight β dual usability is what makes the agent coachable and the human verifiable. The agent chains commands, reads structured state, and reports exactly what it did; the orchestrator re-runs the same commands and sees exactly what the agent saw. When a test command is invoked by an agent, its results default to a machine-parseable form; humans still get their readable summary. That single discipline is what makes the self-improving loop possible β see Section 10.
The Staged VCS Flow¶
The version-control workflow is where the contract meets the guardrails. It is deliberately staged and gated:
git add <paths> # staging is manual, by design
make commit # runs the commit gate, then commits ONLY staged files
git push
make release [TAG=v1.2.3] # gates β clean tree β tag β push the tag
| Step | What Happens | What It Prevents |
|---|---|---|
Manual git add |
You choose exactly what ships | Accidental wholesale commits |
make commit |
Staged gate (validate + staged security scan) runs first | Bad or secret-laden changes entering history |
Tag-based make release |
Clean-tree check β tag β push tag only | Untested "releases" and half-built tags |
β οΈ The boundary you hold (from Chapter 1): AI never stages, commits, or pushes. The AI drafts and edits files, then reports "changes ready for review" (
git status/git diff) and stops. The ship flow is the orchestrator's action β even when the task says "proceed." This is the review boundary from Chapter 1, applied to the command surface.
10. The Validation Gates¶
Key Focus: Quality is enforced, not assumed β gates real or absent, the gate ladder (atomic β commit β full), and the Iterate-to-Green loop that makes AI self-correcting.
Validation is the layer that turns "AI generated this" into "AI generated this and it is correct." But validation has a failure mode of its own: the fake gate.
Gates Real or Absent¶
The hard-won lesson from real projects: a gate that always passes is worse than no gate at all. A stub that prints "skipping" while the pipeline reports "all gates passed" gives false confidence β and both humans and AI treat green as green. The rule:
A gate is a promise. A gate that always passes is a lie. Ship real gates, or ship none.
| Fake Gate | Real Gate |
|---|---|
| Prints "β passed" without checking anything | Actually runs the check and fails on violation |
| Gives false confidence in CI | Fails the pipeline loudly, with a fix path |
| Hides the problem until production | Surfaces the problem at the cheapest point |
πͺ The Gate Ladder¶
Gates are not a flat pile β they are a ladder with different rungs for different moments:
flowchart TD
A["Atomic Rungs<br/>validate Β· security-scan<br/>(fast, one concern each)"] --> B["Commit Gate<br/>check-staged<br/>(validate + staged security scan)"]
B --> C["Full Gate<br/>ci<br/>(validate + security-scan β local == CI)"]
C --> D["Release<br/>(gates β clean tree β tag β push)"]
style A fill:#e3f2fd
style B fill:#fff3e0
style C fill:#f3e5f5
style D fill:#e8f5e9
| Rung | Command | When You Run It | Scope |
|---|---|---|---|
| Atomic | make validate, make security-scan |
Any time you want one concern checked | Fast, one concern each |
| Commit gate | make check-staged |
Before every commit β what make commit runs |
Staged diff only, so it stays fast |
| Full gate | make ci |
Before push / release | Everything β identical to what CI runs |
| Release | make release [TAG=...] |
Shipping a version | Full gate + clean tree + tag |
The key design decision is the full vs. staged split (the commit gate scans only the staged diff, the full gate scans everything). Without it, the commit path is either slow (full scan on every commit) or dishonest (no scan at all). With it, the commit path is fast and honest, and the release path is exhaustive.
π Security as a Gate¶
Security belongs in the ladder, not as an afterthought. The security scan runs as an atomic rung, in staged form on the commit path, and in full form on the CI path:
| Risk | What the Gate Catches |
|---|---|
| Secret leakage | Hardcoded credentials committed to the repo |
| Supply chain | Suspicious dependencies, missing lock files |
| Misconfiguration | Wide-open permissions, unsafe defaults |
The same discipline that governs validation gates applies here: the scan is real, it fails loudly, and its failures carry a fix path. (Security and compliance get their own depth later in the book; this chapter just wires the gate into the ladder.)
The Iterate-to-Green Loop¶
The final piece of the validation layer is the loop that makes AI self-correcting. It is a non-negotiable working rule for every AI agent:
AI work is not done because it was written β it is done when the gate is green.
1. RUN the gate for the change
2. READ the failure β the error output is the spec for the fix
3. FIX the root cause β never mask, skip, or bypass the gate
4. RE-RUN, and repeat until green
5. Only then report success β stating what was run and the result
A red gate is a finding to fix, not a reason to claim success. If a gate cannot run in the current environment, the AI reports it as blocked with the exact command β never as passing. This loop is what turns "the repository validates" from an aspiration into an observed property of every change.
π‘ Testability Is the AI's Feedback Signal¶
Testability is not a standalone document β it is a contract woven through the repository, and it is the AI's primary feedback mechanism:
| Where | The Contract |
|---|---|
| The Rule (in the Law) | AI-generated code includes appropriate tests |
| The Boundary (in the blueprint) | Testing boundaries and coverage expectations are defined |
| The Evidence (in the gates) | Test suites run through the command surface; the gate ladder fails any change that lacks evidence |
Why structure matters. Test results are not only evidence for humans β they are the primary structured feedback that drives the self-improving loop. Their output must be machine-parseable β structured results, machine-readable CLI output β so an agent can read what failed, why it failed, and where it failed, then fix and re-run. A gate whose output is prose only a human can interpret is a gate that blinds the agent.
The closed loop:
AI generates β the command surface runs the tests β AI parses the structured results
β AI fixes the failure β AI re-runs to green β AI proposes a governance update β human approves
11. The Self-Improving Loop at Org Scale¶
Key Focus: The control plane β a single source of truth, reusable building blocks, and a disciplined roll-out β and why this is where the self-improving loop compounds.
A self-improving repository improves itself. A control plane makes that improvement compound across an entire organisation: improve the foundation once, sync it everywhere, collect evidence, repeat.
The Manifest: One Source of Truth¶
The control plane's core artifact is a manifest β a declarative file that describes every repository, its tier, its class, its owner, its lifecycle, its policy, and the teams and permissions that apply. It is the single source of truth for the organisation:
| The Manifest Declares | What It Drives |
|---|---|
| Repos, tiers, classes, lifecycle | Cloning, workspace file, foundation-sync eligibility |
| Teams and permissions | Access and onboarding (planned sync) |
| Runner groups and profiles | Execution capacity and trust boundaries |
Because the manifest is declarative and validated, the answer to "what is the state of the org?" is always read the file, run the gate β never "ask the person who knows." AI assistants read the manifest before touching org tooling; the orchestrator changes the file and validates.
π¦ Reusable Building Blocks: The Roll-Out Discipline¶
The foundation standard β the documentation contract, the governance templates, the command-surface verbs, the reusable scripts β lives in one place and reaches every repository through a disciplined roll-out: assess the current state, preview what would change, apply it idempotently. The roll-out never edits a repository's own surface β the repository's gates and its specifics stay its own. How this machinery is built is Part Three, which assumes the vocabulary introduced here and builds on it rather than re-teaching it; this is the self-improving loop from Chapter 1 made concrete:
flowchart LR
A["Improve the foundation<br/>(one place)"] --> B["Validate<br/>(gate green)"]
B --> C["Roll out to every repo<br/>(assess β preview β apply)"]
C --> D["Collect evidence<br/>(what worked, what drifted)"]
D --> A
style A fill:#e3f2fd
style B fill:#fff3e0
style C fill:#f3e5f5
style D fill:#e8f5e9
The multiplier made real. One human orchestrator, one control plane, and the same foundation rolls out across every repository. The book's claim in Chapter 1 β that the orchestrator's leverage comes from systems, not effort β is exactly this loop. (The quantified multiplier β "NΓ faster" β is a claim this book only makes once measured across a release milestone; treat marketing numbers elsewhere with suspicion.)
β¨ Self-Documenting Automation: The Timeless Intent Pattern¶
For the loop to work, every artifact must be reviewable by human or AI at any time, on the surface where it is actually reviewed. This is the Timeless Intent pattern β the invariant each artifact maintains, stated where it is read:
| Surface | The Contract |
|---|---|
| Automation run output | Every step: a timeless βΆ intent (the invariant it maintains), short action lines, a β
/β outcome, and on failure a β FIX: next action with a doc pointer |
| Code definition site | The file/function header states the invariant the code maintains; error messages carry the actionable β FIX: shape |
| Status dashboards | Every critical invariant is observable as a live signal, consuming the same check logic as the gates β never a second source of truth |
Timeless over incident. The intent is the enduring contract ("this hostname must always answer unauthenticated"), never the bug that prompted the fix ("your zone had sign-on enabled"). Incident detail β error codes, symptoms β belongs in the FIX line or the runbook, where it is timeless troubleshooting.
π‘ Why this matters for AI: an artifact that only makes sense in light of the last incident is not maintainable β by a human or an AI. The Timeless Intent pattern is what lets an AI agent read any workflow's output, spot a deviation, and propose the fix without a conversation history.
The Feature Ledger: Making Status Observable¶
Every repository maintains a capability ledger (features.md): each feature has a lifecycle state, a validation, and a dashboard signal. The states form a standard ladder:
planned β in-progress β implemented β configured β healthy β degraded β deprecated β removed
The ledger is the organisation's honesty surface. A capability is "healthy" only when its validation passes and its dashboard signal is live β status is observed, not asserted. This is the workflow-structure counterpart to the validation gates: enforcement on one side, visibility on the other.
π The Feedback Architecture¶
The self-improving loop runs on structured outputs. Each link in the chain β test results, validation-gate output, command responses β must be machine-readable, so the agent can locate a failure and act on it without a human interpreting the output first. If a single link outputs unstructured prose that only a human can interpret, the agent's ability to self-improve is severed at that point. Build the chain once β generate β run β parse β fix β propose β and every improvement after it is automatic.
π©Ί The Post-Mortem Auto-Update Rule¶
When an AI-generated change fails a validation gate, fixing the code is only half the work. The rule: the agent also proposes a specific update to a governance file β the Playbook, the Map, the runbook, or the change log β so the same failure cannot recur. The trigger is the structured failure output: the agent reads it, diagnoses the root cause, applies the fix, and proposes the governance update that encodes the lesson. A failure that fixes the code but forgets the lesson is a failure that will repeat.
π§ͺ Prompt Regression Testing¶
How do you know the Law is actually obeyed? By testing it. Prompt regression testing deliberately prompts the AI to violate a rule in a sandbox, verifies the constraint holds, and logs the result. Each test is logged to a dedicated regression log (docs/prompt-regression-log.md) β date, rule tested, the violation attempt, and the outcome β so the proof that the Law holds is reviewable by human and agent alike and stays out of the everyday context. If the Law can be talked out of enforcing its own rules, the problem is in the Law, not in the prompt: strengthen the constraint and re-run the regression. Adversarial testing in depth belongs to Part Two β the principle belongs here: a rule you have never tried to break is a rule you do not yet trust.
12. AI Agents in the Governed System¶
Key Focus: CLI assistants, IDE agents, and harnesses as readers of the repository's structure; the 3-Tier model strategy that routes work to the right model; and the boundaries that keep the human in charge.
Everything so far β the Law, the Map, the command surface, the gates β exists so that AI can work inside a governed system. This section shows how the agents plug in, how to route their work across model tiers, and where the lines are.
The Agent as Reader, Not Owner¶
The AI assistant β a CLI tool, an IDE agent, or a harness β is a reader of structure. It does not remember the rules; it reads them. It does not own the workflow; it invokes the commands. That is what makes assistants interchangeable β the same tool-centric-versus-repository-centric contrast Chapter 1 drew, now built rather than described.
π§ Key Insight: The book does not claim a specific assistant is more "reproducible" than another β that is a tool property to verify on your own bench, not a foundation claim. The foundation claim is stronger: any reader of the repository inherits its structure, so the workflow survives the tool.
π The 3-Tier Strategy: Routing Work to the Right Model¶
Model selection is fitness for purpose, not loyalty to a brand. The 3-Tier strategy is the routing rule used throughout this book's own production workflow:
| Tier | Role | Use It For |
|---|---|---|
| Tier 1 β Architect | Complex reasoning, system design | Architectural planning, deep structural reviews |
| Tier 2 β Editor | High-volume, repetitive execution | Default (~80% of tasks): editing, boilerplate, validation fixes |
| Tier 3 β Sovereign | Zero data egress, absolute privacy | Sensitive code, secrets, offline environments |
The default is Tier 2 β most work is routine. Escalate to Tier 1 only for complex reasoning. Mandate Tier 3 for anything sensitive: for sovereign work, models run locally, so nothing leaves the machine. The tier is defined by where the model runs, not by any one model or registry β pull a verified open-weight model and serve it on your own hardware. What each tier costs, when to escalate, and how to meter usage are economics this book considers properly in Part Two. The routing rule itself is durable: right-size the model to the task.
The Agent Harness Pattern¶
When work scales past a single interaction, the most advanced systems use a harness β a framework that orchestrates multiple agents toward a goal. The repository itself can act as one:
| Layer | Component | Role in the Loop |
|---|---|---|
| 1. Router | Makefile targets (make validate, make improve) |
Directs tasks to the right command and workflow |
| 2. Context Manager | AGENTS.md + AI_CONTEXT.md |
Shared state and rules; every agent reads from here |
| 3. Agent Pool | CLI assistants, IDE agents, validation scripts | Execute tasks; learn from feedback; improve over time |
| 4. Feedback Loop | Git history + validation results | Records outcomes; informs the next iteration |
The loop is the self-improving pattern from Chapter 1 in action: validation failures make the Law clearer, successful patterns enrich the Map, repeated tasks become new commands, and Git history shows what is working.
The AI Workflow Loop¶
Inside the governed system, every AI task follows the same sequence β the loop this book has been building toward:
- Read the Law (
AGENTS.md) β the non-negotiables - Read the Map (
AI_CONTEXT.md) β the architecture and conventions - Read the manifest when the task spans repositories β the org's source of truth
- Make the smallest coherent change
- Run the gate and iterate to green β never declare success on unverified work
- Stop and report β the boundary from Section 9: never stage, commit, or push
| Boundary (from Chapter 1) | Applied Here |
|---|---|
| Review before anything ships | AI output is treated like a junior engineer's PR |
| The repository is the source of truth | Agents read the Law and the Map; they don't own them |
| Validation is automated, not assumed | Gates run on every change; iterate-to-green is mandatory |
| Model work is right-sized | The 3-Tier strategy routes the task to the model that fits |
| Human authority is final | AI suggests; the human approves every write, commit, and release |
π‘οΈ The Human Orchestrator Authority¶
The self-improving loop has a last gate, and it is not automated. Human Orchestrator Authority: an AI agent may read, parse, suggest, execute commands, and propose fixes β but every change to the repository ultimately rests with the human orchestrator. The agent operates inside a sandbox of read / execute / suggest; the write / commit / merge authority is reserved for the human.
| The AI May | Only the Human May |
|---|---|
| Read the Law, the Map, and the state | Change the Law, the Map, and the contracts |
| Run commands and parse results | Commit, merge, and release |
| Propose fixes and governance updates | Approve or reject every proposal |
| Suggest a release | Ship it |
The workflow: AI generates β AI runs the tests β AI reads the results β AI proposes fixes β AI proposes governance updates β the human reviews and approves β changes are committed. Every step is automated except the final authority, which remains human.
π The safety net: this is what keeps the "self-improving" loop from ever becoming a "self-destructing" loop. The human can reject, modify, or override any proposal. The AI is a powerful assistant, not an autonomous decision-maker β and every procedure in the Playbook carries an explicit human approval gate before anything is committed. The AI does ninety-five percent of the work; the human signs the final five percent.
13. Synthesis: The Repository as the Ultimate Force Multiplier¶
Key Focus: How the six capabilities operate as one lifecycle β and why building them into the repository raises the quality of every tool plugged into it.
The six capabilities are not six features. They are one operating loop, and each stage is what keeps the next honest:
flowchart LR
R["Read<br/>(Law + Map)"] --> RO["Route<br/>(load the slice)"]
RO --> A["Act<br/>(follow the procedure)"]
A --> V["Validate<br/>(gate each step)"]
V --> L["Log<br/>(context & action summary)"]
L --> E{"Escalate<br/>or complete?"}
E -->|"condition fired"| H["Human decides"]
E -->|"green"| D["Done"]
H --> RO
style R fill:#e3f2fd
style RO fill:#e3f2fd
style A fill:#fff3e0
style V fill:#fff3e0
style L fill:#f3e5f5
style E fill:#e8f5e9
Routing and budgeting (Sections 3 and 7) decide what enters the prompt; act and validate (Sections 5 and 10) decide how the work is done. Log (Section 8) records it, and escalate (Section 6) hands the loop back to the human. The heartbeat from Chapter 1 β propose, validate, apply, repeat β is this loop seen from the repository's side.
π The Order Is a Dependency, Not a Preference¶
Routing precedes economy: you cannot budget a context you do not control. Continuity precedes transparency: there is nothing to summarize if state does not survive. Boundaries precede orchestration: chaining steps is safe only once stop conditions exist. Transparency sits over all of it.
Implement in this order: routing, continuity, boundaries, orchestration, economy, transparency.
The Maturity Model: Minimum Viable, Then Full¶
No repository adopts all six at once. Start with the minimum; take the full pattern when the work justifies it.
| Capability | Minimum viable | Full pattern |
|---|---|---|
| Context Routing | One routing table | Per-task-type routing, verified |
| Session Continuity | Artifact with task and next step | Full schema with decisions and gate status |
| Workflow Orchestration | One named, gated procedure | A library with stop conditions and rollback |
| Escalation Boundaries | Six declared stop conditions | Conditions plus tests that trigger them |
| Context Economy | The Law/Map split alone | Task-scope budgeting, reviewed per task |
| Execution Transparency | An append-only log with the core fields | The full summary, checked against routing |
The minimum column is a real implementation, not a placeholder: each row closes its failure mode.
Why This Elevates Any Tool¶
A repository built this way does not depend on a capable assistant; it supplies what the assistant lacks β session memory, context selection, workflow support, guardrails, cost control, and audit history. A modest tool plugged into it therefore behaves like a better one, because the structure it lacks was never the tool's job. This is the chapter's opening claim β the repository is the hero β demonstrated, not asserted.
π§ Key Insight: You do not wait for a tool to gain these capabilities. You build them once, in the repository, and every tool you plug in inherits them β the practical meaning of "tools are transient, the repository is permanent."
14. Putting It Into Practice¶
Key Focus: The bootstrap β build your own control plane or clone one β plus the checklist and quick reference that turn this chapter into a working system.
Build or Clone: The Bootstrap¶
You have two valid starting points:
| Path | When to Choose It | First Steps |
|---|---|---|
| Clone a control plane | A foundation already exists (team, org, or your own past work) | git clone β make help β make setup β start |
| Build your own | Starting fresh, or the existing repos are unstructured | Follow the 30-minute bootstrap below |
The 30-minute bootstrap, compressed to what actually matters:
# 1. Initialize (5 min)
git init && touch README.md .gitignore
# 2. The Law, the Map, and the Playbook (10 min)
# AGENTS.md β rules that never change; AI_CONTEXT.md β architecture and facts;
# PLAYBOOK.md β the procedures that must be repeatable and gated.
# If you manage more than one repo, keep the reusable parts generic β how
# they are shared is a later-part concern, not part of this bootstrap.
# 3. The command surface (5 min)
# Makefile with thin targets: help, setup, validate, check-staged, ci,
# plus the VCS surface (status, sync, log, diff, commit, release).
# 4. The gates (5 min)
# scripts/validate.sh β a REAL check. A stub that prints success is a lie.
# 5. The first loop (5 min)
make validate && git add <paths> && make commit
β Foundation Checklist¶
β‘ README.md β the front door: what this repo is, how to start, links to governance
β‘ architecture.md β the core blueprint: design, components, constraints
β‘ AGENTS.md β the Law: rules that never change
β‘ AI_CONTEXT.md β the Map: current state, conventions, key file locations
β‘ PLAYBOOK.md β the Playbook: procedures with explicit human approval gates
β‘ docs/features.md β the delivery-plan ledger: planned and released work
β‘ docs/capabilities.md β the drivers: the business outcomes behind the work
β‘ observability.md β the operational mirror (when the repo is operated)
β‘ operations.md β the runbook (when the repo is operated)
β‘ CHANGELOG.md β a record of what changed and why
β‘ The command surface β thin targets / CLI verbs that delegate to scripts/
β‘ scripts/ β the real logic, including a REAL validate gate
β‘ Structured test results β machine-parseable output the agent can read
β‘ docs/prompt-regression-log.md β the rule-violation regression log (adopt with prompt regression testing)
β‘ The staged flow β manual git add, gated commit, tag-based release
β‘ An AI assistant configured to read the Law and the Map
β‘ A human approval gate on every write, commit, and release
β‘ Context routing rules β task type β Map sections
β‘ `.session/` in `.gitignore` β the session artifact
β‘ One named, gated Playbook procedure
β‘ Escalation conditions in the Law β the stop-and-report rules
β‘ Context-loading rules β what loads when
β‘ `docs/ai-execution-log.md` β the action summary log
β‘ A verification step for each capability β one check you can run
π Quick Reference¶
Commands are illustrated as Make targets; the same verbs are surfaced through your CLI where one exists β the verb is the contract.
| Action | Command |
|---|---|
| See every command | make help |
| Fast commit gate | make check-staged |
| Full gate (local == CI) | make ci |
| Commit staged changes | make commit (custom message: m="..." make commit) |
| Tag-based release | make release [TAG=v1.2.3] |
| Review the staged diff | make diff-staged |
| Sync with upstream | make sync |
Common Issues & Fixes¶
| Issue | Likely Cause | Fix |
|---|---|---|
| Gate passes but nothing was checked | Stub gate | Replace with a real check β a fake gate is a lie |
make commit refuses to run |
Staged gate failed | Read the failure, fix the root cause, re-run (iterate to green) |
| AI "completed" without running the gate | No enforcement | Require iterate-to-green; treat unverified work as blocked |
| Different commands in different repos | Surface drift | Align to the standard names; same intent β same command |
| High token spend | Context bloat / wrong tier | Use the Law/Map split; route with the 3-Tier strategy |
| Entire Map loaded for a one-line change | No context routing | Add task-type routing |
| A new tool cannot continue previous work | No session artifact | Create .session/current.md; gitignore it |
| Edits chained without validating between steps | No Playbook procedure | Write one named, gated procedure |
| Agent "fixed" something outside its scope | No escalation conditions | Declare stop-and-report rules |
| Small tasks cost as much as large ones | No task-scope budgeting | Add context-loading rules per task scope |
| Cannot verify the agent followed the routing | No execution log | Add the log; require the summary |
15. Chapter Summary¶
Key Focus: The universal pattern β what you can now build, and the one-line law the whole chapter rests on.
What You Learned¶
This chapter built the repository that holds Chapter 1's three structures:
- The repository is the hero β four layers (Content, Validation, Intelligence, Automation) plus a layered documentation contract make it readable by humans and AI alike β and it carries every link of Chapter 1's chain, from driver to outcome
- The Law, the Map, and the Playbook β
AGENTS.mdholds the rules,AI_CONTEXT.mdholds the context,PLAYBOOK.mdholds the gated procedures β and reusable building blocks keep all three identical across many repositories - The command surface is a contract β one dual-usable surface for humans and agents over pluggable scripts; shared blocks stay identical, repository-owned gates stay local
- Gates are promises β real or absent, arranged as a ladder (atomic β commit β full), with the Iterate-to-Green loop and machine-readable results making AI self-correcting
- The loop compounds at scale β the control-plane concept (a single source of truth, reusable building blocks, a disciplined roll-out) turns one improvement into an organisation-wide improvement; structured feedback, the Post-Mortem Auto-Update Rule, and prompt regression testing keep the loop honest
- Agents are readers, not owners β they inherit the structure, are routed by the 3-Tier strategy, and work inside the boundaries you hold β with Human Orchestrator Authority as the final gate
- The repository operates the agent β six capabilities (routing, session continuity, orchestration, escalation boundaries, context economy, execution transparency) turn a governed repository into an operating environment that any tool inherits
The Universal Pattern¶
Any repository + AI + Git + Validation = a self-improving system
Where: - Every change is auditable (Git commits) - Every change is validated (real gates) - Every change improves the system (the loop feeds back) - The workflow itself evolves (templates + sync)
Your Next Steps¶
1. Build or clone your self-improving repository (30 minutes)
- Law, Map, Playbook, command surface, real gates
2. Run your first improvement cycle (15 minutes)
- Improve β validate β iterate to green β human approves β commit
3. Expand to your actual work (ongoing)
- Any repository: the pattern is portable
4. Scale to a control plane (when you manage more than one repo)
- One source of truth β shared blocks β roll-out β evidence
16. Where This Leads: From One Repository to Many¶
Key Focus: The arc β this chapter completes the foundation; what comes next applies the pattern to your work, then scales it.
What Comes Next¶
You now hold the governed repository: the unit of orchestration. The book continues in two practice parts, and the patterns you built here are the ones every later chapter reuses:
- Part Two β The Orchestrator's Workbench takes this foundation into real delivery work: where each control belongs and what belongs in the tool, what AI-readable code and architecture look like, the six concerns in depth, and how to assemble a real system from providers, dependencies and contracts.
- Part Three β The Delivery System makes it organisational: version control as the portfolio's source of truth, the control plane as a product, versioning and release management, governance the machines enforce, the agent plane at scale, portfolio operations and measurement β closing by walking the abilities named in Chapter 1 Β§4.9, and stating for each what the evidence is.
The patterns you built here are the ones every later topic reuses:
| You Built in This Chapter | Every Later Topic Reuses |
|---|---|
| A stable command surface | Same verbs, different backends β the contract never changes |
| Real gates with structured results | Nothing claims success until it is validated |
| The Law, the Map, and the Playbook | Governing every AI interaction, in any domain |
| Human Orchestrator Authority | The final gate on every change, everywhere |
| Context routing and budgeting | Cost stays proportional to task scope |
| Session artifact and execution log | Work and its reasoning survive every tool change |
π§ Key Insight: The repository is the seed of the control plane. Get the single unit right β stable commands, real gates, structured feedback, human authority β and multiplying it is a mechanical problem. Get the unit wrong, and you scale the mess.
From one governed repository to many β Part Two builds the workbench, Part Three makes it a delivery system.
Part of: The DevOps Engineer's Guide to Effective AI Usage β and Becoming a Software Orchestrator