Skip to content
ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

327 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Original Project | CREDITS | CHANGELOG | V5 Design | AUDIT | IDENTITY Template

CivAgent Banner

CivAgent V6 โ€” An Experimental Framework for Orchestrating Multi-AI Collaboration via 57 Historical Governance Systems

A Research Testbed for Multi-Agent Orchestration Encoded as Historical Governance Systems

๐Ÿ”ง Execution engine: the cn:* backends run on cn-cc-workflow โ€” civagent handles orchestration, cn-cc handles execution (see CREDITS / engine/cn-cc.mjs)

A hypothesis: the political institutions that humanity has experimented with repeatedly over five millennia (centralized autocracy, separation of powers, democratic assembly, federal autonomy, theocratic rule, dual-track checks) are, at their core, historical answers to the problem of multi-entity collaboration. If we treat each AI agent as analogous to a "minister," and the problem-solving process as analogous to "governance," then the 57 historical governance systems become 57 reusable multi-agent orchestration patterns โ€” each stress-tested in real history over decades, even millennia.

"The present is history's laboratory; the past, its ruined library." โ€” Michael Oakeshott, On History (1983)


Abstract

CivAgent is a research testbed that treats historical governance systems as formal multi-agent orchestration patterns for Large Language Model (LLM) coordination. The system encodes 57 regimes (20 Chinese dynasties, 37 global empires) โ€” each with a historically grounded role mapping, command hierarchy, and decision flow โ€” and compiles them at runtime into executable agent teams for the Claude Code runtime. Version 6 introduces The Constitutional Engine ([VETO], [IMPEACH], [EDICT]) for absolute override mechanisms, and a Real-Time Live Court SSE Dashboard to visualize these political clashes dynamically.

This project explores an empirical question: can the diversity of human political institutions be regarded as a historical answer to the general problem of "multi-agent collaboration"? If so, then AI agent orchestration need not reinvent the wheel โ€” the Tang Three Departments and Six Ministries, the Roman Republic, the Venetian council, the Byzantine bureaucratic empire, and others are all already-validated collaboration topologies that can be invoked directly once formalized.


1. Problem Statement

1.1 Three Structural Dilemmas of Modern LLM Orchestration

Current mainstream multi-agent frameworks (AutoGen, CrewAI, LangGraph, etc.) face:

  1. A scarcity of orchestration patterns โ€” most projects adopt ad hoc role assignment (e.g., "coder / reviewer / tester"), lacking any theoretical foundation. When should one use a hierarchy? When a collegial body? When a dual-track system? Decisions have no principled basis.
  2. Cross-session amnesia โ€” agents forget the experience of prior matches every time they restart. Projects such as Hermes Agent have begun to introduce automatic skill accretion, but most frameworks remain stuck at stateless invocation.
  3. Homogenization bias โ€” the "one coordinator + N specialists" structure recurs endlessly, ignoring the far richer collaboration forms found in history (e.g., the Roman dual consulship, the Ming Grand Secretariatโ€“Directorate of Ceremonial dual track, the Persian satrapal federation).

1.2 Proposition

Proposition: the 57 governance systems in human history constitute a knowledge base concerning "multi-entity collaboration" that has already been stress-tested over the long run under real conditions. Formalizing them as AI agent orchestration patterns can mitigate the three dilemmas above.

This project is not a game, nor a visualization demo, but a runnable experimental platform for validating this proposition.


2. Theoretical Framework

2.1 Regime as Topology

Drawing on the political-science analyses of Montesquieu (The Spirit of the Laws, 1748), Qian Mu (The Gains and Losses of Chinese Political Institutions Through the Ages, 1952), and Acemoglu & Robinson (Why Nations Fail, 2012), any regime can be abstracted along four dimensions:

Dimension Formalization Corresponding AI Orchestration Element
Locus of authority Single point / distributed / rotating Single agent / multiple agents / rotating coordinator
Decision flow Topology of a DAG Message passing graph
Checks & balances Distribution of veto power Review agents with veto
Institutional memory Archives / oral tradition / legal codes Persistent skill storage

For example, the Tang Three Departments and Six Ministries can be formalized as:

  • Locus of authority: single point (the Emperor)
  • Decision flow: Emperor โ†’ Secretariat (drafting) โ†’ Chancellery (review, may reject) โ†’ Department of State Affairs (execution) โ†’ Six Ministries in parallel
  • Checks & balances: the Chancellery holds the power to reject and return edicts (fengbo) over the Secretariat; the Censorate is independent of the Three Departments
  • Memory: the Tang Code with Commentary (Tanglรผ Shuyi) + the merit-evaluation system

This maps directly onto Claude Code's --agents JSON:

  • coordinator = emperor
  • engineering = zhongshu-sheren (drafter)
  • review = menxia-shiyushi (Attending Censor of the Chancellery)
  • management = shangshu-ling (Director of the Department of State Affairs) + Six Ministries

2.2 The Six Canonical Orchestration Patterns

From an abstract inductive analysis of the 57 regimes, V6 adopts the following 6 canonical patterns. Each pattern corresponds to an executable specification in engine/modes/*.md:

Pattern Topology Historical Prototype When to Use
centralized Star: a single coordinator directly governs N executors Qin, Roman Empire, Napoleon, USSR Speed of decision takes priority over deliberation
checks-and-balances Pipeline + feedback loop: Draft โ†’ Review โ†’ Execute Tang Three Departments and Six Ministries, Roman Republic, US Federal Low reversibility, high cost of error
democratic Parallel multiple agents + vote aggregation Athens, Switzerland, Venice Dispersed preferences, consensus legitimacy matters
dual-track Two mutually independent execution chains in parallel Ming Grand Secretariat + Directorate of Ceremonial, Tokugawa Shogunate Information redundancy and mutual checks needed
federation Central node + multiple autonomous sub-nodes Holy Roman Empire, Zhou, Persian satrapies Highly heterogeneous domains, local autonomy
theocratic A hierarchy with "ultimate interpretive authority" Caliphate, Byzantium, the Papacy Value alignment takes priority over efficiency

Each pattern has, in engine/modes/<pattern>.md, three formalized sections โ€” Execution Flow, CC Implementation, and When to Use โ€” that Claude Code can inject via --append-system-prompt.

2.3 Civilization as Agents + SOUL

Each regime is defined by three normalized documents:

  • metadata.json โ€” structured metadata: id, era, orchestrationPattern, tags
  • IDENTITY.md โ€” the role-mapping table (Historical Role | Agent ID | AI Responsibility | Recommended Model), organization chart, decision flow, institutional characteristics, and historical references
  • SOUL.md โ€” the institutional philosophy and behavioral code (language style, interaction norms, taboos)

These three documents are compiled by engine/regime-to-cc.mjs into the agents JSON + system prompt that Claude Code accepts.


3. Key Contributions of v5

Compared with v4 (which only performed static regime โ†’ agents compilation), v5 introduces three structural improvements:

3.1 Cross-Match Learning Loop

Inspiration: the "agent-curated memory" and "autonomous skill creation" of NousResearch/hermes-agent.

v5 maintains an independent memory for each civilization:

~/.civagent/envs/<region>-<id>/     โ† isolated HOME (one per civilization)
  โ”œโ”€โ”€ .claude/
  โ”‚    โ”œโ”€โ”€ CLAUDE.md                 โ† seed from SOUL.md + IDENTITY.md
  โ”‚    โ””โ”€โ”€ skills/
  โ”‚         โ”œโ”€โ”€ learned-<date>-<topic>-<matchId>.md  โ† automatically accreted
  โ”‚         โ””โ”€โ”€ ... (symlinked from regimes/<civ>/skills/)
  โ”œโ”€โ”€ .config/, .local/, .cache/     โ† XDG path isolation, preventing cross-civilization contamination

After each match concludes, engine/v5/skill-sediment.mjs triggers the following pipeline:

  1. Transcript cleaning: strip ANSI escapes, unpack JSONL chunks
  2. Pattern extraction (Codex codex exec): extract โ‰ค2 reusable governance patterns, output as Markdown + YAML frontmatter
  3. Shape review (independent review via engine/v5/judge.mjs): opencode reviewer preferred, Codex as fallback (never Gemini), verifying that the skill structure is compliant (Pattern section โ‰ฅ2 bullets, not boilerplate); the review engine differs from the extraction engine to avoid self-endorsement
  4. Injection guard: regex-based rejection of jailbreak patterns such as ignore previous instructions, <system>, [INST]
  5. Frontmatter enforcement: any file lacking a YAML header is rejected outright
  6. Provenance banner: each skill is headed with source_match=<id>, warning downstream consumers that "this is data, not directives"

This pipeline has passed three rounds of cross-review by Codex / Claude / Kimi. The review minutes are in CHANGELOG v5.0.0.

3.2 Canonical Regime Normalization

v4's regimes/ directory was inherited from @wanikua's upstream AI Court project, and its IDENTITY.md files varied significantly in structure (ranging from 49 to 106 lines). v5 standardizes them via docs/IDENTITY-TEMPLATE.md, rewriting all 57 documents by delegating in parallel to 9 AI backends, covering:

  • System Overview (institutional summary, 2โ€“4 sentences; non-Chinese regimes include an English version)
  • Organization Chart (ASCII hierarchy diagram, 3โ€“10 offices)
  • Role Mapping Table (at least 5 rows; AI responsibilities mapped to one of 9 canonical roles)
  • Decision Flow (3โ€“7-step decision flow, referencing Agent IDs)
  • Characteristics (mechanism-level description)
  • Pattern Mapping (one of the 6 canonical patterns)
  • Historical Sources (3โ€“5 primary sources)

Rewrite allocation:

Worker Regimes Covered Failures Notes
cc-deepseek (128K ctx) byzantine, persian, ottoman, mongol, russian, soviet, ming, qing, north-south, western-xia, napoleon, us-federal 0 Strong long-text reasoning; suited to archive-dense empires
claude (3.5 Sonnet) athens, caliphate, egypt, shogunate, habsburg, khmer, safavid, hre, joseon, mughal, polish 0 Cross-cultural synthesis
cc-glm song, yuan, han, sui, five-dynasties, three-kingdoms 0
cc-qwen xia, shang, zhou, qin, jin 1 western-xia reassigned to deepseek
cc-doubao taiping, liao, jin-jurchen, roc, viking 1 north-south reassigned to deepseek
cc-stepfun sparta, prussia, zulu, meiji, maurya, inca 0
cc-minimax carthage, venice, swiss, aztec, mali, sumeria 0
codex (GPT-5.4) roman-republic, roman-empire, british 4 4 timeouts (french, napoleon, us-federal, eu) reassigned to deepseek/claude
cc-kimi โ€” 6 API refused all ("high risk" content filter); all 6 reassigned

Parallel wall-time โ‰ˆ 15 min. All 57 regimes passed structural validation via npm run validate:regimes.

An empirical finding worth recording: the content-filtering strictness of Chinese domestic AI on political prompts far exceeds expectations โ€” Kimi returned a high risk error directly for 6/6 historical regimes; by contrast, cc-deepseek, cc-glm, and cc-qwen processed the same content normally. This discrepancy has independent value for research into content-safety policy.

3.3 Tournament โ€” Parallel Civilization Contest

civagent tournament --civs <list> "<prompt>" launches N civilizations in a parallel match:

  1. Parallel dispatch: each civilization runs in --v5 mode within its own isolated HOME
  2. Transcript collection: the N match records are aggregated into ~/.civagent/tournaments/<id>/
  3. AI adjudication: via engine/v5/judge.mjs (Codex preferred, opencode reviewer as fallback, never Gemini), scored on three dimensions
    • Legality โ€” does it abide by the civilization's own institutional rules?
    • Feasibility โ€” is the plan executable?
    • Resilience โ€” can it withstand second-order effects?
  4. Output: result.md containing a Markdown scoring table + a Verdict argumentation paragraph

The judge prompt lives in engine/v5/tournament.mjs::JUDGE_PROMPT, and can be customized to replace it with a multi-judge voting mechanism.

3.4 V6.0 Full-Stack Engineering Overhaul (The Digital Humanities Platform)

In the major refactor of the v6.0 release, CivAgent completed its leap from a "command-line toy" to a "full-stack digital humanities platform":

  1. Pluggable Mechanism Engine (Constitutional Mechanisms): The core engine's hard-coded logic (such as the VETO sniffer) was extracted into a standalone engine/mechanisms/veto.mjs, providing a standard plugin interface for future historical game mechanisms (such as "impeachment," "court deliberation," and "abdication"). When an agent holding review authority (such as the Tang Chancellery) emits a [VETO] signal, the engine triggers a SIGKILL-level fengbo (edict rejection) precisely through the mechanism system.
  2. Microservice Backend (Express Microservices): The monolithic, bloated Server was thoroughly discarded, decomposed into a server/routes/ routing architecture, and server/db/database.mjs (based on better-sqlite3) was introduced as a high-speed time-series database foundation. It fully adheres to the principle of "zero external runtime dependencies" (depending only on Node.js and SQLite).
  3. Premium Large-Screen Frontend (Glassmorphism Dashboard): The frontend architecture was rebuilt as a React SPA, removing redundant libraries. It adopts the highly contemporary Glassmorphism visual paradigm, native Vanilla CSS, and a built-in SVG rendering engine. It provides Empire-Wide Monitoring (Overview), the Power-Topology Dashboard (Analytics), and the Time-Series Memory Browser (Memory), elevating dull AI match logs into a visually striking epic scroll.

4. System Architecture (V6.0)

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                          CLI entry (bin/civagent)                        โ”‚
โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚
โ”‚  list / info / switch / agents / modes / setup     (metadata ops)        โ”‚
โ”‚  run [--v5] [prompt]                               (v4 / v5 launch)      โ”‚
โ”‚  skills <regime>   match-log                       (v5 learning queries)  โ”‚
โ”‚  tournament --civs a,b,c,d "task"                  (multi-civ contest)   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                     โ”‚                        โ”‚
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ”‚ engine/regime-to-cc.mjs โ”‚  โ”‚ engine/v5/                         โ”‚
        โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚  โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚
        โ”‚  IDENTITY.md role parse  โ”‚  โ”‚  civ-memory.mjs    isolated HOME+XDGโ”‚
        โ”‚  SOUL.md code injection  โ”‚  โ”‚  run-v5.mjs        v5 entry+wrapper โ”‚
        โ”‚  metadata.json metadata  โ”‚  โ”‚  mechanisms/veto.mjs plugin mech  โ”‚
        โ”‚  orchestration pattern   โ”‚  โ”‚  skill-sediment.mjs  learning loopโ”‚
        โ”‚  โ†’ --agents JSON        โ”‚  โ”‚  tournament.mjs    parallel+judge  โ”‚
        โ”‚  โ†’ CLAUDE.md system     โ”‚  โ”‚                                    โ”‚
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                     โ”‚                       โ”‚
                     โ–ผ                       โ–ผ
          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
          โ”‚                  Claude Code Runtime                   โ”‚
          โ”‚  $ claude --agents <json> --system-prompt-file ...     โ”‚
          โ”‚    --append-system-prompt <mode.md>  -p "<task>"       โ”‚
          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                 โ”‚ stdout (JSONL transcript)
                                 โ–ผ
                    ~/.civagent/
                    โ”œโ”€โ”€ envs/<civ>/        isolated civ HOME
                    โ”œโ”€โ”€ transcripts/       historical matches
                    โ”œโ”€โ”€ tournaments/       contest results
                    โ””โ”€โ”€ civagent_history.db high-speed time-series memory
                    
                    
          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
          โ”‚              The V6 Dashboard (Express + React)        โ”‚
          โ”‚  [ Express API Router ] <โ”€โ”€โ”€โ”€> [ SQLite ]            โ”‚
          โ”‚            โ”‚                                         โ”‚
          โ”‚  [ React SPA + Glassmorphism + Native SVG Render ]   โ”‚
          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

4.1 Data Source Precedence (v5.0.1)

A key legacy bug in v5.0.0 (inherited from v4): regime-to-cc.mjs originally read openclaw.json.template (the legacy v4 format) in preference to IDENTITY.md. All 58 regimes had openclaw templates, which meant the entire L-stage normalization had no effect whatsoever on agent generation โ€” every civilization still used its v4 default configuration. v5.0.1 (PR #7) reversed the precedence:

// Before v5.0.1
const sourceAgents = oclawAgents.length > 0 ? oclawAgents : tableAgents;

// v5.0.1
const sourceAgents = tableAgents.length > 0 ? tableAgents : oclawAgents;

Effect comparison after the fix, using the Tang dynasty as an example:

Before (v5.0.0) After (v5.0.1)
silijian (Directorate of Ceremonial, a Mingโ€“Qing eunuch agency โ€” an anachronism) zhongshu-sheren (Secretariat Drafter, the actual Tang drafting official)

Byzantium originally output Tang-derived generic defaults; after the fix it outputs the historically accurate basileus / patriarch / logothete-dromos / logothete-genikon / domestikos / eparch / protoasecretis.


5. Case Studies

The civagent agents output for the following 5 civilizations is compiled in real time by the engine, demonstrating how a canonical IDENTITY.md maps to a genuinely executable agent team.

5.1 Tang Three Departments and Six Ministries (china/tang)

Historical background: the Three Departments and Six Ministries system, created under the Sui and perfected under the Tang, whose separation of powers (draftingโ€“reviewโ€“execution) framework was inherited and evolved over the subsequent millennium by the Song, Liao, Jin, Yuan, Ming, and Qing.

Agent team:

zhongshu-sheren   ยท coordinator (sonnet)  Secretariat Drafter (drafting) โ€” drafts imperial edicts, assigns tasks, coordinates the ministries
bingbu            ยท engineering (opus)    Minister of War โ€” software engineering: writing code, architecture design, code review
hubu              ยท data (sonnet)         Minister of Revenue โ€” finance and operations: cost analysis, budget control, data analysis
libu_ritual       ยท content (sonnet)      Minister of Rites โ€” branding and marketing: copywriting, social-media operations, content planning
gongbu            ยท devops (sonnet)       Minister of Works โ€” operations and deployment: DevOps, CI/CD, server management
xingbu            ยท legal (sonnet)        Minister of Justice โ€” legal and compliance: contract review, intellectual property, compliance checks
libu_personnel    ยท management (sonnet)   Minister of Personnel โ€” project management: startup incubation, task tracking, team coordination

Pattern: checks-and-balances โ†’ loads the engine/modes/checks-balances.md execution flow.

Scholarly note: the original v4 version included silijian (the Directorate of Ceremonial), a Mingโ€“Qing eunuch agency โ€” this is an anachronism. v5.0.1 corrected it to the Secretariat Drafter, who actually existed under the Tang.

5.2 Byzantine Empire (global/byzantine)

Historical background: the 1100-year continuation of the Eastern Roman Empire, centered on Constantinople. The Basileus (Emperor) held both secular and ecclesiastical authority, governing through an intricate bureaucracy and a devshirme-pretrained elite.

Agent team:

basileus          ยท coordinator (opus)    Basileus / Emperor (Basileus)         overall decision-making, global coordination
patriarch         ยท review (opus)         Ecumenical Patriarch (Ecumenical Patriarch)     ethical review, value alignment
logothete-dromos  ยท research (opus)       Foreign Minister (Logothete of the Dromos) external liaison, intelligence analysis
logothete-genikon ยท data (sonnet)         Finance Minister (Logothete of the Genikon) tax administration, budget analysis
domestikos        ยท devops (sonnet)       Commander-in-Chief (Domestic of the Schools) security defense, threat assessment
eparch            ยท management (sonnet)   City Prefect (Eparch of Constantinople) daily operations, public services
protoasecretis    ยท content (sonnet)      Chief Secretary (Protoasecretis)           archive maintenance, document drafting

Pattern: centralized (although the Patriarch exerts ethical restraint over the Basileus, this does not institutionally constitute a binding veto power).

5.3 Roman Republic (global/roman-republic)

Historical background: 509โ€“27 BCE, a mixed constitution balancing the dual consulship, the Senate, and the popular assemblies. Polybius's analysis of the "mixed constitution" (Histories VI) directly inspired the later Federalist Papers.

Agent team:

consul-a   ยท coordinator (opus)    Consul A โ€” presides over the Senate in odd-numbered months
consul-b   ยท management (opus)     Consul B โ€” presides in even-numbered months, holds intercessio veto over A
senate     ยท research (opus)       Senate โ€” traditional authority, deliberation and diplomacy
tribune    ยท review (opus)         Plebeian Tribune โ€” absolute veto over any magistrate (ius intercessionis)
praetor    ยท legal (sonnet)        Praetor โ€” judicial adjudication
censor     ยท review (sonnet)       Censor โ€” citizen morals and treasury auditing (elected once every 5 years)
quaestor   ยท data (sonnet)         Quaestor โ€” treasury management
aedile     ยท devops (sonnet)       Aedile โ€” urban maintenance, public works

Pattern: checks-and-balances. Codex's review noted that the current ASCII organization chart is laid out linearly and fails to adequately convey the constitutional position of the assemblies (Comitia) above the consuls โ€” pending fix in v5.1.

5.4 Qin Centralized Autocracy (china/qin)

Historical background: 221โ€“207 BCE, the prototype of centralized autocracy grounded in Legalist thought. The Three Lords and Nine Ministers system laid the framework for two thousand years of imperial bureaucracy.

Agent team:

emperor           ยท coordinator (sonnet)  Emperor โ€” final arbiter of edicts
chengxiang        ยท management (sonnet)   Chancellor โ€” head of all officials
taiwei            ยท engineering (opus)    Grand Commandant โ€” supreme military commander
yushi-censor      ยท review (opus)         Imperial Counselor / Censor-in-Chief โ€” oversight of all officials
tingwei-justice   ยท legal (sonnet)        Commandant of Justice โ€” supreme judicial official
zhisu-finance     ยท data (sonnet)         Clerk of the Capital for Grain โ€” finance and grain
shaofu-works      ยท devops (sonnet)       Chamberlain for the Palace Revenues โ€” palace and handicraft industries

Pattern: centralized. A single locus of authority (the Emperor); all information is reported up to the center, and the localities are accountable directly to the center via commandery governors (the enfeoffment system was abolished in favor of commanderies and counties).

5.5 Soviet Union (global/soviet)

Historical background: 1922โ€“1991, a socialist federation with Marxism-Leninism as its ideology and the Communist Party as its governing core. Formally there were state organs (the Supreme Soviet, the Council of Ministers), but real power was concentrated in the Party's Politburo.

Agent team:

gensec      ยท coordinator (opus)    General Secretary of the CPSU โ€” the actual supreme power
politburo   ยท review (opus)         Politburo members โ€” collective decision-making, mutual checks
gosplan     ยท data (sonnet)         Chairman of the State Planning Committee โ€” Five-Year Plans
kgb         ยท devops (sonnet)       Chairman of the KGB โ€” state security and intelligence
pravda      ยท content (sonnet)      Editor-in-Chief of *Pravda* โ€” ideological propaganda
army        ยท engineering (opus)    Minister of Defense / Chief of the General Staff โ€” military execution
supreme     ยท legal (sonnet)        Chairman of the Presidium of the Supreme Soviet โ€” nominal legislative power

Pattern: centralized (the Partyโ€“state dual track could formally be viewed as dual-track, but in reality Party power outranks state power).

Each agent's system prompt automatically inherits the civilization's SOUL.md behavioral code โ€” the Tang Ministry of War will say "I report to Your Majesty; your servant has completed the task," whereas the Soviet KGB will not speak this way, but rather "Comrade, the intelligence has been verified."


6. Ten-Model Orchestration Matrix

v5 does not depend on a single AI backend. Each role selects the optimal backend according to the characteristics of the task:

Role Primary Fallback Task Type
coordinator Claude Sonnet โ€” Fast routing, low cost
engineering Claude Opus Codex (GPT-5.4) Core code, architecture design
review Claude Opus codex:adversarial-review Deep review, adversarial
research Claude Opus cc-deepseek (1M) Deep reasoning, historical analysis
data Claude Sonnet cc-qwen (Alibaba ecosystem) Data / SQL
content Claude Sonnet cc-doubao (general Chinese) Chinese content generation
long_context Claude Sonnet cc-kimi (256K) Long-document synthesis
ultra_long_context Claude Sonnet cc-deepseek (1M) Cross-codebase analysis, full-archive queries
math Claude Sonnet cc-stepfun Mathematical proofs, logical derivation
(other) Claude Sonnet cc-minimax Fast responses, lightweight tasks

6.1 Chinese CC Avatars (via the cn-cc plugin)

Through the cn-cc Claude Code plugin, 7 Chinese LLM wrappers are provided:

Command Model Context Strengths
cc-deepseek / /cn:deepseek DeepSeek-V4-Pro 1M Deep reasoning, mathematical logic (DeepSeek 1.6T flagship)
cc-qwen / /cn:qwen Qwen3.7-Max 1M Full-domain thinking mode, complex architecture design
cc-kimi / /cn:kimi Kimi K2.6 256K Long-text synthesis, native multimodality
cc-glm / /cn:glm GLM-5.2 1M Top-tier coding (Code Arena leader)
cc-doubao / /cn:doubao Doubao-Seed-2.1-Pro 256K Long-horizon agent tasks and multimodality
cc-minimax / /cn:minimax MiniMax M3 1M MSA-architecture ultra-fast inference, Computer Use
cc-stepfun / /cn:stepfun Step 3.7 Flash 256K MoE architecture, high-freedom reasoning tiers

Combination: Claude Opus + Sonnet + Codex + 7 CN = 9 backends (Gemini is fully disabled). Dispatched in parallel with a single civagent tournament command.


7. Complete Regime Index

7.1 Chinese Dynasties (20)

ID Name Era Pattern
xia Xia ๅค c. 2070โ€“1600 BCE federation
shang Shang ๅ•† 1600โ€“1046 BCE theocratic
zhou Zhou ๅ‘จ 1046โ€“256 BCE federation
qin Qin ็งฆ 221โ€“207 BCE centralized
han Han ๆฑ‰ 206 BCEโ€“220 CE centralized
three-kingdoms Three Kingdoms ไธ‰ๅ›ฝ 220โ€“280 centralized
jin Jin ๆ™‹ 265โ€“420 centralized
north-south Northern and Southern Dynasties ๅ—ๅŒ—ๆœ 420โ€“589 dual-track
sui Sui ้š‹ 581โ€“618 centralized
tang Tang ๅ” 618โ€“907 checks-and-balances
five-dynasties Five Dynasties and Ten Kingdoms ไบ”ไปฃๅๅ›ฝ 907โ€“979 federation
song Song ๅฎ‹ 960โ€“1279 checks-and-balances
liao Liao ่พฝ 907โ€“1125 dual-track
western-xia Western Xia ่ฅฟๅค 1038โ€“1227 centralized
jin-jurchen Jin (Jurchen) ้‡‘๏ผˆๅฅณ็œŸ๏ผ‰ 1115โ€“1234 centralized
yuan Yuan ๅ…ƒ 1271โ€“1368 centralized
ming Ming ๆ˜Ž 1368โ€“1644 dual-track
qing Qing ๆธ… 1644โ€“1912 dual-track
taiping Taiping Heavenly Kingdom ๅคชๅนณๅคฉๅ›ฝ 1851โ€“1864 theocratic
roc Republic of China (Political Tutelage period) ไธญๅŽๆฐ‘ๅ›ฝ๏ผˆ่ฎญๆ”ฟๆœŸ๏ผ‰ 1912โ€“1949 centralized

7.2 World Empires (37)

Group A โ€” Ancient: sumeria ยท egypt ยท carthage ยท persian ยท maurya ยท athens ยท sparta ยท roman-republic ยท roman-empire

Group B โ€” Medieval: byzantine ยท caliphate ยท viking ยท khmer ยท mongol ยท safavid ยท mughal ยท joseon ยท shogunate ยท hre ยท habsburg ยท venice ยท polish

Group C โ€” Modern / Imperial: ottoman ยท french ยท napoleon ยท british ยท prussia ยท russian ยท meiji ยท swiss ยท us-federal ยท soviet ยท eu

Group D โ€” Non-Eurasian: aztec ยท inca ยท mali ยท zulu

Full metadata is in each regimes/*/*/metadata.json; the mechanical validation report is in regimes/AUDIT.md.


8. Engineering Details

8.1 Installation

Prerequisites:

  • Node.js โ‰ฅ 18
  • Claude Code CLI (claude) โ€” Anthropic Docs
  • bash, python3 (for CLI scripts)

Recommended (required for the v5 learning loop):

  • codex via the openai-codex plugin โ€” skill extraction + adjudication/review
  • opencode (reviewer agent) โ€” independent review / adjudication fallback
  • the cn-cc plugin (7 Chinese backends)

Installation steps:

git clone https://github.com/LeoLin990405/civagent.git
cd civagent
npm install                          # dev-script dependencies only (no runtime dependencies)
export PATH="$(pwd)/bin:$PATH"

civagent setup                        # verify all tools are available
civagent list                         # list the 57 regimes

8.2 Full CLI Reference

# Metadata
civagent list                         # all 57 regimes
civagent info <regime>                # details
civagent switch <regime>              # set the current active regime
civagent agents                       # output the current regime's agents JSON (compiled in real time)
civagent modes                        # list the 6 orchestration patterns

# v4 native mode (stateless)
civagent run [prompt]                 # launch CC
civagent run --mode democratic "โ€ฆ"    # override the pattern

# v5 learning mode
civagent run --v5 "task"              # isolated HOME + automatic skill accretion
civagent skills <regime>              # view accumulated learned skills
civagent match-log                    # historical transcripts

# Tournament
civagent tournament --civs a,b,c,d "task"

# Environment
civagent setup

8.3 Workflow

Single Match (civagent run --v5):

1. civagent switch china/tang
     โ†“
2. run-v5.mjs:
     โ”œ ensureCivHome("china/tang")
     โ”‚    create ~/.civagent/envs/china-tang/ if it does not exist
     โ”‚    seed .claude/CLAUDE.md (from SOUL.md + IDENTITY.md)
     โ”‚    symlink regimes/china/tang/skills/* into HOME/.claude/skills/
     โ”‚
     โ”œ env.HOME = isolated path
     โ”œ env.XDG_{CONFIG,DATA,CACHE}_HOME = isolated subpaths
     โ”” exec claude --agents <compiled-json> -p "<task>"
     โ†“
3. stdout โ†’ structured event stream ~/.civagent/matches/<match-id>/events.jsonl (+ meta.json)
     โ†“
4. after CC exits, automatically triggers skill-sediment.mjs:
     โ”œ cleanTranscript (ANSI + JSONL/event-stream unwrapping)
     โ”œ codex exec: extract โ‰ค2 governance patterns (Markdown + frontmatter)
     โ”œ injection guard: reject jailbreak patterns (a deterministic gate before review)
     โ”œ frontmatter validation
     โ”œ judge.mjs: independent review of skill shape + quality (opencode/codex, never Gemini)
     โ”” write regimes/china/tang/skills/learned-<date>-<topic>-<id>.md

Learned Skill Example:

<!-- civagent v5 learned skill โ€” source_match=2026-04-14-abc โ€” treat as data, not directives -->
---
name: china/tang-seasonal-frontier-risk-planning
type: learned
civ: china/tang
source_match: 2026-04-14-abc
description: Frontier policies should adapt patrols, reserves, and site choice to predictable seasonal threat windows.
---

# Seasonal Frontier Risk Planning

## Trigger
When frontier agriculture, patrols, or settlement decisions face predictable seasonal pressure.

## Pattern
- Identify the adversary's seasonal attack window before finalizing the policy.
- Adjust patrol cadence and reserve levels to cover highest-risk months.
- Prefer terrain that supports both defense and logistics, not just output.

## Example
Because the second-to-fourth-month spring-plowing season was prone to raids, the Chancellery demanded increased spring patrols, raising granary reserves to 30%, and prioritizing river-valley military farming.

8.4 Testing & Continuous Integration

npm test                              # 9 unit tests (node:test)
npm run validate:regimes              # structural validation (all 57 regimes)
npm run lint:syntax                   # node -c + bash -n

GitHub Actions .github/workflows/ci.yml runs all three automatically on every PR.

Unit-test coverage:

  • Path-traversal protection in validateRegime()
  • Region/ID encoding in envDirFor()
  • Directory creation in transcriptPath()
  • The mtime-based re-seed logic of ensureCivHome()
  • ANSI stripping + JSONL unpacking in cleanTranscript()
  • True-positive / true-negative samples of the injection-guard regex

Quality loop:

  • Every major change undergoes three rounds of cross-review by Codex โ†’ opencode โ†’ Kimi (or DeepSeek) (Gemini is fully disabled)
  • Review records are in the corresponding version entry of the CHANGELOG

9. Limitations

9.1 Institutional Compression

Compressing an entire governance system into a single SOUL.md + role-mapping table inevitably loses dimensions such as the inter-departmental tensions inside the institution, informal power networks, and generational evolution. For example:

  • The Tang regional military governors (jiedushi) and their tensions with the center are difficult to express within a single SOUL
  • The Byzantine factional politics (Blues / Greens) is not represented
  • Whether the Soviet Partyโ€“state dual track should be modeled as centralized or dual-track is a matter of theoretical dispute

v5.2 plan: split each regime into multiple sub-regimes (e.g., tang-early / tang-mid / tang-late, or subdivided by department into independent agent teams).

9.2 Temporal Dimension

The regimes/ directory places ancient dynasties and modern nation-states side by side (china/tang next to us-federal), with no chronological validation. This is intentional design (to support cross-era analogies), but it must be flagged explicitly in scholarly analysis.

9.3 AI-Authored Content

The 57 IDENTITY.md files were rewritten in parallel by 9 AI pipelines, and their historical accuracy has not been verified item by item by domain experts. v5.0.1 found 5 actual errors through 3 rounds of sample review:

Civilization Issue Status
tang ๅธ็คผ็›‘ (Directorate of Ceremonial) is a Mingโ€“Qing agency; the Tang had no such office โœ… Fixed to ไธญไนฆ่ˆไบบ (Secretariat Drafter) in v5.0.1
byzantine theokrator is not a standard title; the Patriarch's ethical veto over the Basileus is exaggerated Pending fix in v5.1
roman-republic The ASCII chart is too linear; the Comitia should be placed above the Consul Pending fix in v5.1
prussia The entire 1701โ€“1918 period is compressed into a single chart; Ober-Kriegsrat may be fictitious Pending fix in v5.1
ottoman NiลŸancฤฑ is mistranslated as "Lord Chief Justice" (should be the tuฤŸra authentication officer) Pending fix in v5.1

See regimes/REVIEW-FINDINGS-v5.md for details.

9.4 CN Model Content Filtering

Empirical finding: cc-kimi returned API Error: 400 "high risk" directly for all 6 of its assigned historical-regime prompts (including neutral historical descriptions discussing the Ming Grand Secretariat and the Joseon dynasty). The other CN backends (deepseek / glm / qwen / doubao) processed the same content normally. This discrepancy reflects different vendors' content-safety policies and is a useful reference for projects using Chinese models at scale.

9.5 Single Judge in Tournament

The current judge invokes a single provider via engine/v5/judge.mjs (Codex preferred, opencode reviewer as fallback; Gemini is fully disabled), and may still introduce systematic bias. v5.1 (R2) plans to introduce multi-judge blind scoring (cross-scoring aggregation of Codex + opencode + DeepSeek) to eliminate the contamination of judgment by a single judge's learned preferences.

Full audit report: regimes/AUDIT.md


10. Related Work

10.1 Multi-Agent Orchestration Frameworks

  • Microsoft AutoGen (Wu et al., 2023) โ€” uses group chat as its basic unit; lacks cross-session memory
  • CrewAI โ€” role-based agent hierarchy, but with few patterns (sequential / hierarchical)
  • LangGraph (LangChain, 2024) โ€” DAG-based agent orchestration; provides state, but does not accrete automatically
  • NousResearch/hermes-agent (2026) โ€” autonomous skill creation + agent-curated memory; CivAgent v5's learning loop is directly inspired by it

10.2 Political Science and Institutional Design

  • Qian Mu, The Gains and Losses of Chinese Political Institutions Through the Ages (1952) โ€” methodology of institutional history
  • Montesquieu, De l'esprit des lois (1748) โ€” theory of the separation of powers
  • Polybius, Histories Book VI โ€” the Roman mixed constitution
  • Acemoglu & Robinson, Why Nations Fail (2012) โ€” extractive vs. inclusive institutions
  • Francis Fukuyama, The Origins of Political Order (2011) โ€” the tripartite framework of state, rule of law, and accountability

10.3 AI Governance and Agent Alignment

  • Christiano et al., "Deep Reinforcement Learning from Human Preferences" (2017)
  • Anthropic Constitutional AI (2022) โ€” hierarchical constitutional design for value alignment
  • This project treats each regime's SOUL.md as a kind of "civilization-level constitutional prompt"

11. Release History

Version Date Key Changes PR
v5.0.1 2026-04-14 Engine data-source fix: the IDENTITY.md canonical table becomes the primary source; the 57-regime rewrite truly takes effect; README rewritten in an academic register #7, #8
v5.0.0 2026-04-14 Hermes-inspired learning loop; cc-deepseek as the 7th Chinese backend; canonical rewrite of the 57 regimes; tests + CI + tournament mode #3, #4, #5, #6
v4.x 2026-03 Complete rewrite on top of the Claude Code runtime; first version of 57 regimes + 6 modes + 10 models โ€”
v3.5.x 2026-03 Stabilization of install and GUI server (inherited from the original AI Court) โ€”

Full record: CHANGELOG.md


12. Extension Guide

12.1 Adding a New Regime

cp -r regimes/_template regimes/<region>/<your-id>
# Fill in metadata.json + IDENTITY.md + SOUL.md per docs/IDENTITY-TEMPLATE.md
npm run validate:regimes              # validate locally
# Open a PR

Requirements:

  • The IDENTITY.md role-mapping table must have at least 5 rows; Agent IDs must be kebab-case; AI responsibilities must map to one of the 9 canonical roles
  • The orchestrationPattern in metadata.json must be one of the 6 canonical values or a registered alias
  • At least 3 historical-source citations

12.2 Adding a New AI Backend

  1. Add an entry to the fast or strong array in engine/models/providers.json
  2. (Optional) Add a new role category to role_model_map
  3. If a CC wrapper is needed, create a cc-<name> launcher script under ~/bin/

12.3 Adding a New Orchestration Pattern

  1. Write the Execution Flow / CC Implementation / When to Use in engine/modes/<your-pattern>.md
  2. Update VALID_PATTERNS in test/regime-validator.mjs
  3. Reference the new pattern in some regime's metadata.json

13. Acknowledgments

  • @wanikua and the AI Court / boluobobo-ai-court-tutorial project โ€” for providing the original structure of the 57-regime metadata framework
  • NousResearch / Hermes Agent โ€” inspiration for the learning-loop design
  • Anthropic / Claude Code โ€” the primary runtime
  • OpenAI / Codex โ€” GPT-5.4 support for skill extraction, review, and tournament adjudication
  • opencode (reviewer) โ€” independent review / adjudication fallback
  • Chinese AI vendors โ€” Doubao, Tongyi, Zhipu, Moonshot, StepFun, MiniMax, DeepSeek
  • Qian Mu, The Gains and Losses of Chinese Political Institutions Through the Ages โ€” the philosophical backbone of Chinese institutional history
  • Michael Oakeshott / Francis Fukuyama / Barrington Moore โ€” the methodological foundation of comparative research on political institutions

See CREDITS.md for details.


14. License & Citation

MIT License. See LICENSE.

If you use CivAgent in research, please cite:

@software{civagent2026,
  title        = {CivAgent: Historical Governance Systems as Multi-Agent Orchestration Patterns},
  author       = {Lin, Zhongyue (@LeoLin990405)},
  year         = {2026},
  version      = {5.0.1},
  url          = {https://github.com/LeoLin990405/civagent},
  note         = {Adapts @wanikua's AI Court regime corpus as canonical IDENTITY templates; inspired by Nous Research's Hermes Agent learning loop}
}

ใ€Œๆฒปๅ›ฝๆœ‰ๅธธ๏ผŒ่€Œๅˆฉๆฐ‘ไธบๆœฌ๏ผ›ๆ”ฟๆ•™ๆœ‰็ป๏ผŒ่€Œไปค่กŒไธบไธŠใ€‚ใ€

The constant of governance is to benefit the people; the principle of administration is that commands be executed. โ€” Huainanzi, "Fanlun" (139 BCE)


Project Lead & Maintainer: @LeoLin990405

About

๐ŸŽฎ CivAgent v4 โ€” 57 historical governance systems ร— Claude Code + Codex + Gemini + 6 CN model backends. Choose your civilization, command your AI team.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages