📐 Agent 2

Technical Planning Agent

The Technical Planning Agent transforms the Discovery spec into a complete implementation blueprint — TDD, interface contracts, data schema, task graph, machine-readable Zod schemas, and a full parallelism map — all produced in a single pass triggered by !plan.

Planning Output Artifacts

Triggered by !plan. The Planner produces the complete artifact set directly:

ArtifactPathContents
TDD.mdartifacts/build/Technical Design Document: architecture decisions, data flow, API design, error handling strategy, test contract requirements
INTERFACES.mdartifacts/build/API endpoint signatures, component prop interfaces, event schemas
SCHEMA.mdartifacts/build/Database schema with relationships, indexes, and migration strategy
TASK-GRAPH.mdartifacts/build/Ordered task list with dependencies, test contracts, acceptance criteria, and Parallelism Map
[module].contracts.tsartifacts/build/contracts/Zod schemas for every major data model and API response shape
openapi.yamlartifacts/build/contracts/OpenAPI 3.1 stubs for all declared endpoints
FILE_OWNERSHIP_MAP.mdartifacts/build/Every project file mapped to the task(s) that own it — used for Change Impact Tracking
DECISIONS.mdartifacts/build/Architecture decisions log including Pattern Library matches applied
HANDOFF.json v2artifacts/build/Updated with task_count, contracts_path, schema_hash, stack_versions, component_library

Machine-Readable Contract Layer

The Planner emits two contract types that create a ground truth for Builder and Verifier:

Zod Schemas

// artifacts/build/contracts/user.contracts.ts
import { z } from 'zod';

export const UserSchema = z.object({
  id: z.string().cuid(),
  email: z.string().email(),
  role: z.enum(['ADMIN', 'USER']),
  createdAt: z.coerce.date(),
});

export const CreateUserSchema = UserSchema.omit({ id: true, createdAt: true });
export type User = z.infer<typeof UserSchema>;

OpenAPI Stubs

# artifacts/build/contracts/openapi.yaml
openapi: "3.1.0"
info:
  title: "Project API"
  version: "1.0.0"
paths:
  /api/users:
    post:
      operationId: createUser
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateUser' }
      responses:
        "201":
          content:
            application/json:
              schema: { $ref: '#/components/schemas/User' }

Task Schema

Every task in TASK-GRAPH.md follows this schema, including the v3.0 parallelism and checkpoint fields:

### TASK-001: Set up authentication with NextAuth v5
**Status:** PENDING
**Task type:** auth
**Platform:** web
**Dependencies:** none
**depends_on:** none
**can_parallel:** false
**output_files:**
- src/lib/auth.ts
- src/app/api/auth/[...nextauth]/route.ts

**Acceptance criteria:**
- Users can sign in with Google OAuth
- Session is stored in database (not JWT)
- Unauthenticated requests to /api/protected return 401

**Test contract status:** REQUIRED

**Test contract:**
| # | Behavior description | Test type | Test file |
|---|---|---|---|
| TC-1 | Sign-in with valid credentials creates session | integration | tests/auth.test.ts |
| TC-2 | Unauthenticated request to /api/protected returns 401 | integration | tests/auth.test.ts |

**Gate commands:**
pnpm agent:check

**Checkpoint:** (written by Builder after commit_by_task.py — git SHA + timestamp)
FieldValuesPurpose
task_typeapi | auth | data | infra | ui | config | feature | cicd | obsDetermines which scripts run and which Pattern Library queries apply
depends_on[TASK-NNN] or "none"Explicit dependency edges for batch ordering
can_paralleltrue | falseWhether this task may execute concurrently with siblings in the same batch
output_files[list of files]Used by parallel_runner.go for write-conflict detection
Checkpointgit SHA + timestampWritten by Builder after commit_by_task.py — enables !replay TASK-NNN

Standard Infrastructure Tasks

The Planner automatically injects standard infrastructure tasks into every TASK-GRAPH based on project type. These tasks are never omitted — they are appended after the human-authored feature tasks.

CI/CD Tasks (all project types)

Task IDNameOutput
TASK-CICD-1CI workflow.github/workflows/ci.yml
TASK-CICD-2Deploy workflow.github/workflows/deploy.yml
TASK-CICD-3Security scan workflow.github/workflows/security.yml
TASK-CICD-4GoReleaser config.goreleaser.yaml — Linux CLI projects only

Observability Tasks — HTTP API projects

Task IDNameOutput
TASK-OBS-1Structured loggerJSON logging middleware on all routes
TASK-OBS-2Metrics endpointGET /metrics (Prometheus format)
TASK-OBS-3Health & readiness probesGET /health, GET /ready
TASK-OBS-4OpenTelemetry tracingOTLP exporter configured

Observability Tasks — CLI projects

Task IDNameOutput
TASK-OBS-1Verbose / debug flags--verbose and --debug global flags with leveled output
TASK-OBS-2Log file output--log-file <path> flag writing structured JSON log

Spec Validation Gate

After Phase B completes, spec_validate.py runs automatically. It must exit 0 before !build is unlocked. The script performs seven checks:

1 Every feature in feature-spec.md has at least one owning task in TASK-GRAPH.md
2 No task has a circular dependency (DAG validation)
3 All API endpoints in INTERFACES.md appear in openapi.yaml
4 All database tables in SCHEMA.md have a corresponding Zod schema in contracts/
5 Every task has at least one test contract (TC row) for Standard and Complex tier projects
6 FILE_OWNERSHIP_MAP.md covers all files listed in task output_files fields
7 HANDOFF.json v2 is present and valid JSON with required fields
🚨
Spec validation failure blocks !build

If spec_validate.py exits non-zero, the Orchestrator refuses to unlock !build and displays the failing checks. The Planner must fix the artifacts before the gate can open.

Schema Change Safety

Whenever SCHEMA.md is modified during Planning or mid-build, migration_safety.py generate runs automatically. It produces a Migration Risk Report with:

  • Delta between old and new schema (added/removed/modified columns and tables)
  • Risk severity per change: LOW | MEDIUM | HIGH
  • Bidirectional SQL: forward migration and rollback SQL
  • Data loss assessment for each destructive change
⚠️
HIGH severity risks block the pipeline

Any schema change classified HIGH (e.g., dropping a column with existing data, changing a column type non-losslessly) blocks the pipeline until the human issues !migration-approve or !migration-cancel. See Orchestrator — Migration Sub-Commands.

FILE_OWNERSHIP_MAP

The FILE_OWNERSHIP_MAP.md maps every project file to the task(s) responsible for it. This powers Change Impact Tracking in Agent 3 — when a file is modified, the Builder looks up which other tasks own files in the same module and re-runs their tests.

| File | Owning Task(s) |
|---|---|
| src/lib/auth.ts | TASK-001 |
| src/app/api/auth/[...nextauth]/route.ts | TASK-001 |
| src/components/LoginForm.tsx | TASK-003 |
| src/lib/db.ts | TASK-002, TASK-001 |

Pattern Library Integration

At activation, the Planner queries PATTERN_INDEX.md with the project's stack keywords. Matched patterns are recorded in DECISIONS.md and applied directly in planning without re-solving known problems.

Example: a project with nextjs + prisma + nextauth will automatically apply:

  • PATTERN-001 — NextAuth v5 + Prisma database sessions
  • PATTERN-002 — Zod env validation at module load time
  • PATTERN-003 — Prisma singleton with globalThis hot-reload guard

Planning Validation Checklist

Before emitting Phase B artifacts, the Planner self-validates:

CheckPass condition
Every task has acceptance criteriaNo task row is missing the "Acceptance criteria" field
Every Complex-tier task has test contractsTest contract status is REQUIRED and at least one TC row exists
No circular task dependenciesTASK-GRAPH has no cycles
All spec features mapped to tasksEvery feature-spec.md feature has at least one owning task
Contracts cover all API endpointsEvery endpoint in INTERFACES.md appears in openapi.yaml
FILE_OWNERSHIP_MAP is completeEvery planned file has at least one owning task