R5 (Semi-Final Evaluation) is about to close. Next is R6 (Mentoring) for projects that request or are assigned a mentor, then R7 (Grand Final). The MENTORING backend exists but has gaps that block operational use:
- Admin Config form omits two `MentoringConfigSchema` fields (`mentoringRequestDeadlineDays`, `passThroughIfNoRequest`)
- Round Overview shows generic stats only — no mentor-specific dashboard
-`/admin/projects/[id]/mentor` exposes only AI suggestions; manual mentor selection is missing entirely from the UI
- Juror "Confirm Your Evaluation Preferences" banner pulls in LIVE_FINAL groups (not appropriate for a live ceremony)
- Multi-role users (juror + mentor) land on primary role's dashboard only; no quick path for an admin to bulk-promote jurors
- Zero tests for MENTORING round behavior
This spec covers all of the above plus workspace messaging/file UX polish, in one design with phased PRs.
## Goals
1. Admin can fully configure a MENTORING round from the UI (no DB-direct edits needed for any `MentoringConfigSchema` field).
2. Admin can see at a glance: who requested mentoring, who has a mentor, who doesn't, who's mentoring whom, what the mentor pool looks like.
3. Admin can manually assign a mentor to any project, AND auto-fill all unassigned projects in one action.
4. Files uploaded in the mentor workspace land at `<projectName>/mentorship/<file>` in the configured bucket, with paths constructed server-side.
5. Mentors and applicant teams see recent messages on their respective dashboards.
6. A juror who is also a mentor can switch dashboards in one click, without seeing irrelevant LIVE_FINAL preference cards.
7. The MENTORING round behavior (pass-through, eligibility, advancement) is covered by integration tests.
## Non-goals
- Redesigning messaging or notifications from scratch.
- Replacing the AI mentor-matching service with a different model.
- Building a mentor scheduling/calendar feature.
- Bulk-promoting jurors to mentors via CSV import (per-row checkbox + bulk action is enough for this iteration).
- Migrating any existing mentor file objects in MinIO (none exist yet — spec asserts a pre-flight check).
## Out-of-scope but adjacent
- Grand Finale (R7 LIVE_FINAL) UX — explicitly deferred per user direction (handled separately, much further build-out planned).
- Mentor pool capacity / load-balancing algorithm changes — covered only by surfacing existing fields in the admin view.
---
## High-level architecture
No new top-level architecture. Extending existing patterns:
- **Storage path:** new helper `generateMentorObjectKey(projectTitle, fileName)` in `src/lib/minio.ts` that returns `<sanitizedProjectName>/mentorship/<timestamp>-<sanitizedFileName>` — exact same shape as `generateObjectKey()` with `roundName="mentorship"`. Server-side only.
- **Config schema:** no Prisma migration. The two missing fields (`mentoringRequestDeadlineDays`, `passThroughIfNoRequest`) already exist in `MentoringConfigSchema` and are read by `round-engine.ts` and `applicant.ts` — only the form needs updating.
| (continuous) | §G | Low | Tests added in each PR for the surface changing in that PR |
A standalone test PR is *not* planned — tests ride with the change they cover.
---
## §A. MENTORING round Config form
**Files:**
-`src/components/admin/round-config/mentoring-config.tsx` (likely path; locate the round-type-specific config component used by `(admin)/admin/rounds/[roundId]` Config tab)
-`src/components/admin/round-config/launch-readiness.tsx` (or similar — the component that renders the 0/3 readiness checklist)
**Changes:**
1. Add **"Mentoring Request Window"** section to the Config form:
- Numeric input bound to `configJson.mentoringRequestDeadlineDays` — int, min 1, max 90, default 14.
- Help text: "Number of days from round opening during which teams may request mentoring. After this window, no new requests are accepted."
2. Add **"Pass-through behavior"** toggle bound to `configJson.passThroughIfNoRequest`:
- Default `true` (matches schema default).
- Off-state label: "Hold all projects in PENDING until mentor is assigned (manual gate)"
- On-state label: "Auto-PASS projects that don't request mentoring (default)"
- Required only when `configJson.filePromotionEnabled === true` AND `configJson.promotionTargetWindowId` is set (i.e., the round is configured to promote mentor-authored files into a downstream submission window).
- Otherwise treat the readiness item as N/A and don't count it against the 0/3 (it becomes 0/2 for mentoring rounds without promotion configured).
5. Help-text added to the existing **Eligibility** dropdown explaining each option:
-`requested_only` — only projects that flag `mentoringRequested` participate (default).
-`all_advancing` — every project advancing into this round gets a mentor.
-`admin_selected` — admin manually picks which projects participate.
**Tests** (in PR 3): one per `MentoringConfigSchema` field — render with default config, change input, submit, assert config persisted via the existing config-save mutation.
-`src/app/(admin)/admin/rounds/[roundId]/projects-tab.tsx` (Projects tab — exact filename to confirm during impl)
-`src/app/(admin)/admin/mentors/page.tsx` (currently a redirect stub — replace with a real list page)
-`src/app/(admin)/admin/mentors/[id]/page.tsx` (also a stub today; replace with mentor detail)
- New tRPC procedures on `mentor` router (admin-gated): `getRoundStats`, `getMentorPool`, `getMentorDetail`
**Round Overview — replace generic Round Details with a mentoring-specific stats card** when `round.roundType === 'MENTORING'`:
- **Top-line counts** (single row of stat cards):
- Total projects in round
- Requested mentoring (count + % of total)
- Mentor assigned (count + % of total)
- Awaiting assignment (= requested - assigned)
- **Request window** card:
- Deadline (computed from `windowOpenAt + mentoringRequestDeadlineDays`)
- Time remaining (live countdown, using existing `formatCountdown` helper)
- "Closes in N days" pill, turns amber within 48 hours, red within 12 hours
- **Mentor pool** card:
- Pool size (count of users with MENTOR role in the program)
- Average load (assigned projects ÷ pool size)
- Capacity remaining (sum of `User.maxAssignmentsOverride` minus current load, where overrides exist)
- Link → `/admin/mentors`
- **Workspace activity** card:
- Total messages exchanged (sum across all assignments in round)
- Total files uploaded
- Total milestones completed
- "Last activity" timestamp
**Round Details panel** stays at the bottom of the Overview tab when round is MENTORING (the existing panel is still useful for type/status/position/dates), but with these field-level adjustments:
- Replace "Jury Group: —" row with "Mentor Pool: N members" (link to `/admin/mentors`).
- The new "mentoring stats card" (top-line counts, request window, mentor pool, workspace activity) renders **above** the Round Details panel, not in place of it.
**Projects tab — when round is MENTORING**, the per-project row shows:
- Project title + team lead
- "Requested mentoring" badge (yes/no)
- "Mentor assigned" cell — mentor name + expertise overlap chip, OR "Unassigned" with inline "Assign" button → opens the manual-pick drawer (see §C)
-`src/server/routers/mentor.ts` (`getCandidates` new procedure for manual picker; ensure `autoAssignBulk` exposes a "skip already assigned" param — confirm and document)
**Page rewrite — three sections, all visible at once (not tabs):**
- If assigned: mentor name, email, country, expertise overlap chips, "Assigned by [admin], 3 days ago, method: MANUAL/AUTO", actions: Unassign | Swap
- If unassigned: empty state with copy "No mentor assigned yet — pick one below or use AI"
3.**Pick a mentor** card with a tab strip:
- **Tab 1 — Manual picker** (default selected):
- Searchable input
- Sortable table of all MENTOR-role users in the program: name, expertise tags, country, current load, capacity, **expertise overlap with this project** (computed: count of shared tags / total project tags, displayed as a percentage chip)
- **Fallback**: if AI fails (no `OPENAI_API_KEY`, network error, or returns empty) — show expertise-tag-overlap ranking as the suggestion source instead, with a banner: "AI matching unavailable — showing expertise-tag overlap instead". (The fallback ranking is the same algorithm as Tab 1's default sort, so the lists may look similar — that's fine.)
**Auto-fill remainder** (bulk action):
- On round Projects tab + Round Overview, button: "Auto-fill mentors for unassigned projects".
- Call `mentor.autoAssignBulk` with the round ID; the service filters to projects-in-round-without-MentorAssignment, scoped further by the round's `eligibility` config:
-`requested_only` → only projects with `mentoringRequested=true`
-`all_advancing` → every project in the round
-`admin_selected` → button disabled (admins must pick manually for this mode)
- Confirm the existing service already skips projects with a MentorAssignment (any method); if it doesn't, fix in the same PR.
- Result toast: "Assigned N projects, skipped M already-assigned, K unassignable (no matching mentor)".
Replace single-`role` switch in `src/app/page.tsx` with a priority list that is *filtered by actionable work*. The user lands on the highest-priority role for which they have something to do right now; if no role has active work, fall back to the static priority order.
New tRPC query: `user.getDefaultDashboard()` (server-side, called from `src/app/page.tsx`):
For each role the user holds (in priority order), the server checks "does this user have actionable work in this role right now?":
| Role | "Has actionable work" predicate |
|------|---------------------------------|
| SUPER_ADMIN / PROGRAM_ADMIN | Always true (admin work is always present) |
| AWARD_MASTER | Any unfinalized award decision in an active round in current edition |
| JURY_MEMBER | Any `JuryAssignment` linked to a round whose `status = ROUND_ACTIVE` AND the user has at least one PENDING evaluation |
| MENTOR | Any `MentorAssignment` whose linked round is `ROUND_ACTIVE` AND `workspaceEnabled = true` |
| APPLICANT | Any `Project` led by user with at least one `ProjectRoundState` in a non-terminal state in an active round |
| OBSERVER | Always false (observers have nothing to act on) |
| AUDIENCE | Always false |
Algorithm:
1. Try roles in priority order. Return the first role whose predicate is true.
2. If no role has actionable work, return the highest-priority role the user holds (static fallback).
3. Always end with a non-null route (worst case: any signed-in user has at least their primary role).
**Why this matters (your example):** a juror+observer who logs in during an open jury round lands on `/jury` (because they have a pending evaluation), not `/observer`. A mentor+juror logs in during an active MENTORING round → `/mentor`. After both rounds close, same user logs in → static fallback (jury > mentor) → `/jury`. The role switcher in the user menu is always available to override.
**Decision: context-aware, not "remember last view".** "Remember last view" requires a new column and surprises users when their last context disappears (round closed, role removed). Context-aware is deterministic, explains itself, and handles the cross-role overlap cleanly. The role switcher dropdown is the user's escape hatch.
**Tests** (in PR 6):
- Juror with pending evaluation in active round + Observer → `/jury`
- Juror with no active assignments + Observer → `/jury` (fallback to static priority)
- Mentor+Juror, MENTORING round active, no jury work → `/mentor`
- Mentor+Juror, both rounds active with work in both → `/jury` (priority order breaks the tie)
- Observer-only user → `/observer`
- Multi-role with no active work anywhere → static-priority fallback
**2. Bulk juror→mentor promotion** on `/admin/members`:
- Add row checkboxes to the Members table (already a table — confirm during impl).
- When ≥1 row selected, surface a bulk action toolbar with "Add role…" dropdown (OBSERVER / MENTOR / AWARD_MASTER) and "Remove role…".
- Call new `user.bulkUpdateRoles({ userIds, addRole?, removeRole? })` mutation. Server-side: only SUPER_ADMIN/PROGRAM_ADMIN, log a `DecisionAuditLog` entry per user changed.
- After success, refresh the table and toast "Added MENTOR role to N users; M already had it (no-op)".
**3. Mentor-onboarding email** (one-shot):
- New email template at `src/lib/email/templates/mentor-onboarding.tsx`: brief welcome, explanation of mentor responsibilities, link to `/mentor`, link to "Switch View" doc/walkthrough.
- Trigger: in `user.bulkUpdateRoles` and the existing single-user `updateRoles` mutation, when MENTOR is **newly** added (i.e., wasn't in `roles[]` before this update) → enqueue the email. Idempotent on subsequent edits that keep MENTOR in `roles`.
- Add a `User.mentorOnboardingSentAt: DateTime?` column for idempotency. Migration: nullable column, no backfill needed.
- Restructure: banner sits in a flex container above the header rather than being `position: fixed` over it. The header height stays unchanged; the banner pushes content down.
- Alternative (smaller change): keep `position: fixed` but `pointer-events: none` on the banner div and re-enable `pointer-events: auto` on the inner "Return to Admin" button only. Either fixes the menu intercept.
- Pick the simpler diff at impl time; document choice in PR.
**5. Banner shows all roles:**
- When `session.user.roles.length > 1`, render comma-separated list: "Impersonating Dr. Sophie Laurent (JURY MEMBER, MENTOR)".
**6. Standardize the role-switcher (location + presentation):**
Today's state:
- Header layouts (`role-nav.tsx`) — used by jury, mentor, applicant, observer, award-master — put the user menu **top-right** with role-switcher items inside the dropdown.
- Admin layout (`admin-sidebar.tsx`) puts the user menu **bottom-left of the sidebar** with its own duplicate `ROLE_SWITCH_OPTIONS` constant + `switchableRoles` filter (lines 161, 191, 377-401).
Two problems: (a) duplicated logic across two files; (b) different physical placement, so a multi-role user has to learn two patterns to find "Switch View".
Changes:
- **Extract a shared module** at `src/components/layouts/role-switcher.tsx` exporting:
-`useRoleSwitcher()` hook returning `{ switchableRoles: Array<{ label, path, icon }>, currentBasePath }`. Both `role-nav.tsx` and `admin-sidebar.tsx` import this. Source of truth for `ROLE_SWITCH_OPTIONS` lives here only.
-`RoleSwitcherMenuItems` component — renders the dropdown items (used inside both layouts' user menus). Keeps rendering inline-consistent.
-`RoleSwitcherPill` component — a standalone visible button that renders just outside the user-menu dropdown, with label "Switch View" + the icon of the next-best alternate role. Visible only when `switchableRoles.length > 0`. Click opens a small popover listing alternates.
- **Place the `RoleSwitcherPill` in a consistent location across all layouts**: top-right of the header, immediately to the LEFT of the notifications bell. For the admin layout (sidebar-based), add a top-right header strip that hosts the pill + notifications + theme toggle, mirroring the other dashboards. (The admin sidebar keeps everything else; just the top-bar is added.)
Why top-right: that's where the existing role-nav layouts already put switching/profile actions. Admins gain the pill in the same spot — no learning curve when switching from /admin to /jury.
- **Pill behavior:**
- Hidden if `switchableRoles.length === 0` (single-role users see nothing — clean default).
- Hidden when `isImpersonating` (impersonator UX is already different; the existing impersonation banner with "Return to Admin" handles role-switching for that path).
- On hover/focus: shows tooltip "Switch dashboard view".
- Keyboard: `Cmd+Shift+V` shortcut opens the popover (nice-to-have; ship if it doesn't add much code).
- **Admin sidebar bottom user pill stays** (so admin users can still sign out / open settings from there). The role-switcher items are removed from that menu — they live exclusively in the new pill + the user-dropdown's switch list. (Avoids three places to switch view.)
**Acceptance for §D.6:** any signed-in user with `roles.length > 1` sees a "Switch View" pill in the same screen position regardless of which dashboard they're currently in.
**Change:** Query the membership's jury group, including its linked rounds. Filter out memberships where every linked round is LIVE_FINAL or DELIBERATION. Keep memberships where at least one linked round is INTAKE / FILTERING / EVALUATION / SUBMISSION / MENTORING.
This produces `<sanitizedProjectName>/mentorship/<timestamp>-<sanitizedFileName>`, matching the existing project-file scheme.
**Procedure changes:**
1. Add a presign procedure (if not present): `mentor.presignWorkspaceUpload({ mentorAssignmentId, fileName, mimeType, size })` →
- Loads the `MentorAssignment` + linked `Project` (server-side).
- Authorizes: user is the assigned mentor OR a project team member (mentorProcedure for mentors; protectedProcedure with project-team check for applicants).
- Returns `{ uploadUrl, bucket, objectKey }` — the presigned PUT URL is short-lived (1h).
2. Change `workspaceUploadFile` to accept ONLY `{ uploadToken, description? }` (where `uploadToken` is an opaque value returned by the presign call). The presign procedure stores `{ token → { mentorAssignmentId, fileName, mimeType, size, bucket, objectKey } }` in a short-lived cache (in-memory or Redis if configured, 1h TTL). The upload procedure looks up the token, validates that the user is the same one who called presign, then writes the `MentorFile` row using the cached values. This eliminates any client-controlled path entirely.
3. Mirror the same change for applicant-side uploads to mentor workspace (if a separate procedure exists).
**Migration:** Pre-flight — confirm `MentorFile` table is empty (or only test data) in production. If it has any rows, migrate `objectKey`s to the new scheme via a one-shot script; otherwise skip migration.
3. Project A has `mentoringRequested=true`, project B does not.
4. Round-engine activation: B auto-PASSED (pass-through), A stays PENDING.
5. Admin manually assigns mentor M1 to project A. A flips PENDING → IN_PROGRESS. Mentor + team get assignment notification.
6. M1 sends a message in workspace; team replies. Both messages appear in respective dashboard previews.
7. M1 uploads a file. ObjectKey matches `<projectA-title>/mentorship/<timestamp>-...`. Team comments on the file.
8. M1 marks all required milestones complete → assignment.completionStatus = "completed".
9. Admin closes round. A and B both PASSED; A also COMPLETED.
This single test covers the operational path the user actually cares about for the upcoming round.
---
## Open questions
1.**`generateMentorObjectKey` — which "project name" field do we pass?** `Project.title` is the obvious choice (it's what `generateObjectKey` for submission files uses). Confirm during impl that there's no team-name-specific field we should prefer.
2.**Does `JuryGroup` have a direct `rounds` Prisma relation?** Spec assumes it; confirm field name during impl. If it's `Round.juryGroupId` only (no back-relation), use a nested `Round` query.
3.**Mentor-onboarding email content** — copy needs writing. Owned by admin, not blocking impl; can ship with placeholder copy and finalize before going live.
4.**`mentor.autoAssignBulk` — does it already skip manually-assigned?** Spec assumes yes; confirm by reading source during PR 4. If no, change is small (add `where: { method: { not: 'MANUAL' } }` to its query).
5.**Pre-flight check on existing mentor files in prod MinIO before §F.1** — must be empty or migrated, not orphaned. Confirm via `prisma db query` against prod read replica before deploying PR 2.
## Risks
| Risk | Severity | Mitigation |
|------|----------|------------|
| Existing mentor files in prod use legacy keys | High if hit | Pre-flight check; migration script ready before deploy |
| `bulkUpdateRoles` accidentally removes a critical role | Med | Server-side guard: SUPER_ADMIN cannot be self-demoted; audit log all changes |
| Multi-role redirect priority surprises some users | Low | Document the priority order; role switcher exists for override |
| AI fallback ordering doesn't match prior AI suggestions | Low | UX banner clearly states fallback is in use; keep logic simple |
| Filter on `getOnboardingContext` accidentally hides valid memberships | Low | Tests cover the three cases; ship behind no flag, easy to revert |
## Migration plan
- §A: no migration.
- §B: no migration.
- §C: no migration.
- §D: one Prisma migration adding nullable `User.mentorOnboardingSentAt: DateTime?`. No backfill (treat all existing users as not-yet-onboarded; on next role edit, email fires once).
- §E: no migration.
- §F.1: optional one-shot script to rewrite legacy `MentorFile.objectKey` rows to the new scheme. Only runs if pre-flight check finds rows. The script copies objects to the new key path then updates DB rows in a transaction; old keys remain readable until manual cleanup.
- §F.2: optional Prisma index on `MentorMessage(workspaceId, createdAt DESC)` if not present.
## Rollback
Each PR independently revertable. PRs 1, 2, 4 ship with no migration → straight git revert. PR 6 has a migration → revert PR + one-line down migration to drop the column. PR 3 has no migration; PR 5 has no migration.
## Acceptance criteria (per phase)
**PR 1 (§E):**
- Sophie Laurent (member of Screening, Expert, Finals jury groups) sees Screening + Expert preferences only — not Finals.
**PR 2 (§F.1):**
- New mentor file uploads write to `<projectName>/mentorship/<timestamp>-<file>` in MinIO.
- Removing `bucket` / `objectKey` from a `workspaceUploadFile` call still succeeds.
- Old `objectKey` upload payloads now fail Zod validation.
**PR 3 (§A):**
- All `MentoringConfigSchema` fields are editable from the Config tab.
- A draft MENTORING round with no document-promotion configured can pass Launch Readiness without a "File requirements set" check.
**PR 4 (§C):**
- Admin can manually assign any MENTOR-role user to any project from `/admin/projects/[id]/mentor`.
- Round Projects tab "Auto-fill remaining" assigns to all `mentoringRequested=true` projects without a mentor.
- Page renders sensibly with no `OPENAI_API_KEY` set (expertise-tag fallback).
**PR 5 (§B):**
- MENTORING round Overview shows live counts (requested / assigned / unassigned), deadline countdown, mentor pool size, workspace activity totals.
-`/admin/mentors` shows real list of MENTOR-role users with current assignments.
- Juror+observer logging in during an active jury round lands on `/jury` (context-aware default). Same user logging in after the round closes lands on `/jury` via static fallback (still highest-priority role they hold).
- Mentor+juror with active mentoring assignments and no jury work lands on `/mentor`.
-`RoleSwitcherPill` ("Switch View") renders in the top-right of the header on every dashboard for multi-role users, in the same screen position regardless of layout. Single-role users don't see it.
- Admin sidebar still has the user pill at the bottom-left for sign-out / settings; role-switcher entries are removed from that menu (live in the new pill instead).