# TeamBuild — Current Handoff State

**Last Updated:** 2026-02-10
**Last Phase Completed:** Design Doc finalized (003)
**Current Phase:** Design complete — ready to build

---

## What Is This Project?

An AI-powered engineering workflow system that manages the full development lifecycle — from idea through maintenance — using specialized AI agents. The system should be modular, provider-agnostic, and self-improving through built-in metrics.

Owner: Josh @ MetrIQ

---

## What Has Been Decided

All decisions below were made during the initial interview ([conversation-logs/001-initial-interview.md](conversation-logs/001-initial-interview.md)).

### v0.1 Build Order
1. **Interview Agent** — two modes: direct interview + gap analysis on incomplete specs
2. **PM Integration** — Plane first (personal), Linear-ready (work). Single source of truth for all agent coordination
3. **Coding Agent Team** — high autonomy, TDD, self-validating. Spec → PR pipeline
4. **Critique/Review Layer** — applies at every phase. Circuit breaker: 3-5 attempts then escalate to human
5. **Cost/Performance Metrics** — built BY items 1-4 as a dogfooding test
6. **Provider Abstraction** — model-agnostic from day one. Validate Pydantic AI first

### Hard Requirements
- Modular components — every piece must be plug-and-play, usable independently per project/user
- TDD, strict linting, type checks
- Python for AI orchestration, TypeScript for web frontend, best tool otherwise
- Open source first, self-hosted where possible
- Circuit breaker on all agent loops (3-5 attempts max)
- Track tokens, costs, context window health everywhere
- Terminal-first workflow, desktop + PM notifications for v1

### What Success Looks Like
Hand off a feature spec → agents build through PR with real validation → human only steps in when genuinely stuck or for final approval. PM tool shows exactly what's happening. Cost and quality metrics prove the system is effective.

---

## Critical Architectural Constraint: Context Window Management

**This is the single biggest technical risk in the system.** See [requirements.md — Context Window Management](requirements.md) for full details.

**The problem:** Previous "prime" approaches front-loaded entire codebase understanding into context, consuming the smart window before agents could do real work. On large codebases, this made agents functionally useless.

**The solution:** Targeted, lazy context loading. Agents fetch only what's relevant to their specific task. Key mechanisms:
- Atomic index notes per module (Zettelkasten-inspired navigation)
- Task-scoped context driven by PM ticket scope markers
- Context budget tracking with degradation warnings
- Shared knowledge layer (external storage, not context window)
- Auto-maintained indexes updated as agents work

**This affects every module's design** — see the impact table in requirements.md.

---

## What Has NOT Been Decided

- Beads format — referenced for token/project management, needs research
- Notification implementation (desktop notification library/approach)
- DuckDB vs SQLite for metrics storage (research needed)
- Plane API specifics (research needed before PM module)
- tree-sitter Python bindings for AST parsing (research needed before `teambuild init`)

---

## Completed: Design Doc with Mermaid Diagrams

**Output:** [design-doc.md](design-doc.md)

The design doc covers all required areas with Mermaid diagrams:
- High-level system architecture (all modules and how they connect)
- Module dependency graph (what's independent, what depends on what)
- Agent lifecycle (how an agent picks up work, does it, validates, reports)
- Critique/review flow (two-pass architecture + circuit breaker pattern)
- PM integration data flow (ticket creation → assignment → status → completion)
- Metrics collection points (6 collection points annotated on architecture)
- Context window management (atomic indexes, progressive disclosure, budget tracking)
- Interview Agent internal architecture (detailed enough to build from)
- Package structure for the full project

### Design Decisions Resolved
| Question | Decision |
|----------|----------|
| **TeamBuild identity** | Workflow framework — owns planning, validation, review, metrics. Code execution is pluggable. |
| **Integration model** | CLI + git-native `.index.md` files. No agent runtime dependency. Config in `[tool.teambuild]`. |
| **Project understanding** | Three-layer: static analysis + AST/tree-sitter + lazy AI summarization. 80% free. |
| **Managed executor** | Optional `teambuild code` wrapping coding agents. Built last. |
| **Agent runtime config** | Thin optional generators (`teambuild setup`), NOT an adapter pattern. |
| PM abstraction | Adapter pattern (PlaneAdapter, LinearAdapter implement PMAdapter ABC) |
| Agent coordination | PM-driven + git worktrees for file isolation, 3-tier delegation (solo/subagent/team) |
| Metrics storage | JSONL → DuckDB/SQLite (research needed), all behind MetricsStore ABC, with PM export |
| Module interfaces | Python packages + Pydantic models for all inputs/outputs |
| Atomic index implementation | Hierarchical `.index.md` — root index routes to 2-3 relevant module indexes |
| Context budgeting | Smart window ~120K, housekeeping 30K, hard ceiling 150K |
| Package structure | Monorepo + import-linter enforced layer boundaries. Tests colocated. |
| Self-validation | Standalone `teambuild check` CLI. Language-agnostic categories resolved per-language. |

---

## Next Task: Build Module 1

Design doc is complete. All outstanding items from conversation 002 have been written into design-doc.md (sections 3, 4, 8, 9).

### Key Design Decisions Made in Conversation 003

1. **TeamBuild identity resolved** — Workflow framework, not agent runtime. Owns planning, validation, review, metrics. Code execution is a pluggable slot.
2. **Integration model** — CLI + git-native `.index.md` files. No `.claude/` dependency. No `.teambuild/` directory. Config in `[tool.teambuild]` in pyproject.toml.
3. **Three-layer project understanding** — Static analysis (free) + AST/tree-sitter (free) + AI summarization (lazy, cached). `teambuild init` runs L1+L2 for free, one AI call for root index.
4. **Managed executor is optional, built last** — `teambuild code` wraps coding agents with rules + monitoring. Not core to the system. Built after everything else is proven.
5. **No adapter pattern for agent runtimes** — Thin, optional setup generators instead (`teambuild setup claude`). Not an abstraction layer.
6. **Validation is standalone** — `teambuild check` works regardless of what wrote the code. Wired into git hooks or CI, not agent-specific hooks.

### Build Sequence (from design-doc.md §14)

1. **Project scaffolding** — pyproject.toml with uv, import-linter, ruff, mypy, pytest
2. **Provider Abstraction** — AgentProvider ABC, Pydantic AI implementation, MockProvider, config
3. **Metrics Collection** — lightweight collector lib, JSONL store
4. **Interview Agent** — InterviewAgent, QuestionGenerator, CompletenessTracker, NoteKeeper, OutputFormatter, domain libraries, CLI command
5. **PM Integration** — PMAdapter ABC, PlaneAdapter, ticket models
6. **Validation Runner** — `teambuild check`, language-agnostic gates, auto-detection
7. **Critique/Review Layer** — two-pass review, agentPrompt, circuit breaker
8. **Cost/Performance Metrics** (full module) — storage, dashboards, PM export. Built BY items 1-7.
9. **Context & Index Manager** — three-layer analysis, `.index.md` generation
10. **Managed Executor** (optional) — `teambuild code`, wraps coding agents
11. **Setup Generators** (optional) — `teambuild setup claude/cursor/generic`

---

## Research Inventory

### Reviewed and Incorporated into Requirements
- `base-plan.md` — original build plan, now superseded by requirements.md
- `initial-build-ticket-idea.md` — original build ticket idea, key ideas incorporated
- `research/clarity-interviewer/` — story-based interview methodology (Teresa Torres, Dylan Davis). **Synthesized into Interview Agent spec** — see `interview-agent-synthesis.md` for full comparison. Key mechanics incorporated: story-based questioning, completeness tracking, dynamic question generation, domain libraries, explorer mindset.

### Reviewed and Incorporated into Design Doc (002)

All research below was reviewed in conversation 002 and informed the design doc (`design-doc.md`).

#### `research/early-research/`
- **Pydantic AI POC** — validated provider abstraction pattern. Generic `AgentProvider` interface works across Anthropic, OpenAI, Bedrock, Ollama. Adopted as foundation for Provider Abstraction layer.
- **25 skills (PIV-Swarm workflow)** — prime → explore → discuss → spec → plan → execute → validate → commit. Schema-driven decisions reduce questions by 70%. Progressive context loading (Level 1/2/3). Fresh context per task via `context: fork`. All patterns incorporated into design.
- **GOALS.md, thoughts.md, my-current-process.md** — Josh's earlier thinking. Key insight: "Context is King, Sessions are Natural, Quality is Non-Negotiable." Token budget management, multi-session architecture, precompact hooks.
- **Decision schemas** — architecture-patterns.yaml, api-patterns.yaml, testing-strategies.yaml, database-decisions.yaml, deployment-options.yaml. Smart defaults pattern adopted for Interview Agent question reduction.

#### `research/hooks/`
- Hook patterns adopted for Critique/Review Layer Pass 1 (lightweight, synchronous checks). Pre-commit lint, post-edit format, post-failure autofix with targeted fix instructions. Circuit breaker pattern via stateful retry tracking. Context compaction rules (compact early, never without plan + report).

#### `research/opus_first_ideas/`
- **12 specialist agent roles** reviewed (Researcher, Architect, PM, Backend/Frontend/Data/AI/DevOps Engineers, Code Reviewer, QA Tester, Docs Writer, Performance Evaluator). Informed the agent coordination model.
- **10-phase lifecycle** reviewed (Idea → Research → Design → Spec → Plan → Dev → Test → Evaluate → Update System → Maintenance). Informed overall system architecture.
- **3-tier delegation model** adopted (Solo / Subagent / Team) with cost implications (1x / ~2x / ~5x).
- **5 reusable skills** reviewed (Critique, Cost Tracker, Research Report, Ticket Format, Mermaid Diagrams).

#### `current_ai/`
- Josh's current Claude Code setup reviewed. PIV-Swarm workflow, smart defaults, 3-tier testing, helper scripts (analyze_complexity.py, check_coverage.py, estimate_complexity.py). Skills mapped to TeamBuild modules: /prime → Context Agent, /explore → Research Agent, /discuss → Interview Agent, /spec → PM Integration, /execute → Coding Agent Team, /code-review → Critique/Review Layer.

#### `research/code-review/`
- **ai-reviewer.mjs** — GitHub Actions AI code reviewer using Bedrock. Key concepts adopted for design:
  - **`agentPrompt` field** — AI-to-AI handoff prompt per issue. Review produces fix prompts that coding agents pick up directly. Turns review into a pipeline, not a handoff.
  - **False positive prevention** — mandatory 5-point self-check, banned speculative language, "zero issues = ideal outcome."
  - **Priority-based truncation** — file priority weights for context budget allocation.
  - **Stale comment resolution** — auto-minimize resolved issues. Adopted for PM integration.
  - **Two-pass review** — automated checks (Pass 1) + AI deep review (Pass 2).

---

## Project Structure

```
teambuild/
├── CLAUDE.md                     # Agent entry point — read this first
├── HANDOFF.md                    # THIS FILE — current state and next task
├── design-doc.md                 # System design with Mermaid diagrams
├── requirements.md               # Standalone requirements spec from interview
├── interview-agent-synthesis.md  # Clarity-interviewer + TeamBuild synthesis
├── base-plan.md                  # Original plan (superseded by requirements.md)
├── initial-build-ticket-idea.md  # Original inspiration doc
├── conversation-logs/
│   ├── 001-initial-interview.md  # Full interview transcript + metrics
│   ├── 002-design-doc.md        # Research review + design doc creation
│   └── 003-integration-model.md # Integration model + project understanding + identity resolution
├── research/
│   ├── code-review/             # GitHub Actions AI reviewer (ai-reviewer.mjs)
│   ├── early-research/          # Early exploration, Pydantic AI POC, skills/schemas
│   ├── hooks/                   # Development hooks for quality control
│   └── opus_first_ideas/        # Opus dry run — agent roles, lifecycle phases
└── current_ai/                   # Josh's current Claude Code setup
```
