# Media Team Hub — Project State & Agent Map **Audit / repair date:** 2026-11-19 **Branch:** `master` **Last commit:** `2cec220` — *docs(D8): mark D8 complete — all checks green* **Working tree:** all D9–E7, admin/training/calendar/settings work **and the security/correctness repair pass** are uncommitted. This is the single largest operational risk in the repo (see §16). **Audit scope:** full source read (`src/**`, `e2e/**`, `drizzle/**`, Docker/CI/config), followed by a repair pass, an event-photography feature slice, and a full re-verification. **Verified after the repair pass** | Check | Command | Result | | --- | --- | --- | | Unit tests | `./node_modules/.bin/vitest run` | **38 files, 293 tests passed** | | Typecheck | `./node_modules/.bin/tsc --noEmit` | **exit 0, no output** | | Lint | `./node_modules/.bin/eslint src e2e` | **clean** | | Production build | `./node_modules/.bin/next build` | **exit 0** | | E2E (Playwright) | `./node_modules/.bin/playwright test` | **32/32 passed** against the isolated `media_e2e` database | | Migration | `drizzle-kit migrate` | `0015_vengeful_sabra.sql` applied | | Container | `docker compose up -d --build app` | rebuilt, healthy, `/api/health` 200 | > **Read this document first, then `.agent/PROGRESS.md` (the canonical build log) and `.pi/DEAD_ENDS.md` (recurring traps).** > `README.md` points here. `docs/ARCHITECTURE.md`, `docs/BUILD-SPEC.md`, `docs/BUILD-PLAN.md`, `docs/FEATURE-SUMMARY.md` remain the product spec. --- ## 1. Executive summary Media Team Hub is a **working, container-deployed church media-team scheduling and training app**. The core loop is complete end to end: recurring services → instances → seats → assign / auto-fill → publish → queued email → cron dispatch → one-click confirm/decline → reminders → post-service completion. Competency tracking, a real admin console, training lessons with uploads, and week/month/year calendars are also in place. A first **event-photography** slice lets coordinators assign photographers to one-off events and lets those photographers share RAW and edited files in per-event folders. **Architecture in one paragraph.** Next.js 15 App Router (React 19, TypeScript strict) on a Node container, Postgres via Drizzle ORM, Auth.js v5 JWT sessions with a magic-link credentials provider. Business rules live in **pure, unit-tested modules under `src/domain/`** (no DB imports). `src/db/*` resolves joins and applies those rules inside transactions. Server Components read; client components interact and POST to route handlers. Notifications are an **outbox table** drained by guarded cron routes, so publishing never depends on email availability. Email transports resolve at send time: Gmail SMTP (admin-configured, encrypted at rest) → Postmark → console/file transport. **Strong points** - One pure rule per domain module, named tests, reused across auto-fill, conflicts, readiness and ranking. - Idempotency as a first-class pattern: instance generation, slot materialization, auto-fill apply, outbox dedupe keys, publish/unpublish no-ops, completion job. - Correct transaction boundaries for publish + audit + outbox, claim consumption + status + audit, and clear + notification cancel + audit. - Deliberate timezone handling (UTC instants, local dates, the `occurs_on` UTC-midnight trap). - DB-level invariants: one active assignment per slot, slot parent XOR, shadow needs a paired mentor, unavailability span checks, case-insensitive unique email. **Repair pass (what changed since the first audit)** - Ten unguarded API routes are now authorized; legacy approve/deny/invite use the signed-in actor. - Magic links are single-use, production rate-limited, auto-activation defaults off, and the console URL is only returned when explicitly enabled. Production delivers the link through the mail transport. - `POST /api/dev/reset` requires `ALLOW_DEV_RESET=true` plus an admin session. - Manual assignment now enforces the **full** hard-conflict set, not just the duplicate rule. - The grid renders every seat, reads only active assignments, and is one query instead of N+1. - Optimistic edits are serialized and roll back per slot correctly. - Post-publish assign/clear, unpublish and declines reconcile the outbox. - The dispatcher claims rows atomically, recovers stuck `sending` rows, and refuses to retry terminal rows. - A completion job maintains `last_served_on` / `last_served_at` after services end. - Mentor approval is persisted and editable; approval semantics no longer depend on a nullable timestamp. - Uploads are signature-checked; non-image attachments download with `nosniff`; baseline security headers added. - CI now targets `master` and runs migrations, E2E and build against its own Postgres. - **Event photography MVP:** `events`, photographer/editor assignments, per-event folders, extension-validated RAW/JPEG uploads streamed to the uploads volume, dedupe by SHA-256, authenticated downloads, and an E2E proving one photographer's file downloads byte-for-byte for another. --- ## 2. Phase / unit status | Phase | Units | State | | --- | --- | --- | | **A** Foundation | A1 scaffold/container, A2 schema+seed, A3 auth, A4 app shell | DONE (committed) | | **B** People + taxonomy | B1 invite/approve/deny, B2 profile/prefs/SMS consent, B3 catalog CRUD, B4 positions+skills+requirements | DONE (committed) | | **C** Competency | C1 composer, C2 self-comfort, C3 assessments/matrix, C4 readiness, C5 mentor, C6 goals+shadows | DONE (committed) | | **D** Scheduling | D1 services/rrule, D2 instances, D3 slots, D4 blackouts, D5 conflicts, D6 ranking, D7 grid, D8 assign/clear, D9 auto-fill, D10 publish | D9/D10 code done, uncommitted | | **E** Notifications | E1 outbox, E2 dispatcher, E3 transport, E4 respond, E6 log actions, E7 rules | uncommitted; **E5 SMS deferred** | | **Extras** | Admin console, training/uploads, calendars, runtime settings, prune CLI, Docker deploy | uncommitted | | **Repair** | Security, assignment correctness, notification reconciliation, completion job, CI/env/docs | DONE, uncommitted | | **Event photography (MVP)** | Events + photographer/editor assignments, shared folders, streamed RAW/JPEG uploads, downloads, manager event deletion + file cleanup, E2E | DONE, uncommitted | | **Announcements** | Admin/coordinator authoring, publish/unpublish, delete, published-only volunteer feed, E2E | DONE, uncommitted | | **Not started** | F1 rich text (TipTap) + sanitize, G exports/swaps, full J event seats/reminders/publish pipeline, I launch pass | — | --- ## 3. Stack, runtime, deployment ### Versions - Next.js `15.5.29`, React `19.1.0`, TypeScript 5, Node 22 - Tailwind CSS 4, local shadcn-style primitives (Radix Slot/Label, CVA, clsx, tailwind-merge, lucide-react) - Drizzle ORM `0.45.4` + `drizzle-kit 0.31.11`, driver `postgres` (postgres.js) - Auth.js / `next-auth 5.0.0-beta.32`, `jose` - `nodemailer` (Gmail SMTP), `zod 4` - Vitest 5, Playwright 1.65 The planning docs target Cloudflare Workers/D1/R2; the implementation is a portable Node container + Postgres + local volumes + HTTP cron routes. ### Deployment - `Dockerfile` — multi-stage (`base` → `builder` → `tools` → `runner`), non-root runtime, pre-created `/tmp/outbox` and `/tmp/uploads`. - `docker-compose.yml` — `app` + `db` (Postgres 16) + one-shot `migrate` under the `tools` profile. Host ports: app `3000`, Postgres `5433` by default. Volumes: `pgdata`, `outbox-data`, `uploads-data`. - Migrations are **not** run by `docker compose up`; run `docker compose --profile tools run --rm migrate`. - Local compose defaults keep the console login usable (`MAGIC_LINK_DEV_TRANSPORT=true`) and keep the destructive reset **off**. ### Environment variables `.env.example` now reflects the real set. | Variable | Used for | Notes | | --- | --- | --- | | `DATABASE_URL` | Postgres | `postgres://media:media@localhost:5433/media` locally | | `NEXTAUTH_SECRET` / `AUTH_SECRET` | Auth.js, HS256 tokens, **at-rest encryption key** | Rotating it makes the stored Gmail password undecryptable (treated as unset) | | `NEXTAUTH_URL` / `AUTH_URL` / `APP_ORIGIN` | Fallback origin | Runtime links prefer `PUBLIC_ORIGIN`, else the request origin | | `PUBLIC_ORIGIN` | **Canonical origin for emailed links** | Set in any non-LAN deployment; otherwise a client-supplied Host can influence links | | `AUTO_ACTIVATE_NEW_USERS` | Magic-link signup | **Default false**; must be exactly `true` to auto-activate | | `MAGIC_LINK_DEV_TRANSPORT` | Console sign-in transport | Defaults on outside production; compose sets `true`; production default false (sends mail) | | `ALLOW_DEV_RESET` | `POST /api/dev/reset` | Must be `true`; E2E sets it, production does not | | `CRON_SECRET` | HTTP cron auth | `Authorization: Bearer …` or `?secret=…`; empty = session-only | | `POSTMARK_FROM`, `POSTMARK_SERVER_TOKEN` | Email sender/Postmark | Admin settings override the sender | | `OUTBOX_DIR`, `UPLOAD_DIR` | Console mail / attachments | `/tmp/outbox`, `/tmp/uploads` | | `CHURCH_TIMEZONE` | Settings display | Code uses `src/lib/tz.ts` | | `SENTRY_DSN` | Declared, unused | No observability wired | `.env` exists locally and was not read. --- ## 4. Repository map ``` . ├── .agent/PROGRESS.md Canonical build log (units, decisions, bugs, repair pass) ├── .pi/DEAD_ENDS.md Append-only ledger of proven traps ├── .github/workflows/ci.yml master branch: drift check → typecheck → lint → test → migrate → e2e → build ├── docs/ │ ├── ARCHITECTURE.md Product architecture spec │ ├── BUILD-SPEC.md Screen-by-screen spec + 18 rules │ ├── BUILD-PLAN.md 56 units / 10 phases │ ├── FEATURE-SUMMARY.md Plain-language feature list │ ├── PROJECT-STATE.md ← this document │ └── superpowers/ Per-unit handoffs + D8 plan/spec ├── drizzle/ 16 migrations (0000–0015) + snapshots + journal ├── e2e/ 11 spec files + shared helpers ├── src/ │ ├── app/ Routes, pages, route handlers │ ├── auth/ Auth.js config, permissions, gates, magic links, invites │ ├── components/ app-level + ui primitives │ ├── db/ Schema + data access + seed/prune/complete jobs │ ├── domain/ PURE business rules │ └── lib/ tz, uuid, secret, email, uploads, respond, rate limit, utils ├── Dockerfile / docker-compose.yml ├── drizzle.config.ts ├── next.config.ts Baseline security headers ├── playwright.config.ts workers:1, env-overridable DB URL ├── vitest.config.ts └── package.json ``` ### Scripts | Script | Purpose | | --- | --- | | `pnpm dev` | `next dev --turbopack` | | `pnpm build` / `start` | production build / start | | `pnpm typecheck` | `tsc --noEmit` | | `pnpm lint` | `eslint .` | | `pnpm test` / `test:watch` | Vitest | | `pnpm test:e2e` | Playwright (starts its own built server) | | `pnpm db:generate` / `db:migrate` / `db:seed` | Drizzle + seed | | `pnpm db:prune` | orphan sweep for user-owned rows | --- ## 5. File-by-file map ### `src/app` — pages and route handlers | File | Role | | --- | --- | | `layout.tsx`, `page.tsx` | Root layout; `/` → `/schedule` | | `login/page.tsx` | Magic-link request; shows the link only when the dev transport returns it | | `respond/page.tsx` | Public confirm/decline page from an emailed token | | `globals.css` | Tailwind 4 + design tokens | | `(app)/layout.tsx` | Session gate for the app group | | `(app)/schedule/page.tsx` | Week/month/year lenses; role-aware editor/admin bar | | `(app)/roster/page.tsx` | Active team table | | `(app)/training/page.tsx` | Lessons; admin authoring | | `(app)/announcements/page.tsx` | Team feed; authors create, publish/unpublish and delete | | `(app)/settings/page.tsx` | Deployment facts + admin email form | | `(app)/admin/page.tsx` | Admin hub: People, Skill levels, Positions, Services, Reminders, Email, Notifications | | `(app)/events/page.tsx` | Upcoming/past events; managers create; photographers see their assignments | | `(app)/events/[id]/page.tsx` | Brief, assigned photographers, shared folders | | `(app)/events/[id]/folders/[folderId]/page.tsx` | Photo gallery, upload, download, delete | | `api/health/route.ts` | `{ status: "ok", time }` | | `api/auth/[...nextauth]/route.ts` | Auth.js handlers | | `api/admin/route.ts` | Permission chokepoint demo | | `api/assignments/route.ts` | Assign/clear with full conflict engine + outbox reconciliation | | `api/respond/route.ts` | Token confirm/decline (rate-limited) | | `api/training/files/[id]/route.ts` | Authenticated attachment streaming | | `api/events/route.ts` | List visible events; create (manager) | | `api/events/[id]/photographers/route.ts` | Assign/remove photographers and editors | | `api/events/[id]/folders/route.ts` | Create a folder on an event | | `api/events/[id]/folders/[folderId]/photos/route.ts` | Streamed single-photo upload + checksum dedupe | | `api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts` | Authenticated stream/download, uploader-or-manager delete | | `api/events/[id]/route.ts` | Manager delete: event, folders/photos, event files on disk | | `api/announcements/route.ts` | Read feed; author create/edit/publish/delete | | `api/dev/cron/complete/route.ts` | **New:** post-service completion | | `api/dev/**` | Admin/cron JSON API (see §9) | ### `src/components` | File | Role | | --- | --- | | `ui/{button,card,input,label,badge}.tsx` | Local primitives | | `app/app-layout.tsx`, `nav.tsx` | Shell; Admin tab only for admins | | `app/state-message.tsx`, `toast.tsx` | Empty/error states; toasts | | `app/schedule-grid.tsx` | Table grid; every seat rendered; timezone label from `CHURCH_TIMEZONE` | | `app/schedule-grid-editor.tsx` | Serialized optimistic edits, per-slot rollback, soft-warning count | | `app/schedule-admin-bar.tsx` | Auto-fill, Publish / "Publish anyway", Unpublish | | `app/week-nav.tsx`, `calendar-nav.tsx` | Week anchors; week/month/year toggle | | `app/month-calendar.tsx`, `year-calendar.tsx` | Read-only overviews | | `app/respond-form.tsx` | Confirm/decline POST | | `app/settings-form.tsx` | From address + admin inbox | | `app/training-panel.tsx` | Lesson list + admin authoring/upload | | `app/admin/people-panel.tsx` | Full user manager + per-person skills + **mentor toggle** | | `app/admin/skills-matrix-panel.tsx` | Matrix + inline verify form | | `app/admin/positions-panel.tsx` | Positions + requirements editor | | `app/admin/services-panel.tsx` | Service templates + instance generator | | `app/admin/reminders-panel.tsx` | Rule CRUD / pause | | `app/admin/notifications-panel.tsx` | Outbox log + retry + send-test | | `app/admin/email-panel.tsx` | Gmail app-password connection | ### `src/domain` — pure rules (no DB imports; all unit-tested) | Module | Rule it owns | Reused by | | --- | --- | --- | | `assessments.ts` | Skill ladder; server-owned `levelFrom`; no-op change refused | readiness, mentor, conflicts, db/assessments | | `readiness.ts` | Weighted level + 0.3 comfort blend; core-below-required blocks | ranking, auto-fill, assign facts | | `mentor.ts` | Level ≥ min AND opt-in AND admin-approved | conflicts, shadows, auto-fill, assign facts | | `shadows.ts` | Trainee slot needs a mentor-ready paired mentor | C6 | | `growthGoals.ts` | Goal lifecycle state machine | (no API/UI yet) | | `userSkills.ts` | Self-comfort validation | API | | `skills.ts` | Skill-name composition | composer API | | `positions.ts` | Publishable = ≥1 core skill; weight range | requirements API | | `conflicts.ts` | 10 hard/soft conflicts | auto-fill + **manual assign** | | `ranking.ts` | Availability → roster → one-per-instance → core gate → readiness | auto-fill | | `autoFill.ts` | Greedy constraint-difficulty walk with monthly cap | db/autoFill | | `assign.ts` | D8 duplicate gate (kept for its focused tests; full engine now used) | — | | `availability.ts` | Inclusive ranges + rrule; `isUnavailable` | ranking, conflicts, assign | | `recurrence.ts` | RFC-5545 subset | instances, seed | | `instances.ts` | Deterministic occurrence planning | db/instances | | `slots.ts` | Headcount → seats; call time | db/slots | | `publish.ts` | Coverage/gap validation; unpublish blocks on confirmations | db/publish | | `notifications.ts` | Outbox status machine + dedupe keys | dispatcher | | `dispatch.ts` | Guard order, quiet hours (SMS), retry policy | dispatcher | | `reminders.ts` | Offset rules → send instants | db/reminders | | `templates.ts` | Assignment + reminder email templates | outbox, reminders | | `calendar.ts` | Month/year helpers | schedule | | `users.ts` | Email normalization, display name, last-admin guard, removal plan | users API | | `consent.ts` | Consent bound to phone; reset on change | profile API | ### `src/db` — data access | File | Responsibility | | --- | --- | | `index.ts` | postgres.js client (`max: 10`) + Drizzle | | `schema.ts` | **All 30 tables** + enums + relations | | `seed.ts` | Idempotent seed + `resetAndSeed()` + CLI guard | | `prune.ts`, `cleanup.ts` | Orphan sweep CLI + implementation | | `admin.ts`, `users.ts` | Roster read model; full admin CRUD + removal rules | | `userSkills.ts` | Self-comfort upsert, add/remove, **mentor approval** | | `assessments.ts` | Transactional verify + matrix/history | | `profile.ts` | Partial profile update, SMS consent, prefs | | `catalog.ts`, `positions.ts`, `services.ts` | Taxonomy, positions/skills, service templates | | `instances.ts`, `slots.ts` | Idempotent generation/materialization | | `assignments.ts` | Active-in-instance query + **full conflict fact resolver** | | **`complete.ts`** | **Post-service completion job** | | `grid.ts` | One-query week grid (all seats, active assignments only) | | `calendar.ts`, `volunteers.ts` | Range overview; picker options | | `unavailability.ts` | Blackout CRUD/cancel | | `autoFill.ts` | Resolve facts + apply proposals (slot status synced) | | `publish.ts` | Publish/unpublish transactions + audit + enqueue + cancel | | `audit.ts` | Pure `auditRow()` + `writeAudit()` | | `outbox.ts` | Enqueue publish mail, cancel assignment/instance mail, log, retry | | `dispatcher.ts` | Claiming dispatcher + stale-sending recovery | | `reminders.ts` | Rule CRUD + enqueue at publish | | `respond.ts` | Respond read model + single-use apply + slot status | | `settings.ts` | Email identity + encrypted Gmail password | | `training.ts` | Lesson/resource CRUD | | **`events.ts`** | **Event access, photographer assignments, folders, photo metadata, checksum lookup, event delete** | | **`announcements.ts`** | **Announcement list/create/update/delete** | ### `src/auth`, `src/lib` | File | Role | | --- | --- | | `auth/config.ts` | Credentials provider; JWT carries `id`/`email`/`systemRole`; `trustHost` | | `auth/permissions.ts` | Permission union, role matrix, `requirePermission`, `AuthError` | | `auth/roles.ts` | `SYSTEM_ROLES` + helpers | | `auth/api.ts` | `gateOrUser`, `gateSession`, `gateSelfOr`, `gateCron`, `clientIp` | | `auth/magic-link.ts` | Single-use tokens, user resolve/create, dev/mail transport, origin resolution | | `auth/invites.ts` | Status machine + invite/approve/deny wrappers + audit | | `lib/tz.ts` | DST-safe local↔UTC, formatting, week starts | | `lib/uuid.ts` | RFC 9562 UUIDv7 | | `lib/respond.ts` | HS256 respond tokens | | `lib/email.ts` | Gmail → Postmark → console resolver | | `lib/secret.ts` | AES-256-GCM at-rest encryption | | `lib/uploads.ts` | Allowlist, stored names, **magic-byte verification** | | `lib/rate-limit.ts` | In-memory fixed-window limiter | | `lib/slug.ts`, `lib/utils.ts` | Slugify, `cn()` | | **`lib/event-access.ts`** | **Pure manager/assignee/delete rules** | | **`lib/event-photos.ts`** | **RAW+image allow-list, generated storage paths, traversal guard, safe dispositions** | | **`lib/http.ts`** | **JSON/error response helpers** | ### `e2e` `admin`, `announcements`, `assign-mutations`, `auto-fill`, `calendar`, `events`, `notifications`, `publish`, `schedule-grid`, `services`, `settings`, `shell`, `training` specs + `dev.ts` (`signInAs`, `resetDb`, `firstInstanceId`, `BASE`). Browser tests should run with `TEST_DATABASE_URL` pointed at `media_e2e`, not the development database. --- ## 6. Data model Postgres, UUIDv7 text PKs in app code, `timestamptz` instants, local `date` columns. Soft-delete (`active`) for taxonomy/roles; terminal assignment history retained. ### Tables (30) | Table | Purpose | Key constraints | | --- | --- | --- | | `users` | Accounts/roles/profile | unique email + **unique `lower(email)`**, status enum, `deactivated_at` | | `notification_preferences` | Channel prefs + TCPA evidence | PK `user_id`, cascade | | `roles` | Schedulable positions | unique slug, `active`, call offset, headcount | | `services` | Recurring templates | unique name, rrule, local start, duration | | `service_instances` | Occurrences | unique `(service_id, starts_at)`, status enum | | `slots` | Seats (instance or event) | unique `(instance, role, index)`; parent XOR CHECK; shadow-pair CHECK | | `assignments` | Who holds a seat | partial unique active per slot; `user_id` RESTRICT | | `audit_log` | Append-only admin trail | actor NOT NULL | | `unavailability` | Blackouts/vacations | unique active range; span CHECKs | | `skill_categories`, `vendors`, `technologies`, `functions` | Taxonomy | frozen slugs, deactivate-only, RESTRICT | | `skills` | Rated unit | unique slug + `dedupe_key` | | `position_skills` | Requirements | PK `(position, skill)`, weight, required level, core | | `user_skills` | Competency | unique `(user, skill)`; comfort nullable; verified level; **mentor approval** | | `skill_assessments` | Append-only level history | no update/delete path; `comfort_at_time` | | `growth_goals` | Growth plans | unique `(user, skill)`; status enum | | `notifications` | Outbox | unique `dedupe_key`; status enum; `(status, scheduled_for)` | | `used_tokens` | Single-use respond jti | PK jti; cascade | | **`used_magic_tokens`** | **Single-use sign-in jti** | PK jti (safe to prune after 10 min) | | `notification_rules` | Offset reminders | unique key; **channel CHECK** | | `app_settings` | Runtime key/value | PK key | | `training_lessons`, `training_resources` | Training + attachments | cascade | | **`events`** | **One-off coverage events + shot brief** | starts_at index; creator SET NULL | | **`event_photographers`** | **Who can see/contribute** | PK `(event, user)`; event/user cascade; role enum | | **`event_folders`** | **Shared folders per event** | unique `(event, name)`; kind enum | | **`event_photos`** | **Photo metadata (bytes on disk)** | unique `(folder, checksum)`; uploader RESTRICT | | **`announcements`** | **Team feed posts** | published flag; author SET NULL | **Notably absent:** `skill_equivalencies`, a separate mentor-approval table, notification templates (code). `slots.event_id` still exists as an unconstrained text column and is **not** linked to the new `events` table; full event seats/reminders remain phase J work. ### Enums `SYSTEM_ROLES`, `USER_STATUSES`, `ASSIGNMENT_STATUSES`, `SLOT_STATUSES`, `INSTANCE_STATUSES`, `SKILL_LEVELS`, `ASSESSMENT_KINDS`, `GOAL_STATUSES`, `NOTIFICATION_STATUSES`, `UNAVAILABILITY_KINDS`, `NOTIFICATION_RULE_EVENTS`, `NOTIFICATION_CHANNELS`, `SMS_CONSENT_SOURCES`, `CONFIRMED_VIAS`, `ASSIGNMENT_SOURCES`. Domain ladders are drift-guarded against DB enums by tests. ### Migrations (0000–0015) Core tables → unique indexes → notification prefs → taxonomy → skills/position_skills → user_skills → assessments → growth_goals + shadow CHECK → unavailability → audit_log → notifications/used_tokens → notification_rules → app_settings/training → `0013` used_magic_tokens, mentor approval columns, unique lower(email), channel CHECK → `0014` events, event_photographers, event_folders, event_photos → **`0015` announcements**. --- ## 7. Scheduling lifecycle ``` services (rrule + local start) │ GET /api/dev/cron/instances [session schedule.publish | CRON_SECRET] ▼ service_instances (idempotent; DST-safe UTC) │ GET /api/dev/cron/slots [session | CRON_SECRET] (skips published) ▼ slots (headcount seats; call_time = start + offset; status kept in sync) │ ├── manual: POST /api/assignments {assign|clear} [schedule.publish] │ full conflict engine → hard conflicts 409; soft returned as warnings ├── auto: POST /api/dev/schedule/:id/auto-fill [schedule.publish] │ rank → greedy fill under monthly cap → proposed/auto ▼ assignments (proposed) │ ├── publish: POST /api/dev/schedule/:id/publish {allowGaps} │ one transaction: validate coverage → published → │ audit week.published → enqueue assignment mail + reminders ├── late seat: assigning into a published week also enqueues that seat's │ mail/reminders (dedupe keys make it idempotent) ▼ notifications (queued) │ GET /api/dev/cron/notifications [session | CRON_SECRET] │ recover stale sending → guards → atomic claim → send │ Gmail → Postmark → console; retry 5/30/120 min, 3 attempts ▼ email with signed single-use confirm/decline links (14 days) │ ├── GET /respond?t=… read-only └── POST /api/respond (rate-limited) transaction: consume jti → verify volunteer → confirmed/declined → sync slot status → audit decline cancels that assignment's queued mail │ ▼ GET /api/dev/cron/complete [session | CRON_SECRET] past published assignments → completed; last_served_on / last_served_at updated ``` **Invariants and where they live** - One active assignment per slot: DB partial unique index + `activeAssignmentInInstance`. - One active assignment per person per instance: full conflict engine (manual) and ranking (auto). - Shadow seat never covers and needs a mentor: CHECK + `validateShadowPairing` + `validatePublish`. - Publish is atomic with its audit and queue writes; re-publish is a no-op. - Unpublish is refused while anyone is confirmed; on success it cancels queued mail. - Clearing a seat cancels its mail **before** deleting the assignment; a missing assignment is treated as cancelled by the dispatcher. --- ## 8. Auth & authorization **Sign-in** 1. `POST /api/dev/magic-link {email}` → rate-limited in production → resolve/create user (active only when `AUTO_ACTIVATE_NEW_USERS=true`, else `pending_approval`) → sign 10-min token with `jti`. 2. Dev/console: the URL is returned and printed only when `MAGIC_LINK_DEV_TRANSPORT=true`. Production: the link is sent through the configured transport (console/file when no provider is set). 3. `GET /api/dev/complete?token=…` verifies the token, **consumes the `jti` once**, then establishes the session. Invalid/used links redirect to `/login`. 4. `authorize()` rejects non-active or deactivated users. **Permissions** | Permission | admin | coordinator | volunteer | trainee | | --- | --- | --- | --- | --- | | `admin.settings`, `design.theme`, `users.manage`, `training.author` | ✅ | — | — | — | | `content.author`, `schedule.publish` | ✅ | ✅ | — | — | | `schedule.view`, `roster.view`, `volunteer.serve`, `volunteer.blackout` | ✅ | ✅ | ✅ | partial (no roster) | **Gates** - `gateOrUser(permission)` → user or 401/403; rejects a session without a stable `id`. - `gateSession()` → any signed-in user. - `gateSelfOr(permission, targetUserId)` → self or elevated permission (profile, blackouts). - `gateCron(req, permission)` → `CRON_SECRET` bearer/query, else a session with the permission. - `clientIp(req)` → first forwarded hop (used by rate limiting and TCPA evidence). **UI enforcement:** the app-group layout gates everything; `/admin` redirects non-admins; the nav hides the Admin tab. **Remaining auth risks:** no CSRF token on JSON writes (SameSite cookie only); the rate limiter is per-process; email enumeration on the magic-link endpoint is mitigated by a neutral response but the JSON still reports status; `PUBLIC_ORIGIN` must be set for emailed links if the app is reachable off-LAN. --- ## 9. HTTP route inventory | Route | Methods | Guard | Purpose | | --- | --- | --- | --- | | `/api/health` | GET | none (intended) | liveness | | `/api/auth/[...nextauth]` | * | none (intended) | Auth.js | | `/api/admin` | GET | `admin.settings` | chokepoint demo | | `/api/assignments` | POST | `schedule.publish` | assign/clear (full conflicts) | | `/api/respond` | POST | token + rate limit | confirm/decline | | `/api/training/files/:id` | GET | signed-in | attachment bytes | | `/api/events` | GET | signed-in | events visible to the caller | | `/api/events` | POST | `schedule.publish` | create an event | | `/api/events/:id/photographers` | POST/DELETE | `schedule.publish` | assign/remove photographer or editor | | `/api/events/:id/folders` | POST | assigned or `schedule.publish` | create a folder | | `/api/events/:id/folders/:folderId/photos` | POST | assigned or `schedule.publish` | streamed RAW/image upload | | `/api/events/:id/folders/:folderId/photos/:photoId` | GET/DELETE | assigned read; uploader or manager delete | download/delete | | `/api/events/:id` | DELETE | `schedule.publish` | delete event + folders/photos + files | | `/api/announcements` | GET | signed-in | published feed; drafts for authors | | `/api/announcements` | POST/PATCH/DELETE | `content.author` | create / publish toggle / delete | | `/api/dev/magic-link` | POST | none (rate-limited) | request link | | `/api/dev/complete` | GET | token + single use | establish session | | `/api/dev/approve` | POST | `users.manage` | approve (actor server-owned) | | `/api/dev/deny` | POST | `users.manage` | deny | | `/api/dev/invite` | POST | `users.manage` | invite | | `/api/dev/reset` | POST | `ALLOW_DEV_RESET=true` + `admin.settings` | truncate + reseed | | `/api/dev/cron/instances` | GET | cron secret or `schedule.publish` | generate instances | | `/api/dev/cron/slots` | GET | cron secret or `schedule.publish` | materialize seats | | `/api/dev/cron/notifications` | GET | cron secret or `schedule.publish` | dispatch tick | | `/api/dev/cron/complete` | GET | cron secret or `schedule.publish` | close past services | | `/api/dev/schedule/instances` | GET | cron secret or `schedule.publish` | instance helper | | `/api/dev/schedule/:id/auto-fill` | GET/POST | `schedule.publish` | preview/apply | | `/api/dev/schedule/:id/publish` | POST/DELETE | `schedule.publish` | publish/unpublish | | `/api/dev/services` | GET/POST/PATCH | `schedule.publish` | templates | | `/api/dev/notification-rules` | GET/POST/PATCH | `schedule.publish` | reminder rules | | `/api/dev/notifications` | GET/POST | `schedule.publish` | log, retry, send-test | | `/api/dev/settings` | GET/PUT | `admin.settings` | email identity/Gmail | | `/api/dev/users` | GET/POST/PATCH/DELETE | `users.manage` | user CRUD | | `/api/dev/user-skills` | GET | `schedule.view` | competency rows | | `/api/dev/user-skills` | POST | `schedule.view` | own comfort | | `/api/dev/user-skills` | PATCH/DELETE | `users.manage` | level / mentor / remove | | `/api/dev/skills/matrix` | GET | `training.author` | matrix | | `/api/dev/skills/verify` | POST | `training.author` | level change | | `/api/dev/skills` | GET/POST/PATCH | `training.author` | skill CRUD | | `/api/dev/skills/compose` | POST | `training.author` | name preview | | `/api/dev/skills/assessments` | GET | `training.author` | assessment history | | `/api/dev/positions` | GET/POST/PATCH | `training.author` | position CRUD | | `/api/dev/positions/requirements` | GET/POST | `training.author` | requirements | | `/api/dev/catalog` | GET/POST/PATCH | `training.author` | taxonomy CRUD | | `/api/dev/profile` | PATCH/POST | self or `users.manage` | profile / SMS consent | | `/api/dev/unavailability` | GET/POST/PATCH | self or (`schedule.publish` for reads/writes) | blackouts | | `/api/dev/training/lessons` | GET/POST/PATCH/DELETE | signed-in read; `training.author` write | lessons | | `/api/dev/training/resources` | POST/DELETE | `training.author` | uploads | > The `/api/dev/*` prefix is historical. These are the production-facing admin APIs; a future pass should rename them (`/api/admin/*`) and keep `/api/dev/complete` as an auth callback. Not a security boundary — the guards are. --- ## 10. UI map | Page | Role | Interactions | | --- | --- | --- | | `/login` | public | request link; shows link only on the dev transport | | `/schedule?view=week` | all | read-only for volunteers/trainees; coordinators/admins get inline assign/clear + admin bar | | `/schedule?view=month` / `year` | all | read-only overviews → week | | `/roster` | all | active team table | | `/training` | all | volunteers read; admins author/publish/upload/delete | | `/events` | all | managers create/see all; photographers see assigned events | | `/events/[id]` | assigned + managers | brief, photographer assignment (managers), folders | | `/events/[id]/folders/[folderId]` | assigned + managers | multi-file upload, previews, downloads, delete own/manager | | `/announcements` | all | volunteers read published posts; admin/coordinator author, publish, delete | | `/settings` | all | facts; admin email form | | `/admin` | admin | People (add/edit/approve/skills/mentor/deactivate/delete), Skill levels (matrix + verify), Positions (requirements), Services (templates + generate), Reminder rules, Email, Notifications | | `/respond` | token | confirm / decline | **Session validation:** every `gateOrUser` request re-reads the account row. A JWT whose user was deleted, deactivated or re-seeded (for example after a test reset) now gets a `401 STALE_SESSION` instead of writing rows with a phantom `user_id`; the photo uploader redirects to `/login`. **Event photography access model:** managers (`schedule.publish`) see every event and assign people; only assigned photographers/editors (plus managers) can open an event, create folders, upload, and download each other's files. Unassigned users get a 404. Files are stored under `UPLOAD_DIR/events//`, never in Postgres; the filename/type is validated by extension (RAW or image), the SHA-256 dedupes re-uploads per folder, and non-previewable files are forced to download. Managers can delete an event; the DB cascade removes folders/photos and the route recursively removes that event's directory, with an audit row. **Announcements access model:** every signed-in user reads published posts. `content.author` (admin/coordinator) also sees drafts and can create, publish/unpublish or delete. Bodies are plain text and rendered as text, never HTML. Still missing screens (APIs exist): volunteer profile + prefs, blackout calendar, self-comfort sliders, growth goals/mentor queue, catalog taxonomy admin, skill composer, ranked/conflict-aware assign picker. --- ## 11. Notifications - **Status machine:** `queued → sending → sent`; failures return to `queued` with 5/30/120-minute backoff and end at `failed` after 3 attempts; `cancelled` on decline/unpublish/clear; `suppressed` on missing consent or SMS. - **Dedupe:** unique `template:reference:channel` (`assignment.published:{id}:email`, `reminder.{key}:{id}:email`). - **Dispatch guards:** terminal → assignment live (missing assignment = cancel) → user active → channel consent → due → quiet hours (SMS only) → send. - **Concurrency:** rows are claimed with an atomic `UPDATE … WHERE status IN (queued,failed)`; a concurrent tick sees 0 rows. `sending` rows older than 10 minutes are recovered to `queued`. - **Retry:** admin retry only accepts `failed`/`suppressed`. - **Transports:** Gmail SMTP (stored app password, encrypted) → Postmark (`POSTMARK_SERVER_TOKEN`) → console JSON under `OUTBOX_DIR`. - **Rules:** seeded `t_7` (−7 d, 09:00, email), `friday` (−2 d, 18:00, email+sms), `day_of` (0 d, 06:30, sms). Applied at publish; email rows only until SMS lands. - **Reconciliation:** late assigns enqueue their mail; clears cancel before delete; unpublish cancels the instance's queued rows. **Remaining:** no retention/pruning for `notifications` or used tokens; `reminder_count` is not incremented on send; no delivery webhooks/bounce handling. --- ## 12. Competency - `self_comfort` (volunteer signal) and `verified_level` (gate) are independent; the slider path never writes verified columns. - Every level move appends `skill_assessments` with server-owned `level_from`, `comfort_at_time`, assessor; demotions audited. - Readiness = `0.7 × weighted level + 0.3 × null-safe mean core comfort`, with any core skill below required ⇒ blocked. - Mentor readiness = verified level ≥ `mentor_min_level` AND opt-in AND **persisted admin approval** (`mentor_approved_at/by`), editable in the People panel. - Conflict engine (10 rules) is now used by both auto-fill and manual assignment; soft conflicts are returned as warnings. - Growth goals have a pure state machine + table but no API/UI yet. --- ## 13. Training, uploads, settings - Lessons: plain-text body, published flag, ordering. Volunteers see published; admins author/publish/delete. Two starter lessons seeded only when the table is empty. - Attachments: images/PDF/plain text/Markdown/Word, ≤5 MB, random stored name, metadata in Postgres, bytes under `UPLOAD_DIR`. - Uploads verify **magic bytes** against the declared MIME. - Serving requires a session; only images render inline, everything else is an attachment, with `nosniff`. - Any signed-in team member can fetch any attachment id (team-wide content by design). - Delete removes bytes best-effort; there is no orphan-file sweep. - Runtime settings: `app_settings` holds sender/inbox and the Gmail address + AES-256-GCM app password. Blank password keeps the stored one; an empty address disconnects Gmail. Saves are audited without the secret. - The encryption key derives from `NEXTAUTH_SECRET`: rotating it silently disables Gmail sending (it falls back to Postmark/console). --- ## 14. Testing & verification - Unit: **38 files / 293 tests**, focused on pure domain rules + auth/permissions/tokens/uploads/rate limit + event access/format/delete-path rules. - E2E: **32 tests** on the isolated `media_e2e` database, including event create → assign → upload RAW/JPEG → cross-photographer download → manager delete, plus announcement create → volunteer visibility → unpublish. - E2E: 11 specs, serial (`workers: 1`) because suites share one Postgres and reset it in `beforeAll`. - `playwright.config.ts` builds+starts the app on :3000, DB URL overridable via `TEST_DATABASE_URL`/`DATABASE_URL`, and sets `AUTO_ACTIVATE_NEW_USERS=true`, `MAGIC_LINK_DEV_TRANSPORT=true`, `ALLOW_DEV_RESET=true`. - CI targets `master`, provides a Postgres service, checks migration drift (`db:generate` + `git diff --exit-code -- drizzle`), typechecks, lints, tests, migrates, runs E2E and builds. - Local E2E still resets the development database; CI is isolated. Do not run it against a database you care about. --- ## 15. Running locally This shell has **no `pnpm` on PATH**; use local binaries. ```bash # 1. Postgres (host port 5433) docker compose up -d db export DATABASE_URL="postgres://media:media@localhost:5433/media" export NEXTAUTH_SECRET="local-dev-secret" export AUTO_ACTIVATE_NEW_USERS=true # dev only export MAGIC_LINK_DEV_TRANSPORT=true # dev console link export ALLOW_DEV_RESET=true # only if running E2E # 2. Migrate + seed ./node_modules/.bin/drizzle-kit migrate ./node_modules/.bin/tsx src/db/seed.ts # 3. Build + run ./node_modules/.bin/next build PORT=3000 ./node_modules/.bin/next start # 4. Checks ./node_modules/.bin/tsc --noEmit ./node_modules/.bin/vitest run ./node_modules/.bin/eslint src e2e ./node_modules/.bin/playwright test ``` **Traps** - **Never `pkill -f next-server`** — it can match the agent's own UI host (`pi-web`). Kill by PID; the app's process shows as `next-server (v15.5.29)`. - Background processes started inside a SYNC command may be cleaned up; use the BACKGROUND process type for a server you need to keep. - Turbopack dev and a production `.next/` conflict; `rm -rf .next` before `next dev`. - `pnpm start` needs `NEXTAUTH_SECRET`. - `occurs_on` is a local calendar date stored as UTC midnight — read its **UTC** date. - Drizzle 0.45.4 cannot type `one()` relations where an FK column is part of a PK/unique key; those tables are queried directly. - Partial unique indexes cannot be `ON CONFLICT` arbiters. - `ON CONFLICT DO NOTHING` returns no rows on re-run; re-fetch canonical ids in the seed. - Raw `sql` comparisons need an explicit cast for `Date` parameters (`${iso}::timestamptz`). ### Scheduling the cron routes There is no in-app scheduler. Call these on a timer with `CRON_SECRET` (an admin session also works): | Route | Suggested cadence | | --- | --- | | `/api/dev/cron/instances` | daily | | `/api/dev/cron/slots` | daily, after instances | | `/api/dev/cron/notifications` | every 5 minutes | | `/api/dev/cron/complete` | daily after the last service | Local compose does not set `CRON_SECRET`, so an external scheduler must be given one or the calls will be rejected. --- ## 16. Remaining risks and gaps ### P0 — operational | # | Issue | Why it matters | | --- | --- | --- | | 1 | **Everything since D8 is uncommitted**, including migrations `0010`–`0015`, the repair pass, event photography and announcements | One accident loses most of the product; no review or rollback point exists. **Commit before any further feature work.** | ### P1 — correctness / hardening | # | Issue | Fix direction | | --- | --- | --- | | 2 | `PUBLIC_ORIGIN` is empty by default in compose; without it, emailed links derive from `Host`/`X-Forwarded-Host` | Set a canonical origin in every non-LAN deployment; consider refusing to generate mail links without it in production | | 3 | No retention: `notifications`, `used_tokens`, `used_magic_tokens`, orphaned upload files grow forever | Add a prune job (counts first) and expose it in admin | | 4 | `reminder_count` is never incremented; `reliability_score` unused; no no-show workflow | Extend the completion job / add an admin mark-served action and metrics reporting | | 5 | Rate limiting is in-memory and per-process; magic-link JSON still echoes account status | Move counters to Postgres/Redis if scaled; keep the response neutral | | 6 | Rotating `NEXTAUTH_SECRET` silently disables the stored Gmail password | Version the encryption key separately, or surface a clear "reconnect Gmail" warning | | 7 | No CSRF token on JSON writes; cookie SameSite is the only defence | Add an origin check on state-changing routes (or a CSRF token) | | 8 | Training attachments are readable by any signed-in user; client MIME is only signature-checked, not deeply validated | Acceptable for team-wide content; add per-lesson ACLs only if content becomes sensitive | | 9 | No scheduled cron runner in the repo/compose; `CRON_SECRET` is unset locally | Document/automate the timer (systemd, host cron, or a scheduler container) | | 10 | `slots.event_id` is still an unconstrained text column and is not linked to the new `events` table; the event MVP uses a separate assignment table | Add the FK and event seats when phase J's scheduling pipeline is built, or drop the column | | 11 | Legacy `slots.status` rows created before the repair may still read `open` for filled seats | Harmless (all reads use assignment `EXISTS`); backfill in a one-off script if the admin UI starts showing it | | 12 | E2E locally resets the development DB | Always run it against a disposable database; CI uses its own service | ### P2 — product / polish - No rich text, exports (PDF/XLSX/CSV/ICS), swaps, SMS, volunteer self-service screens, ranked picker, catalog/skill-composer admin, growth-goal UI. Announcements are deliberately plain text until F1 lands. - Event photos have no thumbnails/transcoding, ZIP folder download, per-file progress beyond the current file, or storage quota/cleanup; browser previews use the original JPEG. - No observability (Sentry/structured request logs) and no delivery webhooks/bounce handling. - `README.md`/docs are current now, but the `/api/dev/*` naming remains historical. - No pagination on the notification log beyond a limit; no filters in the UI beyond what the API supports. --- ## 17. Recommendations ### Do next (small, high value) 1. **Commit the work** in logical commits: security/auth; assignment/grid; notifications/completion; event photography (schema + APIs + UI + E2E); announcements; migrations `0013`–`0015`; uploads/CI/env; tests; docs. Exclude `.env`, `.next`, `test-results`, `tsconfig.tsbuildinfo`. 2. **Set `PUBLIC_ORIGIN`** for the deployed URL and wire an external scheduler with `CRON_SECRET` for the four cron routes. 3. **Add retention** for notifications and token tables; prune expired magic/respond tokens and orphan upload bytes. 4. **Surface warnings in the grid UI.** The assign API now returns soft conflicts; show them in the toast/conflict panel instead of only a count. 5. **Add a ranked assign picker.** `rankCandidates` already returns eligible/excluded volunteers with reasons, scores, missing skills, mentor/refresher badges; it makes availability and core-skill rules visible before a 409. 6. **Finish event delivery:** ZIP a folder for offline editing, generate thumbnails for JPEGs so a 400-photo gallery is light, and add retention/storage-usage reporting. Full event seats/reminders should later reuse the assignment pipeline and link `slots.event_id`. ### Improvements - Volunteer self-service: profile/prefs, blackout calendar, self-comfort sliders, "my serving" with confirm/decline. - Catalog taxonomy admin + skill composer screens (APIs exist). - Growth goals + mentor queue UI (state machine and table exist). - Increment `reminder_count`, compute reliability from completion/no-show, and report fairness ("who hasn't served in N weeks"). - Delivery observability: provider webhooks, bounce/complaint handling, a failed-send alert to the admin inbox. - CSRF/origin checks on writes; move rate limiting to a shared store; add CSP after auditing Next's inline scripts. - Retention and audit views for `audit_log`. ### Features (in build-plan order) 1. **F1 rich text** (TipTap + server-side sanitize) for training and announcements. 2. **G exports and swaps** — ICS feed, CSV/XLSX roster export, printable PDF booth sheet, volunteer swap requests with coordinator approval (`swap` source already exists). 3. **J one-off events (next slice)** — link `slots.event_id` to the existing `events` table, add event seats, reminders/confirmations and publish, reusing the assignment pipeline. 4. **E5 SMS** — Twilio transport + 10DLC, opt-in UI (consent/quiet-hour fields already modelled). 5. **Fairness/reliability reporting** on top of the completion job. 6. **Automation** — auto-fill on generation, "still unfilled in 72h" alerts (`slot.unfilled` rule event already exists but is unused). 7. **Multi-campus/venue** — relax the unique service name and scope services/roles by venue. 8. **CSV volunteer import** and a first-run admin checklist. --- ## 18. Conventions & guardrails 1. **Pure rule first.** Put business behaviour in `src/domain/*.ts` (no `src/db` imports), test it with rule-named tests, then call it from `src/db/*`. 2. **One write transaction per state change** (publish + audit + outbox; claim + status + audit; clear + cancel + audit). 3. **Idempotency by unique key**, not branching; return only inserted rows so counts are meaningful. 4. **Partial updates:** `undefined` = leave alone, `null` = clear. 5. **Dates:** `timestamptz` for instants, `date` for local calendar days; read date columns with UTC getters; build instants with `localToUtc`. 6. **Deactivate taxonomy/roles**, keep assignment history, never update/delete audit or assessment rows. 7. **Migrations:** edit schema → `drizzle-kit generate` → review SQL → `drizzle-kit migrate`; commit SQL + snapshot + journal together; never edit an applied migration. 8. **Every route declares its guard** (`gateOrUser` / `gateSelfOr` / `gateCron` / token). Public routes are health, auth, respond/magic-link/complete (token-based). 9. **E2E** resets one shared DB serially; add a `beforeAll` reset via `e2e/dev.ts` and keep `workers: 1` unless you add per-worker databases. 10. **Kill servers by PID** (see §15); background long-running processes with the BACKGROUND type. 11. **Server Components read; client components mutate.** DB access never lives in `"use client"` files. 12. **Record decisions and fixes** in `.agent/PROGRESS.md`; add a new `.pi/DEAD_ENDS.md` entry after an approach fails twice. --- ## 19. Open product decisions 1. **Sign-up policy** — invite-only (now the default) vs self-serve with approval. If self-serve returns, add an email-verification step rather than auto-activating. 2. **Canonical public origin** — fixed `PUBLIC_ORIGIN` (recommended) vs request-derived links. 3. **Assignment authority** — do coordinators override hard conflicts with an audited note, or are hard blocks absolute? Soft conflicts already warn. 4. **Mentor approval** — admin-only (current) or coordinators too? Persisted per skill now. 5. **Events scope** — needed for the pilot, or service-only first? 6. **SMS timing** — when to start 10DLC registration. 7. **Retention windows** — notifications, audit history, uploads, used tokens. --- *This map describes the code in the working tree on 2026-11-19, after the repair pass. Where the planning docs and the code disagree, the code and `.agent/PROGRESS.md` are the record of what was actually decided.*