A House Divided A House DividedDocumentation
↵
Changelog
Game Design/Platform

Technical Architecture

Last updated 2026-10-29
Source files

Summary#

A House Divided is one Next.js application that serves the UI, every API route and the hourly turn processor from a single process, backed by MongoDB. There is no separate backend or external scheduler: the turn clock is node-cron started inside the web process at boot. This page records the stack, how a turn is scheduled and locked, the phase ordering that is load-bearing, the core collections, and how the pieces fail and recover.

Player guide: none; this is an engineering page. Player-facing turn timing is described in the Wiki.

Rules#

Technology stack#

Versions come from .

Layer Technology Version
Framework Next.js (App Router) ^16.4.2
UI React 19.3.1
Language TypeScript 6.0.2
Styling Tailwind CSS ^4
Database MongoDB native driver ^7.4.0
Auth Custom JWT via jose ^6.2.9
Scheduler node-cron ^4.6.0
Testing Vitest (unit/integration) + Playwright (E2E) ^5.0.1 / ^1.64.0
Deployment Railway (Nixpacks build, next start) railway.toml
File Storage Cloudflare R2 (prod) / local filesystem (dev) n/a

Request flow#

Turn processor#

Phase groups#

The table groups phases by concern. It is illustrative, not exhaustive (the registry also holds governor/SCOTUS, extraction and prospecting, decolonization, spheres of influence, impeachment, by-elections and ledger-reconciliation phases not shown).

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 and notifications#

Security and fairness#

Notable API routes#

Route Method Purpose
/api/cron/turn GET Turn processor HTTP fallback (primary is in-process node-cron)
/api/cron/fog-update GET Campaign fog-of-war visibility update
/api/auth/me GET Current user and 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
/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 and opposition leader
/api/whitehouse/cabinet GET All cabinet positions with member and 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 Hero banner redirect (307 to the image URL)
/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

Data#

The high-level core collections the application reads and writes. Player-visible data is surfaced through API routes; users, adminLogs, actionLogs and gameConfig are internal.

Core#

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

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 and 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 to character mapping)

Campaigns, geography and metrics#

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
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, NPP and content#

Collection Purpose
newsPosts News posts created by players
newsReactions Reactions and comments on news posts
notifications Per-player notification queue (146 types, paginated)
feedback Bug reports and suggestions (with captured context)
nppInfluenceAttempts Records of influence attempts
nppRelationships Player-NPP relationship scores
nppEndorsements NPP endorsements of candidates
playerEndorsements Player endorsements

Admin and 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, isProcessing lock, fastMode, next scheduled turn
roadmapItems Admin-managed roadmap entries with phase, category, status
roadmapCategories Category/subcategory groupings for roadmap items

The list is not exhaustive; economy, central bank, corporation and trade collections are documented in their own pages. Indexes are managed by versioned migration entries under src/lib/migrations/entries/ and the index seeder ().

Configuration#

Setting Default Where set
TURN_CRON_MINUTE 0 (only 0 or 30 accepted; other values fall back to 0 with a warning) environment, read by resolveTurnCronMinute in
GameState.fastMode off; when on, the turn schedule is 0,30 * * * * gameState document, read in
TURN_PHASE_TIMEOUT_MS 4 minutes (DEFAULT_PHASE_TIMEOUT_MS); clamped to 1 to 30 minutes environment, resolvePhaseTimeoutMs in
TURN_LOCK_STALE_MS 20 minutes
TURN_LOCK_HEARTBEAT_MS 30 seconds
CRON_SECRET none; required by requireCron() environment
NODE_OPTIONS --max-old-space-size=3072 --max-semi-space-size=64 startCommand in railway.toml
Health check path /api/health, timeout 300 s, restart on failure, 5 retries railway.toml
GameState.forexEnabled gates the forex phase gameState document
Game time cache 5 seconds (CACHE_TTL_MS), invalidated by sync-date
Cron route maxDuration 800 seconds

Other in-process schedules registered in : the stuck-lock sweep (*/5 * * * *), fog of war, stock-exchange refresh, share-fill recovery, retention, money journal prune and alt scoring, among others.

Timing#

flowchart TD
  A[node-cron primary :00 or :30] --> L{turn lock free?}
  B[backup cron +30 min] --> G{turn completed this hour?}
  G -- no --> L
  G -- yes --> X[skip]
  L -- held --> S[skip, log]
  L -- free --> P[acquire isProcessing lock, heartbeat 30 s]
  P --> R[run registry phases in order, 4 min timeout each]
  R --> W[persist GameState and TurnLog]
  W --> U[release lock, emit event]
  C[stuck-lock sweep every 5 min] -. repossess stale lock .-> L

Worked trace#

Normal mode, TURN_CRON_MINUTE unset (0), one world.

  1. 14:00 UTC: turnCronSchedule(0, false) is 0 * * * *, so the primary cron fires. getGameState() shows isActive and no live lock, the lock is taken and heartbeated every 30 s, and the registry phases run in order.
  2. The turn completes at 14:02 and TurnLog is written with real time 14:02.
  3. 14:30 UTC: backupTurnSchedule(0) is (0 + 30) % 60 = 30, so 30 * * * * fires. shouldFireBackupTurn computes turnHourBucket(14:02, 0) = floor(14:02 / 1h) = hour 14 and turnHourBucket(14:30, 0) = hour 14. Same bucket, so alreadyRanThisHour is true and the backup returns false: no second turn.
  4. Alternative, primary missed: no completed turn in hour 14, buckets differ from the latest completed turn (hour 13), so the backup fires and runs the turn at 14:30.
  5. With TURN_CRON_MINUTE=30: the turn fires at 14:30 and completes at 14:31. turnHourBucket(14:31, 30) = floor((14:31 - 0:30) / 1h) is bucket 14; the backup at 15:00 gives floor((15:00 - 0:30) / 1h) is also 14, so it skips. The backup is (30 + 30) % 60 = 0, i.e. 0 * * * *.
  6. If the process died mid-turn at 14:00 with the last heartbeat at 14:05, the lock is considered stale after TURN_LOCK_STALE_MS (20 minutes), i.e. from 14:25; the stuck-lock sweep (every 5 minutes) can then repossess it and the 14:30 backup can run.

Edge cases and limits#

Invariants#

Failure and recovery#

Connections#

Driven by:

Affects:

Tests#

Known issues and history#

Last checked: 2026-10-29, version 1.18.0

Ask