Wiki System
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:
- Game guides and reference articles covering mechanics, strategy, elections and congress. Core guides are TypeScript
WikiSeedPageobjects () seeded into thewikiPagesMongoDB collection; player submissions also exist and go through moderator review. - 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)
- Guide pages: player-written or admin-written articles on mechanics, strategy and lore. Examples:
getting-started,election-mechanics,campaign-strategy. - Election History: a special-cased slug (
elections) that renders a dynamic elections browser rather than a markdown page. - Admin-seeded reference pages: core guides seeded from
src/lib/seeds/wiki/. There is no sync fromdocs/design. These haveisAutoGenerated: false.
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)
- draft: set when a submission is rejected (returned for revision). Visible only to the submitting player and admins.
- pending_review: set automatically when any authenticated player with a character submits a new page. Visible only to the submitting player and admins.
- published: publicly visible. Approval can apply optional edits to content, title, description or tags.
- archived: soft-deleted via the admin DELETE endpoint. Treated as non-existent for public views.
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:
- The wiki must not be disabled (see Configuration).
- A signed-in user with a character (
requireAuthWithCharacter). - Rate limit
api/wiki:{userId}: 30 requests per 60 seconds. - Schema validation (
createWikiPageSchema, ): see the limits table. - Non-moderators must supply a
categoryfromPLAYER_SUBMITTABLE_CATEGORY_IDS():characters,corporations,player-parties,events,reference. Admins and moderators skip this. - Content screen (
screenWikiContent, ): hard-block slur and threat patterns, short spam patterns, a link-stuffing check and an all-capitals check. - Creation cooldown:
WIKI_CREATE_COOLDOWN_HOURS = 12() since the player's latest page. Edits are never limited. Admins and moderators bypass it. - 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:
electionId,electionType,state,stateName,year,result(wonorlost),votes,votesPct,party(name resolved frompoliticalPartiesbysequentialIdandcountryId, falling back to the rawcand.party),officeLabel,completedAt.votesPct = votes / totalVotes * 100, or 0 when the tally is missing or has zero votes.votesis read fromtally.totalVotes[candidateId], 0 when absent.resultiswonif the candidate is inwinnerIds; for multi-seat election types (MULTI_SEAT_TYPES) it iswonwhen the estimated seats are above 0.- The entry is placed first in the array and any earlier entry with the same
electionIdis removed, so reruns replace rather than duplicate.
The data appears on the canonical /character/[id] page.
Flavor text. Entity pages with no user-authored content get templated text at render time:
- Politicians: picks a bio template and "approach" phrase deterministically from a hash of the politician's ID. Inputs are name, state, party, office status, and whether they are an NPP.
- Parties: returns hand-written blurbs for
democrat,republicanandindependent, and a generic template for all other parties. - Leadership roles: provides static blurbs and responsibility lists for 15 roles: the 10 US congressional roles,
speaker_of_the_bundestag,chair_npcsc,chair_cppcc,speaker_ng_repsandpresident_ng_senate.
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:
- All
wikiPagesdocuments - All player character profiles (excluding banned users)
- All active NPP profiles
- All seat pages derived from
getAllSeatSlugs() - All leadership role pages
- All party pages
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#
- Page creation, edit, approve and reject act immediately on request. Author edits call
revalidatePathfor the page; reseed revalidates/wiki. - Election history is written during election resolution in turn processing, once per resolved election, from the resolution code in
src/lib/turn/election/(generalResolution.ts,presidentResolution.ts,finalizedElectionCleanup.ts). - Flavor text, entity pages, wikilinks and the search index are computed at request time.
- Public caches: page list 300 s (stale-while-revalidate 600 s), live stats 120 s (stale-while-revalidate 180 s).
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.
- Rate limit: first request in the window, passes (30 allowed).
- Schema: slug is 11 characters (3 to 100), content is at least 50 characters, passes.
- Category
referenceis in the submittable list, passes. - Link ratio:
120 / 400 = 0.30, above 0.25, so the request returns 400 "Too many links relative to body text". - The player rewrites with 60 link characters in 400: ratio
0.15, passes. No capitals problem. - Cooldown: no earlier page, passes. Slug unused, passes.
- Stored:
status: "pending_review",isAutoGenerated: false,editHistory: [created]. Moderators are notified. - The player resubmits another new page 5 hours later: remaining cooldown is
12 h - 5 h = 7 h = 25,200,000 ms, so 429 withretryAfterMs: 25200000. - A moderator approves:
statusbecomespublished,reviewedByis set, and history gainsapproved. - The player edits the published page: it returns to
pending_reviewand history gainsedited.
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#
- Disabled wiki: all wiki API routes return 403 for non-moderators. Moderators keep access so they can review seeded content before it goes public.
- Missing tally or zero votes:
votesis 0 andvotesPctis 0. - NPPs and candidates without a character: no election history is written (NPP profiles use their own route).
- Multi-seat elections:
wonmeans estimated seats above 0. - Private pages: excluded from public lists and from
loadWikiContent. - Broken wikilinks: render as italic text, not a dead link.
- Admin cache: the admin page list is never share-cached because it includes private pages.
- Unknown widget identifier: falls back to a plain code block.
- Content filter scope: a deliberately short blocklist, so legitimate text is rarely rejected. Place names that share letters with a slur are masked before matching. Moderator review remains the real safety net.
- No docs sync: the wiki is not generated from design docs.
Invariants#
- A slug is unique across
wikiPages. Enforced by an explicit existence check on create (race between two simultaneous creates is not guarded in the route); a unique index is not asserted here. - Player submissions always enter as
pending_review. Enforced in the route; there is no test named for this specific rule. - Authors cannot change
status,featuredorprivate. Enforced by stripping those fields in the author PATCH. - Only
pending_reviewpages can be approved or rejected. Enforced by a 400 check in each route. - At most one election-history entry per
electionIdper politician. Enforced by filtering out the prior entry before prepending. - Content limits (lengths, tag counts) hold at creation and edit. Enforced by the zod schemas.
- Slugs never contain ObjectIds for player-owned pages. Enforced by
playerWikiSlug,corporationWikiSlugandpartyWikiSlug.
Failure and recovery#
- Seed content drifts or is lost: an admin reseed upserts the seed pages. It skips pages with human edits unless forced, so a forced reseed overwrites edits.
- Legacy slugs containing identifiers: repaired by the sync-prior-submissions route.
- Pages missing the game stamp: repaired by the backfill-game-stamp route.
- Election history missing or wrong: the writer is idempotent per election, so rerunning election resolution for that election replaces the entry; otherwise a data heal on
politicianOverridesrepairs it. - Moderator notification fails: logged only. The page still sits in the review queue, which an admin can list at any time.
- Report relay fails: the report is still stored in
wikiReportsand the player still gets success. - Wiki abuse or bad launch content: switching the wiki off hides it from non-moderators while it is fixed.
Connections#
Driven by
- Election resolution (
updatePoliticianPagesAfterElection): writes election history shown on character profiles. - Game state (
wikiDisabled): gates every wiki route. - Characters, NPPs, parties, seats and leadership data: the source of auto-generated entity pages and search entries.
- The seed list in
src/lib/seeds/wiki/: the source of core guide pages.
Affects
- Wiki System: the player-facing description of the same system.
- Moderator tooling: submissions and edits notify moderators; approvals and rejections notify the submitter, and rejection writes a moderator audit log entry.
- Navbar search: draws from the wiki index plus profiles, seats, leadership and parties.
Tests#
- : the content screen.
- , , : search ranking, sources and endpoint.
- , , , , .
- , , , , .
- , , : seeding and preservation.
- , , : editor and chart widgets.
- Gaps: no test file is named for the create, author edit, approve and reject routes, the creation cooldown, the wikilink resolver, the redirect map,
politicianFlavor,leadershipFlavor, orupdatePoliticianPagesAfterElectiondirectly (election resolution tests exercise it indirectly).
Known issues and history#
GET /api/wikiand the document type still carry the legacycategoryandcontentTypefields alongsidetags.- Slug uniqueness is checked with a read before insert, so two simultaneous creates of the same slug could race.
- Earlier text of this page said the reject and approve actions were admin only; the code allows moderators too.
- The redirect and component tables list the current entries; the registry and
WIKI_REDIRECTSare the source of truth if they drift.
Last checked: 2026-10-29, version 1.18.0
A House Divided
Corporate Warfare
Grand Century
Margin of Victory
Desktop client