---
description: Run parallel quality audits on backlog cards before development, then apply findings and commit.
allowed-tools: Bash, Task, Edit, Write, Read, Grep, Glob, WebFetch, WebSearch, TaskCreate, TaskUpdate, TaskList, TaskGet, TeamCreate, TeamDelete, SendMessage, AskUserQuestion
---

You are the **pre-development check orchestrator**. When the user invokes `/check`, you coordinate parallel audit agents on backlog cards that are **not yet developed** (status TODO or READY) to catch issues before implementation starts.

**CRITICAL: This skill ALWAYS uses an agent team architecture.** Each audit agent runs as an independent teammate with its own context window. This prevents context saturation when reviewing many cards.

## Step 1 — Identify Cards

Look for backlog cards with status `TODO` or `READY` that need pre-development validation.

- If the user provided card IDs as arguments → use those.
- If cards are identifiable from the conversation context → use those.
- If not → ask the user which card IDs to check (accept same formats as `/new`: space-separated, comma-separated, or hyphen-range).

Read each card from `${paths.backlog_dir}/*.yml` to understand scope, requirements, acceptance criteria, and planned changes.

## Step 2 — Choose Audit Profile

| Profile | Agents launched in parallel |
|---------|----------------------------|
| **Code + Performance** | plan-auditor, code-reviewer, doc-reviewer, api-perf-cost-auditor |
| **Code** | plan-auditor, code-reviewer, doc-reviewer |

**Default (no prompt needed):** choose **Code + Performance** when any card in scope has an
API/performance-sensitive surface — i.e. its `areas` includes `api` or `data`, or its
`files_likely_touched` includes API-route / data-access / query paths. Otherwise default to **Code**.
Announce the chosen profile and proceed — this keeps `/check` runnable autonomously (e.g. triggered
programmatically before development) without a human-in-the-loop on every run.

Only prompt with `AskUserQuestion` (the two options above) when `/check` is invoked interactively AND
the heuristic is ambiguous (e.g. mixed scope where the perf-sensitivity of the cards is unclear). A
human-present run may still override the default by passing the profile explicitly.

## Step 3 — Gather Context (lightweight)

Before launching audits, gather **only metadata** to build agent prompts — do NOT read full file contents into your own context:

1. Read the backlog card(s) YAML — store the raw text for each card.
2. If the card has `files_likely_touched` → note the file paths (do NOT read the files yourself).
3. If the card has `links.prd` → note the PRD path (do NOT read it yourself).
4. If the card references parent/child cards → note their paths.

**The audit agents will read files themselves in their own context windows.** Your job is to give them paths and card content, not to pre-load everything.

## Step 4 — Create Agent Team & Launch Audits

### 4a. Create the team

Use `TeamCreate` with name `check-audit` and description based on the cards being reviewed.

### 4b. Create tasks

Use `TaskCreate` to create one task per audit agent per card. Structure:

- For **N cards x M agents**, create **N x M tasks** (e.g., 5 cards x 4 agents = 20 tasks).
- Each task subject: `[CARD-ID] <agent-type> audit`
- **Set the owner/assignee on each task to its audit agent's teammate name** (the `Teammate name`
  from the mapping in 4c) — this is the claim/lock. Each teammate processes ONLY tasks owned by it;
  it never claims a task already owned by another teammate. If `TaskCreate` cannot set an owner at
  creation, the teammate MUST claim atomically: skip any task whose owner is already set to a
  different teammate, and refuse to start a task it has not successfully claimed.
- Each task description: contains the full card YAML content + file paths to read + PRD path + instructions.

**IMPORTANT**: Embed the full card YAML content directly in the task description so agents don't need to re-read it. But for source files and PRDs, only provide paths — agents read those in their own context.

### 4c. Launch teammate agents in parallel

For each **audit agent type**, spawn ONE teammate using the `Task` tool with `team_name: "check-audit"`. Each teammate:

- Receives a prompt telling it to check `TaskList`, claim its tasks, and process them sequentially.
- Has its own independent context window.
- Writes findings back into the task description or sends a message to the orchestrator.

**Agent type mapping:**

| Audit Role | `subagent_type` | Teammate name |
|------------|-----------------|---------------|
| plan-auditor | `plan-auditor` | `plan-auditor` |
| code-reviewer | `code-reviewer` | `code-reviewer` |
| doc-reviewer | `doc-reviewer` | `doc-reviewer` |
| api-perf-cost-auditor | `api-perf-cost-auditor` | `perf-auditor` |

Launch ALL teammates in a single message (parallel tool calls).

### 4d. Teammate prompt template

Each teammate receives this prompt:

```
You are the {AGENT_ROLE} (teammate name "{TEAMMATE_NAME}") for a pre-development audit team ("check-audit").

## Your workflow

1. Call `TaskList` and select ONLY the tasks whose owner/assignee is you ("{TEAMMATE_NAME}"); if the
   task store does not expose an owner field, fall back to matching the `<agent-type>` token in the
   task subject to your role. Ignore every other task — it belongs to another teammate.
2. For each of YOUR tasks (in ID order):
   a. Call `TaskGet` to read the full task description (contains card YAML + file paths).
   b. **Claim it**: mark task as `in_progress` via `TaskUpdate`. If `TaskGet` shows it is already
      `in_progress` or `completed` (another agent got it first), SKIP it — never re-process a claimed
      task.
   c. Read any source files or PRDs referenced in the task (use Read tool — paths are in the task description).
   d. Perform your audit (see audit instructions below).
   e. **Write your findings into the task description** via `TaskUpdate` with the updated `description` field. Append a `## FINDINGS` section at the end of the existing description with your full markdown findings. This is the primary delivery mechanism — the orchestrator will read findings from the task store.
   f. Send a brief notification to the orchestrator via `SendMessage` (type "message", recipient "orchestrator") saying which task is done. Do NOT include full findings in the message — just the task ID and a one-line summary. The orchestrator reads findings from the task store.
   g. Mark task as `completed` via `TaskUpdate`.
   h. Move to the next task.
3. After all tasks are done, send a final "all tasks complete" message to the orchestrator.

**IMPORTANT**: Always write findings to the task description (step e) before sending the notification (step f). The task description update is durable; the message is just a ping.

## Audit Instructions

{AGENT_SPECIFIC_INSTRUCTIONS}

## Output Format

For each card, return findings as:

### [CARD-ID] — {Agent Role} Findings

- [ ] **Finding title** — Description of the issue, risk, or gap. (Severity: HIGH/MEDIUM/LOW) [Target: <field>]
- [ ] **Finding title** — ... (Severity: ...) [Target: <field>]

If no findings: "No issues found for [CARD-ID]."

**`[Target: <field>]` tag is mandatory** on every finding. It tells the orchestrator exactly which card field to edit. Use one of:

| Target tag | When to use |
|---|---|
| `[Target: requirements]` | Missing or wrong requirement text |
| `[Target: acceptance_criteria]` | Missing AC, vague AC that needs rewriting |
| `[Target: definition_of_done]` | Missing DoD checkbox |
| `[Target: files_likely_touched]` | Missing file path |
| `[Target: depends_on]` | Missing dependency card ID |
| `[Target: areas]` | Missing area entry (api, docs, data, ui) |
| `[Target: git_strategy]` | `git_strategy: TBD` or wrong value |
| `[Target: unknowns]` | Unresolved unknown that should be surfaced |
| `[Target: notes]` | LOW severity only — informational, no structural edit needed |
```

**Agent-specific instructions:**

**plan-auditor**: Review the backlog card's plan, requirements, and acceptance criteria BEFORE development starts. Check for: missing requirements, vague acceptance criteria, hidden dependencies not listed in `depends_on`, ambiguous scope boundaries, missing edge cases, gaps between PRD and card requirements, unrealistic assumptions, missing unknowns that should be flagged. For every finding, assign the `[Target: <field>]` tag that indicates which card field the orchestrator should edit.

**code-reviewer**: Review the existing files listed in `files_likely_touched` (read them yourself) and assess: will the planned changes conflict with existing patterns? Are there architectural concerns with the proposed approach? Does the card's implementation plan align with existing code conventions? Are there existing utilities or patterns the card should reuse but doesn't mention? For each finding, tag with `[Target: files_likely_touched]`, `[Target: requirements]`, or `[Target: notes]` as appropriate.

**doc-reviewer**: Check that the card has proper documentation links, PRD references are valid and aligned, and that the planned changes will require doc updates not mentioned in the card. Verify that `files_likely_touched` includes relevant doc files. Check if `areas` (ui, api, data, external) are complete. Tag missing files as `[Target: files_likely_touched]`, missing areas as `[Target: areas]`, missing doc requirements as `[Target: requirements]`, and `git_strategy: TBD` as `[Target: git_strategy]`.

**api-perf-cost-auditor** (only for "Code + Performance" profile): Review the planned API routes, data access patterns, and architecture described in the card. Read the referenced source files yourself. Check for potential performance bottlenecks, N+1 query risks, missing caching opportunities, cost inefficiencies in the proposed design. Tag structural gaps as `[Target: requirements]` and informational notes as `[Target: notes]`.

## Step 5 — Collect & Merge Findings

Wait for all teammates to complete their tasks, then **read findings from the task store** (do NOT rely solely on `SendMessage` delivery). Use `TaskList` to check when all tasks are `completed`, then call `TaskGet` on each task to read the `## FINDINGS` section from its description. Consolidate all findings into a single report grouped by card, then by agent:

```
# Pre-Dev Audit Report

## [CARD-ID-1] — Card Title

### Plan Audit Findings
- [ ] Finding 1...
- [ ] Finding 2...

### Code Review Findings
- [ ] Finding 1...

### Doc Review Findings
- [ ] Finding 1...

### Performance Findings (if applicable)
- [ ] Finding 1...

## [CARD-ID-2] — Card Title
...
```

**CRITICAL — Persist report to file before proceeding.** After consolidating the report, write it to `/tmp/check-audit-report-{TEAM-NAME}-{RUN-ID}.md` using the Write tool, where `{RUN-ID}` is a full timestamp-plus-uuid (NOT a date-only name, which collides across same-day concurrent runs). This ensures findings survive context compaction between Steps 5 and 7. If context is compacted and you lose the in-memory report, re-read findings from this same path.

Present this consolidated report to the user.

## Step 6 — Cleanup Team

Use `SendMessage` with `type: "shutdown_request"` to gracefully shut down all teammates, then `TeamDelete` to clean up.

## Step 7 — Apply Findings to Cards (make implementation-ready)

**Goal**: Transform each card from "audited" to "implementation-ready" by editing its structured YAML fields directly. Do not just append a checklist to `notes`.

**Read findings from the persisted report file** (the exact `/tmp/check-audit-report-{TEAM-NAME}-{RUN-ID}.md` path written in Step 5) rather than from context memory.

### 7a. Field mapping rules

For each finding in the report, apply edits to the card YAML based on the `[Target: <field>]` tag:

| Target tag | Card field | What to do |
|---|---|---|
| `[Target: requirements]` | `requirements` | Append the missing requirement as a new list item. If the finding says to fix/replace an existing one, find and rewrite it. |
| `[Target: acceptance_criteria]` | `acceptance_criteria` | Append a new `"[ ] [AC-N] ..."` item (N = next sequential number). If vague AC rewrite: find the specific AC and replace its text. |
| `[Target: definition_of_done]` | `definition_of_done` | Append a new `"[ ] ..."` item. |
| `[Target: files_likely_touched]` | `files_likely_touched` | Append the missing file path. Never duplicate an existing path. |
| `[Target: depends_on]` | `depends_on` | Append the missing card ID to the list. |
| `[Target: areas]` | `areas` | Add the missing area key/value (e.g., `docs: [path]`). |
| `[Target: git_strategy]` | `git_strategy` | Replace `TBD` with `feat/<CARD-ID>-<slug> from <base-branch>` (derive slug from card title; resolve `<base-branch>` from `git.trunk_branch` in `baldart.config.yml`, or autodetect if absent). |
| `[Target: unknowns]` | `unknowns` | Append a new `[U-N] UNKNOWN: ...` entry if the finding surfaces a genuine unknown. |
| `[Target: notes]` | `notes` | Do NOT edit structured fields — collect these into the audit trail summary only (Step 7b). |

### 7b. Severity policy

- **HIGH severity**: MUST apply to the target field. These are blockers — the card cannot be safely implemented without them.
- **MEDIUM severity**: SHOULD apply to the target field. Skip only if the finding requires human judgment that cannot be resolved automatically (e.g., ambiguous requirement text where multiple interpretations exist). If skipping, add a `[MANUAL]` tag to the note.
- **LOW severity**: Do NOT edit structured fields. Include in the audit trail note only.

### 7c. Audit trail in `notes`

After applying all structural edits, append a **brief** audit trail to the card's `notes` field:

```yaml
## Applied by /check — YYYY-MM-DD
Applied N findings to structured fields (H high, M medium).
Manual review needed: [list any [MANUAL] items, or "none"].
```

Do NOT dump the full findings list into `notes`. The structured fields now carry the content.

### 7d. Per-card workflow

For each card:
1. Read the persisted report → collect all findings for this card ID.
2. Read the current card YAML.
3. Apply HIGH findings first, then MEDIUM, then write audit trail.
4. Write the updated card YAML.
5. Re-read the card to verify edits landed correctly.

## Step 8 — Commit

1. Validate ONLY the files you changed. `/check` edits backlog card YAML (and at most a note line) —
   it never touches application code, so running the project's lint/build (which may require compiled
   assets, a database, or env vars) here would fail spuriously and block the commit for no benefit.
   Instead, run the cheap, meaningful check: markdownlint / a YAML parse on the modified card files
   (e.g. `npx markdownlint-cli2 <changed .md>` and/or a `js-yaml` / `yq` parse of each changed `.yml`)
   to confirm they are well-formed. If a check is unavailable, note it and proceed.
2. Stage only the modified backlog card files.
3. Commit with message: `[CARD-ID] Apply pre-dev audit findings from /check`.
4. If multiple cards: one commit per card, or a single commit referencing all card IDs.

## Step 9 — Summary

Present a final summary to the user:

- Per card: N findings applied to structured fields (breakdown by target field), N manual items needing human review
- `git_strategy` resolutions made (if any)
- Commit hash(es)
- Any `[MANUAL]` items that need owner input before starting development
