# Build Plan — Agent Execution Guide **Audience:** the AI coding agent (and any human supervising it) **Companions:** [`BUILD-SPEC.md`](./BUILD-SPEC.md) (what), [`ARCHITECTURE.md`](./ARCHITECTURE.md) (how) **Rule of this document:** if a unit is not on this list, it is not in scope yet. --- ## 1. How to use this plan You are building **one unit at a time**, top to bottom, within a phase. Each unit is a vertical slice that ends in something you can run, test, and commit. You do not start unit N+1 until unit N's **check** passes and you have appended a line to `.agent/PROGRESS.md`. ```text ┌─ pick next unit ──────────────────────────────────────────────┐ │ 1. Read: this unit's card + the files listed in "Touch" │ │ 2. Write the smallest code that satisfies "Done when" │ │ 3. Run the unit's check command │ │ 4. Pass → append to PROGRESS.md → commit → next unit │ │ Fail → attempt++ (max 3, see §3) → fix the cause, not the │ │ assertion → re-run only the failing check │ └───────────────────────────────────────────────────────────────┘ ``` **Never** read the whole repository at the start of a unit. The unit card tells you exactly which files matter. That is the context discipline that keeps you inside the window. --- ## 2. The five rules that prevent looping These are hard rules, not preferences. 1. **One unit, one concern.** If you find yourself editing a fifth file, stop: the unit is split wrongly. Revert to the last commit and report that it needs splitting (see §10). 2. **Three strikes, then stop.** Three failed attempts at the same check, or the **same error message twice in a row**, means you stop and write a handoff packet (§4.3). Do not "try one more thing." 3. **Change the approach, never the assertion.** A failing test is fixed by changing production code. Deleting an assertion, skipping a test, adding `any`, or loosening a type to make a check pass is a **build failure**, not a pass. 4. **Do not re-verify what already passed.** Run the unit's check, not the whole suite, not every check you know. The full gate runs at checkpoints only (§8). 5. **No opportunistic refactoring.** Not the file you touched, not "while I'm here." Improvements go in `.agent/BACKLOG.md` and get scheduled later. --- ## 3. The anti-loop protocol (mechanical) Keep an **attempt ledger** for the current unit, in the session and in `PROGRESS.md`: ```text UNIT D5 · attempt 1 · `pnpm test src/domain/conflicts.test.ts` FAIL: expected 1 conflict, got 0 — blackout range end exclusive UNIT D5 · attempt 2 · same command FAIL: expected 1 conflict, got 0 — blackout range end exclusive ← SAME SIGNATURE → STOP. Two identical errors = my model of the bug is wrong, not my patch. ``` **Escalation ladder — do these in order, not in a loop:** | Attempt | What you may change | | --- | --- | | 1 | Implement the obvious solution. | | 2 | Change **one** assumption. Add a failing unit test that isolates the smallest case (one date, one user) before touching the fix. | | 3 | Reduce scope: implement the simplest correct version, mark the rest as `// TODO(unit-id)` and file it in `BACKLOG.md`. | **Hard stops — write the handoff packet and end the turn:** - Same error twice. - A check fails that is **outside** your unit's file list (you broke something you shouldn't have touched). - You need a schema change that is not in your unit's card. - You are about to add a dependency. - You have read more than ~6 files for one unit. - The unit has grown past ~400 changed lines. Stopping with a clear packet is a **success**. Grinding is the failure mode this document exists to prevent. --- ## 4. Unit contract ### 4.1 Every unit card has these fields | Field | Meaning | | --- | --- | | **Goal** | One sentence, in user-visible terms. | | **Depends** | Unit IDs that must be green first. | | **Touch** | The only files you may create/modify. A new file is listed as new. | | **Done when** | The exact command run + expected observable. | | **Don't** | Known temptations for this unit (caching, refactors, extra states). | | **Size** | S ≈ 1 file / <150 LOC · M ≈ 2–4 files / <400 LOC. **There are no L units.** | ### 4.2 Definition of Done (applies to every unit) - [ ] The unit's check command exits `0`, output pasted into the commit body. - [ ] `pnpm typecheck` passes (no `any`, no `@ts-ignore`, no `as unknown as`). - [ ] `pnpm lint` passes with zero new suppressions. - [ ] No new file outside **Touch**. - [ ] If user-facing: renders at 360 px width and is keyboard-reachable. - [ ] If it touches a domain rule: that rule has a unit test named after it. - [ ] `.agent/PROGRESS.md` has a new line (append-only). - [ ] One commit, message `unit(): `. ### 4.3 Handoff packet (when you stop) Write this to `.agent/HANDOFF.md`, commit nothing else, and end your turn: ```markdown ## Unit — blocked **Goal:** … **Check:** `pnpm test …` → exits 1 **Exact error:** **Attempts:** 1. changed X → same error 2. changed Y → same error **What I believe is true:** (3 bullets max, with file:line evidence) **What I did not try, and why:** (so the next agent doesn't repeat) **Files touched:** … **Recommended next step:** split unit / reduce scope to / human decision needed on ``` ### 4.4 The progress ledger — `.agent/PROGRESS.md` Append-only, one line per unit. This survives context loss and is the first thing any new session reads. ```markdown ## Done - A1 scaffold — `pnpm build` green — 2026-11-18 - A2 schema core — `pnpm db:migrate && pnpm db:seed` green — 2026-11-18 - A3 auth — `pnpm test src/auth` green (401/403/200) — 2026-11-18 ## In progress - (none) ## Decisions (do not re-litigate) - Money/percent stored as integers. Dates: `occurs_on` = local date, `starts_at` = UTC. - Scoring lives in `src/domain/**` as pure functions. No DB access there. ``` --- ## 5. Dependency map ```mermaid flowchart TD A1[A1 scaffold] --> A2[A2 schema] A2 --> A3[A3 auth] A3 --> A4[A4 shell] A4 --> B1[B1 approvals] B1 --> B2[B2 profile] A2 --> B3[B3 catalog] B3 --> C1[C1 skills] C1 --> B4[B4 positions] B4 --> D1[D1 services] A2 --> D1 D1 --> D2[D2 instances] D2 --> D3[D3 slots] B2 --> D4[D4 blackouts] D3 --> D5[D5 conflicts] D4 --> D5 C1 --> C4[C4 readiness] C3[C3 matrix] --> C4 D5 --> D6[D6 candidates] C4 --> D6 D3 --> D7[D7 grid] D6 --> D8[D8 assign] D7 --> D8 D8 --> D9[D9 auto-fill] D8 --> D10[D10 publish] D10 --> E1[E1 outbox] E1 --> E2[E2 dispatcher] E2 --> E3[E3 email] E3 --> E4[E4 magic links] E1 --> E5[E5 sms] D10 --> G2[G2 ics] E3 --> F1[F1 richtext] F1 --> F3[F3 courses] F3 --> F4[F4 gating] A2 --> G1[G1 swaps] D8 --> G1 A2 --> G3[G3 dashboard] D10 --> G4[G4 exports] A3 --> H1[H1 ai gateway] ``` **Parallel-safe pairs** (different file trees, no shared schema change): `E-track × F-track`, `G2 × E-track`, `C2 × D-track`. Never parallelize two units that both write `src/db/schema.ts`. --- ## 6. Phase A — Foundation (units A1–A4) **Phase demo:** a signed-in user sees an empty shell at 360 px. | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | A1 | Scaffold: Next 15 + TS strict, Tailwind, shadcn init, Drizzle, Zod, Vitest, lint, CI | M | — | `pnpm build && pnpm typecheck && pnpm test` all exit 0 with one placeholder test | | A2 | Schema core: users, roles, services, instances, slots, assignments + migration + seed script | M | A1 | Drop DB → `pnpm db:migrate && pnpm db:seed` exits 0; `SELECT count(*) FROM service_instances` > 0 | | A3 | Auth: magic-link sign-in (dev console transport), session cookie, `requirePermission()` chokepoint, role enum | M | A2 | `pnpm test src/auth` green: 401 anonymous, 403 volunteer on `/admin`, 200 admin | | A4 | App shell: layout, nav (5 tabs mobile / rail desktop), tokens, error + empty states, `/api/health` | M | A3 | `pnpm test:e2e --grep shell` passes at 360 px viewport | **A2 note:** write the schema in the order users → roles → services → instances → slots → assignments. Do not add the catalog tables yet (B3). Resist "while I'm in the schema." --- ## 7. Phase B — People, catalog, positions (units B1–B4) **Phase demo:** an admin invites someone, approves them, and defines a position with a skill requirement. | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | B1 | Invite → pending → approve/deny, with status transitions and an outbox row (console) | M | A3 | Test: invite creates `pending_approval`; approve flips to `active`; denied user cannot sign in | | B2 | Profile + notification prefs + SMS consent capture (timestamp, source, ip) | S | B1 | Test: changing phone resets consent; consent fields populated on opt-in | | B3 | Catalog CRUD: categories, vendors, technologies, functions (deactivate, not delete; slug frozen) | M | A2 | Test: create → rename keeps slug → deactivate hides from pickers but row persists | | B4 | Positions: CRUD + requirements editor (skill, weight, required level, core) | M | B3, C1 | Test: position with no core skill refuses to save as publishable | **B3 is a read-heavy unit.** Do not build the `/admin/catalog` UI yet — data layer + minimal form only. The six-tab UI arrives in I2 if time allows; the API is what other units need. --- ## 8. Phase C — Skills and competency (units C1–C6) **Phase demo:** a volunteer rates sliders, an admin sees a matrix and verifies a level. | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | C1 | Skills composer: category + optional technology + optional function → dedupe_key, name prefill | M | B3 | Test: duplicate (category, tech, function) rejected; null tech creates generic skill | | C2 | Volunteer `/profile/skills`: sliders with anchor labels, verified chip, growth request button | M | C1, B2 | E2E: move slider → save → reload shows value; verified level unchanged | | C3 | Admin skills matrix: grid, filters, verify-level modal writing `skill_assessments` | M | C1 | Test: verify writes assessment row + updates level; audit row exists | | C4 | **Readiness scoring** — pure function in `src/domain/readiness.ts` | S | C1, B4 | `pnpm test readiness` green on 6 cases: no skills → blocked · all core at required → 100 · core below required → blocked + missing[] · non-core gaps → score < 100 · null comfort → level-only score · expert + 100 comfort → expert | | C5 | Mentor designation: opt-in, admin approval, per-skill `mentor_ready` | S | C3 | Test: expert without opt-in is not mentor_ready; opt-in without admin approval is not either | | C6 | Growth goals + shadow pairing validation (a shadow requires a mentor in the same instance) | M | C5, D3 | Test: shadow slot without paired mentor rejects at the data layer | **C4 is the single most reused function in the app** (picker, auto-fill, matrix, dashboard). Write it pure, no DB, no imports from `src/db`. If it needs data, pass it in. --- ## 9. Phase D — Scheduling (units D1–D10) **Phase demo:** a full week built on the grid and published. | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | D1 | Service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth) | M | B4 | `pnpm test recurrence` green on 5 named cases: spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable | | D2 | Instance generator (idempotent, 16-week window) on a cron route | M | D1 | Run twice → instance count unchanged; published instance untouched | | D3 | Slot materialization from `position_skills`/requirements (headcount, call time) | S | D2 | Test: Audio headcount 2 creates 2 slots with correct call_time | | D4 | Blackout CRUD + `isUnavailable(user, date)` pure function, ranges + rrule | M | B2 | `pnpm test availability` green incl. inclusive-end case | | D5 | **Conflict engine** — pure function, hard vs soft conflicts | M | D3, D4 | Table-driven test: 10 cases, one per rule in BUILD-SPEC §7 | | D6 | Candidate ranking service (availability filter → readiness → score) | M | D5, C4 | Test: away user excluded; unqualified blocked with reason code; ordering deterministic | | D7 | Grid UI, read-only: rows = instances, cols = positions, week nav | M | D3 | E2E: renders a seeded week; no console errors | | D8 | Assign / unassign / clear with optimistic update + rollback toast | M | D7, D6 | E2E: assign → appears immediately; forced failure rolls back with a message | | D9 | Auto-fill proposals (reuse D6) + "apply all" | M | D8 | Test: proposals are deterministic for a fixed seed; apply is a no-op on second run | | D10 | Publish / unpublish: transaction, validation, audit row, **no notifications yet** | M | D8 | Test: publish with open slots blocked unless `allowGaps`; re-publish is idempotent | **D5 is the highest-risk unit in the project.** Isolate it: pure function, table-driven tests, zero UI, zero DB. If it takes more than 3 attempts, ship the hard-conflict subset and mark soft conflicts `TODO(D5)`. **D10 deliberately does not send anything.** Notification wiring is E1. This separation is why an email outage can never block a schedule. --- ## 10. Phase E — Communications (units E1–E7) **Phase demo:** publish → exactly one email arrives; confirm link works. (E5 SMS is deferred — launch is email-only.) | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | E1 | Outbox: enqueue on publish, `dedupe_key` unique, status enum | M | D10 | Test: enqueue twice → 1 row; declined assignment cancels its rows | | E2 | Dispatcher: cron tick, guards (dedupe → assignment active → consent → quiet hours), retry/backoff | M | E1 | Test with fake clock: 3 failures → `failed`; quiet-hours SMS reschedules to 08:00 | | E3 | Email: React Email templates, Postmark adapter, console transport in dev | M | E2 | `pnpm test notifications/email` green; dev send writes to `/tmp/outbox` | | E4 | Magic-link respond: signed token, GET renders, POST mutates, single use | M | E3 | Test: GET does not change state; second POST with same jti rejects | | E5 | SMS: Twilio adapter, STOP/HELP webhook, email fallback on failure | **Deferred** — launch is email-only. Reuses E2's dispatcher with no rework. | — | — | | E6 | Admin notification log + retry + "send test to me" | M | E3 | E2E: failed row retries and reaches `sent` against the fake transport | | E7 | Reminder rules CRUD (the Friday row: offset −2, 18:00, email+sms) | S | E1 | Test: changing offset changes computed `scheduled_for`; no code change needed | **The reminder acceptance test is the project's most important check.** Run it at the E-phase checkpoint, not before. --- ## 11. Phase F — Rich text and training (units F1–F6) | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | F1 | TipTap editor + schema allowlist + **server-side** JSON→HTML render + sanitize | M | A4 | Test: script/iframe payload stripped; `javascript:` link rejected | | F2 | Upload signing + R2 write + image node with required alt text | M | F1 | Test: oversized file rejected; missing alt blocks publish | | F3 | Courses/lessons CRUD + viewer + progress (dwell / 90% watched) | M | F1 | E2E: complete a lesson → progress ring updates | | F4 | Gating: eligibility from verified level + required course completion | S | F3, C4 | Test: incomplete course keeps user out of picker; override requires reason | | F5 | Announcements + pages (audience targeting, expiry) | S | F1 | Test: audience filter excludes non-matching role | | F6 | Run sheets per instance + print stylesheet | S | F1, D3 | `pnpm test:e2e --grep "print"` — one service per page, headers repeat | **F1 is where sanitization is decided.** Render on the server with the same schema. Never store client HTML as truth. If you are tempted to `dangerouslySetInnerHTML` the client payload, stop — that is a security bug, not a shortcut. --- ## 12. Phase G — Swaps, calendar, dashboard, exports (units G1–G5) | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | G1 | Swaps: request, peer accept, coordinator approve, reassignment + notifications | M | D8, E3 | Test: original stays responsible until approval; both parties notified | | G2 | ICS feed with opaque token, revocable | S | D10 | Fetch feed → valid VEVENT with call time; revoke → 404 | | G3 | Dashboard cards (coverage, gaps, approvals, cron health) | M | D10, E2 | E2E: seeded gaps show red; heartbeat older than 20 min shows banner | | G4 | Export engine: **CSV first**, shared dataset query, formula-injection guard | M | D10 | Test: `=cmd()` cell exported as `'=cmd()`; coordinator scope filters rows | | G5 | XLSX + PDF renderers on the same datasets | M | G4 | Open artifact in a reader; header row frozen / booth sheet is one page | **Split G4/G5 on purpose.** CSV proves the dataset and the security guard; XLSX and PDF are formatting on top. Two smaller units instead of one large one. --- ## 13. Phase H — AI (units H1–H4, optional) | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | H1 | AI gateway: server-only client, model allowlist, per-user daily cap, `ai_runs` logging, kill switch | M | A3 | Test: flag off hides every affordance; cap returns a friendly refusal | | H2 | Ask-the-schedule: 3 read-only tools over existing services | M | H1, D6 | Test: unknown intent returns "I can't answer that" instead of inventing | | H3 | Draft copy into the editor (JSON in, JSON out, schema-validated) | S | H1, F1 | Test: output that fails schema is rejected, not rendered | | H4 | Explain auto-fill from the score breakdown | S | H1, D9 | Test: explanation cites the actual score components | **H-phase rule:** if any H unit is attempted before phase D–F are green, stop. AI is additive and must never be on the critical path. --- ## 13.5 Phase J — Events & photography (units J1–J6) Run after Phase G. Depends on scheduling, notifications and rich text being green. **Not** a parallel scheduling system: it reuses the picker, the conflict engine and the outbox. | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | J1 | `event_types` + `events` CRUD (rich-text description and brief fields) | M | B3, F1 | Test: create event → appears in list → brief renders sanitized | | J2 | `slots.event_id` migration + `event_positions` materialization (CHECK: exactly one of instance/event) | M | J1, D3 | Migration runs on a seeded DB; CHECK rejects a slot with both or neither | | J3 | Event assignment UI reusing D6 ranker + D8 assign mutations | M | J2, D8, C4 | E2E: assign photographer → conflict rules apply → overlap blocked | | J4 | Event notifications via existing rules (`event.assigned`, −2 d reminder, `event.unfilled`) | S | J3, E7 | Test: publish event → 1 email + 1 SMS; unfilled alert at T-7 | | J5 | Brief page `/events/[id]/brief` (phone, printable, tap-to-call) | S | J1, F6 | Renders at 360 px, printable, no console errors | | J6 | Status flow + deliverable-due flag + dashboard tile | S | J3 | Test: past event stuck at `covered` flags after `deliverable_due` | ### Deferred — Phase K (media library, phase 2) Do **not** start these until the launch gate passes and the church has agreed a retention policy and storage budget. | ID | Unit | Notes | | --- | --- | --- | | K1 | Multipart upload + `upload_batches` + checksum dedupe | Resumable; Worker signs only | | K2 | Gallery with JPEG proxies + pagination | Browsers cannot render RAW | | K3 | RAW download with `media.raw_download` + `media_downloads` audit | Signed, 15 min, single use | | K4 | Retention job (delete originals, keep rows) | Default 90 days | | K5 | Release/consent gate before gallery publishing | Minors; blocks publish | ## 14. Phase I — Launch (units I1–I4) | ID | Unit | Size | Depends | Done when | | --- | --- | --- | --- | --- | | I1 | Accessibility + mobile pass: focus order in the grid, labels, contrast, 44 px targets | M | D8, F3 | Axe scan on 5 volunteer routes: 0 critical; keyboard-only grid assign works | | I2 | Starter catalog seed + CSV import (dry run, row errors) | M | B3 | Import 3 bad rows → nothing written, errors listed by line | | I3 | Demo seed (6 volunteers, 8 weeks, 2 courses) for preview environments | S | A2 | `pnpm db:seed:demo` populates a browsable app | | I4 | Runbook + env docs + deploy check + backup/restore drill | S | all | Restore drill completed; README commands work from a clean clone | --- ## 15. Checkpoint gates Run the **full gate** only here — not per unit. | Gate | After | Commands | Must be true | | --- | --- | --- | --- | | **G1 Foundation** | A4 | `pnpm typecheck && pnpm lint && pnpm test && pnpm build` | All green; shell renders at 360 px | | **G2 Data** | B4 | + `pnpm db:reset && pnpm db:seed` | Schema rebuilds from zero; seed is idempotent | | **G3 Scheduling** | D10 | + `pnpm test:e2e --grep schedule` | A full week publishes; no notifications sent | | **G4 Comms** | E7 | + the **reminder acceptance test** | One email, correct call time, second cron run sends nothing (SMS variant added when E5 is built) | | **G5 Content** | F6 | + `pnpm test:e2e --grep training` | Lesson completes; gating blocks an untrained assign | | **G5.5 Events** | J6 | `pnpm test:e2e --grep events` | An event is staffed, briefed, reminded and marked delivered | | **G6 Feature-complete** | G5 | full suite + manual pass | Every Must in BUILD-SPEC §3.1 demoed on a phone | | **G7 Launch** | I4 | full suite + restore drill | Clean-clone setup works; runbook accurate | **Gate output goes in the commit body.** A gate that fails does not get "re-run until green" — it gets a handoff packet. --- ## 16. Context budget — how to stay inside the window | Situation | Rule | | --- | --- | | Starting a unit | Read the unit card + only the files in **Touch** + one neighbour file if needed. Nothing else. | | Need to find something | `code_search` with a specific symbol; never `cat` a 600-line file. Use a line window. | | File over ~400 lines | Do not read it whole. Search for the symbol, read ±40 lines. | | Unit needs > 6 files | The unit is too big — split it before writing code. | | Re-deriving a decision | Check `PROGRESS.md` → *Decisions*. If it is not there, add it after deciding. | | Long tool output | Ask for exit codes and the first error, not the last 500 lines. | | Session feels heavy | Finish the current unit, commit, write the ledger line, stop. The next session resumes from `PROGRESS.md`. | **Stopping at a clean commit is always better than starting a unit you cannot finish.** Half-built units are what cause loops, because the next session cannot tell what was intended. --- ## 17. Commits, branches, rollback - One commit per unit: `unit(): ` + gate output in the body. - Branch per phase (`phase-d-scheduling`), merged at the gate. Never work across two phases in one branch. - Before any risky refactor inside a unit: commit the green state first, so `git reset --hard` returns you to something that works. - If a unit is abandoned, **revert it** rather than leaving partial code. `PROGRESS.md` records that it was reverted and why. --- ## 18. What "done" means for the whole project The plan is complete when every gate has passed and these three things are true: 1. A volunteer can go invite → approve → train → shadow → signed off → scheduled → reminded → confirmed without an admin touching anything after publish. 2. Two admins build and publish a week in under 10 minutes, measured. 3. An admin can add a new position, a new technology and a new skill, and schedule against them, with no deploy. Everything else is a follow-up ticket in `.agent/BACKLOG.md`.