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

Wiki System

Last updated 2026-10-29
Source files

Summary#

The wiki is a community knowledge base embedded in the game, served at /wiki/[slug], browsable at /wiki, and searchable site-wide from the navbar. It has two kinds of content:

  1. Game guides and reference articles covering mechanics, strategy, elections and congress. Core guides are TypeScript WikiSeedPage objects () seeded into the wikiPages MongoDB collection; player submissions also exist and go through moderator review.
  2. Auto-generated entity pages assembled from live game data at request time: politicians (player characters and NPPs), parties, congressional seats and leadership roles. These have no entries in wikiPages; they are rendered from database queries and flavor-text templates.

Player guide: Wiki System

Source: src/app/api/wiki/ and src/app/api/admin/wiki/ (routes), src/lib/wiki/ (flavor, search, redirects, content loading), (validation), (document type).

Rules#

Page types#

Manual pages (stored in wikiPages)

Dynamic entity pages (not stored in wikiPages) are served from dedicated app routes that query game data directly:

Route pattern Description
/wiki/party/[id] Party profile: seat counts, member count, economic/social position, flavor text
/wiki/seat/[slug] Office seat: current holder(s) for governor, US Senate class, or House delegation
/wiki/leadership/[role] Congressional leadership role: Speaker, Majority/Minority Leaders and Whips
/character/[id] Canonical public player profile with election history and game-facing context
/politicians/npp/[id] Canonical public NPP profile with election history

Seat slugs follow the pattern {state-lowercase}-{governor|senate-class-1|senate-class-2|senate-class-3|house} (for example fl-senate-class-1, ca-governor).

Slugs for player-owned pages key off public sequential IDs, never ObjectIds (): player-{sequentialId}, corp-{sequentialId}, and party-{countryId lowercase}-{sequentialId}.

Edit workflow#

Player-submitted pages go through a review cycle. Admin-created pages bypass review and publish immediately.

(player creates)         (moderator reviews)     (moderator rejects)
    draft  ──────────>  pending_review  ──────>  draft
                              │
                              └──────────────>  published
                                               (moderator approves)
published  ──────────>  archived
           (admin deletes)

Drafts and pending pages return 404 to users who are neither the page author nor an admin. Approve and reject require the moderator role (requireModerator: admin or moderator). Reject requires a reason string of 10 to 500 characters. An approve or reject on a page that is not pending_review returns 400.

The editHistory array records every state transition with the acting user's ObjectId, a timestamp, an action (created | edited | approved | rejected | archived) and an optional note (the rejection reason, or the list of fields a moderator changed while approving).

Submission checks#

A player POST /api/wiki runs these in order:

  1. The wiki must not be disabled (see Configuration).
  2. A signed-in user with a character (requireAuthWithCharacter).
  3. Rate limit api/wiki:{userId}: 30 requests per 60 seconds.
  4. Schema validation (createWikiPageSchema, ): see the limits table.
  5. Non-moderators must supply a category from PLAYER_SUBMITTABLE_CATEGORY_IDS (): characters, corporations, player-parties, events, reference. Admins and moderators skip this.
  6. Content screen (screenWikiContent, ): hard-block slur and threat patterns, short spam patterns, a link-stuffing check and an all-capitals check.
  7. Creation cooldown: WIKI_CREATE_COOLDOWN_HOURS = 12 () since the player's latest page. Edits are never limited. Admins and moderators bypass it.
  8. The slug must be unused.
Limit Value Source
Slug 3 to 100 chars, ^[a-z0-9-]+$ createWikiPageSchema
Title 3 to 200 chars createWikiPageSchema
Description 10 to 500 chars createWikiPageSchema
Content 50 to 100,000 chars createWikiPageSchema
Tags at most 10, each 2 to 30 chars createWikiPageSchema
Link ratio rejected above 0.25 of non-whitespace characters (only checked once the body has at least 100 non-whitespace characters) computeLinkRatio in contentFilter.ts
Capitals rejected when more than 200 letters and upper-case share above 0.6 screenWikiContent
Page report rate limit 5 per 60 seconds per IP WIKI_REPORT_LIMITS in

On success the page is inserted as pending_review with isAutoGenerated: false and the game stamp, and moderators are notified without blocking the response (failures are logged only).

Permissions#

Action Who can do it
Read published pages Anyone (unauthenticated or authenticated)
Read draft/pending pages Author or admin
Create a page Any authenticated player with a character (POST /api/wiki)
Edit own page Author (PATCH /api/wiki/[slug]); published edits go to pending_review
Edit any field (incl. status) Admin (PATCH /api/admin/wiki/[slug])
Delete (archive) a page Admin only (DELETE /api/admin/wiki/[slug])
Approve a page Moderator or admin
Reject a page Moderator or admin
Create page bypassing review Admin only (POST /api/admin/wiki)

The canEdit flag returned by GET /api/wiki/[slug] is true for the page's author or any admin. Author edits cannot change status, featured or private: those fields are stripped from the update. An author edit of a published page sets it back to pending_review, appends an edited history entry and pings moderators.

Auto-generation#

Politician election history. When an election resolves during turn processing, updatePoliticianPagesAfterElection() () runs for every candidate. It returns early unless election.status === "completed", and skips NPP candidates (cand.isNPP) and candidates with no characterId. For each remaining candidate it writes a PoliticianElectionEntry into politicianOverrides.electionHistory:

The data appears on the canonical /character/[id] page.

Flavor text. Entity pages with no user-authored content get templated text at render time:

Wikilinks. loadWikiContent() () turns [[Page Title]] and [[Page Title|label]] into markdown links using a lowercase title-to-slug map built from published pages. Markdown link characters in the label are escaped. A link whose title matches no page renders as italic text (_Page Title_). Code-backed pages render from current code rather than the database copy.

Custom markdown components#

Page content supports embedded components via fenced code blocks with a custom language identifier. The registry WIKI_COMPONENT_REGISTRY lives in ; an unknown identifier falls back to a plain code block. Heavy widgets are loaded on demand.

Language identifier Component Description
flowchart-turn TurnProcessingFlowchart Visual diagram of turn processing phases
favorability-decay FavorabilityDecayDiagram Favorability decay curve visualization
senate-classes SenateClassesDiagram Senate class rotation diagram
congress-snapshot CongressSnapshot Live widget showing current House/Senate seat counts
vote-share-calculator VoteShareCalculator Interactive calculator for vote share math
clearing-posture ClearingPostureDiagram Clearing posture diagram
capital-loop CapitalLoopDiagram Capital loop diagram
commodity-distribution CommodityDistribution Commodity distribution widget
country-history CountryHistory Country history widget
sector-seed-map SectorSeedMap Sector seed map
starting-state-dashboard StartingStateDashboard Starting-state dashboard
cabinet-guide CabinetGuide Cabinet guide widget
guide-screenshot WikiGuideScreenshot Guide screenshot embed
wiki-chart WikiChart Chart generated from game constants (src/lib/wiki/charts/)

Search index#

The navbar search is built in (ranking) and (sources). It merges:

Results are WikiSearchItem objects with slug, title, description, href, and optional searchText (heading extracts and content snippets). The GET /api/wiki/search endpoint takes q, tags (comma-separated) and limit (default 20, clamped to 1 to 50).

Redirects#

maps legacy or shorthand slugs to canonical paths (WIKI_REDIRECTS):

Slug Redirects to
democrat /wiki/party/1?country=us
democrats /wiki/party/1?country=us
republican /wiki/party/2?country=us
republicans /wiki/party/2?country=us
election-history /wiki/elections
Country aliases The matching country overview
Feature aliases The matching canonical wiki page

The redirect helper preserves query strings in canonical targets, which is required for country-scoped party pages. Country aliases include america (us-overview), britain (uk-overview), china, germany, ireland, japan, nigeria, ussr and soviet-union (ru-overview) and east-germany (dd-overview). Feature aliases include crisis-system (crisis-interaction), formula-deep-dive (reference-formulas) and meta-strategy (advanced-strategy). Consult WIKI_REDIRECTS for the complete current map.

API routes#

Public routes

Method Path Description
GET /api/wiki List published wiki pages without content bodies; private pages are hidden from non-admins. Public variant s-maxage=300; admin variant private, no-store
POST /api/wiki Submit a new page; requires auth and a character; status set to pending_review
GET /api/wiki/[slug] Fetch a single page by slug; enforces status visibility rules
PATCH /api/wiki/[slug] Author edit of own page
GET /api/wiki/search Full-text search over published pages; params: q, tags (comma-separated), limit
GET /api/wiki/tags Returns system tags (with per-tag page counts) and player-defined tags
GET /api/wiki/templates Returns all wikiTemplates documents
GET /api/wiki/templates/[id] Returns a single template by slug
GET /api/wiki/elections Completed election summaries, grouped by year+type and state+type; supports ?year=&type= and ?state=&type= filters
GET /api/wiki/elections/[id] Full detail for a single completed election: primary results + general results from vote tallies
GET /api/wiki/live-stats Current Congress seat counts by party and active/upcoming election counts; s-maxage=120
POST /api/wiki/report Record a page issue (stale, incorrect, update-request, other) with a note up to 2000 chars

Admin routes

Method Path Description
POST /api/admin/wiki Create a page; published immediately (bypasses review)
PATCH /api/admin/wiki/[slug] Update any field on an existing page including status
DELETE /api/admin/wiki/[slug] Soft-delete: sets status to archived
GET /api/admin/wiki/review-queue List all pending_review pages sorted by creation date
POST /api/admin/wiki/review/[slug]/approve Approve a pending page (moderator); optionally apply edits to content, title, description, or tags
POST /api/admin/wiki/review/[slug]/reject Reject a pending page (moderator), returning it to draft; requires a reason string
POST /api/admin/wiki/reseed Upsert the seed pages into wikiPages. Non-destructive by default; pages with human edits are skipped unless force is true; optional slugs list (1 to 200)
POST /api/admin/wiki/sync-prior-submissions Rename legacy ObjectId-embedded slugs to sequentialId slugs
GET/POST /api/admin/wiki/toggle Read or flip gameState.wikiDisabled
POST /api/admin/wiki/backfill-game-stamp Backfill gameIteration and gameStartDate on existing pages

Data#

wikiPages collection (player-visible: published, non-private pages)#

Field Type Description
_id ObjectId Standard document ID
slug string Unique URL identifier; lowercase alphanumeric + hyphens
title string Display title
description string Short summary (10-500 chars)
content string Markdown body (50-100,000 chars)
status WikiPageStatus One of draft, pending_review, published, archived
submittedBy ObjectId? User who created the page
reviewedBy ObjectId? Moderator or admin who approved the page
tags string[]? Freeform and system tags; first tag used as primary category
category string? Legacy field, required from players at submission
contentType WikiPageContentType? Legacy field
templateType string? References a wikiTemplates document slug
featured boolean? Shown in featured section on wiki home
private boolean? Hidden from non-admins in lists and from loadWikiContent
difficulty WikiPageDifficulty? One of beginner, intermediate, advanced
estimatedReadTime number? Minutes
isAutoGenerated boolean? True for pages seeded by migration scripts
autoGenerateConfig AutoGenerateConfig? { type, entityId, widgetComponents? } where type is one of party, leadership, seat, politician
gameIteration, gameStartDate string? Stamp from getGameStamp() on player-created pages
createdAt, updatedAt Date
editHistory EditHistoryEntry[]? Log of created, edited, approved, rejected, archived

Types: .

Other collections#

Collection Role Fields written or read
wikiTemplates Read by the editor _id (template slug), name, description, icon, fields[] (id, label, placeholder, type of text, textarea or markdown, required, order)
systemTags Read for tag lists Name, description, icon, Tailwind color class, sort order. Player-created tags are plain strings on wikiPages.tags with no systemTags document
politicianOverrides Written after each election politicianId, electionHistory[] (PoliticianElectionEntry), updatedAt. Player-visible on /character/[id]
wikiReports Written by POST /api/wiki/report slug, reason, note, ip, userId?, createdAt, relayAttempted. Not player-visible
gameState (_id: "current") Read by every wiki route wikiDisabled
users Read username, displayName for moderator notifications
electionCandidates, states, politicalParties, elections Read by the election-history writer Candidate, state name, party name, election type and end time

Configuration#

Setting Default Where set
gameState.wikiDisabled unset, treated as false ; flipped by POST /api/admin/wiki/toggle. When true, wiki API routes return 403 "Wiki is currently disabled" to everyone except admins and moderators
WIKI_CREATE_COOLDOWN_HOURS 12
WIKI_REPORT_LIMITS 5 requests per 60,000 ms
Page creation rate limit 30 per 60 seconds per user inline in
GAME_ITERATION, GAME_START_DATE environment variables unset (no stamp written) read in
WIKI_REPORT_ENDPOINT environment variable unset (no relay) ; relay uses a 3000 ms timeout and failures are swallowed
PLAYER_SUBMITTABLE_CATEGORY_IDS characters, corporations, player-parties, events, reference

There are no era or country presets for the wiki system itself. Seeded page content differs per era and country, but the machinery does not.

Timing#

player submit -> screens -> pending_review -> moderator approve -> published
election resolves (turn) -> politicianOverrides.electionHistory -> /character/[id]

Worked trace#

A player with no previous page submits slug mayor-guide, category reference, content of 400 non-whitespace characters of which 120 are inside a markdown link.

  1. Rate limit: first request in the window, passes (30 allowed).
  2. Schema: slug is 11 characters (3 to 100), content is at least 50 characters, passes.
  3. Category reference is in the submittable list, passes.
  4. Link ratio: 120 / 400 = 0.30, above 0.25, so the request returns 400 "Too many links relative to body text".
  5. The player rewrites with 60 link characters in 400: ratio 0.15, passes. No capitals problem.
  6. Cooldown: no earlier page, passes. Slug unused, passes.
  7. Stored: status: "pending_review", isAutoGenerated: false, editHistory: [created]. Moderators are notified.
  8. The player resubmits another new page 5 hours later: remaining cooldown is 12 h - 5 h = 7 h = 25,200,000 ms, so 429 with retryAfterMs: 25200000.
  9. A moderator approves: status becomes published, reviewedBy is set, and history gains approved.
  10. The player edits the published page: it returns to pending_review and history gains edited.

Election history: a non-NPP candidate gets 52,000 of 100,000 total votes in a single-seat race and is in winnerIds. votesPct = 52,000 / 100,000 * 100 = 52, result = "won". The entry is prepended to electionHistory; a rerun of the same election replaces it.

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

Connected pages

← Referenced by
docsWiki System
Ask