# ADT – Implementation Plan (v2)

> Comprehensive plan for building Auto Dev Team from zero to production.
> Incorporates all 15 architectural refinements from design discussions.
> Status: **Draft for discussion**

---

## Table of Contents

1. [Guiding Principles](#1-guiding-principles)
2. [System Modules](#2-system-modules)
3. [MVP Scope](#3-mvp-scope)
4. [Post-MVP Roadmap](#4-post-mvp-roadmap)
5. [Implementation Phases](#5-implementation-phases)
6. [Functionality Breakdown per Module](#6-functionality-breakdown-per-module)
7. [Phase Dependency Map](#7-phase-dependency-map)
8. [Risk & Mitigation](#8-risk--mitigation)
9. [Summary & Timeline](#9-summary--timeline)

---

## 1. Guiding Principles

- **ADT builds itself** — The platform must be developed following its own 3.1–3.8 workflow.
- **Local-first** — Everything must work locally before moving to cloud/K8s.
- **Agent-first architecture** — The multi-agent system is the core; everything else wraps around it.
- **Modular monolith** — Every module must be deployable independently or together.
- **Quality gates are non-negotiable** — No step proceeds without the previous step's acceptance.
- **Agents are stateless workers** — All state lives in the Task model and Context Manager, not in agents.
- **Top-down, general-to-particular** — Every producing agent follows L1→L2→L3→L4 generation.
- **Structural validation before LLM review** — Mechanical checks run before self-challenge.
- **Trace everything from day one** — Cost and trace data collected from the first LLM call.

---

## 2. System Modules

ADT is composed of **two major systems**, each containing multiple modules:

### System A: Agent Engine (the brain)

| Module | Code Name | Description |
|--------|-----------|-------------|
| A1 | `agent-core` | Agent base framework: lifecycle, tools, self-challenge, structural validation, top-down generation, LLM abstraction, escalation protocol |
| A2a | `orchestrator` | Workflow engine: pipeline definition, adaptive pipeline from archetypes, state machine, step gates |
| A2b | `coordinator` | Agent coordinator: task decomposition (module × L1-L4), hybrid assignment, module locking, parallelism, dependency tracking |
| A3 | `agent-pm` | PM Agent — requirement gathering, archetype selection, tech stack resolution, complexity assessment |
| A4 | `agent-architect` | Architect Agent — design generation (top-down L1→L4), diagrams, module boundaries |
| A5 | `agent-ux` | UX Agent — UI flow prototyping *(post-MVP)* |
| A6 | `agent-dev` | Dev Agent — code generation (top-down L1→L4), TDD, fix loop with regression |
| A7 | `agent-qa` | QA Agent — test definition (top-down), test quality review, unit + integration testing, regression re-runs |
| A8 | `agent-devops` | DevOps Agent — repo setup, workspace management |
| A9 | `agent-reviewer` | Reviewer Agent — workflow verification, acceptance gate validation |
| A10 | `agent-delivery` | Delivery Agent — packaging (top-down), documentation generation, ZIP delivery |
| A11 | `shared-rag` | Shared knowledge base (RAG) + reference implementations per archetype |
| A12 | `prompt-handler` | Common prompt management, versioned templates |
| A13 | `context-manager` | Centralized context hydration: recipes, smart windowing, snapshots, summarization |
| A14 | `task-queue` | Task persistence, role-based queues, task assignment, module locks |
| A15 | `trace-system` | Hierarchical tracing, LLM cost tracking per provider/model, audit log |
| A16 | `archetype-registry` | Project archetype definitions, pipeline adaptation, tech stack defaults |
| A17 | `billing-agent` | Billing Agent — independent cost traceability |

### System B: SaaS Platform (the body)

| Module | Code Name | Description |
|--------|-----------|-------------|
| B1 | `platform-auth` | Signup, login, authentication, organization management |
| B2 | `platform-tenancy` | Multi-tenant isolation, tenant configuration |
| B3 | `platform-projects` | Project CRUD, lifecycle management, concurrent projects |
| B4 | `platform-chat` | Customer chat interface for interacting with agents |
| B5 | `platform-dashboard` | Analytics dashboards (spend, savings, time) |
| B6 | `platform-billing` | Pricing engine, cancellation logic, step-based billing |
| B7 | `platform-admin` | Organization admin tools, user management, roles |
| B8 | `platform-artifacts` | Artifact storage, reports, deliverables management |
| B9 | `platform-debug` | Post-delivery debugging intake and management |
| B10 | `platform-api` | External API layer for all platform operations |

---

## 3. MVP Scope

> **Goal**: A working local system where one user can submit a software request and ADT agents take it through the full adaptive pipeline, producing a real deliverable with full traceability.

### MVP = Agent Engine (core) + Minimal Platform Shell

#### ✅ IN MVP

| ID | Functionality | Module(s) | Why MVP |
|----|--------------|-----------|---------|
| MVP-01 | Agent base framework (lifecycle, tools, comms) | A1 | Foundation — nothing works without this |
| MVP-02 | Top-down generation protocol (L1→L4) | A1 | Core quality mechanism for all producing agents |
| MVP-03 | Self-challenge protocol | A1 | Every agent self-validates output before handoff |
| MVP-04 | Structural validation layer (lint, types, parse) | A1 | Mechanical checks before LLM self-challenge |
| MVP-05 | LLM abstraction layer (multi-provider, deterministic settings) | A1 | Foundation for best-model-per-role strategy |
| MVP-06 | Human escalation protocol | A1 | Know when to stop and ask for help |
| MVP-07 | Workflow orchestrator with adaptive pipeline | A2a | Pipeline adapts per archetype — core differentiator |
| MVP-08 | Agent coordinator with module locking & parallelism | A2b | Tasks decomposed per module × L1-L4, parallel execution |
| MVP-09 | Task model (persistent, pausable, acceptance criteria) | A14 | Every unit of work is tracked and resumable |
| MVP-10 | Context Manager (recipes, snapshots, smart windowing) | A13 | Anti-hallucination — agents get only what they need |
| MVP-11 | Archetype registry (script, cli_tool, api_backend, web_app, etc.) | A16 | Right pipeline for the right project type |
| MVP-12 | Tracing system (hierarchical traces, LLM cost tracking) | A15 | Observability from day one; feeds future pricing |
| MVP-13 | PM Agent — chat, archetype selection, tech stack, estimation | A3 | First step in every project |
| MVP-14 | Architect Agent — top-down design generation + diagrams | A4 | Quality gate before development |
| MVP-15 | Dev Agent — top-down code generation (L1-L4), fix loop with regression | A6 | Core value — actual software output |
| MVP-16 | QA Agent — test definition (top-down), quality review, unit + integration tests | A7 | Quality assurance with test quality gate |
| MVP-17 | DevOps Agent — GitHub repo creation & workspace management | A8 | Workspace for agents |
| MVP-18 | Reviewer Agent — workflow verification & acceptance validation | A9 | Ensures pipeline integrity |
| MVP-19 | Delivery Agent — packaging, documentation, ZIP delivery | A10 | Deliverable output |
| MVP-20 | Billing Agent — independent cost tracking | A17 | Isolated billing traceability |
| MVP-21 | Shared RAG with reference implementations per archetype | A11 | Token efficiency + anti-hallucination grounding |
| MVP-22 | Prompt handler with versioned templates | A12 | Consistency across agents + A/B capability |
| MVP-23 | Minimal web UI (React + Tailwind: chat + project tracking) | B4 | Web-first; SaaS-ready patterns |
| MVP-24 | Project state tracking (PostgreSQL) | B3 | Track where a project is in the pipeline |
| MVP-25 | Artifact storage (local filesystem + repo) | B8 | Reports, code, diagrams need to be stored |

#### ❌ NOT IN MVP (deferred)

| ID | Functionality | Module(s) | Why Deferred |
|----|--------------|-----------|--------------|
| POST-01 | UX Agent — navigable prototype generation | A5 | Complex; design acceptance can use static mockups |
| POST-02 | Kubernetes deployment | A8 | Local-first; K8s adds infra complexity |
| POST-03 | Kustomize + GitHub Actions CI/CD | A8 | Requires K8s; defer until cloud phase |
| POST-04 | System/interaction testing on K8s | A7 | Requires K8s deployment |
| POST-05 | Customer signup & authentication | B1 | Single-user local mode first |
| POST-06 | Multi-tenant support | B2 | Single-user local mode first |
| POST-07 | Analytics dashboards | B5 | Trace data collected from day one; dashboards later |
| POST-08 | Billing & pricing engine | B6 | No payments until SaaS launch |
| POST-09 | Organization/user management | B7 | Single-user first |
| POST-10 | Post-delivery debugging flow | B9 | Requires delivery to exist first |
| POST-11 | Repository fork to customer | A10 | Requires multi-tenant GitHub setup |
| POST-12 | Packaged artifacts (compiled images) | A10 | Requires containerization pipeline |
| POST-13 | External API layer | B10 | Internal-first, API later |
| POST-14 | Concurrent project execution | B3 | Single project first, scale later |
| POST-15 | Outcome learning / feedback loops | — | Architecture supports from day one; implementation later |

---

## 4. Post-MVP Roadmap

### Wave 2: Full Pipeline + Cloud Readiness
- UX Agent with navigable prototypes
- Kubernetes deployment support
- Kustomize + GitHub Actions
- System/interaction testing on K8s
- Repository fork delivery
- Packaged artifact delivery

### Wave 3: SaaS Platform Launch
- Customer signup & auth
- Multi-tenant isolation
- Organization & user management
- Billing & pricing engine (uses trace data from day one)
- External API layer

### Wave 4: Scale & Intelligence
- Analytics dashboards (uses trace data from day one)
- Post-delivery debugging
- Concurrent project execution
- Outcome learning from accumulated project data
- Cross-project knowledge transfer
- Agent performance optimization & self-improvement

---

## 5. Implementation Phases

### Phase -1: Software Design & Approval (Before any code)

> ADT follows its own process. Before building, we design and get approval.

| Step | Task | Deliverable |
|------|------|-------------|
| -1.1 | Create comprehensive software design document | `docs/DESIGN.md` with all 29 sections |
| -1.2 | Review architecture: system diagram, agents, coordinator, context manager | Approved architecture |
| -1.3 | Review task model: entities, acceptance criteria, decomposition, lifecycle | Approved task model |
| -1.4 | Review workflow engine: adaptive pipeline, archetypes, state machine | Approved workflow |
| -1.5 | Review quality stack: top-down, structural validation, self-challenge, regression | Approved quality approach |
| -1.6 | Review data model: PostgreSQL schema (projects, tasks, locks, traces, LLM costs) | Approved schema |
| -1.7 | Review API design (REST + WebSocket) | Approved endpoints & protocol |
| -1.8 | Review tech stack decisions | All choices confirmed |
| -1.9 | Resolve open questions & assumptions | No blockers for Phase 0 |

**Exit criteria**: Design document fully approved. All open questions resolved. No disagreements remaining.

---

### Phase 0: Foundation (Weeks 1–3)

> Set up the project, tooling, agent framework, AND the new core infrastructure
> (context manager, task queue, tracing, archetypes). Phase 0 is now 3 weeks
> because the new infrastructure is foundational — everything after depends on it.

| Step | Task | Deliverable |
|------|------|-------------|
| **0.1** | Initialize project repository structure | Monorepo with all module folders |
| **0.2** | Set up Python environment + dependencies | `pyproject.toml`, virtual env |
| **0.3** | Install & configure Google ADK | Working ADK setup |
| **0.4** | PostgreSQL setup + initial schema (Alembic migrations) | DB with projects, tasks, traces, locks, artifacts tables |
| | | |
| **0.5** | Build `agent-core` — base agent class (stateless worker) | Agent with lifecycle: claim → hydrate → work → validate → challenge → return |
| **0.6** | Build `agent-core` — top-down generation protocol | L1→L4 sub-task support for all producing agents |
| **0.7** | Build `agent-core` — structural validation layer | Syntax check, lint (Ruff), type check (mypy), import resolution |
| **0.8** | Build `agent-core` — self-challenge protocol | Criteria-based self-evaluation with anti-hallucination checks |
| **0.9** | Build `agent-core` — LLM abstraction layer | Multi-provider (OpenAI, Google, Anthropic), deterministic settings, cost per call |
| **0.10** | Build `agent-core` — escalation protocol | 3-level escalation: clarify, present options, flag for human |
| | | |
| **0.11** | Build `context-manager` — context recipes + bundles | Per-archetype, per-task-type, per-level context hydration |
| **0.12** | Build `context-manager` — snapshots + summarization | Immutable snapshots at task assignment; hierarchical summarization for large artifacts |
| | | |
| **0.13** | Build `task-queue` — task model + persistence | Task entity with acceptance criteria, status lifecycle, parent/child |
| **0.14** | Build `task-queue` — module locking (EXCLUSIVE/SHARED) | Lock acquisition, release, conflict detection |
| | | |
| **0.15** | Build `trace-system` — hierarchical tracing | project → step → task → agent_exec → llm_call trace tree |
| **0.16** | Build `trace-system` — LLM cost tracking | Cost computation per provider/model, stored per call |
| | | |
| **0.17** | Build `archetype-registry` — YAML loader + archetype definitions | At least 3 archetypes: script, cli_tool, api_backend |
| **0.18** | Build `archetype-registry` — pipeline adaptation logic | Load archetype → determine which steps run |
| | | |
| **0.19** | Build `prompt-handler` — versioned template engine | Template rendering with version field, logged in traces |
| **0.20** | Build `shared-rag` — local vector store (ChromaDB) | RAG ingestion + retrieval with project + archetype scoping |
| **0.21** | Seed RAG with reference implementations | At least api_backend reference project + patterns + anti-patterns |
| | | |
| **0.22** | Build `orchestrator` — basic workflow engine | Pipeline that loads archetype and manages step progression |
| **0.23** | Build `coordinator` — task decomposition + assignment | Step → module × L1-L4 tasks, hybrid push/pull assignment |
| | | |
| **0.24** | Scaffold minimal web UI (React + Tailwind + Vite) | Basic chat page + project shell, SaaS-ready structure |
| **0.25** | Backend API shell (FastAPI) | WebSocket chat endpoint + project CRUD + trace query |
| | | |
| **0.26** | Integration test: 2 agents communicating via coordinator | Proof: agent claims task → hydrates context → produces output → self-challenges → returns |

**Exit criteria**: Two agents can claim tasks from the queue, receive hydrated context bundles, produce output using top-down generation, run structural validation, self-challenge, and return traced results with cost tracking. Archetype registry returns correct pipeline for at least 3 archetypes. A minimal web chat page can send/receive messages.

---

### Phase 1: Requirements & Design Agents (Weeks 4–5)

> Build the first two workflow steps (3.1 and 3.2).

| Step | Task | Deliverable |
|------|------|-------------|
| 1.1 | Build `agent-pm` — chat interaction logic | Agent that asks clarifying questions |
| 1.2 | Build `agent-pm` — archetype selection & tech stack resolution | Analyze description → match archetype → resolve tech stack |
| 1.3 | Build `agent-pm` — requirement document generation | Structured requirement output |
| 1.4 | Build `agent-pm` — complexity & cost estimation | Low/mid/high assessment with time/cost per step |
| 1.5 | Build `agent-architect` — top-down design generation (L1→L4) | Architecture doc: module skeleton → interfaces → dependencies → details |
| 1.6 | Build `agent-architect` — diagram generation (Mermaid) | Component, class, sequence diagrams |
| 1.7 | Build `agent-reviewer` — design verification | Verify design completeness & consistency |
| 1.8 | Build acceptance gate: customer approves (requirements + archetype + design) | Approval mechanism (web UI) |
| 1.9 | Integration test: requirement → archetype → design → review → approval | End-to-end for steps 3.1–3.2 |

**Exit criteria**: A user can describe a software idea in chat, PM selects archetype and tech stack, customer approves requirements, Architect generates top-down design with diagrams, customer approves design. All traced with costs.

---

### Phase 2: Development & Testing Agents (Weeks 6–8)

> Build the code generation and testing pipeline (3.4 and 3.5).
> This is the most complex phase — top-down generation, parallelism, and regression protection.

| Step | Task | Deliverable |
|------|------|-------------|
| 2.1 | Build `agent-devops` — GitHub repo creation + workspace setup | Automated repo with structure from archetype |
| 2.2 | Build `agent-qa` — top-down test definition (L1→L4) | Test skeleton → test stubs → fixtures → assertions |
| 2.3 | Build `agent-qa` — test quality review (pre-dev gate) | QA reviews test definitions before Dev starts coding |
| 2.4 | Build `agent-dev` — top-down code generation (L1→L4) | Skeleton → contracts → wiring → logic per module |
| 2.5 | Build coordinator — parallel module execution | Multiple modules building L1-L4 in parallel |
| 2.6 | Build `agent-qa` — unit test execution with full regression | Run ALL tests after every change (not just new ones) |
| 2.7 | Build `agent-dev` — fix loop with regression protection | Fix → re-run ALL tests → verify no regressions |
| 2.8 | Build `agent-qa` — integration testing (cross-module) | Tests that verify modules work together |
| 2.9 | Build `agent-reviewer` — code verification | Verify code matches accepted design & all tests pass |
| 2.10 | Build `agent-dev` — code committed to repo | Git operations (commit, push) |
| 2.11 | Integration test: design → tests → code → review → repo | End-to-end for steps 3.4–3.5 with parallel modules |

**Exit criteria**: From an accepted design, the system decomposes into modules, generates tests (top-down, quality reviewed), generates code (top-down, parallel modules), runs full regression tests, fixes issues without creating new ones, and pushes to GitHub. All with module locking, parallel execution, and full trace/cost data.

---

### Phase 3: Delivery & Full Pipeline (Weeks 9–10)

> Complete the MVP pipeline end-to-end.

| Step | Task | Deliverable |
|------|------|-------------|
| 3.1 | Build `agent-delivery` — top-down packaging (L1→L4) | Contents → structure → documentation → packaging |
| 3.2 | Build `agent-delivery` — documentation generation | README, SETUP, CHANGELOG, inline comments, .env.example |
| 3.3 | Build `billing-agent` — cost tracking per project | Independent billing traceability from trace data |
| 3.4 | Wire full adaptive pipeline: archetype → steps → modules → L1-L4 | Complete workflow with skipped/optional steps per archetype |
| 3.5 | Wire web UI to full pipeline | Chat + project tracking + step tracker + artifact download |
| 3.6 | Build local artifact storage | Reports, diagrams, code stored locally + in DB |
| 3.7 | End-to-end test: full project from idea to ZIP delivery | Test with at least 2 archetypes (script + api_backend) |
| 3.8 | Dogfood: use ADT to build a small module of ADT itself | Self-referential validation |

**Exit criteria**: A user can open a browser, describe "I want a TODO app", PM selects `api_backend` archetype, pipeline adapts, design is generated (top-down), code is generated (top-down, parallel modules), tests pass (with regression), reviewer verifies, and a ZIP with working, tested, documented code is delivered — fully autonomously via the web UI. All with full trace and cost data.

---

### Phase 4: UX Prototype & Cloud (Weeks 11–14)

| Step | Task | Deliverable |
|------|------|-------------|
| 4.1 | Build `agent-ux` — UI flow prototype generation | Navigable HTML mockups |
| 4.2 | Build customer feedback loop for UX | Iterate on mockups before dev |
| 4.3 | Build Kubernetes deployment support | Namespace creation, pod deployment |
| 4.4 | Build Kustomize configuration generation | Environment overlays |
| 4.5 | Build GitHub Actions pipeline generation | CI/CD for customer projects |
| 4.6 | Build `agent-qa` — system/interaction testing | Tests against deployed app |
| 4.7 | Add delivery options: repo fork, container images | Full delivery menu |
| 4.8 | Add remaining archetypes (data_pipeline, library, infrastructure, mobile_backend) | Full archetype coverage |

**Exit criteria**: Full 3.1–3.8 pipeline working including UX prototyping, K8s deployment, and all delivery options with full archetype coverage.

---

### Phase 5: SaaS Platform (Weeks 15–21)

| Step | Task | Deliverable |
|------|------|-------------|
| 5.1 | Design platform database schema | Multi-tenant data model |
| 5.2 | Build `platform-auth` — signup, login, JWT/session | Working auth system |
| 5.3 | Build `platform-tenancy` — tenant isolation | Data & execution isolation |
| 5.4 | Build `platform-projects` — project management | Create, track, cancel projects |
| 5.5 | Expand `platform-chat` — full SaaS chat experience | Multi-tenant, multi-project UI |
| 5.6 | Build `platform-billing` — pricing engine (uses trace cost data) | Step-based billing from actual LLM costs |
| 5.7 | Build `platform-admin` — org & user management | Roles, teams, permissions |
| 5.8 | Build `platform-api` — REST API layer | API for all platform operations |
| 5.9 | Build `platform-artifacts` — cloud artifact storage | S3/GCS for reports & deliverables |
| 5.10 | Integration: connect platform to agent engine | Projects trigger agent workflows |

**Exit criteria**: A customer can sign up, create a project, interact with agents via chat, track progress, and receive deliverables with itemized billing.

---

### Phase 6: Scale & Polish (Weeks 22–28)

| Step | Task | Deliverable |
|------|------|-------------|
| 6.1 | Build `platform-dashboard` — analytics & metrics (from trace data) | Cost, time, agent performance dashboards |
| 6.2 | Build `platform-debug` — post-delivery debugging | Bug report → fix cycle |
| 6.3 | Build concurrent project execution | Multiple projects in parallel |
| 6.4 | Build outcome learning from project data | Improve prompts, archetypes, reference implementations |
| 6.5 | Performance optimization — agents, RAG, context manager | Faster, cheaper agent execution |
| 6.6 | Security audit & hardening | Encryption, secret management |
| 6.7 | Load testing & scalability validation | Proven scale targets |
| 6.8 | Documentation & onboarding flows | User guides, API docs |

**Exit criteria**: Production-ready SaaS platform with analytics, learning, and scale.

---

## 6. Functionality Breakdown per Module

### A1: `agent-core` (Phase 0)
```
agent-core/
├── base_agent.py             # Abstract base (stateless worker)
├── tool_registry.py          # Register & invoke tools per agent
├── memory.py                 # Short-term & long-term memory per task
├── messaging.py              # Inter-agent message types & protocol
├── self_challenge.py         # Criteria-based self-evaluation + anti-hallucination
├── top_down.py               # L1→L4 generation protocol
├── structural_validator.py   # Lint (Ruff), type check (mypy), parse, import resolution
├── escalation.py             # 3-level human escalation protocol
├── llm_provider.py           # Multi-provider abstraction (OpenAI, Google, Anthropic)
├── state.py                  # Agent state management
└── config.py                 # Per-agent configuration loader (agents.yaml)
```

### A2a: `orchestrator` (Phase 0)
```
orchestrator/
├── workflow_engine.py        # Loads archetype → builds adaptive pipeline
├── archetype_loader.py       # Load archetype YAML → pipeline definition
├── step_registry.py          # Maps pipeline steps to agent roles
├── state_machine.py          # Project state transitions
└── gate_manager.py           # Customer acceptance gates
```

### A2b: `coordinator` (Phase 0)
```
coordinator/
├── agent_coordinator.py      # Event-driven task coordination
├── task_decomposer.py        # Step → module × L1-L4 sub-tasks
├── parallelism_manager.py    # Parallel module execution
├── dependency_tracker.py     # Task dependency graph
└── conflict_resolver.py      # Module lock conflict handling
```

### A13: `context-manager` (Phase 0)
```
context-manager/
├── context_manager.py        # Main context hydration service
├── context_recipes.py        # Per-archetype, per-task-type, per-level recipes
├── context_bundle.py         # ContextBundle dataclass
├── snapshot.py               # Immutable context snapshots
└── summarizer.py             # Hierarchical summarization for large artifacts
```

### A14: `task-queue` (Phase 0)
```
task-queue/
├── task_model.py             # Task entity + sub-tasks + acceptance criteria
├── task_queue.py             # PostgreSQL-backed role-based queues
├── task_assignment.py        # Hybrid pull/push assignment
└── module_lock.py            # EXCLUSIVE/SHARED module locking
```

### A15: `trace-system` (Phase 0)
```
trace-system/
├── tracer.py                 # Hierarchical trace creation
├── trace_models.py           # Trace dataclasses
├── cost_tracker.py           # LLM cost computation per provider/model
└── trace_store.py            # Persistence to PostgreSQL
```

### A16: `archetype-registry` (Phase 0)
```
archetype-registry/
├── registry.py               # Load + query archetype definitions
├── pipeline_adapter.py       # Archetype → adaptive pipeline
└── tech_stack_resolver.py    # Archetype defaults + customer overrides
```

### A3: `agent-pm` (Phase 1)
```
agent-pm/
├── pm_agent.py               # PM agent implementation
├── chat_handler.py           # Conversational requirement gathering
├── requirement_builder.py    # Structured requirement document builder
├── archetype_selector.py     # Match description → archetype (with confidence)
├── tech_stack_resolver.py    # Resolve tech stack from archetype + customer input
├── complexity_assessor.py    # Low/mid/high complexity engine
└── cost_estimator.py         # Time and cost estimation per step
```

### A4: `agent-architect` (Phase 1)
```
agent-architect/
├── architect_agent.py        # Architect agent implementation
├── design_generator.py       # Top-down: L1 modules → L2 interfaces → L3 deps → L4 details
├── diagram_engine.py         # Mermaid diagram generation
├── integration_planner.py    # External system integration definitions
└── modular_monolith.py       # Module boundary definition
```

### A6: `agent-dev` (Phase 2)
```
agent-dev/
├── dev_agent.py              # Dev agent implementation
├── skeleton_generator.py     # L1: file tree + responsibilities
├── contract_generator.py     # L2: typed stubs (valid, parseable code)
├── wiring_generator.py       # L3: import graph + call chain
├── logic_generator.py        # L4: business logic per function
├── fix_loop.py               # Fix → full regression re-run → verify no regressions
└── git_ops.py                # Git commit, push, branch operations
```

### A7: `agent-qa` (Phase 2)
```
agent-qa/
├── qa_agent.py               # QA agent implementation
├── test_definer.py           # Top-down: L1 test files → L4 assertions
├── test_quality_reviewer.py  # Pre-dev gate: reviews test completeness
├── test_runner.py            # Runs ALL tests (full regression every time)
├── integration_tester.py     # Cross-module integration tests
└── report_generator.py       # Test report generation
```

### A9: `agent-reviewer` (Phase 1–2)
```
agent-reviewer/
├── reviewer_agent.py         # Reviewer agent implementation
├── workflow_verifier.py      # Verify all steps ran correctly
├── design_verifier.py        # Verify design completeness & consistency
├── code_verifier.py          # Verify code matches accepted design
├── acceptance_checker.py     # Validate outputs against acceptance criteria
└── checklist_engine.py       # Verification checklist generation
```

### A10: `agent-delivery` (Phase 3)
```
agent-delivery/
├── delivery_agent.py         # Delivery agent implementation
├── zip_packager.py           # ZIP packaging
└── doc_generator.py          # README, SETUP, CHANGELOG, .env.example
```

### A11: `shared-rag` (Phase 0)
```
shared-rag/
├── store.py                  # Vector store abstraction (ChromaDB)
├── ingestion.py              # Document chunking & embedding
├── retrieval.py              # Similarity search with project + archetype scoping
└── seed_data/                # Reference implementations per archetype
    ├── api_backend/
    │   ├── reference_project/
    │   ├── patterns.md
    │   ├── anti_patterns.md
    │   └── security_checklist.md
    ├── script/
    │   └── patterns.md
    └── general/
        ├── git_conventions.md
        └── documentation_standards.md
```

### A12: `prompt-handler` (Phase 0)
```
prompt-handler/
├── template_engine.py        # Prompt template rendering with version tracking
├── role_prompts.py           # System prompts per agent role
└── templates/                # Versioned YAML prompt templates
    ├── pm.yaml
    ├── architect.yaml
    ├── dev.yaml
    ├── qa.yaml
    ├── devops.yaml
    ├── reviewer.yaml
    └── delivery.yaml
```

---

## 7. Phase Dependency Map

```
Phase -1: Software Design & Approval ◄── YOU ARE HERE
    │
    ├──► Phase 0: Foundation (3 weeks)
    │        │
    │        ├──► Phase 1: Requirements & Design Agents (2 weeks)
    │        │        │
    │        │        ├──► Phase 2: Development & Testing Agents (3 weeks)
    │        │        │        │
    │        │        │        ├──► Phase 3: Delivery & Full Pipeline (2 weeks)
    │        │        │        │        │
    │        │        │        │        ◄── MVP COMPLETE (Week 10)
    │        │        │        │        │
    │        │        │        │        ├──► Phase 4: UX + Cloud (Wave 2)
    │        │        │        │        │        │
    │        │        │        │        │        ├──► Phase 5: SaaS Platform (Wave 3)
    │        │        │        │        │        │        │
    │        │        │        │        │        │        ├──► Phase 6: Scale & Polish (Wave 4)
    │        │        │        │        │        │        │
    │        │        │        │        │        │        └──► 🚀 PRODUCTION
```

**Critical path**: Phase -1 → 0 → 1 → 2 → 3 (MVP)

**Parallel opportunities after MVP**:
- Phase 4 (UX + Cloud) and Phase 5 (SaaS Platform) can partially overlap
- Dashboard & analytics (Phase 6) can start once platform has data (trace data available from Phase 0)

---

## 8. Risk & Mitigation

| Risk | Impact | Likelihood | Mitigation |
|------|--------|-----------|------------|
| LLM quality insufficient for code gen | High | Medium | Top-down L1→L4 reduces scope per call; reference implementations ground output; structural validation catches mechanical errors; multi-model fallback |
| Agent hallucination (inventing APIs, modules) | High | Medium | Context Manager limits input; self-challenge includes grounding check; structural validation catches phantom imports; RAG provides known-good patterns |
| Context window overflow | High | Medium | Context recipes limit token budget per task type; hierarchical summarization; L4 functions get ~3K tokens each |
| Agent coordination becomes chaotic | High | Medium | Strong task model; module locking prevents conflicts; coordinator manages dependencies; event-driven architecture |
| Generated code doesn't pass tests | Medium | High | Fix loop with regression protection; full test re-run every iteration; escalation after max retries |
| Fix loop creates regressions | Medium | Medium | Full regression re-run after every fix; tests never pruned |
| Over-engineering simple projects | Medium | Medium | Archetypes adapt pipeline; scripts skip design/verification; minimal pipeline for low complexity |
| Scope creep on MVP | High | High | Strict MVP boundary; 25 items in, 15 deferred; phase gates enforce |
| Phase 0 takes too long (3 weeks) | Medium | Medium | Phase 0 builds foundational infrastructure used by ALL later phases; investment pays off in Phase 1+ |
| Google ADK doesn't support non-Google LLMs | High | Unknown | Q1 to validate in Phase 0; thin wrapper as fallback |
| RAG context pollution across projects | Medium | Medium | Project-scoped RAG partitions; archetype-scoped reference collections |
| Cost of LLM API calls during development | Medium | High | Deterministic temperature; trace + cost tracking from day one; use cheaper models for summarization; token budgets per recipe |

---

## 9. Summary & Timeline

| Milestone | Target | What You Get |
|-----------|--------|-------------|
| **Phase -1** | Pre-Week 1 | Approved software design, no blockers |
| **Phase 0** | Week 3 | Core infra: agents + tasks + context + tracing + archetypes working |
| **Phase 1** | Week 5 | Requirements + Design pipeline working with archetype selection |
| **Phase 2** | Week 8 | Code generation + testing with top-down, parallel modules, regression |
| **Phase 3 (MVP)** | Week 10 | Full pipeline: idea → adaptive pipeline → working ZIP with full traceability |
| **Phase 4** | Week 14 | UX prototypes + K8s deployment + full archetype coverage |
| **Phase 5** | Week 21 | SaaS platform with auth, billing (from trace data), multi-tenant |
| **Phase 6** | Week 28 | Production-ready with analytics, learning, & debugging |

### What's New in v2 (All 15 Refinements Incorporated)

| # | Refinement | Where It Appears |
|---|-----------|-----------------|
| 1 | Task model with acceptance criteria | MVP-09, Phase 0 (0.13), A14 |
| 2 | Centralized Context Manager | MVP-10, Phase 0 (0.11-0.12), A13 |
| 3 | Agent Coordinator + module locking | MVP-08, Phase 0 (0.23), Phase 2 (2.5), A2b |
| 4 | Hierarchical tracing + cost tracking | MVP-12, Phase 0 (0.15-0.16), A15 |
| 5 | Project archetypes + adaptive pipeline | MVP-11, Phase 0 (0.17-0.18), Phase 1 (1.2), A16 |
| 6 | Structural validation layer | MVP-04, Phase 0 (0.7), in agent-core |
| 7 | Reference implementations in RAG | MVP-21, Phase 0 (0.21), in shared-rag |
| 8 | Test quality review (QA pre-dev gate) | MVP-16, Phase 2 (2.3), in agent-qa |
| 9 | Documentation as first-class output | MVP-19, Phase 3 (3.2), in agent-delivery |
| 10 | Regression protection | Phase 2 (2.6-2.7), in agent-qa + agent-dev |
| 11 | Deterministic LLM settings | MVP-05, Phase 0 (0.9), in agent-core |
| 12 | Human escalation protocol | MVP-06, Phase 0 (0.10), in agent-core |
| 13 | Integration testing | Phase 2 (2.8), in agent-qa |
| 14 | Prompt versioning | MVP-22, Phase 0 (0.19), in prompt-handler |
| 15 | Top-down generation (L1→L4) | MVP-02, Phase 0 (0.6), Phase 1 (1.5), Phase 2 (2.2, 2.4), A1 |

---

*This plan is a living document. Let's review, challenge, and refine it together.*
