diff --git a/app/admin/tracker/[github]/page.tsx b/app/admin/tracker/[github]/page.tsx
index a6cd704..7b58b43 100644
--- a/app/admin/tracker/[github]/page.tsx
+++ b/app/admin/tracker/[github]/page.tsx
@@ -1,14 +1,7 @@
-import { notFound, redirect } from "next/navigation";
-import Link from "next/link";
-import { ChevronRight, ExternalLink } from "lucide-react";
-import { Avatar } from "@/components/ui/avatar";
-import { PRStateBadge } from "@/components/ui/badge";
-import { StatusBadge } from "@/components/tracker/status-badge";
-import { SyncButton } from "@/components/tracker/sync-button";
+import { redirect } from "next/navigation";
import { getMember, getSession } from "@/lib/session";
import { can } from "@/lib/permissions";
-import { loadStudent } from "@/lib/tracker/store";
-import { ageLabel, formatDate } from "@/lib/tracker/format";
+import { StudentView } from "@/components/tracker/student-view";
export const dynamic = "force-dynamic";
@@ -17,15 +10,6 @@ export async function generateMetadata({ params }: { params: Promise<{ github: s
return { title: `${decodeURIComponent(github)} · Student tracker` };
}
-function Stat({ label, value, hint }: { label: string; value: string | number; hint?: string }) {
- return (
-
- );
-}
-
export default async function StudentTrackerPage({ params }: { params: Promise<{ github: string }> }) {
const { github } = await params;
const session = await getSession();
@@ -33,113 +17,5 @@ export default async function StudentTrackerPage({ params }: { params: Promise<{
const me = await getMember(session.usn);
if (!me || me.status !== "approved" || !can(me, "tracker:view")) redirect("/dashboard");
- const s = await loadStudent(decodeURIComponent(github));
- if (!s) notFound();
- const now = new Date();
- const t = s.totals;
- const pct = (n: number | null) => (n === null ? "—" : `${n}%`);
-
- return (
-
-
-
- Admin
-
- Student tracker
-
- {s.name}
-
-
-
-
-
-
- {s.syncedAt ? `PR numbers refreshed ${ageLabel(s.syncedAt, now)}` : `PR numbers from the ${formatDate(s.snapshotDate)} sheet; not yet refreshed from GitHub`}
-
-
- {s.syncError && Last sync failed: {s.syncError}. Showing the previous numbers. }
-
-
-
-
-
- What needs doing
-
-
Blocker {s.blocker ?? "None recorded"}
-
Waiting {s.waitingDays !== null ? `${s.waitingDays} days on the primary PR` : "—"}
-
Last PR opened {formatDate(s.lastStudentActivity)}{s.daysSinceActivity !== null && ` (${s.daysSinceActivity}d ago)`}
-
Last maintainer response {s.daysSinceMaintainer !== null ? `${s.daysSinceMaintainer}d ago` : "None on record"}
-
Suggested next step {s.recommendation ?? "—"}
- {s.suggestedMessage &&
Draft message (edit before sending) {s.suggestedMessage} }
-
- These suggestions come from the mentorship sheet and may be out of date after a sync.
-
-
-
- Change since 31 Oct
-
- {s.progress.summary || "No change recorded."} (PRs {s.progress.prevTotal} → {t.total}, merged {s.progress.prevMerged} → {t.merged}
- {s.progress.gradeChange && `, grade ${s.progress.gradeChange}`})
-
-
-
-
- Pull requests ({s.prs.length})
- {s.prs.length === 0 ? (
- No public pull requests on record.
- ) : (
-
- )}
-
-
-
- Appreciation ({s.appreciation.length})
- {s.appreciation.length === 0 ? (
- No maintainer appreciation found yet.
- ) : (
-
- )}
-
-
-
- );
+ return ;
}
diff --git a/app/admin/tracker/page.tsx b/app/admin/tracker/page.tsx
index ef70579..2862828 100644
--- a/app/admin/tracker/page.tsx
+++ b/app/admin/tracker/page.tsx
@@ -1,14 +1,7 @@
import { redirect } from "next/navigation";
-import Link from "next/link";
-import { ChevronRight } from "lucide-react";
import { getMember, getSession } from "@/lib/session";
import { can } from "@/lib/permissions";
-import { loadStudents } from "@/lib/tracker/store";
-import { toRow } from "@/lib/tracker/rows";
-import { summarize } from "@/lib/tracker/summary";
-import { ageLabel, formatDate } from "@/lib/tracker/format";
-import { TrackerDashboard, type FeedItem } from "@/components/tracker/tracker-dashboard";
-import { SyncButton } from "@/components/tracker/sync-button";
+import { TrackerOverview } from "@/components/tracker/tracker-overview";
export const metadata = { title: "Open Source Student Tracker" };
// Reads Firestore per request so a sync shows up on the next refresh; GitHub is never called from here.
@@ -20,54 +13,5 @@ export default async function TrackerPage() {
const me = await getMember(session.usn);
if (!me || me.status !== "approved" || !can(me, "tracker:view")) redirect("/dashboard");
- const students = await loadStudents();
- const now = new Date();
-
- if (students.length === 0) {
- return (
-
- Open Source Student Tracker
-
- No first-year data has been imported yet. Run npm run import:tracker -- <export.txt> --commit to load the mentorship workbook.
-
-
- );
- }
-
- const summary = summarize(students);
- const snapshotDate = students.reduce((latest, s) => (s.snapshotDate > latest ? s.snapshotDate : latest), "");
- const synced = students.filter((s) => s.syncedAt).map((s) => s.syncedAt as string).sort();
- const failing = students.filter((s) => s.syncError).length;
-
- const feed: FeedItem[] = students
- .flatMap((s) => s.appreciation.map((a) => ({ github: s.github, name: s.name, reviewer: a.reviewer, comment: a.comment.slice(0, 220), date: a.date, repo: a.repo, url: a.url })))
- .sort((a, b) => (b.date ?? "").localeCompare(a.date ?? ""))
- .slice(0, 8);
-
- return (
-
-
-
- Admin
-
- Student tracker
-
-
-
- Open Source Student Tracker
-
- First-year progress in open source. Numbers describe public GitHub activity only, so a quiet student may be working privately.
-
-
- Imported snapshot {formatDate(snapshotDate)} · {synced.length}/{students.length} students refreshed from GitHub
- {synced.length > 0 && ` · latest ${ageLabel(synced[synced.length - 1], now)}`}
- {failing > 0 && ` · ${failing} failed their last sync`}
-
-
-
-
-
-
-
- );
+ return ;
}
diff --git a/app/api/admin/tracker/records/route.ts b/app/api/admin/tracker/records/route.ts
new file mode 100644
index 0000000..4261d42
--- /dev/null
+++ b/app/api/admin/tracker/records/route.ts
@@ -0,0 +1,82 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { z } from "zod";
+import { authErrorResponse, requireCapability } from "@/lib/session";
+import { checkRateLimit, RATE_LIMITS } from "@/lib/rate-limit";
+import { createRecord, deleteRecord, loadRecords, updateRecord, type Author } from "@/lib/tracker/records-store";
+
+export const runtime = "nodejs";
+
+async function actor() {
+ const { session, member } = await requireCapability("tracker:view");
+ const author: Author = { usn: session.usn, name: member.name, isAdmin: member.role === "admin" };
+ return { session, author };
+}
+
+const fail = (status: number, message: string) => NextResponse.json({ ok: false, message }, { status });
+
+/** GET ?github= → that student's mentor records. Mentors and admins only. */
+export async function GET(request: NextRequest) {
+ try {
+ await actor();
+ } catch (error) {
+ return authErrorResponse(error);
+ }
+ const github = request.nextUrl.searchParams.get("github")?.trim();
+ if (!github) return fail(400, "github is required.");
+ return NextResponse.json({ ok: true, records: await loadRecords(github) });
+}
+
+async function limited(usn: string) {
+ const r = await checkRateLimit("tracker-records", usn, RATE_LIMITS.write);
+ return r.ok ? null : NextResponse.json({ ok: false, message: `Slow down: try again in ${r.retryAfterSeconds}s.` }, { status: 429, headers: { "Retry-After": String(r.retryAfterSeconds) } });
+}
+
+export async function POST(request: NextRequest) {
+ let a;
+ try {
+ a = await actor();
+ } catch (error) {
+ return authErrorResponse(error);
+ }
+ const blocked = await limited(a.session.usn);
+ if (blocked) return blocked;
+
+ const result = await createRecord(await request.json().catch(() => null), a.author);
+ return result.ok ? NextResponse.json({ ok: true, record: result.record }, { status: 201 }) : fail(result.status, result.message);
+}
+
+const IdBody = z.object({ id: z.string().trim().min(1).max(100) });
+
+/** PUT { id, ...record } replaces a record's content; type and student stay fixed. */
+export async function PUT(request: NextRequest) {
+ let a;
+ try {
+ a = await actor();
+ } catch (error) {
+ return authErrorResponse(error);
+ }
+ const blocked = await limited(a.session.usn);
+ if (blocked) return blocked;
+
+ const body = await request.json().catch(() => null);
+ const id = IdBody.safeParse(body);
+ if (!id.success) return fail(400, "id is required.");
+ const result = await updateRecord(id.data.id, body, a.author);
+ return result.ok ? NextResponse.json({ ok: true, record: result.record }) : fail(result.status, result.message);
+}
+
+export async function DELETE(request: NextRequest) {
+ let a;
+ try {
+ a = await actor();
+ } catch (error) {
+ return authErrorResponse(error);
+ }
+ const blocked = await limited(a.session.usn);
+ if (blocked) return blocked;
+
+ const id = IdBody.safeParse({ id: request.nextUrl.searchParams.get("id") });
+ if (!id.success) return fail(400, "id is required.");
+ const result = await deleteRecord(id.data.id, a.author);
+ return result.ok ? NextResponse.json({ ok: true }) : fail(result.status, result.message);
+}
diff --git a/app/api/dev/tracker/records/route.ts b/app/api/dev/tracker/records/route.ts
new file mode 100644
index 0000000..81571ef
--- /dev/null
+++ b/app/api/dev/tracker/records/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { demoEnabled } from "@/lib/tracker/demo";
+import { createRecord, deleteRecord, updateRecord, type Author } from "@/lib/tracker/records-store";
+
+export const runtime = "nodejs";
+
+/**
+ * Same record logic as /api/admin/tracker/records, but on the in-memory demo
+ * data and with no sign-in. Exists only for `next dev` with TRACKER_DEMO=1 and
+ * answers 404 otherwise, so it cannot be reached in production.
+ */
+const author: Author = { usn: "demo", name: "Demo Mentor", isAdmin: true };
+const gone = () => new NextResponse(null, { status: 404 });
+const out = (r: { ok: boolean; status?: number; message?: string; record?: unknown }, okStatus = 200) =>
+ r.ok ? NextResponse.json({ ok: true, record: r.record }, { status: okStatus }) : NextResponse.json({ ok: false, message: r.message }, { status: r.status });
+
+export async function POST(request: NextRequest) {
+ if (!demoEnabled()) return gone();
+ return out(await createRecord(await request.json().catch(() => null), author), 201);
+}
+
+export async function PUT(request: NextRequest) {
+ if (!demoEnabled()) return gone();
+ const body = (await request.json().catch(() => null)) as { id?: string } | null;
+ if (!body?.id) return NextResponse.json({ ok: false, message: "id is required." }, { status: 400 });
+ return out(await updateRecord(body.id, body, author));
+}
+
+export async function DELETE(request: NextRequest) {
+ if (!demoEnabled()) return gone();
+ const id = request.nextUrl.searchParams.get("id");
+ if (!id) return NextResponse.json({ ok: false, message: "id is required." }, { status: 400 });
+ return out(await deleteRecord(id, author));
+}
diff --git a/app/dev/tracker/[github]/page.tsx b/app/dev/tracker/[github]/page.tsx
new file mode 100644
index 0000000..44677bb
--- /dev/null
+++ b/app/dev/tracker/[github]/page.tsx
@@ -0,0 +1,11 @@
+import { notFound } from "next/navigation";
+import { demoEnabled } from "@/lib/tracker/demo";
+import { StudentView } from "@/components/tracker/student-view";
+
+export const dynamic = "force-dynamic";
+
+export default async function DemoStudentPage({ params }: { params: Promise<{ github: string }> }) {
+ if (!demoEnabled()) notFound();
+ const { github } = await params;
+ return ;
+}
diff --git a/app/dev/tracker/page.tsx b/app/dev/tracker/page.tsx
new file mode 100644
index 0000000..40359bf
--- /dev/null
+++ b/app/dev/tracker/page.tsx
@@ -0,0 +1,12 @@
+import { notFound } from "next/navigation";
+import { demoEnabled } from "@/lib/tracker/demo";
+import { TrackerOverview } from "@/components/tracker/tracker-overview";
+
+export const metadata = { title: "Student tracker (demo)" };
+export const dynamic = "force-dynamic";
+
+/** Development preview on made-up data. 404s everywhere except `next dev` with TRACKER_DEMO=1. */
+export default function DemoTrackerPage() {
+ if (!demoEnabled()) notFound();
+ return ;
+}
diff --git a/components/dashboard/dashboard-nav.tsx b/components/dashboard/dashboard-nav.tsx
index 271eb08..f232cf1 100644
--- a/components/dashboard/dashboard-nav.tsx
+++ b/components/dashboard/dashboard-nav.tsx
@@ -13,6 +13,7 @@ import {
Trophy,
ShieldCheck,
ClipboardCheck,
+ Activity,
Menu,
X,
} from "lucide-react";
@@ -32,13 +33,13 @@ interface NavLink {
const LINKS: NavLink[] = [
{ name: "Overview", href: "/dashboard", icon: },
+ { name: "Student tracker", href: "/admin/tracker", icon: , tracker: true },
{ name: "Projects", href: "/dashboard/projects", icon: },
{ name: "Explore", href: "/dashboard/explore", icon: },
{ name: "Sessions", href: "/dashboard/events", icon: },
{ name: "Members", href: "/dashboard/members", icon: },
{ name: "Leaderboard", href: "/dashboard/leaderboard", icon: },
{ name: "Sign-offs", href: "/dashboard/journey", icon: , reviewer: true },
- { name: "Tracker", href: "/admin/tracker", icon: , tracker: true },
{ name: "Admin", href: "/admin", icon: , elevated: true },
];
diff --git a/components/tracker/records-panel.tsx b/components/tracker/records-panel.tsx
new file mode 100644
index 0000000..e129543
--- /dev/null
+++ b/components/tracker/records-panel.tsx
@@ -0,0 +1,301 @@
+"use client";
+
+import { useState, type FormEvent } from "react";
+import { useRouter } from "next/navigation";
+import { CalendarClock, CheckCircle2, Pencil, Plus, Trash2, TriangleAlert, X } from "lucide-react";
+import { formatDate } from "@/lib/tracker/format";
+import {
+ BADGES, BADGE_LABELS, CONTEXT_LABELS, CONTEXT_TYPES, DIFFICULTIES, NOTE_TYPES, NOTE_TYPE_LABELS, TASK_STATUSES, TASK_STATUS_LABELS,
+ type TrackerRecord,
+} from "@/lib/tracker/records";
+import type { WeeklySummary } from "@/lib/tracker/weekly";
+
+type Kind = TrackerRecord["kind"];
+type Values = Record;
+
+interface Field {
+ name: string;
+ label: string;
+ type: "text" | "textarea" | "date" | "number" | "select";
+ required?: boolean;
+ options?: readonly (readonly [string, string])[];
+ hint?: string;
+}
+
+const opts = (values: readonly T[], labels?: Record) => values.map((v) => [v, labels?.[v] ?? v] as const);
+
+const FIELDS: Record = {
+ task: [
+ { name: "title", label: "Task or issue title", type: "text", required: true },
+ { name: "repo", label: "Repository (owner/name)", type: "text" },
+ { name: "issueNumber", label: "Issue number", type: "number" },
+ { name: "issueUrl", label: "Issue link", type: "text", hint: "Must start with https://" },
+ { name: "description", label: "Description", type: "textarea" },
+ { name: "difficulty", label: "Difficulty", type: "select", required: true, options: opts(DIFFICULTIES, { easy: "Easy", medium: "Medium", hard: "Hard" }) },
+ { name: "status", label: "Status", type: "select", required: true, options: opts(TASK_STATUSES, TASK_STATUS_LABELS) },
+ { name: "assignedAt", label: "Assigned on", type: "date", required: true },
+ { name: "dueDate", label: "Expected by", type: "date" },
+ { name: "blockers", label: "Blockers", type: "textarea" },
+ { name: "nextAction", label: "Next action", type: "text" },
+ ],
+ note: [
+ { name: "noteType", label: "Type of note", type: "select", required: true, options: opts(NOTE_TYPES, NOTE_TYPE_LABELS) },
+ { name: "text", label: "Note", type: "textarea", required: true },
+ { name: "visibility", label: "Who can see it", type: "select", required: true, options: [["mentors", "Mentors only"], ["student", "Mentors and the student"]], hint: "The student view is not built yet, so nothing is shown to students today." },
+ ],
+ appreciation: [
+ { name: "title", label: "Title", type: "text", required: true },
+ { name: "reason", label: "Why they deserve it", type: "textarea", required: true },
+ { name: "badge", label: "Badge", type: "select", required: true, options: opts(BADGES, BADGE_LABELS) },
+ { name: "sourceUrl", label: "Link to the work", type: "text" },
+ { name: "date", label: "Date", type: "date", required: true },
+ ],
+ review: [
+ { name: "weekStart", label: "Week starting (Monday)", type: "date", required: true },
+ { name: "completed", label: "Completed this week", type: "textarea" },
+ { name: "inProgress", label: "In progress", type: "textarea" },
+ { name: "learned", label: "What was learned", type: "textarea" },
+ { name: "difficult", label: "What was difficult", type: "textarea" },
+ { name: "helpNeeded", label: "Help needed", type: "textarea" },
+ { name: "nextWeek", label: "Plan for next week", type: "textarea" },
+ { name: "blockers", label: "Blockers", type: "textarea" },
+ { name: "confidence", label: "Confidence", type: "select", required: true, options: [["1", "1 – lost"], ["2", "2 – unsure"], ["3", "3 – okay"], ["4", "4 – good"], ["5", "5 – very confident"]] },
+ { name: "hours", label: "Hours or sessions", type: "number" },
+ { name: "mentorFeedback", label: "Mentor feedback", type: "textarea" },
+ ],
+ context: [
+ { name: "contextType", label: "What happened", type: "select", required: true, options: opts(CONTEXT_TYPES, CONTEXT_LABELS), hint: "These days are left out of the consistency score." },
+ { name: "startDate", label: "From", type: "date", required: true },
+ { name: "endDate", label: "To", type: "date", required: true },
+ { name: "text", label: "Detail (optional)", type: "textarea" },
+ ],
+};
+
+const KIND_LABELS: Record = { task: "Task", note: "Note", appreciation: "Appreciation", review: "Weekly review", context: "Leave / context" };
+const NUMERIC = new Set(["issueNumber", "confidence", "hours"]);
+const NULLABLE = new Set(["issueNumber", "hours", "dueDate"]);
+
+export function defaults(kind: Kind, today: string, monday: string): Values {
+ switch (kind) {
+ case "task": return { difficulty: "medium", status: "planned", assignedAt: today };
+ case "note": return { noteType: "learned", visibility: "mentors" };
+ case "appreciation": return { badge: "general", date: today };
+ case "review": return { weekStart: monday, confidence: "3" };
+ case "context": return { contextType: "approved-leave", startDate: today, endDate: today };
+ }
+}
+
+/** Form strings → the JSON the API validates. Blank optional numbers and dates become null. */
+export function toPayload(kind: Kind, github: string, values: Values): Record {
+ const out: Record = { github, kind };
+ for (const f of FIELDS[kind]) {
+ const raw = (values[f.name] ?? "").trim();
+ if (raw === "" && NULLABLE.has(f.name)) out[f.name] = null;
+ else if (NUMERIC.has(f.name)) out[f.name] = raw === "" ? undefined : Number(raw);
+ else out[f.name] = raw;
+ }
+ return out;
+}
+
+const fromRecord = (r: TrackerRecord): Values =>
+ Object.fromEntries(FIELDS[r.kind].map((f) => [f.name, String((r as unknown as Record)[f.name] ?? "")]));
+
+function summary(r: TrackerRecord): { title: string; sub: string; date: string } {
+ switch (r.kind) {
+ case "task": return { title: r.title, sub: `${TASK_STATUS_LABELS[r.status]} · ${r.difficulty}${r.dueDate ? ` · due ${formatDate(r.dueDate)}` : ""}${r.blockers ? ` · blocked: ${r.blockers}` : ""}`, date: r.assignedAt };
+ case "note": return { title: NOTE_TYPE_LABELS[r.noteType], sub: r.text, date: r.createdAt.slice(0, 10) };
+ case "appreciation": return { title: `${BADGE_LABELS[r.badge]}: ${r.title}`, sub: r.reason, date: r.date };
+ case "review": return { title: `Week of ${formatDate(r.weekStart)} (confidence ${r.confidence}/5)`, sub: [r.completed && `Done: ${r.completed}`, r.blockers && `Blockers: ${r.blockers}`, r.helpNeeded && `Needs: ${r.helpNeeded}`].filter(Boolean).join(" · ") || "No details", date: r.weekStart };
+ case "context": return { title: CONTEXT_LABELS[r.contextType], sub: r.text || `${formatDate(r.startDate)} to ${formatDate(r.endDate)}`, date: r.startDate };
+ }
+}
+
+interface Props {
+ github: string;
+ /** Records API; defaults to the real, signed-in one. */
+ endpoint?: string;
+ records: TrackerRecord[];
+ today: string;
+ monday: string;
+ weekly: WeeklySummary;
+ currentTask: Extract | null;
+ counts: { open: number; overdue: number; blocked: number };
+}
+
+const input = "mt-1 w-full bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-400/60";
+
+function List({ title, items }: { title: string; items: string[] }) {
+ return (
+
+
{title}
+
{items.length === 0 ? None : {items.slice(0, 5).map((i) => {i} )}{items.length > 5 && and {items.length - 5} more } }
+
+ );
+}
+
+export function RecordsPanel({ github, endpoint = "/api/admin/tracker/records", records, today, monday, weekly, currentTask, counts }: Props) {
+ const router = useRouter();
+ const [kind, setKind] = useState("task");
+ const [values, setValues] = useState(defaults("task", today, monday));
+ const [editing, setEditing] = useState(null);
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [confirming, setConfirming] = useState(null);
+ const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
+
+ function start(k: Kind, record?: TrackerRecord) {
+ setKind(k);
+ setValues(record ? fromRecord(record) : defaults(k, today, monday));
+ setEditing(record?.id ?? null);
+ setOpen(true);
+ setMessage(null);
+ }
+
+ async function call(method: string, url: string, body?: unknown): Promise<{ ok: boolean; message?: string }> {
+ try {
+ const res = await fetch(url, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined });
+ return await res.json().catch(() => ({ ok: false, message: `Request failed (${res.status}).` }));
+ } catch {
+ return { ok: false, message: "Could not reach the server. Check your connection and try again." };
+ }
+ }
+
+ async function submit(e: FormEvent) {
+ e.preventDefault();
+ setBusy(true);
+ const payload = toPayload(kind, github, values);
+ const res = await call(editing ? "PUT" : "POST", endpoint, editing ? { ...payload, id: editing } : payload);
+ setBusy(false);
+ if (res.ok) {
+ setMessage({ ok: true, text: editing ? "Saved." : "Added." });
+ setOpen(false);
+ setEditing(null);
+ router.refresh();
+ } else setMessage({ ok: false, text: res.message ?? "Something went wrong." });
+ }
+
+ async function remove(id: string) {
+ setBusy(true);
+ const res = await call("DELETE", `${endpoint}?id=${encodeURIComponent(id)}`);
+ setBusy(false);
+ setConfirming(null);
+ setMessage(res.ok ? { ok: true, text: "Deleted." } : { ok: false, text: res.message ?? "Could not delete." });
+ if (res.ok) router.refresh();
+ }
+
+ return (
+
+
+ Current work
+ {currentTask ? (
+ <>
+ {currentTask.title}
+
+
Repository {currentTask.repo || "—"}{currentTask.issueNumber ? ` #${currentTask.issueNumber}` : ""}
+
Status {TASK_STATUS_LABELS[currentTask.status]} · {currentTask.difficulty}
+
Assigned / expected {formatDate(currentTask.assignedAt)} / {formatDate(currentTask.dueDate)}
+
Next action {currentTask.nextAction || "—"}
+
Blockers {currentTask.blockers || "None recorded"}
+ {currentTask.description &&
Description {currentTask.description} }
+
+ {counts.open} open task{counts.open === 1 ? "" : "s"}{counts.overdue > 0 && ` · ${counts.overdue} overdue`}{counts.blocked > 0 && ` · ${counts.blocked} blocked`}
+ >
+ ) : (
+ No open task recorded. Add one below so mentors can see what this student is working on.
+ )}
+
+
+
+ Week of {formatDate(weekly.week.start)}
+
+
+
+
+
+
+
+
Progress and consistency
+ {weekly.progress.explanation}{weekly.consistencyChange !== null && ` Consistency ${weekly.consistencyChange >= 0 ? "up" : "down"} ${Math.abs(weekly.consistencyChange)} points over four weeks.`}
+
+
+
+
+
+
+
+
Mentor records ({records.length})
+ {(Object.keys(KIND_LABELS) as Kind[]).map((k) => (
+
start(k)} className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded-lg border border-white/10 hover:border-cyan-400/60 text-neutral-200">
+ {KIND_LABELS[k]}
+
+ ))}
+
+
+
+ {message && (
+
+ {message.ok ? : }{message.text}
+
+ )}
+
+
+ {open && (
+
+ )}
+
+ {records.length === 0 ? (
+ Nothing recorded yet. Use the buttons above to add a task, note, appreciation, weekly review or leave.
+ ) : (
+
+ {records.map((r) => {
+ const s = summary(r);
+ return (
+
+ {formatDate(s.date)}
+ {KIND_LABELS[r.kind]}
+
+ {s.title}
+ {s.sub}
+ by {r.authorName}{r.kind === "note" && ` · ${r.visibility === "mentors" ? "mentors only" : "visible to student"}`}
+
+ {confirming === r.id ? (
+
+ Delete this record?
+ remove(r.id)} className="px-2 py-1 rounded bg-red-500/80 text-white">Yes, delete
+ setConfirming(null)} className="px-2 py-1 rounded border border-white/10">Cancel
+
+ ) : (
+
+ start(r.kind, r)} aria-label={`Edit ${s.title}`} className="p-1.5 rounded text-neutral-400 hover:text-white">
+ setConfirming(r.id)} aria-label={`Delete ${s.title}`} className="p-1.5 rounded text-neutral-400 hover:text-red-300">
+
+ )}
+
+ );
+ })}
+
+ )}
+
+
+ );
+}
diff --git a/components/tracker/section-tabs.tsx b/components/tracker/section-tabs.tsx
new file mode 100644
index 0000000..04500e4
--- /dev/null
+++ b/components/tracker/section-tabs.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+export interface Tab {
+ /** Element id to jump to, or "top" for the top of the page. */
+ id: string;
+ label: string;
+}
+
+/**
+ * A sticky row of tabs that scroll to sections of the page and highlight the
+ * one in view. Plain buttons, so they work with the keyboard and screen
+ * readers; `aria-current` marks the active one.
+ */
+export function SectionTabs({ tabs, label }: { tabs: Tab[]; label: string }) {
+ const [active, setActive] = useState(tabs[0]?.id ?? "top");
+
+ useEffect(() => {
+ const ids = tabs.map((t) => t.id).filter((id) => id !== "top");
+ const targets = ids.map((id) => document.getElementById(id)).filter((el): el is HTMLElement => el !== null);
+ if (targets.length === 0) return;
+
+ const update = () => {
+ // Active = the last section whose top has passed the sticky bars.
+ let current = tabs[0]?.id ?? "top";
+ if (window.scrollY > 200) {
+ for (const t of tabs) {
+ if (t.id === "top") continue;
+ const el = document.getElementById(t.id);
+ if (el && el.getBoundingClientRect().top <= 180) current = t.id;
+ }
+ }
+ setActive(current);
+ };
+ update();
+ window.addEventListener("scroll", update, { passive: true });
+ return () => window.removeEventListener("scroll", update);
+ }, [tabs]);
+
+ function go(id: string) {
+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ const behavior: ScrollBehavior = reduce ? "auto" : "smooth";
+ if (id === "top") window.scrollTo({ top: 0, behavior });
+ else document.getElementById(id)?.scrollIntoView({ behavior, block: "start" });
+ setActive(id);
+ }
+
+ return (
+
+
+ {tabs.map((t) => (
+
+ go(t.id)}
+ aria-current={active === t.id ? "true" : undefined}
+ className={`whitespace-nowrap px-3 py-1.5 rounded-full text-sm font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400 ${
+ active === t.id ? "bg-cyan-400/15 text-cyan-300" : "text-neutral-400 hover:text-white hover:bg-white/5"
+ }`}
+ >
+ {t.label}
+
+
+ ))}
+
+
+ );
+}
diff --git a/components/tracker/student-activity.test.tsx b/components/tracker/student-activity.test.tsx
new file mode 100644
index 0000000..4979816
--- /dev/null
+++ b/components/tracker/student-activity.test.tsx
@@ -0,0 +1,46 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import { StudentActivity } from "./student-activity";
+import { buildEvents } from "@/lib/tracker/metrics";
+import { pr, student } from "@/lib/tracker/test-fixtures";
+
+const s = student({
+ prs: [
+ pr({ url: "a", title: "Fix the parser", createdAt: "2026-09-02" }),
+ pr({ url: "b", title: "Docs tweak", state: "merged", createdAt: "2026-10-12", closedAt: "2026-10-14" }),
+ pr({ url: "c", title: "Add tests", createdAt: "2026-11-03" }),
+ pr({ url: "d", title: "Handle empty input", createdAt: "2026-11-10" }),
+ ],
+});
+
+describe("StudentActivity", () => {
+ it("renders the totals, direction, consistency breakdown and timeline for one month", () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain("Progress direction");
+ expect(html).toContain("Consistency score");
+ expect(html).toContain("Weekly regularity");
+ expect(html).toContain("Add tests");
+ expect(html).toContain("Handle empty input");
+ expect(html).not.toContain("Fix the parser"); // opened before the one-month window
+ expect(html).toContain("data as of 13 Nov 2026");
+ });
+
+ it("opens on all time by default so a quiet recent month does not hide a student's history", () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain("Fix the parser"); // opened in September, outside the last month
+ expect(html).toContain("2 Sept 2026 to 13 Nov 2026");
+ expect(html).toContain("Pull requests over time");
+ });
+
+ it("says there is not enough data instead of drawing empty charts", () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain("Not enough activity data yet.");
+ expect(html).toContain("No activity on record to score yet.");
+ expect(html).toContain("Nothing recorded in this period.");
+ });
+
+ it("never promises metrics it does not collect", () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain("not collected yet");
+ });
+});
diff --git a/components/tracker/student-activity.tsx b/components/tracker/student-activity.tsx
new file mode 100644
index 0000000..6e78843
--- /dev/null
+++ b/components/tracker/student-activity.tsx
@@ -0,0 +1,304 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { Bar, CartesianGrid, Cell, ComposedChart, Legend, Line, Pie, PieChart, PolarAngleAxis, RadialBar, RadialBarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
+import { ArrowDownRight, ArrowRight, ArrowUpRight, CircleHelp, ExternalLink, Flame } from "lucide-react";
+import { formatDate } from "@/lib/tracker/format";
+import {
+ consistencyScore, countKinds, DIRECTION_LABELS, firstEventDate, inRange, KIND_LABELS, previousRange, progressDirection, RANGE_LABELS, resolveRange,
+ weekStreaks, weeklyBuckets, type ActivityEvent, type ActivityKind, type Direction, type RangeKey,
+} from "@/lib/tracker/metrics";
+
+interface Props {
+ events: ActivityEvent[];
+ /** The day the numbers were last true; every range ends here, not on today's date. */
+ asOf: string;
+ /** Days a mentor excused (leave, research...); weeks fully covered leave the consistency maths. */
+ excused?: string[];
+ /** PR counts by kind of repository, for the "where the work went" donut. */
+ repoMix?: { name: string; value: number }[];
+ /** Period shown first. "All time" so every student opens on a graph of their whole history. */
+ initialRange?: RangeKey;
+}
+
+const COLOURS: Record = { pr_opened: "#38bdf8", pr_merged: "#4ade80", pr_closed: "#a3a3a3", appreciation: "#f472b6", task_completed: "#a78bfa", weekly_review: "#fbbf24", mentor_note: "#fb923c" };
+const SERIES: { kind: ActivityKind; label: string }[] = [
+ { kind: "pr_opened", label: "Opened" },
+ { kind: "pr_merged", label: "Merged" },
+ { kind: "pr_closed", label: "Closed" },
+ { kind: "appreciation", label: "Appreciation" },
+ { kind: "task_completed", label: "Tasks done" },
+ { kind: "weekly_review", label: "Reviews" },
+];
+const REPO_COLOURS = ["#4ade80", "#38bdf8", "#a3a3a3", "#facc15"];
+const TOOLTIP = { background: "#0a0a0a", border: "1px solid #262626", borderRadius: 8 } as const;
+const EMPTY = "Not enough activity data yet.";
+
+const DIRECTION_STYLE: Record = {
+ improving: { tone: "text-green-300 border-green-500/30 bg-green-500/10", icon: },
+ stable: { tone: "text-sky-300 border-sky-500/30 bg-sky-500/10", icon: },
+ declining: { tone: "text-yellow-300 border-yellow-500/30 bg-yellow-500/10", icon: },
+ insufficient: { tone: "text-neutral-300 border-neutral-500/30 bg-neutral-500/10", icon: },
+};
+
+const shortDay = (iso: string) => formatDate(iso).replace(/ \d{4}$/, "");
+
+/** Words and colour for a 0-100 score. The words carry the meaning; colour is a bonus. */
+function scoreBand(score: number): { label: string; colour: string } {
+ if (score >= 70) return { label: "Steady", colour: "#4ade80" };
+ if (score >= 40) return { label: "Some gaps", colour: "#facc15" };
+ return { label: "Quiet lately", colour: "#fb923c" };
+}
+
+function Tile({ label, value, hint, colour }: { label: string; value: string | number; hint?: string; colour?: string }) {
+ return (
+
+ );
+}
+
+export function StudentActivity({ events, asOf, excused = [], repoMix = [], initialRange = "all" }: Props) {
+ const [key, setKey] = useState(initialRange);
+ const [custom, setCustom] = useState({ start: "", end: asOf });
+ const [shown, setShown] = useState>({ pr_opened: true, pr_merged: true, pr_closed: false, appreciation: false, task_completed: false, weekly_review: false, mentor_note: false });
+
+ const first = firstEventDate(events);
+ const range = resolveRange(key, asOf, custom, first);
+ const view = useMemo(() => {
+ if (!range) return null;
+ const inside = inRange(events, range);
+ const buckets = weeklyBuckets(events, range);
+ let running = events.filter((e) => e.kind === "pr_merged" && e.date < range.start).length;
+ return {
+ inside,
+ counts: countKinds(inside),
+ chart: buckets.map((b) => ({ ...b, label: shortDay(b.from), total: (running += b.pr_merged) })),
+ previous: countKinds(inRange(events, previousRange(range))),
+ direction: progressDirection(events, range),
+ consistency: consistencyScore(events, range, excused),
+ };
+ }, [events, range, excused]);
+
+ const streaks = useMemo(() => weekStreaks(events, asOf, excused), [events, asOf, excused]);
+ const hasData = !!view && view.inside.length > 0;
+ const style = view ? DIRECTION_STYLE[view.direction.direction] : null;
+ const band = view?.consistency ? scoreBand(view.consistency.score) : null;
+ const outcome = view
+ ? [
+ { name: "Merged", value: view.counts.pr_merged, fill: COLOURS.pr_merged },
+ { name: "Closed without merge", value: view.counts.pr_closed, fill: COLOURS.pr_closed },
+ { name: "Still open", value: Math.max(0, view.counts.pr_opened - view.counts.pr_merged - view.counts.pr_closed), fill: COLOURS.pr_opened },
+ ].filter((d) => d.value > 0)
+ : [];
+ const mix = repoMix.filter((m) => m.value > 0);
+
+ return (
+
+
+ Activity over time
+
+
+ Period
+ setKey(e.target.value as RangeKey)} className="mt-1 block bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white">
+ {(Object.keys(RANGE_LABELS) as RangeKey[]).map((k) => {RANGE_LABELS[k]} )}
+
+
+ {key === "custom" && (
+ <>
+
+ From
+ setCustom((c) => ({ ...c, start: e.target.value }))} className="mt-1 block bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white" />
+
+
+ To
+ setCustom((c) => ({ ...c, end: e.target.value }))} className="mt-1 block bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white" />
+
+ >
+ )}
+
+ {range ? `${formatDate(range.start)} to ${formatDate(range.end)}` : "Pick a start date on or before the end date."}
+ {" · "}data as of {formatDate(asOf)}
+
+
+
+
+ {!view ? (
+
Choose a valid date range to see activity.
+ ) : (
+ <>
+
+
+ Consistency score
+ {view.consistency && band ? (
+ <>
+
+
+
+
+
+
+
+
+ {view.consistency.score}/100
+ {band.label}
+
+
+
+ How is this calculated?
+ {view.consistency.explanation}
+
+ {view.consistency.parts.map((p) => (
+ {p.label} {p.points}/{p.max}: {p.detail}
+ ))}
+
+
+ >
+ ) : (
+ No activity on record to score yet.
+ )}
+
+
+
+ Progress direction
+
+ {style?.icon}
+ {DIRECTION_LABELS[view.direction.direction]}
+
+ {view.direction.explanation}
+ Points: PR opened 1, merged 2, task done 2, review 1, appreciation 1, compared with the previous equally long period. Several kinds of activity count, never one number alone.
+
+
+
+ Streak
+
+
0 ? "text-orange-400" : "text-neutral-600"} aria-hidden />
+
+
{streaks.currentWeeks} weeks
+
in a row with a PR opened or merged
+
+
+ Longest run on record: {streaks.longestWeeks} week{streaks.longestWeeks === 1 ? "" : "s"} . A week still in progress does not break the streak.
+
+
+
+
+
Commits, reviews given and issues are not collected yet, so they are not shown instead of being guessed.
+
+
+
+
+
Pull requests over time
+
Bars show each week; the line is merged PRs so far.
+
+
+ Show or hide metrics
+ {SERIES.map((s) => (
+
+ setShown((v) => ({ ...v, [s.kind]: e.target.checked }))} />
+
+ {s.label}
+
+ ))}
+
+
+ {!hasData ? {EMPTY}
: (
+ <>
+
+
+
+
+
+
+
+
+ {SERIES.filter((s) => shown[s.kind]).map((s) => (
+
+ ))}
+
+
+
+
+ {view.chart.map((b) => Week of {b.label}: {b.pr_opened} opened, {b.pr_merged} merged, {b.total} merged so far )}
+ >
+ )}
+
+
+
+
+ Pull request outcomes
+ {outcome.length === 0 ? {EMPTY}
: (
+ <>
+
+
+
+
+ {outcome.map((d) => | )}
+
+
+
+
+
+
+ {outcome.map((d) => {d.name}: {d.value} )}
+ >
+ )}
+
+
+
+ Where the work went
+ {mix.length === 0 ? {EMPTY}
: (
+ <>
+
+
+
+
+ {mix.map((d, i) => | )}
+
+
+
+
+
+
+ {mix.map((d) => {d.name}: {d.value} PRs )}
+ >
+ )}
+
+
+
+
+ 0 && view.inside.length <= 8} className="space-y-3">
+ Timeline ({view.inside.length})
+ {view.inside.length === 0 ? (
+ Nothing recorded in this period.
+ ) : (
+
+ {view.inside.map((e) => (
+
+ {formatDate(e.date)}
+ {KIND_LABELS[e.kind]}
+
+ {e.url ? (
+ {e.title}
+ ) : e.title}
+ {e.detail}
+
+
+ ))}
+
+ )}
+
+
+ >
+ )}
+
+ );
+}
diff --git a/components/tracker/student-view.tsx b/components/tracker/student-view.tsx
new file mode 100644
index 0000000..298d07a
--- /dev/null
+++ b/components/tracker/student-view.tsx
@@ -0,0 +1,198 @@
+import { notFound } from "next/navigation";
+import Link from "next/link";
+import { ChevronRight, ExternalLink } from "lucide-react";
+import { Avatar } from "@/components/ui/avatar";
+import { PRStateBadge } from "@/components/ui/badge";
+import { StatusBadge } from "./status-badge";
+import { SyncButton } from "./sync-button";
+import { loadStudent } from "@/lib/tracker/store";
+import { ageLabel, formatDate } from "@/lib/tracker/format";
+import { asOfDate, buildEvents, weekStart } from "@/lib/tracker/metrics";
+import { currentWork, excusedDays, recordEvents } from "@/lib/tracker/records";
+import { loadRecords } from "@/lib/tracker/records-store";
+import { weeklySummary } from "@/lib/tracker/weekly";
+import { SectionTabs } from "./section-tabs";
+import { RecordsPanel } from "./records-panel";
+import { StudentActivity } from "./student-activity";
+
+function Stat({ label, value, hint }: { label: string; value: string | number; hint?: string }) {
+ return (
+
+ );
+}
+
+interface Props {
+ github: string;
+ basePath: string;
+ rootHref: string;
+ rootLabel: string;
+ sync: boolean;
+ /** API the forms talk to; the demo preview points this at its in-memory copy. */
+ recordsEndpoint: string;
+}
+
+/** A student's whole page once access has been checked. Auth is the caller's job. */
+export async function StudentView({ github, basePath, rootHref, rootLabel, sync, recordsEndpoint }: Props) {
+ const s = await loadStudent(github);
+ if (!s) notFound();
+ const now = new Date();
+ const records = await loadRecords(s.github);
+ const asOf = asOfDate(s);
+ const events = buildEvents(s, recordEvents(records));
+ const excused = excusedDays(records);
+ const work = currentWork(records, asOf);
+ const monday = weekStart(asOf);
+ const t = s.totals;
+ const pct = (n: number | null) => (n === null ? "—" : `${n}%`);
+ const credible = s.prs.filter((p) => p.credible).length;
+ const teaching = s.prs.filter((p) => p.teaching).length;
+ const repoMix = [
+ { name: "Credible repos", value: credible },
+ { name: "Teaching repos", value: teaching },
+ { name: "Other repos", value: Math.max(0, s.prs.length - credible - teaching) },
+ ];
+ const headline =
+ t.total === 0
+ ? "No public pull requests yet."
+ : `${t.total} pull request${t.total === 1 ? "" : "s"}: ${t.merged} merged, ${t.open} open, ${t.closed} closed.${s.daysSinceActivity !== null ? ` Last one opened ${s.daysSinceActivity} days before the data date.` : ""}`;
+
+ return (
+
+
+
+ {rootLabel}
+
+ Student tracker
+
+ {s.name}
+
+
+
+
+
{headline}
+
+
+
+ {s.syncedAt ? `PR numbers refreshed ${ageLabel(s.syncedAt, now)}` : `PR numbers from the ${formatDate(s.snapshotDate)} sheet; not yet refreshed from GitHub`}
+
+ {sync && }
+ {s.syncError && Last sync failed: {s.syncError}. Showing the previous numbers. }
+
+
+
+
+
+
+
+
+
+
+
+
+ {[
+ `Grade ${s.grade ?? "—"}`,
+ `GSoC: ${s.gsocReadiness || "—"}`,
+ `${t.projects} project${t.projects === 1 ? "" : "s"}`,
+ `Title hygiene ${pct(t.titleHygienePct)}`,
+ s.progress.prevTotal !== t.total || s.progress.prevMerged !== t.merged ? `Since 31 Oct: PRs ${s.progress.prevTotal} → ${t.total}, merged ${s.progress.prevMerged} → ${t.merged}` : "No change since 31 Oct",
+ ].map((chip) => {chip} )}
+
+
+
+
+
+
+ What needs doing
+ {s.recommendation ?? "Nothing suggested. Check in with the student."}
+
+ Blocker: {s.blocker ?? "none recorded"}
+ {s.waitingDays !== null ? `Waiting ${s.waitingDays} days` : "Nothing waiting"}
+ Last PR: {formatDate(s.lastStudentActivity)}{s.daysSinceActivity !== null && ` (${s.daysSinceActivity}d ago)`}
+ Maintainer replied: {s.daysSinceMaintainer !== null ? `${s.daysSinceMaintainer}d ago` : "never on record"}
+
+ {s.suggestedMessage && (
+
+ Draft message (edit before sending)
+ {s.suggestedMessage}
+
+ )}
+ Suggestions come from the mentorship sheet and may be out of date after a sync.
+
+
+
+
+
+ Pull requests ({s.prs.length})
+ {s.prs.length === 0 ? (
+ No public pull requests on record.
+ ) : (
+
+ )}
+
+
+
+ Appreciation ({s.appreciation.length})
+ {s.appreciation.length === 0 ? (
+ No maintainer appreciation found yet.
+ ) : (
+
+ )}
+
+
+
+ );
+}
diff --git a/components/tracker/tracker-dashboard.tsx b/components/tracker/tracker-dashboard.tsx
index e10e4cd..d5c8ddc 100644
--- a/components/tracker/tracker-dashboard.tsx
+++ b/components/tracker/tracker-dashboard.tsx
@@ -3,12 +3,16 @@
import { useMemo, useState } from "react";
import Link from "next/link";
import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
-import { Search, X, Heart } from "lucide-react";
+import { Search, X, Heart, Lightbulb } from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import { StatusBadge } from "@/components/tracker/status-badge";
import { formatDate } from "@/lib/tracker/format";
-import { filterRows, NO_FILTERS, sortRows, type Filters, type SortKey, type TrackerRow } from "@/lib/tracker/rows";
+import { averageConsistency, filterRows, NO_FILTERS, sortRows, type Filters, type SortKey, type TrackerRow } from "@/lib/tracker/rows";
import type { CohortSummary } from "@/lib/tracker/summary";
+import { INSIGHT_TITLES, groupInsights, type Insight } from "@/lib/tracker/insights";
+import { DIRECTION_LABELS, type Direction } from "@/lib/tracker/metrics";
+import { ArrowDownRight, ArrowRight, ArrowUpRight, CircleHelp } from "lucide-react";
+import { ENGAGEMENT_HINTS, ENGAGEMENT_LABELS, ENGAGEMENT_ORDER, summarizeEngagement, type Engagement } from "@/lib/tracker/engagement";
import { STATUS_LABELS, type Grade, type StatusKey } from "@/lib/tracker/types";
export interface FeedItem {
@@ -25,7 +29,10 @@ interface Props {
rows: TrackerRow[];
summary: CohortSummary;
feed: FeedItem[];
+ insights: Insight[];
snapshotDate: string;
+ /** Where student pages live. */
+ basePath?: string;
}
const PAGE_SIZE = 25;
@@ -42,7 +49,7 @@ interface CardDef {
apply?: Partial;
}
-export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
+export function TrackerDashboard({ rows, summary, feed, insights, snapshotDate, basePath = "/admin/tracker" }: Props) {
const [filters, setFilters] = useState(NO_FILTERS);
const [sortKey, setSortKey] = useState("waiting");
const [dir, setDir] = useState<"asc" | "desc">("desc");
@@ -53,6 +60,7 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
setPage(0);
};
+ const avg = averageConsistency(rows);
const cards: CardDef[] = [
{ label: "Students", value: summary.students, hint: "Everyone in the first-year cohort", apply: NO_FILTERS },
{ label: "Opened a PR", value: summary.withPR, hint: "At least one public pull request" },
@@ -62,6 +70,7 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
{ label: "Total PRs", value: summary.totalPRs, hint: `${summary.mergedPRs} merged · ${summary.openPRs} open · ${summary.closedPRs} closed` },
{ label: "Projects", value: summary.projects, hint: "Distinct repositories worked in" },
{ label: "Appreciation", value: summary.appreciation, hint: "Maintainer comments with praise" },
+ { label: "Avg consistency", value: avg === null ? "—" : `${avg}/100`, hint: "Mean 0-100 score over the last month; hover a student's score on their page for the breakdown" },
{ label: "Need mentor attention", value: summary.needAttention, hint: "Stuck, inactive, changes requested or follow-up", apply: { attentionOnly: true } },
];
@@ -69,7 +78,7 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
const pages = Math.max(1, Math.ceil(visible.length / PAGE_SIZE));
const shown = visible.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
- const dirty = filters.query !== "" || filters.status !== "all" || filters.grade !== "all" || filters.attentionOnly;
+ const dirty = filters.query !== "" || filters.status !== "all" || filters.grade !== "all" || filters.attentionOnly || filters.direction !== "all" || filters.engagement !== "all";
const chart = (Object.keys(STATUS_LABELS) as StatusKey[]).map((k) => ({ key: k, label: STATUS_LABELS[k], count: summary.byStatus[k] }));
const attentionList = rows.filter((r) => r.attention).sort((a, b) => (b.waitingDays ?? 0) - (a.waitingDays ?? 0)).slice(0, 8);
@@ -85,6 +94,8 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
return (
+
set({ ...NO_FILTERS, engagement: e })} />
+
{cards.map((card) => {
const body = (
@@ -142,7 +153,7 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
{attentionList.map((r) => (
- {r.name}
+ {r.name}
{r.waitingDays !== null ? `${r.waitingDays}d waiting` : "no PR waiting"}
@@ -154,6 +165,8 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
+
+
Students
@@ -175,6 +188,13 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
{(Object.keys(STATUS_LABELS) as StatusKey[]).map((k) =>
{STATUS_LABELS[k]} )}
+
+ What they are doing
+ set({ engagement: e.target.value as Filters["engagement"] })} className="bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white">
+ Everyone
+ {ENGAGEMENT_ORDER.map((k) => {ENGAGEMENT_LABELS[k]} )}
+
+
PR grade
set({ grade: e.target.value as Grade | "all" })} className="bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white">
@@ -182,6 +202,13 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
{(["A", "B", "C", "D"] as Grade[]).map((g) => Grade {g} )}
+
+ Progress direction
+ set({ direction: e.target.value as Filters["direction"] })} className="bg-neutral-900 border border-white/10 rounded-lg px-3 py-2 text-sm text-white">
+ Any direction
+ {(Object.keys(DIRECTION_LABELS) as Direction[]).map((d) => {DIRECTION_LABELS[d]} )}
+
+
set({ attentionOnly: e.target.checked })} />
Needs attention
@@ -203,19 +230,20 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
sortBy("name")}>Student
- Status
- sortBy("grade")}>Grade
+ Doing now, and why
+ PR status
+ Last 12 weeks
sortBy("total")}>PRs
sortBy("merged")}>Merged
sortBy("waiting")}>Waiting
- sortBy("activity")}>Last PR
- Praise
+ sortBy("consistency")} title="0-100 over the last month, from public PR activity">Consistency
+ Trend
Details
{shown.length === 0 && (
- No students match these filters.
+ No students match these filters.
)}
{shown.map((r) => (
@@ -228,15 +256,19 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
+
+
+ {r.engagement !== "active" && {r.engagementReason}
}
+
- {r.grade ?? "—"}
+
{r.total}
{r.merged}
{r.waitingDays !== null ? `${r.waitingDays}d` : "—"}
- {formatDate(r.lastStudentActivity)}
- {r.appreciation}
+
+
- View
+ View
))}
@@ -262,7 +294,7 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
{feed.map((f, i) => (
- {f.name}
+ {f.name}
· {f.repo} · {formatDate(f.date)}
“{f.comment}” — {f.reviewer}
@@ -273,3 +305,141 @@ export function TrackerDashboard({ rows, summary, feed, snapshotDate }: Props) {
);
}
+
+
+const INSIGHTS_PER_GROUP = 4;
+
+function InsightsPanel({ insights, basePath }: { insights: Insight[]; basePath: string }) {
+ const groups = groupInsights(insights);
+ return (
+
+ Mentor insights
+ Suggestions from public PR activity. Each says why it appeared; check before acting, since the student may be working somewhere we cannot see.
+ {groups.length === 0 ? (
+ Nothing stands out right now.
+ ) : (
+
+ {groups.map(({ kind, items }) => (
+
+
{INSIGHT_TITLES[kind]} ({items.length})
+
+ {items.slice(0, INSIGHTS_PER_GROUP).map((i) => (
+
+ {i.name}
+ {i.reason}
+ Action: {i.action}
+
+ ))}
+
+ {items.length > INSIGHTS_PER_GROUP &&
and {items.length - INSIGHTS_PER_GROUP} more
}
+
+ ))}
+
+ )}
+
+ );
+}
+
+
+/** Twelve tiny bars, one per week. Drawn as SVG so 142 rows cost nothing; the label carries the numbers for screen readers. */
+function Sparkline({ values, label }: { values: number[]; label: string }) {
+ const max = Math.max(1, ...values);
+ const w = 6;
+ const gap = 2;
+ const h = 24;
+ return (
+
+ {values.map((v, i) => {
+ const bar = v === 0 ? 2 : Math.max(4, Math.round((v / max) * h));
+ return ;
+ })}
+
+ );
+}
+
+/** A number and a small bar, so a column of scores can be compared by eye. */
+function ScoreBar({ score }: { score: number | null }) {
+ if (score === null) return — ;
+ const colour = score >= 70 ? "#4ade80" : score >= 40 ? "#facc15" : "#fb923c";
+ return (
+
+ {score}
+
+
+
+
+ );
+}
+
+const TREND: Record = {
+ improving: { icon: , tone: "text-green-300" },
+ stable: { icon: , tone: "text-sky-300" },
+ declining: { icon: , tone: "text-yellow-300" },
+ insufficient: { icon: , tone: "text-neutral-400" },
+};
+
+function Trend({ direction }: { direction: Direction }) {
+ const { icon, tone } = TREND[direction];
+ return {icon}{DIRECTION_LABELS[direction]} ;
+}
+
+
+const ENGAGEMENT_TONE: Record = {
+ active: { bar: "#4ade80", chip: "bg-green-500/15 text-green-300 border-green-500/30" },
+ break: { bar: "#38bdf8", chip: "bg-sky-500/15 text-sky-300 border-sky-500/30" },
+ "other-work": { bar: "#a78bfa", chip: "bg-violet-500/15 text-violet-300 border-violet-500/30" },
+ quiet: { bar: "#fb923c", chip: "bg-orange-500/15 text-orange-300 border-orange-500/30" },
+ "not-started": { bar: "#737373", chip: "bg-neutral-500/15 text-neutral-300 border-neutral-500/30" },
+};
+
+function EngagementBadge({ kind }: { kind: Engagement }) {
+ return {ENGAGEMENT_LABELS[kind]} ;
+}
+
+/** The one-look answer: how many are active, on a break, doing other work, or quiet, and why. */
+function EngagementPanel({ rows, active, onPick }: { rows: TrackerRow[]; active: Engagement | "all"; onPick: (e: Engagement) => void }) {
+ const { counts, reasons } = useMemo(() => summarizeEngagement(rows), [rows]);
+ const total = Math.max(1, rows.length);
+ return (
+
+
+
Who is doing what
+
GitHub shows only PRs. The reason behind a quiet stretch is whatever a mentor recorded as leave or other work on the student's page. Click a box to filter the table.
+
+ `${ENGAGEMENT_LABELS[k]} ${counts[k]}`).join(", ")}>
+ {ENGAGEMENT_ORDER.map((k) => counts[k] > 0 && )}
+
+
+ {ENGAGEMENT_ORDER.map((k) => (
+
onPick(k)}
+ aria-pressed={active === k}
+ title={ENGAGEMENT_HINTS[k]}
+ className={`text-left rounded-xl border p-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400 ${active === k ? "border-cyan-400/70 bg-white/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.07]"}`}
+ >
+
+
+ {counts[k]}
+
+ {ENGAGEMENT_LABELS[k]}
+ {ENGAGEMENT_HINTS[k]}
+
+ ))}
+
+ {reasons.length > 0 && (
+
+
Why students are not active
+
+ {reasons.map((r) => (
+
+ {r.group} {r.count}
+
+ ))}
+
+
+ )}
+
+ );
+}
diff --git a/components/tracker/tracker-overview.tsx b/components/tracker/tracker-overview.tsx
new file mode 100644
index 0000000..fa47620
--- /dev/null
+++ b/components/tracker/tracker-overview.tsx
@@ -0,0 +1,88 @@
+import Link from "next/link";
+import { ChevronRight } from "lucide-react";
+import { loadStudents } from "@/lib/tracker/store";
+import { loadAllRecords } from "@/lib/tracker/records-store";
+import { byKind } from "@/lib/tracker/records";
+import { toRow } from "@/lib/tracker/rows";
+import { summarize } from "@/lib/tracker/summary";
+import { cohortInsights } from "@/lib/tracker/insights";
+import { ageLabel, formatDate } from "@/lib/tracker/format";
+import { TrackerDashboard, type FeedItem } from "./tracker-dashboard";
+import { SyncButton } from "./sync-button";
+import { SectionTabs } from "./section-tabs";
+
+interface Props {
+ /** Where student pages live, e.g. "/admin/tracker". */
+ basePath: string;
+ rootHref: string;
+ rootLabel: string;
+ /** Show the GitHub refresh button. Off in demo mode, where nothing is synced. */
+ sync: boolean;
+}
+
+/** Everything the tracker home shows once access has been checked. Auth is the caller's job. */
+export async function TrackerOverview({ basePath, rootHref, rootLabel, sync }: Props) {
+ const [students, allRecords] = await Promise.all([loadStudents(), loadAllRecords()]);
+ const now = new Date();
+
+ if (students.length === 0) {
+ return (
+
+ Open Source Student Tracker
+
+ No first-year data has been imported yet. Run npm run import:tracker -- <export.txt> --commit to load the mentorship workbook.
+
+
+ );
+ }
+
+ const summary = summarize(students);
+ const snapshotDate = students.reduce((latest, s) => (s.snapshotDate > latest ? s.snapshotDate : latest), "");
+ const synced = students.filter((s) => s.syncedAt).map((s) => s.syncedAt as string).sort();
+ const failing = students.filter((s) => s.syncError).length;
+
+ const feed: FeedItem[] = students
+ .flatMap((s) => s.appreciation.map((a) => ({ github: s.github, name: s.name, reviewer: a.reviewer, comment: a.comment.slice(0, 220), date: a.date, repo: a.repo, url: a.url })))
+ .concat(students.flatMap((st) => byKind(allRecords.get(st.github) ?? [], "appreciation").map((a) => ({ github: st.github, name: st.name, reviewer: a.authorName, comment: `${a.title}: ${a.reason}`.slice(0, 220), date: a.date, repo: "Mentor appreciation", url: a.sourceUrl || `${basePath}/${st.github}` }))))
+ .sort((a, b) => (b.date ?? "").localeCompare(a.date ?? ""))
+ .slice(0, 8);
+
+ return (
+
+
+
+ {rootLabel}
+
+ Student tracker
+
+
+
+ Open Source Student Tracker
+
+ First-year progress in open source. Numbers describe public GitHub activity only, so a quiet student may be working privately.
+
+
+ Imported snapshot {formatDate(snapshotDate)} · {synced.length}/{students.length} students refreshed from GitHub
+ {synced.length > 0 && ` · latest ${ageLabel(synced[synced.length - 1], now)}`}
+ {failing > 0 && ` · ${failing} failed their last sync`}
+
+ {sync && }
+
+
+
+
+
toRow(st, allRecords.get(st.github) ?? []))} summary={summary} feed={feed} insights={cohortInsights(students, allRecords)} snapshotDate={snapshotDate} basePath={basePath} />
+
+
+ );
+}
diff --git a/docs/first-year-tracker.md b/docs/first-year-tracker.md
index 9584938..b3d1ca9 100644
--- a/docs/first-year-tracker.md
+++ b/docs/first-year-tracker.md
@@ -26,6 +26,32 @@ GitHub is called by the sync (`lib/tracker/sync.ts`), from two places:
Each run refreshes up to 20 students whose cache is older than 3 hours (one search each, oldest first) and stops at the first rate-limit response. A failed fetch keeps the old numbers and records `syncError`; it never turns into zeros. A sync updates PR counts, the PR list and last-activity dates. Status, priority, blocker, recommendation and appreciation come from the sheet and are not re-judged.
+## Progress over time, consistency and insights
+
+All of it is derived from the cached PR list and appreciation comments by `lib/tracker/metrics.ts` (one source of truth, unit tested). Nothing extra is stored.
+
+- **Period selector** on a student's page: last 1, 2 or 3 weeks, 1 or 2 months, or a custom range. Ranges end on the student's *data date* (the later of the sheet snapshot and the last GitHub sync), not today, so stale data never reads as "stopped working".
+- **Progress direction** compares activity points (PR opened 1, merged 2, appreciation 1) with the previous equally long period. A change of 20% or more is improving/declining; under two weeks of history is "not enough data".
+- **Consistency score** (0-100): weekly regularity 60, recency 25, recent streak 15, with the breakdown shown. Only the student's own actions count (PRs opened and merged). The function already accepts excused days (leave, research) and drops fully excused weeks from the maths; the UI for recording them arrives with mentor notes.
+- **Mentor insights** (`lib/tracker/insights.ts`): PRs waiting 5+ days, changes requested, 30+ days quiet, declining activity, recent credible merges, strong progress. Every item states why and what to do, and is worded as a possibility.
+- Dashboard columns and filters for direction and consistency, plus an average-consistency card.
+
+## Mentor records
+
+Tasks and current work, notes (14 types, mentors-only or student-visible), appreciation with badges, weekly reviews and leave/context entries live in Firestore collection `devforge_tracker_records`, separate from the synced PR cache so a sync never overwrites them. `GET/POST/PUT/DELETE /api/admin/tracker/records` (needs `tracker:view`, 60 writes a minute). Input is validated with zod (real dates, http(s)-only links, Monday week starts, 1-5 confidence); duplicates are refused with 409; mentors can edit only their own records, admins any. Records are queried by `github` alone and sorted in code, so no composite index is needed on the shared Firestore project. Approved leave and similar entries drop whole weeks out of the consistency score. Tasks marked done count as activity; a task is only "missed" after its due date has passed.
+
+## Trying it without real data
+
+```bash
+TRACKER_DEMO=1 npm run dev # then open http://localhost:3000/dev/tracker
+```
+
+Serves ten made-up students and a few records from memory (nothing touches Firestore, edits reset on restart). It needs no sign-in, which is why it only exists when `NODE_ENV` is not `production` AND `TRACKER_DEMO=1`; the `/dev/tracker` pages and `/api/dev/tracker/records` return 404 otherwise. The real `/admin/tracker` pages and API are unchanged and always require sign-in.
+
+## Not built yet
+
+Student and viewer role views (students cannot yet see their own page or the notes marked visible to them), the GitHub/GitLab/Bitbucket abstraction, and issue, commit and review sync. Issues, commits and reviews given are not in the data, so they are left out rather than shown as zero.
+
## Known limits
The workbook has PR data only. Commits, reviews given, weekly reviews, mentor notes, tasks and a per-student consistency score are not in it, so the tracker does not show them. Credible-repo checks on synced PRs use stars and forks only (the workbook also checks open issues and archived status).
diff --git a/lib/firebase/collections.ts b/lib/firebase/collections.ts
index 8c1aaa4..0b36d8a 100644
--- a/lib/firebase/collections.ts
+++ b/lib/firebase/collections.ts
@@ -29,6 +29,7 @@ export const COLLECTIONS = {
collabRequests: "devforge_collab_requests",
prJourney: "devforge_pr_journey",
firstYearTracker: "devforge_first_year_tracker",
+ trackerRecords: "devforge_tracker_records",
} as const;
export type ClubCollection = (typeof COLLECTIONS)[keyof typeof COLLECTIONS];
diff --git a/lib/tracker/demo.ts b/lib/tracker/demo.ts
new file mode 100644
index 0000000..1b8f2a1
--- /dev/null
+++ b/lib/tracker/demo.ts
@@ -0,0 +1,105 @@
+import type { TrackerRecord } from "./records";
+import type { TrackerPR, TrackerStudent } from "./types";
+
+/**
+ * Realistic made-up students for trying the tracker locally without touching
+ * the shared Firestore project. Only reachable when NODE_ENV is not
+ * "production" AND TRACKER_DEMO=1, so it can never show in production.
+ */
+export const demoEnabled = (): boolean => process.env.NODE_ENV !== "production" && process.env.TRACKER_DEMO === "1";
+
+const DATA_DATE = "2026-11-13";
+
+function pr(repo: string, n: number, title: string, state: TrackerPR["state"], created: string, closed: string | null, extra: Partial = {}): TrackerPR {
+ return { repo, number: n, title, state, createdAt: created, closedAt: closed, lastUpdate: closed ?? created, waitingDays: null, blocker: null, credible: false, teaching: false, approved: false, url: `https://github.com/${repo}/pull/${n}`, ...extra };
+}
+
+function mk(github: string, name: string, status: TrackerStudent["status"], prs: TrackerPR[], extra: Partial = {}): TrackerStudent {
+ const merged = prs.filter((p) => p.state === "merged").length;
+ const open = prs.filter((p) => p.state === "open").length;
+ const closed = prs.filter((p) => p.state === "closed").length;
+ const lastOpened = prs.map((p) => p.createdAt ?? "").sort().pop() || null;
+ return {
+ github, name, snapshotDate: DATA_DATE, status, statusLabel: status, priority: status === "stuck" || status === "inactive" ? "Critical" : "Medium",
+ grade: merged >= 4 ? "A" : merged >= 2 ? "B" : prs.length ? "C" : "D", gsocReadiness: merged >= 3 ? "On track" : "Needs external signal", gsocRank: null, gsocScore: null, gsocNote: null,
+ totals: { total: prs.length, open, merged, closed, credibleMerges: prs.filter((p) => p.state === "merged" && p.credible).length, credibleOpen: prs.filter((p) => p.state === "open" && p.credible).length, mergeSuccessPct: merged + closed ? Math.round((merged / (merged + closed)) * 100) : null, titleHygienePct: 60, approvals: 0, reviewFeedbackHandled: 0, projects: new Set(prs.map((p) => p.repo)).size },
+ repos: [...new Set(prs.map((p) => p.repo))], lastStudentActivity: lastOpened,
+ daysSinceActivity: lastOpened ? Math.round((Date.parse(`${DATA_DATE}T00:00:00Z`) - Date.parse(`${lastOpened}T00:00:00Z`)) / 86_400_000) : null,
+ daysSinceMaintainer: null, waitingDays: null, blocker: null, recommendation: null, suggestedMessage: null,
+ progress: { prevTotal: Math.max(0, prs.length - 2), prevMerged: Math.max(0, merged - 1), prevGrade: null, gradeChange: "", summary: "" },
+ prs, appreciation: [], syncedAt: null, syncError: null, ...extra,
+ };
+}
+
+const C = { credible: true };
+export function demoStudents(): TrackerStudent[] {
+ return [
+ mk("asha-rao", "Asha Rao", "merged", [
+ pr("django/django", 22001, "Fixed #35100 -- Clarified QuerySet docs", "merged", "2026-09-08", "2026-09-12", C),
+ pr("pandas-dev/pandas", 71001, "DOC: fix typo in read_csv", "merged", "2026-09-22", "2026-09-25", C),
+ pr("zulip/zulip", 40001, "docs: update setup guide", "merged", "2026-10-06", "2026-10-09", C),
+ pr("checkstyle/checkstyle", 22450, "Issue #22400: add test", "merged", "2026-10-20", "2026-10-27", C),
+ pr("zulip/zulip", 40500, "docs: fix broken link", "merged", "2026-11-04", "2026-11-11", C),
+ pr("django/django", 22250, "Fixed #37000 -- Tidied admin docs", "open", "2026-11-10", null, { ...C, waitingDays: 3 }),
+ ], { appreciation: [{ repo: "zulip/zulip", prNumber: 40500, prTitle: "docs: fix broken link", reviewer: "timabbott", reviewerRole: "MEMBER", date: "2026-11-11", type: "Personal praise", comment: "Thanks, this is a clear improvement.", url: "https://github.com/zulip/zulip/pull/40500" }] }),
+ mk("rohan-mehta", "Rohan Mehta", "merged", [
+ pr("sugarlabs/musicblocks", 9100, "fix: palette search cursor", "merged", "2026-09-30", "2026-10-04", C),
+ pr("sugarlabs/musicblocks", 9400, "test: cover search messages", "merged", "2026-10-18", "2026-10-22", C),
+ pr("sugarlabs/musicblocks", 10100, "fix: guard invalid EDO values", "merged", "2026-11-03", "2026-11-09", C),
+ pr("sugarlabs/musicblocks", 10300, "fix: restore trashed blocks", "open", "2026-11-10", null, C),
+ ], { appreciation: [{ repo: "sugarlabs/musicblocks", prNumber: 10100, prTitle: "fix: guard invalid EDO values", reviewer: "zealot-zew", reviewerRole: "COLLABORATOR", date: "2026-11-09", type: "Review comment", comment: "Looks good, thanks for the thorough tests.", url: "https://github.com/sugarlabs/musicblocks/pull/10100" }] }),
+ mk("meera-iyer", "Meera Iyer", "stuck", [
+ pr("apache/airflow", 74100, "Databricks: detect table version changes", "open", "2026-09-28", null, { ...C, waitingDays: 46, blocker: "no maintainer response since opening (46d)" }),
+ pr("apache/airflow", 74300, "docs: operator example", "open", "2026-10-06", null, { ...C, waitingDays: 38 }),
+ ], { waitingDays: 46, blocker: "no maintainer response since opening (46d)", recommendation: "Post a polite nudge, or route to another maintainer." }),
+ mk("karan-singh", "Karan Singh", "changes-requested", [
+ pr("axios/axios", 11284, "docs: clarify npm test requirements", "merged", "2026-10-03", "2026-10-05", C),
+ pr("axios/axios", 11287, "fix: serialize customProps in toJSON", "open", "2026-10-03", null, { ...C, waitingDays: 23, blocker: "changes requested 23d ago, not addressed" }),
+ ], { waitingDays: 23, blocker: "changes requested 23d ago, not addressed" }),
+ mk("divya-nair", "Divya Nair", "inactive", [
+ pr("ssagar1999/our-dev-wall", 118, "firstcommit", "open", "2026-08-21", null, { teaching: true, waitingDays: 84 }),
+ ], { waitingDays: 84, blocker: "no maintainer response since opening (84d)", daysSinceActivity: 84 }),
+ mk("farhan-ali", "Farhan Ali", "waiting-on-maintainer", [
+ pr("metabrainz/listenbrainz-server", 3970, "BrainzPlayer: add aria-labels", "merged", "2026-11-02", "2026-11-02", C),
+ pr("metabrainz/listenbrainz-server", 3979, "LB-2023: setting to hide flair animations", "open", "2026-11-09", null, { ...C, waitingDays: 4 }),
+ pr("metabrainz/listenbrainz-server", 3986, "LB-2002: dedupe merged recordings", "open", "2026-11-12", null, { ...C, waitingDays: 1 }),
+ ]),
+ mk("sneha-kulkarni", "Sneha Kulkarni", "follow-up", [
+ pr("ant-design/ant-design", 59451, "docs: tip on running tests", "merged", "2026-10-01", "2026-10-02", C),
+ pr("openmrs/openmrs-core", 6667, "TRUNK-6727: exclude retired locations", "open", "2026-10-08", null, { ...C, waitingDays: 36 }),
+ ], { waitingDays: 36 }),
+ mk("vikram-patel", "Vikram Patel", "no-pr-data", []),
+ mk("ananya-das", "Ananya Das", "closed-without-merge", [
+ pr("stdlib-js/stdlib", 15417, "chore: fix lint errors", "closed", "2026-09-22", "2026-09-25", C),
+ ]),
+ mk("tanvi-shah", "Tanvi Shah", "merged", [
+ pr("ssagar1999/our-dev-wall", 38, "Add profile", "merged", "2026-08-20", "2026-08-21", { teaching: true }),
+ pr("NST-DEVFORGE/workbook", 25, "Sign the workbook", "merged", "2026-09-21", "2026-09-22", { teaching: true }),
+ ]),
+ ];
+}
+
+export function demoRecords(): TrackerRecord[] {
+ const base = { authorUsn: "demo", authorName: "Demo Mentor", createdAt: "2026-11-10T09:00:00.000Z", updatedAt: "2026-11-10T09:00:00.000Z" };
+ return [
+ { ...base, id: "d1", github: "asha-rao", kind: "task", title: "Fix #37000: admin docs typo sweep", repo: "django/django", issueNumber: 37000, issueUrl: "https://github.com/django/django/issues/37000", description: "Read the admin docs and fix wording issues.", difficulty: "easy", status: "in-review", assignedAt: "2026-11-05", dueDate: "2026-11-14", blockers: "", nextAction: "Respond to review comments", dedupeKey: "d1" },
+ { ...base, id: "d2", github: "asha-rao", kind: "task", title: "Zulip setup guide cleanup", repo: "zulip/zulip", issueNumber: 40001, issueUrl: "", description: "", difficulty: "medium", status: "done", assignedAt: "2026-11-01", dueDate: "2026-11-10", blockers: "", nextAction: "", completedAt: "2026-11-11T08:00:00.000Z", dedupeKey: "d2" },
+ { ...base, id: "d3", github: "asha-rao", kind: "note", noteType: "overcame-challenge", text: "Struggled with the Django contribution workflow at first; paired with a mentor and now submits clean PRs.", visibility: "mentors", relatedTask: "", dedupeKey: "d3" },
+ { ...base, id: "d4", github: "asha-rao", kind: "appreciation", title: "Consistent, kind reviews", reason: "Helped two juniors fix their first PRs.", badge: "helpful-reviewer", sourceUrl: "", date: "2026-11-08", dedupeKey: "d4" },
+ { ...base, id: "d5", github: "asha-rao", kind: "review", weekStart: "2026-11-09", completed: "Merged the zulip docs fix.", inProgress: "Admin docs sweep.", learned: "How Django tickets map to PRs.", difficult: "Writing a good ticket reference.", helpNeeded: "", nextWeek: "Pick a small bug in pandas.", blockers: "", confidence: 4, hours: 8, mentorFeedback: "", dedupeKey: "d5" },
+ { ...base, id: "d6", github: "meera-iyer", kind: "task", title: "Databricks table version detection", repo: "apache/airflow", issueNumber: 74195, issueUrl: "", description: "", difficulty: "hard", status: "blocked", assignedAt: "2026-09-28", dueDate: "2026-10-30", blockers: "No maintainer has reviewed it in 6 weeks.", nextAction: "Ask in the airflow Slack for a reviewer", dedupeKey: "d6" },
+ { ...base, id: "d7", github: "meera-iyer", kind: "context", contextType: "approved-leave", startDate: "2026-10-12", endDate: "2026-10-25", text: "Exams.", dedupeKey: "d7" },
+ { ...base, id: "d8", github: "rohan-mehta", kind: "appreciation", title: "Mentor’s choice: tests first", reason: "Writes a failing test before every fix.", badge: "mentors-choice", sourceUrl: "", date: "2026-11-09", dedupeKey: "d8" },
+ ] as TrackerRecord[];
+}
+
+type Store = { students: Map; records: Map };
+const g = globalThis as unknown as { __trackerDemo?: Store };
+
+/** Kept on globalThis so dev hot-reloads do not reset what you just typed in. */
+export function demoStore(): Store {
+ if (!g.__trackerDemo) {
+ g.__trackerDemo = { students: new Map(demoStudents().map((s) => [s.github, s])), records: new Map(demoRecords().map((r) => [r.id, r])) };
+ }
+ return g.__trackerDemo;
+}
diff --git a/lib/tracker/engagement.test.ts b/lib/tracker/engagement.test.ts
new file mode 100644
index 0000000..6d8813e
--- /dev/null
+++ b/lib/tracker/engagement.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { engagementFor, summarizeEngagement } from "./engagement";
+import { record, student } from "./test-fixtures";
+
+const quiet = (over = {}) => student({ daysSinceActivity: 60, totals: { ...student().totals, total: 3 }, ...over });
+
+describe("engagementFor", () => {
+ it("calls a student with a recent PR active, even with leave on file", () => {
+ const r = [record("context", { startDate: "2026-11-01", endDate: "2026-11-30" })];
+ expect(engagementFor(student({ daysSinceActivity: 5 }), r).kind).toBe("active");
+ expect(engagementFor(student({ daysSinceActivity: 30 }), []).kind).toBe("active");
+ });
+
+ it("treats leave covering the data date as a break, with the mentor's reason", () => {
+ const r = [record("context", { contextType: "personal-circumstances", startDate: "2026-11-01", endDate: "2026-11-30", text: "Exams" })];
+ const e = engagementFor(quiet(), r);
+ expect(e.kind).toBe("break");
+ expect(e.reason).toContain("Exams");
+ });
+
+ it("treats research and outside projects as other work", () => {
+ const r = [record("context", { contextType: "external-project", startDate: "2026-11-10", endDate: "2026-12-10" })];
+ expect(engagementFor(quiet(), r).kind).toBe("other-work");
+ });
+
+ it("ignores context that has ended or has not started", () => {
+ const ended = [record("context", { startDate: "2026-10-01", endDate: "2026-10-20" })];
+ const future = [record("context", { startDate: "2026-11-20", endDate: "2026-11-25" })];
+ expect(engagementFor(quiet(), ended).kind).toBe("quiet");
+ expect(engagementFor(quiet(), future).kind).toBe("quiet");
+ });
+
+ it("separates never-started from quiet, and says no reason is recorded", () => {
+ expect(engagementFor(student({ daysSinceActivity: null }), []).kind).toBe("not-started");
+ const q = engagementFor(quiet({ blocker: "Setup problem" }), []);
+ expect(q.kind).toBe("quiet");
+ expect(q.reason).toContain("no reason is recorded");
+ expect(q.reason).toContain("Setup problem");
+ });
+});
+
+describe("summarizeEngagement", () => {
+ it("counts every kind and groups reasons for the inactive", () => {
+ const s = summarizeEngagement([
+ { engagement: "active", engagementGroup: "x" }, { engagement: "quiet", engagementGroup: "No reason recorded" },
+ { engagement: "quiet", engagementGroup: "No reason recorded" }, { engagement: "break", engagementGroup: "Approved leave" },
+ ]);
+ expect(s.counts).toEqual({ active: 1, break: 1, "other-work": 0, quiet: 2, "not-started": 0 });
+ expect(s.reasons[0]).toEqual({ kind: "quiet", group: "No reason recorded", count: 2 });
+ expect(s.reasons).toHaveLength(2);
+ });
+});
diff --git a/lib/tracker/engagement.ts b/lib/tracker/engagement.ts
new file mode 100644
index 0000000..cd5f39a
--- /dev/null
+++ b/lib/tracker/engagement.ts
@@ -0,0 +1,97 @@
+import { byKind, CONTEXT_LABELS, type ContextType, type TrackerRecord } from "./records";
+import { asOfDate } from "./metrics";
+import type { TrackerStudent } from "./types";
+
+/**
+ * One answer per student to "what are they doing right now, and why?".
+ *
+ * GitHub can only tell us that someone is or is not opening PRs. The *why* for
+ * a quiet student has to come from a mentor, recorded as a "context" entry
+ * (leave, research, an outside project). Without one the honest answer is
+ * "no reason recorded", not a guess.
+ */
+export type Engagement = "active" | "break" | "other-work" | "quiet" | "not-started";
+
+export const ENGAGEMENT_ORDER: Engagement[] = ["active", "break", "other-work", "quiet", "not-started"];
+
+export const ENGAGEMENT_LABELS: Record = {
+ active: "Active",
+ break: "On a break",
+ "other-work": "Doing other work",
+ quiet: "Quiet, no reason recorded",
+ "not-started": "Not started",
+};
+
+export const ENGAGEMENT_HINTS: Record = {
+ active: "Opened or updated a PR in the last 30 days",
+ break: "Mentor recorded approved leave or personal circumstances",
+ "other-work": "Mentor recorded research, an outside project or non-code work",
+ quiet: "No PR in 30+ days and nobody has recorded why. Ask them",
+ "not-started": "No public pull request yet",
+};
+
+/** A student with a PR this recently counts as active. */
+export const ACTIVE_WITHIN_DAYS = 30;
+
+export interface EngagementInfo {
+ kind: Engagement;
+ /** Short group used to count reasons across the cohort, e.g. "Approved leave". */
+ group: string;
+ /** One sentence for a person: what and why. */
+ reason: string;
+}
+
+const BREAK_TYPES: ContextType[] = ["approved-leave", "personal-circumstances"];
+
+export function engagementFor(s: TrackerStudent, records: TrackerRecord[] = [], asOf: string = asOfDate(s)): EngagementInfo {
+ if (s.daysSinceActivity !== null && s.daysSinceActivity <= ACTIVE_WITHIN_DAYS) {
+ return {
+ kind: "active",
+ group: "Opened a PR in the last 30 days",
+ reason: s.daysSinceActivity === 0 ? "Opened a PR today." : `Last PR ${s.daysSinceActivity} day${s.daysSinceActivity === 1 ? "" : "s"} ago.`,
+ };
+ }
+
+ // Newest entry that covers the data date wins.
+ const current = byKind(records, "context")
+ .filter((c) => c.startDate <= asOf && c.endDate >= asOf)
+ .sort((a, b) => b.startDate.localeCompare(a.startDate))[0];
+ if (current) {
+ const label = CONTEXT_LABELS[current.contextType];
+ const why = current.text ? `: ${current.text}` : "";
+ return {
+ kind: BREAK_TYPES.includes(current.contextType) ? "break" : "other-work",
+ group: label,
+ reason: `${label}${why} (until ${current.endDate}).`,
+ };
+ }
+
+ if (s.totals.total === 0) {
+ return { kind: "not-started", group: "No public PR yet", reason: "No public pull request on record." };
+ }
+
+ const gap = s.daysSinceActivity === null ? "No recent PR" : `No PR for ${s.daysSinceActivity} days`;
+ const hint = s.blocker ? ` Sheet notes a blocker: ${s.blocker}.` : "";
+ return { kind: "quiet", group: "No reason recorded", reason: `${gap}, and no reason is recorded.${hint}` };
+}
+
+export interface EngagementSummary {
+ counts: Record;
+ /** Reason groups with counts, largest first, for every kind except active. */
+ reasons: { kind: Engagement; group: string; count: number }[];
+}
+
+export function summarizeEngagement(rows: { engagement: Engagement; engagementGroup: string }[]): EngagementSummary {
+ const counts: Record = { active: 0, break: 0, "other-work": 0, quiet: 0, "not-started": 0 };
+ const byGroup = new Map();
+ for (const r of rows) {
+ counts[r.engagement]++;
+ if (r.engagement === "active") continue;
+ const key = `${r.engagement}|${r.engagementGroup}`;
+ const g = byGroup.get(key) ?? { kind: r.engagement, group: r.engagementGroup, count: 0 };
+ g.count++;
+ byGroup.set(key, g);
+ }
+ const reasons = [...byGroup.values()].sort((a, b) => b.count - a.count || a.group.localeCompare(b.group));
+ return { counts, reasons };
+}
diff --git a/lib/tracker/insights.test.ts b/lib/tracker/insights.test.ts
new file mode 100644
index 0000000..cf1190d
--- /dev/null
+++ b/lib/tracker/insights.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+import { cohortInsights, groupInsights, insightsFor } from "./insights";
+import { pr, student } from "./test-fixtures";
+
+const withPRs = (over: Parameters[0] = {}) =>
+ student({ totals: { ...student().totals, total: 1, open: 1 }, prs: [pr({ url: "x" })], ...over });
+const kinds = (s: ReturnType) => insightsFor(s).map((i) => i.kind);
+
+describe("insightsFor", () => {
+ it("flags a student with no PR at all and stops there", () => {
+ const found = insightsFor(student({ name: "Asha Rao" }));
+ expect(found).toHaveLength(1);
+ expect(found[0].kind).toBe("no-activity");
+ expect(found[0].reason).toMatch(/may need attention/);
+ expect(found[0].action).toContain("Asha");
+ });
+
+ it("flags a PR waiting past the threshold, naming the days, but not before it", () => {
+ const waiting = insightsFor(withPRs({ waitingDays: 6 })).find((i) => i.kind === "waiting-on-review");
+ expect(waiting?.reason).toContain("6 days");
+ expect(kinds(withPRs({ waitingDays: 4 }))).not.toContain("waiting-on-review");
+ });
+
+ it("says changes-requested instead of waiting-on-review when the ball is with the student", () => {
+ const k = kinds(withPRs({ status: "changes-requested", waitingDays: 12 }));
+ expect(k).toContain("changes-unaddressed");
+ expect(k).not.toContain("waiting-on-review");
+ });
+
+ it("flags long inactivity with a hedged reason", () => {
+ const found = insightsFor(withPRs({ daysSinceActivity: 45 })).find((i) => i.kind === "inactive");
+ expect(found?.reason).toContain("45 days");
+ expect(found?.reason).toMatch(/might be on a break/);
+ });
+
+ it("celebrates a recent credible merge", () => {
+ const s = student({
+ totals: { ...student().totals, total: 1, merged: 1 },
+ prs: [pr({ url: "m", state: "merged", credible: true, createdAt: "2026-11-05", closedAt: "2026-11-10" })],
+ });
+ const found = insightsFor(s).find((i) => i.kind === "deserves-appreciation");
+ expect(found?.tone).toBe("positive");
+ });
+
+ it("does not celebrate an old merge or a non-credible one", () => {
+ const old = student({ totals: { ...student().totals, total: 1, merged: 1 }, prs: [pr({ url: "m", state: "merged", credible: true, createdAt: "2026-08-01", closedAt: "2026-08-03" })] });
+ const small = student({ totals: { ...student().totals, total: 1, merged: 1 }, prs: [pr({ url: "m", state: "merged", credible: false, createdAt: "2026-11-05", closedAt: "2026-11-10" })] });
+ expect(kinds(old)).not.toContain("deserves-appreciation");
+ expect(kinds(small)).not.toContain("deserves-appreciation");
+ });
+
+ it("gives every insight a reason and an action", () => {
+ for (const i of insightsFor(withPRs({ waitingDays: 30, daysSinceActivity: 60 }))) {
+ expect(i.reason.length).toBeGreaterThan(10);
+ expect(i.action.length).toBeGreaterThan(10);
+ }
+ });
+});
+
+describe("cohortInsights / groupInsights", () => {
+ it("puts attention before positives and the longest waits first", () => {
+ const a = withPRs({ github: "a", waitingDays: 10 });
+ const b = withPRs({ github: "b", waitingDays: 40 });
+ const win = student({ github: "w", totals: { ...student().totals, total: 1, merged: 1 }, prs: [pr({ url: "w", state: "merged", credible: true, createdAt: "2026-11-05", closedAt: "2026-11-10" })] });
+ const all = cohortInsights([a, win, b]);
+ expect(all.map((i) => i.github)).toEqual(["b", "a", "w"]);
+ expect(all[2].tone).toBe("positive");
+ });
+
+ it("groups by kind", () => {
+ const groups = groupInsights(cohortInsights([withPRs({ github: "a", waitingDays: 10 }), withPRs({ github: "b", waitingDays: 20 })]));
+ expect(groups).toHaveLength(1);
+ expect(groups[0].items).toHaveLength(2);
+ });
+
+ it("is empty for an empty cohort", () => {
+ expect(cohortInsights([])).toEqual([]);
+ });
+});
diff --git a/lib/tracker/insights.ts b/lib/tracker/insights.ts
new file mode 100644
index 0000000..7fa8451
--- /dev/null
+++ b/lib/tracker/insights.ts
@@ -0,0 +1,128 @@
+import { asOfDate, buildEvents, daysBetween, progressDirection, resolveRange, type DirectionResult } from "./metrics";
+import { byKind, currentWork, recordEvents, type TrackerRecord } from "./records";
+import type { TrackerStudent } from "./types";
+
+/**
+ * Mentor insights: who may need a reply, a nudge or a thank-you. Each one says
+ * why it fired and what to do, in hedged words, because the data is public PR
+ * activity and a quiet student may simply be working somewhere we cannot see.
+ */
+export type InsightKind =
+ | "waiting-on-review"
+ | "changes-unaddressed"
+ | "inactive"
+ | "declining"
+ | "strong-progress"
+ | "deserves-appreciation"
+ | "no-activity"
+ | "blocked-task"
+ | "help-requested";
+
+export interface Insight {
+ kind: InsightKind;
+ github: string;
+ name: string;
+ /** Why this fired, naming the numbers. */
+ reason: string;
+ /** What a mentor could do about it. */
+ action: string;
+ /** "attention" needs a human soon; "positive" is worth a thank-you. */
+ tone: "attention" | "positive";
+ /** Higher sorts first within a tone. */
+ weight: number;
+}
+
+export const INSIGHT_TITLES: Record = {
+ "waiting-on-review": "Pull requests waiting for review",
+ "changes-unaddressed": "Changes requested, not addressed",
+ inactive: "Quiet for a long time",
+ declining: "Activity dropping",
+ "strong-progress": "Making strong progress",
+ "deserves-appreciation": "Deserve appreciation",
+ "no-activity": "No public pull request yet",
+ "blocked-task": "Blocked tasks",
+ "help-requested": "Asked for help",
+};
+
+export const WAITING_REVIEW_DAYS = 5;
+export const INACTIVE_DAYS = 30;
+const RECENT_WIN_DAYS = 14;
+
+export function insightsFor(s: TrackerStudent, records: TrackerRecord[] = []): Insight[] {
+ const out: Insight[] = [];
+ const base = { github: s.github, name: s.name };
+ const asOf = asOfDate(s);
+ const range = resolveRange("1m", asOf);
+ const dir: DirectionResult | null = range ? progressDirection(buildEvents(s, recordEvents(records)), range) : null;
+ const first = s.name.split(" ")[0] || s.name;
+
+ const work = currentWork(records, asOf);
+ const blocked = byKind(records, "task").filter((t) => t.status === "blocked");
+ if (blocked.length > 0) {
+ const oldest = blocked.reduce((a, b) => (a.assignedAt <= b.assignedAt ? a : b));
+ out.push({ ...base, kind: "blocked-task", tone: "attention", weight: 3.5,
+ reason: `This may need attention because "${oldest.title}" is marked blocked${oldest.blockers ? ` (${oldest.blockers})` : ""}${work.overdue ? ` and ${work.overdue} task${work.overdue === 1 ? " is" : "s are"} overdue` : ""}.`,
+ action: "Ask what is in the way and whether another mentor or maintainer can unblock it." });
+ }
+ const latestReview = byKind(records, "review")[0];
+ if (latestReview?.helpNeeded) {
+ out.push({ ...base, kind: "help-requested", tone: "attention", weight: 3,
+ reason: `In the weekly review for ${latestReview.weekStart}, ${first} asked for help: "${latestReview.helpNeeded.slice(0, 120)}".`,
+ action: "Reply to the request, or pair them with someone who has done this before." });
+ }
+
+ if (s.totals.total === 0) {
+ out.push({ ...base, kind: "no-activity", tone: "attention", weight: 1,
+ reason: "This may need attention because no public pull request is on record. They could be working privately or not have started.",
+ action: `Ask ${first} which issue they picked up, or assign one small starter issue.` });
+ return out;
+ }
+
+ if (s.status === "changes-requested") {
+ out.push({ ...base, kind: "changes-unaddressed", tone: "attention", weight: 3 + (s.waitingDays ?? 0) / 100,
+ reason: `A maintainer asked ${first} for changes${s.waitingDays !== null ? ` and the PR has been waiting ${s.waitingDays} days` : ""}. The ball may be with the student.`,
+ action: "Sit with them, walk through the requested changes and agree a short deadline." });
+ } else if (s.totals.open > 0 && s.waitingDays !== null && s.waitingDays >= WAITING_REVIEW_DAYS && s.status !== "inactive") {
+ out.push({ ...base, kind: "waiting-on-review", tone: "attention", weight: 2 + s.waitingDays / 100,
+ reason: `${first} has had a pull request waiting ${s.waitingDays} days${s.daysSinceMaintainer === null ? " with no maintainer reply on record" : ""}.`,
+ action: "Post a polite nudge, or consider routing it to another maintainer." });
+ }
+
+ if (s.daysSinceActivity !== null && s.daysSinceActivity >= INACTIVE_DAYS) {
+ out.push({ ...base, kind: "inactive", tone: "attention", weight: 2.5 + Math.min(s.daysSinceActivity, 200) / 1000,
+ reason: `This may need attention because the last PR was opened ${s.daysSinceActivity} days before the data date. They might be on a break.`,
+ action: `Check in directly: find out whether ${first} wants to continue, and reassign if not.` });
+ } else if (dir?.direction === "declining") {
+ out.push({ ...base, kind: "declining", tone: "attention", weight: 1.5,
+ reason: `${dir.explanation}`,
+ action: "A quick conversation will tell you whether this is a break, a hard task or a blocker." });
+ }
+
+ const recentCredible = s.prs.filter(
+ (p) => p.state === "merged" && p.credible && p.closedAt && daysBetween(p.closedAt.slice(0, 10), asOf) <= RECENT_WIN_DAYS && daysBetween(p.closedAt.slice(0, 10), asOf) >= 0,
+ );
+ if (recentCredible.length > 0) {
+ out.push({ ...base, kind: "deserves-appreciation", tone: "positive", weight: 2 + recentCredible.length,
+ reason: `${first} merged ${recentCredible.length} PR${recentCredible.length === 1 ? "" : "s"} into credible repositories in the last ${RECENT_WIN_DAYS} days.`,
+ action: "Say thank you in the group and line up the next, slightly larger issue." });
+ }
+ if (dir?.direction === "improving" && dir.current >= 3) {
+ out.push({ ...base, kind: "strong-progress", tone: "positive", weight: 1 + dir.current / 100,
+ reason: dir.explanation,
+ action: "Worth recognising, and a good moment to suggest a stretch goal." });
+ }
+ return out;
+}
+
+/** All insights across the cohort, attention first, then by weight. */
+export function cohortInsights(students: TrackerStudent[], records: Map = new Map()): Insight[] {
+ return students
+ .flatMap((s) => insightsFor(s, records.get(s.github) ?? []))
+ .sort((a, b) => (a.tone === b.tone ? b.weight - a.weight : a.tone === "attention" ? -1 : 1));
+}
+
+export function groupInsights(all: Insight[]): { kind: InsightKind; items: Insight[] }[] {
+ const groups = new Map();
+ for (const i of all) groups.set(i.kind, [...(groups.get(i.kind) ?? []), i]);
+ return [...groups].map(([kind, items]) => ({ kind, items }));
+}
diff --git a/lib/tracker/metrics.test.ts b/lib/tracker/metrics.test.ts
new file mode 100644
index 0000000..b25388a
--- /dev/null
+++ b/lib/tracker/metrics.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it } from "vitest";
+import {
+ activityPoints, addDays, asOfDate, buildEvents, consistencyScore, countKinds, firstEventDate, inRange, isIsoDate, previousRange, progressDirection, sparkline,
+ resolveRange, spanDays, weekStart, weekStreaks, weeklyBuckets, type ActivityEvent,
+} from "./metrics";
+import { pr, student } from "./test-fixtures";
+
+const ev = (date: string, kind: ActivityEvent["kind"] = "pr_opened", url = `u-${date}-${kind}`): ActivityEvent => ({ date, kind, title: "t", detail: "d", url });
+
+describe("dates and ranges", () => {
+ it("validates ISO dates strictly", () => {
+ expect(isIsoDate("2026-11-13")).toBe(true);
+ expect(isIsoDate("2026-02-30")).toBe(false);
+ expect(isIsoDate("13/11/2026")).toBe(false);
+ expect(isIsoDate("")).toBe(false);
+ });
+
+ it("finds the Monday of a week and adds days across month ends", () => {
+ expect(weekStart("2026-11-13")).toBe("2026-11-09"); // Friday
+ expect(weekStart("2026-11-09")).toBe("2026-11-09");
+ expect(weekStart("2026-11-15")).toBe("2026-11-09"); // Sunday
+ expect(addDays("2026-11-30", 1)).toBe("2026-12-01");
+ });
+
+ it("resolves presets ending on asOf and is inclusive", () => {
+ const r = resolveRange("1w", "2026-11-13");
+ expect(r).toEqual({ start: "2026-11-07", end: "2026-11-13" });
+ expect(spanDays(r!)).toBe(7);
+ expect(spanDays(resolveRange("2m", "2026-11-13")!)).toBe(60);
+ });
+
+ it("rejects bad custom ranges", () => {
+ expect(resolveRange("custom", "2026-11-13")).toBeNull();
+ expect(resolveRange("custom", "2026-11-13", { start: "2026-11-10", end: "2026-11-01" })).toBeNull();
+ expect(resolveRange("custom", "2026-11-13", { start: "nope", end: "2026-11-01" })).toBeNull();
+ expect(resolveRange("custom", "2026-11-13", { start: "2026-11-01", end: "2026-11-10" })).toEqual({ start: "2026-11-01", end: "2026-11-10" });
+ });
+
+ it("builds the previous window of equal length directly before", () => {
+ expect(previousRange({ start: "2026-11-07", end: "2026-11-13" })).toEqual({ start: "2026-10-31", end: "2026-11-06" });
+ });
+
+ it("uses the later of snapshot and sync date as the data date", () => {
+ expect(asOfDate({ snapshotDate: "2026-11-13", syncedAt: null })).toBe("2026-11-13");
+ expect(asOfDate({ snapshotDate: "2026-11-13", syncedAt: "2026-12-01T05:00:00Z" })).toBe("2026-12-01");
+ expect(asOfDate({ snapshotDate: "2026-11-13", syncedAt: "2026-11-01T05:00:00Z" })).toBe("2026-11-13");
+ expect(asOfDate({ snapshotDate: "2026-11-13", syncedAt: "garbage" })).toBe("2026-11-13");
+ });
+});
+
+describe("buildEvents", () => {
+ it("emits opened, merged and closed events and appreciation", () => {
+ const events = buildEvents(student({
+ prs: [
+ pr({ url: "m", state: "merged", createdAt: "2026-10-01", closedAt: "2026-10-05" }),
+ pr({ url: "c", state: "closed", createdAt: "2026-10-02", closedAt: "2026-10-03" }),
+ pr({ url: "o", state: "open", createdAt: "2026-10-04" }),
+ ],
+ appreciation: [{ repo: "o/r", prNumber: 1, prTitle: "T", reviewer: "x", reviewerRole: "", date: "2026-10-06", type: "", comment: "Nice", url: "a" }],
+ }));
+ expect(countKinds(events)).toMatchObject({ pr_opened: 3, pr_merged: 1, pr_closed: 1, appreciation: 1, task_completed: 0 });
+ expect(events[0].date).toBe("2026-10-06"); // newest first
+ });
+
+ it("counts a duplicated record once and skips undated or malformed ones", () => {
+ const events = buildEvents(student({
+ prs: [pr({ url: "same" }), pr({ url: "same" }), pr({ url: "nodate", createdAt: null }), pr({ url: "bad", createdAt: "yesterday" }), pr({ url: "mergedNoDate", state: "merged", createdAt: "2026-10-01", closedAt: null })],
+ }));
+ expect(events.filter((e) => e.kind === "pr_opened")).toHaveLength(2);
+ expect(events.filter((e) => e.kind === "pr_merged")).toHaveLength(0);
+ });
+
+ it("accepts full ISO timestamps by taking the day", () => {
+ expect(buildEvents(student({ prs: [pr({ url: "t", createdAt: "2026-10-01T10:00:00Z" })] }))[0].date).toBe("2026-10-01");
+ });
+});
+
+describe("counting and buckets", () => {
+ const events = [ev("2026-11-02"), ev("2026-11-04", "pr_merged"), ev("2026-11-11"), ev("2026-10-01")];
+
+ it("filters inclusively and weights merges higher", () => {
+ const inside = inRange(events, { start: "2026-11-02", end: "2026-11-11" });
+ expect(inside).toHaveLength(3);
+ expect(activityPoints(inside)).toBe(4);
+ expect(activityPoints([])).toBe(0);
+ });
+
+ it("buckets by Monday weeks and clips partial weeks to the range", () => {
+ const buckets = weeklyBuckets(events, { start: "2026-11-02", end: "2026-11-13" });
+ expect(buckets.map((b) => b.week)).toEqual(["2026-11-02", "2026-11-09"]);
+ expect(buckets[0]).toMatchObject({ pr_opened: 1, pr_merged: 1 });
+ expect(buckets[1]).toMatchObject({ pr_opened: 1, from: "2026-11-09", to: "2026-11-13" });
+ expect(weeklyBuckets(events, { start: "2026-11-04", end: "2026-11-04" })[0]).toMatchObject({ from: "2026-11-04", to: "2026-11-04" });
+ });
+});
+
+describe("progressDirection", () => {
+ const range = { start: "2026-11-01", end: "2026-11-30" };
+ const old = ev("2026-09-01"); // gives the student a long history
+
+ it("is insufficient when the first activity is under two weeks old", () => {
+ const d = progressDirection([ev("2026-11-25")], range);
+ expect(d.direction).toBe("insufficient");
+ expect(progressDirection([], range).direction).toBe("insufficient");
+ });
+
+ it("is improving when activity rises by 20% or more", () => {
+ const d = progressDirection([old, ev("2026-10-05"), ev("2026-11-03"), ev("2026-11-10"), ev("2026-11-20")], range);
+ expect(d).toMatchObject({ direction: "improving", current: 3, previous: 1 });
+ expect(d.explanation).toMatch(/Improving/);
+ });
+
+ it("is declining when activity falls by 20% or more, and says it may be a break", () => {
+ const d = progressDirection([old, ev("2026-10-05"), ev("2026-10-10"), ev("2026-10-15"), ev("2026-11-20")], range);
+ expect(d).toMatchObject({ direction: "declining", changePct: -67 });
+ expect(d.explanation).toMatch(/break or private work/);
+ });
+
+ it("is stable inside the 20% band, and when both periods are empty", () => {
+ const flat = progressDirection([old, ev("2026-10-05"), ev("2026-11-05")], range);
+ expect(flat.direction).toBe("stable");
+ expect(progressDirection([old], { start: "2026-11-01", end: "2026-11-30" })).toMatchObject({ direction: "stable", changePct: null });
+ });
+
+ it("treats first activity after an empty period as improving", () => {
+ expect(progressDirection([old, ev("2026-11-05")], range)).toMatchObject({ direction: "improving", previous: 0, changePct: null });
+ });
+
+ it("does not let a merge count the same as an open", () => {
+ const d = progressDirection([old, ev("2026-11-05", "pr_merged")], range);
+ expect(d.current).toBe(2);
+ });
+});
+
+describe("consistencyScore", () => {
+ const range = { start: "2026-10-19", end: "2026-11-15" }; // four full Mon-Sun weeks
+
+ it("returns null when the student has done nothing", () => {
+ expect(consistencyScore([], range)).toBeNull();
+ expect(consistencyScore([ev("2026-11-01", "appreciation")], range)).toBeNull();
+ });
+
+ it("scores a student active every week highly, with an explanation that adds up", () => {
+ const r = consistencyScore([ev("2026-10-20"), ev("2026-10-27"), ev("2026-11-03"), ev("2026-11-14")], range)!;
+ expect(r.score).toBe(99);
+ expect(r.parts.reduce((s, p) => s + p.points, 0)).toBe(r.score);
+ expect(r.explanation).toContain("4 of 4 weeks");
+ });
+
+ it("scores a one-off burst much lower", () => {
+ const r = consistencyScore([ev("2026-10-20")], range)!;
+ expect(r.score).toBeLessThan(40);
+ expect(r.parts[0].detail).toBe("Active in 1 of 4 weeks");
+ });
+
+ it("only counts what the student did, not appreciation or closures", () => {
+ const r = consistencyScore([ev("2026-10-20"), ev("2026-10-27", "appreciation"), ev("2026-11-03", "pr_closed")], range)!;
+ expect(r.parts[0].detail).toBe("Active in 1 of 4 weeks");
+ });
+
+ it("leaves fully excused weeks out instead of counting them against the student", () => {
+ const events = [ev("2026-10-20"), ev("2026-11-10")];
+ const without = consistencyScore(events, range)!;
+ const leave = Array.from({ length: 14 }, (_, i) => addDays("2026-10-26", i)); // two whole Mon-Sun weeks
+ const withLeave = consistencyScore(events, range, leave)!;
+ expect(withLeave.score).toBeGreaterThan(without.score);
+ expect(withLeave.parts[0].detail).toBe("Active in 2 of 2 weeks");
+ expect(withLeave.explanation).toContain("2 excused weeks");
+ });
+
+ it("returns null if every week is excused", () => {
+ const all = Array.from({ length: 28 }, (_, i) => addDays("2026-10-19", i));
+ expect(consistencyScore([ev("2026-10-20")], range, all)).toBeNull();
+ });
+
+ it("is never above 100", () => {
+ const many = Array.from({ length: 28 }, (_, i) => ev(addDays("2026-10-19", i)));
+ expect(consistencyScore(many, range)!.score).toBeLessThanOrEqual(100);
+ });
+});
+
+describe("weekStreaks", () => {
+ it("is zero without activity", () => {
+ expect(weekStreaks([], "2026-11-13")).toEqual({ currentWeeks: 0, longestWeeks: 0 });
+ });
+
+ it("counts consecutive active weeks and tracks the longest", () => {
+ const events = [ev("2026-09-01"), ev("2026-09-08"), ev("2026-09-15"), ev("2026-10-20"), ev("2026-10-27"), ev("2026-11-03"), ev("2026-11-10")];
+ expect(weekStreaks(events, "2026-11-13")).toEqual({ currentWeeks: 4, longestWeeks: 4 });
+ });
+
+ it("does not break the streak for a current week that has not had activity yet", () => {
+ const events = [ev("2026-10-27"), ev("2026-11-03")];
+ expect(weekStreaks(events, "2026-11-11").currentWeeks).toBe(2);
+ });
+
+ it("breaks after a missed week, but an excused week bridges the gap", () => {
+ const events = [ev("2026-10-13"), ev("2026-10-27"), ev("2026-11-03")];
+ expect(weekStreaks(events, "2026-11-05").currentWeeks).toBe(2);
+ const leave = Array.from({ length: 7 }, (_, i) => addDays("2026-10-19", i));
+ expect(weekStreaks(events, "2026-11-05", leave).currentWeeks).toBe(3);
+ });
+});
+
+describe("all-time range and sparkline", () => {
+ it("runs from the first event to the data date, falling back to two months with none", () => {
+ expect(resolveRange("all", "2026-11-13", undefined, "2026-08-20")).toEqual({ start: "2026-08-20", end: "2026-11-13" });
+ expect(resolveRange("all", "2026-11-13", undefined, null)).toEqual({ start: "2026-09-15", end: "2026-11-13" });
+ expect(resolveRange("all", "2026-11-13", undefined, "2027-01-01")).toEqual({ start: "2026-09-15", end: "2026-11-13" });
+ });
+
+ it("gives twelve weekly counts, oldest first, counting only what the student did", () => {
+ const spark = sparkline([ev("2026-11-10"), ev("2026-11-11", "pr_merged"), ev("2026-11-12", "appreciation"), ev("2026-10-27"), ev("2026-02-01")], "2026-11-13");
+ expect(spark).toHaveLength(12);
+ expect(spark[11]).toBe(2); // week of 9 Nov: one opened + one merged; appreciation is not the student's action
+ expect(spark[9]).toBe(1); // week of 26 Oct
+ expect(spark.reduce((a, b) => a + b, 0)).toBe(3); // the February event is outside the window
+ expect(sparkline([], "2026-11-13")).toEqual(Array(12).fill(0));
+ });
+
+ it("finds the earliest event regardless of order", () => {
+ expect(firstEventDate([ev("2026-10-05"), ev("2026-08-01"), ev("2026-09-01")])).toBe("2026-08-01");
+ expect(firstEventDate([])).toBeNull();
+ });
+});
diff --git a/lib/tracker/metrics.ts b/lib/tracker/metrics.ts
new file mode 100644
index 0000000..604fafe
--- /dev/null
+++ b/lib/tracker/metrics.ts
@@ -0,0 +1,369 @@
+import type { TrackerStudent } from "./types";
+
+/**
+ * One place that turns a student's cached record into time-based numbers, so the
+ * dashboard, the detail page and the insights all agree. Everything here is pure:
+ * dates are yyyy-mm-dd strings in UTC and "today" is always passed in as `asOf`.
+ *
+ * What it can see: public PRs (opened / merged / closed) and maintainer
+ * appreciation. It cannot see commits, reviews given, private work or time
+ * spent, so none of those are invented. Phase 2 adds mentor-entered records.
+ */
+
+export type RangeKey = "all" | "1w" | "2w" | "3w" | "1m" | "2m" | "custom";
+
+export const RANGE_LABELS: Record = {
+ all: "All time",
+ "1w": "Last week",
+ "2w": "Last 2 weeks",
+ "3w": "Last 3 weeks",
+ "1m": "Last month",
+ "2m": "Last 2 months",
+ custom: "Custom range",
+};
+
+const RANGE_DAYS: Record, number> = { "1w": 7, "2w": 14, "3w": 21, "1m": 30, "2m": 60 };
+
+export interface DateRange {
+ /** Inclusive. */
+ start: string;
+ /** Inclusive. */
+ end: string;
+}
+
+/* ---------- date helpers ---------- */
+
+const DAY_MS = 86_400_000;
+
+export const isIsoDate = (s: string): boolean => {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;
+ const t = Date.parse(`${s}T00:00:00Z`);
+ return !Number.isNaN(t) && new Date(t).toISOString().slice(0, 10) === s;
+};
+
+export const dayNum = (iso: string): number => Math.floor(Date.parse(`${iso.slice(0, 10)}T00:00:00Z`) / DAY_MS);
+export const fromDayNum = (n: number): string => new Date(n * DAY_MS).toISOString().slice(0, 10);
+export const addDays = (iso: string, n: number): string => fromDayNum(dayNum(iso) + n);
+export const daysBetween = (from: string, to: string): number => dayNum(to) - dayNum(from);
+export const spanDays = (r: DateRange): number => daysBetween(r.start, r.end) + 1;
+
+/** Monday of the week containing `day` (1970-01-01 was a Thursday). */
+const weekStartNum = (n: number): number => n - ((n + 3) % 7);
+export const weekStart = (iso: string): string => fromDayNum(weekStartNum(dayNum(iso)));
+
+/**
+ * `null` when the key is "custom" and the dates are missing, malformed or back
+ * to front. "all" runs from the student's first activity (`firstEvent`) to
+ * `asOf`, or the last two months when they have none.
+ */
+export function resolveRange(key: RangeKey, asOf: string, custom?: { start: string; end: string }, firstEvent?: string | null): DateRange | null {
+ if (key === "all") {
+ const start = firstEvent && firstEvent <= asOf ? firstEvent : addDays(asOf, -59);
+ return { start, end: asOf };
+ }
+ if (key === "custom") {
+ if (!custom || !isIsoDate(custom.start) || !isIsoDate(custom.end) || custom.start > custom.end) return null;
+ return { start: custom.start, end: custom.end };
+ }
+ return { start: addDays(asOf, -(RANGE_DAYS[key] - 1)), end: asOf };
+}
+
+/** The equally long window immediately before `r`, for "compared with last time". */
+export function previousRange(r: DateRange): DateRange {
+ const len = spanDays(r);
+ return { start: addDays(r.start, -len), end: addDays(r.start, -1) };
+}
+
+/* ---------- activity events ---------- */
+
+export type ActivityKind = "pr_opened" | "pr_merged" | "pr_closed" | "appreciation" | "task_completed" | "weekly_review" | "mentor_note";
+
+export const KIND_LABELS: Record = {
+ pr_opened: "Pull request opened",
+ pr_merged: "Pull request merged",
+ pr_closed: "Pull request closed without merge",
+ appreciation: "Appreciation received",
+ task_completed: "Task completed",
+ weekly_review: "Weekly review",
+ mentor_note: "Mentor feedback",
+};
+
+export interface ActivityEvent {
+ date: string;
+ kind: ActivityKind;
+ title: string;
+ detail: string;
+ url: string;
+}
+
+/**
+ * Actions the student took. Merges count because they mean the PR was kept alive
+ * through review. Closures and appreciation are other people's decisions, so
+ * they never raise or lower consistency.
+ */
+const STUDENT_KINDS: ActivityKind[] = ["pr_opened", "pr_merged", "task_completed", "weekly_review"];
+
+/** Points behind the progress direction. Merging is worth more than opening. */
+const POINTS: Record = { pr_opened: 1, pr_merged: 2, pr_closed: 0, appreciation: 1, task_completed: 2, weekly_review: 1, mentor_note: 0 };
+
+/**
+ * The student's dated events. A record counts once however many times it is
+ * listed (same kind + link), and anything without a valid date is left out
+ * rather than guessed at.
+ */
+export function buildEvents(s: TrackerStudent, extra: ActivityEvent[] = []): ActivityEvent[] {
+ const seen = new Set();
+ const out: ActivityEvent[] = [];
+ const add = (e: ActivityEvent) => {
+ if (!isIsoDate(e.date)) return;
+ const key = `${e.kind}|${e.url || e.title}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ out.push(e);
+ };
+
+ for (const p of s.prs) {
+ const ref = `${p.repo}#${p.number}`;
+ const dated = (d: string | null) => (d ? d.slice(0, 10) : "");
+ add({ date: dated(p.createdAt), kind: "pr_opened", title: p.title, detail: ref, url: p.url });
+ if (p.state === "merged") add({ date: dated(p.closedAt), kind: "pr_merged", title: p.title, detail: ref, url: p.url });
+ if (p.state === "closed") add({ date: dated(p.closedAt), kind: "pr_closed", title: p.title, detail: ref, url: p.url });
+ }
+ for (const a of s.appreciation) {
+ add({
+ date: a.date ? a.date.slice(0, 10) : "",
+ kind: "appreciation",
+ title: a.comment.length > 140 ? `${a.comment.slice(0, 137)}…` : a.comment,
+ detail: `${a.reviewer} · ${a.repo}`,
+ url: a.url,
+ });
+ }
+ for (const e of extra) add(e);
+ return out.sort((a, b) => b.date.localeCompare(a.date));
+}
+
+export const inRange = (events: ActivityEvent[], r: DateRange): ActivityEvent[] => events.filter((e) => e.date >= r.start && e.date <= r.end);
+
+export type KindCounts = Record;
+
+export function countKinds(events: ActivityEvent[]): KindCounts {
+ const c: KindCounts = { pr_opened: 0, pr_merged: 0, pr_closed: 0, appreciation: 0, task_completed: 0, weekly_review: 0, mentor_note: 0 };
+ for (const e of events) c[e.kind]++;
+ return c;
+}
+
+export const activityPoints = (events: ActivityEvent[]): number => events.reduce((sum, e) => sum + POINTS[e.kind], 0);
+
+/**
+ * "As of" for a student: the day their numbers were last true. After a GitHub
+ * sync that is the sync day; before one, it is the sheet's snapshot date.
+ * Using today instead would make every student look like they stopped working
+ * on the day the data stopped being refreshed.
+ */
+export function asOfDate(s: Pick): string {
+ const synced = s.syncedAt ? s.syncedAt.slice(0, 10) : "";
+ return isIsoDate(synced) && synced > s.snapshotDate ? synced : s.snapshotDate;
+}
+
+const earliest = (events: ActivityEvent[]): string | null => events.reduce((min, e) => (min === null || e.date < min ? e.date : min), null);
+const latestOnOrBefore = (events: ActivityEvent[], day: string): string | null =>
+ events.reduce((max, e) => (e.date <= day && (max === null || e.date > max) ? e.date : max), null);
+
+/* ---------- weekly buckets ---------- */
+
+export interface WeekBucket extends KindCounts {
+ /** Monday of the week, yyyy-mm-dd. */
+ week: string;
+ /** First and last day of the week that fall inside the range. */
+ from: string;
+ to: string;
+}
+
+export function weeklyBuckets(events: ActivityEvent[], r: DateRange): WeekBucket[] {
+ const buckets: WeekBucket[] = [];
+ for (let w = weekStartNum(dayNum(r.start)); w <= dayNum(r.end); w += 7) {
+ const week = fromDayNum(w);
+ const from = week < r.start ? r.start : week;
+ const weekEnd = fromDayNum(w + 6);
+ const to = weekEnd > r.end ? r.end : weekEnd;
+ buckets.push({ week, from, to, ...countKinds(events.filter((e) => e.date >= from && e.date <= to)) });
+ }
+ return buckets;
+}
+
+/** Date of the oldest event, or `null` with none. */
+export const firstEventDate = earliest;
+
+/**
+ * Student activity per week for the last `weeks` weeks ending at `asOf`, oldest
+ * first. Feeds the table's sparkline: a shape you can read at a glance.
+ */
+export function sparkline(events: ActivityEvent[], asOf: string, weeks = 12): number[] {
+ const start = addDays(weekStart(asOf), -7 * (weeks - 1));
+ return weeklyBuckets(events, { start, end: asOf }).map((b) => b.pr_opened + b.pr_merged + b.task_completed + b.weekly_review);
+}
+
+/* ---------- progress direction ---------- */
+
+export type Direction = "improving" | "stable" | "declining" | "insufficient";
+
+export const DIRECTION_LABELS: Record = {
+ improving: "Improving",
+ stable: "Stable",
+ declining: "Declining",
+ insufficient: "Not enough data",
+};
+
+export interface DirectionResult {
+ direction: Direction;
+ current: number;
+ previous: number;
+ /** Percent change in activity points, or `null` when the earlier period had none. */
+ changePct: number | null;
+ explanation: string;
+}
+
+/** A move of at least this much, either way, counts as a change rather than noise. */
+const CHANGE_THRESHOLD_PCT = 20;
+/** Fewer days of history than this is not enough to call a trend. */
+const MIN_HISTORY_DAYS = 14;
+
+/**
+ * Compares activity points in `range` with the previous equally long window.
+ * Several kinds of activity feed the points, not PR count alone, and a student
+ * whose first activity is under two weeks old is never called "declining".
+ */
+export function progressDirection(events: ActivityEvent[], range: DateRange): DirectionResult {
+ const prior = previousRange(range);
+ const current = activityPoints(inRange(events, range));
+ const previous = activityPoints(inRange(events, prior));
+
+ const first = earliest(events);
+ if (!first || daysBetween(first, range.end) < MIN_HISTORY_DAYS) {
+ return {
+ direction: "insufficient", current, previous, changePct: null,
+ explanation: "At least two weeks of activity are needed before a trend means anything.",
+ };
+ }
+ if (previous === 0 && current === 0) {
+ return { direction: "stable", current, previous, changePct: null, explanation: "No recorded activity in this period or the one before it." };
+ }
+ if (previous === 0) {
+ return { direction: "improving", current, previous, changePct: null, explanation: `Improving: ${current} activity points this period, none in the period before.` };
+ }
+ const changePct = Math.round(((current - previous) / previous) * 100);
+ if (changePct >= CHANGE_THRESHOLD_PCT) {
+ return { direction: "improving", current, previous, changePct, explanation: `Improving: activity rose ${changePct}% (${previous} → ${current} points) compared with the previous period.` };
+ }
+ if (changePct <= -CHANGE_THRESHOLD_PCT) {
+ return { direction: "declining", current, previous, changePct, explanation: `Declining: activity fell ${Math.abs(changePct)}% (${previous} → ${current} points) compared with the previous period. This may be a break or private work.` };
+ }
+ return { direction: "stable", current, previous, changePct, explanation: `Stable: activity is within ${CHANGE_THRESHOLD_PCT}% of the previous period (${previous} → ${current} points).` };
+}
+
+/* ---------- consistency ---------- */
+
+export interface ScorePart {
+ label: string;
+ points: number;
+ max: number;
+ detail: string;
+}
+
+export interface ConsistencyResult {
+ score: number;
+ parts: ScorePart[];
+ explanation: string;
+}
+
+const WEIGHT_REGULARITY = 60;
+const WEIGHT_RECENCY = 25;
+const WEIGHT_STREAK = 15;
+
+/**
+ * 0-100, built from three visible parts: how many weeks in the range had any
+ * student activity, how recently they last acted, and how many of the latest
+ * weeks in a row were active. Weeks wholly covered by `excused` days (approved
+ * leave and the like) are removed from the maths instead of counted against
+ * the student. `null` when there is no activity on record at all.
+ */
+export function consistencyScore(events: ActivityEvent[], range: DateRange, excused: string[] = []): ConsistencyResult | null {
+ const mine = events.filter((e) => STUDENT_KINDS.includes(e.kind));
+ if (mine.length === 0) return null;
+
+ const excusedSet = new Set(excused);
+ const weeks = weeklyBuckets(mine, range).map((b) => {
+ const days = daysBetween(b.from, b.to) + 1;
+ let excusedDays = 0;
+ for (let i = 0; i < days; i++) if (excusedSet.has(addDays(b.from, i))) excusedDays++;
+ return { active: b.pr_opened + b.pr_merged + b.task_completed + b.weekly_review > 0, excused: excusedDays === days };
+ });
+ const counted = weeks.filter((w) => !w.excused);
+ if (counted.length === 0) return null;
+
+ const activeWeeks = counted.filter((w) => w.active).length;
+ const regularity = Math.round((activeWeeks / counted.length) * WEIGHT_REGULARITY);
+
+ const last = latestOnOrBefore(mine, range.end);
+ const sinceLast = last ? Math.max(0, daysBetween(last, range.end)) : spanDays(range);
+ const recency = Math.round(Math.max(0, 1 - sinceLast / spanDays(range)) * WEIGHT_RECENCY);
+
+ let run = 0;
+ for (let i = weeks.length - 1; i >= 0; i--) {
+ if (weeks[i].excused) continue;
+ if (!weeks[i].active) break;
+ run++;
+ }
+ const streak = Math.round((run / counted.length) * WEIGHT_STREAK);
+
+ const parts: ScorePart[] = [
+ { label: "Weekly regularity", points: regularity, max: WEIGHT_REGULARITY, detail: `Active in ${activeWeeks} of ${counted.length} weeks` },
+ { label: "Recency", points: recency, max: WEIGHT_RECENCY, detail: last ? `Last activity ${sinceLast} day${sinceLast === 1 ? "" : "s"} before the end of the range` : "No activity before the end of the range" },
+ { label: "Recent streak", points: streak, max: WEIGHT_STREAK, detail: `${run} active week${run === 1 ? "" : "s"} in a row at the end` },
+ ];
+ const score = Math.min(100, regularity + recency + streak);
+ const skipped = weeks.length - counted.length;
+ return {
+ score,
+ parts,
+ explanation: `Active in ${activeWeeks} of ${counted.length} weeks${skipped ? ` (${skipped} excused week${skipped === 1 ? "" : "s"} left out)` : ""}, last acted ${sinceLast} day${sinceLast === 1 ? "" : "s"} before the end, ${run} active week${run === 1 ? "" : "s"} in a row. Based on the PR activity and mentor records on file.`,
+ };
+}
+
+/* ---------- streaks ---------- */
+
+export interface Streaks {
+ /** Consecutive active weeks ending now. A quiet week in progress does not break it. */
+ currentWeeks: number;
+ longestWeeks: number;
+}
+
+export function weekStreaks(events: ActivityEvent[], asOf: string, excused: string[] = []): Streaks {
+ const mine = events.filter((e) => STUDENT_KINDS.includes(e.kind) && e.date <= asOf);
+ if (mine.length === 0) return { currentWeeks: 0, longestWeeks: 0 };
+
+ const active = new Set(mine.map((e) => weekStartNum(dayNum(e.date))));
+ const excusedWeeks = new Set();
+ const perWeek = new Map();
+ for (const d of excused) if (isIsoDate(d)) perWeek.set(weekStartNum(dayNum(d)), (perWeek.get(weekStartNum(dayNum(d))) ?? 0) + 1);
+ for (const [w, n] of perWeek) if (n >= 7) excusedWeeks.add(w);
+
+ const firstWeek = weekStartNum(dayNum(earliest(mine) as string));
+ const thisWeek = weekStartNum(dayNum(asOf));
+
+ let longest = 0;
+ let run = 0;
+ for (let w = firstWeek; w <= thisWeek; w += 7) {
+ if (active.has(w)) run++;
+ else if (!excusedWeeks.has(w)) run = 0;
+ longest = Math.max(longest, run);
+ }
+
+ let current = 0;
+ for (let w = thisWeek; w >= firstWeek; w -= 7) {
+ if (active.has(w)) current++;
+ else if (excusedWeeks.has(w) || (w === thisWeek && current === 0)) continue;
+ else break;
+ }
+ return { currentWeeks: current, longestWeeks: Math.max(longest, current) };
+}
diff --git a/lib/tracker/parse-sheet.test.ts b/lib/tracker/parse-sheet.test.ts
index 0eafcd4..2aa3adb 100644
--- a/lib/tracker/parse-sheet.test.ts
+++ b/lib/tracker/parse-sheet.test.ts
@@ -111,3 +111,21 @@ describe("parseSheetExport", () => {
expect(() => parseSheetExport("## Sheet name: Dashboard\nCohort snapshot: 13 November 2026")).toThrow(/Students/);
});
});
+
+describe("percent cells from a raw spreadsheet (fractions, no % sign)", () => {
+ const raw = parseSheetExport(
+ EXPORT.replace("33%,33%,33%,50.0%", "0.3333,0.3333,0.3333,1").replace("40.0%", "0.4"),
+ );
+ const asha = raw.students.find((s) => s.github === "asha-r")!;
+
+ it("reads 1 as 100% and 0.4 as 40%, not 1% and 0.4%", () => {
+ expect(asha.totals.mergeSuccessPct).toBe(100);
+ expect(asha.totals.titleHygienePct).toBe(40);
+ });
+
+ it("still reads text percentages as they are", () => {
+ const text = parseSheetExport(EXPORT).students.find((s) => s.github === "asha-r")!;
+ expect(text.totals.mergeSuccessPct).toBe(50);
+ expect(text.totals.titleHygienePct).toBe(40);
+ });
+});
diff --git a/lib/tracker/parse-sheet.ts b/lib/tracker/parse-sheet.ts
index 3e65b31..4d5459e 100644
--- a/lib/tracker/parse-sheet.ts
+++ b/lib/tracker/parse-sheet.ts
@@ -61,11 +61,19 @@ function count(value: string | undefined): number | null {
return Number(v);
}
+/**
+ * "100.0%" is already a percentage. A bare number is a spreadsheet's raw
+ * fraction (a cell formatted as %, read without its format): 1 means 100%,
+ * 0.2857 means 28.6%. Without this a fully merged student read as "1%".
+ */
function percent(value: string | undefined): number | null {
- const v = (value ?? "").trim().replace("%", "");
+ const raw = (value ?? "").trim();
+ const hasSign = raw.endsWith("%");
+ const v = raw.replace("%", "");
if (v === "" || !/^\d+(\.\d+)?$/.test(v)) return null;
const n = Number(v);
- return n >= 0 && n <= 100 ? n : null;
+ const pct = !hasSign && n <= 1 ? Math.round(n * 1000) / 10 : n;
+ return pct >= 0 && pct <= 100 ? pct : null;
}
function text(value: string | undefined): string | null {
diff --git a/lib/tracker/records-store.ts b/lib/tracker/records-store.ts
new file mode 100644
index 0000000..baad7eb
--- /dev/null
+++ b/lib/tracker/records-store.ts
@@ -0,0 +1,107 @@
+import { club, COLLECTIONS } from "@/lib/firebase/collections";
+import { dedupeKey, recordInput, type RecordInput, type TrackerRecord } from "./records";
+import { demoEnabled, demoStore } from "./demo";
+import { docId, loadStudent } from "./store";
+
+const records = () => club(COLLECTIONS.trackerRecords);
+
+/** Newest first. Sorted here, not in Firestore: a where()+orderBy() would need a composite index on a shared project. */
+const newestFirst = (a: TrackerRecord, b: TrackerRecord) => b.createdAt.localeCompare(a.createdAt);
+
+export async function loadRecords(github: string): Promise {
+ if (demoEnabled()) return [...demoStore().records.values()].filter((r) => r.github === docId(github)).sort(newestFirst);
+ const snap = await records().where("github", "==", docId(github)).get();
+ return snap.docs.map((d) => d.data()).sort(newestFirst);
+}
+
+/** Every student's records in one read, grouped by handle, for the dashboard. */
+export async function loadAllRecords(): Promise> {
+ const all = demoEnabled() ? [...demoStore().records.values()] : (await records().get()).docs.map((d) => d.data());
+ const out = new Map();
+ for (const r of all) {
+ out.set(r.github, [...(out.get(r.github) ?? []), r]);
+ }
+ for (const [k, v] of out) out.set(k, v.sort(newestFirst));
+ return out;
+}
+
+export type SaveResult =
+ | { ok: true; record: TrackerRecord }
+ | { ok: false; status: 400 | 403 | 404 | 409; message: string };
+
+export interface Author {
+ usn: string;
+ name: string;
+ /** Admins may change anyone's record; others only their own. */
+ isAdmin: boolean;
+}
+
+const nowIso = () => new Date().toISOString();
+
+/** One place that writes, so demo mode and Firestore stay in step. */
+async function persist(record: TrackerRecord): Promise {
+ if (demoEnabled()) demoStore().records.set(record.id, record);
+ else await records().doc(record.id).set(record);
+}
+const newId = (): string => (demoEnabled() ? `demo-${Math.random().toString(36).slice(2, 10)}` : records().doc().id);
+async function fetchRecord(id: string): Promise {
+ if (demoEnabled()) return demoStore().records.get(id) ?? null;
+ const snap = await records().doc(id).get();
+ return snap.exists ? (snap.data() as TrackerRecord) : null;
+}
+
+/** Keeps completedAt in step with status: set the first time a task is done, cleared if reopened. */
+export function completionFor(input: RecordInput, previous: TrackerRecord | null, now: string): string | null | undefined {
+ if (input.kind !== "task") return undefined;
+ if (input.status !== "done") return null;
+ return previous && previous.kind === "task" && previous.status === "done" && previous.completedAt ? previous.completedAt : now;
+}
+
+export async function createRecord(raw: unknown, author: Author): Promise {
+ const parsed = recordInput.safeParse(raw);
+ if (!parsed.success) return { ok: false, status: 400, message: parsed.error.issues[0]?.message ?? "Invalid record." };
+ const input = { ...parsed.data, github: docId(parsed.data.github) };
+
+ if (!(await loadStudent(input.github))) return { ok: false, status: 404, message: "No such student." };
+
+ const key = dedupeKey(input);
+ const existing = await loadRecords(input.github);
+ if (existing.some((r) => r.dedupeKey === key)) return { ok: false, status: 409, message: "This looks like a record that already exists." };
+
+ const now = nowIso();
+ const record = { ...input, id: newId(), authorUsn: author.usn, authorName: author.name, createdAt: now, updatedAt: now, dedupeKey: key, completedAt: completionFor(input, null, now) } as TrackerRecord;
+ // Firestore rejects undefined fields.
+ if (record.completedAt === undefined) delete (record as { completedAt?: unknown }).completedAt;
+ await persist(record);
+ return { ok: true, record };
+}
+
+export async function updateRecord(id: string, raw: unknown, author: Author): Promise {
+ const parsed = recordInput.safeParse(raw);
+ if (!parsed.success) return { ok: false, status: 400, message: parsed.error.issues[0]?.message ?? "Invalid record." };
+
+ const previous = await fetchRecord(id);
+ if (!previous) return { ok: false, status: 404, message: "No such record." };
+ if (previous.authorUsn !== author.usn && !author.isAdmin) return { ok: false, status: 403, message: "You can only change records you wrote." };
+ if (previous.kind !== parsed.data.kind || previous.github !== docId(parsed.data.github)) return { ok: false, status: 400, message: "A record's student and type cannot be changed." };
+
+ const input = { ...parsed.data, github: previous.github };
+ const key = dedupeKey(input);
+ const clash = (await loadRecords(previous.github)).some((r) => r.id !== id && r.dedupeKey === key);
+ if (clash) return { ok: false, status: 409, message: "Another record already matches this one." };
+
+ const now = nowIso();
+ const record = { ...input, id, authorUsn: previous.authorUsn, authorName: previous.authorName, createdAt: previous.createdAt, updatedAt: now, dedupeKey: key, completedAt: completionFor(input, previous, now) } as TrackerRecord;
+ if (record.completedAt === undefined) delete (record as { completedAt?: unknown }).completedAt;
+ await persist(record);
+ return { ok: true, record };
+}
+
+export async function deleteRecord(id: string, author: Author): Promise {
+ const previous = await fetchRecord(id);
+ if (!previous) return { ok: false, status: 404, message: "No such record." };
+ if (previous.authorUsn !== author.usn && !author.isAdmin) return { ok: false, status: 403, message: "You can only delete records you wrote." };
+ if (demoEnabled()) demoStore().records.delete(id);
+ else await records().doc(id).delete();
+ return { ok: true, record: null };
+}
diff --git a/lib/tracker/records.test.ts b/lib/tracker/records.test.ts
new file mode 100644
index 0000000..05beb43
--- /dev/null
+++ b/lib/tracker/records.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from "vitest";
+import { buildEvents, consistencyScore } from "./metrics";
+import { byKind, currentWork, dedupeKey, excusedDays, recordEvents, recordInput } from "./records";
+import { completionFor } from "./records-store";
+import { pr, record, student } from "./test-fixtures";
+
+const task = { github: "a", kind: "task", title: "Fix parser", difficulty: "hard", status: "planned", assignedAt: "2026-11-02" };
+
+describe("recordInput validation", () => {
+ it("accepts a minimal task and fills defaults", () => {
+ const r = recordInput.parse(task);
+ expect(r).toMatchObject({ kind: "task", repo: "", issueNumber: null, dueDate: null, blockers: "" });
+ });
+
+ it("rejects missing titles, bad dates and unknown kinds", () => {
+ expect(recordInput.safeParse({ ...task, title: " " }).success).toBe(false);
+ expect(recordInput.safeParse({ ...task, assignedAt: "2026-02-30" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...task, kind: "nonsense" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...task, status: "finished" }).success).toBe(false);
+ });
+
+ it("rejects a due date before the assigned date", () => {
+ const r = recordInput.safeParse({ ...task, dueDate: "2026-11-01" });
+ expect(r.success).toBe(false);
+ });
+
+ it("rejects negative, zero and fractional issue numbers", () => {
+ for (const n of [-1, 0, 1.5]) expect(recordInput.safeParse({ ...task, issueNumber: n }).success).toBe(false);
+ });
+
+ it("only allows http(s) links, never javascript: URLs", () => {
+ expect(recordInput.safeParse({ ...task, issueUrl: "https://github.com/o/r/issues/1" }).success).toBe(true);
+ expect(recordInput.safeParse({ ...task, issueUrl: "javascript:alert(1)" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...task, issueUrl: "ftp://x" }).success).toBe(false);
+ });
+
+ it("trims and caps text", () => {
+ expect((recordInput.parse({ ...task, title: " hi " }) as { title: string }).title).toBe("hi");
+ expect(recordInput.safeParse({ ...task, title: "x".repeat(141) }).success).toBe(false);
+ });
+
+ it("requires a Monday for weekly reviews and a 1-5 confidence", () => {
+ const review = { github: "a", kind: "review", weekStart: "2026-11-09", confidence: 3 };
+ expect(recordInput.safeParse(review).success).toBe(true);
+ expect(recordInput.safeParse({ ...review, weekStart: "2026-11-10" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...review, confidence: 0 }).success).toBe(false);
+ expect(recordInput.safeParse({ ...review, confidence: 6 }).success).toBe(false);
+ expect(recordInput.safeParse({ ...review, hours: -2 }).success).toBe(false);
+ expect(recordInput.safeParse({ ...review, hours: 81 }).success).toBe(false);
+ });
+
+ it("rejects leave that ends before it starts or runs over a year", () => {
+ const c = { github: "a", kind: "context", contextType: "approved-leave", startDate: "2026-11-05", endDate: "2026-11-01" };
+ expect(recordInput.safeParse(c).success).toBe(false);
+ expect(recordInput.safeParse({ ...c, endDate: "2028-01-01" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...c, endDate: "2026-11-07" }).success).toBe(true);
+ });
+
+ it("requires a reason and a real date for appreciation, defaulting the badge", () => {
+ const a = { github: "a", kind: "appreciation", title: "Thanks", reason: "Helped a lot", date: "2026-11-05" };
+ expect((recordInput.parse(a) as { badge: string }).badge).toBe("general");
+ expect(recordInput.safeParse({ ...a, reason: "" }).success).toBe(false);
+ expect(recordInput.safeParse({ ...a, badge: "gold-star" }).success).toBe(false);
+ });
+});
+
+describe("dedupeKey", () => {
+ it("matches the same task regardless of case and spacing, but not a different one", () => {
+ const a = recordInput.parse({ ...task, title: "Fix Parser" });
+ const b = recordInput.parse({ ...task, title: "fix parser" });
+ const c = recordInput.parse({ ...task, title: "Fix lexer" });
+ expect(dedupeKey(a)).toBe(dedupeKey(b));
+ expect(dedupeKey(a)).not.toBe(dedupeKey(c));
+ });
+
+ it("allows one weekly review per week", () => {
+ const r = (w: string) => recordInput.parse({ github: "a", kind: "review", weekStart: w, confidence: 3 });
+ expect(dedupeKey(r("2026-11-09"))).toBe(dedupeKey(r("2026-11-09")));
+ expect(dedupeKey(r("2026-11-09"))).not.toBe(dedupeKey(r("2026-11-16")));
+ });
+});
+
+describe("excusedDays", () => {
+ it("lists every day of every leave entry once, even when entries overlap", () => {
+ const days = excusedDays([record("context", { startDate: "2026-11-01", endDate: "2026-11-03" }), record("context", { startDate: "2026-11-03", endDate: "2026-11-04" })]);
+ expect(days.sort()).toEqual(["2026-11-01", "2026-11-02", "2026-11-03", "2026-11-04"]);
+ expect(excusedDays([])).toEqual([]);
+ expect(excusedDays([record("note")])).toEqual([]);
+ });
+
+ it("lifts the consistency score through to the score calculation", () => {
+ const events = buildEvents(student({ prs: [pr({ url: "1", createdAt: "2026-10-20" }), pr({ url: "2", createdAt: "2026-11-10" })] }));
+ const range = { start: "2026-10-19", end: "2026-11-15" };
+ const leave = record("context", { startDate: "2026-10-26", endDate: "2026-11-08" });
+ expect(consistencyScore(events, range, excusedDays([leave]))!.score).toBeGreaterThan(consistencyScore(events, range)!.score);
+ });
+});
+
+describe("recordEvents", () => {
+ it("turns completed tasks, appreciation, reviews and mentor observations into events", () => {
+ const events = recordEvents([
+ record("task", { status: "done", completedAt: "2026-11-08T09:00:00.000Z", title: "Ship it" }),
+ record("task", { status: "in-progress", title: "Not done" }),
+ record("appreciation", { title: "Nice", date: "2026-11-05" }),
+ record("review", { weekStart: "2026-11-02" }),
+ record("note", { noteType: "mentor-observation", createdAt: "2026-11-06T10:00:00.000Z" }),
+ record("note", { noteType: "learned" }),
+ record("context"),
+ ]);
+ expect(events.map((e) => e.kind).sort()).toEqual(["appreciation", "mentor_note", "task_completed", "weekly_review"]);
+ expect(events.find((e) => e.kind === "weekly_review")?.date).toBe("2026-11-08");
+ expect(events.find((e) => e.kind === "task_completed")?.title).toBe("Ship it");
+ });
+
+ it("counts a record once when the same event is passed twice", () => {
+ const r = record("task", { status: "done", completedAt: "2026-11-08T09:00:00.000Z" });
+ const events = buildEvents(student(), [...recordEvents([r]), ...recordEvents([r])]);
+ expect(events.filter((e) => e.kind === "task_completed")).toHaveLength(1);
+ });
+
+ it("makes completed tasks and reviews count toward consistency", () => {
+ const events = buildEvents(student(), recordEvents([record("task", { status: "done", completedAt: "2026-11-10T00:00:00.000Z" })]));
+ expect(consistencyScore(events, { start: "2026-11-02", end: "2026-11-15" })).not.toBeNull();
+ });
+});
+
+describe("currentWork", () => {
+ it("picks blocked first, then in progress, and counts overdue and blocked", () => {
+ const w = currentWork([
+ record("task", { title: "Planned", status: "planned", dueDate: "2026-11-01" }),
+ record("task", { title: "Going", status: "in-progress" }),
+ record("task", { title: "Stuck", status: "blocked" }),
+ record("task", { title: "Done", status: "done", dueDate: "2026-10-01" }),
+ ], "2026-11-13");
+ expect(w.task?.title).toBe("Stuck");
+ expect(w).toMatchObject({ open: 3, overdue: 1, blocked: 1 });
+ });
+
+ it("is empty without open tasks", () => {
+ expect(currentWork([record("task", { status: "done" })], "2026-11-13")).toEqual({ task: null, open: 0, overdue: 0, blocked: 0 });
+ expect(byKind([record("note")], "task")).toEqual([]);
+ });
+});
+
+describe("completionFor", () => {
+ const input = recordInput.parse({ ...task, status: "done" });
+ it("stamps completion the first time a task is done", () => {
+ expect(completionFor(input, null, "2026-11-10T00:00:00.000Z")).toBe("2026-11-10T00:00:00.000Z");
+ });
+ it("keeps the original stamp on later edits and clears it when reopened", () => {
+ const prev = record("task", { status: "done", completedAt: "2026-11-08T00:00:00.000Z" });
+ const reopened = recordInput.parse({ ...task, status: "in-progress" });
+ expect(completionFor(input, prev, "2026-11-12T00:00:00.000Z")).toBe("2026-11-08T00:00:00.000Z");
+ expect(completionFor(reopened, prev, "x")).toBeNull();
+ });
+ it("is not applicable to other kinds", () => {
+ expect(completionFor(recordInput.parse({ github: "a", kind: "note", noteType: "learned", text: "x" }), null, "x")).toBeUndefined();
+ });
+});
diff --git a/lib/tracker/records.ts b/lib/tracker/records.ts
new file mode 100644
index 0000000..2198cc8
--- /dev/null
+++ b/lib/tracker/records.ts
@@ -0,0 +1,206 @@
+import { z } from "zod";
+import { addDays, dayNum, isIsoDate, weekStart, type ActivityEvent } from "./metrics";
+
+/**
+ * Mentor-entered records, stored apart from the synced PR cache so a GitHub
+ * sync can never overwrite them. One collection holds every kind; `kind`
+ * says which fields apply. Everything here is pure (validation + helpers);
+ * Firestore access lives in records-store.ts.
+ */
+
+export const TASK_STATUSES = ["planned", "in-progress", "blocked", "in-review", "done"] as const;
+export const DIFFICULTIES = ["easy", "medium", "hard"] as const;
+export const NOTE_TYPES = [
+ "learned", "difficult-problem", "technical-skill", "communication", "teamwork", "initiative", "problem-solving",
+ "handling-feedback", "helped-others", "research", "challenge", "overcame-challenge", "mentor-observation", "student-reflection",
+] as const;
+export const BADGES = [
+ "first-pull-request", "first-merged-pull-request", "consistent-contributor", "documentation-champion", "bug-finder",
+ "helpful-reviewer", "community-contributor", "mentors-choice", "open-source-streak", "issue-resolution-leader", "general",
+] as const;
+export const CONTEXT_TYPES = ["approved-leave", "research", "non-code-contribution", "external-project", "personal-circumstances"] as const;
+
+export type TaskStatus = (typeof TASK_STATUSES)[number];
+export type NoteType = (typeof NOTE_TYPES)[number];
+export type Badge = (typeof BADGES)[number];
+export type ContextType = (typeof CONTEXT_TYPES)[number];
+
+export const TASK_STATUS_LABELS: Record = {
+ planned: "Planned", "in-progress": "Working on it", blocked: "Blocked", "in-review": "In review", done: "Done",
+};
+export const NOTE_TYPE_LABELS: Record = {
+ learned: "What they learned", "difficult-problem": "Difficult problem solved", "technical-skill": "Technical skill improved",
+ communication: "Communication", teamwork: "Teamwork", initiative: "Initiative", "problem-solving": "Problem-solving",
+ "handling-feedback": "Handling feedback", "helped-others": "Helped other contributors", research: "Research completed",
+ challenge: "Challenge faced", "overcame-challenge": "How they overcame it", "mentor-observation": "Mentor observation", "student-reflection": "Student reflection",
+};
+export const BADGE_LABELS: Record = {
+ "first-pull-request": "First Pull Request", "first-merged-pull-request": "First Merged Pull Request", "consistent-contributor": "Consistent Contributor",
+ "documentation-champion": "Documentation Champion", "bug-finder": "Bug Finder", "helpful-reviewer": "Helpful Reviewer",
+ "community-contributor": "Community Contributor", "mentors-choice": "Mentor’s Choice", "open-source-streak": "Open Source Streak",
+ "issue-resolution-leader": "Issue Resolution Leader", general: "Appreciation",
+};
+export const CONTEXT_LABELS: Record = {
+ "approved-leave": "Approved leave", research: "Research work", "non-code-contribution": "Non-code contribution",
+ "external-project": "External project work", "personal-circumstances": "Health or personal circumstances",
+};
+
+/* ---------- validation ---------- */
+
+const text = (max: number) => z.string().trim().max(max);
+const required = (max: number) => z.string().trim().min(1, "Required").max(max);
+const optionalText = (max: number) => text(max).default("");
+const date = z.string().refine(isIsoDate, "Use a real date, yyyy-mm-dd");
+/** Only http(s): a stored `javascript:` link would run when a mentor clicks it. */
+const url = z.string().trim().max(500).refine((v) => v === "" || /^https?:\/\/[^\s]+$/i.test(v), "Must be an http(s) link").default("");
+
+const base = { github: z.string().trim().min(1).max(39) };
+
+export const taskInput = z.object({
+ ...base,
+ kind: z.literal("task"),
+ title: required(140),
+ repo: optionalText(100),
+ issueNumber: z.number().int().positive().max(10_000_000).nullable().default(null),
+ issueUrl: url,
+ description: optionalText(2000),
+ difficulty: z.enum(DIFFICULTIES),
+ status: z.enum(TASK_STATUSES),
+ assignedAt: date,
+ dueDate: date.nullable().default(null),
+ blockers: optionalText(1000),
+ nextAction: optionalText(500),
+}).refine((t) => !t.dueDate || t.dueDate >= t.assignedAt, { message: "Due date cannot be before the assigned date", path: ["dueDate"] });
+
+export const noteInput = z.object({
+ ...base,
+ kind: z.literal("note"),
+ noteType: z.enum(NOTE_TYPES),
+ text: required(2000),
+ /** "mentors" stays private; "student" is for the student view to show once it exists. */
+ visibility: z.enum(["mentors", "student"]).default("mentors"),
+ relatedTask: optionalText(80),
+});
+
+export const appreciationInput = z.object({
+ ...base,
+ kind: z.literal("appreciation"),
+ title: required(120),
+ reason: required(1000),
+ badge: z.enum(BADGES).default("general"),
+ sourceUrl: url,
+ date,
+});
+
+export const reviewInput = z.object({
+ ...base,
+ kind: z.literal("review"),
+ weekStart: date.refine((d) => weekStart(d) === d, "Week must start on a Monday"),
+ completed: optionalText(2000),
+ inProgress: optionalText(2000),
+ learned: optionalText(2000),
+ difficult: optionalText(2000),
+ helpNeeded: optionalText(1000),
+ nextWeek: optionalText(2000),
+ blockers: optionalText(1000),
+ confidence: z.number().int().min(1).max(5),
+ hours: z.number().min(0).max(80).nullable().default(null),
+ mentorFeedback: optionalText(2000),
+});
+
+export const contextInput = z.object({
+ ...base,
+ kind: z.literal("context"),
+ contextType: z.enum(CONTEXT_TYPES),
+ startDate: date,
+ endDate: date,
+ text: optionalText(1000),
+}).refine((c) => c.startDate <= c.endDate, { message: "End date cannot be before the start date", path: ["endDate"] })
+ .refine((c) => dayNum(c.endDate) - dayNum(c.startDate) < 370, { message: "A single entry can cover at most a year", path: ["endDate"] });
+
+export const recordInput = z.discriminatedUnion("kind", [taskInput, noteInput, appreciationInput, reviewInput, contextInput]);
+export type RecordInput = z.infer;
+
+export type TrackerRecord = RecordInput & {
+ id: string;
+ /** USN of the member who wrote it; mentors can only change their own. */
+ authorUsn: string;
+ authorName: string;
+ createdAt: string;
+ updatedAt: string;
+ /** Set when a task first becomes "done"; cleared if it is reopened. */
+ completedAt?: string | null;
+ dedupeKey: string;
+};
+
+/* ---------- helpers ---------- */
+
+/** What makes two records the same record. Used to refuse double entry. */
+export function dedupeKey(r: RecordInput): string {
+ const norm = (s: string) => s.trim().toLowerCase().replace(/\s+/g, " ");
+ switch (r.kind) {
+ case "task": return `task|${norm(r.repo)}|${r.issueNumber ?? ""}|${norm(r.title)}|${r.assignedAt}`;
+ case "note": return `note|${r.noteType}|${norm(r.text)}`;
+ case "appreciation": return `appreciation|${r.date}|${norm(r.title)}`;
+ case "review": return `review|${r.weekStart}`;
+ case "context": return `context|${r.contextType}|${r.startDate}|${r.endDate}`;
+ }
+}
+
+export const byKind = (records: TrackerRecord[], kind: K) =>
+ records.filter((r): r is Extract => r.kind === kind);
+
+/** Every day covered by a mentor-recorded leave or context entry, for the consistency score. */
+export function excusedDays(records: TrackerRecord[]): string[] {
+ const days = new Set();
+ for (const c of byKind(records, "context")) {
+ const len = dayNum(c.endDate) - dayNum(c.startDate);
+ for (let i = 0; i <= len && i < 370; i++) days.add(addDays(c.startDate, i));
+ }
+ return [...days];
+}
+
+/** Records as timeline events, so notes, tasks and reviews sit beside PRs. */
+export function recordEvents(records: TrackerRecord[]): ActivityEvent[] {
+ const out: ActivityEvent[] = [];
+ for (const r of records) {
+ const link = `record:${r.id}`;
+ switch (r.kind) {
+ case "task":
+ if (r.status === "done" && r.completedAt) out.push({ date: r.completedAt.slice(0, 10), kind: "task_completed", title: r.title, detail: [r.repo, r.issueNumber ? `#${r.issueNumber}` : ""].filter(Boolean).join(""), url: r.issueUrl || link });
+ break;
+ case "appreciation":
+ out.push({ date: r.date, kind: "appreciation", title: `${BADGE_LABELS[r.badge]}: ${r.title}`, detail: `${r.reason.slice(0, 100)} · from ${r.authorName}`, url: r.sourceUrl || link });
+ break;
+ case "review":
+ out.push({ date: addDays(r.weekStart, 6), kind: "weekly_review", title: `Weekly review (confidence ${r.confidence}/5)`, detail: r.blockers ? `Blockers: ${r.blockers.slice(0, 100)}` : "No blockers reported", url: link });
+ break;
+ case "note":
+ if (r.noteType === "mentor-observation") out.push({ date: r.createdAt.slice(0, 10), kind: "mentor_note", title: NOTE_TYPE_LABELS[r.noteType], detail: r.text.slice(0, 140), url: link });
+ break;
+ case "context":
+ break;
+ }
+ }
+ return out.filter((e) => isIsoDate(e.date));
+}
+
+export interface CurrentWork {
+ task: Extract | null;
+ open: number;
+ overdue: number;
+ blocked: number;
+}
+
+/** The task a mentor should see first: blocked, then in progress, then the rest, newest assigned first. */
+export function currentWork(records: TrackerRecord[], today: string): CurrentWork {
+ const open = byKind(records, "task").filter((t) => t.status !== "done");
+ const rank: Record = { blocked: 0, "in-progress": 1, "in-review": 2, planned: 3, done: 4 };
+ const sorted = [...open].sort((a, b) => rank[a.status] - rank[b.status] || b.assignedAt.localeCompare(a.assignedAt));
+ return {
+ task: sorted[0] ?? null,
+ open: open.length,
+ overdue: open.filter((t) => t.dueDate !== null && t.dueDate < today).length,
+ blocked: open.filter((t) => t.status === "blocked").length,
+ };
+}
diff --git a/lib/tracker/rows.test.ts b/lib/tracker/rows.test.ts
index b8dd527..10b603c 100644
--- a/lib/tracker/rows.test.ts
+++ b/lib/tracker/rows.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { filterRows, NO_FILTERS, sortRows, toRow, type TrackerRow } from "./rows";
+import { averageConsistency, filterRows, NO_FILTERS, sortRows, toRow, type TrackerRow } from "./rows";
import { needsAttention, summarize } from "./summary";
import type { TrackerStudent } from "./types";
@@ -40,7 +40,7 @@ describe("needsAttention / summarize", () => {
});
describe("filterRows / sortRows", () => {
- const rows: TrackerRow[] = people.map(toRow);
+ const rows: TrackerRow[] = people.map((p) => toRow(p));
it("searches name, handle, repo and PR titles case-insensitively", () => {
expect(filterRows(rows, { ...NO_FILTERS, query: "STUCK" }).map((r) => r.github)).toEqual(["stuck1"]);
@@ -65,3 +65,25 @@ describe("filterRows / sortRows", () => {
expect(rows).toEqual(copy);
});
});
+
+describe("direction and consistency on rows", () => {
+ it("carries a direction and consistency, and filters by direction", () => {
+ const rows = people.map((p) => toRow(p));
+ expect(rows.every((r) => ["improving", "stable", "declining", "insufficient"].includes(r.direction))).toBe(true);
+ expect(filterRows(rows, { ...NO_FILTERS, direction: "insufficient" }).length).toBe(rows.filter((r) => r.direction === "insufficient").length);
+ expect(filterRows(rows, { ...NO_FILTERS, direction: "declining" }).every((r) => r.direction === "declining")).toBe(true);
+ });
+
+ it("averages only the students that have a score", () => {
+ const base = toRow(people[0]);
+ expect(averageConsistency([])).toBeNull();
+ expect(averageConsistency([{ ...base, consistency: null }])).toBeNull();
+ expect(averageConsistency([{ ...base, consistency: 80 }, { ...base, consistency: 40 }, { ...base, consistency: null }])).toBe(60);
+ });
+
+ it("sorts by consistency with unscored students last when descending", () => {
+ const base = toRow(people[0]);
+ const sorted = sortRows([{ ...base, github: "a", consistency: null }, { ...base, github: "b", consistency: 90 }, { ...base, github: "c", consistency: 10 }], "consistency", "desc");
+ expect(sorted.map((r) => r.github)).toEqual(["b", "c", "a"]);
+ });
+});
diff --git a/lib/tracker/rows.ts b/lib/tracker/rows.ts
index 392f900..f3a6b9c 100644
--- a/lib/tracker/rows.ts
+++ b/lib/tracker/rows.ts
@@ -1,3 +1,6 @@
+import { asOfDate, buildEvents, consistencyScore, progressDirection, resolveRange, sparkline, type Direction } from "./metrics";
+import { currentWork, excusedDays, recordEvents, type TrackerRecord } from "./records";
+import { engagementFor, type Engagement } from "./engagement";
import { needsAttention } from "./summary";
import type { Grade, StatusKey, TrackerStudent } from "./types";
@@ -19,11 +22,37 @@ export interface TrackerRow {
daysSinceActivity: number | null;
lastStudentActivity: string | null;
attention: boolean;
+ /** Last-month activity compared with the month before; see lib/tracker/metrics.ts. */
+ direction: Direction;
+ /** 0-100 over the last month, or `null` when there is no activity to score. */
+ consistency: number | null;
+ /** Activity per week for the last 12 weeks, oldest first: the shape drawn in the table. */
+ spark: number[];
+ /** What they are doing now and why; see lib/tracker/engagement.ts. */
+ engagement: Engagement;
+ engagementGroup: string;
+ engagementReason: string;
+ /** Title of the most urgent open task a mentor recorded, if any. */
+ currentTask: string | null;
/** Name, handle, repos and PR titles, lower-cased, for the search box. */
haystack: string;
}
-export function toRow(s: TrackerStudent): TrackerRow {
+/** Text of a record worth finding by search: task and issue titles, note content. */
+function recordText(r: TrackerRecord): string[] {
+ switch (r.kind) {
+ case "task": return [r.title, r.repo, r.description];
+ case "note": return [r.text];
+ case "appreciation": return [r.title, r.reason];
+ case "review": return [r.completed, r.learned, r.blockers];
+ case "context": return [r.text];
+ }
+}
+
+export function toRow(s: TrackerStudent, records: TrackerRecord[] = []): TrackerRow {
+ const events = buildEvents(s, recordEvents(records));
+ const range = resolveRange("1m", asOfDate(s));
+ const eng = engagementFor(s, records);
return {
github: s.github,
name: s.name,
@@ -38,7 +67,14 @@ export function toRow(s: TrackerStudent): TrackerRow {
daysSinceActivity: s.daysSinceActivity,
lastStudentActivity: s.lastStudentActivity,
attention: needsAttention(s),
- haystack: [s.name, s.github, ...s.repos, ...s.prs.map((p) => p.title)].join("\n").toLowerCase(),
+ direction: range ? progressDirection(events, range).direction : "insufficient",
+ consistency: range ? consistencyScore(events, range, excusedDays(records))?.score ?? null : null,
+ spark: sparkline(events, asOfDate(s)),
+ engagement: eng.kind,
+ engagementGroup: eng.group,
+ engagementReason: eng.reason,
+ currentTask: currentWork(records, asOfDate(s)).task?.title ?? null,
+ haystack: [s.name, s.github, ...s.repos, ...s.prs.map((p) => p.title), ...records.flatMap(recordText), eng.reason].join("\n").toLowerCase(),
};
}
@@ -47,11 +83,19 @@ export interface Filters {
status: StatusKey | "all";
grade: Grade | "all";
attentionOnly: boolean;
+ direction: Direction | "all";
+ engagement: Engagement | "all";
}
-export const NO_FILTERS: Filters = { query: "", status: "all", grade: "all", attentionOnly: false };
+export const NO_FILTERS: Filters = { query: "", status: "all", grade: "all", attentionOnly: false, direction: "all", engagement: "all" };
-export type SortKey = "name" | "merged" | "total" | "waiting" | "activity" | "grade";
+export type SortKey = "name" | "merged" | "total" | "waiting" | "activity" | "grade" | "consistency";
+
+/** Mean consistency over students who have one; `null` when nobody does. */
+export function averageConsistency(rows: TrackerRow[]): number | null {
+ const scored = rows.filter((r) => r.consistency !== null) as (TrackerRow & { consistency: number })[];
+ return scored.length === 0 ? null : Math.round(scored.reduce((sum, r) => sum + r.consistency, 0) / scored.length);
+}
export function filterRows(rows: TrackerRow[], f: Filters): TrackerRow[] {
const q = f.query.trim().toLowerCase();
@@ -59,6 +103,8 @@ export function filterRows(rows: TrackerRow[], f: Filters): TrackerRow[] {
if (f.status !== "all" && r.status !== f.status) return false;
if (f.grade !== "all" && r.grade !== f.grade) return false;
if (f.attentionOnly && !r.attention) return false;
+ if (f.engagement !== "all" && r.engagement !== f.engagement) return false;
+ if (f.direction !== "all" && r.direction !== f.direction) return false;
return !q || r.haystack.includes(q);
});
}
@@ -72,6 +118,7 @@ export function sortRows(rows: TrackerRow[], key: SortKey, dir: "asc" | "desc"):
case "waiting": return r.waitingDays ?? -1;
case "activity": return r.daysSinceActivity ?? Number.MAX_SAFE_INTEGER;
case "grade": return r.grade ?? "Z";
+ case "consistency": return r.consistency ?? -1;
}
};
const sign = dir === "asc" ? 1 : -1;
diff --git a/lib/tracker/store.ts b/lib/tracker/store.ts
index 638c9ab..49566e1 100644
--- a/lib/tracker/store.ts
+++ b/lib/tracker/store.ts
@@ -1,4 +1,5 @@
import { club, COLLECTIONS } from "@/lib/firebase/collections";
+import { demoEnabled, demoStore } from "./demo";
import type { TrackerStudent } from "./types";
/**
@@ -10,15 +11,21 @@ const tracker = () => club(COLLECTIONS.firstYearTracker);
export const docId = (github: string) => github.trim().toLowerCase();
export async function loadStudents(): Promise {
+ if (demoEnabled()) return [...demoStore().students.values()].sort((a, b) => a.name.localeCompare(b.name));
const snap = await tracker().get();
return snap.docs.map((d) => d.data()).sort((a, b) => a.name.localeCompare(b.name));
}
export async function loadStudent(github: string): Promise {
+ if (demoEnabled()) return demoStore().students.get(docId(github)) ?? null;
const snap = await tracker().doc(docId(github)).get();
return snap.exists ? (snap.data() as TrackerStudent) : null;
}
export async function saveStudent(student: TrackerStudent): Promise {
+ if (demoEnabled()) {
+ demoStore().students.set(docId(student.github), student);
+ return;
+ }
await tracker().doc(docId(student.github)).set(student);
}
diff --git a/lib/tracker/sync.ts b/lib/tracker/sync.ts
index 96d9f30..403a2e8 100644
--- a/lib/tracker/sync.ts
+++ b/lib/tracker/sync.ts
@@ -50,7 +50,10 @@ async function syncOne(student: TrackerStudent, now: Date): Promise<"updated" |
return "updated";
} catch (error) {
const limited = error instanceof GithubError && (error.status === 403 || error.status === 429);
- const message = error instanceof Error ? error.message : "Unknown error";
+ const notFound = error instanceof GithubError && (error.status === 422 || error.status === 404);
+ const message = notFound
+ ? "GitHub can't find or search this username. Check the handle is spelled right and the account still exists"
+ : error instanceof Error ? error.message : "Unknown error";
// Keep the old numbers; just record why they are stale.
await saveStudent(applyFailure(student, message));
return limited ? "rate-limited" : "failed";
diff --git a/lib/tracker/test-fixtures.ts b/lib/tracker/test-fixtures.ts
new file mode 100644
index 0000000..b99bcde
--- /dev/null
+++ b/lib/tracker/test-fixtures.ts
@@ -0,0 +1,33 @@
+import type { TrackerPR, TrackerStudent } from "./types";
+
+/** Shared builders for tracker tests. */
+export function pr(over: Partial & { url: string }): TrackerPR {
+ return { repo: "o/r", number: 1, title: "T", state: "open", createdAt: "2026-11-01", closedAt: null, lastUpdate: null, waitingDays: null, blocker: null, credible: false, teaching: false, approved: false, ...over };
+}
+
+export function student(over: Partial = {}): TrackerStudent {
+ return {
+ github: "a", name: "A B", snapshotDate: "2026-11-13", status: "merged", statusLabel: "Merged", priority: "Completed", grade: "B",
+ gsocReadiness: "", gsocRank: null, gsocScore: null, gsocNote: null,
+ totals: { total: 0, open: 0, merged: 0, closed: 0, credibleMerges: 0, credibleOpen: 0, mergeSuccessPct: null, titleHygienePct: null, approvals: 0, reviewFeedbackHandled: 0, projects: 0 },
+ repos: [], lastStudentActivity: null, daysSinceActivity: null, daysSinceMaintainer: null, waitingDays: null, blocker: null,
+ recommendation: null, suggestedMessage: null, progress: { prevTotal: 0, prevMerged: 0, prevGrade: null, gradeChange: "", summary: "" },
+ prs: [], appreciation: [], syncedAt: null, syncError: null, ...over,
+ };
+}
+
+import type { TrackerRecord } from "./records";
+
+let seq = 0;
+/** A record with sensible defaults; pass the fields that matter to the test. */
+export function record(kind: K, over: Record = {}): Extract {
+ const defaults: Record> = {
+ task: { title: "Fix bug", repo: "o/r", issueNumber: 12, issueUrl: "", description: "", difficulty: "medium", status: "in-progress", assignedAt: "2026-11-02", dueDate: null, blockers: "", nextAction: "" },
+ note: { noteType: "learned", text: "Learned rebasing", visibility: "mentors", relatedTask: "" },
+ appreciation: { title: "Great docs", reason: "Clear and kind", badge: "documentation-champion", sourceUrl: "", date: "2026-11-05" },
+ review: { weekStart: "2026-11-09", completed: "", inProgress: "", learned: "", difficult: "", helpNeeded: "", nextWeek: "", blockers: "", confidence: 4, hours: null, mentorFeedback: "" },
+ context: { contextType: "approved-leave", startDate: "2026-11-01", endDate: "2026-11-07", text: "" },
+ };
+ seq++;
+ return { id: `r${seq}`, github: "a", kind, authorUsn: "u1", authorName: "Mentor", createdAt: "2026-11-06T10:00:00.000Z", updatedAt: "2026-11-06T10:00:00.000Z", dedupeKey: `k${seq}`, ...defaults[kind], ...over } as Extract;
+}
diff --git a/lib/tracker/weekly.test.ts b/lib/tracker/weekly.test.ts
new file mode 100644
index 0000000..44a4c3a
--- /dev/null
+++ b/lib/tracker/weekly.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { buildEvents } from "./metrics";
+import { recordEvents } from "./records";
+import { pr, record, student } from "./test-fixtures";
+import { weeklySummary } from "./weekly";
+
+const WEEK = "2026-11-09";
+
+function summary(records: Parameters[0], prs = [pr({ url: "p", createdAt: "2026-11-10" })], asOf?: string) {
+ const s = student({ prs });
+ return weeklySummary(s, records, buildEvents(s, recordEvents(records)), WEEK, [], asOf);
+}
+
+describe("weeklySummary", () => {
+ it("covers Monday to Sunday", () => {
+ expect(summary([]).week).toEqual({ start: "2026-11-09", end: "2026-11-15" });
+ });
+
+ it("lists new PRs, merges and finished tasks for the week only", () => {
+ const s = summary(
+ [record("task", { title: "Finished", status: "done", completedAt: "2026-11-11T00:00:00.000Z" }), record("task", { title: "Old", status: "done", completedAt: "2026-10-01T00:00:00.000Z" })],
+ [pr({ url: "m", title: "Merged one", state: "merged", createdAt: "2026-11-02", closedAt: "2026-11-12" }), pr({ url: "o", title: "New one", createdAt: "2026-11-10" })],
+ );
+ expect(s.completed).toEqual(expect.arrayContaining(["Merged: Merged one", "Task done: Finished"]));
+ expect(s.completed.join()).not.toContain("Old");
+ expect(s.newContributions).toEqual(["New one"]);
+ });
+
+ it("reports a task due this week and not finished as a missed goal", () => {
+ const s = summary([record("task", { title: "Late", status: "in-progress", dueDate: "2026-11-12" }), record("task", { title: "OnTime", status: "done", dueDate: "2026-11-12", completedAt: "2026-11-11T00:00:00.000Z" })]);
+ expect(s.missedGoals).toEqual(["Late was due 2026-11-12"]);
+ });
+
+ it("does not call a task missed before its due date has passed", () => {
+ const late = record("task", { title: "Soon", status: "in-progress", dueDate: "2026-11-14" });
+ expect(summary([late], undefined, "2026-11-13").missedGoals).toEqual([]);
+ expect(summary([late], undefined, "2026-11-15").missedGoals).toEqual(["Soon was due 2026-11-14"]);
+ expect(summary([record("task", { title: "Today", status: "planned", dueDate: "2026-11-13" })], undefined, "2026-11-13").missedGoals).toEqual([]);
+ });
+
+ it("shows task statuses as words, not codes", () => {
+ expect(summary([record("task", { title: "R", status: "in-review" })]).ongoing.join()).toContain("(in review)");
+ });
+
+ it("collects blockers from blocked tasks and the week's review", () => {
+ const s = summary([record("task", { title: "T", status: "blocked", blockers: "Waiting on CI" }), record("review", { weekStart: WEEK, blockers: "No laptop" })]);
+ expect(s.blockers).toEqual(["T: Waiting on CI", "Weekly review: No laptop"]);
+ expect(s.nextSteps.join(" ")).toContain("blockers");
+ });
+
+ it("asks for a review when none was recorded, and surfaces help requests", () => {
+ expect(summary([]).nextSteps.join(" ")).toContain("No weekly review");
+ expect(summary([record("review", { weekStart: WEEK, helpNeeded: "Git rebase" })]).nextSteps[0]).toContain("Git rebase");
+ });
+
+ it("lists open work as ongoing", () => {
+ const s = summary([record("task", { title: "Active", status: "in-progress" })]);
+ expect(s.ongoing).toEqual(expect.arrayContaining(["Active (working on it)", "Open PR: T"]));
+ });
+});
diff --git a/lib/tracker/weekly.ts b/lib/tracker/weekly.ts
new file mode 100644
index 0000000..85acda3
--- /dev/null
+++ b/lib/tracker/weekly.ts
@@ -0,0 +1,60 @@
+import { addDays, consistencyScore, inRange, progressDirection, type ActivityEvent, type DateRange, type DirectionResult } from "./metrics";
+import { byKind, TASK_STATUS_LABELS, type TrackerRecord } from "./records";
+import type { TrackerStudent } from "./types";
+
+/**
+ * The automatic weekly summary for one Monday-to-Sunday week: what was
+ * finished, what is still going, what slipped, and what to do next. Built from
+ * the same events and records as everything else, so it cannot disagree.
+ */
+export interface WeeklySummary {
+ week: DateRange;
+ completed: string[];
+ ongoing: string[];
+ missedGoals: string[];
+ newContributions: string[];
+ blockers: string[];
+ progress: DirectionResult;
+ /** Consistency over the four weeks ending this week, minus the four before. `null` when either is unscored. */
+ consistencyChange: number | null;
+ nextSteps: string[];
+}
+
+export function weeklySummary(s: TrackerStudent, records: TrackerRecord[], events: ActivityEvent[], weekStart: string, excused: string[] = [], asOf?: string): WeeklySummary {
+ const week: DateRange = { start: weekStart, end: addDays(weekStart, 6) };
+ /** A due date only counts as missed once it has passed; a week still in progress has later days to go. */
+ const today = asOf ?? week.end;
+ const inside = inRange(events, week);
+ const tasks = byKind(records, "task");
+ const review = byKind(records, "review").find((r) => r.weekStart === weekStart) ?? null;
+
+ const completed = [
+ ...inside.filter((e) => e.kind === "pr_merged").map((e) => `Merged: ${e.title}`),
+ ...inside.filter((e) => e.kind === "task_completed").map((e) => `Task done: ${e.title}`),
+ ];
+ const ongoing = [
+ ...tasks.filter((t) => t.status !== "done" && t.assignedAt <= week.end).map((t) => `${t.title} (${TASK_STATUS_LABELS[t.status].toLowerCase()})`),
+ ...s.prs.filter((p) => p.state === "open" && p.createdAt && p.createdAt <= week.end).map((p) => `Open PR: ${p.title}`),
+ ];
+ const missedGoals = tasks
+ .filter((t) => t.dueDate !== null && t.dueDate >= week.start && t.dueDate <= week.end && t.dueDate < today && !(t.status === "done" && t.completedAt && t.completedAt.slice(0, 10) <= t.dueDate))
+ .map((t) => `${t.title} was due ${t.dueDate}`);
+ const blockers = [
+ ...tasks.filter((t) => t.status === "blocked" && t.blockers).map((t) => `${t.title}: ${t.blockers}`),
+ ...(review?.blockers ? [`Weekly review: ${review.blockers}`] : []),
+ ];
+
+ const progress = progressDirection(events, week);
+ const mine = (range: DateRange) => consistencyScore(events, range, excused)?.score ?? null;
+ const now = mine({ start: addDays(week.end, -27), end: week.end });
+ const before = mine({ start: addDays(week.end, -55), end: addDays(week.end, -28) });
+
+ const nextSteps: string[] = [];
+ if (review?.helpNeeded) nextSteps.push(`Follow up on the help asked for: ${review.helpNeeded}`);
+ if (blockers.length) nextSteps.push("Talk through the blockers above and unblock or reassign.");
+ if (missedGoals.length) nextSteps.push("Agree a new date for the missed goals, or drop them if priorities changed.");
+ if (review === null) nextSteps.push("No weekly review was recorded for this week; ask for one.");
+ if (nextSteps.length === 0) nextSteps.push("Nothing urgent. Confirm next week's plan.");
+
+ return { week, completed, ongoing, missedGoals, newContributions: inside.filter((e) => e.kind === "pr_opened").map((e) => e.title), blockers, progress, consistencyChange: now !== null && before !== null ? now - before : null, nextSteps };
+}
diff --git a/package.json b/package.json
index 6674dec..f06c66e 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,8 @@
"set:photo": "tsx scripts/set-photo.ts",
"import:cohort": "node scripts/import-cohort-csv.mjs",
"snapshot:oss": "tsx scripts/oss-snapshot.ts",
- "import:tracker": "tsx scripts/import-tracker-sheet.ts"
+ "import:tracker": "tsx scripts/import-tracker-sheet.ts",
+ "sync:tracker": "tsx scripts/sync-tracker-all.ts"
},
"dependencies": {
"bcrypt": "^6.0.0",
diff --git a/scripts/import-tracker-sheet.ts b/scripts/import-tracker-sheet.ts
index 77d1b27..251c679 100644
--- a/scripts/import-tracker-sheet.ts
+++ b/scripts/import-tracker-sheet.ts
@@ -3,6 +3,7 @@
*
* npx tsx scripts/import-tracker-sheet.ts # dry run, writes nothing
* npx tsx scripts/import-tracker-sheet.ts --commit # writes devforge_first_year_tracker
+ * ... --commit --keep-synced # skips students already synced from GitHub
*
* The export holds who is stuck, what maintainers said and suggested nudges for
* named students. That is mentor-only material, so it goes to Firestore (read
@@ -22,6 +23,8 @@ import { summarize } from "../lib/tracker/summary";
const args = process.argv.slice(2);
const file = args.find((a) => !a.startsWith("--"));
const commit = args.includes("--commit");
+/** Leave students already refreshed from GitHub alone, so a re-import cannot overwrite live data. */
+const keepSynced = args.includes("--keep-synced");
if (!file) {
console.error("Usage: npx tsx scripts/import-tracker-sheet.ts [--commit]");
@@ -42,9 +45,11 @@ async function main() {
}
// Imported lazily so a dry run needs no Firebase credentials.
- const { saveStudent } = await import("../lib/tracker/store");
- for (const student of result.students) await saveStudent(student);
- console.log(`Wrote ${result.students.length} documents to devforge_first_year_tracker.`);
+ const { saveStudent, loadStudents } = await import("../lib/tracker/store");
+ const synced = keepSynced ? new Set((await loadStudents()).filter((s) => s.syncedAt).map((s) => s.github.toLowerCase())) : new Set();
+ const toWrite = result.students.filter((s) => !synced.has(s.github.toLowerCase()));
+ for (const student of toWrite) await saveStudent(student);
+ console.log(`Wrote ${toWrite.length} documents to devforge_first_year_tracker${synced.size ? ` (${synced.size} already synced from GitHub were left as they are)` : ""}.`);
}
main().catch((error) => {
diff --git a/scripts/sync-tracker-all.ts b/scripts/sync-tracker-all.ts
new file mode 100644
index 0000000..7e01e1c
--- /dev/null
+++ b/scripts/sync-tracker-all.ts
@@ -0,0 +1,53 @@
+/**
+ * Refreshes every tracker student from GitHub, batch by batch.
+ *
+ * npx tsx scripts/sync-tracker-all.ts
+ *
+ * Uses the same sync as the dashboard's refresh button (lib/tracker/sync.ts),
+ * which spends one GitHub search per student. It waits a minute between batches
+ * to stay inside GitHub's 30-searches-a-minute limit and backs off longer if
+ * GitHub says it is rate limiting. Students synced within the last 3 hours are
+ * skipped, so it is safe to re-run or stop at any point.
+ */
+import { config } from "dotenv";
+config({ path: ".env.local" });
+
+const WAIT_MS = 65_000;
+const RATE_LIMIT_WAIT_MS = 5 * 60_000;
+const MAX_ROUNDS = 30;
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+async function main() {
+ const { syncStale } = await import("../lib/tracker/sync");
+ const { loadStudents } = await import("../lib/tracker/store");
+
+ let outages = 0;
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
+ let report;
+ let all;
+ try {
+ report = await syncStale();
+ all = await loadStudents();
+ outages = 0;
+ } catch (error) {
+ // A dropped connection should pause the run, not end it. Finished students are already saved.
+ if (++outages > 5) throw error;
+ console.log(`network/Firestore error (${(error as Error).message.slice(0, 80)}); retrying in 30s (${outages}/5)`);
+ await sleep(30_000);
+ round--;
+ continue;
+ }
+ const synced = all.filter((s) => s.syncedAt && !s.syncError).length;
+ console.log(`round ${round}: checked ${report.checked}, updated ${report.updated}, failed ${report.failed}, rateLimited ${report.rateLimited} | ${synced}/${all.length} students synced`);
+
+ if (report.checked === 0) {
+ console.log("Nobody left to refresh.");
+ return;
+ }
+ await sleep(report.rateLimited ? RATE_LIMIT_WAIT_MS : WAIT_MS);
+ }
+ console.log("Stopped after the maximum number of rounds; run it again to continue.");
+}
+
+main().then(() => process.exit(0)).catch((e) => { console.error(e); process.exit(1); });
diff --git a/vitest.config.ts b/vitest.config.ts
index 01d65cb..c406e6e 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -1,13 +1,15 @@
import path from "path";
import { defineConfig } from "vitest/config";
-// Unit tests for pure logic in lib/. Tests live next to the code as *.test.ts.
+// Unit tests for pure logic in lib/, plus server-render smoke tests for components.
+// Tests live next to the code as *.test.ts(x).
export default defineConfig({
resolve: {
alias: { "@": path.resolve(__dirname) },
},
+ esbuild: { jsx: "automatic" },
test: {
- include: ["lib/**/*.test.ts"],
+ include: ["lib/**/*.test.ts", "components/**/*.test.tsx"],
environment: "node",
},
});