feat: Member Effectiveness Score + Representation Alignment View (v0.9.9)

Member Effectiveness Score
- New BillCosponsor table (migration 0018) with per-bill co-sponsor
  party data required for the bipartisan multiplier
- bill_category column on Bill (substantive | commemorative | administrative)
  set by a cheap one-shot LLM call after each brief is generated
- effectiveness_score / percentile / tier columns on Member
- New bill_classifier.py worker with 5 tasks:
    classify_bill_category  — triggered from llm_processor after brief
    fetch_bill_cosponsors   — triggered from congress_poller on new bill
    calculate_effectiveness_scores — nightly at 5 AM UTC
    backfill_bill_categories / backfill_all_bill_cosponsors — one-time
- Scoring: distance-traveled pts × bipartisan (1.5×) × substance (0.1×
  for commemorative) × leadership (1.2× for committee chairs)
- Percentile normalised within (seniority tier × party) buckets
- Effectiveness card on member detail page with colour-coded bar
- Admin panel: 3 new backfill/calculate controls in Maintenance section

Representation Alignment View
- New GET /api/alignment endpoint: cross-references user's stanced bill
  follows (pocket_veto/pocket_boost) with followed members' vote positions
- Efficient bulk queries — no N+1 loops
- New /alignment page with ranked member list and alignment bars
- Alignment added to sidebar nav (auth-required)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Jack Levy
2026-03-14 18:05:09 -04:00
parent cba19c7bb3
commit d0da0b8dce
19 changed files with 910 additions and 5 deletions

View File

@@ -0,0 +1,163 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { alignmentAPI } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
import type { AlignmentScore } from "@/lib/types";
function partyColor(party?: string) {
if (!party) return "bg-muted text-muted-foreground";
const p = party.toLowerCase();
if (p.includes("republican") || p === "r") return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
if (p.includes("democrat") || p === "d") return "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400";
return "bg-muted text-muted-foreground";
}
function AlignmentBar({ pct }: { pct: number }) {
const color =
pct >= 66 ? "bg-emerald-500" : pct >= 33 ? "bg-amber-500" : "bg-red-500";
return (
<div className="flex-1 h-1.5 bg-muted rounded overflow-hidden">
<div className={`h-full rounded ${color}`} style={{ width: `${pct}%` }} />
</div>
);
}
function MemberRow({ member }: { member: AlignmentScore }) {
const pct = member.alignment_pct;
return (
<Link
href={`/members/${member.bioguide_id}`}
className="flex items-center gap-3 py-3 hover:bg-accent/50 rounded-md px-2 -mx-2 transition-colors"
>
{member.photo_url ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={member.photo_url}
alt={member.name}
className="w-9 h-9 rounded-full object-cover shrink-0 border border-border"
/>
) : (
<div className="w-9 h-9 rounded-full bg-muted flex items-center justify-center shrink-0 border border-border text-xs font-medium text-muted-foreground">
{member.name.charAt(0)}
</div>
)}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium truncate">{member.name}</span>
<span className="text-sm font-mono font-semibold shrink-0">
{pct != null ? `${Math.round(pct)}%` : "—"}
</span>
</div>
<div className="flex items-center gap-2 mt-1">
{member.party && (
<span className={`text-xs px-1.5 py-0.5 rounded font-medium ${partyColor(member.party)}`}>
{member.party.charAt(0)}
</span>
)}
{member.state && (
<span className="text-xs text-muted-foreground">{member.state}</span>
)}
{pct != null && <AlignmentBar pct={pct} />}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{member.aligned} aligned · {member.opposed} opposed · {member.total} overlapping vote{member.total !== 1 ? "s" : ""}
</p>
</div>
</Link>
);
}
export default function AlignmentPage() {
const currentUser = useAuthStore((s) => s.user);
const { data, isLoading } = useQuery({
queryKey: ["alignment"],
queryFn: () => alignmentAPI.get(),
enabled: !!currentUser,
staleTime: 5 * 60 * 1000,
});
if (!currentUser) {
return (
<div className="text-center py-20 space-y-3">
<p className="text-muted-foreground">Sign in to see your representation alignment.</p>
<Link href="/login" className="text-sm text-primary hover:underline">Sign in </Link>
</div>
);
}
if (isLoading) {
return <div className="text-center py-20 text-muted-foreground text-sm">Loading alignment data</div>;
}
const members = data?.members ?? [];
const hasStance = (data?.total_bills_with_stance ?? 0) > 0;
const hasFollowedMembers = members.length > 0 || (data?.total_bills_with_votes ?? 0) > 0;
return (
<div className="space-y-6 max-w-xl">
<div>
<h1 className="text-2xl font-bold">Representation Alignment</h1>
<p className="text-sm text-muted-foreground mt-1">
How often do your followed members vote with your bill positions?
</p>
</div>
{/* How it works */}
<div className="bg-card border border-border rounded-lg p-4 text-sm space-y-1.5">
<p className="font-medium">How this works</p>
<p className="text-muted-foreground leading-relaxed">
For every bill you follow with <strong>Pocket Boost</strong> or <strong>Pocket Veto</strong>, we check
how each of your followed members voted on that bill. A Yea vote on a boosted bill counts as
aligned; a Nay vote on a vetoed bill counts as aligned. All other combinations count as opposed.
Not Voting and Present are excluded.
</p>
{data && (
<p className="text-xs text-muted-foreground pt-1">
{data.total_bills_with_stance} bill{data.total_bills_with_stance !== 1 ? "s" : ""} with a stance ·{" "}
{data.total_bills_with_votes} had roll-call votes
</p>
)}
</div>
{/* Empty states */}
{!hasStance && (
<div className="text-center py-12 text-muted-foreground space-y-2">
<p className="text-sm">No bill stances yet.</p>
<p className="text-xs">
Follow some bills with{" "}
<Link href="/bills" className="text-primary hover:underline">Pocket Boost or Pocket Veto</Link>{" "}
to start tracking alignment.
</p>
</div>
)}
{hasStance && members.length === 0 && (
<div className="text-center py-12 text-muted-foreground space-y-2">
<p className="text-sm">No overlapping votes found yet.</p>
<p className="text-xs">
Make sure you&apos;re{" "}
<Link href="/members" className="text-primary hover:underline">following some members</Link>
, and that those members have voted on bills you&apos;ve staked a position on.
</p>
</div>
)}
{/* Member list */}
{members.length > 0 && (
<div className="bg-card border border-border rounded-lg p-4">
<div className="divide-y divide-border">
{members.map((m) => (
<MemberRow key={m.bioguide_id} member={m} />
))}
</div>
</div>
)}
</div>
);
}

View File

@@ -187,6 +187,42 @@ export default function MemberDetailPage({ params }: { params: Promise<{ id: str
</div>
)}
{/* Effectiveness Score */}
{member.effectiveness_score != null && (
<div className="bg-card border border-border rounded-lg p-4 space-y-3">
<h3 className="text-sm font-semibold">Effectiveness Score</h3>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Score</span>
<span className="font-medium">{member.effectiveness_score.toFixed(1)}</span>
</div>
{member.effectiveness_percentile != null && (
<>
<div className="h-1.5 bg-muted rounded overflow-hidden">
<div
className={`h-full rounded transition-all ${
member.effectiveness_percentile >= 66
? "bg-emerald-500"
: member.effectiveness_percentile >= 33
? "bg-amber-500"
: "bg-red-500"
}`}
style={{ width: `${member.effectiveness_percentile}%` }}
/>
</div>
<p className="text-xs text-muted-foreground">
{Math.round(member.effectiveness_percentile)}th percentile
{member.effectiveness_tier ? ` among ${member.effectiveness_tier} members` : ""}
</p>
</>
)}
<p className="text-xs text-muted-foreground leading-relaxed">
Measures legislative output: how far sponsored bills travel, bipartisan support, substance, and committee leadership.
</p>
</div>
</div>
)}
{/* Service history */}
{termsSorted.length > 0 && (
<div className="bg-card border border-border rounded-lg p-4 space-y-3">

View File

@@ -22,7 +22,7 @@ import {
Wrench,
} from "lucide-react";
import Link from "next/link";
import { settingsAPI, adminAPI, notificationsAPI, type AdminUser, type LLMModel, type ApiHealthResult } from "@/lib/api";
import { settingsAPI, adminAPI, notificationsAPI, type AdminUser, type LLMModel, type ApiHealthResult, alignmentAPI } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
function relativeTime(isoStr: string): string {
@@ -862,6 +862,27 @@ export default function SettingsPage() {
}
const maintenance: ControlItem[] = [
{
key: "cosponsors",
name: "Backfill Co-sponsors",
description: "Fetch co-sponsor lists from Congress.gov for all bills. Required for bipartisan multiplier in effectiveness scoring.",
fn: adminAPI.backfillCosponsors,
status: "on-demand",
},
{
key: "categories",
name: "Classify Bill Categories",
description: "Run a lightweight LLM call on each bill to classify it as substantive, commemorative, or administrative. Used to weight effectiveness scores.",
fn: adminAPI.backfillCategories,
status: "on-demand",
},
{
key: "effectiveness",
name: "Calculate Effectiveness Scores",
description: "Score all members by legislative output, bipartisanship, bill substance, and committee leadership. Runs automatically nightly at 5 AM UTC.",
fn: adminAPI.calculateEffectiveness,
status: "on-demand",
},
{
key: "backfill-actions",
name: "Backfill All Action Histories",

View File

@@ -12,6 +12,7 @@ import {
Heart,
Bell,
Settings,
BarChart2,
Landmark,
LogOut,
X,
@@ -27,6 +28,7 @@ const NAV = [
{ href: "/members", label: "Members", icon: Users, adminOnly: false, requiresAuth: false },
{ href: "/topics", label: "Topics", icon: Tags, adminOnly: false, requiresAuth: false },
{ href: "/following", label: "Following", icon: Heart, adminOnly: false, requiresAuth: true },
{ href: "/alignment", label: "Alignment", icon: BarChart2, adminOnly: false, requiresAuth: true },
{ href: "/collections", label: "Collections", icon: Bookmark, adminOnly: false, requiresAuth: true },
{ href: "/notifications", label: "Notifications", icon: Bell, adminOnly: false, requiresAuth: true },
{ href: "/how-it-works", label: "How it works", icon: HelpCircle, adminOnly: false, requiresAuth: false },

View File

@@ -1,5 +1,6 @@
import axios from "axios";
import type {
AlignmentData,
Bill,
BillAction,
BillDetail,
@@ -303,4 +304,16 @@ export const adminAPI = {
apiClient.get<{ status: string; batch_id?: string; doc_count?: number; submitted_at?: string }>(
"/api/admin/llm-batch-status"
).then((r) => r.data),
backfillCosponsors: () =>
apiClient.post("/api/admin/backfill-cosponsors").then((r) => r.data),
backfillCategories: () =>
apiClient.post("/api/admin/backfill-categories").then((r) => r.data),
calculateEffectiveness: () =>
apiClient.post("/api/admin/calculate-effectiveness").then((r) => r.data),
};
// Alignment
export const alignmentAPI = {
get: () =>
apiClient.get<AlignmentData>("/api/alignment").then((r) => r.data),
};

View File

@@ -51,6 +51,9 @@ export interface Member {
leadership_json?: MemberLeadership[];
sponsored_count?: number;
cosponsored_count?: number;
effectiveness_score?: number;
effectiveness_percentile?: number;
effectiveness_tier?: string;
latest_trend?: MemberTrendScore;
}
@@ -119,6 +122,27 @@ export interface Bill {
latest_trend?: TrendScore;
updated_at?: string;
has_document?: boolean;
bill_category?: string;
}
export interface AlignmentScore {
bioguide_id: string;
name: string;
party?: string;
state?: string;
chamber?: string;
photo_url?: string;
effectiveness_percentile?: number;
aligned: number;
opposed: number;
total: number;
alignment_pct?: number;
}
export interface AlignmentData {
members: AlignmentScore[];
total_bills_with_stance: number;
total_bills_with_votes: number;
}
export interface BillDetail extends Bill {