Skill: kkenny0/taku-build (version 1.0.0)

--- name: taku-build description: > Execute an approved implementation plan. Triggers after /taku-plan, or on "build this", "implement the plan", "start coding", "run the plan", "execute tasks", "写代码", "开始实现", "执行计划", "开发吧", "开始写". Also handles worktree setup on "create a worktree", "isolated environment", "new branch workspace", "创建工作树". --- # Taku Build - Auditable Implementation Build implements the approved contract and leaves Review enough evidence to decide whether the work can ship. Rule labels: `[IRON LAW]` means a non-negotiable correctness constraint. `[GUIDANCE]` means a strong default that may adapt when context justifies it. [IRON LAW] No production code without a failing test, reproduction, or explicit verification anchor first. If the repo lacks a test harness, create the smallest reproducible check and say why. ## Preflight Before editing: 1. Read `PLAN.md`, an approved Quick mini design, or the explicit user-approved task contract. 2. If the plan has a `Build Agent Contract`, read Required fields first and use Optional fields only for context. 3. Load `references/tdd.md` for the local TDD cycle. 4. Use `references/worktrees.md` only when isolation is needed. 5. Choose execution mode yourself: sequential, parallel, or hybrid. Do not ask the user to choose a mode unless the choice changes product scope, cost, or risk. ## Output Contract Build speaks in three stable shapes only. ### BUILD PREFLIGHT ```text BUILD PREFLIGHT - Mode: sequential | parallel | hybrid - Reason: [one sentence] - Subagents: available | unavailable; using sequential wave execution - Waves: [wave-slug: task-slug list, or wave-1 for single task] - Worktree: not needed | [path] - TDD: enabled - Ledger: - task-slug: files=[...] | tdd=[...] | status=pending | deviation=none | evidence=none - Next: [first wave/task] ``` ### BUILD UPDATE ```text BUILD UPDATE - Completed: [wave-slug or task-slug] - Tasks: [task-slug list] - Result: [tests/repro/spec check observed] - Deviations: none | approved: [...] | needs-review: [...] - Ledger delta: [only changed rows] - Next: [next wave/task or REVIEW] ``` ### BUILD COMPLETE ```text BUILD COMPLETE - Executed waves: [...] - Task ledger: [all done | exceptions listed] - Changed files: [...] - Verification evidence: [commands and outcomes] - Deviations: none | approved: [...] | needs-review: [...] - Residual risk: none | [...] - Status: READY_FOR_REVIEW | BLOCKED - Next: REVIEW ``` The ledger is a handoff artifact, not a diary. Keep one row per task with these fields: `task-slug`, `files`, `tdd`, `status`, `deviation`, `evidence`. ## Mode Selection - **Sequential:** tasks are tightly coupled or there are 1-2 obvious steps. - **Parallel:** tasks are independent and touch disjoint files. - **Hybrid:** waves depend on earlier waves, but tasks inside a wave are independent. Preserve plan task IDs when available. If the plan lacks IDs, create stable kebab-case slugs. If a file appears in multiple tasks, those tasks are dependent and must not run in parallel. When subagents are unavailable, keep the same wave schedule and execute each wave locally in order. Report that in `BUILD PREFLIGHT`. ## Execution Loop For each task or wave: 1. Mark ledger row(s) `in_progress`. 2. Create the failing test, reproduction, or verification anchor. 3. Implement the smallest change that satisfies the spec. 4. Run the task verification. 5. Check spec compliance before code quality. 6. Update the ledger with status, evidence, and deviations. 7. Emit `BUILD UPDATE`. Do not mark a task `done` until its spec and TDD/verification anchor have evidence. ## Deviation Policy Use the approved contract as the boundary. - `deviation=none`: implementation matches the plan. - `deviation=approved`: user explicitly approved the difference; preserve the approval in later summaries. - `deviation=needs-review`: implementation differs from plan and has not been approved. `needs-review` deviations block `READY_FOR_REVIEW` unless the deviation is the only safe path and is clearly documented for Review. ## Reconciliation After every parallel or hybrid wave: - check for overlapping file changes - run the smallest integration verification - verify no task leaked outside its assigned files without recording a deviation Reconciliation is required even when all individual tasks report done. ## Completion Gate Before routing to Review: - every task is `done` or explicitly `not-done` with reason - every done task has evidence - all deviations are either `none`, `approved`, or `needs-review` - changed files are listed - verification evidence is listed Then emit `BUILD COMPLETE` and route to `/taku-review`. ## Known Pitfalls **Ledger missing at Review.** Review cannot distinguish approved deviation from scope drift. Prevention: create the ledger in `BUILD PREFLIGHT` and preserve task slugs in every update. **Parallel tasks touched the same file.** One task overwrote another. Prevention: duplicate file paths create dependencies; run them sequentially. **TDD anchor skipped after a test-harness failure.** The agent called the code "probably correct." Prevention: debug or bound the harness failure, then preserve a verifiable anchor before claiming completion.

path: agents/openai.yaml
content: display_name: Taku Build
short_description: Execute approved plans with TDD and visible progress.
default_prompt: Use Taku Build to choose an execution mode, follow TDD, and implement the approved plan.


path: references/tdd.md
content: ---
name: taku-tdd
description: Use whenever writing implementation code. Triggers during /taku-build, /taku-build (sequential mode), or when the user starts implementing a feature.
---

# Test-Driven Development

## Overview

Write the test first. Watch it fail. Write the minimal code to pass it. Refactor.

**Core principle:** If you didn't watch the test fail, you don't know it tests the right thing.

## Why TDD Prevents Bugs

Tests written after code pass immediately — proving nothing. You might test the wrong thing, test implementation instead of behavior, or miss edge cases entirely.

Test-first forces you to see the test fail first, proving it actually catches the bug you're about to fix. This single discipline prevents an entire class of defects: code that "should work" but doesn't.

**Order matters:**
- Tests-after answer "What does this do?" — biased by your implementation
- Tests-first answer "What should this do?" — driven by requirements

## The Iron Law

```
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
```

Wrote code before the test? Delete it. Not "save as reference," not "adapt while writing tests." Delete it completely and start fresh from tests.

## RED-GREEN-REFACTOR Cycle

### RED — Write Failing Test

One minimal test. Clear name. Real code (no mocks unless unavoidable).

```python
def test_retries_failed_operations_three_times():
    attempts = 0
    def operation():
        nonlocal attempts
        attempts += 1
        if attempts < 3:
            raise ConnectionError("fail")
        return "success"

    result = retry_operation(operation)
    assert result == "success"
    assert attempts == 3
```

### Verify RED — Watch It Fail

Run the test. Confirm:
- It fails (not errors out)
- Failure message matches expectations (missing function, not typo)
- It fails because the feature doesn't exist yet

Test passes immediately? Wrong test — it's verifying existing behavior. Delete and rewrite.

**Why watch it fail:** A test that passes before the feature exists isn't testing the feature — it's testing something else. If you don't see it fail, you don't know what it's actually testing. The failure is proof that the test is wired to the right thing.

### GREEN — Minimal Code

Write the simplest code that makes the test pass. No extra features, no "while I'm here" improvements.

```python
def retry_operation(fn, max_retries=3):
    for i in range(max_retries):
        try:
            return fn()
        except Exception:
            if i == max_retries - 1:
                raise
```

### Verify GREEN — Watch It Pass

Run all tests. Confirm:
- New test passes
- All existing tests still pass
- Output is clean (no warnings, no skips)

### REFACTOR — Clean Up

Remove duplication, improve names, extract helpers. Keep tests green. No new behavior.

**Why separate refactor step:** GREEN produces working code, but working code written to pass a specific test often has duplication or awkward structure. The refactor step is where you clean up WITHOUT adding features. Combining cleanup with implementation risks introducing bugs alongside the cleanup. Keep the steps separate: first make it work, then make it clean.

## Anti-Rationalization Table

| Excuse | Why it's wrong |
|--------|---------------|
| "Too simple to test" | Simple code breaks too. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what did I build?" Tests-first = "what should I build?" |
| "Already manually tested" | Ad-hoc testing has no record, can't re-run, easy to forget cases. |
| "Deleting X hours of work is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep as reference, write tests first" | You'll unconsciously adapt it. That's testing after. Delete means delete. |
| "Need to explore the design first" | Fine — throw away exploration, start fresh with TDD. |
| "Test is hard to write" | Hard to test = hard to use. The test is telling you something. |
| "TDD will slow me down" | TDD is faster than debugging in production. Always. |
| "This is different because..." | It's not. |

Any of these running through your head? Stop. Delete the code. Write the test first.

## When TDD Doesn't Apply

Ask your human partner for these cases:
- Throwaway prototypes
- Generated code
- Pure configuration files

Everything else gets a test first.

## Known Pitfalls

**Test passes immediately on the RED step — and nobody notices.** The test was supposed to verify a new `calculateDiscount()` function. But the test called `calculate_price()` (an existing function) by mistake. It passed immediately. The developer assumed the function already existed and moved on. The real `calculateDiscount()` was never implemented.

*What went wrong:* The RED step requires watching the test fail AND confirming the failure is for the expected reason. This test failed to fail, which should have been a red flag. Instead, it was treated as a green light.

*Prevention:* "Verify RED" step says: "Test passes immediately? Wrong test — it's verifying existing behavior. Delete and rewrite." This check is not optional. A test that passes before the feature exists is testing the wrong thing.

**Writing the test after code, then claiming TDD was followed.** Code was written first (200 lines). Then tests were written that call the exact implementation. The tests pass, but they test the implementation, not the behavior. When the implementation was refactored later, all tests broke — they were coupled to internal structure.

*What went wrong:* The Iron Law was violated in spirit. Writing tests after code isn't TDD — it's documentation of what you happened to build. The tests are biased toward the implementation.

*Prevention:* The Iron Law says: "Wrote code before the test? Delete it." This isn't hyperbole. Delete the code, write the test, watch it fail, then re-implement. The fresh implementation will be driven by requirements (the test) rather than assumptions (your first draft). The re-implementation is usually better.

**Testing implementation details instead of behavior.** The test asserts that `processOrder()` calls `validateCart()` then `applyDiscount()` then `createCharge()` in sequence. A refactor that combined `validateCart` and `applyDiscount` into a single `prepareOrder()` step broke all tests — even though the observable behavior (order processed, discount applied, charge created) was identical.

*What went wrong:* Tests asserted HOW the code works (internal call sequence) instead of WHAT the code does (observable outcomes). Implementation-coupled tests resist refactoring and produce false failures.

*Prevention:* "Good Tests" says tests should demonstrate the desired API surface. Test inputs and outputs, not internal mechanics. If you need to check intermediate state, test it through the public API, not by asserting on private methods or call order.

## Good Tests

- **Minimal:** One behavior per test. "and" in the name? Split it.
- **Clear:** Name describes the expected behavior, not the implementation.
- **Shows intent:** Demonstrates the desired API surface.

## Verification Checklist

Before marking work complete:

- [ ] Every new function/method has a test
- [ ] Watched each test fail before implementing
- [ ] Each test failed for the expected reason
- [ ] Wrote minimal code to pass
- [ ] All tests pass with clean output
- [ ] Edge cases and error paths covered

## Debugging Integration

Found a bug? Write a failing test that reproduces it first. Follow the TDD cycle. The test proves the fix works and prevents regression.

Never fix a bug without a test.


path: references/worktrees.md
content: ---
name: taku-worktree
description: >
  Use when starting feature work that needs isolation from the current workspace —
  creates isolated git worktrees with auto-detected project setup and baseline test
  verification. Triggers on "create a worktree", "new branch workspace", "isolated
  environment", "start a feature branch", or when build-phase work needs a clean
  sandbox before making changes.
---

# taku-worktree — Git Worktree Isolation

Git worktrees let you work on multiple branches simultaneously without switching. One workspace per feature. No context pollution. No stash juggling. No "wait, I was in the middle of something."

## Why This Matters

Branch switching kills flow. You have uncommitted work, dependencies installed, test state cached. Switching branches means redoing all of that. Worktrees give each feature its own directory, its own node_modules, its own lockfile state. Switch instantly. Never lose context.

## Directory Selection

Follow this priority:

1. **Existing directory:** Check for `.worktrees/` or `worktrees/`. If both exist, `.worktrees/` wins.
2. **CLAUDE.md preference:** `grep -i "worktree" CLAUDE.md` — if specified, use it.
3. **Ask the user:** If neither exists, offer `.worktrees/` (project-local, hidden) or a global location.

## Safety: Verify gitignore

Before creating a project-local worktree, verify the directory is ignored:

```bash
git check-ignore -q .worktrees 2>/dev/null
```

If NOT ignored, fix it immediately:

```bash
echo ".worktrees/" >> .gitignore
git add .gitignore && git commit -m "chore: add .worktrees/ to gitignore"
```

Why: Unignored worktree contents get tracked by git. That pollutes `git status` and risks committing worktree artifacts. Fix it now or regret it later.

## Creation Steps

### 1. Detect project type

```bash
project=$(basename "$(git rev-parse --show-toplevel)")
```

### 2. Create the worktree

```bash
git worktree add ".worktrees/$BRANCH_NAME" -b "$BRANCH_NAME"
cd ".worktrees/$BRANCH_NAME"
```

### 3. Auto-detect and install dependencies

```bash
[ -f package.json ] && npm install
[ -f Cargo.toml ] && cargo build
[ -f requirements.txt ] && pip install -r requirements.txt
[ -f pyproject.toml ] && poetry install
[ -f go.mod ] && go mod download
```

Don't hardcode. Detect from project files. If none match, skip dependency install.

**Why auto-detect:** Hardcoded setup commands break on different projects and become stale. Auto-detection from project files means the worktree setup works for any project without modification.

### 4. Run baseline tests

Run the project's test suite. If tests fail before you've changed anything, that's a pre-existing problem. Report it and ask whether to proceed.

**Why baseline tests:** Without a baseline, you can't distinguish bugs you introduced from bugs that already existed. The baseline establishes what "passing" looks like in this worktree's environment. If tests fail here, any work you do will be built on a broken foundation.

```bash
npm test        # or cargo test, pytest, go test ./...
```

If tests pass: report the count. "Worktree ready. 47 tests, 0 failures."

If tests fail: show the output. Ask the user. Don't silently proceed with a broken baseline.

### 5. Report

```
Worktree: .worktrees/<branch-name>
Tests: <N> passing, <M> failing
Ready to implement: <feature-name>
```

## Cleanup

When the feature is done and merged:

```bash
git worktree remove ".worktrees/$BRANCH_NAME"
git branch -d "$BRANCH_NAME"
```

If the branch isn't merged yet and you want to keep it, just remove the worktree:

```bash
git worktree remove ".worktrees/$BRANCH_NAME"
```

## Common Mistakes

| Mistake | Consequence | Fix |
|---------|------------|-----|
| Skip gitignore check | Worktree contents tracked by git | Always `git check-ignore` before creating |
| Proceed with failing tests | Can't tell new bugs from old | Report failures, get permission |
| Hardcode setup commands | Breaks on different projects | Auto-detect from project files |
| Never clean up worktrees | Disk usage grows, stale branches | Remove worktree after merge |

## Known Pitfalls

**Creating worktree without checking gitignore.** A worktree was created in `.worktrees/my-feature`. After implementing the feature, `git status` showed 2,000+ untracked files — the worktree's `node_modules/` and build artifacts. The entire worktree contents were about to be committed.

*What went wrong:* The gitignore check was skipped because "it usually works." The `.worktrees/` directory wasn't in `.gitignore`, so git saw everything inside it as untracked files.

*Prevention:* The Safety step is first for a reason: `git check-ignore -q .worktrees`. If it's not ignored, fix it BEFORE creating the worktree. This is a 10-second check that prevents a very messy cleanup.

**Baseline tests failing but proceeding anyway.** The worktree was created, `npm install` ran, `npm test` showed 3 failures. The developer proceeded with implementation assuming the failures were pre-existing. After 2 hours of work, the tests still failed — 2 were pre-existing but 1 was caused by a dependency version mismatch in the worktree's fresh install.

*What went wrong:* Failing baseline tests were assumed to be someone else's problem. The worktree's isolated environment had a different dependency resolution than the main workspace.

*Prevention:* If baseline tests fail, report the output and ask whether to proceed. Don't assume failures are pre-existing. In isolated worktrees, dependency versions may differ. Verifying the baseline protects you from debugging your own changes against a broken foundation.

**Stale worktrees accumulating.** Over 3 months, 12 worktrees were created for various features. 10 were merged, but the worktrees were never cleaned up. Each had its own `node_modules/` (500MB each). Six gigabytes of disk space consumed by dead worktrees.

*What went wrong:* The Cleanup step was never executed. After merging, developers moved on without removing worktrees.

*Prevention:* Add worktree cleanup to the post-merge routine. After merging or discarding a branch, remove the worktree immediately. List stale worktrees with `git worktree list` periodically.

## Completion

Status: DONE when worktree is created, dependencies installed, and baseline tests pass. DONE_WITH_CONCERNS if baseline tests fail but user chose to proceed. BLOCKED if git worktree setup fails.


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)