A House Divided A House DividedDocumentation
Changelog
Game Design/Platform

Technical Architecture

Last updated 2026-08-21
Source files

Technology Stack#

Layer Technology Version
Framework Next.js (App Router) 16.3
UI React 19.2
Language TypeScript 6.0
Styling Tailwind CSS 4
Database MongoDB native driver 7.4
Auth Custom JWT via jose 6.2
Testing Vitest (unit/integration) + Playwright (E2E) 4.1 / 1.61
Deployment Railway (Nixpacks build, next start) n/a
File Storage Cloudflare R2 (prod) / local filesystem (dev) n/a

Architecture Pattern#

Request Flow#

Turn Processor#

Section Phases Key constraint
1. Resources & finance actionRefresh, fundGeneration, corporationTurn, partyInfluenceTurn, lineOfCreditTurn, nppFundGeneration, savingsInterestTurn, bondTurn, commodityPrices, recomputeSharePrices, portfolio/corp/exchange/investor/wealth snapshots, financialSuspectScan Share-price recompute must precede market snapshots
2. Demographics turnoutDecay -> partyGOTV -> partyOrgTurn Sequential (decay before GOTV)
3. Party elections statePartyElections, nationalPartyElections, nationalCommitteeElections, partyActionGeneration, emptyPartyCleanup Parallel election processors, then cleanup
4. NPP & coalitions coalitionDisbandVotes, nppBehavior NPP behavior runs after party processing
5. Bills & cabinets billLifecycle, country bill lifecycles from COUNTRY_BILL_PHASES, stateBillTimers, cabinetNominations Parallel-safe
6. Campaigns & actions campaignTurn, nppActionProcessing, activityLogging Activity summary after action phases
7. Election resolution candidatePartySweep -> primaryResolution -> voteAccumulation -> campaignSpendReset -> electionTimers -> primarySnapshots -> electionResolution -> clearResolvedSupport -> leadershipVacate Strictly sequential; ordering is load-bearing
8. Parliamentary govt parliamentaryGovernmentFormation, parliamentaryGovernmentPhases, parliamentaryVacancyWatcher After election resolution
9. Election coverage perpetualElections, country election phases from COUNTRY_ELECTION_PHASES, leadershipElections, staleCandidateCleanup, presidentialSuccession Parallel-safe coverage before succession
10. Fiscal year fiscalYear (turn 40 of 48, October) Conditional
11. Effects & regional ops policyEffects, demographicEffects, policyReactionDecay, archetypeApprovalDecay, unownedSectorGrowth, metricDecay, subsidyBudget, regionalBudgetProcessing, jpRegionalBudgetProcessing, deRegionalBudgetProcessing, crisisTurn, ministerialOrders Parallel-safe state/regional updates
12. National aggregation gdpGrowth, nationalMetrics, tradeGrowthMirror, inflationRecalc, forexTurn, centralBankChairTurn, centralBankChairSelection Ordered; forex is gated by GameState.forexEnabled
13. History & health metricHistory, approvalSnapshot, interestRateSnapshot, partyHistorySnapshot, gameHealthSnapshot, suspiciousDetection After metrics and central-bank updates
14. Persistence GameState update, TurnLog insert, in-process event emit Critical, not wrapped in try/catch

Multi-Country Support#

Communication & Notifications#

Notifications#

Hero Image System#

Toast Notifications#

Database Schema (High-Level)#

Core Collections#

Collection Purpose
users Auth credentials, ban status, fingerprints
characters Player stats, funds, actions, office, policy positions, bio
npps AI politicians with personality traits, cooldowns, influence state
elections Active/upcoming/completed races (all types)
electionCandidates Per-candidate rows; status active/withdrawn
electionVoteTallies General-phase vote totals, turn snapshots, seats estimate
primarySnapshots Hourly primary standings for trend display
electedOfficials Current office holders (players + NPPs); canonical post-election source
politicalParties Party data, treasury, action pool, leadership IDs
statePartyOrg Per-state-party org level, treasury, leadership, tax rate
statePartyElections Leadership elections for Chair/VC/Treasurer
statePartyVotes Votes cast in state party leadership elections
statePartyElectionCandidates Candidates in state party leadership elections

Legislation#

Collection Purpose
bills Full bill lifecycle with chamber tallies and timeline timestamps
billVotes Per-member votes on bills
legislationTypes Policy domains, legislation types, policy options (economic/social scores)
committeeAssignments Committee positions (Chair, Ranking Member) per legislation type
statePolicies Base policy per legislation type for nation and each state

Elections & Leadership#

Collection Purpose
speakerElections Speaker election state (12h voting window; _id: "current")
speakerNominations Active House Speaker candidacies and votes
houseLeadershipElections Majority/Minority Leader elections (_id: majority_leader | minority_leader)
houseLeadershipNominations Candidacies and votes for House Majority/Minority Leader
senateLeadershipElections Pro Tempore/Majority/Minority Leader elections
senateLeadershipNominations Candidacies and votes for Senate leadership

Cabinet#

Collection Purpose
cabinetNominations Pending and resolved cabinet nominations; status active/confirmed/rejected
cabinetMembers Confirmed cabinet members (position → character mapping)

Campaigns & Economy#

Collection Purpose
campaigns Campaign state: resource allocation, manager assignment
campaignOperations Log of campaign spending, upgrades, activities
countyElectionData County-level partisan lean and population for election visualization

Geography & Metrics#

Collection Purpose
states Population, GDP, lean, house districts
stateDemographics Per-state demographic groups, category weights
demographicCategories Category definitions (race, gender, etc.) and groups
stateMetrics 9-category metrics per state

Social & Content#

Collection Purpose
newsPosts News posts created by players
newsReactions Reactions and comments on news posts
notifications Per-player notification queue (129 types, paginated)
feedback Bug reports and suggestions (with captured context)

NPP Relations#

Collection Purpose
nppInfluenceAttempts Records of influence attempts
nppRelationships Player-NPP relationship scores
nppEndorsements NPP endorsements of candidates
playerEndorsements Player endorsements

Admin & System#

Collection Purpose
adminLogs Admin activity audit trail
actionLogs Records of player action execution
gameConfig Turn config, action costs, office bonuses, starting stats
gameState Current turn number, pause state, lastTurnProcessed, next scheduled turn
roadmapItems Admin-managed roadmap entries with phase, category, status
roadmapCategories Category/subcategory groupings for roadmap items

Deployment Considerations#

Hosting#

Scaling#

Testing#

Layer Tool Command Notes
Unit Vitest npm test src/**/*.test.ts
Integration Vitest npm test API route tests with mocked MongoDB
E2E Playwright npm run test:e2e e2e/*.spec.ts; requires npm run dev; set E2E_TEST_EMAIL/E2E_TEST_PASSWORD

Security & Fairness#

Notable API Routes#

Route Method Purpose
/api/cron/turn GET Hourly turn processor (in-process node-cron; this route is the HTTP-triggerable fallback)
/api/cron/fog-update GET Campaign fog-of-war visibility update
/api/auth/me GET Current user + character
/api/elections GET All elections (filter by type/state/status)
/api/elections/[id] GET Single election with candidates and tally
/api/elections/[id]/state/[stateId]/county-results GET County-level vote distribution
/api/elections/[id]/state/[stateId]/cd-results GET Congressional district seat assignments
/api/country/[code]/legislature/members GET Chamber composition by country (e.g. UK Commons: 650 seats, party breakdown)
/api/country/[code]/legislature/bills GET/POST Bills list for the country's legislature; propose a bill (member/admin)
/api/country/[code]/legislature/leaders GET Presiding officer / head of government / opposition leader for the country
/api/whitehouse/cabinet GET All cabinet positions with member + nomination data
/api/whitehouse/cabinet/nominations POST President nominates a character
/api/whitehouse/cabinet/nominations/[id]/vote POST Senator votes on a nomination
/api/whitehouse/cabinet/fire POST President fires a cabinet member
/api/campaigns/[id] GET Campaign detail (owner/party/public access tiers)
/api/campaigns/mine GET Current user's campaign
/api/news GET/POST News feed and post creation
/api/country/[code]/approval GET National government approval, per country
/api/country/[code]/budget/federal GET Federal budget data, per country
/api/images/hero/[slug] GET Wikimedia image proxy (24h cache)
/api/roadmap GET Public roadmap data for wiki page
/api/admin/seed GET/POST Universal game seeder (admin only)
/api/admin/roadmap GET/POST/PUT/DELETE Roadmap item management (admin only)
/api/admin/roadmap/categories GET/POST/PUT/DELETE Roadmap category management (admin only)
/api/admin/law-types POST Create custom legislation type (admin only)
/api/performance GET Game performance metrics

Implementation Status#

System Status
Authentication + characters ✅ Complete
Turn system (modular, 120+ phases via a phase registry) ✅ Complete
Elections (all 5 types, perpetual, Electoral College) ✅ Complete
NPP system (entry, dropout, influence, Speaker/leadership auto-vote) ✅ Complete
Bill lifecycle (two chambers + President) ✅ Complete
Party system (national + state, leadership elections) ✅ Complete
Cabinet (nomination → Senate vote → confirm/fire) ✅ Complete
Congress leadership (Speaker + House/Senate leaders, auto-trigger after elections) ✅ Complete
Campaign fund generation + taxes ✅ Complete
Campaign manager pages (3-tier access, dedicated /campaign/[id]) ✅ Complete
Campaign song (YouTube embed, autoplay controls) ✅ Complete
Demographics + state metrics (9 categories) ✅ Complete
County/district election maps ✅ Complete
News / posts system ✅ Complete
Admin panel (fully modularised, Law Types, Universal Seeder) ✅ Complete
Map view (real geographic paths, Political Lean mode) ✅ Complete
Player bio + profile page ✅ Complete
Achievements system (58 achievements, rarity tiers) ✅ Complete
Notifications (129 types, pagination, filtering) ✅ Complete
Discord integration ✅ Complete
Multi-country support (29 configured countries) ✅ Complete
UK House of Commons (composition, bills, leadership) ✅ Complete
Roadmap system (admin-managed, public wiki page) ✅ Complete
Public + developer changelog page ✅ Complete
API validation (Zod schemas, admin + key routes) ✅ Complete
API testing (Vitest integration + Playwright E2E) ✅ Complete
API hardening (rate limiting, request logging) ✅ Complete
Legislative amendments 🔲 Placeholder
US Senate filibuster / cloture and veto override ✅ Complete
Policy effects on state metrics and granular demographics ✅ Complete
Presidential and regional executive orders ✅ Complete
Special executive appointments beyond the existing cabinet and succession systems 🔲 Planned