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:

  1. The App Architecture — the Clean Architecture layering and multi-site dispatch the AI must respect
  2. The Governance System — the four-layer governance system that constrains AI behavior
  3. The Self-Evolution Loop — How the governance system improves itself after every mistake

2. Architecture Overview ​

Architecture Overview

Two Systems, One Repo ​

DimensionApp CodeGovernance Code
Volume1M+ lines (Dart)Tens of thousands of lines of constraints + hundreds of thousands of lines of knowledge docs
ProducerAI AgentAI Agent (validated by human)
EvolutionFeature developmentSelf-evolution from mistakes
VerificationType checker + tests + gate scriptsGate 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 ​

Five-Layer Clean Architecture

LayerResponsibility
App (multiple regional sites)Site entry, site-specific config, DI bootstrap
FeaturesPages, Hubs, Widgets
DomainRepository interfaces + UseCases
InfrastructureImplements Core interfaces (network, storage, device …)
CorePure 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:

MechanismWhen to useHow it works
ConfigA value/toggle differs per siteAbstract class with defaults; each site overrides
DelegateA behavioral step differs per siteAbstract class with default implementation; site overrides one method
ServiceEntire capability differs per siteInterface; 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):

Reactive State Management

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 ​

Four-Layer Governance Hierarchy

4.1 Four-Layer Governance Hierarchy ​

LayerCountLinesLoading StrategyRole
RulesDozensA few thousandAlways loaded (every conversation)MUST / MUST NOT hard constraints
GuidesDozensTens of thousandsOn demand (file-path routing)Full examples, decision trees, templates
Skills~100—Triggered by intentEnd-to-end automated workflows
LearningsHundredsTens of thousandsConsumed during self-evolutionRaw 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

Governance Routing

4.2 File-Path Routing ​

When the AI modifies a file, the system automatically loads relevant governance:

File path patternGovernance loaded
Routing-related filesRouting guide + pop contract + deeplink encoding rules
*_hub.dartState management guide (20+ constraints)
Storage-related filesStorage guide (type boundaries, encryption tiers)
pubspec.yamlDependency rules (layer matrix)
WebSocket / stream filesStream 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 saysSkill triggeredWhat happens
"Add a new page"add-pageGenerates route + page + hub + DI registration
"What's the test coverage?"easytestQueries coverage data, diagnoses gaps, suggests next action
"Migrate this module"migrate-moduleMulti-phase workflow with gates between phases
"Analyze this crash"crashlytics-blameParses 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:

  1. INVESTIGATE — Read actual files before drawing conclusions; no guessing
  2. REFLECT — State why/what/how before each tool call
  3. GENERATE KNOWLEDGE — List 2-3 verifiable facts before writing
  4. REUSE OVER CREATE — Search existing code/libraries first; label source and confidence
  5. 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 ls parent 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 Skill Is Not a Prompt Template

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 → Output

If a gate assertion fails, the workflow is hard-blocked — no skipping, no bypassing.

5.2 Skill Categories ​

CategoryExamplesCapability
Code generationAdd page, add hub, add serviceGenerate architecture-compliant code from zero
TestingAdd test, case-to-test, coverage trackingCode→test, use-case→test
MigrationMigrate module, migrate imageLegacy→new 1:1 migration with verification
QualityQuality convergence, lint fix, code reviewAutomated quality guard
OperationsFix iOS build, disk cleanupDev environment repair
AnalysisCrash analysis, MR understandingProblem 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 ​

Self-Evolution Loop

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 ​

TriggerLearning prefixExample
AI gets correctedpitfall-"Don't use Stream.value to mock continuous streams"
Governance gap foundpitfall- / pattern-"No rule covers storage schema migration in tests"
Architecture decision madedecision-"Chose DI polymorphism over feature flags for site differentiation"
Skill execution driftsdrift-"migrate-module skipped Phase 2 gate check"
Effective pattern validatedpattern-"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 ​

Quality Gate Stack

7.1 Pre-Submit Quality Checks ​

Code change
  ├─ Identify the scope affected by the change
  ├─ Run automated tests and quality checks
  └─ Checks fail → submission blocked

Every 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 → Archive

Over a hundred formal changes have been managed this way. Prevents "governance drift" — where rules accumulate contradictions without holistic review.


8. Real-World Numbers ​

MetricValue
Dart code1M+ lines
Total code (all languages)Several million lines (many languages)
FilesTens of thousands
Git commits10,000+
Governance constraintsTens of thousands of lines (Rules + Guides + Learnings)
Knowledge docsHundreds of thousands of lines (design docs + guides)
Skills~100
Formal changes100+
Self-evolved learningsHundreds
Regional sitesMultiple
Component packages10+

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.