# TeamBuild v0.1 — Requirements Specification

**Source:** Initial interview with Josh (2026-02-08)
**Full transcript:** [conversation-logs/001-initial-interview.md](conversation-logs/001-initial-interview.md)

---

## Problem Statement

The biggest limiter in development is lack of clarity before coding starts. A base goal exists but not a plan for execution. When inputs and expected outputs are well-defined, anything can be built. The current workflow fails to extract and formalize this information up front, leading to wasted effort, rework, and agents that declare "done" without actually validating their output.

---

## System Overview

An AI-powered engineering workflow system with modular, specialized agents that handle the full development lifecycle. The system must be:

- **Modular** — every component is plug-and-play. Leave behind what you don't need. Adaptable per project or per user.
- **Provider-agnostic** — not locked to any AI provider. Abstraction layer from day one.
- **Self-validating** — agents verify their own work before involving a human.
- **Self-measuring** — cost, performance, and quality metrics are built into every surface.
- **Context-efficient** — agents load only the context they need for their specific task. No front-loading entire codebases into the context window.

---

## Architectural Constraint: Context Window Management

**This is the single biggest technical risk in the system and must be addressed in every design decision.**

### The Problem

Previous attempts at agent-driven development used a "prime" approach — loading full codebase understanding into the context window before starting work. On large, scalable codebases, this consumed so much of the high-quality context window that agents were operating in degraded ("dumb") context by the time they started actually building. The smarter the priming, the dumber the execution.

### The Requirement

Agents must use **targeted, lazy context loading** — fetching only what's relevant to their specific task. An agent fixing a login bug should not need to understand the billing module.

### Design Principles for Context Management

1. **Atomic documentation** — inspired by Zettelkasten. Each module/folder has a concise index note describing what it does, what it exposes, and how to find more detail. Agents traverse these indexes to locate relevant code without reading everything.
2. **Progressive disclosure** — start with high-level summaries, drill down only when needed. Module README → function signatures → implementation details.
3. **Task-scoped context** — the PM ticket defines what files/modules are relevant. Agents start from the ticket scope, not from "understand the whole project."
4. **Context budget tracking** — every agent operation should know how much context it has consumed vs. how much remains. This feeds into the metrics module and triggers warnings before degradation.
5. **Shared knowledge layer** — when one agent learns about a module, that understanding should be cached/indexed so the next agent doesn't re-read the same files. Not in the context window — in external storage (indexed notes, embeddings, summaries).
6. **Auto-generated indexes** — agents should update module index notes as they work. If an agent touches a file and the index is stale, it updates it. This keeps the navigation layer fresh without manual maintenance.
7. **Context health as a first-class metric** — track where agents are in their context window, what percentage is "priming" vs. "working," and correlate context health with output quality.

### What This Means for Each Module

| Module | Context Management Impact |
|--------|--------------------------|
| Interview Agent | Low risk — conversations are naturally scoped. But output docs must be structured for easy partial reading by downstream agents. |
| PM Integration | Tickets must include scope markers — which modules/files are relevant. This is the primary scoping mechanism for coding agents. |
| Coding Agent Team | Highest risk. Must use indexed navigation, not full codebase loading. Task-scoped context from PM ticket. Progressive disclosure for unfamiliar code. |
| Critique/Review Layer | Medium risk. Reviewers need broader context than builders but still shouldn't load everything. Scope to changed files + their direct dependencies. |
| Cost/Performance Metrics | Must track context window health. Alert when agents are approaching degraded context. Correlate context usage with output quality over time. |
| Provider Abstraction | Must expose context window limits per model/provider so agents can budget accordingly. |

---

## v0.1 Components (Build Order)

### 1. Interview Agent

**Purpose:** Extract clear requirements from stakeholders before any building begins. Uses story-based methodology (Teresa Torres) to discover insights stakeholders don't realize they have, while maintaining focus on producing concrete technical deliverables.

**Philosophy:** The interview process draws out unconscious knowledge through specific situations and examples, not generalizations. Every interview produces a structured, actionable deliverable.

---

#### Two Operating Modes

##### Mode 1: Direct Interview (Story-Based Requirements Discovery)

**When to use:** Stakeholder is available for conversation and needs to define requirements, features, or technical decisions.

**Process:**
1. Analyze initial input (brain dump, topic, or description)
2. Infer role/goal (e.g., "product strategist defining auth requirements")
3. Confirm with stakeholder before starting
4. Conduct story-based interview using dynamic question generation
5. Track completeness internally (1-10 scale)
6. Follow valuable tangents (explorer mindset)
7. Conclude naturally when completeness reaches 9-10
8. Produce structured requirements document

**Output:** Requirements document with clear inputs, outputs, data sources, scope, constraints, edge cases, and success criteria. Detailed enough to generate tickets from.

##### Mode 2: Gap Analysis (Story-Based Spec Critique)

**When to use:** An existing spec or plan has been provided but is incomplete.

**Process:**
1. Analyze the existing spec against domain patterns
2. Identify gaps (missing inputs, undefined outputs, unclear scope, unaddressed edge cases)
3. Generate targeted story-based questions to fill each gap
4. Either interview the stakeholder directly OR produce a question list for them to answer
5. Update the spec with new information
6. Validate completeness

**Output:** Updated requirements document or a gap report with targeted questions for stakeholders.

---

#### Core Mechanics (Both Modes)

##### 1. ONE Question at a Time
- Never ask two questions in the same turn
- Never ask a question with sub-parts
- Wait for the answer before generating the next question
- Exception: Confirmation questions during setup ("Does that sound right?")

##### 2. Story-Based Questioning

Prefer specific situations over generalizations. Humans are terrible at generalizing but good at recalling specific experiences.

**❌ NEVER ASK:**
- "What do you usually do when..."
- "How do you generally handle..."
- "What typically happens when..."
- "In general, how do you feel about..."

**✅ ALWAYS ASK:**
- "Tell me about the last time you..."
- "Describe a specific situation where..."
- "Walk me through exactly what happened when..."
- "Give me a concrete example of when..."

**When to use story-based:**
- Understanding pain points and past failures
- Discovering workflows and processes
- Identifying edge cases from real experiences
- Learning about user behavior
- Understanding past technical decisions

**When to use direct questions:**
- Pure technical constraints (API limits, compliance requirements)
- Explicit scope decisions (what's in/out for v1)
- Quantifiable requirements (performance targets, user counts)
- Simple confirmations

##### 3. Dynamic Question Generation

After each stakeholder response, generate 3-5 candidate questions internally, then select the best one:

```
Potential Follow-ups:
  1. [Most relevant to current understanding gaps]
  2. [Alternative angle on the same topic]
  3. [Rabbit trail that might reveal hidden insight]
  4. [Confirmation if something seems contradictory]
  5. [Scope/constraint clarification]
Selected: [Pick based on completeness gaps and insight potential]
```

Do not follow a pre-scripted sequence. Every question must be dynamically informed by the previous answer.

##### 4. Internal Note-Taking

After each stakeholder response, maintain internal notes (not shown to stakeholder):

```
Current Understanding: [Summary of what's been learned so far]
Key Insights: [Important discoveries — especially things they didn't realize]
Technical Constraints: [Hard limits, compliance, performance requirements]
User Profile: [Working style, values, priorities, pain points]
Unanswered Questions: [What we still don't know for the deliverable]
Potential Follow-ups (1-5): [Next question candidates]
Completeness: [X/10 — how complete for this deliverable?]
```

Use these notes to drive question selection and know when to conclude.

##### 5. Completeness Tracking

Maintain an internal completeness score (1-10) based on whether the deliverable can be built:

**1-3 (Very Incomplete):** Major gaps. Missing critical information about inputs, outputs, or scope.

**4-6 (Partial):** Some core elements defined but significant gaps remain. Not ready to build.

**7-8 (Mostly Complete):** Core requirements clear, minor gaps or edge cases still need clarification.

**9-10 (Complete):** All inputs, outputs, scope, constraints, edge cases, and success criteria are clear. Ready to generate tickets and start building.

**Stop when:** Completeness reaches 9-10 AND no new insights are emerging.

##### 6. Profile Building

Build a lightweight stakeholder profile during the interview (extract from their responses, don't ask directly unless necessary):

- **Working style:** Terminal-based, IDE-focused, prefers keyboard shortcuts, etc.
- **Values:** Efficiency, quality, cost, security, user experience, etc.
- **Pain points:** What frustrates them most
- **Priorities:** What matters most vs. least
- **Technical preferences:** Languages, tools, patterns they prefer

Use this profile to:
- Adapt question phrasing to their context
- Connect requirements to what they care about
- Customize output format to their working style
- Identify potential resistance or concerns

##### 7. Explorer Mindset

When a stakeholder's answer hints at something unexpected or potentially valuable, pursue it. Hidden insights often live in tangents.

**Example:** If they mention "our previous prime function consumed all the context," that's worth exploring even if it wasn't part of the planned question sequence. It might reveal a critical architectural constraint.

Balance structure (deliverable focus) with curiosity (discovery).

##### 8. Natural Conclusion

Find a natural stopping point based on:
- Completeness score reaches 9-10 (primary signal)
- All critical gaps filled (inputs, outputs, scope, constraints)
- Stakeholder indicates they're done
- No new insights emerging for 3+ questions
- Typical range: 15-30 questions for requirements discovery

Signal the transition clearly: "I think we've covered the core of this. Let me pull together what we've discovered."

##### 9. Structured Output (Always)

Every interview produces a concrete deliverable. Format depends on the domain and goal:

**For Requirements Discovery:**
```markdown
# [Project/Feature Name] — Requirements Specification

## Problem Statement
[Core problem being solved, from interview stories]

## System Overview
[High-level description]

## Requirements
### Component 1: [Name]
**Purpose:** [What it does]
**Inputs:** [What it needs]
**Outputs:** [What it produces]
**Constraints:** [Technical/business limits]
**Edge Cases:** [From interview stories]

[Repeat for each component]

## Success Criteria
- [How we know it works]

## Out of Scope
[What's explicitly not included]
```

**For Feature Specifications:**
```markdown
# Feature: [Name]

## User Story
[Specific situation from interview]

## Inputs
- [Data/info the feature needs]

## Outputs
- [What the feature produces]

## Workflow
1. [Step by step from interview stories]

## Success Criteria
- [Measurable outcomes]

## Edge Cases
- [From real examples shared]

## Technical Constraints
- [Performance, security, compliance]
```

---

#### Core Framework Every Interview Must Cover

Regardless of mode or domain, every interview must answer:

1. **Where is the data?** What does it look like? What format? Where is it stored?
2. **What should the outputs look like?** Format, structure, destination?
3. **What does v1 look like?** Scope, timeline, what's in vs. out?
4. **What are the inputs and expected outputs for each feature?** Be specific.
5. **What are the edge cases?** (Discovered through story-based questions about past failures)
6. **What are the success criteria?** How do we know it works?
7. **What are the constraints?** Technical, business, compliance, performance

---

#### Domain Libraries

The Interview Agent has access to domain-specific question libraries that grow over time:

**`domains/software-requirements.md`** — Patterns for discovering software requirements
- Question templates for common scenarios
- Known pitfalls and how to avoid them
- Case studies from past interviews
- Successful question patterns

**`domains/feature-specs.md`** — Patterns for feature definition
- User story templates
- Workflow discovery questions
- Edge case exploration patterns

**`domains/architecture-decisions.md`** — Patterns for technical decisions
- Trade-off exploration questions
- Constraint discovery patterns
- Past decision retrospectives

**`domains/bug-investigations.md`** — Patterns for bug/issue root cause analysis
- Reproduction scenario questions
- Environment and context discovery
- Timeline reconstruction

**Living documents:** After each interview, the agent should:
- Update domain files with new patterns discovered
- Add successful questions to the library
- Document pitfalls encountered
- Record case studies with outcomes

This makes the Interview Agent smarter over time.

---

#### Context Management for Interview Agent

**Low risk** — conversations are naturally scoped to the topic at hand. No need to load entire codebases.

**Key requirement:** Output documents must be structured for easy partial reading by downstream agents. Use clear headings, concise summaries, and progressive disclosure (high-level overview → detailed specs).

Downstream coding agents should be able to read just the relevant sections without loading the entire requirements document into context.

---

#### Example Interview Flow (Direct Mode)

**Setup:**
- User: "Need to add authentication to the app, OAuth probably, don't want the session management nightmare from last time"
- Agent analyzes: Role = software architect, Goal = auth requirements, Domain = software-requirements
- Agent: "I'll be interviewing you as a software architect to help define requirements for this authentication feature. Sound right?"
- User: "Yeah"

**Interview:**

**Agent:** "You mentioned 'session management nightmare from last time.' Tell me about that specific situation. What happened?"

**User:** "We used OAuth with Google and it worked great until users started getting randomly logged out..."

*[Internal notes: pain point = random logouts, assumption = OAuth again?, unanswered = root cause?, completeness = 2/10]*

**Agent:** "Walk me through a specific instance when a user got logged out. What were they doing?"

**User:** "One user was filling out a long form, token expired after 30 minutes, they got kicked to login, lost all their work..."

*[Internal notes: insight = token expiry + no refresh = data loss, pain = lost work, completeness = 3/10]*

**Agent:** "What was going through your mind when you found out about that?"

**User:** "We needed automatic token refresh and we needed to save form state even if they get logged out..."

*[Internal notes: requirements emerging = auto-refresh + state persistence, completeness = 5/10]*

*[Continues with story-based questions, following tangents about token storage, security, third-party vs. custom auth]*

*[After ~18 questions, completeness = 9/10]*

**Agent:** "I think we've covered the core of this. Let me pull together what we've discovered."

**Output:** Structured requirements.md with auth components, inputs/outputs, constraints, edge cases from stories, success criteria.

---

#### Modularity

Must work standalone — usable on any project, not just within the full TeamBuild system. Can be invoked as:
- A CLI tool for any project
- A skill/agent within TeamBuild
- An API endpoint for external tools
- A standalone service

The interview methodology and domain libraries are project-agnostic and reusable.

---

### 2. PM Integration

**Purpose:** Single source of truth for all project coordination. Prevents agents from doing duplicate or conflicting work.

**v1 target:** Plane (self-hosted, personal account for testing)
**Must also support:** Linear (work environment)

**Core capabilities:**
- Create projects, features, and tickets from specs/requirements
- Agents pull assignments from the PM tool (no duplicate work)
- Status updates as agents work (in progress, blocked, review, done)
- Token/cost tracking per ticket (ties into metrics module)
- Coordination layer — if an agent is working on something, others can see it

**Abstraction requirement:** The PM layer must be abstract enough that swapping Plane for Linear (or a future tool) requires only writing a new adapter, not rewriting the integration.

**Research needed:** Beads format for project/token management across multiple agents.

**Modularity:** The PM adapter pattern should be reusable across projects. The Plane adapter and Linear adapter are independent modules.

---

### 3. Coding Agent Team

**Purpose:** Take a spec or ticket from the PM tool and build it through to a pull request.

**Autonomy model:** High autonomy with quality gates. Human is the exception handler, not the primary reviewer.

**Workflow:**
1. Agent picks up a ticket from PM tool
2. Updates ticket status to in-progress
3. Reads the spec/requirements
4. Writes tests first (TDD)
5. Implements the code
6. Self-validates: tests pass, linting passes, server/app runs, inputs produce expected outputs
7. Submits for review (Critique/Review Layer)
8. If review passes → PR + ticket update
9. If review fails → auto-fix loop (see Critique/Review Layer)

**Self-validation must include:**
- All tests pass (pytest for Python, appropriate runner for other languages)
- Linting passes (ruff for Python, appropriate linter for other languages)
- Type checks pass
- Server/application starts without errors
- Inputs produce expected outputs (integration-level check)

**Modularity:** Individual coding agents (Python, TypeScript, Rust, etc.) should be independent modules. The team orchestrator is a separate module that coordinates them.

---

### 4. Critique/Review Layer

**Purpose:** Catch problems before they move forward. Applies at every phase, not just code.

**Review types (may be separate agents/skills):**
- **Plan Critique** — reviews specs and plans before building starts
- **Code Review** — code quality, patterns, readability
- **Bug Detection** — logical errors, edge cases
- **Security Review** — OWASP top 10, dependency vulnerabilities
- **Test Validation** — test coverage, test quality, missing test cases
- **Spec Compliance** — does the output match what was requested?

**Circuit breaker pattern:**
- If a coding agent fails on the same issue 3-5 times (configurable), stop the loop
- Escalate to the human with:
  - What was attempted
  - What failed each time
  - Where the agent is stuck
  - Suggested next steps or questions
- Notification via desktop notification + PM tool ticket update

**Automation rule:** If tests fail or the server doesn't start, it loops back to the coding agent automatically — no human involvement needed for mechanical fixes.

**Modularity:** Each review type is an independent skill/agent. Projects can enable the ones they need. The circuit breaker is a shared utility.

---

### 5. Cost/Performance Metrics

**Purpose:** Measure everything so the system can improve and prove its value.

**Dogfooding:** This module is built BY items 1-4, serving as the first real test of the system.

**What to track:**
- Token usage per agent, per ticket, per project
- Actual cost per agent, per ticket, per project (by provider/model)
- Estimated vs. actual cost (improve prediction accuracy over time)
- Context window health — are agents staying in the "smart" window or degrading into the "dumb" window?
- Startup costs — how much does it cost for an agent to learn a new codebase?
- Time per ticket, per phase
- Circuit breaker triggers — how often agents get stuck, on what
- Model comparisons — did Sonnet do this cheaper/faster/better than Opus?

**Where metrics appear:**
- CLI output (during development)
- PM tool (per-ticket and per-project reports)
- Dashboard (web-based, later)
- Project reviews and retrospectives
- Future project estimations

**Modularity:** Metrics collection is a lightweight library that any module can import. Metrics storage and display are separate modules.

---

### 6. Provider Abstraction

**Purpose:** Ensure the system is not locked to any AI provider.

**Leading candidate:** Pydantic AI — needs validation in research phase before committing.

**Requirements:**
- Swap models per agent role (e.g., Haiku for search compilation, Opus for review, Sonnet for coding)
- Swap providers entirely (Claude → OpenAI → local model) without rewriting agent logic
- Track which model/provider is used per task (feeds into metrics)

**Validation needed:**
- Does Pydantic AI support all providers we need?
- Does it add meaningful overhead?
- Are there alternatives that do it better?

**Modularity:** This is the foundation layer — all agents depend on it. Must be stable and well-tested before building agents on top of it.

---

## Technical Constraints

| Constraint | Detail |
|-----------|--------|
| Primary AI language | Python |
| Web frontend | TypeScript |
| Other | Best tool for the job, don't force it |
| Testing | TDD — tests written before implementation |
| Linting | Strict (ruff for Python, equivalent for others) |
| Type checking | Required |
| Open source | Prefer open source. Self-hosted where possible |
| Modularity | Every component usable independently |
| Provider lock-in | None. Abstraction layer from day one |

---

## User Environment

| Aspect | Detail |
|--------|--------|
| Primary interface | Terminal (Claude Code), IDE |
| Notifications (v1) | Desktop notifications + PM tool |
| Notifications (later) | Slack, Teams, Discord integration |
| Working style | Minimal typing, aliases, keyboard shortcuts |
| Oversight model | High agent autonomy, easy human override when off-rails |

---

## Out of Scope for v0.1

These are captured for future phases but explicitly not part of the first build:

- Communication integrations (Slack, Teams, Discord)
- Web dashboard for metrics (CLI + PM tool first)
- Full Research Agent (referenced in base-plan.md but not prioritized for v0.1)
- Voice/audio features
- Simulation capabilities
- News watcher bot
- Cron-based ticket watchers
- Multiple simultaneous project support
