Building a Production App from Scratch with AI Agents: Architecture and the Self-Evolving Governance System
1. Introduction
Can an AI agent write production-grade code — not a demo, not a prototype, but a real multi-site crypto trading app serving a large user base?
We did it. Over a million lines of Dart code, tens of thousands of files, several million total lines across many languages — all generated by AI agents. No human writes code line by line; humans only define constraints and approve architecture decisions.
This post covers three parts:
- The App Architecture — the Clean Architecture layering and multi-site dispatch the AI must respect
- The Governance System — the four-layer governance system that constrains AI behavior
- The Self-Evolution Loop — How the governance system improves itself after every mistake
2. Architecture Overview
Two Systems, One Repo
| Dimension | App Code | Governance Code |
|---|---|---|
| Volume | 1M+ lines (Dart) | Tens of thousands of lines of constraints + hundreds of thousands of lines of knowledge docs |
| Producer | AI Agent | AI Agent (validated by human) |
| Evolution | Feature development | Self-evolution from mistakes |
| Verification | Type checker + tests + gate scripts | Gate scripts + contract assertions |
| Ratio | — | Every 2–3 lines of Dart map to roughly 1 line of Markdown |
The last number is the key insight: code and governance are at near 1:1 investment level. This is the real cost of getting production-grade output from AI agents.
3. App Architecture — The Boundaries the AI Must Respect
3.1 Five-Layer Clean Architecture
| Layer | Responsibility |
|---|---|
| App (multiple regional sites) | Site entry, site-specific config, DI bootstrap |
| Features | Pages, Hubs, Widgets |
| Domain | Repository interfaces + UseCases |
| Infrastructure | Implements Core interfaces (network, storage, device …) |
| Core | Pure interfaces + shared contracts |
Strict dependency rules: dependencies point toward Core — business code depends on interfaces, never on implementations. Domain and Infrastructure never depend on each other; both face Core only, and DI wires the implementations at startup. Violations fail the build. This rule is expressed in a short block of text that is always loaded into every AI conversation — like a hardware-level constraint that cannot be bypassed.
3.2 Multi-Site Without If/Else
The app serves multiple regional markets with different features, compliance requirements, and UI. The differentiation mechanism:
| Mechanism | When to use | How it works |
|---|---|---|
| Config | A value/toggle differs per site | Abstract class with defaults; each site overrides |
| Delegate | A behavioral step differs per site | Abstract class with default implementation; site overrides one method |
| Service | Entire capability differs per site | Interface; each site provides completely different implementation |
Zero if (site == 'xxx') in shared code. DI polymorphism IS the dispatch — each site registers its own implementations at startup, and runtime site-switching re-injects them atomically.
3.3 Reactive State Management
The state layer uses a signal-based system (similar to Solid.js signals, but in Dart):
Data flows one way: WebSocket push → Service (broadcast stream) → Hub (StreamSignal) → Widget (minimal subtree rebuild); user actions flow back by calling Hub methods.
- Hub = pure Dart state container (zero UI framework imports, zero BuildContext)
- Signal = reactive primitive (value changes → dependents rebuild automatically)
- Watch = minimal subtree rebuild (only the widget reading that signal rebuilds)
20+ hard constraints govern how Hubs are written. Each one is distilled from hands-on development experience.
4. The Governance System — A Four-Layer Architecture for Constraining the AI
4.1 Four-Layer Governance Hierarchy
| Layer | Count | Lines | Loading Strategy | Role |
|---|---|---|---|---|
| Rules | Dozens | A few thousand | Always loaded (every conversation) | MUST / MUST NOT hard constraints |
| Guides | Dozens | Tens of thousands | On demand (file-path routing) | Full examples, decision trees, templates |
| Skills | ~100 | — | Triggered by intent | End-to-end automated workflows |
| Learnings | Hundreds | Tens of thousands | Consumed during self-evolution | Raw material: pitfalls, decisions, patterns |
Why four layers instead of one big document?
Context window is finite. Loading tens of thousands of lines into every conversation is impossible. The layered design is an attention budget optimization:
- Rules (a few thousand tokens): always loaded — violations are always bugs
- Guides: loaded only when the AI touches a related file path
- Skills: loaded only when the user's intent matches
- Learnings: never loaded into working conversations — only consumed during evolution
4.2 File-Path Routing
When the AI modifies a file, the system automatically loads relevant governance:
| File path pattern | Governance loaded |
|---|---|
| Routing-related files | Routing guide + pop contract + deeplink encoding rules |
*_hub.dart | State management guide (20+ constraints) |
| Storage-related files | Storage guide (type boundaries, encryption tiers) |
pubspec.yaml | Dependency rules (layer matrix) |
| WebSocket / stream files | Stream subscription guide (reference counting, dead-stream traps) |
The AI gets different instructions depending on what code it's touching — like a semantic-level linter that can express runtime constraints.
4.3 Intent Routing
When the user expresses an intent, the system routes to the right skill:
| User says | Skill triggered | What happens |
|---|---|---|
| "Add a new page" | add-page | Generates route + page + hub + DI registration |
| "What's the test coverage?" | easytest | Queries coverage data, diagnoses gaps, suggests next action |
| "Migrate this module" | migrate-module | Multi-phase workflow with gates between phases |
| "Analyze this crash" | crashlytics-blame | Parses stack trace, git blames, reproduces, finds root cause |
4.4 Anti-Hallucination Protocol
The #1 risk of AI-generated code isn't style — it's fabrication. The AI might:
- Import a class that doesn't exist
- Reference an API path it invented from naming patterns
- Assume a method signature without checking
Five mandatory steps before generating code:
- INVESTIGATE — Read actual files before drawing conclusions; no guessing
- REFLECT — State why/what/how before each tool call
- GENERATE KNOWLEDGE — List 2-3 verifiable facts before writing
- REUSE OVER CREATE — Search existing code/libraries first; label source and confidence
- VERIFY — Self-check for fabricated entities/relations/context; delete anything unsourced
Hard rules on top:
- Financial data (prices, rates, contract params) — never fabricate, period
- File paths — must
lsparent directory before generating - Identifiers — never infer from naming patterns, grep to verify first
5. Skills — From "Write Code" to "Execute Workflow"
5.1 A Skill Is Not a Prompt Template
A skill = an end-to-end automated workflow:
A prompt template is one-shot text: feed it to the model, take whatever comes back — no pre-checks, no gates, no way to verify the result. A skill packages an intent trigger, phased instructions, deterministic scripts, gate assertions and artifacts together:
Pre-checks → Phase 0 → Gate assertion → Phase 1 → Gate assertion → ... → Phase N → OutputIf a gate assertion fails, the workflow is hard-blocked — no skipping, no bypassing.
5.2 Skill Categories
| Category | Examples | Capability |
|---|---|---|
| Code generation | Add page, add hub, add service | Generate architecture-compliant code from zero |
| Testing | Add test, case-to-test, coverage tracking | Code→test, use-case→test |
| Migration | Migrate module, migrate image | Legacy→new 1:1 migration with verification |
| Quality | Quality convergence, lint fix, code review | Automated quality guard |
| Operations | Fix iOS build, disk cleanup | Dev environment repair |
| Analysis | Crash analysis, MR understanding | Problem diagnosis |
5.3 Skill Boundaries = Blast Radius Boundaries
Critical design decision: skills have strict input boundaries.
Example: coverage gap from lcov (code fact) → code-driven skill. Untranslated QA test cases (case fact) → case-driven skill. These two must never cross — mixing them lets each skill's responsibilities and outputs contaminate the other. Problems like this are recorded as learnings and, once they accumulate, upgraded to a formal rule.
6. The Self-Evolution Loop — How the Governance System Improves Itself
6.1 The Closed Loop
Mistake / Correction / Effective pattern found
↓
Record to learnings (pitfall- / decision- / pattern- / drift-)
↓
Same topic accumulates ≥3 entries
↓
Trigger harness-evolve → Propose upgrade to rules / guides / skills
↓
Human confirms → Formal governance (committed to git, shared across team)6.2 Five Trigger Moments for Learnings
| Trigger | Learning prefix | Example |
|---|---|---|
| AI gets corrected | pitfall- | "Don't use Stream.value to mock continuous streams" |
| Governance gap found | pitfall- / pattern- | "No rule covers storage schema migration in tests" |
| Architecture decision made | decision- | "Chose DI polymorphism over feature flags for site differentiation" |
| Skill execution drifts | drift- | "migrate-module skipped Phase 2 gate check" |
| Effective pattern validated | pattern- | "Property-based sort test is more stable than exact-match" |
6.3 Evolution in Practice
A typical, generic example:
Round 1: AI writes a Mock class without stubbing all consumed getters → test crashes with Null is not subtype of bool. Learning recorded.
Round 2: Same pattern in a different module. Learning recorded again.
Round 3: Third occurrence triggers harness-evolve. System proposes a new MUST NOT rule:
"Never declare a Mock class without stubbing every getter/method the production code consumes"
Human confirms → rule is committed. The AI never makes this mistake again.
6.4 Why Not Write Rules Upfront?
Because you don't know what you don't know.
Coarse constraints can be predefined ("App layer must not import Infrastructure"). But fine-grained pitfalls ("mocktail's any(named:) for abstract parameters needs registerFallbackValue") only emerge through real experience.
The learning pool is the accumulator for this discovery process. Rules are distilled wisdom; learnings are raw experience.
7. Quality Gates — The Last Line of Defense
7.1 Pre-Submit Quality Checks
Code change
├─ Identify the scope affected by the change
├─ Run automated tests and quality checks
└─ Checks fail → submission blockedEvery change goes through automated testing and quality checks before submission; only changes that pass make it into the codebase.
7.2 Background Prewarming
Checks run ahead of time in the background after each commit and their results are reused, cutting the pre-submit wait from minutes to seconds.
7.3 Change Management
Even governance changes go through a formal workflow:
Proposal → Design → Task breakdown → Implementation → Verification → ArchiveOver a hundred formal changes have been managed this way. Prevents "governance drift" — where rules accumulate contradictions without holistic review.
8. Real-World Numbers
| Metric | Value |
|---|---|
| Dart code | 1M+ lines |
| Total code (all languages) | Several million lines (many languages) |
| Files | Tens of thousands |
| Git commits | 10,000+ |
| Governance constraints | Tens of thousands of lines (Rules + Guides + Learnings) |
| Knowledge docs | Hundreds of thousands of lines (design docs + guides) |
| Skills | ~100 |
| Formal changes | 100+ |
| Self-evolved learnings | Hundreds |
| Regional sites | Multiple |
| Component packages | 10+ |
9. Design Tradeoffs
1. Why always-load rules instead of all-on-demand?
Rule violations are always bugs (e.g., cross-layer imports). Can't rely on routing to catch them — must be in every context window. Cost: a few thousand tokens permanently occupied per conversation.
2. Why ≥3 occurrences before upgrading to a formal rule?
A single pitfall might be a corner case. Three occurrences prove it's systemic. Premature rules create false constraints.
3. Why ~100 separate skills instead of fewer general-purpose ones?
Skill boundary = blast radius boundary. add-test breaking only affects tests, not routing. Combining skills combines their failure modes.
4. Why not replace text governance with automated linters?
Linters check syntax patterns. They can't express "when switching sites, cached DI references become stale" — that's a runtime semantic constraint requiring a natural-language explanation of the why, plus example code showing the how.
5. Why not let humans write code for critical parts?
Consistency. An AI that strictly follows the rules produces more architecturally consistent code than 5 humans with different habits. The governance system IS the senior engineer — it just happens to be made of text files.
6. What's the cost?
Context window consumption. The rules permanently occupy a few thousand tokens per conversation. The fundamental tradeoff of AI governance: attention vs correctness.
10. Conclusion
Making AI write code is easy. Making AI continuously write correct code requires a governance system with investment proportional to the codebase itself.
Our governance system wasn't designed in one shot — it's the product of hundreds of learnings, and over a hundred formal changes. Every rule and every learning comes from real feedback in practice.
The real scaling law of AI coding: code can be generated infinitely, but governance must evolve in lockstep.
Three numbers to remember:
- 1 : 2–3 — the governance-to-Dart line ratio, near 1:1 investment level
- Hundreds — learnings accumulated before the system stabilized
- ~100 — skills that turn "write code" into "execute verified workflow"
One sentence: Getting AI to continuously write correct code relies not on smarter models, but on a governance system that co-evolves with the codebase.