---
name: marco-souza/implement-tasks
source: https://app.decimal.ai/s/marco-souza-implement-tasks@1/SKILL.md
source_sha256: 7b6822d26e61
---

# Implement Tasks (Pure Orchestrator)

This skill **never writes code itself**. It resolves the dependency graph,
generates prompt files in `tasks/`, and spawns isolated tmux subagents that do
the actual implementation. The orchestrator only validates, coordinates, and
monitors — all code changes come from subagents.

## ⛔ Hard Restriction: No Direct File Edits

**The orchestrator agent MUST NOT directly edit, create, or delete any project
source files.** This is a non-negotiable constraint. The orchestrator is a
coordinator, not an implementer.

### Permitted Actions

- ✅ **Read files** — Read tasks.json, prompt files, subagent output, source files
- ✅ **Browser actions** — Navigate to docs, search for solutions, read API references
- ✅ **Run scripts** — validate-dag.ts, generate-prompts.ts, spawn-wave.sh, status-tasks.ts
- ✅ **Run shell commands** — grep, find, git log, tmux management, cat
- ✅ **Write orchestrator artifacts** — Status files, progress reports, handoff notes

### Forbidden Actions

- ❌ **Edit source files** — No edit, write, or delete on any project source files
- ❌ **Create implementation files** — No new .ts, .js, .go, .py, etc. files
- ❌ **Modify configuration** — No changes to package.json, tsconfig, etc.
- ❌ **Run implementation commands** — No npm install, go build, cargo build, etc.

**If implementation work is needed, spawn a subagent.** That's the whole point.

## When to Use

- A `tasks.json` file exists (created by `prd-to-tasks` or manually)
- The user says: "implement the tasks," "build it," "execute the plan," "start coding"
- Multiple interdependent tasks need coordinated execution

## When NOT to Use

- No `tasks.json` exists — run `prd-to-tasks` first (or `create-prd` → `prd-to-tasks`)
- User wants to manually review/pick each task — use `project-files` TODO-driven workflow
- Exploration or research phase — use `explore` skill first

> **Note:** There is no "just do it directly" exception. Even single tasks
> are delegated to a tmux subagent. The orchestrator stays clean.

## Prerequisites

- A valid `tasks.json` file in the current working directory
- `tmux` installed and available on PATH
- `pi` CLI available on PATH (the subagent runner)
- **`spawn-subagents` skill** — Required for spawning isolated pi subagents in tmux
- **`mixture-of-experts` skill** — Required for expert definitions and MoE delegation patterns
- `terminal-multiplexer` skill — For tmux session management
- Reusable scripts in `.agents/scripts/`:
  - `validate-dag.ts` — validates tasks.json structure and DAG
  - `generate-prompts.ts` — writes `tasks/TASK-XXXX-prompt` from tasks.json (auto-validates)
  - `spawn-wave.sh` — launches tmux sessions respecting the DAG
  - `status-tasks.ts` — shows task status (done/running/pending/blocked)

## Output Convention

All task artifacts live under `tasks/`:

```
tasks/
├── tasks.json                  ← input plan (generated by prd-to-tasks)
├── T001-prompt                 ← self-contained prompt for the subagent
├── T002-prompt
├── T003-prompt
├── ...
├── T001.out                    ← captured subagent stdout/stderr
├── T002.out
├── T003.out
├── ...
├── T001.done                   ← marker file (written by subagent on completion)
├── T002.done
└── ...
```

> **Rule:** The orchestrator reads from `/tmp/` for DONE detection, but writes
> prompt files and output logs to the project's `tasks/` directory so they are
> versionable and reviewable.

## Overview

```
tasks.json
    │
    ▼
┌─────────────────┐
│ 1. Parse &      │
│    Validate DAG  │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ 2. Generate     │
│    prompt files  │  → tasks/T001-prompt, T002-prompt, ...
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ 3. Spawn tmux   │
│    subagents     │  → one per task, respecting DAG waves
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ 4. Monitor &    │
│    report        │  → poll DONE markers, aggregate results
└─────────────────┘
```

## Workflow

### Step 1: Read and Parse tasks.json

Read the file and extract the task graph:

```bash
# Read the file
cat tasks.json
```

Parse mentally or with a script:

- **Tasks** — The full task list with IDs, descriptions, dependencies
- **Phases** — The phase grouping and order
- **Metadata** — Project name, total estimates
- **Dependency graph** — Build the DAG (who depends on whom)

### Step 2: Validate the Task Graph

Before implementing, check for common issues:

1. **All dependency IDs exist** — No dangling references
2. **No circular dependencies** — The graph must be a DAG (can run a topological sort)
3. **All tasks have acceptance criteria** — Cannot verify completion without them
4. **All tasks have agent and moeExperts** — Required for delegation (added by `prd-to-tasks` step 6)
5. **Phase ordering is logical** — Foundation before features, core before polish

Run validation with the shared DAG validator:

```bash
bun .agents/scripts/validate-dag.ts tasks.json --summary
```

This checks: valid JSON, missing dependencies, circular dependencies, phase keys, unique IDs, agent/moeExperts fields, and agent summary consistency. With `--summary` it also prints the topological order, waves, and hour estimates.

**If validation fails**, the script exits with code 1 and prints a specific error. Stop and report the issues. Do NOT proceed until fixed.

### Step 3: Determine Execution Order

Use topological sort (Kahn's algorithm) to produce a valid execution order.
Group tasks into **waves** — same-wave tasks have no mutual deps, run in parallel:

| Wave | Tasks | Deps |
|------|-------|------|
| 1 | T001, T003 | (none) |
| 2 | T002, T004 | T001 |
| 3 | T005 | T002, T003 |
| ... | ... | ... |

Wait for all tasks in a wave to complete before launching the next wave.

### Step 4: Generate Prompt Files

Use the shared prompt generator — it auto-validates, includes PRD context, and orders tasks topologically:

```bash
bun .agents/scripts/generate-prompts.ts
```

For manual generation or custom logic, write one self-contained prompt file per task to `tasks/TASK-XXXX-prompt`.
These files are the **only input** subagents receive — they must contain
everything needed to implement the task autonomously.

> **Output convention:** Prompts go to `tasks/TASK-XXXX-prompt`.
> Subagent output goes to `tasks/TASK-XXXX.out`. DONE markers go to
> `tasks/TASK-XXXX.done`. Everything is versionable.

### Step 5: Spawn tmux Subagents in Detached Sessions (NEVER implement directly)

**This skill is a pure orchestrator — it never writes code itself.** Every
task is delegated to an isolated tmux session running `pi`. Use the shared
spawn script which handles base64 encoding, prompt files, and wave ordering:

```bash
# Spawn next ready wave (auto-detects pending tasks with met dependencies)
# Returns IMMEDIATELY — sessions run detached in background
bash .agents/scripts/spawn-wave.sh

# Spawn specific tasks
bash .agents/scripts/spawn-wave.sh T001 T003

# Preview what would spawn
bash .agents/scripts/spawn-wave.sh --dry-run
```

The script auto-generates prompts if missing, validates tasks.json, and skips
already-completed tasks (`.done` markers). **Each call spawns one wave and
returns immediately** — the tmux sessions run detached in the background.

> **⚠️ NEVER use `spawn-wave.sh --all` from within an agent session.**
> The `--all` flag blocks with `sleep` loops waiting for each wave, which
> will hit the tool timeout (300s). It is intended for humans running from
> a terminal. Agents must use the async wave-by-wave pattern below.

#### Async Wave-by-Wave Pattern

```bash
# 1. Spawn first wave (returns immediately)
bash .agents/scripts/spawn-wave.sh

# 2. Check status — poll until wave completes
bun .agents/scripts/status-tasks.ts --compact

# 3. When current wave is done, spawn the next wave
bash .agents/scripts/spawn-wave.sh

# 4. Repeat steps 2-3 until all tasks are done
```

#### Monitoring

```bash
bun .agents/scripts/status-tasks.ts          # full status table
bun .agents/scripts/status-tasks.ts --compact # one-line summary
bun .agents/scripts/status-tasks.ts --pending # only pending/blocked

# Peek at a specific task's live output
tmux capture-pane -t task-T005 -p | tail -20
```

#### Checking tmux sessions directly

```bash
tmux ls                                    # list all sessions
tmux ls | grep "task-"                     # list task sessions only
tmux kill-session -t task-T005             # kill a specific task session
tmux kill-session -t task-                 # kill all task sessions
```

### Step 6: Verify Completion

After each task, verify against acceptance criteria:

```
✅ T001: Set up project structure
  - ✓ Directory structure matches conventions
  - ✓ Type definitions compile
  - ✓ Configuration loads correctly

✅ T002: JWT token generation
  - ✓ Tokens generated with correct claims
  - ✓ Expired tokens rejected
  - ✓ Tampered tokens rejected
  - ✓ Validation under 5ms
```

If any criterion fails, fix before marking the task complete.

### Step 7: Handle Failures

If a task cannot be completed:

1. **Diagnose the issue** — Is it a code bug, missing info, design flaw?
2. **If fixable:** Fix and re-verify
3. **If blocked by missing info:** Use `grill-me` to ask the user
4. **If the approach is wrong:** Update the task or PRD and re-plan
5. **If dependency was done wrong:** Fix the dependency first, then retry

```bash
# Example: Task fails because dependency T002 has a bug
echo "Task T003 blocked: Middleware test fails because T002's token validation
doesn't handle edge case X. Going back to fix T002 first."

# Re-run T002 with the specific issue
pi -p "Fix T002 (JWT token validation): handle edge case X where [details].
Acceptance criteria: [original + new]"
```

### Step 8: Report Progress

Report progress after each phase completion:

```
Phase 1: Foundation — ✅ Complete (3/3 tasks, 8h estimated, 7.5h actual)

✅ T001 - Project setup (2h)
✅ T002 - JWT utils (4h)
✅ T003 - Auth middleware (1.5h — simpler than expected)

Phase 2: Core — 🔄 In Progress (1/3 tasks)

✅ T004 - Login endpoint (3h)
🔄 T005 - Registration endpoint (in progress...)
⏳ T006 - Password reset (waiting on T005)

Next: T005 → T006 → Phase 3 (Polish)
```

### Step 9: Final Report

When all tasks are complete, produce a synthesis report:

```markdown
# Implementation Complete: [Project Name]

**Completed:** YYYY-MM-DD
**Tasks:** 8/8 complete
**Estimated:** 32h | **Actual:** 30h

## Summary

[2-3 sentences about what was built]

## Phase Breakdown

### Phase 1: Foundation

- T001, T002, T003 completed

### Phase 2: Core

- T004, T005, T006 completed

### Phase 3: Polish

- T007, T008 completed

## Files Changed

- `src/auth/types.ts` — JWT type definitions
- `src/auth/utils.ts` — Token generation and validation
- `src/auth/middleware.ts` — Auth middleware
- `src/routes/auth/login.ts` — Login endpoint
- `src/routes/auth/register.ts` — Registration endpoint
- `src/routes/auth/reset.ts` — Password reset endpoint
- `tests/auth/` — Test suite (12 tests)
- `PRD-auth.md` — Updated with implementation notes

## Acceptance Criteria Status

All 24 criteria across 8 tasks verified.

## Known Issues / Follow-ups

- None

## Next Steps

- Deploy to staging for QA
- Run integration tests against staging
```

## Example: Full Orchestration Run (Async Pattern)

```bash
#!/bin/bash
# Pure orchestrator — validates, generates prompts, spawns one wave, exits.
# The agent polls status and spawns subsequent waves independently.
# NEVER implements code directly.

set -e
TASKS_FILE="tasks.json"
SCRIPTS=".agents/scripts"

echo "🚀 Orchestrating: $(bun -e "import { loadTasks } from './$SCRIPTS/lib/tasks-lib.ts'; const d = await loadTasks('$TASKS_FILE'); console.log(d.metadata.project)")"

# Step 1: Validate DAG
bun $SCRIPTS/validate-dag.ts "$TASKS_FILE" --summary

# Step 2: Generate prompt files (auto-validates, includes PRD context)
bun $SCRIPTS/generate-prompts.ts "$TASKS_FILE"

# Step 3: Spawn the first wave (returns immediately — sessions run detached)
bash $SCRIPTS/spawn-wave.sh

# The agent now reports wave status to the user, polls for completion,
# and spawns subsequent waves as they become available.
# Each wave is spawned with: bash $SCRIPTS/spawn-wave.sh
# Status is checked with: bun $SCRIPTS/status-tasks.ts --compact
echo "📡 First wave spawned. Poll with: bun $SCRIPTS/status-tasks.ts --compact"
```

## Best Practices

### DOs

- **Validate the graph first** — Don't start implementing a broken plan
- **Verify each task against acceptance criteria** — Don't mark done without checking
- **Fix problems at the source** — If T005 fails because T002 is buggy, fix T002
- **Report progress clearly** — Phase + task status so the user knows what's happening
- **Use explicit agent and moeExperts from tasks.json** — Read them directly, don't infer. They were assigned during `prd-to-tasks` step 6 for a reason.
- **Keep the user in the loop** — Especially when a task is blocked or needs clarification

### DON'Ts

- **Don't implement code yourself** — The orchestrator delegates 100% of work to subagents
- **Don't use `tmux send-keys` for prompts** — Quoting breaks on multi-line content. Use prompt files + `--append-system-prompt` instead
- **Don't embed prompts in shell scripts** — Use Python to write files; avoid heredocs with quotes
- **Don't skip dependencies** — Tasks built on broken foundations are broken
- **Don't run everything in parallel** — Respect the DAG; work wave by wave
- **Don't use `spawn-wave.sh --all`** — It blocks with `sleep` loops and hits tool timeouts. Always spawn one wave at a time and poll for completion
- **Don't ignore acceptance criteria** — They define "done"
- **Don't proceed after validation failure** — Fix the tasks.json first
- **Don't lose track of what's done** — Keep `IMPLEMENTATION_STATUS.md` updated

## Scaling: Large Task Sets (50+ Tasks)

For large projects:

- **Process phase by phase** — Complete all of Phase 1 before starting Phase 2
- **Batch parallel tasks** — Within a phase, run independent tasks concurrently (up to 3-5 at a time)
- **Pause between phases** — Report progress and let the user review before continuing
- **Use tmux sessions** — Long-running tasks in background tmux sessions
- **Track with a status file** — Write `IMPLEMENTATION_STATUS.md` to persist progress:

```markdown
# Implementation Status: User Auth System

Last Updated: 2026-04-27 14:30

## Phase 1: Foundation

- [x] T001: Project setup
- [x] T002: JWT utils
- [x] T003: Auth middleware

## Phase 2: Core

- [x] T004: Login endpoint
- [ ] T005: Registration (in progress)
- [ ] T006: Password reset
```

## Integration with Other Skills

```
create-prd    → Produces PRD
prd-to-tasks  → Produces tasks.json
implement-tasks → Executes tasks.json
    ├── Uses: spawn-subagents (delegate work to isolated pi instances)
    ├── Uses: mixture-of-experts (expert definitions, spawn/aggregate patterns)
    ├── Uses: terminal-multiplexer (for tmux session management)
    ├── Uses: grill-me (when blocked by ambiguity)
    └── Uses: project-files (for status tracking)
```

## Edge Cases

### Empty Task List

If `tasks.json` has zero tasks:

```
tasks.json has 0 tasks. Nothing to implement.
Was the PRD created? Run create-prd first.
```

### Single Task

For a single task, skip the full orchestration and just implement it with a lighter-weight review:

```
Only 1 task (T001). No dependencies. Implementing directly with architect + maintainer review.
```

Set up a focused MoE call with just 2 experts.

### Blocked by External Dependency

```
Task T003 depends on T000 (EXTERNAL: API credentials).
T000 is marked external/blocker. Cannot proceed past T000.

Options:
1. Wait for credentials (pause implementation)
2. Mock the external service for development (create a mock task)
3. Skip T003 and implement other independent tasks
```

### Failed Validation

If the tasks.json has issues, report them clearly:

```
❌ tasks.json validation failed:

1. T007 depends on T999 (does not exist)
2. Circular dependency: T004 → T006 → T004

Fix these before implementing. Suggested fixes:
- T007: Did you mean T009?
- T004/T006: Remove one dependency direction
```

### User Interrupts Mid-Implementation

Save progress and create a handoff:

```bash
# Write current state
cat > IMPLEMENTATION_STATUS.md << 'EOF'
# Implementation Status: Interrupted

Last Updated: 2026-04-27 15:00
Interrupted during: Phase 2, Task T005 (Registration endpoint)

## Completed
- [x] T001-T004

## In Progress
- [ ] T005 (partially done — auth utils written, endpoint stubbed)

## Not Started
- [ ] T006-T012
EOF

echo "Progress saved to IMPLEMENTATION_STATUS.md"
echo "Resume with: 'continue implementing tasks'"
```