| name | agile:clean:room |
| description | Orchestrates a complete clean-room reverse engineering process that produces legally-defensible Product Requirements Documents (PRD), artifacts across all four agile levels (initiative → epic → feature → user story), and formal team separation for handoff to an independent implementation team. Operates at EPIC scope (against a codebase path) or INITIATIVE scope (against an approved initiative design.md, looping over its Epic Candidates table). Plugs into the initiative workflow via canonical `initiative:` frontmatter so `agile-initiative-progress` can track realization and task completion on one dashboard. Use when you need independent specifications for a development team with no access to original source, or when you want to reverse-engineer every epic in a multi-epic initiative in one coordinated run. Triggers on "clean room", "clean-room reverse engineer", "reverse engineer initiative", "reverse engineer epic", "generate PRD from codebase", "legally clean spec", "spec team vs impl team", "reverse engineer this initiative".
|
| user-invocable | true |
| disable-model-invocation | false |
| allowed-tools | ["Read","Edit","Write","Glob","Grep","Bash","Agent","Skill","TaskCreate","TaskList","TaskGet","TaskUpdate","SendMessage","AskUserQuestion","TeamCreate"] |
Agile Clean Room
Orchestrate a complete clean-room reverse engineering process that produces legally-defensible Product Requirements Documents (PRD), agile artifacts across all four work-item levels, and formal team separation for handoff to an independent implementation team. This skill:
- Creates comprehensive PRD — Full specifications including Interface Control Documents, State Machines, Data Flow Diagrams
- Manages team separation — Specification Team (access to original) vs Implementation Team (no access)
- Provides inbox-based communication — Formal clarification request system between teams
- Tracks dependency graphs — Visual task blocking/unblocking with ASCII diagrams
- Uses functional naming — Epic/feature names describe capability, not product identity
- Spans the full agile hierarchy — Initiative → Epic → Feature → User Story → Task, with canonical
initiative: frontmatter so agile-initiative-progress can track realization and task completion on one dashboard
Workflow Position
┌─ STRATEGIC (initiative-scope) ─────────────────────────────────┐
│ /agile:initiative:brainstorm → design.md APPROVED │
│ /agile:initiative:refine → design.md REFINED (optional) │
└──────────────────────────────┬─────────────────────────────────┘
▼
┌─ REVERSE-ENGINEERING (this skill) ──────────────────────────────┐
│ /agile:clean:room @initiative (initiative mode) │
│ /agile:clean:room <codebase-path> (epic mode, legacy) │
│ │
│ Phase 0: Level detection │
│ Phases 1–2: Parse inputs + 6-agent parallel extraction │
│ Phase 3: Synthesis + requirement merge │
│ Phase 3.5: OPTIONAL 5-expert refinement panel │
│ Phase 4: design.md (+ initiative: frontmatter in init. mode) │
│ Phase 5: plan.md, epic.md, feature specs + User Stories │
│ Phase 6: Consistency gate (fails on orphan tasks) │
│ Phase 7: Commit + handoff │
│ Phases 8–11: PRD, team setup, inbox, dependency graph │
└──────────────────────────────┬─────────────────────────────────┘
▼
┌─ IMPLEMENTATION (per epic) ─────────────────────────────────────┐
│ /agile:epic:implement <epic> │
│ /agile:epic:progress <epic> │
└──────────────────────────────┬─────────────────────────────────┘
▼
┌─ VISIBILITY (initiative-scope) ─────────────────────────────────┐
│ /agile:initiative:progress <slug> │
│ matches realized epics via canonical initiative: frontmatter │
│ counts 6-state task markers → unified dashboard │
└─────────────────────────────────────────────────────────────────┘
See references/initiative-integration.md for the precise contract between
clean-room and the initiative trio, and references/refinement-protocol.md
for the Phase 3.5 design.
Output Artifacts
| Artifact | Purpose | Legal Status |
|---|
prd/ | Product Requirements Document | CLEAN — Can be handed to Implementation Team |
epic/ | Agile epic structure | Internal planning |
evidence/ | Legal evidence package | Audit trail |
tasks/dependency-graph.md | Visual task dependency tracking | Progress visualization |
teams/ | Team configuration and firewall rules | Clean-room separation |
Legal Guardrails and Red Lines
MANDATORY: Functional Naming Protocol
CRITICAL LEGAL REQUIREMENT: This skill produces specifications for a legally separated development team that must have ZERO knowledge of what product is being reverse-engineered. To maintain legal defensibility:
-
NEVER use product names in epic names, feature names, folder names, or specifications:
- ❌
001-myproduct-cli, 002-superwhisper-ui
- ✅
001-command-interface, 002-terminal-renderer
-
ALWAYS use functional naming that describes WHAT the system does:
- Epic names:
NNN-[functional-description] (e.g., 001-cli-framework, 002-query-engine)
- Feature names:
NNN-XX-[capability-name] (e.g., 001-01-command-parser)
- Interface names:
I[Function][Type] (e.g., ICommandHandler, ITerminalRenderer)
-
Code names are OPTIONAL and only for internal reference:
- If used, code names must NOT appear in folder names or file paths
- Code names can appear in document content only when legally required
- Prefer functional descriptions over code names entirely
The Red Line: Non-Negotiable Constraints
These are ABSOLUTE PROHIBITIONS. Violation compromises legal defensibility:
| Red Line | Description | Enforcement |
|---|
| Identity Reveal | Never state what product is being reverse-engineered | All outputs use functional naming |
| Code Contamination | No code snippets, file paths, or structure from original | Specifications describe WHAT, never HOW |
| Naming Parallels | No similar names to original components | All interfaces/classes use independent naming |
| Team Crossover | Implementation Team must never see original | Firewall separation in all communications |
| Algorithm Disclosure | Never specify algorithms from original | Describe functional requirements only |
| Product-Based Naming | No product names in folders/files | Use functional naming exclusively |
Specification Cleanliness Check
Before ANY specification is approved, verify:
✅ All terminology is generic and functional (no product names)
✅ No references to original product name or company
✅ Interface names are independently designed
✅ Functional requirements describe behavior, not implementation
✅ State machines use generic state names
✅ Data models use independent field names
✅ No file paths or directory structures from original
✅ Performance metrics are specified without original benchmarks
✅ Epic/feature names describe capability, not product identity
Handoff Package Classification
All PRD artifacts must be marked:
Classification: CLEAN — No original source contamination
Legal Status: Suitable for Implementation Team handoff
Verification: Specification Team attests to IP cleanliness
Naming: Functional naming enforced throughout
Cascading Legal Requirements to Sub-Skills
When invoking downstream skills (e.g., agile-product-brainstorm), MUST propagate these legal constraints:
- Enforce functional naming: Epic/feature names describe capability, not product
- Require IP cleanliness: Ensure sub-skills never reveal original product identity
- Review all outputs: Verify sub-skill outputs comply with red lines before use
- Sanitize PRDs: Any PRD generated must use functional naming exclusively
Sub-skills that MUST receive legal constraints:
agile-product-brainstorm — PRD generation must use functional naming
agile-epic-brainstorm — Epic design must use generic terminology
agile-epic-plan — Feature specs must not reference original
Invocation
Epic mode (legacy — unchanged):
/agile:clean:room /path/to/original/codebase
/agile:clean:room /path/to/codebase "Additional requirement: must support OAuth2 and PostgreSQL"
/agile:clean:room https://github.com/org/repo "Focus on the CLI and TUI components"
Initiative mode (NEW — reverse-engineer every epic candidate in one run):
/agile:clean:room @agile/initiatives/001-modernize-auth/design.md /path/to/original/codebase
/agile:clean:room 001 /path/to/original/codebase (resolves initiative by number)
Initiative-first mode (brainstorm the initiative then reverse-engineer it):
/agile:clean:room --initiative "Modernize auth across all services" /path/to/codebase
Phase 0: Level Detection
Parse $ARGUMENTS before anything else. The scope determines which downstream
phases loop.
| Argument form | Mode | Behavior |
|---|
Argument matches @agile/initiatives/NNN-*/design.md | Initiative | Read design.md; require **Status**: APPROVED or REFINED; loop clean-room over each Epic Candidate Seq. |
First argument is a bare 3-digit number (e.g. 001, 042) | Initiative | Resolve to agile/initiatives/NNN-*/design.md; otherwise same as above. |
Argument starts with --initiative "<seed>" followed by a codebase path | Initiative-first | Delegate to agile-initiative-brainstorm with the seed; then proceed as initiative mode against the new slug. |
First argument is a local path (/, ./, ../) or http(s)://<git-url> | Epic | Legacy flow: single-epic clean-room run over the given codebase. |
| No arguments | Interactive | Ask the user whether they want initiative mode or epic mode; then gather the missing inputs. |
Outputs of Phase 0
MODE ∈ {EPIC, INITIATIVE, INITIATIVE_FIRST}
TARGET_PATH — local path to the target codebase (clone first if a URL)
ADDITIONAL_REQUIREMENTS — optional quoted string merged in Phase 3
- If INITIATIVE / INITIATIVE_FIRST:
INITIATIVE_SLUG (e.g. 001-modernize-auth)
INITIATIVE_DESIGN_PATH (the design.md to read, never write)
CANDIDATES — array of {seq, name, scope, sprint, deps, risk} parsed from the Epic Candidates table
Pre-flight (Initiative mode only)
Run these checks before any epic is generated. Fail loudly — never fabricate.
INITIATIVE_DESIGN_PATH exists and Status is APPROVED or REFINED.
- The design.md contains a parsable
## 5. Epic Candidates section with a Seq column.
- No existing epic already carries
initiative: <INITIATIVE_SLUG> with a Seq that would collide.
TARGET_PATH is readable and contains source (the codebase being reverse-engineered).
If any check fails, stop and explain. Direct the user to the remediation path
documented in references/initiative-integration.md.
Hard Gate
Do NOT proceed with analysis if TARGET_PATH does not exist or is not readable,
or if Phase 0 pre-flight fails. Report the specific validation failure and exit.
Phase 1: Entry and Validation
Phase 1 runs once in epic mode, and once per Epic Candidate in initiative
mode. Where this phase mentions SEQ / INITIATIVE_SLUG, those are empty in
epic mode.
- Validate
TARGET_PATH using Bash (test -d and test -r)
- If invalid, report the error and stop
- Run
agile-epic-brainstorm/scripts/next-epic-number.sh to obtain the next epic number (NNN). In initiative mode, draw one number per candidate in Seq order, so downstream numbering is deterministic.
- Generate a functional kebab-case epic name based on the system's primary capability (or, in initiative mode, from the Epic Candidate's
Name column after confirming it is IP-clean):
- Analyze the codebase to identify the core functional domain
- Use descriptive terms like:
query-engine, terminal-ui, command-processor, tool-execution
- ❌ AVOID: product names, brand names, code names, proper nouns
- ✅ PREFER: verb-noun or noun-noun functional descriptions
- Examples:
cli-framework, terminal-renderer, session-manager, permission-system
- Create the epic directory:
agile/epics/NNN-[functional-name]/
- Record
MODE, INITIATIVE_SLUG, SEQ, and NNN in a scratch state file for later phases.
Phase 2: Parallel Reverse Engineering Analysis
Dispatch the clean-room agent team in parallel. Each agent reads its system prompt from .claude/agents/reverse/.
Before dispatching, read the agent definition files to extract system prompts:
.claude/agents/reverse/spec-analyzer.md
.claude/agents/reverse/spec-writer.md
.claude/agents/reverse/spec-reviewer.md
.claude/agents/reverse/architecture-advisor.md
.claude/agents/reverse/risk-guardian.md
.claude/agents/reverse/evidence-curator.md
Agent 1: Spec Analyzer
Purpose: Analyze the target codebase for components, functionality, and specification gaps.
Dispatch prompt:
You are the Specification Analyzer. Analyze the codebase at [TARGET_PATH].
Identify:
1. All major functional components and their responsibilities
2. Public interfaces and APIs
3. Key workflows and state machines
4. Error handling patterns
5. Data models and entities
6. Performance-critical areas
Output a structured markdown report with:
- Component inventory (name, purpose, files involved)
- Interface inventory (inputs, outputs, contracts)
- Workflow inventory (sequence of operations)
- Gap analysis (areas requiring deeper specification)
Agent 2: Architecture Advisor
Purpose: Identify the original architecture and recommend .NET-native alternatives.
Dispatch prompt:
You are the Architecture Advisor. Analyze the codebase at [TARGET_PATH].
Identify:
1. Original architecture patterns and frameworks used
2. Dependency injection approach
3. Configuration management
4. Async/streaming patterns
5. UI/TUI architecture
6. Tool/plugin system architecture
7. LLM provider abstraction
Output a structured markdown report with:
- Original architecture summary
- For each major pattern, recommend the .NET idiomatic equivalent
- Flag any structural choices that must NOT be copied
- Independence recommendations
Agent 3: Risk Guardian
Purpose: Establish a legal risk baseline for the clean-room effort.
Dispatch prompt:
You are the Risk Guardian. Review the target codebase at [TARGET_PATH].
Assess:
1. Copyright risks (unique expression that must not be copied)
2. Trade secret risks (confidential algorithms or processes)
3. Patent risks (novel algorithms or methods)
4. Process risks (areas where clean-room separation is critical)
Output a Risk Assessment Report in the standard format.
Assign risk levels (Critical/High/Medium/Low) to each component.
Agent 4: Spec Writer
Purpose: Draft initial clean-room specifications for the most important components.
Dispatch prompt:
You are the Specification Writer. Based on the codebase at [TARGET_PATH], draft clean-room specifications for the top 5-7 most critical components.
For each component, produce:
- Specification ID (e.g., SPEC-CORE-001, SPEC-UI-001)
- Purpose statement
- Functional Requirements (with IDs and priorities)
- Interface Definitions (C#-style, independent naming)
- Behavioral Specifications (state machines, workflows)
- Data Models
- Error Handling
- Performance Requirements
- Acceptance Criteria (Gherkin format)
Ensure ZERO contamination: no copied names, no code snippets, no file paths from original.
Output each specification as a separate markdown section.
Agent 5: Spec Reviewer
Purpose: Review the Spec Writer's drafts for IP cleanliness and quality.
Wait until Spec Writer completes. Then dispatch:
You are the Specification Reviewer. Review the following draft specifications for IP cleanliness, completeness, clarity, consistency, testability, and architecture alignment.
[attach Spec Writer output]
Output a Specification Review Report with:
- Verdict per specification (APPROVED / NEEDS_REVISION / REJECTED)
- Scores across 6 dimensions
- Specific action items for any specification needing revision
Agent 6: Evidence Curator
Purpose: Initialize the evidence trail for legal defensibility.
Dispatch prompt:
You are the Evidence Curator. Initialize an evidence package for the clean-room epic.
Create the following in agile/epics/NNN-epic-name/evidence/:
1. manifest.json with project metadata
2. A specification version control template
3. A clarification request log template
4. A team separation agreement template
Output the file contents and recommended directory structure.
Run all independent agents (1, 2, 3, 4, 6) in parallel using run_in_background: true.
Run agent 5 sequentially after agent 4 completes.
Phase 3: Synthesis and User Requirement Merge
- Collect all agent outputs
- Resolve conflicts (e.g., if Risk Guardian flags a component that Spec Writer over-specified)
- Merge
ADDITIONAL_REQUIREMENTS into the specification set:
- Map user requirements to new or existing specifications
- Add features derived from user requirements
- Update acceptance criteria to cover user requirements
- Read
references/clean-room-methodology.md and references/product-specification-template.md to ensure conformance
- Produce a consolidated Clean-Room Specification Summary containing:
- Epic-level problem statement
- Component inventory with spec IDs
- Architecture decision seeds
- Risk summary
- Feature candidates derived from specifications
Phase 3.5: Refinement Hook (Optional)
After synthesis but before writing design.md, offer a 5-expert stress-test
of the synthesized design. Default is skip; medium+ scope epics should run it.
See references/refinement-protocol.md for the full protocol, rationale,
and when to run more than one iteration.
Prompt the user
Via AskUserQuestion:
- Skip refinement (default — fast, matches legacy behavior).
- Run 5-expert refinement panel (Recommended for 4+ features or any HIGH-risk item).
If the user selects the panel, follow up with a single question for iteration
count (1, 2, or 3; default 1). More than 3 belongs at the initiative level
via /agile:initiative:refine.
Agents
Reuse the agent prompt files from
.claude/skills/agile-initiative-refine/templates/agent-prompts/:
| Agent | Subagent type | Focus |
|---|
| Proposer | general-purpose | Alternative scopes, interface boundaries, architecture options. |
| Challenger | general-purpose | Devil's advocate on assumptions, scope creep, hidden couplings. |
| Grounder | Explore | Verifies the synthesized design is realizable against TARGET_PATH. |
| Reviewer | general-purpose | Completeness, coherence, spec ↔ feature ↔ story traceability. |
| Critic | general-purpose | Risk vs. value, feasibility, red-flag detection. |
Focus domains (3, not 5)
Clean-room's refinement skips D2 (epic decomposition — we just produced it)
and D4 (timeline/risk — belongs to initiative-refine). Use:
- D1: Strategic alignment (and alignment with parent initiative if in INITIATIVE mode).
- D3: Codebase reality (Grounder drives this).
- D5: Coherence & polish (traceability across spec → feature → story).
Dispatch pattern
- Spawn Grounder first, alone, with access to
TARGET_PATH. Grounder
produces a codebase-reality report.
- When Grounder returns, spawn Proposer, Challenger, Reviewer, Critic in
parallel. Each gets the Clean-Room Specification Summary plus Grounder's
report.
- Synthesize findings into:
- a Refinement Notes section that will be appended to
design.md in
Phase 4;
- a sibling
refinement-report.md in the epic directory (date,
iteration count, per-agent findings, consensus/contested classification,
decisions taken).
Firewall discipline
Grounder's raw codebase findings MUST NOT propagate into any artifact destined
for the Impl-Team side of the firewall (PRD, ICDs, state machines, dataflows).
Phase 8 produces those artifacts and scrubs them separately.
Status
Do not change status: to REFINED. Clean-room epics remain APPROVED after
refinement; the REFINED status is reserved for agile-initiative-refine
applied to the parent initiative's design.md.
Phase 4: Generate design.md
-
Read .claude/skills/agile-epic-brainstorm/templates/design-template.md
-
Fill the template using the Clean-Room Specification Summary:
- Problem Statement: Why a clean-room reimplementation is needed
- Success Criteria: Measurable outcomes from the spec summary
- Constraints & Risks: Copy the Risk Guardian's findings
- Dependencies: Any predecessor epics or external deliverables
- Approaches Considered: Original port vs. clean-room approach
- Chosen Approach: Clean-room with independent .NET architecture
- Technical Direction: High-level architecture from Architecture Advisor
- Feature Candidates: Map each specification to a 2-digit feature ID (
NNN-01, NNN-02, etc.)
-
Prepend canonical YAML frontmatter to the file:
---
epic: NNN-<epic-slug>
status: APPROVED
generator: agile-clean-room
ip-clean: true
source-commit: <baseline-sha-of-TARGET_PATH>
initiative: <INITIATIVE_SLUG>
initiativeCandidate: <SEQ>
---
This block is what agile-initiative-progress uses to match realized epics
back to their parent initiative's Epic Candidates table. Never omit it in
initiative mode.
-
Write to agile/epics/NNN-epic-name/design.md.
-
Initiative-mode only: run
scripts/link-epic-to-initiative.sh <epic-dir> <INITIATIVE_SLUG> <SEQ> to
idempotently ensure the initiative: / initiativeCandidate: frontmatter
fields are present. Running it a second time is a no-op — safe for re-runs
and crash recovery.
-
If Phase 3.5 produced Refinement Notes, append them as a ## Refinement Notes
section at the end of design.md and write the sibling refinement-report.md.
Phase 5: Generate Epic Artifacts
Because agile:epic:plan cannot be invoked via the Skill tool, generate the remaining artifacts directly.
Step 5.1: Generate plan.md
- Read
.claude/skills/agile-epic-plan/templates/plan-template.md
- Derive tier from feature count (LEAN/STANDARD/COMPREHENSIVE)
- Fill the plan template with content from
design.md and agent outputs:
- Strategic Overview from Problem Statement + Chosen Approach
- Architecture Decisions from Architecture Advisor output
- Feature Inventory from Feature Candidates
- Dependencies from component relationships
- Risk Assessment from Risk Guardian output
- Success Criteria from design.md
- Write to
agile/epics/NNN-epic-name/plan.md
Step 5.2: Generate epic.md
- Read
.claude/skills/agile-epic-plan/templates/epic-template.md
- Fill the template from
design.md and plan.md
- Generate the Feature Workflow ASCII DAG from the Dependencies table
- Write to
agile/epics/NNN-epic-name/epic.md
Step 5.3: Generate Feature Specifications and Tasks (Parallel Subagents)
For each feature in the Feature Candidates table:
- Determine feature directory:
agile/epics/NNN-epic-name/NNN-XX-feature-name/
- Read
.claude/skills/agile-epic-plan/templates/spec-template.md
- Read
.claude/skills/agile-epic-plan/templates/tasks-template.md
- Dispatch a subagent with:
Generate spec.md and tasks.md for feature NNN-XX of epic NNN.
FEATURE CONTEXT:
- Feature ID: NNN-XX
- Feature name: [name]
- Feature directory: [path]
- Scope: [from plan.md Feature Inventory]
- Dependencies: [from plan.md]
- Risk: [LOW/MEDIUM/HIGH]
- Story Points: [N]
CLEAN-ROOM SPECIFICATION CONTEXT:
[Attach the relevant SPEC-XXX section from Phase 3]
GENERATION RULES:
1. Create the feature directory
2. Generate spec.md following the spec template:
- Feature metadata: branch name NNN-XX-feature-name, status PENDING
- MANDATORY `## User Stories` section. Every feature MUST declare at
least one story. Use `### NNN-XX-U{n} - <Functional title>` headings.
Each story block MUST include Story Points (Fibonacci 1/2/3/5/8),
Priority (P1|P2|P3), Complexity (LOW|MEDIUM|HIGH), Risk, the
"As a / I want / so that" sentence, "Why this priority", "Independent
Test", and at least two Gherkin-style Acceptance Criteria.
Story text MUST be IP-clean: no product names, no original-code verbs,
no file paths. See `references/user-story-guidelines.md`.
- Requirements: FR-001, FR-002... derived from the clean-room spec
- Success Criteria as checkboxes
- Constitution Compliance entries
3. Generate tasks.md following the tasks template:
- Task IDs: NNN-XX-T{nn} format
- Every task line MUST carry a `[NNN-XX-U{n}]` story reference that
matches a declared story. Phase 6 runs
`scripts/check-story-coverage.sh` and fails the feature if any task
is orphaned or references an undeclared story.
- 6-state markers: all start as [ ]
- Include Tasks Workflow ASCII DAG
- Cross-feature deps documented in header
4. Write files to the feature directory
Dispatch all feature subagents in parallel using run_in_background: true.
Step 5.4: Generate checklist.md
- Read
.claude/skills/agile-epic-plan/templates/checklist-template.md
- Populate with epic metadata, constitution compliance items, and feature completion gates
- Write to
agile/epics/NNN-epic-name/checklist.md
Phase 6: Consistency Check
Perform a mechanical cross-artifact consistency analysis. This phase is a
hard gate — any failure here must be fixed before Phase 7 commits.
- Verify every feature ID in
epic.md has a matching directory.
- Verify every dependency in
epic.md corresponds to an actual feature.
- Verify task IDs match the
NNN-XX-T{nn} pattern.
- Verify
design.md Feature Candidates match epic.md Epic Breakdown.
- Verify no circular dependencies in the Feature Workflow DAG.
- Story coverage (MANDATORY) — run
scripts/check-story-coverage.sh <feature-dir> for every feature directory.
Any orphan task (task with no [NNN-XX-U{n}] reference) or any task
pointing to a story not declared in spec.md is a consistency failure.
- Initiative backlink (initiative mode only) —
design.md MUST contain
initiative: <INITIATIVE_SLUG> in its frontmatter. If missing, run
scripts/link-epic-to-initiative.sh <epic-dir> <INITIATIVE_SLUG> <SEQ>
and re-verify.
- Frontmatter —
design.md MUST carry generator: agile-clean-room,
ip-clean: true, and source-commit: <sha> fields. These anchor the
legal evidence trail and let downstream tooling recognize clean-room-
generated epics.
If any CRITICAL inconsistency is found, fix it and re-run this phase before
committing.
Phase 7: Commit and Handoff
- Create a git commit with message:
docs(agile): add clean-room epic NNN-epic-name with design, plan, and feature specs
- Present a summary to the user:
- Epic number and name
- Feature count
- Specification count
- Risk summary (highest risk level)
- Evidence package location
- Present next-step options via
AskUserQuestion:
["Done — end session"]
["Implement — invoke /agile:epic:implement NNN"] (advise user to type this manually)
["Push to DevOps — invoke /devops:workitem push NNN"] (advise user to type this manually)
Phase 8: PRD Generation (Legally-Clean Handoff)
Generate the complete Product Requirements Document (PRD) that can be legally handed to the Implementation Team with no access to original source code.
Step 8.1: Create PRD Directory Structure
Create agile/epics/NNN-epic-name/prd/ with subdirectories:
icd/ — Interface Control Documents
state/ — State Machine specifications
dataflow/ — Data Flow Diagrams
glossary/ — Terminology definitions
handoff/ — Implementation Team handoff package
Step 8.2: Generate Interface Control Documents (ICDs)
For each major interface identified in Phase 3:
- Read
references/product-specification-template.md section on Interface Definitions
- Create
prd/icd/SPEC-XXX-icd.md for each specification:
# Interface Control Document: [Component Name]
**Document ID**: ICD-[SPEC-ID]
**Version**: 1.0
**Status**: CLEAN for Implementation Team
## Interface Summary
| Attribute | Value |
| ------------------ | ------------------------------------------ |
| **Interface Name** | [Independent name, no original references] |
| **Purpose** | [What this interface enables] |
| **Protocol** | [Synchronous/Asynchronous/Event-driven] |
| **Data Format** | [JSON/Binary/Stream/etc] |
## Contract Definition
### Inputs
| Parameter | Type | Required | Description | Constraints |
| --------- | --------- | -------- | ------------- | ------------------ |
| [param1] | [C# type] | Yes/No | [Description] | [Validation rules] |
### Outputs
| Return Value | Type | Description | Error Conditions |
| ------------ | --------- | ------------- | ---------------- |
| [return] | [C# type] | [Description] | [When it fails] |
### Events/Callbacks
| Event | Payload | Trigger Condition |
| ----------- | ------- | ----------------- |
| [EventName] | [Type] | [When fired] |
## Sequence Diagram
```ascii
[ASCII sequence diagram showing interaction]
```
Error Handling
| Error Code | Condition | Recovery Action |
|---|
| [CODE_001] | [When it occurs] | [How to handle] |
Performance Requirements
- Max latency: [X]ms
- Max throughput: [Y] ops/sec
- Concurrency: [Z] simultaneous calls
Version History
| Version | Date | Author | Changes |
|---|
| 1.0 | [date] | Spec Team | Initial CLEAN specification |
### Step 8.3: Generate State Machine Specifications
For each stateful component identified in Phase 3:
1. Create `prd/state/SPEC-XXX-state.md`:
```markdown
# State Machine Specification: [Component Name]
**Document ID**: STATE-[SPEC-ID]
**Version**: 1.0
**Status**: CLEAN for Implementation Team
## State Overview
### States
| State ID | State Name | Description | Entry Actions | Exit Actions |
|----------|------------|-------------|---------------|--------------|
| S1 | [Name] | [Description] | [Actions] | [Actions] |
### Transitions
| From | To | Trigger | Guard Condition | Actions |
|------|----|---------|-----------------|---------|
| S1 | S2 | [Event] | [Condition] | [Actions] |
## State Diagram
```ascii
+--------+ [trigger] +--------+
| S1 | -----------------> | S2 |
+--------+ [guard cond] +--------+
^ |
| |
+-------------------------------+
[reset event]
State Details
State: [S1 Name]
Purpose: [What this state represents]
Valid Transitions:
- To [S2] via [trigger] when [guard]
- To [S3] via [trigger] when [guard]
Entry Actions:
- [Action 1]
- [Action 2]
In-State Behavior:
- [What happens while in this state]
Exit Actions:
- [Action 1]
Event Definitions
| Event ID | Event Name | Payload | Source |
|---|
| E1 | [Name] | [Type] | [Component] |
Implementation Notes
- Thread safety requirements
- Persistence requirements
- Recovery behavior after crash
### Step 8.4: Generate Data Flow Diagrams
1. Create `prd/dataflow/system-dataflow.md`:
```markdown
# System Data Flow Specification
**Document ID**: DF-SYSTEM-001
**Version**: 1.0
## Context Diagram (Level 0)
```ascii
+------------------+
External | |
Input --------> | [System Name] | ------> External Output
| |
Control -------> | | ------> Status/Events
+------------------+
Level 1 Data Flow
+----------+ +----------+ +----------+ +----------+
| Input | --> | Process | --> | Process | --> | Output |
| Handler | | A | | B | | Renderer |
+----------+ +----------+ +----------+ +----------+
^ |
| v
+----------+ +----------+
| Data | <--- | State |
| Store | | Manager |
+----------+ +----------+
Data Store Specifications
| Store | Purpose | Schema | Persistence |
|---|
| [Name] | [Purpose] | [Key fields] | [Duration] |
Data Flow Details
Flow: [Flow Name]
| Attribute | Value |
|---|
| Source | [Component] |
| Destination | [Component] |
| Trigger | [What initiates flow] |
| Data Volume | [Size/frequency] |
| Latency Req | [Timing requirement] |
Data Transformations
| Step | Input | Output | Transformation Logic |
|---|
| T1 | [Type] | [Type] | [Description] |
### Step 8.5: Generate Terminology Glossary
Create `prd/glossary/terminology.md`:
```markdown
# Terminology Glossary
**Document ID**: GLOSSARY-001
**Version**: 1.0
## Purpose
This document defines all domain-specific terms used in the PRD. The Implementation Team MUST use these terms consistently and MUST NOT use terminology from the original source system.
## Term Definitions
| Term | Definition | Related Terms | Notes |
|------|------------|---------------|-------|
| [Term] | [Definition] | [Links] | [Clarifications] |
## Naming Conventions
### Interfaces
- Prefix: `I[Functionality]`
- Examples: `IRenderEngine`, `IInputHandler`
### Classes
- Suffix by type: `...Service`, `...Manager`, `...Engine`
- No abbreviations
### Methods
- Verb-first: `Process...`, `Calculate...`, `Render...`
- Async suffix: `...Async`
## Prohibited Terms
The following terms MUST NOT be used (original source contamination):
| Prohibited | Use Instead | Reason |
|------------|-------------|--------|
| [Original] | [Independent] | IP cleanliness |
Step 8.6: Assemble Handoff Package
Create prd/handoff/README.md:
# Implementation Team Handoff Package
**Epic**: NNN-[functional-name]
**Date**: [date]
**Classification**: CLEAN — No original source contamination
## Package Contents
1. **Product Requirements Document** (this directory)
2. **Interface Control Documents** (`../icd/`)
3. **State Machine Specifications** (`../state/`)
4. **Data Flow Specifications** (`../dataflow/`)
5. **Terminology Glossary** (`../glossary/`)
6. **Evidence Package** (`../../evidence/`)
## Team Separation Agreement
The Implementation Team confirms:
- [ ] No member has accessed original source code
- [ ] All specifications are being read for the first time
- [ ] No communication with Specification Team outside inbox protocol
- [ ] All code will be independently created
## Getting Started
1. Review the Glossary first — terminology is independent
2. Read Interface Control Documents for component boundaries
3. Study State Machines for behavioral requirements
4. Examine Data Flows for integration patterns
5. Submit clarification requests via inbox system
## Communication Protocol
All questions MUST go through the inbox system:
- Location: `../../inbox/`
- Format: Use clarification-request-template.md
- Response time: 24-48 hours
Phase 9: Team Coordination Setup (Claude Code Platform)
Establish two separate Claude Code teams with formal separation between Specification Team (access to original) and Implementation Team (PRD-only). Uses native TaskCreate/TaskUpdate inbox system and SendMessage for coordination.
Step 9.1: Create Specification Team
Use TeamCreate to create the Specification Team:
{
"team_name": "NNN-spec-team",
"description": "Specification Team for epic NNN ([functional-description]) - analyzes original source, produces clean-room PRD"
}
Spawn teammates using Agent tool with team_name: "NNN-spec-team":
- Spec Analyzer — Analyzes original codebase
- Spec Writer — Drafts clean specifications
- Architecture Advisor — Designs independent architecture
- Risk Guardian — Monitors IP cleanliness
Step 9.2: Create Implementation Team
Use TeamCreate to create the Implementation Team:
{
"team_name": "NNN-impl-team",
"description": "Implementation Team for epic NNN ([functional-description]) - implements from PRD only, no original source access"
}
Spawn teammates using Agent tool with team_name: "NNN-impl-team":
- Impl Lead — Coordinates implementation, reviews PRD
- Feature Developer — Implements features from specifications
- QA Engineer — Validates against specifications
Step 9.3: Team Firewall Configuration
Create teams/clean-room-firewall.md documenting access rules:
# Clean-Room Team Firewall
## Team Separation
| Team | Team Name | Source Access | PRD Access |
| -------------- | ------------- | ------------- | ---------- |
| Specification | NNN-spec-team | READ | WRITE |
| Implementation | NNN-impl-team | DENIED | READ |
## Communication Rules
- **Allowed**: SendMessage from Impl Team to Spec Team for clarification requests
- **Allowed**: TaskCreate/TaskUpdate for formal task tracking
- **Prohibited**: Direct file sharing, code snippets, architecture discussion
- **Prohibited**: Any mention of "original" or "source" in Impl Team context
## Work Directory Isolation
- Spec Team: Full project access including `.claude/work/source-analysis/`
- Impl Team: Access only to `prd/`, `agile/epics/NNN-*/spec.md`, own worktree
Step 9.4: Launch tmux Coordination Workspace (Optional)
If user requests split-pane view, use agile-team skill or create tmux session:
tmux new-session -d -s "cleanroom-NNN"
tmux new-window -t "cleanroom-NNN:0" -n "Spec Team"
tmux send-keys -t "cleanroom-NNN:0" "/agile:team status NNN-spec-team" C-m
tmux new-window -t "cleanroom-NNN:1" -n "Impl Team"
tmux send-keys -t "cleanroom-NNN:1" "/agile:team status NNN-impl-team" C-m
Phase 10: Clarification Request System (Task-Based Inbox)
Use Claude Code's native TaskCreate/TaskUpdate system for formal clarification requests between Implementation Team and Specification Team. Each clarification request is a task with dependencies and priority.
Step 10.1: Clarification Request Format
When Implementation Team needs clarification, they use TaskCreate:
{
"subject": "REQ-NNN-XXXX: [Brief question summary]",
"description": "## Clarification Request\n\n**Referencing**: ICD-[SPEC-ID], Section [X.Y]\n**Feature**: NNN-XX\n**Priority**: BLOCKING|HIGH|MEDIUM|LOW\n\n### Question\n[Clear, specific question]\n\n### Context\n[What I've tried, why this matters]\n\n### Proposed Interpretation\n[If applicable, my guess at the answer]\n\n---\n**Requester**: [Impl Team member]\n**Date**: [ISO-8601]",
"metadata": {
"epic": "NNN",
"feature": "NNN-XX",
"spec_ref": "ICD-XXX",
"request_type": "clarification",
"priority": "BLOCKING"
}
}
Step 10.2: Assign to Specification Team
Use TaskUpdate to assign clarification request to Spec Team member:
{
"taskId": "[clarification-task-id]",
"owner": "spec-writer"
}
Then notify via SendMessage:
SendMessage:
message: "New clarification request assigned: REQ-NNN-XXXX. Please review and respond."
to: "spec-writer"
summary: "Clarification request needs answer"
Step 10.3: Answer and Resolution
When Spec Team answers:
- Update task description with answer section
- Mark task complete via
TaskUpdate:
{
"taskId": "[clarification-task-id]",
"status": "completed"
}
- Notify Implementation Team:
SendMessage:
message: "Clarification REQ-NNN-XXXX answered. See task for details."
to: "impl-lead"
summary: "Clarification answered"
Step 10.4: PRD Updates from Clarifications
If clarification reveals spec gaps:
- Create follow-up task for Spec Team:
{
"subject": "Update PRD: [Section] per REQ-NNN-XXXX",
"description": "Update ICD-[SPEC-ID] Section [X.Y] based on clarification answer.\nSee clarification request REQ-NNN-XXXX for details.",
"addBlockedBy": ["[clarification-task-id]"]
}
- Update PRD document
- Notify both teams of specification change
Step 10.5: Legal Audit Trail
All clarification requests are automatically tracked via the task system. For legal defensibility, also log to evidence/clarifications-log.md:
## Clarification Log
| Request ID | Date | From | To | Question Summary | Answer Summary | PRD Updated |
| ------------ | ------ | -------- | ----------- | ---------------- | -------------- | ----------- |
| REQ-NNN-0001 | [date] | impl-dev | spec-writer | [summary] | [summary] | Yes/No |
Phase 11: Dependency Graph Tracking (Task System Integration)
Leverage Claude Code's native task dependency system via TaskUpdate with addBlockedBy. Generate visual ASCII dependency graphs for documentation.
Step 11.1: Create Tasks with Dependencies
When creating tasks for Implementation Team, use addBlockedBy to establish blocking relationships:
{
"subject": "001-01-T03: Create IElement interface",
"description": "..."
}
{
"subject": "001-01-T05: Implement ElementSnapshot",
"description": "...",
"addBlockedBy": ["task-id-a"]
}
Step 11.2: Dependency Discovery
Query task dependencies using TaskGet:
{
"taskId": "[task-id]"
}
Response includes:
blockedBy: Tasks that must complete before this task
blocks: Tasks waiting on this task's completion
Step 11.3: Generate ASCII Dependency Graph
Create tasks/dependency-graph.md for visualization:
# Task Dependency Graph
**Epic**: NNN-epic-name
**Generated**: [timestamp]
**Source**: Claude Code Task System
## Legend
- ✅ Completed
- 🔄 In Progress
- ⏳ Pending (ready to start)
- 🔒 Blocked (dependencies not met)
- → Dependency flow
## Feature 001-01: Core Element Tree
T01 (✅) ───────┐
▼
T02 (🔄) ──→ T04 (⏳) ──┐
├──→ T05 (🔒)
T03 (✅) ───────────────┘
▲
└── blocked by T01, T03
## Cross-Feature Dependencies
001-01 (Core) ─────┐
├──→ 001-03 (Components)
001-02 (Render) ───┘
## Task Status Table
| Task ID | Description | Status | Blocked By | Ready |
|---------|-------------|--------|------------|-------|
| 001-01-T01 | Verify spec | ✅ | - | Yes |
| 001-01-T03 | Create IElement | ✅ | T01 | Yes |
| 001-01-T04 | Create ElementTree | ⏳ | T02 | Yes |
| 001-01-T05 | ElementSnapshot | 🔒 | T03, T04 | No |
## Critical Path
T01 → T03 → T05 → T07 → T09
*Critical path length: 5 tasks*
Step 11.4: Sync Task System to tasks.md
When tasks are completed via TaskUpdate, sync status back to tasks.md:
sed -i 's/- \[ \] 001-01-T03/- [x] 001-01-T03/' tasks.md
Step 11.5: Blocked Task Notifications
When a task becomes unblocked (all dependencies complete):
SendMessage:
message: "Task 001-01-T05 is now unblocked and ready to start. Dependencies: T03 (✅), T04 (✅)"
to: "impl-lead"
summary: "Task unblocked: 001-01-T05"
Key Principles
- Clean-room integrity first: Never copy code, names, or structure from the original. The specifications must describe WHAT, not HOW.
- Agent parallelism: Dispatch independent reverse-engineering agents in parallel to reduce analysis time.
- User requirement merge: Additional arguments from the user are first-class inputs. Merge them into specifications and acceptance criteria.
- Agile conformance: All output artifacts must match the format expected by
agile:epic-implement (2-digit feature IDs, full-prefix task IDs, ASCII DAGs).
- Evidence trail: Always initialize the evidence package. Clean-room is only legally defensible with documentation.
- Claude Code Platform Integration: Use native team coordination features:
TeamCreate for separate Spec and Implementation teams
TaskCreate/TaskUpdate with addBlockedBy for dependency tracking
SendMessage for team communication (with summary parameter)
TaskGet/TaskList for inbox status and blocking queries
References
| File | Purpose |
|---|
references/clean-room-methodology.md | Legal framework and process requirements |
references/product-specification-template.md | Specification format and writing guidelines |
references/architecture-blueprint.md | .NET architecture guidelines for independent design |
references/implementation-guidelines.md | Rules for the implementation team |
references/evidence-trail-protocol.md | Documentation and legal hold requirements |
references/team-separation-protocol.md | Team firewall and communication rules |
references/icd-template.md | Interface Control Document format |
references/state-machine-template.md | State machine specification format |
references/dataflow-template.md | Data flow diagram specification format |
references/initiative-integration.md | Contract between clean-room and the initiative trio (NEW) |
references/refinement-protocol.md | Phase 3.5 five-expert refinement specification (NEW) |
references/user-story-guidelines.md | Mandatory user-story section format, IP-cleanliness rules (NEW) |
New scripts
| Script | Purpose |
|---|
scripts/next-initiative-number.sh | Thin wrapper over agile-initiative-brainstorm's script (numbering canonical upstream). |
scripts/link-epic-to-initiative.sh | Idempotently write initiative: / initiativeCandidate: frontmatter into epic design.md. |
scripts/check-story-coverage.sh | Phase 6 hard gate: fail if any task lacks a declared [NNN-XX-U{n}] story reference. |
After this skill finishes
Direct the user to the unified dashboard:
/agile:initiative:progress <INITIATIVE_SLUG>
agile-initiative-progress will recognize every epic this skill generated
(via canonical initiative: frontmatter), scan each epic's tasks.md for
6-state markers, and render realization + implementation percentages on one
page. No configuration needed — the contract is the frontmatter field.
External Dependencies
This skill relies on these external resources:
.claude/agents/reverse/*.md — Reverse engineering agent system prompts
.claude/skills/agile-epic-brainstorm/templates/design-template.md — Design document template
.claude/skills/agile-epic-plan/templates/*.md — Epic planning templates
.agile/rules/constitution.md — Master constitution for compliance entries
Claude Code Platform Features
| Feature | Tool | Usage |
|---|
| Team Creation | TeamCreate | Create separate Spec and Implementation teams |
| Task Inbox | TaskCreate/TaskUpdate | Clarification requests with addBlockedBy for dependencies |
| Messaging | SendMessage | Team coordination (use message, to, summary params) |
| Status Query | TaskGet/TaskList | Check task status and blocking relationships |
| Teammate Spawning | Agent with team_name | Spawn team members with proper team context |
PRD Generation Resources
references/product-specification-template.md — Interface and specification formats
Team Coordination Resources
teams/clean-room-firewall.md — Team separation rules
Dependency Tracking Resources
scripts/generate-dependency-graph.sh — Generate ASCII dependency visualization from task system