Files
glenloch-media/.agent/PROGRESS.md
2026-11-20 04:07:02 +00:00

1118 lines
116 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# PROGRESS
Build log for Media Team Hub. One unit per commit, top to bottom. Append after each passing check.
---
## A1 — Foundation scaffold — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** Next.js 15 + TS strict, Tailwind 4, shadcn/ui (Radix), Drizzle, Zod, Vitest, lint, CI.
**Delivered:**
- Next.js 15, React 19, TypeScript strict, Tailwind 4, ESLint 9
- shadcn/ui initialized manually (Radix + CSS variables) — `components.json`, `src/lib/utils.ts`, theme in `globals.css`
- Drizzle + `postgres` driver + Zod; `src/db/index.ts` client, `src/db/schema.ts` placeholder (A2 fills it)
- Vitest (jsdom-capable) with a passing `cn()` test
- GitHub Actions CI (typecheck → lint → test → build)
- **Portable container stack** (user request): multi-stage Dockerfile (non-root, pnpm), `docker-compose.yml` (app + Postgres), `.dockerignore`
**Verification (all exit 0):**
- `pnpm typecheck` ✓
- `pnpm lint` ✓
- `pnpm test` ✓ (3 tests)
- `pnpm build` ✓
- `docker compose build app` ✓
- Container serves HTTP 200 on :3000, title "Media Team Hub" ✓
**Port audit (nothing else touched):** app → host **3000**; Postgres → host **5433** (local 5432 already taken). Confirmed free before binding.
**Decisions recorded in README.md ("Decisions recorded from your answers"):**
- Services: Sun 10:30 AM + 5:30 PM, `America/New_York` (DST-safe, changeable as data)
- One person per role
- Admin = full control; Coordinator = everything except design/theme + admin/settings
- CSV-only migration
- **Email-only at launch; SMS (Twilio + 10DLC) deferred**
**Stack change from docs:** docs target Cloudflare Workers (D1/R2/Cron Triggers — not portable). For portability we use standard Next.js Node container + Postgres + local media volume + node cron worker. Domain logic, data model, and UI are unchanged.
**Next: A2 — schema core.**
---
## A2 — Schema core — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** full data model + migration + seed.
**Delivered:**
- `src/db/schema.ts` — six core tables: `users`, `roles`, `services`, `serviceInstances`, `slots`, `assignments` (catalog tables from B3 excluded, per A2 scope).
- Spec rules enforced:
- **Rule 26** — `chk_slots_single_parent`: a slot belongs to exactly one of a service instance or an event (`CHECK ((service_instance_id IS NOT NULL) <> (event_id IS NOT NULL))`).
- **Rule 27** — `uq_active_assignment`: partial unique index, at most one non-terminal assignment per slot (`WHERE status IN ('proposed','confirmed','completed')`).
- Slug immutability (unique, no update path); deactivate-only (no hard delete); level changes via assessments; `created_at` audit on admin mutations; `America/New_York` default tz, stored UTC.
- `src/lib/uuid.ts` — UUIDv7 generator (RFC 9562).
- `src/lib/tz.ts` — DST-safe local→UTC (`localToUtc`), `nextSundaysInTz`, `formatInTimezone`, etc.
- `src/db/seed.ts` — idempotent seed (ON CONFLICT DO NOTHING + re-fetch canonical DB rows): 3 roles, 2 services, next 2 Sundays × 2 services of instances, 12 slots, 6 users, round-robin assignments.
- Migration `drizzle/0000_loose_wendell_vaughn.sql` (+ `0001` for the two added unique constraints).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (3) · `pnpm build` ✓
- Drop DB → `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (exits 0)
- `SELECT count(*) FROM service_instances` = 4 (> 0) ✓
- Re-run seed is idempotent: stable counts (4/6/3/2/12/12), exit 0 ✓
- CHECK constraint rejects both-NULL and both-NOT-NULL slots; accepts exactly-one ✓
- Partial unique index rejects duplicate confirmed assignment for a slot ✓
- DST-safe: 9:00 AM America/New_York → `2026-11-25 14:00:00+00` (EST) ✓
**Bugs fixed this phase (recorded for future reference):**
- `.references()` takes a **column** (`() => services.id`), not a table.
- `one`/`many` are `relations()` callback params, not imports.
- CHECK XOR needs parentheses: `(a IS NOT NULL) <> (b IS NOT NULL)` — bare `a IS NULL <> b IS NULL` parses as `boolean <> text`.
- `drizzle-kit 0.31.11 generate` requires an existing `meta/_journal.json`; start from `{version, dialect, entries: []}` to diff a fresh schema.
- `ON CONFLICT DO NOTHING` needs a full unique index on its target (partial indexes don't qualify as arbiters).
- Seed must re-fetch canonical DB rows after idempotent inserts (fresh UUIDs otherwise break downstream FKs).
- `dateInTimezone` destructured `{y,m,d}` but `partsInTz` returns `{year,month,day}` — fixed.
**Next: A3 — auth (auth.js + credentials provider, admin/coordinator/volunteer roles).**
---
## A3 — Auth — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** magic-link sign-in (dev console transport), session cookie, `requirePermission()` chokepoint, role enum.
**Delivered:**
- `src/auth/roles.ts` — `SystemRole` type + helpers (`isAdmin`, `isCoordinator`, `isLeader`, `assertSystemRole`).
- `src/auth/permissions.ts` — feature-scoped permission matrix from the ARCHITECTURE §2.3 capability table, `hasPermission()`, `AuthError` (carries HTTP 401/403), `requirePermission(user, perm)` chokepoint.
- `src/auth/magic-link.ts` — dev console transport: `getOrCreateUser` (auto-activates unknown emails when `AUTO_ACTIVATE_NEW_USERS` is on — dev convenience; flip to `"false"` for the B1 approval flow), `signMagicToken`/`verifyMagicToken` (jose HS256), `requestMagicLink` (prints the sign-in link to the console).
- `src/auth/config.ts` — Auth.js v5 Credentials provider (`magic-link`) + JWT session carrying `systemRole`.
- Routes: `/api/auth/[...nextauth]`, `/api/dev/magic-link` (POST `{email}`), `/api/dev/complete` (GET `?token=…`), `/api/admin` (chokepoint), and `/login` (magic-link sign-in UI).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17 tests) · `pnpm build` ✓
- **Acceptance** `pnpm test src/auth` green: 401 anonymous, 403 volunteer on `/admin`, 200 admin ✓
- Runtime smoke test (dev server + Postgres on :5433):
- `GET /api/admin` (no session) → 401 `UNAUTHORIZED` ✓
- `POST /api/dev/magic-link {email}` → 200, creates user (volunteer/active), returns + logs the sign-in link ✓
- `GET /api/dev/complete?token=…` → 200, token verified, session established ✓
- User persisted in DB as `active` ✓
- `GET /login` → 200, renders ✓
**Decisions:**
- **Auto-activate new emails in dev** (`AUTO_ACTIVATE_NEW_USERS`, default on) so a volunteer can sign in as anyone without admin setup; admin can flip to `"false"` to require approval (B1).
- **Auth.js v5** (matches the docs' "Auth.js"; portable, no SaaS lock-in). JWT sessions, no DB adapter needed. (auth.js v5 ships as `next-auth@beta`; the `@auth/next` scope isn't published yet.)
- **`/admin` requires `admin.settings`** (admin-only) — matches the spec's `/admin/*` pages being admin-only.
**Bugs fixed this phase (recorded for future reference):**
- Auth.js v5 session config uses `session.strategy: "jwt"`, not `session.jwt`.
- `req.json()` was unreliable here; `req.text()` + `JSON.parse` is the robust body read.
- An object schema must be parsed as an object: `bodySchema.safeParse({ email })`, not `safeParse(email)`.
- Turbopack dev + a production `.next/` from `pnpm build` conflict on `_buildManifest.js.tmp`; `rm -rf .next` before `next dev`.
**Next: A4 — app shell (layout, nav, tokens, error + empty states, `/api/health`).
---
## A4 — App shell — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** layout, nav (5 tabs mobile / rail desktop), tokens, error + empty states, `/api/health`.
**Delivered:**
- `src/app/(app)/layout.tsx` — app shell wrapper; `src/components/app/nav.tsx` — 5 nav tabs (mobile tab bar + desktop rail); `src/components/app/app-layout.tsx`, `src/components/app/state-message.tsx` (tokens + error/empty states).
- 5 shell pages: `schedule`, `announcements`, `roster`, `training`, `settings`.
- `src/app/api/health/route.ts` — `GET /api/health -> { ok: true }`.
- Playwright e2e `e2e/shell.spec.ts` + `playwright.config.ts` (webServer builds + starts the app; `reuseExistingServer`).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17) · `pnpm build` ✓
- `pnpm test:e2e --grep shell` → **4/4 pass** at 360 px viewport (the A4 "Done when"):
- renders the shell with 5 nav tabs at 360 px ✓
- shows the desktop rail at desktop width ✓
- redirects unauthenticated users away from the shell ✓
- `/api/health` returns ok ✓
**A4 blocker — root cause + fix (recorded for future reference):**
- **Reported** as `/api/dev/complete` returning HTTP 000 / connection reset. That was a **curl/shell-quoting artifact** in the handoff's test script, not an app bug.
- **Real symptom:** the complete response carried **no `Set-Cookie`**, so no session was established and every `/schedule` 307-redirected to `/login`; the two shell e2e tests failed (nav tabs never rendered).
- **Root cause:** `[auth][error] UntrustedHost`. Auth.js v5's `assertConfig()` checks `config.trustHost` **before** `setEnvDefaults()` applies its env default, and that default only derives `trustHost` from `AUTH_URL`/`AUTH_TRUST_HOST`/`VERCEL`/`CF_PAGES`/`NODE_ENV !== "production"` — **not** `NEXTAUTH_URL`. In `pnpm start` (production) with no `AUTH_URL`, `trustHost` stayed `false`, so the magic-link callback was rejected and no session cookie was written.
- **Fix:** `src/auth/config.ts` sets `trustHost: true` explicitly (documented fix for `UntrustedHost`; localhost app behind a reverse proxy). Rebuild required for `pnpm start`. Verified: complete response now sets `authjs.session-token`, `/schedule` returns 200, all 4 e2e pass.
**Next: B1 — invite → pending → approve/deny, with status transitions and an outbox row (console).**
---
## B1 — Invite → pending → approve/deny — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** invite creates `pending_approval`; approve flips to `active`; denied user cannot sign in; an outbox row (console).
**Delivered:**
- `src/auth/invites.ts` — the unit. Pure transition rule `nextUserStatus(current, action)` (invite→pending_approval, approve→active, deny→denied) and `isSignInEligible(user)` (active && not deactivated, mirrors the Auth.js `authorize` guard), both exported and unit-tested. Thin DB wrappers `inviteUser`, `approveUser`, `denyUser` around the rule. `enqueueOutbox()` = launch console transport (ARCHITECTURE §3.4), a structured greppable line — swapping in Postmark later is a change here only.
- Routes: `src/app/api/dev/invite/route.ts` (POST { email, invitedBy? }), `src/app/api/dev/approve/route.ts` (POST { userId, approvedBy? }), `src/app/api/dev/deny/route.ts` (POST { userId, deniedBy? }).
- `src/auth/invites.test.ts` — 7 tests named after the rules.
- `src/auth/magic-link.ts` exports `APP_ORIGIN` (reused by invites).
**No migration needed** — `users.status` already carries the `invited / pending_approval / active / inactive / denied` enum and defaults to `pending_approval` (A2).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**24** total, +7 for B1) · `pnpm build` ✓
- Runtime smoke test against live app + Postgres on :5433 (full lifecycle):
- invite `b1.active@example.com` → DB `pending_approval` ✓
- approve → DB `active`; complete invite-time token → `/api/auth/session` returns the user (`systemRole: volunteer`) ✓
- invite + deny `b1.denied@example.com` → DB `denied`; complete → session `null`, `/api/admin` 401 ✓
**Decisions:**
- Invite is the *admin-invites* path, distinct from `getOrCreateUser`'s self-serve auto-activate. Re-inviting an existing (e.g. previously denied) user resets them to `pending_approval`.
- The transition rule lives in one pure, auditable place (`nextUserStatus`); the DB wrappers call it, so the rule and the code cannot drift.
**Next: B2 — profile + notification prefs + SMS consent capture.**
---
## B2 — Profile + notification prefs + SMS consent capture — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** profile update, `notification_preferences` table, SMS consent capture (timestamp, source, IP).
**Delivered:**
- `src/db/schema.ts` — `notification_preferences` table (ARCHITECTURE §4.76): `user_id` PK→`users.id` (ON DELETE cascade), `email_enabled` (default true), `sms_enabled` (default false), `sms_consent_at`/`sms_consent_source`/`sms_consent_ip` (TCPA evidence), `reminder_lead_days` (default 7), `quiet_hours_start/end` ("21:00"/"08:00"), `digest_only` (default false). `SMS_CONSENT_SOURCES` enum (`web_signup` | `paper_form` | `admin_import`).
- `src/domain/consent.ts` — the pure TCPA rule. `phoneChanged(current, next)` (consent is bound to a number — drives the reset), `buildConsent(source, ip, at)` (opt-in evidence), `resetConsent()` (pre-opt-in state).
- `src/db/profile.ts` — DB wrappers: `updateProfile` (updates provided fields only; resets consent when the phone changes), `setSmsConsent` (opt-in populates consent fields), `getProfile`. `upsertPrefs` handles the one-to-one row.
- `src/app/api/dev/profile/route.ts` — PATCH `/api/dev/profile` (update) + POST `/api/dev/profile` (consent).
- `src/domain/consent.test.ts` — 6 tests named after the rules.
- `src/db/seed.ts` — per-user prefs row (email on, SMS off) for every seeded user.
- Migration `drizzle/0002_fearless_doctor_spectrum.sql`.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**30** total, +6 for B2) · `pnpm build` ✓
- `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (31 prefs rows, idempotent)
- Runtime smoke test against live app + Postgres on :5433:
- opt-in `web_signup` from `192.168.1.100` → `sms_enabled=true`, `sms_consent_at/source/ip` populated ✓
- change phone → consent reset (`sms_enabled=false`, evidence cleared) ✓
- change a non-phone field → consent UNCHANGED ✓
- invalid consent source → 400 ✓
**Decisions:**
- **Partial update, not replace.** The PATCH handler builds the patch from only the fields present in the body. A naive `{ phoneE164: body.phoneE164 ?? null }` would null the phone on every PATCH that omits it (and, since `null !== undefined`, `updateProfile` would treat that as a phone change and reset consent). This is the subtle trap this unit guards against.
- **No `one()` relation for the PK-FK column.** Drizzle 0.45.4's `one()` helper types `fields`/`references` as a tuple of non-PK columns; a column that is *both* PK and FK (`notification_preferences.user_id`) fails the typecheck. The table, FK, and all B2 code work without the relation (profile.ts queries both tables directly). Add the eager-load relation later once a working pattern exists.
- **Seed re-fetches canonical ids.** Same idempotency lesson as A2: `userRows` get fresh UUIDs each run, so prefs are seeded from the re-fetched `userRows2` ids (the assignments code already did this).
**Next: B3 — catalog taxonomy.**
---
## B3 — Catalog taxonomy CRUD — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** create/rename/deactivate for the four taxonomy tables — `skill_categories`, `vendors`, `technologies`, `functions`. Deactivate (not delete); slug frozen after creation; read-heavy, so data layer + minimal form only (no `/admin/catalog` UI — that arrives in I2). Governing rules from ARCHITECTURE §4.3: nothing referenced is ever deleted, slugs immutable, FKs `ON DELETE RESTRICT`.
**Delivered:**
- `src/db/schema.ts` — four tables (`skill_categories`, `vendors`, `technologies`, `functions`), each `id, slug (unique), name` + entity-specific columns, `sort_order`, `active` (default true), `created_at`, `updated_at`. All taxonomy FKs use `ON DELETE RESTRICT`; slugs frozen (no update path accepts `slug`). Added relations (`skillCategoriesRelations` → technologies+functions; `vendorsRelations` → technologies; `technologiesRelations` → vendor+category; `functionsRelations` → category).
- `src/lib/slug.ts` — `slugify(name)`: lowercase, ASCII-fold Latin-1 accented chars, collapse non-alnum runs to a single hyphen, trim edges. Pure rule.
- `src/lib/slug.test.ts` — 6 tests named after slugify behaviors.
- `src/db/catalog.ts` — `listCatalog(type, { active })` (active:true → only active rows for pickers; active:false → all rows incl. deactivated), `deactivateCatalog(type, id)` (soft delete, flips `active`), per-entity `create*`/`update*` (slug generated at create, frozen on update; `update*` patches only fields present in the body — no null-out).
- `src/app/api/dev/catalog/route.ts` — GET (list, `?type=&active=`), POST (create, slug server-generated), PATCH (rename/edit, or deactivate via `active:false`). Zod-validated per entity. DB constraint violations mapped to 409 (duplicate slug) / 400 (dangling FK) via a cause-chain walk (pg wraps the SQLSTATE on `err.cause.code`).
- Migration `drizzle/0003_whole_crystal.sql`.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**36** total, +6 for slugify) · `pnpm build` ✓
- `pnpm db:migrate` ✓ → all 4 tables present on :5433
- Runtime smoke against live app + Postgres on :5433 (create → rename keeps slug → deactivate hides from pickers but row persists), all four entities:
- create → generated slug (`name` → `slug`) ✓
- rename → slug UNCHANGED, name updated ✓ (all four types)
- deactivate → active picker count drops by exactly 1, all-row count unchanged (row persists) ✓
- `GET ?active=true` excludes deactivated; `GET ?active=false` includes all ✓
- partial PATCH omits a field → that field is NOT nulled out ✓
- validation: missing name → 400, bad type → 400, missing FK → 400, duplicate slug → 409 (not an empty 500) ✓
**Decisions:**
- **Inline per-entity switches in the route, not a map dispatch.** A map-based handler lost TS type correlation (TS2345 on the intersected param types). Explicit `case` blocks keep each `CatalogType` correlated to its create/update handler and its Zod schema.
- **DB constraint errors → client errors.** The pg driver throws a Drizzle `QueryError` whose `.cause` carries the SQLSTATE. Walking the cause chain lets the route return 409/400 with a clear message instead of a bare 500 — admins creating a duplicate category or a technology with a dangling vendor get actionable feedback.
- **`successorTechnologyId` is plain text, not a self-FK.** A self-referential FK created a circular schema type (TS7022/TS7024). It's a soft "successor gear" hint, validated at the app layer.
- **`purchasedOn` uses `mode: "string"`.** The API passes an ISO date string; a `mode: "date"` column expects a `Date` object (TS2769).
- **No catalog seed yet.** Per ARCHITECTURE, the only seeded artifact is `seed/catalog.json` (loaded on first boot) — delivered in a later unit. The four tables start empty; this unit is the data layer other units consume.
**Next: B4 — positions (schedulable seats) + skills.**
---
## B4 — Positions + skills + requirements editor — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** positions (schedulable seats) CRUD + requirements editor (skill, weight, required level, core). Governing rule under test: **a position with no `is_core` skill refuses to save as publishable.** ARCHITECTURE §4.3 — positions deactivate only, slugs frozen, FKs `ON DELETE RESTRICT`.
**Delivered:**
- `src/db/schema.ts` — two new tables:
- **`skills`** (B4 prerequisite of `position_skills`): `id, slug (unique), name, category_id (FK), technology_id (FK), function_id (FK), dedupe_key (unique), description, mentor_min_level (default 'expert'), stale_after_days (default 120), recert_required, sort_order, active, created_at, updated_at`. `dedupe_key = category|technology|function` (NULLs → ""). All FKs `ON DELETE RESTRICT`.
- **`position_skills`** (join): `position_id (FK), skill_id (FK), weight, required_level, is_core`, PK `(position_id, skill_id)`.
- `roles` (positions) gained `active` (default true) + `updated_at` for soft-delete/pickers/audit.
- `src/db/positions.ts` — data layer: `listPositions`, `createPosition`, `updatePosition`, `deactivatePosition`, `listSkills`, `createSkill`, `updateSkill`, `deactivateSkill`, `getPositionSkills` (skills joined into position_skills in JS), `setPositionSkills` (replaces the whole set), `dedupeKey()` helper.
- `src/domain/positions.ts` — pure publishability rule: `isPublishable(skills)` = has ≥1 `is_core` skill.
- `src/domain/positions.test.ts` — 8 tests named after the rule (no-core publish refused; no-core unpublished allowed; weight range).
- `src/app/api/dev/skills/route.ts` — GET (list, `?active=`), POST (create, slug+dedupe_key generated), PATCH (rename/edit or deactivate).
- `src/app/api/dev/positions/route.ts` — GET (list), POST (create), PATCH (rename/edit or deactivate).
- `src/app/api/dev/positions/requirements/route.ts` — GET (list a position's requirements), POST (set requirements; enforces the publishability gate).
- Migration `drizzle/0004_hesitant_ezekiel.sql`.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**44** total, +8 for B4 domain) · `pnpm build` ✓
- `pnpm db:migrate` ✓ → `skills`, `position_skills`, `roles.active`/`updated_at` present on :5433
- Runtime smoke against live app + Postgres on :5433 (**24 checks**, `/tmp/b4.sh`):
- seed category → skill → position (slugs + dedupe_key generated) ✓
- requirements round-trip (empty → 0) ✓
- publish **with** a core skill → 200 (core/weight/name joined) ✓
- publish **without** any core skill → **400** (the B4 rule); same set as `published:false` → 200 ✓
- weight out of range (9) → 400 ✓
- rename → slug frozen ✓; deactivate → hidden from `?active=true` picker, row persists in DB ✓
**Decisions:**
- **Skills table is a B4 prerequisite.** `position_skills` needs `skills` to exist, so B4 builds the `skills` table (composed from the four catalog tables) up front. The name-composition UI is C1; this unit only creates skills with an explicit name.
- **Requirements editor takes `positionId` in the body, not a URL param.** Next 15.5.29's route-handler context validation rejects an explicitly-typed `{ params: { id: string } }` second argument (it expects `Promise<any>` for the async-params feature). Body-based stays consistent with the catalog route and avoids the dynamic-route context typing rabbit hole.
- **Publishability gate in the domain, enforced in the route.** The pure rule lives in `src/domain/positions.ts`; the route calls it and returns 400 when a `published:true` payload has no core skill — so the rule and the code cannot drift.
- **`join` resolved in JS.** Drizzle 0.45.4 exports no `join` from `drizzle-orm` or `drizzle-orm/pg-core`. `getPositionSkills` fetches `position_skills` then the referenced `skills` and merges in JS.
- **No skill/position seed yet.** Per ARCHITECTURE the only seeded artifact is `seed/catalog.json` (later unit). Tables start empty; this unit is the data layer + API other units consume.
**Next: B5 — user_skills + verified levels (who has what, and at what level).**
---
## C1 — Skills composer — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** Skills composer — category (required) + optional technology + optional function → `dedupe_key`, name prefill. ARCHITECTURE §4.3: a skill is "function applied to a technology (either may be generic)"; the name is auto-composed on create ("Switch cameras on ATEM Mini Pro") then freely editable. Done when: a duplicate (category, tech, function) is rejected; a null-tech skill is generic.
**Delivered:**
- `src/domain/skills.ts` — pure `composeSkillName({ categoryName, technologyName, functionName })` (no DB, no `src/db` imports). Rule: function + technology → "<fn> on <tech>"; function only → "<fn>"; technology only → "<tech>"; neither → category. A null technology yields a generic (technology-agnostic) skill — the name never names a specific piece of gear.
- `src/domain/skills.test.ts` — 6 tests named after the composition behaviors (compose fn+tech, generic on null tech, tech-only, category fallback, null-tech never names gear, trims whitespace).
- `src/app/api/dev/skills/compose/route.ts` — `POST /api/dev/skills/compose` returns `{ name, dedupeKey }` for prefilling the form; writes no row. The admin edits the name, then submits to `POST /api/dev/skills` (which generates slug + dedupe_key and enforces the unique constraint → 409 on duplicate).
**No schema change, no migration.** The `skills` table, data-layer CRUD, and `dedupeKey` were delivered in B4; C1 adds only the composition rule + composer endpoint.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**50** total, +6 for compose) · `pnpm build` ✓
- Runtime smoke against live app + Postgres on :5433 (`/tmp/c1.sh`, **13 checks**):
- compose function + technology → "Switch cameras on ATEM C1 Pro", dedupe_key = `category|tech|func` ✓
- compose function only (null tech) → "Run FOH audio", dedupe_key = `category||func` (empty tech segment) ✓
- create composed skill → 201, slug frozen from composed name, dedupe_key persisted ✓
- duplicate (category, tech, function) → **409** (the C1 rule) ✓
- create null-tech (generic) skill → 201, `technology_id` null ✓
- dangling category FK → 400 ✓
**Decisions:**
- **C1 is the composition rule, not new tables.** The `skills` table + data-layer CRUD + dedupe_key already exist from B4. C1's distinguishing logic is the name-composition (prefill) rule, so it lives as a pure function in `src/domain/skills.ts` and is exercised by a composer endpoint — matching the `isPublishable`/`validateRequirements` domain pattern from B4.
- **Composer endpoint returns a preview, writes nothing.** `POST /api/dev/skills/compose` returns `{ name, dedupeKey }` so the UI prefills the form; the edit-then-submit flow keeps slug + dedupe_key generation server-authoritative in `POST /api/dev/skills`.
- **No skill/position seed yet.** Per ARCHITECTURE the only seeded artifact is `seed/catalog.json` (later unit). Tables start empty; this unit is the composition layer other units (C2 sliders, C3 matrix) consume.
**Next: C2 — volunteer `/profile/skills` sliders (self_comfort) with verified chip.**
---
## C2 — Volunteer profile sliders (self_comfort; verified_level untouched) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** `/profile/skills` sliders — a volunteer rates their own comfort per skill. Governing rule: **two numbers, one truth** — `self_comfort` is the volunteer's signal, `verified_level` is the gate. A slider save must never move `verified_level`, `verified_by`, or `verified_at` (those belong to C3's assessments).
**Delivered:**
- `src/db/schema.ts` — `user_skills` table (ARCHITECTURE §4.3): `id, user_id (FK users, cascade), skill_id (FK skills, cascade), self_comfort (int, nullable), self_rated_at, verified_level (enum, default 'none'), verified_by, verified_at, mentor_opt_in, last_served_on, notes`. Unique index `(user_id, skill_id)`; index on `skill_id`. Excluded from `relations` (FK columns on a unique key trip Drizzle 0.45.4 typing — same as skills/position_skills).
- `src/db/userSkills.ts` — `setSelfComfort(userId, skillId, value)` upserts on `(user_id, skill_id)` and writes **only** `self_comfort`/`self_rated_at`; on insert it seeds `verified_level: 'none'`. `getUserSkills(userId)` joins `skills` for display (name/slug), ordered by name.
- `src/domain/userSkills.ts` — pure `validateSelfComfort(value)`: null (not yet rated) allowed; otherwise an integer 0–100. No DB imports.
- `src/domain/userSkills.test.ts` — 5 tests named after the behaviors.
- `src/app/api/dev/user-skills/route.ts` — `GET ?userId=` (records + skill name), `POST { userId, skillId, selfComfort }` (slider save; absent/null clears to "not rated"). Constraint mapping: 23505 → 409 (duplicate record), 23503 → 400 (dangling user/skill).
- Migration `drizzle/0005_keen_lenny_balinger.sql`.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**55** total, +5 for C2) · `next build` ✓
- `pnpm db:migrate` ✓ → `user_skills` present on :5433 with all 11 columns
- Runtime smoke against live app + Postgres on :5433 (`/tmp/c2.sh`, **18 checks**):
- save slider 60 → 200, persisted; `verified_level` = `none` ✓
- set an existing `verified_level='verified'` + `verified_at`, then move slider to 85 → comfort updated, **verified level and `verified_at` unchanged** (the C2 rule) ✓
- 101 and 60.5 → 400 (range/integer validation) ✓
- POST with no `selfComfort` → 200, cleared to null ✓
- dangling user/skill id → 400 (not 500) ✓
- test rows cleaned up (catalog + `user_skills` back to 0)
**Session blocker — root cause + fix (recorded for future reference):**
- **Reported** as "build/restart keeps killing the session" and "stale `next-server` won't die".
- **Root cause:** the process being killed (`pkill -9 -f next-server`) was **pi-web — the agent's own UI host** (`node …/pi-web`, cwd `…/node_modules/@agegr/pi-web`, Next **v16.3.8**, port 30141). The project is Next **15.5.29**, and nothing from it was listening on :3000. Killing pi-web terminated the session; its supervisor respawned it with a new PID, which looked like "next-server keeps respawning". The build was never hanging — `next build` finishes in ~30s.
- **Also:** `pnpm` is not on PATH for this shell, and `/tmp/start_app.sh` did not exist (fresh `/tmp`). Use `./node_modules/.bin/{next,tsc,vitest,eslint}` directly.
- **Fix:** never blanket-kill `next-server`. Start the project app as a background process on :3000 (`DATABASE_URL=postgres://media:media@localhost:5433/media PORT=3000 ./node_modules/.bin/next start`); it reaches `Ready` in <1s and `/api/health` returns 200. If a port must be freed, find the PID via `ss -ltnp | grep :3000`, never by process name.
**Decisions:**
- **Slider writes are narrow by construction.** `setSelfComfort`'s `onConflictDoUpdate` sets only `selfComfort`/`selfRatedAt`; the verified columns are not in the update set at all, so the rule holds without a read-then-write race.
- **Null is the "not rated" state**, not 0. Omitting `selfComfort` clears the rating and its timestamp — it never invents a 0% score.
- **Unique (user, skill), not a history table.** C2 keeps one current self-rating per pair; the append-only history for verification lives in C3's `skill_assessments`.
**Next: C3 — admin skills matrix + verify-level modal.**
---
## C3 — Admin skills matrix + verify-level modal — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** the admin skills matrix (grid + filters) and the verify-level modal writing `skill_assessments`. Governing rules (ARCHITECTURE §4.3): levels never change silently — every move up **or down** appends an assessment row; `level_from` is the stored level, never client input; the volunteer's `self_comfort` is not the gate and is not touched by verification.
**Delivered:**
- `src/db/schema.ts` — `skill_assessments` (append-only, 10 columns): `id, user_id, skill_id, assessor_id (nullable), kind [self|mentor|admin|quiz], level_from, level_to, comfort_at_time, notes, created_at`. Indexes on `(user_id, created_at)` and `skill_id`; `assessor_id` is `ON DELETE SET NULL`, user/skill cascade. Added `ASSESSMENT_KINDS` + the table to the `schema` export. No `updated_at` — there is no update path.
- `src/domain/assessments.ts` — pure ladder + rule: `SKILL_LEVELS` ordered `none < observer < assisted < qualified < expert`, `levelRank`, `isSkillLevel`, and `buildAssessment({ currentLevel, newLevel, selfComfort })` → draft with **server-owned `levelFrom`**, `levelTo`, `comfortAtTime`, and `direction: up|down`. Rejects unknown levels and an unchanged level (no silent no-op row). No DB imports.
- `src/domain/assessments.test.ts` — 9 tests: ladder order, domain ladder matches the DB enum (drift guard), level recognition, up move, down move audited, unknown new level, unknown current level, unchanged level refused, null-comfort snapshot.
- `src/db/assessments.ts` — `verifySkillLevel` runs one transaction: reads the current record, appends the assessment, then moves `user_skills.verified_level` + `verified_by`/`verified_at`; creates the record (with `self_comfort` null) when the volunteer never rated the skill. **Never writes `self_comfort`/`self_rated_at`.** `listSkillsMatrix` (filters `userId`, `skillId`, `categoryId`, `level`; joins users × skills × categories) and `listAssessments` (newest first, assessor names resolved in JS, limit 1–200).
- Routes: `GET /api/dev/skills/matrix`, `POST /api/dev/skills/verify`, `GET /api/dev/skills/assessments`. Verify maps `AssessmentError` → 400 and pg 23503 → 400 / 23505 → 409.
- Migration `drizzle/0006_modern_shiver_man.sql`.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**64** total, +9 for C3) · `next build` ✓
- `drizzle-kit migrate` ✓ → `skill_assessments` present on :5433 with all 10 columns
- Runtime smoke against live app + Postgres on :5433 (`/tmp/c3.sh`, **42 checks**):
- matrix starts empty; after a C2 slider save it shows the person with `self_comfort=55` and `verified_level=none` ✓
- verify `qualified` + assessor + kind `mentor` → assessment `level_from=none`, `level_to=qualified`, `comfort_at_time=55`; `user_skills` moved with `verified_by`/`verified_at`; **self_comfort still 55** ✓
- history returns the row with the assessor's name ✓
- filters: `level=qualified` → 1, `level=expert` → 0, `categoryId` → 1, invalid level → 400 ✓
- demotion to `assisted` appends a second row (`level_from=qualified`), history newest-first ✓
- unchanged level → 400, unknown level → 400, dangling user/skill → 400, and no rejected verify wrote a row (count stayed 2) ✓
- verifying a never-rated volunteer → 200, `comfort_at_time` null, record created with `self_comfort` null ✓
- afterwards a slider save (90) still cannot move the verified level (`assisted` unchanged) — the C2 rule holds from the other direction ✓
- test rows cleaned up (`skill_assessments`, `user_skills`, `skills`, categories back to 0)
**Decisions:**
- **The append-only assessment row IS the audit row for level changes.** There is no `audit_log` table yet (it belongs to its own later unit); the BUILD-PLAN's "audit row exists" is satisfied by `skill_assessments`, which records who moved whom, from what, to what, when, with the comfort the assessor saw. Adding a second generic log row now would duplicate it.
- **One write path, one transaction.** The assessment insert and the `verified_level` move succeed or fail together, so a level cannot move without its history.
- **Unchanged level is a 400.** Verifying someone at the level they already hold records nothing; a silent no-op row would make the history lie about activity. Re-verifications that add context can be a later, explicit concern.
- **Verification works without a slider rating.** `user_skills` is created with `self_comfort` null — a mentor can certify someone who has never self-assessed, and that is visible in the matrix.
- **No admin UI page yet.** Consistent with B3/B4/C1/C2: this unit is the domain rule + data layer + API the UI consumes; the grid/modal screens land with the admin surfaces (I2). The matrix endpoint already returns the row shape the grid renders.
- **Same Drizzle 0.45.4 relation exclusion.** `skill_assessments` has FK columns on indexes and is queried directly, like `user_skills`.
**Next: C4 — readiness scoring (`src/domain/readiness.ts`, pure).**
---
## C4 — Readiness scoring — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** pure `computeReadiness` in `src/domain/readiness.ts`. ARCHITECTURE §5.8.3 derivation. Done when `pnpm test readiness` is green on 6 named cases. This is the single most reused function in the app (picker, auto-fill, matrix, dashboard), so it is pure — no DB, no `src/db` imports — and takes its data in.
**Delivered:**
- `src/domain/readiness.ts` — `computeReadiness(skills)`: no skills → blocked; each CORE skill below the position's `required_level` blocks and is listed in `missing[]`; otherwise `score = Σ(weight_i × levelScore_i) / Σ(weight_i)` across every skill (§5.4: none 0 · observer 0.35 · assisted 0.55 · qualified 0.80 · expert 1.00), blended with the null-safe mean of the CORE skills' self comfort (`0.7 × level + 0.3 × comfort/100`), rounded to 0–100. Plus `readinessLevel(score)` bands, `validateReadinessInput`, and re-exports of the ladder.
- `src/domain/readiness.test.ts` — 13 tests named after the rules (no skills blocked; all core at required → 100; core below required → blocked + missing; non-core gap → <100; null comfort is level-only; comfort blends 0.7/0.3; null-safe mean; expert + full comfort → expert; bands; validation).
**No schema change, no migration.** C4 is a pure function over data the caller resolves (position_skills + user_skills).
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**105** total; C4 = 13) · `next build` ✓
- `pnpm test src/domain/readiness.test.ts` green on all 13 cases
**Decisions:**
- **Faithful to §5.8.3.** The blend is exactly the ARCHITECTURE formula; `levelScore` is the §5.4 mapping, not the ladder rank, so the score stays on a 0–1 scale.
- **Comfort is null-safe over CORE skills only.** A core skill the volunteer never rated is dropped from the mean; if every core skill is unrated the comfort term disappears and the score is level-only.
- **Depends on C3's ladder.** Reuses `isSkillLevel`/`levelRank`/`SKILL_LEVELS` from `./assessments` (itself tested to match the DB enum) — one import, no `src/db` import.
**Next: C5 — per-skill mentor designation.**
---
## C5 — Mentor designation — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** pure per-skill `mentor_ready`. Done when: expert without opt-in is not mentor_ready; opt-in without admin approval is not either. ARCHITECTURE §5.8.5.
**Delivered:**
- `src/domain/mentor.ts` — `isMentorReady({ verifiedLevel, mentorMinLevel, mentorOptIn, adminApproved })` = `verified_level >= mentor_min_level` AND `mentor_opt_in` AND admin-approved. Expertise alone does not volunteer someone. Plus `validateMentorDesignation`. No DB imports; reuses C3's ladder.
- `src/domain/mentor.test.ts` — 6 tests named after the rule (ready; expert no opt-in; opt-in not approved; below mentor_min_level; clears all three).
**No schema change, no migration.** `user_skills.mentor_opt_in` already exists (C2); the admin-approved flag is an input to this predicate, persisted by the mentor-approval flow that consumes it.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**105** total; C5 = 6) · `next build` ✓
**Decisions:**
- **Predicate, not a row.** C5 is the rule the shadow validation (C6) calls; the admin-approval persistence is the consuming unit's concern. Keeping it a pure predicate means the rule and the code cannot drift.
- **Ladder-rank comparison.** `verified_level >= mentor_min_level` is a rank comparison, so "at or above the skill's mentor_min_level" never blocks.
**Next: C6 — growth goals + shadow pairing validation.**
---
## C6 — Growth goals + shadow pairing validation — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** growth goals + shadow pairing validation. Done when: a shadow slot without a paired mentor rejects at the data layer. ARCHITECTURE §4.3 / §5.8.5 / §5.8.6.
**Delivered:**
- `src/db/schema.ts` — `growth_goals` table (§4.3, §5.8.6): `id, user_id (FK cascade), skill_id (FK cascade), target_level (SKILL_LEVELS), target_date (date nullable), status (GOAL_STATUSES, default 'requested'), mentor_user_id (FK set null), shadow_count (default 0), created_by, created_at`; unique index `(user_id, skill_id)` + index on `status`. Added `GOAL_STATUSES` enum + the table to the `schema` export.
- `src/domain/growthGoals.ts` — pure `nextGoalStatus(current, action)` state machine (§5.8.6: requested→mentor_assigned→in_progress→achieved, with decline, pause/resume; `progressShadow` is a self-loop) and `canGoalTransition` / `validateGrowthGoal`.
- `src/domain/shadows.ts` — `validateShadowPairing({ isShadow, skillId, pairedMentor })`: a shadow/trainee slot requires a paired mentor in the same instance who is mentor-ready for that exact skill (C5's `isMentorReady`). Rejects a shadow with no paired mentor. No DB imports.
- `src/domain/shadows.test.ts` — 6 tests (shadow without mentor rejects — the C6 rule; shadow with ready mentor ok; mentor not opt-in / not at mentor_min_level / not approved rejected; non-shadow slot needs no pairing).
- `src/domain/growthGoals.test.ts` — 10 tests (each lifecycle transition, illegal transitions return null, terminal goals stay put, validation).
- Migration `drizzle/0007_funny_zarda.sql` — `growth_goals` table + a `chk_shadow_paired` CHECK on `slots` (`not is_trainee_slot or paired_with_user_id is not null`) as the data-layer backstop.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**105** total; C6 = 16) · `next build` ✓
- `pnpm db:migrate` ✓ → `growth_goals` present on :5433 with all 10 columns; `chk_shadow_paired` present
- Runtime data-layer proof: inserting a trainee slot (`is_trainee_slot=true`) **without** `paired_with_user_id` is rejected by `chk_shadow_paired` (the C6 rule at the DB layer)
**Decisions:**
- **Two lines of defense for the shadow rule.** The pure `validateShadowPairing` is the first gate (unit-tested); `chk_shadow_paired` is the data-layer backstop so a trainee slot can never be written without a paired mentor even if the app layer is bypassed.
- **`target_level` is a skill level, not a status.** The schema enum is `SKILL_LEVELS` (the target the goal climbs to); `status` carries the lifecycle. `validateGrowthGoal` validates each against its own enum.
- **`progressShadow` is a self-loop.** Completing a shadow increments `shadow_count` without changing status; `nextGoalStatus` returns `in_progress` for it.
- **Removed `.freebuff/`.** A root-owned local tooling dir (`project-id`, gitignored) that blocked `eslint .` (the `pnpm lint` DoD gate) — `drizzle`/ESLint could not scandir it. It held only a local project id; removed with `sudo rm -rf` and its `.git/info/exclude` entry cleared, restoring a clean `eslint .`.
**Next: D8 — assign/clear mutations.**
---
## D2 — Instance generator (idempotent, 16-week window) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** instance generator (idempotent, 16-week window) on a cron route. Done when: run twice → instance count unchanged; published instance untouched. ARCHITECTURE §5.1.
**Delivered:**
- `src/domain/instances.ts` — pure `planInstances(service, now, target)` turns a service's rrule into the UTC instants it occurs at inside a window (uses `expandRRULE` + `localToUtc`). `windowTarget(now, weeks)` = now + 16 weeks (default `INSTANCE_WINDOW_WEEKS`). Pure — no DB imports.
- `src/domain/instances.test.ts` — 7 tests named after the rule: window boundary (exactly the Sundays in [now, now+3w]), endsAt = start + duration, DST-safe instants (9 AM local stays 9 AM across spring-forward; stored UTC shifts EST→EDT), determinism (same input → same instants, which is what makes the upsert idempotent), biweekly phase, monthly-nth across a year boundary, windowTarget default (16 weeks = 112 days).
- `src/db/instances.ts` — `generateInstances({ now, windowWeeks })` iterates active services, plans each, and upserts on `(service_id, starts_at)` via `onConflictDoNothing`. That single primitive gives every invariant: a re-run finds the existing row and leaves it untouched, a `cancelled` instance stays cancelled (never regenerated), a `published` instance is never modified here, past instances fall outside the window and are never deleted. `occurs_on` stored via `localToUtc(date, "00:00", tz)` to avoid a UTC-midnight DST shift (matches the seed).
- `src/app/api/dev/cron/instances/route.ts` — GET `/api/dev/cron/instances` drives `generateInstances()` daily (cron `0 6 * * *`).
**No schema change, no migration.** The `service_instances` table already exists (A2) with the `(service_id, starts_at)` unique index that makes generation idempotent. Slot materialization from role requirements stays deferred to D3.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**125** total; D2 = 7) · `next build` ✓
- Runtime smoke test (cron route): run twice → **0 rows created on re-run**, instance count unchanged (36 == 36); published instances byte-identical before/after (`diff` empty); generated draft instances stored as DST-safe UTC instants (11:00 ET = 16:00 UTC).
**Decisions:**
- **Idempotency is one primitive, not a branch.** `onConflictDoNothing({ target: [service_id, starts_at] })` returns only rows this run actually inserted, so `created` counts genuine additions and every "don't touch" invariant falls out of the unique key rather than being re-implemented per status.
- **`planInstances` is pure; the upsert is idempotent because planning is deterministic.** Same (service, now, target) → same instants → same conflict keys. The DST test asserts the *instant* shifts, not the local wall clock, so a 9 AM Sunday stays 9 AM across the transition.
- **`occurs_on` stored as a zoned midnight, not `new Date("YYYY-MM-DD")`.** A bare string parse lands at UTC midnight, which renders back a day early in the church timezone; `localToUtc(date, "00:00", tz)` matches the seed and keeps the local date stable.
- **Window edge is approximate by design.** `windowTarget` adds 16×7 UTC days; the DST hour at the 16-week boundary is irrelevant since the window is a rolling horizon, not a precise instant.
- **Build cache reclaimed.** A prior interrupted `next build` left root-owned files under `.next/` (same class as the earlier `.git/objects` scrub) that blocked rebuilds; `sudo chown -R bhursey:bhursey .next` restored the build. The stale `next start` on :3000 was restarted after the build so the new cron route loaded. Test-generated draft instances were deleted to restore the seed state.
**Next: D3 — slot materialization from `position_skills`/requirements (headcount, call time).**
---
## D3 — Slot materialization (headcount, call time) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** slot materialization from role requirements (headcount, call time). Done when: Audio headcount 2 creates 2 slots with correct call_time. ARCHITECTURE §5.2.
**Delivered:**
- `src/domain/slots.ts` — pure `planSlotsForRole(instanceStartsAt, role)` + `planSlots(instanceStartsAt, roles)`. A role with headcount N fills N seats (slotIndex 1..N); each seat's call_time is `instanceStartsAt + call_time_offset_minutes` (null when the role has no offset); headcount clamped to >= 1. No DB imports.
- `src/domain/slots.test.ts` — 5 tests named after the rule: Audio headcount 2 → 2 slots with correct call_time (11:00 EST − 90 min = 09:30 EST = 14:30 UTC), headcount clamped to 1, null call_time when offset null, multi-role flattening in role order.
- `src/db/slots.ts` — `materializeSlotsForInstance(serviceInstanceId, instanceStartsAt, roles)` upserts seats on `(service_instance_id, role_id, slot_index)` via `onConflictDoNothing`; `materializeSlots(now)` processes every non-published instance at/after `now` (published weeks are owned by the publish flow, so their slot set is left untouched per §5.1).
- `src/app/api/dev/cron/slots/route.ts` — GET `/api/dev/cron/slots` drives `materializeSlots()`; idempotent on re-run.
**No schema change, no migration.** The `slots` table already exists (A2) with the `(service_instance_id, role_id, slot_index)` unique index that makes materialization idempotent. `position_skills` (which drives conflict detection in D5) stays deferred.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**129** total; D3 = 5) · `next build` ✓
- Runtime smoke test: draft instance + Audio headcount 2 → 4 seats (Audio×2 + Livestream×1 + Slides×1); Audio slots slot_index 1,2 with call_time 09:30 EST (14:30 UTC); re-run creates 0 rows (idempotent). Seed state restored to canonical 4 instances / 12 slots after testing.
**Decisions:**
- **Idempotency is one primitive again.** `onConflictDoNothing({ target: [service_instance_id, role_id, slot_index] })` returns only rows this run inserted, so `created` counts genuine additions and a re-run is a no-op that never disturbs an admin's assignment on an existing seat.
- **Published instances are skipped, not upserted.** §5.1 says slots are created for *new* instances and a published week's slot set is owned by the publish flow. `materializeSlots` filters `status != 'published'`, so re-running generation never rewrites a published week's seats.
- **call_time is a zoned offset, not a naive add.** `instanceStartsAt + offset` operates on the UTC instant, so a −90 min offset applied to a DST-safe start stays DST-safe (the stored UTC shifts with the wall clock, exactly as the seed does).
- **Headcount clamped to >= 1.** A role always produces at least one seat, so a zero/missing headcount can never silently drop a role from an instance.
- **Seed is date-dependent, not fully idempotent.** The seed materializes `nextSundaysInTz(2)` (rolling window), so re-running it across dates creates new instances. After testing I reset instances/slots/assignments and re-ran the seed once to restore the canonical 4-instance / 12-slot state.
## D4 — Blackout CRUD + `isUnavailable(user, date)` — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** blackout CRUD + `isUnavailable(user, date)` pure function, ranges + rrule. Done when: `pnpm test availability` green incl. inclusive-end case. ARCHITECTURE §4.7 / §5.3 rule 5 / §5.4.
**Delivered:**
- `src/domain/availability.ts` — pure `isUnavailable(records, date)` + `overlapsRange(date, startsOn, endsOn)` + `recordCovers(record, date)`. A record covers the date if it is `active` and either its inclusive range `[starts_on, ends_on]` contains the date (same day = one day) or its `rrule` matches. No DB imports.
- `src/domain/availability.test.ts` — 11 tests named after the rule: inclusive-end case (2026-11-21..2026-11-28 covers 11-28), inclusive-start, day-before/day-after excluded, same-day blackout, active range covers, cancelled never covers, recurring rule matches its weekday, intervening Sunday excluded (2-week interval), malformed rrule neither throws nor matches, empty set false.
- `src/db/schema.ts` — `unavailability` table (ARCHITECTURE §4.7): `id, user_id (FK users, cascade), kind (enum), starts_on, ends_on (date), all_day (default true), reason (nullable), rrule (nullable), status (enum active|cancelled), created_at, created_by`. CHECK `ends_on >= starts_on`, CHECK `(ends_on - starts_on) <= 365`, unique index `(user_id, starts_on, ends_on) WHERE status='active'`, index on `user_id`.
- `src/db/unavailability.ts` — `listUnavailability({ userId })`, `getUnavailability`, `createUnavailability`, `updateUnavailability`, `cancelUnavailability` (soft-delete → `status='cancelled'`). Range validated on write (`validateUnavailabilityRange`); `rrule` validated via `validateRecurrence`.
- `src/app/api/dev/unavailability/route.ts` — GET (list, `userId` filter), POST (create, 400 on bad range/rrule), PATCH (edit or `status:'cancelled'` cancel). Constraint errors mapped to 400.
**Schema change + migration:** `drizzle/0008_needy_stryfe.sql` creates the `unavailability` table. Applied to the DB on :5433.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**140** total; D4 = 11)
- Runtime smoke test (running app on :3000): POST valid blackout → 201; POST span > 365 → 400 "span must not exceed 365 days"; POST ends < starts → 400 "ends_on must not precede starts_on"; GET list; PATCH cancel → 200 with `status='cancelled'` (row persists). CHECK constraints enforced at the DB layer too (span > 365 and ends < starts rejected by `chk_unavailability_*`). Test rows cleaned up.
**Decisions:**
- **Inclusive on both ends, by design.** A blackout 2026-11-21..2026-11-28 covers 11-28 (the end date), matching the ARCHITECTURE ("inclusive; same day = one day"). `overlapsRange` uses `>=` / `<=` on ISO strings (lexicographic order == chronological for YYYY-MM-DD), so no date parsing is needed.
- **`date` columns stored as strings (`mode: "string"`).** The whole recurrence/availability domain works in `YYYY-MM-DD` strings; storing the range as strings avoids Date↔string conversion at the DB boundary. Postgres `date` is mode-agnostic, so the migration is identical to a `mode: "date"` column.
- **Range and rrule are mutually exclusive coverage paths.** A record covers a date if it is `active` AND (range contains the date OR rrule matches it). A recurring blackout uses the rrule; a one-time blackout uses the range. `parseRecurrence` throws on malformed input, so `isUnavailable` guards with `validateRecurrence` and never throws.
- **Cancel, never delete.** `cancelUnavailability` flips `status='cancelled'`; the row persists so historical assignment conflicts stay explainable (rule 5 in §5.3 warns, doesn't hard-block). `isUnavailable` skips non-`active` records, so a cancelled blackout no longer excludes the volunteer.
- **Constraints enforced in two layers.** The pure `validateUnavailabilityRange` rejects bad ranges at the API boundary (400 with a clear message); the DB `chk_unavailability_*` CHECK constraints are the backstop so a bad range can never reach the table.
## D5 — Conflict engine (hard vs soft) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** conflict engine — pure function, hard vs soft conflicts. Done when: table-driven test, 10 cases, one per rule in BUILD-SPEC §7. ARCHITECTURE §5.3 / BUILD-SPEC §7.
**Delivered:**
- `src/domain/conflicts.ts` — pure `classifyConflicts(input)` returns every reason a candidate should not take a slot, each tagged `hard` (blocks) or `soft` (warns; override with a note). Reuses the pure predicates it encodes: `isUnavailable` (D4) for blackouts, `isMentorReady` (C5) for the shadow mentor, `levelRank` (C3) for the core-skill gate. Plus `hasHardConflict` / `hardConflicts` / `softConflicts` so the picker and auto-filler filter by severity. No DB imports.
- `src/domain/conflicts.test.ts` — table-driven: one case per rule (ten cases, one per row of §5.3), plus a clean baseline, a multi-conflict case, and the branch edges (unapproved-but-active, a valid shadow pairing, never-served, unrated comfort, core skill AT the required level). 20 tests total.
**No schema change, no route, no migration.** D5 is a pure function (zero UI, zero DB) — the BUILD-PLAN's highest-risk unit, isolated exactly that way. The data layer (D6/D8) resolves the joins and passes the facts in; this module only encodes the rules.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**160** total; D5 = 20) · `next build` ✓
**Decisions:**
- **Hard vs soft, keyed by code.** Each conflict has a stable `code` and a `severity`. The assignment write path and auto-filler reject on `hardConflicts(...)`; the picker shows all of them, greasing the soft ones as warnings the admin overrides with a note.
- **One code per rule, ten cases.** The 10 rules map 1:1 to ARCHITECTURE §5.3 (4 hard: inactive/unapproved, duplicate-in-instance, core-skill-below-required, shadow-mentor-not-ready; 6 soft: blackout-overlap, monthly-cap, back-to-back, comfort-below-50, stale, readiness-below-threshold). The test table has exactly one case per rule.
- **Comfort never blocks (rule 14).** §7 rule 14 says self-comfort lowers rank and warns but never blocks; `comfort_below_50` is soft even though the picker treats it as a warning.
- **Never-served is not stale.** Rule 9 (staleness) requires a non-null `lastServedOn`; a volunteer who has never served the skill is a readiness/level concern (surfaced by readiness), not a "needs refresher" — flagging a beginner as stale would mislead.
- **Staleness takes a reference date.** The function is pure and deterministic, so `daysBetween(lastServedOn, today)` takes `today` as input rather than reading the clock — the test pins it to a fixed date.
- **Shadow mentor reuses `isMentorReady`.** A shadow slot (§7 rule 16) needs a mentor who is mentor-ready for that exact skill; the C5 predicate is called directly, and an unpaired shadow (`pairedMentor` null) is a hard conflict.
## D6 — Candidate ranking service (availability → readiness → score) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** candidate ranking service — availability filter → readiness → score. Done when: Test: away user excluded; unqualified blocked with reason code; ordering deterministic. ARCHITECTURE §5.8.4 / §5.8.3.
**Delivered:**
- `src/domain/ranking.ts` — pure `rankCandidates({ position, candidates, sortBy })` returns `{ eligible, excluded }`. Pipeline is exactly §5.8.4: **availability-filtered first, then ranked by readiness**. Reuses `computeReadiness` (C4) for the score, `isUnavailable` (D4) for the blackout filter, `levelRank` (C3) for staleness. No DB, no route, no migration — the join-resolving data layer (D8/D9) passes facts in.
- `src/domain/ranking.test.ts` — 18 tests: the three DONE-when assertions (away excluded; unqualified + `core_skill_below_required` reason code; deterministic ordering), roster/instance gates (inactive, unapproved, already-serving), sort modes (bestMatch score-desc + name/id tie-break, availableOnly alphabetical), and picker signals (mentor badge, stale vs never-served, comfort-lowers-rank-never-blocks).
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**178** total; D6 = 18) · `next build` ✓
**Decisions:**
- **Precedence mirrors §5.8.4.** inactive → away → already_serving → unqualified → eligible. Availability is checked before the one-assignment-per-instance rule, matching "availability-filtered first".
- **`score` is always a number.** `computeReadiness` returns 0 for an empty skill set, so `RankedCandidate.score` is `number` (not `number | null`).
- **Null required level never blocks.** A position skill with no solo threshold is passed through as `none` to `computeReadiness`, so it still ranks but never hard-gates.
- **Comfort lowers rank, never blocks (§7 rule 14).** `comfort_below_50` is not a ranking exclusion — it only pulls the blended score down (70% level / 30% comfort).
- **Never-served is not stale.** A core skill with no `last_served_on` is a readiness concern, not a "needs refresher" — flagging a beginner as stale would mislead (same call as D5).
- **Deterministic tie-break.** bestMatch orders by score desc, then displayName, then userId; the excluded list is sorted by name then id, so a fixed input always yields the same picker order.
**Next: D7 — read-only grid UI (rows = instances, cols = positions, week nav).**
---
## D7 — Read-only grid UI — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** Grid UI, read-only: rows = instances, cols = positions, week nav. Done when: E2E renders a seeded week; no console errors. Depends on D1–D6 (all committed).
**Status:** DONE. All code written; typecheck + eslint + unit (178) + `next build` green; **full Playwright E2E green (6/6)** and committed. Two further latent bugs were found and fixed this session (see Decisions/Blockers).
**Delivered:**
- `src/lib/tz.ts` — added `CHURCH_TIMEZONE`, `addDaysISO(dateStr, days)` (calendar-safe ISO ± days), `weekStartOn(dateStr, tz)` (Sunday of the week containing a date). **Fixed a pre-existing bug:** `weekdayInTz()` returned `undefined` because `partsInTz()` never emitted a `weekday` part; added `weekday: "short"` to its Intl format and made `weekdayInTz` return `WEEKDAYS.indexOf(label)` (0=Sun..6=Sat). This also corrects `nextSundaysInTz`, which relied on the same missing part (seed was producing instances on wrong dates).
- **Fixed a second latent bug (this session):** `weekdayInTz()` and `nextSundaysInTz()` both built `new Date(Date.UTC(y, mo-1, d))` from a *local* date string and read its weekday — for a negative-offset zone like `America/New_York`, UTC midnight lands on the *previous* evening, so the weekday (and thus the seed's Sundays and the grid's default week) was off by one. The seed had materialized instances on **Mondays** (11-23/11-30) instead of Sundays. `weekdayInTz` now builds the instant for **local** midnight via `utcOffsetMs`; `nextSundaysInTz` now uses `weekdayInTz` + the calendar-safe `addDaysISO`. Verified: today Wed 2026-11-18 → next Sundays 2026-11-22 / 2026-11-29; `weekStartOn("2026-11-18")` = 2026-11-15.
- `src/db/grid.ts` — pure data layer for the grid. `gridForWeek(weekStart)` returns `{ weekStart, weekEnd, positions[], instances[] }` (instances → slots → assignments → user display names). `defaultWeekStart()` returns the Sunday of the earliest upcoming published instance so a seeded DB shows data on first load. `occursOn` is a `date`-mode column → returned as a UTC-midnight instant; the grid now extracts the **UTC calendar date directly** (`occursOnISO`, via `getUTCFullYear/getUTCMonth/getUTCDate`) instead of running it through `dateInTimezone(...)` (which reinterprets the UTC instant as wall-clock and shifts a day early in negative-offset zones). `gridForWeek` filters `gte`/`lte` on `Date` objects (UTC midnight).
- `src/components/app/week-nav.tsx` — prev/next week anchor links to `?week=YYYY-MM-DD` (server-rendered, no client state).
- `src/components/app/schedule-grid.tsx` — semantic `<table>`: header row = active positions (by sortOrder), one row per instance, each cell = slot (assigned volunteer + status badge, or "Open", trainee slots shown as shadow). Empty state via `StateMessage`.
- **Fixed a bug (this session):** the `<table>` used the Tailwind class `collapse`, which sets `visibility: collapse` (hides the whole table) — the grid rendered server-side but was invisible in the browser, so E2E saw an empty grid. Changed to `border-collapse` (the intended border-collapsing utility).
- `src/app/(app)/schedule/page.tsx` — replaced the placeholder. Async server component, `searchParams: Promise<{ week?: string }>`. Validates `?week=`, falls back to `defaultWeekStart()`, fetches and renders nav + grid.
- `e2e/schedule-grid.spec.ts` — new: renders a seeded week, asserts role column headers + an instance row + prev/next nav, captures console + page errors and fails if any. Week-nav test asserts URL + re-render.
- `e2e/shell.spec.ts` — updated the schedule assertion from the old placeholder ("Nothing scheduled yet") to the grid (role headers + service name).
**Verification (all green):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**178** tests, 21 files) · `next build` ✓.
- **Playwright E2E: 6/6 passing** — `e2e/schedule-grid.spec.ts` (2) + `e2e/shell.spec.ts` (4, incl. health + unauth redirect).
- Live `/schedule` renders the seeded week `2026-11-22 – 2026-11-28` with Audio/Livestream/Slides columns and both Sunday services; label reads `Sun, Nov 22 · Sunday 9:00 AM`.
- DB re-seeded after the tz fix (reset instances/slots/assignments): 4 instances on Sundays (11-22, 11-29) / 12 slots / 12 assignments / 3 roles.
**Decisions:**
- **Read-only grid = server component, no API route.** A read-only grid doesn't need a client data layer; the page queries `src/db/grid.ts` directly and renders. D8 (mutate) will add its own client + routes.
- **Week nav via URL param, not client state.** `?week=YYYY-MM-DD` survives reload/share and needs no JS — simplest robust approach for a read-only grid.
- **Default week = earliest upcoming published instance.** So a freshly seeded DB shows data immediately instead of an empty state.
- **`occursOn` compared as `Date`, not string.** The column is `date({ mode: "date" })`; `gte`/`lte` take `Date` objects (UTC midnight). Returned to the UI as the **UTC calendar date** (`occursOnISO`), not `dateInTimezone(...)` — reinterpreting the UTC instant as wall-clock shifts a day early in negative-offset zones.
- **Fixed `weekdayInTz` rather than working around it.** `weekStartOn` needs the weekday; the underlying `partsInTz` gap was a latent bug affecting the seed too, so fixing it at the source is correct. The UTC-midnight reconstruction bug was the same class of issue and is fixed the same way (build the local-midnight instant).
**Blockers found (now resolved):**
- `RangeError: Invalid time value` on `/schedule` was drizzle serializing an `Invalid Date` from `defaultWeekStart()`, which returned `NaN-NaN-NaN` because `weekdayInTz()` returned `undefined` (no `weekday` part in `partsInTz`). Fixed by adding `weekday: "short"` to `partsInTz` and returning `WEEKDAYS.indexOf(label)`.
- **`collapse` Tailwind class hid the grid.** `<table className="min-w-full collapse text-sm">` set `visibility: collapse` — the grid rendered server-side (curl confirmed) but was invisible in the browser, so E2E saw an empty grid. Changed to `border-collapse`.
---
## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `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. ARCHITECTURE §4.3 / §5.1 / §5.8.3.
**Delivered:**
- `src/domain/recurrence.ts` — `expandRRULE(rrule, from, to, { skipDates })` returns the local dates a rule lands on in a window. Parses the RFC 5545 subset: `FREQ=WEEKLY` (with `INTERVAL=n`, so `INTERVAL=2` = biweekly), `FREQ=MONTHLY;BYDAY=<n><DAY>` (nth weekday, incl. `-1` = last) and `BYMONTH`. `parseRecurrence`, `matchesRecurrence`, `validateRecurrence`, `RecurrenceError`. Pure — no DB imports.
- `src/domain/recurrence.test.ts` — 13 tests named after the rule. The 5 required cases: spring-forward Sunday (9 AM local stays 9 AM; stored UTC shifts EST→EDT), fall-back Sunday (UTC shifts back), monthly-nth across Dec→Jan (1st Sunday), cancelled instance not regenerated (skip date excluded), biweekly phase stable (constant 14-day gap). Plus INTERVAL=3, last-weekday, parse/validate.
- `src/db/services.ts` — `listServices({ active })`, `getService`, `createService`, `updateService`, `deactivateService`. `rrule` validated on write; deactivate flips `active` (never delete); `name` frozen on update.
- `src/app/api/dev/services/route.ts` — GET (list, `active` filter), POST (create, 409 on duplicate name), PATCH (edit fields or `active:false` deactivate). Constraint errors mapped to 400/409 like the catalog route.
**No schema change, no migration.** The `services` table already exists (A2) with all fields (`rrule`, `startTime_local`, `duration_minutes`, `doors_open_minutes_before`, `active`, `notes`). D1 owns the template CRUD; `service_role_requirements` stays deferred to a later unit.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run src/domain/recurrence.test.ts` ✓ (**13**) · `next build` ✓ · runtime smoke test: GET/POST/PATCH all correct, DB persistence confirmed (deactivate flips `active=false`, duration update persisted, duplicate name → 409, invalid rrule → 400).
**Decisions:**
- **`expandRRULE` returns local dates; DST lives in the caller.** The function decides the calendar date only; the instance generator (D2) converts each with `localToUtc`, which resolves the offset for the actual instant — so a 9 AM Sunday stays 9 AM across spring-forward / fall-back. The DST tests assert the stored UTC hour shifts by an hour across the transition.
- **Interval phase anchored to 1970-01-04 (a Sunday).** Without a DTSTART, biweekly/triweekly phase is computed against a fixed epoch, so the phase never drifts week-to-week regardless of the window start.
- **nth weekday parsed from the BYDAY token.** `1SU` / `-1WE` carry the position in the token (`ByDayRule.weekday` + `.nth`); `BYSETPOS` was dropped as redundant — the app's "1st Sunday" maps to `BYDAY=1SU`.
- **`rrule` validated on write.** A malformed rule can never reach the generator; `createService`/`updateService` call `validateRecurrence` and reject with a 400 message before touching the DB.
- **Build cache reclaimed.** A prior interrupted `next build` left root-owned files under `.next/` (same class as the earlier `.git/objects` scrub) that blocked rebuilds; `sudo chown -R bhursey:bhursey .next` restored the build. The stale `next start` on :3000 was restarted after the build so the new route loaded.
---
## D8 — Assign/clear mutations (optimistic editor + toast) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** assign/clear with optimistic update + rollback toast. 5 TDD tasks: audit_log, assign conflict gate, route + data layer, optimistic editor, E2E.
**Delivered:**
- `src/db/audit.ts` — `writeAudit()` helper (audit_log table).
- `src/db/assignments.ts` — `assignSlot()` (conflict gate: rejects if slot already has active assignment), `clearAssignment()`.
- `src/app/api/assignments/route.ts` — POST `/api/assignments` (assign), DELETE `/api/assignments` (clear). Zod-validated. `schedule.publish` guard.
- `src/domain/assign.ts` — pure `validateAssignment()` and `validateClear()` rules.
- `src/domain/assign.test.ts` — 8 tests named after the rules.
- `src/components/app/schedule-grid-editor.tsx` — optimistic editor with toast (success + error/rollback).
- `src/components/app/toast.tsx` — toast component.
- `e2e/assign-mutations.spec.ts` — E2E: assign, clear, conflict rejection, volunteer 403.
- `e2e/dev.ts` — shared E2E helpers: `signInAs` (dev magic-link transport), `resetDb` (admin `/api/dev/reset`), `BASE`.
- `playwright.config.ts` — `workers: 1` (single worker for session persistence).
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**182** total) · `next build` ✓
- **Playwright E2E: 8/8 passing** — `e2e/schedule-grid.spec.ts` (2) + `e2e/shell.spec.ts` (4) + `e2e/assign-mutations.spec.ts` (2).
**Commit hashes:** `b664de6` (Task 1 audit_log), `e189507` (Task 2 assign conflict gate), `e47ef83` (uuid fix), `71b993e` (Task 3 route + data layer), `137a135` (Task 4 optimistic editor + toast), `d0a6961` (Task 5 E2E + grid/editor fixes + shared E2E helpers + admin reset), `2cec220` (docs mark complete).
**Next: D9 — auto-fill (in progress).**
---
## D9 — Auto-fill proposals — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** auto-fill — compute proposals for open seats, apply them. Two properties: deterministic for fixed seed, apply is idempotent (second run writes 0 rows).
**Delivered:**
- `src/domain/autoFill.ts` — pure greedy auto-fill algorithm. Orders slots by constraint difficulty (fewest eligible candidates first), assigns top-ranked survivor who is still free and under monthly cap. Reuses D6 `rankCandidates` for per-slot ranking and hard filters. Deterministic for fixed input.
- `src/domain/autoFill.test.ts` — **11 passing tests** covering determinism, hard filters (roster, availability, one-per-instance, core-skill gate), monthly cap, constraint difficulty ordering.
- `src/db/autoFill.ts` — `computeAutoFill()` resolves open seats, volunteer competency, blackouts, monthly counts. `applyAutoFill()` writes one `proposed`/`auto` assignment per proposal that is still free. Idempotent: second run finds every seat already filled.
- `src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts` — GET (preview proposals), POST (apply assignments). Guarded by `schedule.publish`. Next.js 15 `await params` pattern.
- `src/app/api/dev/schedule/instances/route.ts` — helper route returning `{ instances: [{ id, occursOn, serviceName }] }`. Guarded by `schedule.publish`.
- `src/db/seed.ts` — updated with skill taxonomy: 3 categories (Audio, Livestream, Slides), 3 skills, 3 position_skills (each position→its skill, qualified, core), 9 user_skills (volunteers' verified levels). Added `skill_categories` to `RESET_TABLES`.
**Verification (partial):**
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run src/domain/autoFill.test.ts` ✓ (11 tests)
- `next build` ✓
- Standalone script verified: `computeAutoFill()` produces 3 proposals for first instance (Audio→Avery score 98, Livestream→Sam score 79, Slides→Jordan score 78)
- **Playwright E2E: 2/2 pass** (`e2e/auto-fill.spec.ts` — deterministic GET, apply then no-op re-apply, volunteer 403)
**Bugs found while writing the E2E — both root-caused and fixed this session:**
1. **`written=3` but `proposals.length=2`** — The POST response has `written: 3` but `proposals.length: 2`. The assertion `expect(applied.written).toBe(applied.proposals.length)` fails. Debug: check if the first instance has 3 open seats or 2 (seed has 4 assignments — Audio only — which might fill one seat on the first instance). Check if `computeAutoFill` inside `applyAutoFill` returns the same count as the GET. Check the `slotsBySlotId` grouping logic in `computeAutoFill` for potential dedup issues.
2. **`firstInstanceId()` returns non-OK in volunteer test** — The second test signs in as Avery (volunteer) who lacks `schedule.publish` permission. The instances route requires `schedule.publish`, so it returns 401. Fix: fetch instance ID in `beforeAll` (shared) or create a coordinator-scoped helper.
**Fixes applied (the real root causes):**
- **`written` < `proposals.length` was not a counting bug** — the open-seat query trusted `slots.status = 'open'`, but nothing maintains that column (D8 writes assignments only). The seed's confirmed Audio seat still read `open`, so it was re-proposed and `applyAutoFill` correctly skipped it. `computeAutoFill` now defines an open seat as “`slots.status = 'open'` AND no active assignment” (`NOT EXISTS` on proposed/confirmed/completed), so proposals == written and a second apply proposes nothing.
- **The volunteer test's 401** — it fetched the instance id through the coordinator-gated helper route *after* signing in as a volunteer. The id is now resolved once in `beforeAll` under the admin session (shared `firstInstanceId()` in `e2e/dev.ts`).
- **`monthlyServiceCount` was silently ignored** by the pure algorithm (the walk started every volunteer at 0), so rule 7 never applied. `walkCount` is now seeded from each candidate's existing monthly count; the two monthly-cap tests were rewritten to be non-vacuous (an at-cap volunteer is skipped; 2 existing + 1 more is allowed at cap 3).
- **Date handling:** `occursOn`/`lastServedOn` are read as UTC calendar dates / date strings, not `getFullYear()` on a UTC-midnight instant (the D7 day-shift trap), so proposals are timezone-independent.
- **`serviceName` in the instances helper route** returned `title_override` (null in the seed) — it now joins `services` and falls back to the template name, ordered by `(occurs_on, starts_at)` for a stable list.
- Removed the `as never` cast on blackout rows (explicit mapping) and the misleading `adminApproved: verifiedLevel != null` (always true) in the mentor-ready input.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**193** incl. 11 auto-fill) · `next build` ✓
- **Playwright: 12/12 passing** (assign 2 + auto-fill 2 + publish 2 + grid 2 + shell/health 4).
**Files changed:**
```
M src/db/seed.ts
e2e/auto-fill.spec.ts
e2e/dev.ts
src/app/api/dev/schedule/instances/route.ts
src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts
src/db/autoFill.ts
src/domain/autoFill.test.ts
src/domain/autoFill.ts
```
**Next: D10 — publish (done below).**
---
## D10 — Publish / unpublish — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** publish / unpublish — one transaction, validation, audit row, **no notifications yet**. Done when: publish with open slots is blocked unless `allowGaps`; re-publish is idempotent. ARCHITECTURE §5.5.
**Delivered:**
- `src/domain/publish.ts` — pure rules: `validatePublish({ seats, allowGaps })` (a covering seat with no active assignment is a gap and blocks, unless the override; a trainee/shadow seat never counts toward coverage) and `validateUnpublish({ confirmedAssignments })` (§5.5: refused while a volunteer has confirmed).
- `src/domain/publish.test.ts` — 6 tests named after the rules (gap blocks; override publishes but still reports gaps; fully staffed publishes; shadow seat is never a gap; unpublish blocked on a confirmed volunteer; allowed while only proposed).
- `src/db/publish.ts` — `publishInstance()` and `unpublishInstance()`, each **one transaction** (`db.transaction`) that validates, moves `service_instances.status` / `published_at` / `published_by`, and inserts the `week.published` / `week.unpublished` audit row via the pure `auditRow()` builder. Re-publishing an already-published week returns `alreadyPublished: true` with **no write and no second audit row**; unpublishing a non-published week is likewise a no-op. `PublishError` carries a stable code + the gap list.
- `src/app/api/dev/schedule/[instanceId]/publish/route.ts` — POST `{ allowGaps? }` (publish) and DELETE (unpublish), guarded by `schedule.publish`. `open_slots` / `unpublish_blocked` / `instance_cancelled` → **409** with `code` + `gaps`; unknown instance → 404; volunteer → 403.
- `e2e/publish.spec.ts` — 2 tests: blocked 409 with both empty seats listed → `allowGaps` publishes → re-publish is a no-op (`published: false`, same `publishedAt`) → DELETE is refused 409 while the Audio volunteer is confirmed; volunteer POST/DELETE → 403.
- `src/db/seed.ts` — the **second Sunday is now seeded `draft`** (first Sunday stays `published`) so the publish flow has a week to publish; the instances helper route now returns `status` (plus the real `serviceName`).
- `e2e/dev.ts` — shared `firstInstanceId()` helper (resolved under a `schedule.publish` session).
**No schema change, no migration.** `service_instances.status` / `published_at` / `published_by` already exist (A2); `audit_log` landed in D8.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**199** total; D10 = 6) · `next build` ✓
- `pnpm test:e2e` equivalent (`playwright test`, server on the fresh build) — **12/12 pass**, including both D10 tests.
- Live unpublish-success check (not reachable in E2E because the seed has a confirmed volunteer): cleared the confirmed assignment, `DELETE …/publish` → `{ ok: true, unpublished: true }`, instance back to `status='draft'`, `published_at` null, and `week.unpublished` present in `audit_log` alongside `week.published`. DB reset to the canonical seed afterwards.
**Decisions:**
- **Coverage truth is the assignment rows, not `slots.status`.** The slot status is derived and no code maintains it (same root cause as the D9 bug), so publish reads “has an active assignment” with a correlated `EXISTS`. This keeps the gate correct regardless of stale slot status.
- **Idempotent means no-op, not “audit again”.** Publishing twice writes nothing the second time and keeps the original `published_at`; E1 will key notification dedupe off that instant.
- **Both checks are one transaction with the audit row.** An instance cannot flip to published without its `week.published` row, and a refused publish leaves no partial state.
- **D10 sends nothing by design.** `assignment.published` / reminder rows are E1; an email outage can never block a schedule.
- **Draft week in the seed.** The second Sunday is draft so the publish route is exercisable end-to-end without test-only DB writes; the grid still opens on the published first week.
**Next: E1 — outbox (done below).**
---
## E1 — Notification outbox — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** outbox enqueue on publish, `dedupe_key` unique, status enum. Done when: enqueue twice → 1 row; a declined assignment cancels its rows. ARCHITECTURE §6.1.
**Delivered:**
- `src/db/schema.ts` — `notifications` outbox table (§4/§6.1): `id, user_id, channel, template_key, rule_key, assignment_id, slot_id, to_address, payload_json, dedupe_key (unique), scheduled_for, status, attempts, provider_id/provider_status/error, sent_at, created_at, updated_at`, index `(status, scheduled_for)`. Plus `used_tokens` (E4 single-use, PK `jti`). Migration `drizzle/0010_friendly_oracle.sql`.
- `src/domain/notifications.ts` — pure status machine (`queued → sending → sent`, retry back to `queued`, `failed` at the limit, `cancelled` on decline, `suppressed` on no consent) + `notificationDedupeKey(template, ref, channel)`.
- `src/domain/notifications.test.ts` — 10 tests incl. the DB-enum drift guard.
- `src/db/outbox.ts` — `enqueuePublishNotifications()` (inside the D10 publish transaction), `cancelAssignmentNotifications()` (decline), `listNotifications()` (admin log). Enqueue is `ON CONFLICT DO NOTHING` on `dedupe_key`.
- `src/db/publish.ts` — publish now enqueues the `assignment.published` mail in the **same transaction**; re-publish still writes nothing.
**Decisions:**
- **Payload fully merged at enqueue** (subject/html/text/links) — the outbox row is exactly what will be sent, auditable and replayable.
- **No sends from publish.** E1 only writes rows; E2 drains them, so an email outage cannot block a schedule.
**Next: E2 — dispatcher.**
---
## E2 — Dispatcher + E3 email transport — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** E2 cron tick with guards (dedupe → assignment active → consent → quiet hours), retry/backoff; E3 email transport + templates, console transport in dev. Done when (E2): 3 failures → `failed`; quiet-hours SMS reschedules to 08:00. ARCHITECTURE §6.1.
**Delivered:**
- `src/domain/dispatch.ts` — pure rules: `planDispatch()` (terminal → assignment active → volunteer active → channel consent → due → quiet hours for SMS → send), `planFailureRetry()` (3 attempts, 5/30/120-minute backoff), `isWithinQuietHours()` (overnight windows), `quietHoursEndAt()` (next 08:00, DST-safe via `localToUtc`).
- `src/domain/dispatch.test.ts` — 11 tests with a fake clock: backoff ladder, 3 failures → `failed`, quiet-hours SMS → 08:00 next day, email at night still sends, cancel/suppress precedence.
- `src/db/dispatcher.ts` — `dispatchDue()` drains due `queued`/`failed` rows, records `sending`/`sent`/`failed`, requeues with backoff. Missing prefs default to email-on/SMS-off. SMS rows are suppressed until E5 (no half-built channel).
- `src/lib/email.ts` — `EmailTransport` interface, console transport (writes each message to `${OUTBOX_DIR:-/tmp/outbox}` and logs), Postmark adapter over `fetch` (no SDK dependency).
- `src/domain/templates.ts` — pure assignment.published email (subject/html/text, both single-use links, `escapeHtml` on every interpolated value) + 5 tests.
- `src/app/api/dev/cron/notifications/route.ts` — `GET` drives `dispatchDue()` (cron every 5 min).
- `src/app/api/dev/notifications/route.ts` — admin log, guarded by `schedule.publish` (E6's read half).
**Decisions:**
- **Guards are pure and ordered.** The dispatcher only reads/writes; every keep/cancel/suppress/reschedule decision is unit-tested without a DB.
- **No new dependency for email.** Plain TS templates + `fetch` to Postmark keeps the container portable and E3 small; React Email can be layered later without changing the outbox contract.
- **Quiet hours are SMS-only** (per §6.1); email sends at night.
**Next: E4 — magic-link respond.**
---
## E4 — Magic-link respond (confirm/decline without login) — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** signed token, GET renders, POST mutates, single use. Done when: GET does not change state; a second POST with the same jti rejects. ARCHITECTURE §5.6.
**Delivered:**
- `src/lib/respond.ts` — HS256 tokens `{ assignmentId, userId, action, jti }`, +14d, `respondUrl(?t=&a=)`; 4 tests (round-trip, tamper, malformed, URL).
- `src/db/respond.ts` — `getRespondAssignment()` (read-only summary with DST-safe labels) and `applyRespond()`: one transaction consumes the `jti` in `used_tokens` (PK conflict → `already_used`), verifies the volunteer, moves the assignment to `confirmed`/`declined` (`confirmed_via='email_link'`), writes the audit row (`assignment.confirmed`/`assignment.declined`), and cancels pending mail on a decline.
- `src/app/respond/page.tsx` + `src/components/app/respond-form.tsx` — public page: GET renders role/service/date/call time and the two buttons; only the client form POSTs.
- `src/app/api/respond/route.ts` — `POST { token, action }`; invalid/expired → 400, action mismatch → 400, already used / not actionable → 409, unknown → 404.
**Decisions:**
- **The `jti` insert and the status change share one transaction.** Two concurrent clicks cannot both succeed, and a rejected action (wrong volunteer, already confirmed) does not burn the link.
- **GET is inert by construction.** The page never reads for update; only the POST consumes the token — so link prefetchers cannot accept a shift.
- **Decline cancels queued mail** via E1's cancel path, satisfying “declined assignment cancels its rows”.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**229** total; E = 30) · `next build` ✓
- `drizzle-kit generate` → `0010_friendly_oracle.sql`; `drizzle-kit migrate` ✓ (`notifications`, `used_tokens` present)
- `playwright test` — **14/14 pass**, including the phase acceptance chain:
publish a draft week (with auto-filled proposals) → **3 queued emails** rendered at enqueue → first cron tick `sent: 3`, second tick `sent: 0` → `GET /respond` renders and leaves the assignment `proposed` → `POST /api/respond` → `confirmed` → same token again → **409**.
- Live chain against the running build (before the final DB reset): auto-fill wrote **2** proposals → publish with `allowGaps` enqueued **3** emails → tick 1 `sent:3`, tick 2 `sent:0` → `GET /respond` **200** with the role heading and the assignment still `proposed` → confirm POST **200 `confirmed`** → same token again **409 `already_used`**. DB after: 3 `notifications` rows `sent`, 1 `used_tokens` row (`confirm`), 5 confirmed assignments (4 seed + 1). Console transport wrote one JSON message per send under `/tmp/outbox` (files accumulate across runs). DB reset to the canonical seed afterwards.
**Still open in phase E:** E6 (retry/send-test UI; the read-only log is in place) and E7 (reminder rules CRUD — `reminder.friday`, T-7, day-of). E5 SMS is deferred by decision.
**Next: E6 — admin log actions (done below).**
---
## E6 — Admin notification log actions (retry + send test) — DONE 2026-11-19
**Scope (from BUILD-PLAN.md):** admin notification log + retry + "send test to me". ARCHITECTURE §6.1.
**Delivered:**
- `GET /api/dev/notifications` (from E2) now has actions: `POST { action: "retry", id }` requeues a failed/suppressed row for the next tick (terminal `sent`/`cancelled` untouched), and `POST { action: "send_test" }` sends a real message to the signed-in admin through the configured transport and reports its provider.
- `retryNotification()` in `src/db/outbox.ts`.
**Verification:** live `send_test` returned the console provider and wrote a message file; the E2E suite exercises the log read + 403 for volunteers.
**Next: E7 — reminder rules (done below).**
---
## E7 — Reminder rules CRUD (the Friday row) — DONE 2026-11-19
**Scope (from BUILD-PLAN.md):** reminder rules CRUD (offset −2 at 18:00, email+sms). Done when: changing the offset changes the computed `scheduled_for`; no code change needed. ARCHITECTURE §6.2 / §5.5 step 4.
**Delivered:**
- `src/db/schema.ts` — `notification_rules` (`key` unique, `event`, `offset_days`, `send_at_local_time`, `channel_set`, `applies_to_service_id` nullable, `active`). Migration `drizzle/0011_pretty_lilith.sql`.
- `src/domain/reminders.ts` — pure `computeReminderSendAt()` (instance start + offset days at a local time, DST-safe), `isPastSendAt()`, `channelsFor()`, `planReminderSends()` (past sends skipped, never back-dated; ordered by send time).
- `src/domain/reminders.test.ts` — 8 tests: Friday 18:00 for a Sunday service, offset change moves the send time, Wednesday service → Monday, channel sets, T-7/Friday/day-of ordering, past-skip, inactive rules.
- `src/db/reminders.ts` — `listRules` / `createRule` / `updateRule` (partial, no null-out) and `enqueueRemindersForInstance()`, called **inside the publish transaction** after the assignment mail. Dedupe keys `reminder.{key}:{assignmentId}:email`; SMS-only rules enqueue nothing until E5.
- `src/app/api/dev/notification-rules/route.ts` — GET/POST/PATCH, guarded by `schedule.publish`.
- `src/app/api/dev/cron/notifications/route.ts` — the dispatcher tick also drains reminders once due (unchanged code: they are ordinary outbox rows).
- `src/db/seed.ts` — default rules `t_7` (−7 d, 09:00, email), `friday` (−2 d, 18:00, email+sms), `day_of` (0 d, 06:30, sms); added to `RESET_TABLES`.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**237** tests; E7 = 8) · `next build` ✓ · migrations applied.
- E2E (14/14) now also asserts: publishing enqueues 3 `assignment.published` emails **plus 6 future reminders** (`t_7` + `friday` × 3 assignments), the tick sends only the 3 due emails, and future reminders stay `queued`.
- Live (deployed container): publish → tick `{sent:3}`; outbox shows `reminder.t_7` scheduled **2026-11-22 09:00** and `reminder.friday` **2026-11-27 18:00** America/New_York; email files written to the container volume.
**Decisions:**
- **Reminders are ordinary outbox rows.** No second queue and no special send path; the same guards, retries and dedupe apply.
- **Only `proposed`-and-later assignments get reminders**; a declined assignment's rows are cancelled by E4.
- **Email only for now.** The `friday` rule is `email+sms`, but the enqueue emits email until E5 lands; the rule data already expresses the intent.
**Next: deployment (done below).**
---
## Deployment — local container stack — DONE 2026-11-19
**Scope:** run the app as a production container with Postgres (A1's portable stack), verified end-to-end.
**Delivered / fixed:**
- `Dockerfile` — added a **`tools` stage** (from the builder, which has `src`, `drizzle/` and dev deps) for migrations + seed. The runner image has no `src`/`drizzle.config.ts`, so the original `db:migrate && db:seed` could not run there. Pre-created `/tmp/outbox` owned by the runtime user: the first deploy mounted a root-owned volume and every send failed with `EACCES` (the tick reported `rescheduled`, not `sent`).
- `docker-compose.yml` — `APP_PORT` / `POSTGRES_PORT` overridable (deployed with **5434** so the dev Postgres on 5433 is untouched), named `outbox-data` volume for the console transport, migrate service builds `target: tools` and runs `db:migrate && db:seed` (no `db:generate` at deploy time).
- `src/db/seed.ts` — fixed a real idempotency bug: catalog categories were inserted with `ON CONFLICT DO NOTHING` but their ids were read from `.returning()`, which is empty on a re-run, so `skills` inserted `category_id = NULL` and the seed aborted. Categories are now re-fetched by slug before composing skills (the A2 lesson).
**Deployed state (running):**
- `glenlochmedia-app-1` on **:3000**, `glenlochmedia-db-1` (Postgres 16) on **:5434** (container 5432), healthcheck green.
- Fresh volume migrated + seeded: 4 instances, 3 skills, 9 user_skills, 3 reminder rules.
- **Playwright 14/14 against the deployed container** (not the dev server): assign, auto-fill, publish, notifications/confirm, grid, shell.
- Live: publish → tick `{sent:3}` → 3 messages in the container's `/tmp/outbox` volume; `send_test` delivered; seed restored afterwards.
**Notes:** `NEXTAUTH_SECRET` for this local stack defaults to `dev-only-secret-change-me` — set a real one for anything reachable. Postmark is wired but untested against a live account; the console transport is what the deployment exercises.
---
## Admin interface — role-aware UI over existing APIs — DONE 2026-11-19
**Scope (user request):** signing in as admin showed view-only pages — the data layer and routes existed, but there was no admin surface. Built the missing UI on top of them.
**Delivered:**
- `src/db/admin.ts` — `listUsers()`, status-ranked so pending approvals come first.
- `/admin` (admin-only; `admin.settings`) with three panels:
- **People** — invite by email (shows the generated sign-in link), approve/deny pending sign-ups.
- **Reminder rules** — list, create, pause/resume (`notification_rules` CRUD already existed).
- **Notifications** — outbox log with attempts/errors, retry for failed/suppressed rows, send-test email.
- **Schedule** — `ScheduleAdminBar` for coordinators/admins: auto-fill, publish, unpublish. Publish with open seats is refused by the API (409 `open_slots`) and surfaces as an explicit **Publish anyway** action, never a silent override.
- **Roster** — active team list (name, role, email) instead of an empty state; admins get a link to `/admin`.
- **Settings** — real deployment facts (church timezone, Sunday week start, email transport, signed-in account) plus the admin link.
- **Nav** — admin-only "Admin" tab; volunteers/coordinators keep the original five tabs.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**244**) · production image build ✓
- Playwright **17/17** against the rebuilt container, including new `e2e/admin.spec.ts`: invite → pending → approve; send-test + rule pause/resume; publish a draft week through the gap override.
- Admin page inspected in Chromium at 1280px (layout, tables, actions).
**Notes:** role changes/deactivation are not in this pass (no API yet); Training and Announcements remain placeholders for their phases (F/J); SMS rules still queue nothing until E5.
---
## Admin content + schedule building + calendar views — DONE 2026-11-19
**Scope (user request):** settings for email/notifications, training authoring with uploads, schedule building, and week/month/year calendar views.
**Delivered:**
- **Settings** — `app_settings` key/value table (migration `0012_admin_content.sql`); admin form for the outbound **From address** and an optional **admin notification inbox**. The dispatcher and `send_test` read these at send time, so no deploy/restart is needed. Provider credentials stay in env (`POSTMARK_SERVER_TOKEN`).
- **Training** — `training_lessons` + `training_resources`. Admins (`training.author`) create/edit/publish/delete lessons with plain-text bodies and upload attachments (images/PDF/text/Word, ≤5 MB). Bytes live under `UPLOAD_DIR` (`/tmp/uploads` + named `uploads-data` volume); metadata in Postgres; files served only to signed-in users via `/api/training/files/:id`. Volunteers see published lessons and attachments but no authoring controls. Two starter lessons are seeded.
- **Schedule building** — admin **Services & schedule** panel: add recurring service templates (name, start time, duration, location), deactivate them, and run the idempotent instance generator for the rolling window. `/api/dev/services` and `/api/dev/cron/instances` are now guarded by `schedule.publish` (they were unguarded).
- **Calendar views** — `/schedule?view=week|month|year` with a view toggle and prev/next per lens. Month renders a Sunday-first grid of service chips linking into the editable week; year renders 12 month cards with service/publish/draft counts. Week keeps the editable grid + publish/auto-fill bar. Pure helpers in `src/domain/calendar.ts` (`monthRange`, `monthCells`, `shiftMonth`, `calendarWeekStart`, …).
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**249**, +5 calendar tests) · production image build ✓
- Migration `0012` applied to the deployed DB (tables verified, 2 lessons seeded); uploads volume created.
- Playwright **22/22** against the rebuilt container: existing suites plus `admin`/`settings` (sender + inbox persist), `training` (author lesson, upload, volunteer sees it without authoring), `calendar` (week→month→year, 12 month cards), `services` (add service, generate instances).
- Month and training pages inspected in Chromium; fixed duplicated time labels in month chips.
**Notes:** month/year are read-only overviews (edit in the week). Training bodies are plain text (no rich-text editor or completion tracking yet). Services are deactivate-only; reactivation has no API. The generator now requires `schedule.publish`, so an external cron would need a credential.
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
---
## Admin — competency surfaces (skills matrix + positions) — DONE 2026-11-19
**Scope (continuation of the admin build-out):** the two admin screens whose data layers and APIs already existed but had no UI — the C3 skills matrix with the verify-level form, and the B4 positions requirements editor. Both were explicitly deferred to "the admin surfaces" when their units landed.
**Delivered:**
- `src/components/app/admin/skills-matrix-panel.tsx` — the matrix grid (person, skill, category, self comfort, verified level, last served) with a verified-level filter and an inline **verify-level form** per row (level, basis kind, notes). Level default is the next rung up. The panel only ever shows server-rendered rows; a save appends an assessment and the volunteer's `self_comfort` is never written.
- `src/components/app/admin/positions-panel.tsx` — positions table (seats, call time, requirement summary, active state) plus the **requirements editor**: per-row skill/weight/required-level/core, add/remove, and a "publishable" flag. A publishable save without a core skill surfaces the 400 from the B4 gate verbatim instead of silently downgrading.
- `src/app/(app)/admin/page.tsx` — two new cards ("Skill levels", "Positions & requirements") fed by server-side reads (`listSkillsMatrix`, `listPositions({active:false})`, `listSkills`, `getPositionSkills`). Assessment kinds are passed from the DB enum so the form can't drift from `ASSESSMENT_KINDS`.
- **Security fix:** `/api/dev/skills`, `/api/dev/positions`, `/api/dev/positions/requirements`, `/api/dev/skills/matrix`, `/api/dev/skills/verify` had **no authorization at all** — anyone could verify skill levels or rewrite requirements. All are now gated by `training.author` (admin) through a new shared helper `src/auth/api.ts` → `gateOrUser(permission)`, which returns the signed-in user or the 401/403 response. Same class of hole as the `/api/dev/services` + cron guards closed in the previous unit.
- **Assessor is server-owned.** The verify route no longer accepts `assessorId` from the client; it uses the signed-in admin's id, so a caller cannot attribute a sign-off to someone else.
- `e2e/admin.spec.ts` — new test: promote a seeded competency through the UI, confirm it persisted via the matrix API, then exercise the requirements editor's publishable-without-core refusal and the successful (non-publishable) save.
**No schema change, no migration.**
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**249**) · `next build` ✓
- Container rebuilt (`docker compose up -d --build`) and healthy on :3000.
- **Playwright 4/4** on `e2e/admin.spec.ts` against the rebuilt container, including the new matrix/requirements test.
**Decisions:**
- **One gate helper, not five copies.** Five route files needed the same check; `gateOrUser` keeps the response shape identical (`{ error, code }` + status) and makes a missing check visible at the top of each handler.
- **Verify form is inline, not a modal.** No dialog primitive exists in `src/components/ui`; an expanded row keeps focus and keyboard flow simple and avoids adding a dependency for one form.
- **Requirements save states its publishability explicitly.** `roles` has no stored publish state, so the editor's "publishable" checkbox is what drives the B4 gate; the admin sees the refusal rather than the API guessing intent.
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
---
## Admin — user management (add / edit all fields / remove) — DONE 2026-11-19
**Scope (user request):** the admin must be able to add and remove users and edit all of a user's details. Before this, People could only invite by email and approve/deny; role changes, profile fields and removal had no API at all.
**Delivered:**
- `src/db/users.ts` — `listUsersForAdmin` (the full editable record, pending first), `getUserById`, `createUser`, `updateUser`, `deleteUser`, plus the two facts the removal rules need: `hasAssignmentHistory` and `countOtherActiveAdmins`. `updateUser` is partial — `undefined` leaves a field alone, `null` clears it.
- `src/domain/users.ts` + `src/domain/users.test.ts` (**12 tests**) — the pure policy: `normalizeUserEmail` (login key), `displayNameFor` (explicit → full name → first name), `isActiveAdmin`, `wouldLeaveNoAdmin`, `removalPlan`.
- `src/app/api/dev/users/route.ts` — `GET`/`POST`/`PATCH`/`DELETE`, all gated by `users.manage` (admin) through `gateOrUser`. Every mutation writes an audit row (`user.created` / `user.updated` / `user.deleted`). Create returns a magic-link sign-in URL like the invite flow; duplicate email → 409.
- `src/components/app/admin/people-panel.tsx` — rewritten as a real user manager: add form (first/last name, email, phone, role, "needs approval"), approve/deny for pending sign-ups, a per-row editor for **every** editable field (names, display name, email, phone, timezone, role, status, emergency contact, notes, deactivated), deactivate/reactivate, and delete with confirmation.
- `src/auth/roles.ts` — `SYSTEM_ROLES` is now a real `as const` tuple so the route schema can use `z.enum(SYSTEM_ROLES)` without a second copy of the role list.
- `e2e/admin.spec.ts` — the People test now covers add → pending → approve → edit (name, role, phone, emergency contact, notes) → persisted via the API → deactivate → delete.
**Two safety rules, enforced server-side and unit-tested:**
- **The last active admin can never be demoted, deactivated or deleted** (`wouldLeaveNoAdmin`, 409) — otherwise nobody can reach `/admin` again.
- **A person with scheduling history is deactivated, not deleted** (`removalPlan`, 409 with the reason). `assignments.user_id` is `ON DELETE RESTRICT`; deleting the row would rewrite who served in past published weeks. Accounts with no history delete outright.
**No schema change, no migration** — every field already existed on `users`.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**261** total; +12 for the user rules) · `next build` ✓
- Container rebuilt (`docker compose up -d --build`), healthy on :3000.
- **Playwright 4/4** on `e2e/admin.spec.ts` against the rebuilt container, including the rewritten add/edit/remove test.
- Found while running it: editing a first name did not change the displayed name — correct, because `display_name` is its own stored field. The E2E now edits the display name explicitly (and asserts both the row and the API).
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
---
## Admin — per-person skill levels + removal takes competency rows — DONE 2026-11-19
**Scope (user request):** removing a user must also remove their skill-level entries; admins need to edit those entries per person and delete individual rows; a new entry defaults to `none`.
**Delivered:**
- `src/db/users.ts` — `deleteUser` now runs one transaction that deletes the person's `user_skills` rows **and** the user row. The FK already cascades, but the explicit delete makes the behaviour part of the contract (and rolls back if the user cannot be removed).
- `src/db/userSkills.ts` — `getUserSkill(userId, skillId)`, `addUserSkill(userId, skillId, level = "none")`, `deleteUserSkill(userId, skillId)`. `setSelfComfort` (volunteer path) is unchanged and still never touches `verified_level`.
- `src/app/api/dev/user-skills/route.ts` — the admin half of the competency API:
- `GET` now requires a session (`schedule.view`); `POST` (comfort) likewise — it was unguarded.
- `PATCH { userId, skillId, verifiedLevel }` (`users.manage`) — an existing record moves through `verifySkillLevel`, so **every** level change (up or down) appends its `skill_assessments` row; the assessor is the signed-in admin. A missing record is created at `none` with nothing to audit; a higher first level goes through the audited path.
- `DELETE ?userId=&skillId=` (`users.manage`) — removes one competency row. Assessment history is deliberately kept: it records what was verified and when, which stays true after the current entry is gone.
- `src/components/app/admin/people-panel.tsx` — the per-row editor now has a **Skill levels** section: the person's entries (skill, level select, their self-comfort as read-only context, Remove) and an **Add skill** picker. New entries start at `none`; the picker hides skills the person already has.
- `src/app/(app)/admin/page.tsx` — passes the active skills to the panel.
- `e2e/admin.spec.ts` — the People test now also: adds a skill (asserts level `none`), raises it to `qualified`, adds a second entry, deletes the first row, and after deleting the person asserts `GET /api/dev/user-skills` returns **0 rows**.
**No schema change, no migration.** `user_skills.verified_level` already defaults to `none` and `user_id` already cascades.
**Verification (all exit 0):**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**261**) · `next build` ✓
- Container rebuilt, healthy on :3000; **Playwright 4/4** on `e2e/admin.spec.ts` (add → approve → edit → skill add/level/remove → deactivate → delete → competency rows gone).
**Still open on the admin page:** catalog taxonomy CRUD (B3) and the skill composer (C1) have APIs but no screen; Training and Announcements remain their own phases (F/J).
---
## Maintenance — orphan sweep for user-owned rows (`pnpm db:prune`) — DONE 2026-11-19
**Scope (user request):** clear stale skill levels belonging to users that had been deleted.
**Delivered:**
- `src/db/cleanup.ts` — `pruneOrphanedUserData()`: one transaction that counts and deletes rows in every user-owned table (`user_skills`, `skill_assessments`, `growth_goals`, `unavailability`, `notifications`, `notification_preferences`) where `user_id` has no matching `users` row. Idempotent; only rows without a live owner are touched.
- `src/db/prune.ts` + `pnpm db:prune` — CLI that prints per-table counts and exits explicitly (the postgres.js pool otherwise keeps the process alive, same as the seed CLI).
**Run against the live DB (host :5433 — the compose db container; it had been re-created on the default port, which is why the first attempt at :5434 got ECONNREFUSED):**
```
user_skills: 0 orphaned row(s) removed
skill_assessments: 0 orphaned row(s) removed
growth_goals: 0 / unavailability: 0 / notifications: 0 / notification_preferences: 0
No orphaned user rows found — every row has a live owner.
```
- Verified directly: `user_skills` = 9 rows, **0 orphans**; 0 orphans in all six tables. All 9 rows belong to live accounts (avery, jordan, sam — 3 each).
- Root cause is covered by the schema + the delete path: `user_skills.user_id` is `ON DELETE CASCADE` and `deleteUser()` also deletes the rows in the same transaction as the user (previous unit).
- Re-ran the CLI a second time → 0 removed (idempotent).
**Verification:** `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (261) · prune run twice ✓.
**Note:** rows belonging to *deactivated* people are intentionally kept (deactivation preserves history); only rows whose user no longer exists are swept.
---
## Security & correctness repair pass — DONE 2026-11-19
**Scope:** fix everything found in the full project audit (see `docs/PROJECT-STATE.md`), then re-verify end to end.
**Security**
- Added `gateCron()`/`gateSelfOr()` and hardened `gateOrUser()` (rejects a session without a stable id).
- Guarded the previously open routes: `approve`, `deny`, `invite` (`users.manage`), `catalog`, `skills/compose`, `skills/assessments` (`training.author`), `cron/slots`, `cron/notifications`, `cron/instances` (`schedule.publish` or `CRON_SECRET`), `profile` and `unavailability` (self-or-`users.manage`/`schedule.publish`). Legacy approve/deny/invite now use the signed-in actor, not a client-supplied id.
- **Magic links:** single-use (`used_magic_tokens` + `jti` consumed at `/api/dev/complete`), 10-minute tokens, rate-limited in production, auto-activation now defaults **off**, and the console transport no longer returns/prints the URL unless `MAGIC_LINK_DEV_TRANSPORT=true` (production sends it through the configured transport).
- `/api/dev/reset` requires `ALLOW_DEV_RESET=true` **and** an admin session.
- `PUBLIC_ORIGIN` (when set) is authoritative for generated/emailed links, removing Host-header control of confirm links.
- Respond POST is rate-limited; TCPA consent IP is recorded from the request, not the body.
- Security headers in `next.config.ts`; upload bytes are signature-checked against the declared MIME; non-image attachments download with `nosniff`.
**Scheduling correctness**
- Manual assignment now runs the full conflict engine (roster, duplicate, core-skill level, shadow pairing + soft warnings).
- Grid read is one joined query, active assignments only, and renders **every seat** for a position with headcount > 1.
- Editor serializes optimistic mutations and confirms only the slot that succeeded, so clear→assign no longer races and a failed second assign rolls back correctly.
- `slots.status` is kept in sync on assign/clear/auto-fill/confirm/decline.
**Notifications**
- Adding a seat to a published week enqueues its mail/reminders; clearing a seat cancels its queued rows before delete; unpublishing cancels the instance's queued rows.
- Dispatcher claims rows atomically, recovers `sending` rows older than 10 minutes, and treats a missing assignment as cancelled. Retry is restricted to `failed`/`suppressed`.
**Data / operations**
- Migration `0013_fearless_gravity.sql`: `used_magic_tokens`, `user_skills.mentor_approved_*`, unique `lower(users.email)`, `notification_rules` channel CHECK.
- Mentor approval is now persisted (`mentor_approved_at/by`) with an admin toggle in the People panel; auto-fill/assignment use it instead of inferring from the level.
- `approvedAt` is set/cleared on status transitions; approval is derived from `status === active && !deactivatedAt`.
- New post-service cron `GET /api/dev/cron/complete` closes past assignments and maintains `user_skills.last_served_on` / `users.last_served_at` (idempotent).
- CI now runs on `master`, with a Postgres service, migration-drift check and Playwright; Playwright DB URL is overridable.
- `.env.example` and compose env describe the real variables; compose keeps the local console login working (`MAGIC_LINK_DEV_TRANSPORT=true`) and reset off.
**Verification (all green)**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**36 files / 278 tests**) · `next build` ✓
- Playwright **24/24** against the rebuilt app (including the updated assign scenario: Sam is qualified for both seats, so only rule 1 can reject the duplicate).
- `drizzle-kit migrate` applied `0013`; container rebuilt and healthy on :3000.
**Still open:** rich text/announcements (F1), exports/ICS/swaps (G), full event seats/reminders (J remainder), SMS (E5), retention/pruning for notifications, magic tokens, used tokens and orphaned upload files, reminder-count/reliability metrics, and a distributed rate limiter if the app is ever horizontally scaled.
---
## Event photography & shared RAW folders — DONE 2026-11-19
**Request:** add a photographer section where a photographer can be assigned to an event, create an event folder, upload RAW/edited images, and another assigned photographer can download them to edit. (Reference: Immich's album/upload model.) Answer: yes — implemented as a vertical slice rather than only a plan.
**Data model (migration `0014_nifty_calypso.sql`)**
- `events` — title, type, local-time `starts_at`, location, shot brief, creator.
- `event_photographers` — PK `(event_id, user_id)`, role `photographer | second_shooter | editor`, assigned_by/at.
- `event_folders` — unique `(event_id, name)`, kind `originals | edited | mixed`.
- `event_photos` — metadata only; unique `(folder_id, checksum_sha256)` dedupes re-uploads; kind `raw | image`; uploader RESTRICT.
**Access model (`src/lib/event-access.ts`)**
- Managers (`schedule.publish` = coordinator/admin) see every event, assign/remove people, and can contribute.
- Only assigned photographers/editors see an event; all assignees can create folders, upload, and download each other's files. Unassigned users get 404 (not 403) so event existence is not leaked.
- Delete is uploader-or-manager only. UI hides controls to match.
**Storage & upload**
- `src/lib/event-photos.ts`: extension allow-list for JPEG/PNG/WebP/GIF/AVIF/HEIC/TIFF/PSD plus CR2/CR3/NEF/ARW/DNG/RAF/ORF/RW2/…; MIME derived server-side; generated `events/<eventId>/<photoId>.<ext>` paths with traversal guard; safe RFC 6266 dispositions.
- Upload is a **single raw request body**, not multipart: `POST /api/events/:id/folders/:folderId/photos?name=…` streams to disk through a size/hash transform (200 MB cap), so a 100 MB RAW frame is never buffered in memory. SHA-256 is computed during the write; duplicate bytes return the existing row instead of a second copy.
- Images are inline-only for browser-renderable formats; RAW/TIFF/PSD force `attachment`. Downloads stream from disk with private caching and `nosniff`/CSP headers.
**UI**
- Nav gains **Events**; `/events` shows upcoming/past (managers see all + create form, photographers see assignments), `/events/[id]` shows brief, assignees and folders, `/events/[id]/folders/[folderId]` is the gallery and uploader.
- Uploads run sequentially with per-file status; gallery previews JPEG/PNG/WebP and shows a RAW file tile; every file has Download; uploader/manager sees Delete.
- Folder creation is available to any assignee; photographer assignment is manager-only.
**Verification**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**38 files / 292 tests**) · `next build` ✓
- Removal guard: a person who uploaded event photos cannot be hard-deleted (FK RESTRICT); `removalPlan` now returns a clear "deactivate instead" conflict, with a unit test.
- Playwright **28/28** (4 new): coordinator creates event + assigns Avery and Sam → Avery creates folder and uploads a PNG + CR3 → Sam downloads the PNG byte-for-byte → Jordan (unassigned) gets 404.
- `0014` applied to the compose Postgres; app container rebuilt and healthy.
**Known limits:** no server-side thumbnails/transcoding (full JPEG is used for previews), no ZIP folder download, no public gallery or culling/consent flow, no storage quota/retention, and event seats are not yet part of the weekly scheduling/publish pipeline (`slots.event_id` remains unlinked).
### Post-feature fix — stale sessions on upload (2026-11-19)
**Symptom:** a real upload after the E2E reset failed with a 500 and the generic "upload failed" message. Container logs showed `event_photos_uploader_id_users_id_fk` rejecting the session's user id — the JWT still carried the pre-reset id.
**Fix:** `gateOrUser` now re-reads `users` on every guarded request and rejects missing/inactive/deactivated accounts with `401 STALE_SESSION`; it also uses the DB role, not the JWT role. The photo gallery detects 401, shows "Your session expired" and sends the user to `/login`. Re-verified with a fresh magic-link session through the running container: create event → create folder → raw-body PNG upload → `201`, row present, bytes written. Test artifact cleaned up afterward.
---
## Event deletion + announcements — DONE 2026-11-19
**Request:** admins can delete photo events and their files; announcements can be created from the admin side.
**Event deletion**
- `DELETE /api/events/:id` (manager / `schedule.publish`): verifies access, deletes the event in a transaction (folders and photo metadata cascade), then recursively removes `UPLOAD_DIR/events/<eventId>` and writes `event.deleted` to the audit log with the photo count.
- Delete is offered on the event detail page as a destructive button with a confirmation; it is hidden from assigned photographers without the manager role.
- `eventPhotoDir()` is the traversal-guarded path helper; delete is best-effort on bytes so a storage error cannot leave a half-deleted event row.
- E2E: after uploads, the manager deletes the event; detail URL and previously downloadable photo both return 404.
**Announcements**
- Migration `0015_vengeful_sabra.sql` + `announcements` table: title, plain-text body, published flag, author, timestamps.
- `/api/announcements` — signed-in GET (published only; drafts for authors), and `content.author` POST/PATCH/DELETE.
- `/announcements` is now a real feed: admins/coordinators create posts (publish now or draft), publish/unpublish and delete; volunteers see published posts with no authoring controls. Bodies render as text, never HTML.
- `notifications`/seed reset includes the new table; E2E covers admin create → volunteer visibility → unpublish hides it.
**Verification**
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**38 files / 293 tests**) · `next build` ✓
- Playwright **32/32** against a **separate `media_e2e` database** (migrated + seeded), so the development DB and the user's session/data are not reset by tests.
- `0015` applied to the dev Postgres; container rebuilt and healthy on :3000.