Files
glenloch-media/docs/superpowers/plans/2026-11-18-d8-assign-mutations-plan.md
T
Tiel Coder d0a696167f fix(D8): grid slots render, per-cell optimistic revert, shared E2E helpers, admin reset endpoint
- src/db/grid.ts: key role map by ID (was slug, causing all cells to show '—')
- src/components/app/schedule-grid-editor.tsx: revert only failed cell, not entire grid
- src/db/audit.ts: fix import path ./db → @/db
- src/db/seed.ts: add resetAndSeed(), assign Audio only (leave Livestream/Slides open)
- src/auth/config.ts: carry id/email on JWT for audit actor
- e2e/dev.ts: shared signInAs + resetDb helpers
- e2e/schedule-grid.spec.ts: use shared helpers, reset DB beforeAll
- e2e/assign-mutations.spec.ts: E2E for assign/clear with optimistic update + rollback
- src/app/api/dev/reset/route.ts: admin-only DB reset endpoint
- playwright.config.ts: workers: 1 (serial, suites share one Postgres)
2026-11-18 21:51:04 +00:00

12 KiB

D8 — Assign / unassign / clear with optimistic update + rollback toast

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Let coordinators assign, unassign, and clear who fills each slot on the D7 schedule grid, with an instant optimistic cell update and a rollback toast when the write is rejected.

Architecture: A thin client wrapper around the D7 read-only grid holds optimistic per-cell state, calls a POST /api/assignments REST route, and rolls back on non-2xx with a toast. The route guards to coordinators+, enforces the hard conflict rules via the existing D5 conflict engine, writes the assignment (or clears it), and records an audit row.

Tech Stack: Next.js App Router (server + client components), postgres.js + Drizzle, vitest (pure domain tests), Playwright (E2E), uuidv7 (client-safe ids).

Spec: docs/superpowers/specs/2026-11-18-d8-assign-mutations-design.md

Global Constraints

  • BUILD-SPEC §7 rule 1: "A volunteer cannot hold two active assignments in the same service instance."
  • BUILD-SPEC §7 rule 2: "One active assignment per slot (DB-enforced)."
  • BUILD-SPEC §7 rule 12: "Every admin mutation writes an audit row."
  • BUILD-SPEC §7 rule 4 (anti-goal): "Confirmed assignments block deletion — they must be unassigned or swapped"; never a silent delete.
  • BUILD-PLAN D8 done-when: "assign → appears immediately; forced failure rolls back with a message."
  • D8 sends nothing: notifications belong to E1/D10 — an assignment is status="proposed" awaiting the volunteer confirm flow.
  • Domain logic lives in src/domain/** and never touches the DB; routes/components call it.
  • Container: the API route ships in the Next build; the audit_log migration is created with pnpm db:generate, committed to drizzle/, and applied by pnpm db:migrate in the migrate container.

Review Focus

  1. Assigning a volunteer who already holds an active assignment in the same instance (rule 1) must reject with a clear message and roll back — not silently fail. (Pinned by assignHardConflicts test in Task 2 and the rollback E2E in Task 4.)
  2. Assigning to a slot that already has an active assignment (rule 2, DB unique) must return a clean error, not a 500 or a raw DB dump. (Pinned by the forced-failure E2E in Task 4.)
  3. An unauthenticated or volunteer request to assign must get 401/403, not 200. (Pinned by the auth E2E in Task 4.)
  4. A rolled-back assign must revert BOTH the optimistic cell AND leave no half-written row; the toast must show the rejection reason. (Pinned by the rollback E2E in Task 4.)
  5. Clearing an assignment returns the slot to "Open" and writes an audit row (rule 12). (Pinned by the clear E2E in Task 4.)

Task 1: audit_log table + migration + audit-row builder

Files:

  • Modify: src/db/schema.ts
  • Create: drizzle/000X_*.sql (generated)
  • Create: src/db/audit.ts
  • Test: src/db/audit.test.ts

Interfaces:

  • Consumes: nothing.

  • Produces: writeAudit(db, { actorId, action, entityType, entityId, before?, after? }) -> Promise<audit row>; pure auditRow({ actorId, action, entityType, entityId, before?, after?, now? }) -> { id, actorId, action, entityType, entityId, beforeJson, afterJson, createdAt }.

  • Step 1: Write the failing test — in src/db/audit.test.ts, assert auditRow() returns a row with a uuidv7 id, the passed action/entityType/entityId, createdAt = the injected now, and beforeJson/afterJson = JSON.stringify of the inputs (empty string when omitted).

  • Step 2: Run test to verify it fails — run pnpm vitest run src/db/audit.test.ts. Expected: FAIL (module / auditRow not defined).

  • Step 3: Implement — add the auditLog table to src/db/schema.ts (id, actorId, actorIpHash, action, entityType, entityId, beforeJson, afterJson, createdAt per ARCHITECTURE §638; append-only, no app update/delete); add src/db/audit.ts with pure auditRow() (id via uuidv7(), createdAt from an injectable now for testing) and writeAudit(db, input) that inserts it; import auditLog into the schema export.

  • Step 4: Run test to verify it passes — run pnpm vitest run src/db/audit.test.ts. Expected: PASS.

  • Step 5: Generate + commit — run pnpm db:generate (creates drizzle/000X_*.sql), git add the new SQL + schema.ts + audit.ts + test, commit.

Task 2: assign conflict gate (pure, reuse D5)

Files:

  • Create: src/domain/assign.ts
  • Test: src/domain/assign.test.ts

Interfaces:

  • Consumes: type Conflict from src/domain/conflicts (D5).

  • Produces: assignHardConflicts(facts: { alreadyAssignedInInstance: boolean }): Conflict[] — returns the hard conflicts that block an assign; empty when the assign is allowed.

  • Step 1: Write the failing test — in src/domain/assign.test.ts, assert assignHardConflicts({ alreadyAssignedInInstance: false }) returns [], and assignHardConflicts({ alreadyAssignedInInstance: true }) returns one hard conflict with code === "duplicate_in_instance" (the D5 code for §7 rule 1).

  • Step 2: Run test to verify it fails — run pnpm vitest run src/domain/assign.test.ts. Expected: FAIL (assignHardConflicts not defined).

  • Step 3: Implement — in src/domain/assign.ts, implement assignHardConflicts() returning a Conflict[] that hard-blocks on alreadyAssignedInInstance (rule 1) using the D5 duplicate_in_instance code and message; skill gating (rules 6/13) is intentionally out of scope for D8 and stays on the picker.

  • Step 4: Run test to verify it passes — run pnpm vitest run src/domain/assign.test.ts. Expected: PASS.

  • Step 5: Commit — git add src/domain/assign.ts src/domain/assign.test.ts && git commit -m "domain: assign conflict gate (rule 1 duplicate-in-instance)".

Task 3: assign/clear API route

Files:

  • Create: src/db/assignments.ts
  • Create: src/app/api/assignments/route.ts

Interfaces:

  • Consumes: writeAudit (Task 1), assignHardConflicts (Task 2), auth/requirePermission/AuthError (src/auth), uuidv7 (src/lib/uuid), schema assignments/slots/serviceInstances.

  • Produces: POST /api/assignments { action: "assign"|"clear", slotId, userId? } → { ok, id?, status? } on success, { error, code } on 400/401/403/409/500.

  • Step 1: Implement the data layer — in src/db/assignments.ts, implement activeAssignmentInInstance(db, { userId, instanceStart, instanceEnd }): query assignments joined to serviceInstances where userId, status IN (proposed,confirmed,completed), and starts_at within the instance's local-day range; return the row or null. (Validated by the Task 5 E2E — the project tests DB/route logic via Playwright, not vitest.)

  • Step 2: Implement the route — in src/app/api/assignments/route.ts, POST: guard with auth() + requirePermission(..., "schedule.publish") (coordinator+); zod-validate { action, slotId, userId? }; for assign, resolve the slot's instance start, call activeAssignmentInInstance then assignHardConflicts, reject with 409 + the conflict message when hard conflicts exist, else insert an assignments row (id=uuidv7(), status="proposed", source="manual", assignedBy=actor.id, assignedAt=now) and write an assignment.created audit row, return { ok, id, status }; for clear, delete the active assignment for slotId and write an assignment.cleared audit row, return { ok }. Mirror the admin/route.ts error shape (AuthError → 401/403).

  • Step 3: Typecheck — run pnpm tsc --noEmit. Expected: no errors.

  • Step 4: Commit — git add src/db/assignments.ts src/app/api/assignments/route.ts && git commit -m "api: assign/clear route with rule-1 gate + audit".

Task 4: optimistic grid editor + toast

Files:

  • Create: src/components/app/toast.tsx
  • Create: src/components/app/schedule-grid-editor.tsx
  • Modify: src/app/(app)/schedule/page.tsx

Interfaces:

  • Consumes: ScheduleGrid + GridWeek (src/components/app/schedule-grid.tsx, src/db/grid), writeAudit-free (client only calls the route).

  • Produces: <ScheduleGridEditor week={week} role={systemRole} /> — renders the read-only grid for non-coordinators, or the interactive grid (assign controls + optimistic update + toast) for coordinators/admins.

  • Step 1: Write the failing test — (E2E-verified in Task 5; no unit test for client optimistic state.) Skip to Step 2.

  • Step 2: Implement the toast — in src/components/app/toast.tsx, a "use client" minimal toast: a toast(message, kind) helper + a fixed-bottom container; kind is "error" (rollback) or "success".

  • Step 3: Implement the editor — in src/components/app/schedule-grid-editor.tsx, a "use client" component: renders ScheduleGrid; each open non-trainee cell gets an "Assign" control listing eligible volunteers; on selection, optimistically render the cell as filled (pending), POST /api/assignments { action:"assign", slotId, userId }, on success keep the optimistic cell, on non-2xx revert the cell and show an error toast with the message; an assigned cell gets a "Clear" control that optimistically reverts to "Open", POST { action:"clear", slotId }, and rolls back on failure.

  • Step 4: Wire the page — in src/app/(app)/schedule/page.tsx, call auth(), and render <ScheduleGridEditor> when the user is coordinator/admin, else the read-only <ScheduleGrid> (so the D7 volunteer view is unchanged).

  • Step 5: Typecheck + lint — run pnpm tsc --noEmit and pnpm eslint .. Expected: clean.

  • Step 6: Commit — git add src/components/app/toast.tsx src/components/app/schedule-grid-editor.tsx "src/app/(app)/schedule/page.tsx" && git commit -m "ui: optimistic grid editor with assign/clear + rollback toast".

Task 5: E2E (done-when)

Files:

  • Create: e2e/assign-mutations.spec.ts

Interfaces:

  • Consumes: the running app (E2E webServer sets NEXTAUTH_SECRET); a seeded week with at least one open slot and two active volunteers.

  • Step 1: Write the failing test — in e2e/assign-mutations.spec.ts: sign in as a coordinator; assert an open slot shows "Open"; click Assign → pick a volunteer; assert the cell shows that volunteer WITHOUT a full page reload (optimistic); assign the same volunteer to the same instance again → assert the cell reverts to "Open" and a toast shows the rule-1 message; clear the first assignment → assert the cell returns to "Open". Capture console + page errors and fail on any.

  • Step 2: Run test to verify it fails — run npx playwright test e2e/assign-mutations.spec.ts. Expected: FAIL (file / assertions not met).

  • Step 3: Ensure the app is up — start with DATABASE_URL + NEXTAUTH_SECRET set; seed a week with an open slot and two active volunteers if not already seeded.

  • Step 4: Run test to verify it passes — run npx playwright test e2e/assign-mutations.spec.ts. Expected: PASS, no console errors.

  • Step 5: Full gate — run pnpm tsc --noEmit, pnpm eslint ., pnpm vitest run, pnpm build, then npx playwright test e2e/schedule-grid.spec.ts e2e/shell.spec.ts e2e/assign-mutations.spec.ts. Expected: all green.

  • Step 6: Commit — git add e2e/assign-mutations.spec.ts && git commit -m "e2e: assign/clear optimistic + rollback (D8 done-when)".

Self-Review Notes

  • Spec coverage: rule 1 → Task 2 + Task 5; rule 2 → Task 3 (route) + Task 5; rule 12 → Task 1 + Task 3; optimistic + rollback → Task 4 + Task 5; no-notifications → assign defaults to proposed/manual.
  • The D7 read-only E2E (schedule-grid.spec.ts) still passes: the editor renders the grid as a subset plus assign controls.
  • Skill gating (rules 6/13) is deliberately deferred to the picker; the plan marks it as out of scope for D8's route.