Home
Design Archive

Elemental Dynasty — Design Archive

Session of 21–22 November 2026 · Chronicle & Novel System, Canon Governance, Permissions, Backend Architecture, Database Design, API Specification and Roadmap

About this document

This archive is a reconstruction, not a word-for-word transcript. A chat log cannot be exported verbatim once earlier turns leave the working context, so this document consolidates every system, decision and plan that was actually discussed in this session.

It is written as a working design document: each section states what exists today, what was designed in this session, and what is still only a plan. Schemas, endpoints and code in this document are complete and intended to be usable as a starting point for implementation.

Two small corrections were applied while consolidating the database design, and they are noted where they occur: a nullable column cannot sit in a primary key, so user_roles gained a surrogate key, and the direction of permission inheritance is stated explicitly so the recursive query is unambiguous.

1. What was built this session

The session began with the Chronicle: a shared, admin-written record of Karito's adventures that every signed-in player can read from inside Avatar Communion. It grew, across the session, into a full novel system with volumes, canon status and world years.

  • A Chronicle tab inside Avatar Communion, sitting beside the living Communion feed.
  • An admin-only chapter editor: numbered chapters, a title and a large paste field.
  • Basic text formatting for chapters — bold, italics, headers and subheaders — inserted around selected text and rendered back as formatted prose.
  • Chapters can be saved as individual text files, or the whole chronicle as one file.
  • Collapsible chapters, so long chapters no longer fill the screen.
  • The chronicle upgraded into a novel structure: chapters grouped into volumes, each carrying the world year it covers and a canon status (canon, draft or retconned).
  • Volumes and chapters both collapse, and the text export keeps volume headings and status labels.

2. The Chronicle and Novel System

AI-generated chronicles evolved into full-length novels. The structural model that came out of the discussion nests two hierarchies that meet at the chapter: one describes how a life is serialised, the other how a book is bound.

Serialised form — how a life arc is published to readers: Season → Episodes → Chapters → Scenes → Memory Sources.

Bound form — how the same material is printed as a book: Book → Volumes → Chapters → Scenes.

The two meet at the chapter. An episode is a chapter presented in reading order; a volume is a group of chapters presented as one book. A scene is the atomic unit of prose, and every scene points back at the memories it was written from, so any sentence in the game can be traced to what actually happened in the simulation.

  • Season — a long arc of a life or a dynasty, usually one era.
  • Episode — one instalment of a season, mapped to one chapter.
  • Volume — a book-sized span of years, usually one generation or one era.
  • Chapter — a single turn of the story, numbered within its volume.
  • Scene — a discrete moment inside a chapter: location, participants, outcome.
  • Memory Source — the stored event or memory a scene was written from.
Serialised structure
Season 1
├ Episode 1  → Chapter 1
├ Episode 2  → Chapter 2
├ Episode 3  → Chapter 3
└ ...
Season 2
├ Episode 1  → Chapter 13
├ Episode 2  → Chapter 14
└ ...
Bound structure
Book
└ Volumes
   └ Chapters
      └ Scenes
         └ Memory Sources

3. Seasons, Episodes, Chapters and Scenes

Every major life arc automatically generates the full chain, so the player never has to write structure by hand: Season → Episodes → Chapters → Scenes → Memory Sources.

Because the chain is generated from play, a chapter is never invented from nothing. It is assembled from scenes, each of which is anchored to one or more stored memories. That is what makes retcons auditable later: changing a chapter means changing the scenes it was built from, and every scene can be pointed back at its source record.

  • A season opens when a life begins or a new era starts.
  • An episode closes when a chapter is written, so episodes and chapters stay in lockstep.
  • A chapter can hold several scenes; each scene carries its own location, participants and outcome.
  • Living Books: a book is never finished while its dynasty lives. New chapters append to the current volume until the era closes.
  • The AI Author Council drafts a chapter from its scenes; a human moderator settles it into canon.

4. Reading depth

Because the same life arc is stored at several levels of detail, a player chooses how deep to read. Every level is generated from the level below it, so the summary can never contradict the chapter.

  • Quick episode summary — a few lines, for catching up.
  • Full chapter — the written prose, with scenes in order.
  • Entire novel — the whole volume or book, read in order.
  • Historical analysis — the same material read as history, with causes, consequences and canon notes attached.

5. The Chronicle library

The library was designed as one Chronicles area with dedicated shelves, so each scale of story has a home. Two layouts were drawn; the second supersedes the first and is the one to build.

  • My Life Story — volumes, chapters and episodes of the current and past lives.
  • Family Chronicles — the dynasty's saga across generations.
  • Clan Chronicles.
  • City Chronicles.
  • Nation Chronicles.
  • Animal Chronicles.
  • Avatar Chronicles — the cycle's own record.
  • World History — eras, calamities and turning points.
  • Hall of Legends — the figures history refuses to forget.
First layout (superseded)
Chronicles
├ Active Stories
├ Completed Stories
├ Family Sagas
├ Historical Records
├ World Literature
└ Hall of Legends
Final layout (build this)
Chronicles Tab
│
├ My Life Story
│  ├ Volumes
│  ├ Chapters
│  └ Episodes
│
├ Family Chronicles
├ Clan Chronicles
├ City Chronicles
├ Nation Chronicles
├ Animal Chronicles
├ Avatar Chronicles
├ World History
└ Hall of Legends

6. Reader and editor interfaces

Two interfaces carry the system: one for writing, one for reading.

  • Chapter editor: chapter number, volume number and title, world year, canon status, formatting toolbar, character count, save.
  • Reader: volumes collapse into a table of contents; chapters expand in place; each chapter shows its year and any non-canon badge.
  • Export: any chapter, or the entire chronicle, downloads as a plain text file with formatting stripped for readability.
  • Admin controls (edit, remove, new chapter) appear only for admins; every other player reads.
  • Reader Library Interface (designed): shelf → volume → chapter, with the four reading depths as toggles on the same chapter.

7. Canon, retcons and versioning

A living novel needs rules for changing its own past. The designed canon system covers the full lifecycle of a written chapter, from first draft to a retconned record that is preserved rather than deleted.

Lifecycle of a chapter: draft → proposed → in review → approved → canon → retconned. A rejected proposal stays in the record as rejected; nothing is ever destroyed.

  • Canon — the official story.
  • Draft — written but not yet settled.
  • Retconned — superseded by a later chapter, kept for the record rather than deleted.
  • Review states — proposed, in review, approved, rejected.
  • Version comparison, so two revisions of a chapter can be read side by side.
  • Rollback, so an approved edit can be undone without losing the version it replaced.
  • Timeline branching, so an alternate history can be explored without corrupting the main line.
  • Canon governance: who may promote a draft to canon, and what a retcon is allowed to overwrite.
  • Canon Locks: a fact can be pinned so no retcon can touch it without an explicit unlock.

8. Permission inheritance

As the world grows to thousands of clans, cities, nations and novels, assigning permissions by hand becomes impossible. Permissions therefore flow down a hierarchy instead of being granted one user at a time.

Semantics, stated once so the SQL is unambiguous: the tree is drawn with the most senior role at the top, and every role inherits the permissions of every role beneath it. In the permission_inheritance table, parent_role_id is the senior role and child_role_id is the junior role; a senior role's effective permissions include all of its descendants' permissions.

Role hierarchy
Administrator
    │
    ├─ Canon Moderator
    │
    ├─ Historian
    │
    ├─ Nation Leader
    │    │
    │    ├─ Governor
    │    │    │
    │    │    ├─ City Official
    │    │
    │    └─ Military Commander
    │
    ├─ Clan Leader
    │    │
    │    ├─ Clan Officer
    │    │
    │    └─ Clan Member
    │
    └─ Player
Clan inheritance
Dragon Clan
 │
 ├─ Library
 ├─ Chronicles
 ├─ Family Records
 └─ War Archives
City inheritance
Republic City
    │
    ├─ University Archive
    ├─ Public Library
    ├─ City Registry
    └─ Historical Museum
Resource ownership record
{
  "resourceId": "novel_551",
  "ownerType": "clan",
  "ownerId": "dragon_clan"
}

9. Permission resolution rules

Three rules decide the final answer. They are applied in this order, and the last one always wins.

  • Rule 1 — Child inherits parent. A Clan Leader automatically receives Read Clan Novels, Archive Clan Records, View Clan History and View Clan Audit Logs. Nothing is assigned separately.
  • Rule 2 — Explicit deny wins. A Historian allowed to Review Books but denied Approve Retcons cannot approve, even if another role would grant it.
  • Rule 3 — Scope matters. A Governor's permissions apply inside Republic City and nowhere else.
ActionPlayerClan LeaderHistorianModerator
ReadYesYesYesYes
CommentYesYesYesYes
Submit RetconYesYesYesYes
Approve RetconNoNoNoYes
Canon LockNoNoNoYes
RollbackNoNoNoYes
Merge TimelinesNoNoNoYes
Delete CanonNoNoNoYes

10. The moderation dashboard

The dashboard is the command centre for world historians: one screen that answers what needs attention, what is broken, and what history is about to change.

  • Home: six live counters across every queue.
  • Review queue: sorted by priority and blast radius, with the four decisions available in place.
  • Continuity panel: characters, objects and places that appear out of order.
  • Lore panel: things that exist before the world discovered them.
  • AI review panel: the verdicts of each reviewer agent, with a confidence figure.
  • Flagged content: reported books with report counts and four dispositions.
  • Timeline command centre: population, book count and the branch tree.
Dashboard home
═══════════════════════════════

WORLD MODERATION CENTER

Pending Reviews: 482

Retcons Awaiting Approval: 83

Canon Violations: 12

Continuity Errors: 44

Flagged Books: 107

Active Timeline Forks: 28

═══════════════════════════════
Review queue item
Priority: CRITICAL

Retcon #2912

Title: The Fall of Omashu

Requested Change: King survives

Impact: 12 Nations · 344 Books · 5,944 Characters

Risk: Severe

Actions:
[Approve] [Reject] [Branch Timeline] [Escalate]
Continuity violation
WARNING

Character: Kaien

Problem: Dead in Chapter 32

Appears Alive: Chapter 35

Actions:
[Investigate]
Lore violation
Spirit Wolf

Issue: Appears before species is discovered

Severity: Medium
AI review verdicts
Historian AI      PASS       Reliability: 98%
Relationship AI   WARNING    Marriage timeline inconsistent
Flagged content
Book: Rise of the Southern King
Flags: Historical Accuracy
Reports: 12

Actions:
[Archive] [Label] [Review] [Dismiss]
Timeline command centre
Primary Timeline
Population: 18,447,221
Books: 2,100,442
Branches: 42

Main
├ Branch A
├ Branch B
│ ├ Branch B1
│ └ Branch B2
└ Branch C

11. API authentication architecture

At this scale, authentication is JWT plus role claims plus audit signatures. A token proves who you are; it never proves what you are allowed to do on its own.

  • The token carries identity, roles and scopes, but the service re-checks the permission against the database, so a revoked role takes effect immediately.
  • Canon Security Layer: canon_lock, timeline_merge and rollback require a role check plus an audit entry plus an approval chain. A token alone is never sufficient.
  • Refresh tokens are rotated on every use and never reused (see section 16).
Authentication flow
Login
  ↓
Identity Service
  ↓
JWT Token
  ↓
API Gateway
  ↓
Game Services
JWT payload
{
  "sub": "player_791",
  "roles": ["player", "historian"],
  "clans": ["dragon_clan"],
  "cities": ["republic_city"],
  "permissions": ["read_books", "submit_retcon"],
  "exp": 1770000000
}
Service authorization example
POST /retcons/291/approve

Checks:
  Has approve_retcon?
If no:
  403 Forbidden

12. Audit logs and the canon ledger

Nothing in history should ever disappear. Every action writes an immutable log entry, and every canon change is signed into a chain so revisions can be proven in order.

  • Audit search filters: user, role, action, date, novel, chapter, timeline, clan, city.
  • Every entry stores the before and after state, so a change can be read without loading either version.
  • IP addresses are hashed, never stored raw.
  • The canon ledger forms an unbroken chain: each version carries the signature of the one before it.
Audit entry
{
  "auditId": "audit_92912",
  "timestamp": "2028-01-04T12:33:21Z",
  "userId": "player_991",
  "action": "approve_retcon",
  "target": "chapter_772",
  "oldVersion": "7.1",
  "newVersion": "8.0",
  "ip": "hidden",
  "reason": "Lore correction"
}
Audit dashboard
Recent Actions

09:21  ModeratorA    Approved Retcon      Chapter 81
──────────────────────────────────────────────
09:16  Historian44   Reviewed Timeline    Branch C
──────────────────────────────────────────────
09:14  Player991     Submitted Retcon     War of Red Valley
Immutable canon ledger
{
  "event": "Avatar Coronation",
  "version": "1.0",
  "signature": "abc123xyz"
}

When canon changes:

{
  "event": "Avatar Coronation",
  "version": "2.0",
  "previousSignature": "abc123xyz",
  "signature": "def456uvw"
}

13. The Supreme Historical Council

At the top of the system sits a small group of moderators and AI reviewer agents who oversee world history. Before any retcon touching an Avatar, a nation, a major war, a Spirit Realm event, the founding of a city or a legendary bloodline can enter canon, it must pass the full chain.

  • Each AI reviewer can pass, warn or block; a block stops the chain before any human sees it.
  • A moderator vote requires a quorum, and the vote itself is audited.
  • Council approval is the only path that can write a new canon signature for a protected fact.
Approval chain
Historian AI
  ↓
Lore AI
  ↓
Continuity AI
  ↓
Economy AI
  ↓
Politics AI
  ↓
Moderator Vote
  ↓
Council Approval
  ↓
Canon Ledger Update

14. Security and authorization database

Roles and permissions are small tables read on every request, so they are indexed aggressively. Six tables carry the model: roles, permissions, role_permissions, permission_inheritance, user_roles and permission_overrides.

  • roles — the named roles, each with a priority level.
  • permissions — the atomic keys, e.g. read_novel, edit_novel, approve_retcon, rollback_timeline, lock_canon, merge_branch, submit_review.
  • role_permissions — the many-to-many assignment of permissions to roles.
  • permission_inheritance — the role hierarchy, so a senior role inherits every junior role beneath it.
  • user_roles — who holds which role, and at what scope (global, nation, city, clan, family).
  • permission_overrides — per-user exceptions, ALLOW or DENY, with DENY always winning.

15. Moderation API endpoints

The governance surface is grouped into six areas. Every endpoint below is specified in full in section 23.

AreaMethod and pathPurpose
QueueGET /api/moderation/queueList pending reviews, filterable by status and severity
RetconsGET /api/moderation/retcons/{id}Read one retcon request with its impact
RetconsPOST /api/moderation/retcons/{id}/approveApprove a retcon into canon
RetconsPOST /api/moderation/retcons/{id}/rejectReject and keep the request on record
RetconsPOST /api/moderation/retcons/{id}/branchExplore the change as an alternate timeline
CanonPOST /api/moderation/canon/lockPin a canon fact
CanonPOST /api/moderation/canon/unlockRelease a canon lock
CanonGET /api/moderation/canon/history/{factId}Read the signed revision chain of a fact
TimelineGET /api/moderation/timelinesList timeline branches
TimelinePOST /api/moderation/timelines/branchFork a timeline
TimelinePOST /api/moderation/timelines/mergeMerge a branch (two-person approval)
TimelinePOST /api/moderation/timelines/rollbackRoll back to a version (two-person approval)
AuditGET /api/moderation/auditSearch the audit log
AuditGET /api/moderation/audit/{id}Read one audit entry
AuditGET /api/moderation/audit/user/{userId}Every action by one user
ContinuityGET /api/moderation/continuity/errorsList continuity errors
ContinuityPOST /api/moderation/continuity/fixResolve a continuity error
ContinuityPOST /api/moderation/continuity/mark-reviewedMark errors reviewed without changing canon
RetconsPOST /api/retconsSubmit a retcon request (players)

16. Tokens, sessions and rotation

Authentication uses an access token, a refresh token, a session record and an audit record. Raw token text is never stored — only a hash.

Refresh tokens are never reused. When refresh token A issues refresh token B, A is revoked immediately. This prevents replay attacks, and a reused token revokes its whole family.

  • Re-authentication is required after a moderator or administrator session expires.
  • Tokens are stored as hashes; a leaked database does not leak usable sessions.
  • Each refresh token records the family it belongs to and the token it was rotated from, so a stolen chain can be revoked in one statement.
TokenLifetime
Access token15 minutes
Refresh token30 days
Moderator session8 hours
Administrator session4 hours

17. Rate limiting

Different actions carry different limits. Reading is cheap and generous; generation is expensive and tightly bounded.

Actor / actionLimitWindow
Readers300 requests1 minute
Writers (chapter actions)60 actions1 minute
AI novel generation10 active generationsper user, queued beyond
Retcon requests10 requests1 hour
Moderators300 moderation actions1 hour
AdministratorsNo API limitstill fully audited

18. Audit schema and high-security actions

Everything writes to audit. A small set of actions is dangerous enough to require two-person approval: delete timeline, merge canon branch, Avatar history rewrite, world event removal and global rollback.

Two-person approval workflow
Moderator A
  approves
      ↓
Moderator B
  approves
      ↓
System executes
      ↓
Canon ledger signature written

19. Supreme canon protection layer

For the largest events, a final table records a signed chain of revisions. Each row points at the signature it replaced, making every novel, chapter, timeline and retcon fully traceable from the first day of the world to the present.

canon_signatures
CREATE TABLE canon_signatures (
    signature_id UUID PRIMARY KEY,
    entity_id UUID,
    version_number INT,
    previous_signature UUID,
    approved_by UUID,
    signed_at TIMESTAMP
);

20. Complete SQL schema

One migration creates the whole governance model. It is written for PostgreSQL and is intended to run as a single transaction.

Note the correction on user_roles: a nullable scope_id cannot participate in a primary key, so the table carries a surrogate user_role_id and enforces uniqueness with an expression index instead.

001_governance.sql
BEGIN;

CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- ─── Roles ───────────────────────────────────────────────
CREATE TABLE roles (
    role_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_name VARCHAR(100) NOT NULL UNIQUE,
    description TEXT,
    priority_level INT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    CONSTRAINT chk_priority CHECK (priority_level >= 0)
);
CREATE INDEX idx_roles_name ON roles (role_name);
CREATE INDEX idx_roles_priority ON roles (priority_level DESC);

-- ─── Permissions ─────────────────────────────────────────
CREATE TABLE permissions (
    permission_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    permission_key VARCHAR(100) NOT NULL UNIQUE,
    description TEXT
);
CREATE INDEX idx_permissions_key ON permissions (permission_key);

-- ─── Role ↔ permission ───────────────────────────────────
CREATE TABLE role_permissions (
    role_id UUID NOT NULL,
    permission_id UUID NOT NULL,
    PRIMARY KEY (role_id, permission_id),
    FOREIGN KEY (role_id) REFERENCES roles (role_id) ON DELETE CASCADE,
    FOREIGN KEY (permission_id) REFERENCES permissions (permission_id) ON DELETE CASCADE
);
CREATE INDEX idx_role_permissions_role ON role_permissions (role_id);

-- ─── Hierarchy ───────────────────────────────────────────
-- parent_role_id = senior role, child_role_id = junior role.
-- A senior role inherits every permission held by its descendants.
CREATE TABLE permission_inheritance (
    parent_role_id UUID NOT NULL,
    child_role_id UUID NOT NULL,
    PRIMARY KEY (parent_role_id, child_role_id),
    FOREIGN KEY (parent_role_id) REFERENCES roles (role_id) ON DELETE CASCADE,
    FOREIGN KEY (child_role_id) REFERENCES roles (role_id) ON DELETE CASCADE,
    CONSTRAINT chk_no_self_inheritance CHECK (parent_role_id <> child_role_id)
);

-- ─── Assignments ─────────────────────────────────────────
CREATE TABLE user_roles (
    user_role_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    role_id UUID NOT NULL,
    scope_type VARCHAR(50) NOT NULL DEFAULT 'global',
    scope_id UUID,
    assigned_by UUID,
    assigned_at TIMESTAMP NOT NULL DEFAULT now(),
    expires_at TIMESTAMP,
    FOREIGN KEY (role_id) REFERENCES roles (role_id) ON DELETE CASCADE,
    CONSTRAINT chk_scope_type CHECK (
        scope_type IN ('global', 'nation', 'city', 'clan', 'family')
    ),
    CONSTRAINT chk_scope_id CHECK (
        (scope_type = 'global' AND scope_id IS NULL)
        OR (scope_type <> 'global' AND scope_id IS NOT NULL)
    ),
    CONSTRAINT chk_expiry_future CHECK (
        expires_at IS NULL OR expires_at > assigned_at
    )
);
CREATE UNIQUE INDEX uq_user_role_scope
    ON user_roles (
        user_id,
        role_id,
        scope_type,
        COALESCE(scope_id, '00000000-0000-0000-0000-000000000000'::uuid)
    );
CREATE INDEX idx_user_roles_user ON user_roles (user_id);
CREATE INDEX idx_user_roles_scope ON user_roles (scope_type, scope_id);

-- ─── Per-user exceptions ─────────────────────────────────
CREATE TABLE permission_overrides (
    override_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    permission_id UUID NOT NULL,
    effect VARCHAR(10) NOT NULL,
    granted_by UUID,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    expires_at TIMESTAMP,
    FOREIGN KEY (permission_id) REFERENCES permissions (permission_id) ON DELETE CASCADE,
    CONSTRAINT chk_effect CHECK (effect IN ('ALLOW', 'DENY'))
);
CREATE UNIQUE INDEX uq_override
    ON permission_overrides (user_id, permission_id);
CREATE INDEX idx_overrides_user ON permission_overrides (user_id);

-- ─── Retcon requests ─────────────────────────────────────
CREATE TABLE retcon_requests (
    retcon_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(200) NOT NULL,
    requested_by UUID NOT NULL,
    target_entity_type VARCHAR(100) NOT NULL,
    target_entity_id UUID NOT NULL,
    requested_change TEXT NOT NULL,
    reason TEXT,
    priority VARCHAR(20) NOT NULL DEFAULT 'normal',
    risk VARCHAR(20) NOT NULL DEFAULT 'low',
    impact JSONB NOT NULL DEFAULT '{}'::jsonb,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    reviewed_by UUID,
    reviewed_at TIMESTAMP,
    decision_note TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    CONSTRAINT chk_retcon_priority CHECK (
        priority IN ('low', 'normal', 'high', 'critical')
    ),
    CONSTRAINT chk_retcon_risk CHECK (
        risk IN ('low', 'moderate', 'severe', 'existential')
    ),
    CONSTRAINT chk_retcon_status CHECK (
        status IN ('pending', 'in_review', 'approved', 'rejected', 'branched')
    )
);
CREATE INDEX idx_retcons_status ON retcon_requests (status, priority);
CREATE INDEX idx_retcons_target ON retcon_requests (target_entity_type, target_entity_id);

-- ─── Canon facts and locks ───────────────────────────────
CREATE TABLE canon_facts (
    fact_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    fact_key VARCHAR(200) NOT NULL UNIQUE,
    statement TEXT NOT NULL,
    entity_type VARCHAR(100),
    entity_id UUID,
    locked BOOLEAN NOT NULL DEFAULT FALSE,
    locked_by UUID,
    locked_at TIMESTAMP,
    version_number INT NOT NULL DEFAULT 1,
    current_signature UUID,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    updated_at TIMESTAMP NOT NULL DEFAULT now()
);
CREATE INDEX idx_canon_facts_entity ON canon_facts (entity_type, entity_id);
CREATE INDEX idx_canon_facts_locked ON canon_facts (locked) WHERE locked;

-- ─── Timelines ───────────────────────────────────────────
CREATE TABLE timeline_branches (
    branch_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(200) NOT NULL,
    parent_branch_id UUID REFERENCES timeline_branches (branch_id) ON DELETE SET NULL,
    forked_from_version INT,
    forked_from_fact UUID REFERENCES canon_facts (fact_id) ON DELETE SET NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    created_by UUID,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    merged_at TIMESTAMP,
    CONSTRAINT chk_branch_status CHECK (
        status IN ('active', 'merged', 'abandoned', 'archived')
    )
);
CREATE INDEX idx_branches_parent ON timeline_branches (parent_branch_id);

-- ─── Tokens ──────────────────────────────────────────────
CREATE TABLE access_tokens (
    token_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    token_hash TEXT NOT NULL,
    issued_at TIMESTAMP NOT NULL DEFAULT now(),
    expires_at TIMESTAMP NOT NULL,
    revoked BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX idx_access_tokens_user ON access_tokens (user_id);
CREATE INDEX idx_access_tokens_hash ON access_tokens (token_hash);

CREATE TABLE refresh_tokens (
    token_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    token_hash TEXT NOT NULL,
    family_id UUID NOT NULL,
    rotated_from UUID REFERENCES refresh_tokens (token_id) ON DELETE SET NULL,
    issued_at TIMESTAMP NOT NULL DEFAULT now(),
    expires_at TIMESTAMP NOT NULL,
    revoked BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX idx_refresh_tokens_user ON refresh_tokens (user_id);
CREATE INDEX idx_refresh_tokens_family ON refresh_tokens (family_id);

-- ─── Rate limits ─────────────────────────────────────────
CREATE TABLE rate_limits (
    rate_limit_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    scope_type VARCHAR(50) NOT NULL DEFAULT 'user',
    scope_id UUID,
    action_key VARCHAR(100) NOT NULL,
    limit_count INT NOT NULL,
    period_seconds INT NOT NULL,
    CONSTRAINT chk_limit_positive CHECK (limit_count > 0 AND period_seconds > 0)
);
CREATE UNIQUE INDEX uq_rate_limit
    ON rate_limits (
        scope_type,
        action_key,
        COALESCE(scope_id, '00000000-0000-0000-0000-000000000000'::uuid)
    );

-- ─── Audit ───────────────────────────────────────────────
CREATE TABLE audit_logs (
    audit_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    actor_user_id UUID NOT NULL,
    action_type VARCHAR(100) NOT NULL,
    entity_type VARCHAR(100) NOT NULL,
    entity_id UUID,
    old_data JSONB,
    new_data JSONB,
    reason TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT now(),
    ip_hash VARCHAR(255) NOT NULL
);
CREATE INDEX idx_audit_actor ON audit_logs (actor_user_id, created_at DESC);
CREATE INDEX idx_audit_entity ON audit_logs (entity_type, entity_id, created_at DESC);
CREATE INDEX idx_audit_action ON audit_logs (action_type, created_at DESC);

-- ─── Canon signatures ────────────────────────────────────
CREATE TABLE canon_signatures (
    signature_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    entity_id UUID NOT NULL,
    entity_type VARCHAR(100) NOT NULL,
    version_number INT NOT NULL,
    previous_signature UUID REFERENCES canon_signatures (signature_id) ON DELETE SET NULL,
    payload_hash TEXT NOT NULL,
    approved_by UUID,
    signed_at TIMESTAMP NOT NULL DEFAULT now(),
    CONSTRAINT chk_signature_version CHECK (version_number > 0)
);
CREATE UNIQUE INDEX uq_signature_version
    ON canon_signatures (entity_type, entity_id, version_number);

COMMIT;

21. Seed data

The seed installs the ten roles, the permission keys, the grant map, the inheritance edges and the default rate limits. It is idempotent: running it twice changes nothing.

002_seed.sql
BEGIN;

INSERT INTO roles (role_name, description, priority_level) VALUES
    ('player',             'Every signed-in player',                    1),
    ('clan_member',        'Member of a clan',                          5),
    ('clan_officer',       'Officer of a clan',                        10),
    ('historian',          'Reviews books and records',                15),
    ('clan_leader',        'Leads a clan',                             20),
    ('city_official',      'Serves a city administration',             25),
    ('governor',           'Governs a city',                           30),
    ('military_commander', 'Commands a nation''s forces',              35),
    ('canon_moderator',    'Approves retcons and guards canon',        90),
    ('administrator',      'Full platform authority',                 100)
ON CONFLICT (role_name) DO NOTHING;

INSERT INTO permissions (permission_key, description) VALUES
    ('read_novel',        'Read chronicles and novels'),
    ('comment_novel',     'Comment on a published chapter'),
    ('generate_novel',    'Spend AI generation on a new chapter'),
    ('submit_retcon',     'Propose a change to canon'),
    ('review_retcon',     'Read and annotate a retcon request'),
    ('approve_retcon',    'Approve a retcon into canon'),
    ('reject_retcon',     'Reject a retcon request'),
    ('edit_canon',        'Edit canon prose'),
    ('delete_canon',      'Remove canon content'),
    ('lock_canon',        'Pin a canon fact'),
    ('unlock_canon',      'Release a canon lock'),
    ('branch_timeline',   'Fork an alternate timeline'),
    ('merge_timeline',    'Merge a timeline branch'),
    ('rollback_timeline', 'Roll a timeline back to a version'),
    ('view_audit',        'Read audit logs'),
    ('export_audit',      'Export audit logs'),
    ('moderate_content',  'Archive or label flagged content'),
    ('manage_roles',      'Assign and revoke roles')
ON CONFLICT (permission_key) DO NOTHING;

-- Grant map
WITH grants (role_name, permission_key) AS (
    VALUES
        ('player', 'read_novel'),
        ('player', 'comment_novel'),
        ('player', 'submit_retcon'),
        ('player', 'generate_novel'),

        ('clan_member', 'read_novel'),
        ('clan_member', 'comment_novel'),

        ('clan_officer', 'submit_retcon'),

        ('clan_leader', 'submit_retcon'),
        ('clan_leader', 'edit_canon'),

        ('historian', 'review_retcon'),
        ('historian', 'view_audit'),
        ('historian', 'edit_canon'),

        ('city_official', 'review_retcon'),

        ('governor', 'review_retcon'),
        ('governor', 'view_audit'),

        ('military_commander', 'view_audit'),

        ('canon_moderator', 'approve_retcon'),
        ('canon_moderator', 'reject_retcon'),
        ('canon_moderator', 'lock_canon'),
        ('canon_moderator', 'unlock_canon'),
        ('canon_moderator', 'branch_timeline'),
        ('canon_moderator', 'merge_timeline'),
        ('canon_moderator', 'rollback_timeline'),
        ('canon_moderator', 'delete_canon'),
        ('canon_moderator', 'export_audit'),
        ('canon_moderator', 'moderate_content'),

        ('administrator', 'manage_roles')
)
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.role_id, p.permission_id
FROM grants g
JOIN roles r ON r.role_name = g.role_name
JOIN permissions p ON p.permission_key = g.permission_key
ON CONFLICT DO NOTHING;

-- Inheritance: parent = senior, child = junior
INSERT INTO permission_inheritance (parent_role_id, child_role_id)
SELECT parent.role_id, child.role_id
FROM (VALUES
    ('administrator',      'canon_moderator'),
    ('administrator',      'military_commander'),
    ('canon_moderator',    'historian'),
    ('historian',          'player'),
    ('governor',           'city_official'),
    ('city_official',      'player'),
    ('military_commander', 'player'),
    ('clan_leader',        'clan_officer'),
    ('clan_officer',       'clan_member'),
    ('clan_member',        'player')
) AS edges (parent_name, child_name)
JOIN roles parent ON parent.role_name = edges.parent_name
JOIN roles child  ON child.role_name  = edges.child_name
ON CONFLICT DO NOTHING;

-- Default rate limits
INSERT INTO rate_limits (scope_type, action_key, limit_count, period_seconds)
VALUES
    ('role', 'read_request',      300,    60),
    ('role', 'write_chapter',      60,    60),
    ('role', 'generate_novel',     10, 86400),
    ('role', 'submit_retcon',      10,  3600),
    ('role', 'moderation_action', 300,  3600),
    ('role', 'auth_login',         20,   300)
ON CONFLICT DO NOTHING;

COMMIT;

22. OpenAPI specification — header and components

The governance API is specified in full across this section and the next: authentication, shared parameters, every request and response schema, and then every endpoint. The two blocks are one openapi.yaml, split only so each can be read on its own.

openapi.yaml — header and components
openapi: 3.1.0
info:
  title: Elemental Dynasty — Moderation and Canon API
  version: 1.0.0
  description: >
    Governance API for chronicles, retcons, canon locks, timelines and audit.
    All endpoints require a bearer JWT whose subject resolves to a user with
    the required permission and, where relevant, the required scope.
servers:
  - url: https://api.elemental-dynasty.online
    description: Production
  - url: http://localhost:8000
    description: Local development

security:
  - bearerAuth: []

tags:
  - name: Moderation
  - name: Canon
  - name: Timeline
  - name: Audit
  - name: Continuity
  - name: Retcons
  - name: Auth

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  parameters:
    Page:
      name: page
      in: query
      schema: { type: integer, minimum: 1, default: 1 }
    PageSize:
      name: page_size
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
    Severity:
      name: severity
      in: query
      schema: { type: string, enum: [low, medium, high, critical] }
    Status:
      name: status
      in: query
      schema:
        type: string
        enum: [pending, in_review, approved, rejected, branched]
    RetconId:
      name: retcon_id
      in: path
      required: true
      schema: { type: string, format: uuid }
    FactId:
      name: fact_id
      in: path
      required: true
      schema: { type: string, format: uuid }
    AuditId:
      name: audit_id
      in: path
      required: true
      schema: { type: string, format: uuid }
    UserId:
      name: user_id
      in: path
      required: true
      schema: { type: string, format: uuid }

  schemas:
    Error:
      type: object
      required: [error, message]
      properties:
        error: { type: string, example: forbidden }
        message: { type: string, example: Missing permission approve_retcon }
        request_id: { type: string }

    RateLimited:
      allOf:
        - $ref: '#/components/schemas/Error'
        - type: object
          properties:
            retry_after_seconds: { type: integer, example: 42 }

    RetconRequest:
      type: object
      required: [title, target_entity_type, target_entity_id, requested_change]
      properties:
        title: { type: string, maxLength: 200 }
        target_entity_type:
          type: string
          enum: [chapter, novel, fact, timeline, character, city, clan, nation]
        target_entity_id: { type: string, format: uuid }
        requested_change: { type: string, maxLength: 4000 }
        reason: { type: string, maxLength: 2000 }
        priority: { type: string, enum: [low, normal, high, critical], default: normal }

    Retcon:
      allOf:
        - $ref: '#/components/schemas/RetconRequest'
        - type: object
          properties:
            retcon_id: { type: string, format: uuid }
            requested_by: { type: string, format: uuid }
            risk: { type: string, enum: [low, moderate, severe, existential] }
            status: { type: string, enum: [pending, in_review, approved, rejected, branched] }
            impact:
              type: object
              properties:
                nations: { type: integer }
                books: { type: integer }
                characters: { type: integer }
            created_at: { type: string, format: date-time }

    RetconDecision:
      type: object
      required: [reason]
      properties:
        reason: { type: string, maxLength: 2000 }
        two_person_token:
          type: string
          description: Second approver's confirmation token, required for severe and existential risk

    QueueItem:
      type: object
      properties:
        retcon_id: { type: string, format: uuid }
        title: { type: string }
        priority: { type: string, enum: [low, normal, high, critical] }
        risk: { type: string, enum: [low, moderate, severe, existential] }
        status: { type: string }
        age_hours: { type: integer }
        impact:
          type: object
          properties:
            nations: { type: integer }
            books: { type: integer }
            characters: { type: integer }

    ModerationQueue:
      type: object
      properties:
        total: { type: integer }
        items:
          type: array
          items: { $ref: '#/components/schemas/QueueItem' }

    CanonLockRequest:
      type: object
      required: [fact_id, reason]
      properties:
        fact_id: { type: string, format: uuid }
        reason: { type: string, maxLength: 1000 }
        expires_at: { type: string, format: date-time, nullable: true }

    CanonFact:
      type: object
      properties:
        fact_id: { type: string, format: uuid }
        fact_key: { type: string }
        statement: { type: string }
        locked: { type: boolean }
        locked_by: { type: string, format: uuid, nullable: true }
        version_number: { type: integer }
        current_signature: { type: string, format: uuid, nullable: true }
        updated_at: { type: string, format: date-time }

    CanonHistoryEntry:
      type: object
      properties:
        version_number: { type: integer }
        statement: { type: string }
        signature: { type: string, format: uuid }
        previous_signature: { type: string, format: uuid, nullable: true }
        approved_by: { type: string, format: uuid }
        signed_at: { type: string, format: date-time }

    Timeline:
      type: object
      properties:
        branch_id: { type: string, format: uuid }
        name: { type: string }
        parent_branch_id: { type: string, format: uuid, nullable: true }
        status: { type: string, enum: [active, merged, abandoned, archived] }
        population: { type: integer }
        books: { type: integer }
        created_at: { type: string, format: date-time }

    TimelineBranchRequest:
      type: object
      required: [name, forked_from_fact]
      properties:
        name: { type: string, maxLength: 200 }
        forked_from_fact: { type: string, format: uuid }
        parent_branch_id: { type: string, format: uuid, nullable: true }
        note: { type: string, maxLength: 1000 }

    TimelineMergeRequest:
      type: object
      required: [source_branch_id, target_branch_id, reason]
      properties:
        source_branch_id: { type: string, format: uuid }
        target_branch_id: { type: string, format: uuid }
        reason: { type: string, maxLength: 2000 }
        two_person_token: { type: string }

    TimelineRollbackRequest:
      type: object
      required: [branch_id, to_version, reason]
      properties:
        branch_id: { type: string, format: uuid }
        to_version: { type: integer, minimum: 1 }
        reason: { type: string, maxLength: 2000 }
        two_person_token: { type: string }

    AuditEntry:
      type: object
      properties:
        audit_id: { type: string, format: uuid }
        actor_user_id: { type: string, format: uuid }
        action_type: { type: string }
        entity_type: { type: string }
        entity_id: { type: string, format: uuid, nullable: true }
        old_data: { type: object, nullable: true }
        new_data: { type: object, nullable: true }
        reason: { type: string, nullable: true }
        ip_hash: { type: string }
        created_at: { type: string, format: date-time }

    AuditPage:
      type: object
      properties:
        total: { type: integer }
        items:
          type: array
          items: { $ref: '#/components/schemas/AuditEntry' }

    ContinuityError:
      type: object
      properties:
        error_id: { type: string, format: uuid }
        entity_type: { type: string }
        entity_id: { type: string, format: uuid }
        entity_name: { type: string }
        problem: { type: string }
        first_seen_chapter: { type: integer }
        violated_in_chapter: { type: integer }
        severity: { type: string, enum: [low, medium, high, critical] }
        status: { type: string, enum: [open, investigating, fixed, reviewed] }

    ContinuityFixRequest:
      type: object
      required: [error_id, resolution]
      properties:
        error_id: { type: string, format: uuid }
        resolution: { type: string, enum: [retcon, annotate, branch, dismiss] }
        note: { type: string, maxLength: 2000 }

    ContinuityReviewRequest:
      type: object
      required: [error_ids]
      properties:
        error_ids:
          type: array
          minItems: 1
          items: { type: string, format: uuid }

    TokenRequest:
      type: object
      required: [email, password]
      properties:
        email: { type: string, format: email }
        password: { type: string, minLength: 8 }

    RefreshRequest:
      type: object
      required: [refresh_token]
      properties:
        refresh_token: { type: string }

    TokenResponse:
      type: object
      properties:
        access_token: { type: string }
        refresh_token: { type: string }
        token_type: { type: string, example: Bearer }
        expires_in: { type: integer, example: 900 }

23. OpenAPI specification — paths

Every endpoint of the governance surface, with its permission, its request body and its complete response set including 401, 403, 409 and 429.

openapi.yaml — paths
paths:
  # ─── Auth ──────────────────────────────────────────────
  /api/auth/token:
    post:
      tags: [Auth]
      security: []
      summary: Exchange credentials for a token pair
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TokenRequest' }
      responses:
        '200':
          description: Issued
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TokenResponse' }
        '401':
          description: Invalid credentials
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: Too many attempts
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RateLimited' }

  /api/auth/refresh:
    post:
      tags: [Auth]
      security: []
      summary: Rotate a refresh token
      description: >
        Revokes the presented refresh token and issues a new pair. Reuse of a
        rotated token revokes its entire family.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RefreshRequest' }
      responses:
        '200':
          description: Rotated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TokenResponse' }
        '401':
          description: Token invalid, expired or already rotated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  # ─── Retcons ───────────────────────────────────────────
  /api/retcons:
    post:
      tags: [Retcons]
      summary: Submit a retcon request
      description: Requires submit_retcon. Limited to 10 requests per hour per user.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RetconRequest' }
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Retcon' }
        '400':
          description: Malformed request
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: Missing or invalid token
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: Rate limited
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RateLimited' }

  # ─── Moderation queue ─────────────────────────────────
  /api/moderation/queue:
    get:
      tags: [Moderation]
      summary: List the moderation queue
      description: Requires review_retcon.
      parameters:
        - $ref: '#/components/parameters/Status'
        - $ref: '#/components/parameters/Severity'
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PageSize'
      responses:
        '200':
          description: A page of queue items
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ModerationQueue' }
        '401':
          description: Missing or invalid token
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/retcons/{retcon_id}:
    get:
      tags: [Moderation]
      summary: Read one retcon request
      parameters:
        - $ref: '#/components/parameters/RetconId'
      responses:
        '200':
          description: The request
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Retcon' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/retcons/{retcon_id}/approve:
    post:
      tags: [Moderation]
      summary: Approve a retcon into canon
      description: >
        Requires approve_retcon. Writes an audit entry and a canon signature.
        Protected facts require a second approver token.
      parameters:
        - $ref: '#/components/parameters/RetconId'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RetconDecision' }
      responses:
        '200':
          description: Approved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Retcon' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: Already decided, or second approver missing
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422':
          description: Validation failed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/retcons/{retcon_id}/reject:
    post:
      tags: [Moderation]
      summary: Reject a retcon request
      description: Requires reject_retcon. The request is kept as rejected.
      parameters:
        - $ref: '#/components/parameters/RetconId'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RetconDecision' }
      responses:
        '200':
          description: Rejected
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Retcon' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/retcons/{retcon_id}/branch:
    post:
      tags: [Moderation]
      summary: Explore a retcon as an alternate timeline
      description: Requires branch_timeline. The main line is untouched.
      parameters:
        - $ref: '#/components/parameters/RetconId'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimelineBranchRequest' }
      responses:
        '201':
          description: Branch created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Timeline' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  # ─── Canon ────────────────────────────────────────────
  /api/moderation/canon/lock:
    post:
      tags: [Canon]
      summary: Lock a canon fact
      description: Requires lock_canon. Locked facts reject retcons until unlocked.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CanonLockRequest' }
      responses:
        '200':
          description: Locked
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CanonFact' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: Fact not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/canon/unlock:
    post:
      tags: [Canon]
      summary: Release a canon lock
      description: Requires unlock_canon. Writes an audit entry.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CanonLockRequest' }
      responses:
        '200':
          description: Unlocked
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CanonFact' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/canon/history/{fact_id}:
    get:
      tags: [Canon]
      summary: Read the signed history of a canon fact
      parameters:
        - $ref: '#/components/parameters/FactId'
      responses:
        '200':
          description: Versions, oldest first
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/CanonHistoryEntry' }
        '404':
          description: Fact not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

23b. OpenAPI paths — timelines, audit and continuity

The second half of the paths block, continuing the same document.

openapi.yaml — paths (continued)
  # ─── Timelines ────────────────────────────────────────
  /api/moderation/timelines:
    get:
      tags: [Timeline]
      summary: List timeline branches
      parameters:
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PageSize'
      responses:
        '200':
          description: Branches
          content:
            application/json:
              schema:
                type: object
                properties:
                  total: { type: integer }
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/Timeline' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/timelines/branch:
    post:
      tags: [Timeline]
      summary: Fork a timeline
      description: Requires branch_timeline.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimelineBranchRequest' }
      responses:
        '201':
          description: Branch created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Timeline' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/timelines/merge:
    post:
      tags: [Timeline]
      summary: Merge a branch into another
      description: Requires merge_timeline and a second approver token.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimelineMergeRequest' }
      responses:
        '200':
          description: Merged
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Timeline' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: Second approver missing, or branch already merged
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/timelines/rollback:
    post:
      tags: [Timeline]
      summary: Roll a timeline back to an earlier version
      description: Requires rollback_timeline and a second approver token.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TimelineRollbackRequest' }
      responses:
        '200':
          description: Rolled back
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Timeline' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: Second approver missing
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  # ─── Audit ────────────────────────────────────────────
  /api/moderation/audit:
    get:
      tags: [Audit]
      summary: Search the audit log
      description: Requires view_audit.
      parameters:
        - name: user
          in: query
          schema: { type: string, format: uuid }
        - name: role
          in: query
          schema: { type: string }
        - name: action
          in: query
          schema: { type: string }
        - name: entity_type
          in: query
          schema: { type: string }
        - name: from
          in: query
          schema: { type: string, format: date-time }
        - name: to
          in: query
          schema: { type: string, format: date-time }
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PageSize'
      responses:
        '200':
          description: A page of audit entries, newest first
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AuditPage' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/audit/{audit_id}:
    get:
      tags: [Audit]
      summary: Read one audit entry
      parameters:
        - $ref: '#/components/parameters/AuditId'
      responses:
        '200':
          description: The entry
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AuditEntry' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/audit/user/{user_id}:
    get:
      tags: [Audit]
      summary: Read every action by one user
      parameters:
        - $ref: '#/components/parameters/UserId'
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PageSize'
      responses:
        '200':
          description: A page of that user's entries
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AuditPage' }

  # ─── Continuity ───────────────────────────────────────
  /api/moderation/continuity/errors:
    get:
      tags: [Continuity]
      summary: List continuity errors
      parameters:
        - $ref: '#/components/parameters/Severity'
        - $ref: '#/components/parameters/Page'
        - $ref: '#/components/parameters/PageSize'
      responses:
        '200':
          description: Errors
          content:
            application/json:
              schema:
                type: object
                properties:
                  total: { type: integer }
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/ContinuityError' }

  /api/moderation/continuity/fix:
    post:
      tags: [Continuity]
      summary: Resolve a continuity error
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContinuityFixRequest' }
      responses:
        '200':
          description: Resolved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContinuityError' }
        '403':
          description: Missing permission
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }

  /api/moderation/continuity/mark-reviewed:
    post:
      tags: [Continuity]
      summary: Mark errors reviewed without changing canon
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContinuityReviewRequest' }
      responses:
        '200':
          description: Marked
          content:
            application/json:
              schema:
                type: object
                properties:
                  updated: { type: integer }

24. RBAC, rate-limit and audit middleware

The middleware is where the rules become real. Three pieces do the work: permission resolution (which walks the role hierarchy and applies overrides), a rate limiter (a Redis sliding window), and an audit writer (called inside each privileged handler so the change and its record commit together).

app/security/jwt.py
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from app.settings import settings

ALGORITHM = "HS256"
bearer = HTTPBearer(auto_error=False)


def decode_token(token: str) -> dict:
    try:
        return jwt.decode(
            token,
            settings.JWT_SECRET,
            algorithms=[ALGORITHM],
            options={"require": ["exp", "sub"]},
        )
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")


async def current_claims(
    credentials: HTTPAuthorizationCredentials = Depends(bearer),
) -> dict:
    if credentials is None:
        raise HTTPException(status_code=401, detail="Missing bearer token")
    return decode_token(credentials.credentials)
app/security/permissions.py
from dataclasses import dataclass

from fastapi import Depends, HTTPException
from sqlalchemy import text

from app.db import engine
from app.security.jwt import current_claims

INHERITED_PERMISSIONS = text("""
WITH RECURSIVE granted AS (
    SELECT role_id
    FROM roles
    WHERE role_name = ANY(:role_names)
    UNION
    SELECT pi.child_role_id
    FROM permission_inheritance pi
    JOIN granted g ON g.role_id = pi.parent_role_id
)
SELECT DISTINCT p.permission_key
FROM granted g
JOIN role_permissions rp ON rp.role_id = g.role_id
JOIN permissions p ON p.permission_id = rp.permission_id
""")

OVERRIDES = text("""
SELECT p.permission_key, o.effect
FROM permission_overrides o
JOIN permissions p ON p.permission_id = o.permission_id
WHERE o.user_id = :user_id
  AND (o.expires_at IS NULL OR o.expires_at > now())
""")


@dataclass(frozen=True)
class Principal:
    user_id: str
    roles: tuple
    clans: tuple
    cities: tuple
    permissions: frozenset

    def can(self, permission: str) -> bool:
        return permission in self.permissions


async def load_principal(claims: dict) -> Principal:
    user_id = claims.get("sub")
    if not user_id:
        raise HTTPException(status_code=401, detail="Token has no subject")

    roles = tuple(claims.get("roles") or [])

    async with engine.connect() as conn:
        rows = await conn.execute(INHERITED_PERMISSIONS, {"role_names": list(roles)})
        allowed = {row[0] for row in rows}

        rows = await conn.execute(OVERRIDES, {"user_id": user_id})
        for permission_key, effect in rows:
            if effect == "DENY":
                allowed.discard(permission_key)
            elif effect == "ALLOW":
                allowed.add(permission_key)

    return Principal(
        user_id=user_id,
        roles=roles,
        clans=tuple(claims.get("clans") or []),
        cities=tuple(claims.get("cities") or []),
        permissions=frozenset(allowed),
    )


async def get_principal(claims: dict = Depends(current_claims)) -> Principal:
    return await load_principal(claims)


def require_permission(permission: str):
    async def dependency(principal: Principal = Depends(get_principal)) -> Principal:
        if not principal.can(permission):
            raise HTTPException(
                status_code=403,
                detail=f"Missing permission {permission}",
            )
        return principal

    return dependency


def require_scope(scope_type: str, scope_id: str, principal: Principal) -> None:
    """Rule 3: a scoped role only acts inside its scope."""
    if scope_type == "global":
        return
    if scope_type == "clan" and scope_id in principal.clans:
        return
    if scope_type == "city" and scope_id in principal.cities:
        return
    raise HTTPException(status_code=403, detail="Out of scope")
app/security/rate_limit.py
import time
import uuid

from fastapi import Depends, HTTPException

from app.db import redis
from app.security.permissions import Principal, get_principal

WINDOW_KEY = "rl:{action}:{subject}"


async def rate_limit(action_key: str, limit: int, period_seconds: int):
    """Sliding window: one sorted set of request timestamps per subject."""

    async def dependency(principal: Principal = Depends(get_principal)) -> None:
        if "administrator" in principal.roles:
            return  # Administrators are unbounded, but still fully audited.

        key = WINDOW_KEY.format(action=action_key, subject=principal.user_id)
        now = time.time()
        cutoff = now - period_seconds

        pipe = redis.pipeline()
        pipe.zremrangebyscore(key, 0, cutoff)
        pipe.zadd(key, {str(uuid.uuid4()): now})
        pipe.zcard(key)
        pipe.expire(key, period_seconds)
        _, _, count, _ = await pipe.execute()

        if count > limit:
            await redis.zremrangebyscore(key, now, now)
            raise HTTPException(
                status_code=429,
                detail={
                    "error": "rate_limited",
                    "message": f"{action_key} allows {limit} per {period_seconds}s",
                    "retry_after_seconds": period_seconds,
                },
            )

    return dependency
app/security/audit.py
from datetime import datetime, timezone

from sqlalchemy import text

from app.security.permissions import Principal


async def write_audit(
    conn,
    principal: Principal,
    *,
    action_type: str,
    entity_type: str,
    entity_id,
    old_data,
    new_data,
    reason,
    ip_hash: str,
) -> None:
    """Called inside the same transaction as the change it records."""
    await conn.execute(
        text("""
            INSERT INTO audit_logs (
                actor_user_id, action_type, entity_type, entity_id,
                old_data, new_data, reason, created_at, ip_hash
            ) VALUES (
                :actor_user_id, :action_type, :entity_type, :entity_id,
                :old_data, :new_data, :reason, :created_at, :ip_hash
            )
        """),
        {
            "actor_user_id": principal.user_id,
            "action_type": action_type,
            "entity_type": entity_type,
            "entity_id": entity_id,
            "old_data": old_data,
            "new_data": new_data,
            "reason": reason,
            "created_at": datetime.now(timezone.utc),
            "ip_hash": ip_hash,
        },
    )
Usage on a protected route
from fastapi import APIRouter, Depends, HTTPException, Request

from app.security.audit import write_audit
from app.security.ip import hash_ip
from app.security.permissions import Principal, require_permission
from app.security.rate_limit import rate_limit

router = APIRouter()


@router.post("/api/moderation/retcons/{retcon_id}/approve")
async def approve_retcon(
    retcon_id: str,
    body: RetconDecision,
    request: Request,
    principal: Principal = Depends(require_permission("approve_retcon")),
    _: None = Depends(rate_limit("moderation_action", 300, 3600)),
):
    async with engine.begin() as conn:
        retcon = await conn.fetchrow(
            "SELECT * FROM retcon_requests WHERE retcon_id = $1 FOR UPDATE",
            retcon_id,
        )
        if retcon is None:
            raise HTTPException(status_code=404, detail="Retcon not found")
        if retcon["status"] not in ("pending", "in_review"):
            raise HTTPException(status_code=409, detail="Already decided")

        if retcon["risk"] in ("severe", "existential") and not body.two_person_token:
            raise HTTPException(status_code=409, detail="Second approver required")

        await conn.execute(
            """
            UPDATE retcon_requests
               SET status = 'approved',
                   reviewed_by = $2,
                   reviewed_at = now(),
                   decision_note = $3
             WHERE retcon_id = $1
            """,
            retcon_id,
            principal.user_id,
            body.reason,
        )

        await write_audit(
            conn,
            principal,
            action_type="approve_retcon",
            entity_type="retcon_request",
            entity_id=retcon_id,
            old_data={"status": retcon["status"]},
            new_data={"status": "approved", "reason": body.reason},
            reason=body.reason,
            ip_hash=hash_ip(request),
        )

    return {"retcon_id": retcon_id, "status": "approved"}

25. Foundational architecture: six layers

Six layers were identified as upgrades that strengthen the existing simulation without rewriting it. Each layer feeds the next, and each one reads what the game already produces rather than replacing it.

  • Event Layer — every meaningful thing that happens is emitted as an event: a birth, a duel, a treaty, a harvest failure, a spirit sighting.
  • Memory Layer — events become memories that characters and NPCs can recall, with importance and decay.
  • Knowledge Layer — memories become knowledge: what a person, school, city or era actually knows, and what it believes wrongly.
  • Reputation Layer — knowledge of a figure's deeds becomes standing, fame and infamy, per faction and per region.
  • Consequence Layer — events and reputations resolve into delayed effects on families, cities and nations.
  • Chronicle Layer — the written record, drawing scenes from all of the above and binding them into chapters, volumes and books.
LayerStoresFeeds
EventImmutable event rows with kind, scope, actor and payloadMemory, Chronicle
MemoryRecollections with importance, participants and yearKnowledge, Narrative
KnowledgeWhat each holder knows or believesReputation, Dialogue
ReputationStanding per figure, faction and regionConsequence, Politics
ConsequenceDelayed effects with a due yearWorld simulation
ChronicleScenes, chapters, volumes, booksReader, Hall of Legends

26. Compatibility and integration plan

Build compatibility layers first. Existing systems emit events. Events create memories. Memories feed chronicles, reputation, families, companions, cities and world history.

Nothing is rewritten wholesale: each layer reads what the game already produces and adds one new capability on top. If a layer is removed, the game still runs exactly as it does today.

  • Step 1 — Emit events from existing actions without changing their behaviour.
  • Step 2 — Write memories from events, reusing the existing memory model.
  • Step 3 — Derive knowledge and reputation from memories.
  • Step 4 — Queue delayed consequences with a due year.
  • Step 5 — Assemble chronicle scenes from memories and bind them into chapters.

27. Priority roadmap

The agreed build order, with current status.

#LayerStatus
1Event LayerDesigned — next to build
2Memory LayerDesigned
3Knowledge LayerDesigned
4Reputation LayerDesigned
5Consequence LayerDesigned
6Chronicle UpgradeBuilt this session — volumes, canon status, years, collapsible reading
7Season and episode structureDesigned
8Permission inheritance and moderation dashboardDesigned — schema and middleware specified
9OpenAPI service and audit ledgerDesigned — specification complete

28. Built versus designed

A plain statement of what exists in the game today against what remains a design.

SystemState
Chronicle tab in Avatar CommunionBuilt
Chapter editor with formatting toolsBuilt
Chapter and full-chronicle text exportBuilt
Collapsible chaptersBuilt
Volumes, world years, canon statusBuilt
Season and episode structureDesigned
Family, clan, city, nation, animal and Avatar chroniclesDesigned
World Library and Hall of LegendsDesigned
Version comparison, rollback, review statesDesigned
Permission inheritance and scoped rolesDesigned — schema and seed complete
Moderation dashboardDesigned
Audit logs and canon ledgerDesigned — schema complete
OpenAPI, migrations, token rotation, rate limitingDesigned — specification complete
Event, Memory, Knowledge, Reputation, Consequence layersDesigned

29. Next steps

The Chronicle upgrade is complete and live. Everything in sections 8 through 24 is specified but not yet implemented: the governance tables, the permission middleware, the moderation dashboard and the audit ledger.

The build order is: Event Layer first, because every other layer reads from it; then the season and episode structure over the existing chapters; then the separate chronicle shelves; then governance, beginning with the tables and seed, since the dashboard and the API both depend on them.

Reconstruction of this session, not a verbatim transcript.