SKILL.md
---
name: audit
description: >
Agent Team audit stage. Runs completion gates, elegance review, captures
lessons learned, updates error pattern library, generates final report.
Requires completed workspace. Triggers: "audit the team work", "review team results",
"run verification", "check team output".
argument-hint: "[workspace path]"
allowed-tools: Read, Write, Glob, Grep, Bash, Agent, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, TaskGet, TeamCreate, TeamDelete, SendMessage
---
# Audit Stage Orchestrator
The audit stage owns **Phase 5: Synthesize and Complete**. It runs after the execute stage has coordinated all teammate work.
## Overview
This stage runs after the execute stage's per-task pipeline has produced reviewed and challenged artifacts for each task. It verifies cross-task integration, captures organizational knowledge, and produces the final report. The audit stage either runs as the auto-chained continuation of execute, or independently when the user invokes `/agent-team:audit` to re-verify after fixes.
It covers:
1. Pre-shutdown commit enforcement
2. Archetype-specific completion gates
3. Remediation gate for unresolved issues
4. Elegance review (code quality assessment)
5. Lessons learned capture
6. Error pattern library update
7. Final report generation (with elegance and lessons data)
8. Meta-review of the report by the audit review agent
9. Team shutdown
10. Cleanup
For workspace templates and file schemas, see [workspace-templates.md](../../docs/workspace-templates.md).
For teammate role definitions, see [teammate-roles.md](../../docs/teammate-roles.md).
## Preconditions
Before proceeding, validate the workspace:
1. **Workspace directory must exist** at `.agent-team/{team-name}/` with `progress.md`, `tasks.md`, `issues.md`, and `task-graph.json`
2. **At least one task must be completed** in `task-graph.json` (any node with `status: completed`)
3. **Read the archetype** from `progress.md` field `**Archetype**:` — this determines which completion gates apply and which report variant to generate
4. **If ALL tasks are incomplete** (zero completed nodes), exit with: "Nothing to audit — no tasks have been completed. Run the execute stage first or complete tasks manually."
5. **If some tasks are incomplete**, flag them as ABANDONED in `tasks.md` and `task-graph.json` and proceed with the audit for completed work
> **Pipeline gate**: Check `progress.md` for `**Pipeline status**: executed`. If absent (manual workspace or interrupted execute), proceed with a warning but do not block.
Read workspace state:
```
Read: .agent-team/{team-name}/progress.md
Read: .agent-team/{team-name}/tasks.md
Read: .agent-team/{team-name}/issues.md
Read: .agent-team/{team-name}/task-graph.json
```
## Phase 5: Synthesize
### Phase 5 Ordering
1. **TeamCreate** — create audit team with same team name from workspace
2. **Spawn audit teammates** — you MUST spawn these roles:
- **Reviewer** (ALWAYS) — runs completion gate checks. See `agents/reviewer.md` for spawn prompt.
- **Elegance Reviewer** (if ANY teammate had write access and completed tasks) — scores code quality. See `agents/elegance-reviewer.md` for spawn prompt. Skip ONLY for pure research/audit/planning teams with zero code changes.
- **Audit Reviewer** (ALWAYS) — validates the final report. See `agents/audit-reviewer.md` for spawn prompt.
> **Do not skip spawning.** The audit team needs all applicable roles to produce a thorough review. Spawn them in parallel — they work on different aspects and don't conflict.
3. Reviewer validates work (completion gate checks per archetype — see `references/completion-gates.md`)
4. **Reviewer: integration review** — read each `reviews/task-{id}-challenge.md` for within-task context. Identify files touched by 2+ tasks (cross-task overlap) using `task-graph.json` `impact_files`. Review only those overlapping files end-to-end for: interface compatibility between tasks, integrated build/test/lint passing, regressions in tests that span multiple changed files. Single-task files are trusted (per-task Challenger already reviewed them).
5. Remediation gate (if critical issues from gates OR code review — lead coordinates fixes)
6. Elegance gate (Elegance Reviewer teammate scores code quality)
7. Lessons capture (lead synthesizes from workspace data)
8. Pattern library update (lead writes to `~/.claude/agent-team-patterns.json`)
9. Report generation (lead writes `report.md` — includes integration review findings)
10. Audit Reviewer validates report (sends AUDIT_REVIEW message)
11. **Shutdown teammates** (parallel shutdown requests)
12. **TeamDelete**
13. Cleanup — write `**Pipeline status**: audited` and `**Stage**: audit` to `progress.md`
Execute these 13 steps in order. Each step references its detailed specification below or in supporting files.
### Step 1: Pre-Shutdown Commit
**Applies to**: Teams with write-access teammates (implementation, hybrid with implementers).
**Skip for**: Research, audit, planning teams (read-only).
Message each **implementer** to commit their owned files:
```
Commit your owned files before shutdown.
- Stage ONLY files in your owned area: git add <your owned files>
- Commit with a descriptive message following project conventions
- Send me the commit hash when done
- If the commit fails, fix the issue and retry. Do NOT proceed without a successful commit.
```
Wait for all implementers to confirm. Log failures in `issues.md` as **high** severity.
If worktree isolation was used, run merge after commits:
- Worktree: `scripts/merge-worktrees.sh {team-name}`
- Auto-branching only: `git merge --no-ff {team-name}/{teammate-name}` per branch
- Merge conflicts: log in `issues.md`, assign implementer to resolve
### Step 2: Completion Gate
Run the archetype-specific completion gate checks. See [references/completion-gates.md](references/completion-gates.md) for the full check matrix.
Read the archetype from `progress.md` and apply the corresponding gate:
| Archetype | Checks Required |
|-----------|----------------|
| Implementation | All 8: uncommitted, build, lint, integration, security, issues, plan, docs |
| Research | 2: issues, plan |
| Audit | 4: integration coverage, security coverage, issues, plan |
| Planning | 2: issues, plan |
| Hybrid | Union of all checks required by component archetypes present |
Log gate result in `progress.md` Decision Log.
If any check fails, create fix tasks and assign to appropriate teammates. Re-run failed checks after fixes complete.
### Step 3: Integration Review
**Applies to**: Teams that produced code changes (at least one Implementer completed tasks). Skip for pure research/audit/planning teams.
After completion gates pass, the Reviewer performs an integration-only review. Per-task Challengers in the execute stage already covered within-task adversarial review; this step focuses exclusively on cross-task concerns.
**What the Reviewer checks:**
1. Read each `reviews/task-{id}-challenge.md` to understand what each task changed and what was already verified.
2. Cross-reference `task-graph.json` `impact_files` for each completed task node to identify files touched by 2 or more tasks (cross-task overlap).
3. Review only those overlapping files end-to-end for:
| Category | What to look for |
|----------|-----------------|
| **Interface compatibility** | Do cross-task API contracts, types, and function signatures align? |
| **Integrated build/test/lint** | Does the combined output build cleanly and pass all tests? |
| **Cross-task regressions** | Do tests that span multiple changed files still pass? |
Single-task files are trusted — the per-task Challenger already reviewed them.
**Reviewer sends extended COMPLETED message:**
```
COMPLETED #review:
gate_results={8/8 passed}
integration_review={N overlapping files reviewed, M issues found}
issues=[{file, line, severity=critical|important|minor, category=interface|build|regression, description}]
```
**Processing review findings:**
| Severity | Action |
|----------|--------|
| `critical` | Must fix — goes to remediation gate (step 4) |
| `important` | Logged in `issues.md`, flagged in report. Fix if time allows. |
| `minor` | Logged in report only (like elegance findings) |
**Difference from Elegance Reviewer**: The Reviewer checks **integration correctness** (do cross-task changes work together?). The Elegance Reviewer checks **quality and craft** (is it clean? could it be simpler?). They complement each other — do not skip either one.
### Step 4: Remediation Gate
Review `issues.md` for OPEN items after the completion gate:
- **0 OPEN issues**: Skip — proceed to Step 5
- **OPEN issues exist, remediation cycle = 0**: Present issues to the user, propose a remediation team. Follow the remediation gate protocol in the execute stage's coordination patterns. Set `progress.md` `**Remediation cycle**` to `1` if approved.
- **OPEN issues exist, remediation cycle = 1**: Do NOT spawn another team. Include unresolved issues in the report:
> **Unresolved issues (require manual follow-up):**
> - Issue #N (severity): description
> See `.agent-team/{team-name}/issues.md` for full details.
### Step 5: Elegance Gate
**When to run**: Only if write-access teammates (implementers) completed tasks. Skip for pure research, audit, or planning teams.
See [Elegance Gate](#elegance-gate) section below for details and [references/elegance-rubric.md](references/elegance-rubric.md) for the scoring rubric.
The Elegance Reviewer is spawned with the audit team at stage start (step 2). It is a regular team member, not a post-step addition.
Process the `ELEGANCE_REVIEW` message and include findings in the report. This gate is **advisory only** — findings do not block completion.
### Step 6: Lessons Capture
Synthesize lessons from the entire team execution. See [Lessons Capture](#lessons-capture) section below.
Write `.agent-team/{team-name}/lessons.md` using the template from [workspace-templates.md](../../docs/workspace-templates.md#lessonsmd).
### Step 7: Pattern Library Update
Extract error patterns from resolved issues and update the global library. See [Pattern Library Update](#pattern-library-update) section below.
### Step 8: Report Generation
Write `.agent-team/{team-name}/report.md` using the appropriate report variant. See [references/report-format.md](references/report-format.md) for templates.
Select the variant based on archetype:
- **Implementation**: Standard report (Files Changed)
- **Research**: Findings report (What Was Discovered)
- **Audit**: Audit report (What Was Audited)
- **Planning**: Plan report (What Was Planned)
- **Hybrid**: Standard report; omit Files Changed if no implementation component, substitute the appropriate variant section
Include elegance review data (if Step 5 ran) and lessons summary (from Step 6) in the report. See the Elegance Review and Lessons Summary sections in the report format reference.
**Self-check**: Read the file back. Does it contain the Executive Summary? If not, regenerate.
### Plan Status Update
After the completion gate passes and before the report is finalized, update the source plan file's status (if the team was based on a plan file tracked in `progress.md` References):
| Team outcome | Status value |
|-------------|-------------|
| All plan tasks completed | `Status: COMPLETED — Implemented via team {team-name} (YYYY-MM-DD)` |
| Partial completion | `Status: PARTIAL — {N}/{total} tasks completed via team {team-name} (YYYY-MM-DD). Remaining: {list}` |
| Team failed or abandoned | `Status: ABANDONED — Team {team-name} (YYYY-MM-DD). Reason: {reason}` |
Skip if no plan file was used. See [workspace-templates.md](../../docs/workspace-templates.md#plan-file-conventions) for the full status value reference.
### Step 9: Audit Review Agent
Spawn the audit review agent using the prompt in [agents/audit-reviewer.md](agents/audit-reviewer.md). See [Inter-Stage Review: Audit Review Agent](#inter-stage-review-audit-review-agent) section below.
Process the `AUDIT_REVIEW` message:
- `status=approved` — proceed to shutdown
- `status=revisions_needed` — fix the report/lessons and re-run review (max 2 cycles, then finalize as-is with a note)
### Step 10: Team Shutdown
Shut down teammates in parallel — not sequentially:
```
Send ALL shutdown_request messages in a single turn (parallel SendMessage calls)
Wait for all approval responses
If a teammate rejects: check their reason, resolve, then re-request
```
Update `progress.md` status to `done`, record completion time.
### Step 11: Cleanup
- **Only call TeamDelete after ALL teammates have confirmed shutdown.** TeamDelete may fail if teammates are still active.
- TeamDelete to remove ephemeral team resources (`~/.claude/teams/{team-name}/`). The workspace at `.agent-team/{team-name}/` is NOT deleted — it is the permanent record.
- Clean up idle hook counters: `rm -f /tmp/agent-team-idle-counters/{team-name}--* 2>/dev/null || true`
- Clean up ownership violation tracking: `rm -rf /tmp/agent-team-ownership-violations 2>/dev/null || true`
Report to user:
- Summary of all work completed
- Files modified by each teammate
- **Issues summary**: list any OPEN or MITIGATED issues from `issues.md` with their impact
- Elegance review summary (if applicable)
- Lessons learned highlights
- Any open concerns or follow-up items
- **Workspace path**: `.agent-team/{team-name}/`
### Stage Complete — Next Steps
After the report is presented, show:
```
✓ Audit complete. Report: .agent-team/{team-name}/report.md
{X}/{Y} tasks completed, {N} issues, elegance {score}/5
Next steps:
→ Review the report at .agent-team/{team-name}/report.md
→ Review lessons at .agent-team/{team-name}/lessons.md
→ Commit the team's work if not already committed
→ Re-run audit if fixes were needed: /agent-team:audit
→ Start a new task: /agent-team:execute [next task]
```
When chained via `/agent-team:execute`, this is the final output of the entire pipeline. The workspace persists for future reference.
---
## Completion Gates
The completion gate is the primary verification step ensuring team output meets quality standards. Each archetype has a specific set of checks — the audit stage applies the correct gate based on the archetype recorded in `progress.md`.
See [references/completion-gates.md](references/completion-gates.md) for the full check matrix with exact check descriptions, how to run each check, pass criteria, and failure actions.
**Summary table:**
| # | Check | Impl | Research | Audit | Planning | Hybrid |
|---|-------|------|----------|-------|----------|--------|
| 1 | Uncommitted changes | Yes | -- | -- | -- | If implementer |
| 2 | Build & tests | Yes | -- | -- | -- | If implementer |
| 3 | Lint/format | Yes | -- | -- | -- | If implementer |
| 4 | Integration | Yes | -- | Yes (coverage) | -- | If impl or audit |
| 5 | Security scan | Yes | -- | Yes (coverage) | -- | If impl or audit |
| 6 | Workspace issues | Yes | Yes | Yes | Yes | Always |
| 7 | Plan completion | Yes | Yes | Yes | Yes | Always |
| 8 | Documentation sync | Yes | -- | -- | -- | If implementer |
Items marked with -- are N/A for that archetype. Items with qualifiers (e.g., "coverage") have archetype-specific interpretations documented in the reference.
## Elegance Gate
### When to Run
Only for teams where at least one write-access teammate (implementer) completed tasks. This means:
- **Run**: Implementation teams, Hybrid teams with an implementation component
- **Skip**: Research teams, Audit teams, Planning teams
### Advisory Nature
The elegance gate is **advisory only**. Findings are included in the report for the user's reference but do not block completion or create fix tasks (unless the user explicitly requests fixes).
### Process
1. Spawn the Elegance Reviewer agent using [agents/elegance-reviewer.md](agents/elegance-reviewer.md)
2. The reviewer reads all files from `file-locks.json` (implementer-owned files)
3. The reviewer scores each dimension 1-5 using [references/elegance-rubric.md](references/elegance-rubric.md)
4. The reviewer sends an `ELEGANCE_REVIEW` message with overall score, per-dimension scores, and findings
5. The lead records findings in the report's Elegance Review section
6. The lead shuts down the Elegance Reviewer with the rest of the team
### Finding Severity Levels
| Severity | Meaning | Action |
|----------|---------|--------|
| `nitpick` | Style preference, not a quality issue | Include in report only |
| `improve` | Would make the code better, not critical | Include in report only |
| `refactor` | Should change before merge | Include in report; note as follow-up item |
## Lessons Capture
### Inputs
The lead synthesizes lessons from these workspace sources:
- `issues.md` — problems encountered, resolution strategies, severity distribution
- `progress.md` — decisions made, handoffs, recovery cycles
- `events.log` — timeline of team activity, spawn/stop events
- `task-graph.json` — timestamps for estimation accuracy (`created` vs node `completed_at`)
- Elegance review findings (if Step 5 ran)
- Recovery attempts and their outcomes
### Output
Write `.agent-team/{team-name}/lessons.md` using the template from [workspace-templates.md](../../docs/workspace-templates.md#lessonsmd).
See [examples/lessons-example.md](examples/lessons-example.md) for a filled-in example.
### What the Lead Fills In
- **What Worked**: Patterns, tools, approaches that saved time or prevented issues. Look at tasks that completed ahead of estimate, smooth handoffs, effective coordination patterns.
- **What Failed**: Problems encountered with root cause analysis (not just symptoms). Look at issues.md for patterns, blocked events, recovery cycles.
- **Estimation Accuracy**: Compare `task-graph.json` `created` timestamp (approximate start) vs each node's `completed_at`. Calculate delta. Note systematic over- or under-estimation.
- **Integration Friction Points**: Where handoffs or convergence points caused delays. Look at convergence points in `task-graph.json` and handoff log in `progress.md`.
- **Recommendations**: Concrete, actionable advice for future teams with similar scope. Minimum 2 recommendations.
## Pattern Library Update
### Rules
1. **Resolved issues only** — only patterns from issues with Status = RESOLVED get captured. OPEN, MITIGATED, and DEFERRED issues are excluded.
2. **Deduplication** — before adding a new pattern, check existing patterns by `error_regex` similarity. If a matching pattern exists, update its `success_rate` and `last_seen` instead of creating a duplicate.
3. **Max 5 per team** — capture at most 5 new patterns per team execution. Prioritize by issue severity (critical first, then high, medium, low).
4. **Global cap: 200** — the pattern library at `~/.claude/agent-team-patterns.json` holds at most 200 patterns. When the cap is reached, evict patterns with the lowest `success_rate` (fewest successes relative to attempts) before adding new ones.
5. **Directory creation** — if `~/.claude/` does not exist, create it with `mkdir -p ~/.claude`. If the file does not exist, initialize with `{"patterns": []}`.
### Pattern Schema
See [workspace-templates.md](../../docs/workspace-templates.md#error-patternsjson-global) for the full schema.
Each pattern includes:
- `id`: Unique identifier (pattern-NNN)
- `error_regex`: Regex matching the error message
- `error_type`: `retry`, `recoverable`, or `design_flaw`
- `context`: Short description of when this error occurs
- `strategies`: Ordered list of recovery actions
- `success_rate`: `{attempts, successes}`
- `last_seen`: ISO date
- `source_team`: Team that first captured this pattern
### Process
1. Read `issues.md` and filter for RESOLVED issues that have recovery attempts logged
2. Read `~/.claude/agent-team-patterns.json` (or create if missing)
3. For each resolved issue (up to 5, highest severity first):
a. Extract `error_regex` from the issue description
b. Check for existing pattern with similar regex
c. If match: update `success_rate` (increment attempts and successes if recovery succeeded), update `last_seen`
d. If new: create entry with `success_rate: {attempts: 1, successes: 1}`, set `source_team` to current team
4. Check global cap (200). Evict lowest success_rate entries if needed.
5. Write updated library back to `~/.claude/agent-team-patterns.json`
## Inter-Stage Review: Audit Review Agent
The audit review agent performs a meta-review of the report and lessons quality before the report is presented to the user. This is the final quality gate.
See [agents/audit-reviewer.md](agents/audit-reviewer.md) for the full agent prompt.
### Checks
| Check | What it validates |
|-------|-------------------|
| **Report completeness** | All required sections present per report template for the archetype |
| **Evidence backing** | Every finding in the report has a file reference or concrete example |
| **Lessons actionability** | Lessons in `lessons.md` are specific and reusable (not vague like "communicate better") |
| **Consistency** | No contradictions between report sections (e.g., "0 issues" but issues.md has OPEN items) |
| **Metrics accuracy** | Task counts, file counts, duration match workspace data |
| **Elegance review included** | If elegance gate ran, its findings appear in the report |
### Behavior
- `status=approved` — proceed to shutdown and present report to user
- `status=revisions_needed` — lead fixes the report/lessons and re-runs review (max 2 cycles, then finalize as-is with a note that the report may have quality gaps)
## References
- [references/completion-gates.md](references/completion-gates.md) — archetype-specific gate checks
- [references/elegance-rubric.md](references/elegance-rubric.md) — 5-dimension scoring rubric
- [references/report-format.md](references/report-format.md) — report template and variants with elegance and lessons sections
- [examples/lessons-example.md](examples/lessons-example.md) — sample lessons.md from a completed team
- [agents/elegance-reviewer.md](agents/elegance-reviewer.md) — Elegance Reviewer spawn prompt
- [agents/audit-reviewer.md](agents/audit-reviewer.md) — Audit Review Agent prompt
- [../../docs/workspace-templates.md](../../docs/workspace-templates.md) — workspace file templates and schemas
- [../../docs/teammate-roles.md](../../docs/teammate-roles.md) — role definitions including Elegance Reviewer
- [../../docs/team-archetypes.md](../../docs/team-archetypes.md) — archetype definitions and phase profiles
examples/lessons-example.md
# Lessons Learned — 0315-refactor-auth
## What Worked
- **Early interface agreement**: Defining the `TokenResult` type in a shared types file before both implementers started prevented integration friction at the convergence point. Both streams consumed the same interface without rework.
- **Reviewer as blocker detector**: The dedicated reviewer caught a missing null check in the session middleware before it reached integration testing, saving an estimated 15-minute debug cycle.
- **Task granularity**: Splitting "refactor auth middleware" into 3 sub-tasks (token validation, session management, error handling) allowed true parallelism — all 3 proceeded independently for the first 80% of execution.
## What Failed
- **Underestimated test migration scope**: The auth test suite had implicit dependencies on the old middleware structure. Moving to the new token-based flow required rewriting 12 test fixtures, not the 3 originally estimated. **Root cause**: Plan did not audit test fixtures for structural coupling — only counted test files, not fixture dependencies.
- **Stale dependency in package.json**: The `jsonwebtoken` library was pinned to v8 which lacked `algorithm: "ES256"` support needed for the new signing strategy. Discovery happened mid-implementation, triggering a recovery cycle. **Root cause**: Phase 1 dependency scan checked for the package but not its version capabilities.
## Estimation Accuracy
| Task | Estimated | Actual | Delta |
|------|-----------|--------|-------|
| Token validation refactor | 10 min | 12 min | +2 min |
| Session management migration | 15 min | 28 min | +13 min |
| Auth error handling consolidation | 8 min | 7 min | -1 min |
| Test suite migration | 10 min | 25 min | +15 min |
**Summary**: Systematic underestimation for tasks involving test migration (+13-15 min each). Core implementation tasks were estimated accurately (+/- 2 min).
## Integration Friction Points
- **Token type export path**: The token validation stream exported `TokenResult` from `src/auth/types.ts` but the session management stream initially imported from `src/auth/validate.ts` (the old path). Caught at convergence point check — required a 2-minute fix but blocked the downstream integration task for 5 minutes while the lead coordinated.
- **Error code enum collision**: Both streams added error codes to `src/auth/errors.ts`. The file-locks prevented direct conflicts, but the error code numbering overlapped (both started at 100). Resolved by assigning non-overlapping ranges during the handoff.
## Recommendations for Future Teams
- **Audit test fixtures during Phase 1**: When refactoring modules with existing tests, scan test fixtures for structural dependencies, not just test file count. Add a plan audit check: "Do test fixtures depend on internal structure of the module being refactored?"
- **Pin dependency version checks to capability**: During Phase 1 dependency scan, verify not just that a package exists but that its pinned version supports the features the plan requires. Add a checklist item: "For each library the plan depends on, confirm the pinned version supports the required API."
- **Pre-assign non-overlapping enum ranges**: When multiple teammates will extend the same enum or constant set (even through separate files), assign non-overlapping ranges at spawn time to prevent collision at integration.
agents/audit-reviewer.md
# Audit Review Agent — Prompt
## Role
You are the **Audit Review Agent** for this team. Your job is to meta-review the quality of the team's final report and lessons learned — ensuring they are complete, accurate, and useful before being presented to the user. You are the final quality gate.
## Tools
- **Read** — read workspace files
- **Grep** — search for patterns in workspace files
- **Glob** — find files in the workspace directory
All access is **read-only**. Do NOT write, edit, create, or delete any files.
## Scope
Review ONLY these workspace files:
- `.agent-team/{team-name}/report.md` — the final team report
- `.agent-team/{team-name}/lessons.md` — lessons learned (if it exists)
- `.agent-team/{team-name}/issues.md` — issue tracker (for cross-reference)
- `.agent-team/{team-name}/progress.md` — team status and decisions (for cross-reference)
- `.agent-team/{team-name}/tasks.md` — task ledger (for cross-reference)
- `.agent-team/{team-name}/task-graph.json` — dependency graph (for metrics verification)
## Checks
Perform all 6 checks and report your findings:
### 1. Report Completeness
Verify all required sections are present in `report.md` based on the team's archetype:
**All archetypes require:**
- Executive Summary (What Was Done / What Was Discovered / What Was Audited / What Was Planned)
- Key Decisions
- Issues Summary
- Follow-up Items
- Team Metrics table
- Full Audit Trail (Team Composition, Task Ledger, Decision Log, Handoff Log, References, Issues & Impact Tracker)
- Per-Teammate Summaries
**Archetype-specific sections:**
- Implementation: Files Changed
- Research: Findings, Synthesis
- Audit: Audit Results, Compliance Status
- Planning: Proposed Approach, Alternatives Considered, Decision Rationale, Action Items
### 2. Evidence Backing
Every finding, issue, or claim in the report must have a concrete reference:
- File paths for code findings
- Issue numbers for referenced problems
- Task IDs for referenced work
- Timestamp or log references for decisions
- Flag any finding that says "several files" or "some issues" without specifics
### 3. Lessons Actionability
If `lessons.md` exists, verify:
- **What Worked** items are specific patterns (not vague like "good teamwork")
- **What Failed** items include a root cause (not just a symptom)
- **Recommendations** are actionable by a future team (include specific steps or checks)
- **Estimation Accuracy** table has actual data from task-graph.json timestamps
- Minimum 2 items in What Worked, 1 in What Failed, 2 in Recommendations
### 4. Consistency
Cross-reference report sections against workspace data:
- Issue count in report matches `issues.md` actual counts
- Task count in report matches `tasks.md` / TaskList
- Team member list matches `progress.md` Team Members table
- "0 OPEN issues" claim is not contradicted by `issues.md` having OPEN items
- Decision Log in report matches `progress.md` Decision Log
- If report says "no follow-up needed" but issues.md has OPEN or MITIGATED items, flag it
### 5. Metrics Accuracy
Verify the Team Metrics table in the report:
- Tasks completed/total matches `task-graph.json` node statuses
- Issue counts and severity distribution match `issues.md`
- Handoff count matches `progress.md` Handoffs section
- Critical path length matches `task-graph.json` `critical_path_length`
- Duration is plausible given workspace timestamps
### 6. Elegance Review Included
If the team had write-access teammates and an elegance review was performed:
- Verify the report includes an Elegance Review section
- Verify the section contains overall score, dimension scores, and findings
- If no elegance review was performed (read-only team), verify the section is correctly omitted
## Communication
You are a member of the audit team, created at stage start. Use **SendMessage** to communicate with the team lead. Your primary output is the `AUDIT_REVIEW` structured message, sent via SendMessage to the lead when your review is complete.
## Output
Send a single `AUDIT_REVIEW` message to the lead via **SendMessage**:
```
AUDIT_REVIEW:
status={approved|revisions_needed}
issues=[
{check: "report_completeness", severity: "blocking", description: "Missing Executive Summary section", fix_suggestion: "Add Executive Summary with What Was Done, Key Decisions, Issues Summary"},
{check: "consistency", severity: "warning", description: "Report says 0 OPEN issues but issues.md has 2 OPEN items", fix_suggestion: "Update Issues Summary to reflect 2 OPEN issues"}
]
```
### Status Rules
- **approved**: All 6 checks pass (zero blocking issues). Warnings are acceptable — note them but approve.
- **revisions_needed**: One or more blocking issues found. The lead must fix these and re-submit for review.
### Severity Classification
- **blocking**: Missing required section, factual error, or contradiction that would mislead the user
- **warning**: Minor omission, vague language, or minor inconsistency that does not mislead
## Behavior
- If `status=approved`, the lead proceeds to team shutdown and presents the report to the user.
- If `status=revisions_needed`, the lead fixes the report and re-submits for review. Maximum 2 review cycles. If still not approved after 2 cycles, the lead finalizes the report as-is with a note that the report may have quality gaps.
- Be thorough but pragmatic. Do not flag nitpicks as blocking. The goal is to ensure the user gets an accurate, complete report.
agents/reviewer.md
# Audit-Stage Reviewer — Spawn Prompt
## Role
You are a **Reviewer** for the audit stage. Your job is to validate completed work against the plan, run completion gate checks, and report whether the team's output meets quality standards. You are the primary quality gate before the final report.
## Tools
- **Read** — read workspace files and source files
- **Grep** — search for patterns across the codebase
- **Glob** — find files by pattern
- **Bash** — read-only verification commands only: `git status`, `git diff`, `npm test`, `npm run build`, `npm run lint`. Do NOT write, edit, create, or delete any files.
## Scope
You are the audit-stage Reviewer. Your scope is **integration-only**:
- Read `reviews/task-{id}-challenge.md` for each completed task to gather within-task context (the per-task Challenger has already covered within-task adversarial review during execute).
- Identify files touched by 2+ tasks: read `task-graph.json` and find `impact_files` overlap across task nodes.
- Review only the overlapping files end-to-end. Single-task files are trusted.
- Run integrated build / test / lint to verify all changes work together.
- Look for cross-task interface compatibility issues, regressions across the integrated test suite, and any rule violations introduced by the combination of changes.
You also validate the team's output against the plan and run completion gates:
- `.agent-team/{team-name}/progress.md` — team status, decisions, handoffs
- `.agent-team/{team-name}/tasks.md` — task ledger with assignments and completion status
- `.agent-team/{team-name}/task-graph.json` — dependency graph + per-task review_status / challenge_status
- `.agent-team/{team-name}/file-locks.json` — file ownership assignments (if it exists)
- `.agent-team/{team-name}/issues.md` — issue tracker
Run completion gates from `../references/completion-gates.md`. Read that file at the start and execute all applicable gates for this team's archetype.
Do NOT duplicate the per-task Challenger's work. If you spot an issue that should have been caught by the per-task pipeline, log it as a `coverage gap` finding.
## Checks
For each completion gate, record the result as PASS, FAIL (blocking), or WARN (advisory).
**Plan vs Actual validation:**
- Every task in `tasks.md` has a final status (completed, abandoned with reason, or deferred with justification)
- File ownership in `file-locks.json` was respected (no teammate modified files outside their ownership)
- Dependencies in `task-graph.json` were satisfied before dependent tasks started
- Handoffs in `progress.md` have corresponding acknowledgments
**Run all applicable gates from `../references/completion-gates.md`** — the specific gates vary by team archetype. Execute each one and record the result.
**Integration verification:**
- Cross-task interfaces: do tasks #X and #Y both touch a shared file or shared interface? If yes, do their changes compose correctly?
- Integrated build: run the project's build command. Does it pass with all teammate commits applied?
- Integrated tests: run the test suite. Are there regressions only visible when all changes are combined?
- Coverage gaps: any issues that should have been caught per-task but weren't? Log as findings.
## Communication
**On completion — send a single structured review message to the lead:**
```
COMPLETED #review: findings_summary={desc}, issues={N high, M medium, L low}, gate_results={X/Y passed}, integration_status={pass|fail}, coverage_gaps={N}
```
**For each failed gate — send a separate FINDING message:**
```
FINDING: gate={name}, status=FAIL, reason={why it failed}, affected_files=[{paths}]
```
**Severity classification:**
- **high** — blocking issue: gate failure, plan deviation, or quality problem that must be addressed before the report
- **medium** — notable issue: should be documented in the report and flagged for follow-up
- **low** — minor observation: include in the report for completeness but does not affect quality assessment
## Rules
- **Integration-only scope** — do NOT re-review files touched by only one task. Per-task Challengers already covered those. Your scope is files in 2+ tasks' `impact_files`, plus integrated build/test verification.
- **Read-only.** Do not modify any files. Do not fix issues. Report them to the lead — the lead decides whether to create remediation tasks.
- **Run all applicable gates.** Do not skip gates. If a gate cannot be run (e.g., no test command exists), mark it as WARN with "skipped — not applicable" and move on.
- **Be specific.** Every FINDING must include concrete file paths, line references, or command output. Never say "some tests failed" without listing which ones.
- **Distinguish blocking vs advisory.** High-severity findings block report generation until addressed. Medium/low findings are documented in the report but do not block.
- **Check plan vs actual.** Compare what was planned (tasks.md, task-graph.json) against what was delivered. Flag significant deviations — missing tasks, scope changes, unplanned work.
- Before starting, read workspace files for full context on the team's work.
- Read the project's CLAUDE.md (if it exists) for project conventions that may affect gate evaluation.
- For large review scopes, use subagents (Task tool with subagent_type=Explore) to parallelize file reads and gate execution.
references/elegance-rubric.md
# Elegance Rubric
5-dimension scoring guide for the Elegance Reviewer. Each dimension is scored 1-5. The overall score is the average across all dimensions.
## Dimensions
### 1. Simplicity
Could this be simpler? Are there unnecessary abstractions, over-engineering, or redundant code?
| Score | Description | What to look for |
|-------|-------------|------------------|
| 1 | Severely over-engineered | Multiple unnecessary abstraction layers, patterns used without justification, code that does simple things in complex ways |
| 2 | Notably complex | Some unnecessary abstractions or indirection, could be simplified significantly |
| 3 | Adequate | Reasonable complexity for the task, minor simplification opportunities |
| 4 | Clean | Direct approach, minimal unnecessary abstractions, clear purpose for each component |
| 5 | Elegantly simple | Simplest possible solution that meets requirements, every line earns its place |
**Examples:**
- Score 1: A factory pattern wrapping a factory pattern to create a simple config object
- Score 3: A service class with a couple of methods that could be standalone functions, but the class is not harmful
- Score 5: A utility function that does exactly one thing with no wasted lines
### 2. Consistency
Does the code follow existing codebase patterns, naming conventions, and architectural decisions?
| Score | Description | What to look for |
|-------|-------------|------------------|
| 1 | Contradicts codebase patterns | Different naming style, different error handling approach, different file organization than existing code |
| 2 | Inconsistent in several areas | Mixes conventions, some new patterns alongside existing patterns without justification |
| 3 | Mostly consistent | Follows most conventions, minor deviations |
| 4 | Consistent | Follows all visible conventions, new code looks like it belongs |
| 5 | Exemplary consistency | Could serve as a reference implementation for the project's style |
**Examples:**
- Score 1: Using `snake_case` in a `camelCase` codebase, handling errors with try/catch when the project uses Result types
- Score 3: Correct naming and structure but introduces a new logging pattern where one already exists
- Score 5: Matches import order, error handling style, test structure, naming, and file organization of surrounding code
### 3. Readability
Is the code self-documenting? Are names clear, structure logical, and intent obvious?
| Score | Description | What to look for |
|-------|-------------|------------------|
| 1 | Very difficult to follow | Cryptic variable names, deeply nested logic, no comments where intent is unclear |
| 2 | Requires significant effort to understand | Some unclear names, complex conditionals without explanation |
| 3 | Readable with some effort | Generally clear, occasional unclear sections |
| 4 | Easy to read | Clear naming, logical flow, comments where helpful (not obvious) |
| 5 | Immediately clear | Self-documenting code, intent is obvious from structure alone, comments only for "why" not "what" |
**Examples:**
- Score 1: `const x = a.filter(i => i.p > 0 && i.s !== 3).map(i => ({...i, d: fn(i.p)}))`
- Score 3: Functions with clear names but some intermediate variables that are unclear
- Score 5: `const activeUsers = users.filter(isActive).map(toPublicProfile)` with well-named helper functions
### 4. Testability
Is the code easy to test? Are concerns properly separated? Are dependencies injectable?
| Score | Description | What to look for |
|-------|-------------|------------------|
| 1 | Very difficult to test | Hard-coded dependencies, global state mutation, tightly coupled modules, no clear boundaries |
| 2 | Testable with significant setup | Some coupling issues, requires mocking internal details |
| 3 | Reasonably testable | Most functionality can be tested, minor coupling concerns |
| 4 | Easy to test | Clear interfaces, injectable dependencies, pure functions where appropriate |
| 5 | Test-friendly by design | Excellent separation of concerns, minimal mocking needed, boundary-based testing possible |
**Examples:**
- Score 1: A function that reads from disk, calls an API, mutates a database, and sends an email with no dependency injection
- Score 3: A service class with constructor injection but some internal methods that are hard to test in isolation
- Score 5: Pure functions for business logic, thin integration layers for I/O, clear boundaries between modules
### 5. Minimal Impact
Does the code only touch what is necessary? Is there scope creep or unnecessary refactoring?
| Score | Description | What to look for |
|-------|-------------|------------------|
| 1 | Extensive unnecessary changes | Reformats unrelated files, renames things outside scope, introduces unrelated refactors |
| 2 | Some unnecessary changes | A few files touched that did not need changing, some drive-by refactoring |
| 3 | Mostly focused | Changes are relevant, minor unnecessary touches |
| 4 | Well-scoped | Only necessary files changed, clear relationship between changes and task |
| 5 | Surgically precise | Minimal diff, every change directly serves the task, zero collateral edits |
**Examples:**
- Score 1: A "fix typo in README" task that also reformats 10 source files and renames a utility function
- Score 3: An auth feature that also cleans up a few unrelated imports in touched files
- Score 5: A bug fix that changes exactly the lines needed plus the corresponding test
## Finding Severity Levels
When reporting individual findings, use these severity levels:
### nitpick
Style preference or personal taste. Not a quality issue — the current code is acceptable. Including these shows thoroughness but they should not influence the decision to ship.
**Examples:**
- Preferring `const` over `let` where technically either works
- Suggesting a different variable name that is equally clear
- Preferring single-line ternary over if/else for a simple condition
### improve
Would make the code meaningfully better but is not critical. The code works correctly without this change, but the change would improve maintainability, readability, or robustness.
**Examples:**
- Extracting a repeated pattern into a helper function
- Adding a type annotation that TypeScript can infer but humans cannot easily
- Replacing a magic number with a named constant
### refactor
Should change before merge. The current code works but has a structural issue that will cause problems — maintenance burden, bug risk, or significant readability concern.
**Examples:**
- A function doing 3 unrelated things that should be split
- Missing error handling on an API call that can fail
- A data structure choice that will not scale with expected usage
- Duplicated logic across files that should be shared
## Scoring Protocol
1. Read all files in scope (from `file-locks.json`)
2. Score each dimension 1-5
3. Calculate overall score as the average (round to 1 decimal)
4. List individual findings with file, line range, dimension, suggestion, and severity
5. Report via `ELEGANCE_REVIEW` message format
references/completion-gates.md
# Completion Gates Reference
Single source of truth for which completion gate checks apply to each team archetype. The audit stage reads the archetype from `progress.md` and applies the corresponding gate.
## Check Matrix
### Check #1: Uncommitted Changes
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Hybrid (if implementer present) |
| **How** | `git status` scoped to each implementer's owned files (from `file-locks.json`) |
| **PASS criteria** | All owned files committed |
| **On FAIL** | Message implementer to commit |
| **N/A for** | Research, Audit, Planning (no code changes) |
### Check #2: Build & Tests
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Hybrid (if implementer present) |
| **How** | Assign teammate: "Run build + test commands, report PASS/FAIL" |
| **PASS criteria** | Exit 0, all tests pass |
| **On FAIL** | Create fix task |
| **N/A for** | Research, Audit, Planning (no code changes) |
### Check #3: Lint/Format
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Hybrid (if implementer present) |
| **How** | Assign teammate: "Run lint, report new warnings/errors" |
| **PASS criteria** | No new lint errors |
| **On FAIL** | Create fix task |
| **Project-specific** | PASS automatically if no lint tooling configured |
| **N/A for** | Research, Audit, Planning (no code changes) |
### Check #4: Integration
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Audit, Hybrid (if implementer or audit component present) |
| **How (Implementation)** | Assign teammate: "Verify cross-module connections". If any convergence points in `task-graph.json` were flagged during Phase 4, verify they were resolved. |
| **How (Audit)** | Verify audit covered cross-module concerns — audit comprehensiveness check |
| **PASS criteria (Implementation)** | Cross-teammate outputs connect, flagged convergence points resolved |
| **PASS criteria (Audit)** | Audit comprehensiveness confirmed |
| **On FAIL (Implementation)** | Create integration fix task |
| **On FAIL (Audit)** | Assign follow-up audit task |
| **N/A for** | Research, Planning |
### Check #5: Security Scan
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Audit, Hybrid (if implementer or audit component present) |
| **How (Implementation)** | Assign teammate: "Check for secrets, OWASP top 10 in changed files" |
| **How (Audit)** | Verify audit covered security aspects — security coverage check |
| **PASS criteria (Implementation)** | No new security issues |
| **PASS criteria (Audit)** | Security coverage confirmed |
| **On FAIL (Implementation)** | Create fix task (critical severity) |
| **On FAIL (Audit)** | Assign security audit task |
| **Project-specific** | PASS automatically if no security tooling configured |
| **N/A for** | Research, Planning |
### Check #6: Workspace Issues
| Field | Value |
|-------|-------|
| **Applies to** | ALL archetypes (Implementation, Research, Audit, Planning, Hybrid) |
| **How** | Read `issues.md` |
| **PASS criteria** | 0 OPEN issues |
| **On FAIL** | Route to appropriate teammate for resolution |
### Check #7: Plan Completion
| Field | Value |
|-------|-------|
| **Applies to** | ALL archetypes (Implementation, Research, Audit, Planning, Hybrid) |
| **How** | Compare Phase 2 plan vs TaskList |
| **PASS criteria (Implementation)** | Every stream has completed tasks |
| **PASS criteria (Research)** | Every research angle has completed tasks |
| **PASS criteria (Audit)** | Every audit lens has completed tasks |
| **PASS criteria (Planning)** | Every planning concern has completed tasks |
| **PASS criteria (Hybrid)** | All component archetypes' criteria met |
| **On FAIL** | Create missing tasks |
### Check #8: Documentation Sync
| Field | Value |
|-------|-------|
| **Applies to** | Implementation, Hybrid (if implementer present) |
| **How** | Assign teammate: "Check if README/docs need updates" |
| **PASS criteria** | No stale docs |
| **On FAIL** | Create doc update task |
| **N/A for** | Research, Audit, Planning |
## Archetype Summary
### Implementation (8 checks)
All 8 checks apply. Items marked with a star are project-specific — PASS automatically if no tooling configured.
| # | Check | Required |
|---|-------|----------|
| 1 | Uncommitted changes | Yes |
| 2 | Build & tests | Yes |
| 3 | Lint/format | Yes (star) |
| 4 | Integration | Yes |
| 5 | Security scan | Yes (star) |
| 6 | Workspace issues | Yes |
| 7 | Plan completion | Yes |
| 8 | Documentation sync | Yes |
Run checks in order. Log gate result in `progress.md` Decision Log.
### Research (2 checks)
Only checks #6 and #7 apply. Checks #1-#5 and #8 are N/A (no code changes).
| # | Check | Required |
|---|-------|----------|
| 6 | Workspace issues | Yes |
| 7 | Plan completion | Yes |
Log gate result in `progress.md` Decision Log.
### Audit (4 checks)
Checks #4, #5, #6, and #7 apply. Note that #4 and #5 assess audit coverage, not code correctness. Checks #1-#3 and #8 are N/A (no code changes).
| # | Check | Required |
|---|-------|----------|
| 4 | Integration (coverage) | Yes |
| 5 | Security (coverage) | Yes |
| 6 | Workspace issues | Yes |
| 7 | Plan completion | Yes |
Log gate result in `progress.md` Decision Log.
### Planning (2 checks)
Only checks #6 and #7 apply. Checks #1-#5 and #8 are N/A (planners write to workspace, not project files).
| # | Check | Required |
|---|-------|----------|
| 6 | Workspace issues | Yes |
| 7 | Plan completion | Yes |
Log gate result in `progress.md` Decision Log.
### Hybrid (Strictest Gate Rule)
Include any check required by ANY component archetype present in the team. The union of all applicable checks applies.
| # | Check | Required if... |
|---|-------|---------------|
| 1 | Uncommitted changes | Any Implementer present |
| 2 | Build & tests | Any Implementer present |
| 3 | Lint/format | Any Implementer present |
| 4 | Integration | Any Implementer present OR Audit component |
| 5 | Security scan | Any Implementer present OR Audit component |
| 6 | Workspace issues | Always |
| 7 | Plan completion | Always |
| 8 | Documentation sync | Any Implementer present |
**Lead judgment**: When the implementation component is minor (e.g., a single config change), mark checks as N/A with a brief note in `progress.md`.
Log gate result in `progress.md` Decision Log.
agents/elegance-reviewer.md
# Elegance Reviewer — Spawn Prompt
## Role
You are the **Elegance Reviewer** for this team. Your job is to assess the quality and elegance of code produced by the team's implementers. You provide an advisory review — your findings inform the final report but do not block completion.
## Tools
- **Read** — read source files and workspace files
- **Grep** — search for patterns across the codebase
- **Glob** — find files by pattern
- **Bash** — read-only verification commands only (`git diff`, `git log`, `wc`, `npm test`, `npm run lint`, `tsc --noEmit`). Do NOT write, edit, create, or delete any files.
## Scope
Review ONLY files owned by implementers as listed in `.agent-team/{team-name}/file-locks.json`. Do not review files outside this scope.
Read the file-locks first:
```
Read: .agent-team/{team-name}/file-locks.json
```
Then review each file listed. Also read surrounding code (imports, callers, tests) for context on consistency and integration.
## Rubric
Score each of these 5 dimensions on a scale of 1-5. See `skills/audit/references/elegance-rubric.md` for detailed scoring guidance.
| Dimension | What to assess |
|-----------|---------------|
| **Simplicity** | Could this be simpler? Unnecessary abstractions? |
| **Consistency** | Follows existing codebase patterns and conventions? |
| **Readability** | Clear naming, logical structure, self-documenting? |
| **Testability** | Easy to test? Proper separation of concerns? |
| **Minimal impact** | Only touches what's necessary? No scope creep? |
For each finding, classify the severity:
- **nitpick**: Style preference, not a quality issue
- **improve**: Would make code better, not critical
- **refactor**: Should change before merge
## Communication
You are a member of the audit team, created at stage start. Use **SendMessage** to communicate with the team lead. Your primary output is the `ELEGANCE_REVIEW` structured message, sent via SendMessage to the lead when your review is complete.
## Output
Send a single `ELEGANCE_REVIEW` message to the lead via **SendMessage** when your review is complete:
```
ELEGANCE_REVIEW:
overall_score={average of 5 dimensions, rounded to 1 decimal}
dimensions={simplicity: N, consistency: N, readability: N, testability: N, minimal_impact: N}
findings=[
{file: "path/to/file.ts", line_range: "15-22", dimension: "simplicity", suggestion: "Extract repeated validation into a helper", severity: "improve"},
{file: "path/to/file.ts", line_range: "45", dimension: "readability", suggestion: "Rename `x` to `tokenPayload`", severity: "nitpick"}
]
```
If no findings: send the message with an empty findings list and a note: "No actionable findings — code meets elegance standards."
## Important
- This review is **advisory only**. Your findings will be included in the team report for the user's reference. They do NOT block completion and do NOT create fix tasks unless the user explicitly requests fixes.
- Focus on substance over volume. A few meaningful `improve` or `refactor` findings are more valuable than many `nitpick` items.
- Read the project's CLAUDE.md (if it exists) for conventions before scoring Consistency.
- Compare new code against existing patterns in the same module, not against ideal patterns from other projects.
references/report-format.md
# Final Report Format
The final report is a persistent artifact generated at completion. It lives in the workspace directory alongside the tracking files, giving the user a complete record in one place.
## Contents
- [Location](#location) — where the report lives
- [Template](#template) — full report structure
- [Generation Protocol](#generation-protocol) — how the lead generates it
- [Guidelines](#guidelines) — writing conventions
- [Elegance Review](#elegance-review) — code quality assessment section
- [Lessons Summary](#lessons-summary) — team execution insights section
## Location
`.agent-team/{team-name}/report.md` (relative to project root)
This file is generated during Phase 5 (Step 7), after the completion gate, remediation gate, and elegance gate, and before the audit review agent validates it.
## Template
```markdown
# Team Report: {team-name}
**Task**: {one-line description}
**Date**: {completion timestamp}
**Duration**: {approximate wall-clock time from team creation to completion}
**Status**: completed | completed with issues
---
## Executive Summary
### What Was Done
{2-5 bullet points summarizing the work completed}
### Files Changed
{Grouped by teammate, listing created/modified/deleted files}
### Key Decisions
{3-5 most important decisions made during execution, with brief reasoning}
### Issues Summary
- **Resolved**: {count} — {one-line summary of significant ones}
- **Open/Deferred**: {count} — {one-line each, these need user follow-up}
- **Remediation**: {applied | declined | not needed}
> **Unresolved issues (require manual follow-up):**
> _(Include this block only if OPEN issues remain after remediation was declined or after a remediation cycle completed with remaining issues.)_
> - Issue #N (severity): description
> - Issue #N (severity): description
> See `issues.md` for full details.
### Follow-up Items
{Bulleted list of anything that needs attention after the team disbanded}
### Team Metrics
| Metric | Value |
|--------|-------|
| Tasks | {completed}/{total} |
| Issues | {resolved}/{total} ({critical}C {high}H {medium}M {low}L) |
| Handoffs | {count} |
| Blocked events | {count} |
| Remediation cycles | {0 or 1} |
| Re-plans | {count, 0 if none} |
| Critical path length | {initial} → {final} (shifted {count} times) |
| Integration checkpoints | {count} ({passed}/{flagged}) |
| Resumed tasks | {count valid}/{count stale}/{count remaining} (or "N/A — fresh start") |
---
## Elegance Review
_(Include this section only if the elegance gate ran — i.e., the team had write-access teammates that completed tasks. Omit entirely for pure research/audit/planning teams.)_
### Overall Score: {N.N}/5
| Dimension | Score |
|-----------|-------|
| Simplicity | {1-5} |
| Consistency | {1-5} |
| Readability | {1-5} |
| Testability | {1-5} |
| Minimal impact | {1-5} |
### Findings
| File | Lines | Dimension | Severity | Suggestion |
|------|-------|-----------|----------|------------|
| {path} | {range} | {dimension} | {nitpick/improve/refactor} | {suggestion} |
_{If no findings: "No actionable findings — code meets elegance standards."}_
---
## Lessons Summary
_(Include this section if `lessons.md` was generated during the audit stage.)_
### Top Takeaways
{Top 3 most impactful lessons from the team execution — draw from What Worked and What Failed in lessons.md}
1. {takeaway with brief context}
2. {takeaway with brief context}
3. {takeaway with brief context}
### Estimation Accuracy
| Metric | Value |
|--------|-------|
| Tasks on target (+/- 20%) | {count}/{total} |
| Average overrun | {+N min or N/A} |
| Largest overrun | {task name: +N min} |
| Systematic bias | {over/under/none} |
_(Derived from the Estimation Accuracy table in lessons.md. "On target" means actual time was within 20% of estimated time.)_
---
## Full Audit Trail
### Team Composition
| Name | Role | Tasks Completed | Files Owned |
|------|------|----------------|-------------|
| {name} | {role} | {count} ({task IDs}) | {files/areas} |
### Task Ledger
| ID | Subject | Owner | Status | CP | Notes |
|----|---------|-------|--------|----|-------|
| {id} | {subject} | {owner} | completed / deferred | {★ if critical path} | {outcome notes} |
### Decision Log
Chronological record of all decisions made during the session.
- [{timestamp}] {decision and reasoning}
### Handoff Log
Record of cross-teammate information transfers.
- [{timestamp}] {source} -> {target}: {what was handed off}
### References
Source documents consulted during this team's work.
| Type | Path/URL | Description |
|------|----------|-------------|
| {spec/ADR/design/PR/doc} | {path or URL} | {one-line description} |
### Issues & Impact Tracker
| # | Severity | Reporter | Description | Impact | Affected Tasks | Status | Resolution |
|---|----------|----------|-------------|--------|---------------|--------|------------|
| {n} | {level} | {who} | {what} | {impact} | {IDs} | RESOLVED / MITIGATED / OPEN | {how fixed} |
### Per-Teammate Summaries
#### {teammate-name} ({role})
- **Completed**: {task IDs and brief descriptions}
- **Files modified**: {list}
- **Decisions made**: {any local decisions}
- **Open concerns**: {anything flagged}
```
## Generation Protocol
The lead generates the report during Phase 5 Step 7 (MANDATORY — do not skip):
1. Read all workspace files:
- `.agent-team/{team-name}/progress.md` — team members, decisions, handoffs, **references**
- `.agent-team/{team-name}/tasks.md` — task ledger
- `.agent-team/{team-name}/issues.md` — issue tracker
- `.agent-team/{team-name}/task-graph.json` — dependency graph with timestamps
2. Read TaskList for final task states (source of truth for status)
3. Incorporate teammate summaries collected via structured request in Phase 5 step 2 (from the execute stage)
4. Copy References section from `progress.md` into the report's References section
5. If the elegance gate ran (Step 4), include the Elegance Review section with scores and findings from the `ELEGANCE_REVIEW` message
6. If lessons were captured (Step 5), include the Lessons Summary section derived from `.agent-team/{team-name}/lessons.md`
7. Write `.agent-team/{team-name}/report.md` using the template above
8. **Self-check**: read the file back — does it contain the Executive Summary section? If not, regenerate
## Guidelines
- The executive summary should be useful on its own — a user who reads only the top section should understand what happened
- The audit trail preserves full history for detailed review
- If issues are OPEN or MITIGATED, highlight them prominently in the executive summary
- File paths should be relative to the project root where possible
- Keep the report factual — no speculation about what "might" need attention unless backed by evidence from the session
- The report draws from workspace files, not from memory — this ensures accuracy after context compaction
- The Elegance Review section is included only when the elegance gate ran; omit it entirely for read-only teams
- The Lessons Summary section distills the most impactful insights; the full lessons.md remains in the workspace for detailed reference
## Report Variants
All archetypes share the same outer structure (Executive Summary, Elegance Review, Lessons Summary, Team Metrics, Full Audit Trail, Per-Teammate Summaries). Only the middle content sections differ. The lead selects the variant based on the team archetype detected in Phase 1.
### Findings Report
Used by: **research-team**
Replaces the "Files Changed" section in the Executive Summary and adds a Findings section to the Full Audit Trail:
```markdown
### What Was Discovered
{2-5 bullet points summarizing the key findings}
### Findings
#### [Research Angle / Question 1]
- **Key finding**: {concise statement}
- **Evidence**: {file:line references, data points, external sources}
- **Confidence**: high | medium | low
- **Implications**: {what this means for the project/decision}
#### [Research Angle / Question 2]
...
### Synthesis
- **Agreements**: {findings confirmed by multiple researchers}
- **Contradictions**: {conflicting findings with evidence from each side}
- **Open questions**: {what couldn't be determined and why}
- **Recommended next steps**: {actionable items based on findings}
```
The "Files Changed" section is omitted (research teams don't modify files). The "Per-Teammate Summaries" section uses "Findings" instead of "Files modified". Elegance Review section is omitted (no code to review).
### Audit Report
Used by: **audit-team**
Replaces the "Files Changed" section and adds an Audit Results section:
```markdown
### What Was Audited
{2-5 bullet points summarizing the audit scope and standards checked}
### Audit Results
#### Summary
- **Items checked**: {total count}
- **Pass**: {count} | **Fail**: {count} | **Warning**: {count}
- **Overall compliance**: {percentage or qualitative assessment}
> PASS/FAIL/WARNING is the per-checklist-item status (Compliance Status table below). FAIL items are further classified by severity (Critical/High/Medium/Low) in the Findings section based on impact.
#### Findings by Severity
##### Critical
- {finding}: {file:line}, standard violated: {standard}, recommended fix: {fix}
##### High
- {finding}: {file:line}, standard violated: {standard}, recommended fix: {fix}
##### Medium
- {finding}: {file:line}, description
##### Low
- {finding}: {file:line}, description
### Compliance Status
| Standard/Checklist Item | Status | File(s) | Notes |
|------------------------|--------|---------|-------|
| {item} | PASS / FAIL / WARNING / N/A | {file references} | {details} |
```
The "Per-Teammate Summaries" section uses "Audit findings" and "Items checked" instead of "Files modified". Elegance Review section is omitted (no code to review).
### Plan Report
Used by: **planning-team**
Replaces the "Files Changed" section and adds design/planning sections:
```markdown
### What Was Planned
{2-5 bullet points summarizing the planning scope and deliverables}
### Proposed Approach
- {Architecture / design summary}
- {Key components and their responsibilities}
- {Data flow or interaction model}
### Alternatives Considered
| Approach | Pros | Cons | Why Rejected/Chosen |
|----------|------|------|-------------------|
| {approach 1} | {pros} | {cons} | {reasoning} |
| {approach 2} | {pros} | {cons} | {reasoning} |
### Decision Rationale
- {Why this approach over alternatives}
- {Key assumptions and what would invalidate them}
- {Risks and mitigations}
> If the team has Planners but no Strategist, the lead synthesizes the assumption analysis from Planners' "alternatives considered" and "trade-offs" outputs.
### Action Items
- [ ] {Next step to implement this plan, with owner if known}
- [ ] {Next step}
```
The "Per-Teammate Summaries" section uses "Design contributions" and "Decisions proposed" instead of "Files modified". Elegance Review section is omitted (no code to review).