# Proposal: Aurelian Frontier

Design for the Aurelian Frontier game: a capability-native, persistent-world
RPG set on the imperial frontier of an original late-imperial fantasy setting.
The current shell-spawned `adventure-client` artifact remains the deterministic
proof slice for the capability system; this proposal describes the game it
grows into. Both purposes coexist: the QEMU smoke transcript stays stable, and
the design supports a long-running campaign with authoritative shared world
state, multiplayer parties, durable profiles, and audited public history.


## Current State

The existing artifact proves useful plumbing:

- `capos-shell` launches `adventure-client` as an ordinary child process.
- The shell grants explicit `StdIO`, `Adventure`, and `Chat` endpoint clients.
- `adventure-server` owns per-player room and inventory state keyed by the
  endpoint caller-session scoped reference and epoch; normal shell launch
  syntax omits legacy receiver selectors, and remaining explicit selector
  fixtures are not the adventure player identity model.
- `chat-server` carries room-local events and simple NPC process output.
- Focused `make run-adventure` transcript coverage proves launch, movement,
  item pickup, inventory, chat, and process exit; the resident
  `adventure-scenario-test` process covers complex custody logic through
  direct `Adventure` cap calls.

As a game, the playable surface is still narrow: one mission, one party of
named actors, one tactical encounter. The Aurelian frontier map has replaced
the four-room cellar prototype. The first mission recovers `eagle-standard`
from `signal_tower`, uses Maro route evidence, Livia ward delegation, survivor
evacuation, Iunia witness-certified custody, and gate sealing, and keeps the
read-only site graph, mission text, aliases, objectives, metadata, and proof
path in CUE-authored content with checked-in generated Rust output and
freshness verification. Inventory and status now distinguish physical items,
writs, relic custody, marks, evidence, generated calendar/regional/construction
metadata, and disabled-by-default optional fake-agent NPC budget metadata.
Direct NPC game authority remains future work. Room chat history is service
persistence rather than player-owned adventure state. The agent NPC foundation
is deterministic quota/refusal metadata and pure fake-model logic only; live
LLM calls, hosted-agent services, durable NPC memory, and autonomous NPC actions
are not implemented. Commit `f149119` at `2026-04-29 09:09 UTC` landed the
pure targeted-combat foundation in `adventure-content`: deterministic combat
zones, damage kinds, attack and mob profiles, bounded zone damage, fatigue,
interruption, recognition, and alert propagation. The Aurelian adventure server
now consumes generated mob combat profiles, and the client, scenario proof, and
QEMU smoke exercise explicit target-zone attack, skill, and cast commands.
Durable alert groups, authority-combat verbs, and broad weapon handling remain
open.

Subsequent phases keep the same capability architecture and grow the playable
surface: more missions, more sites, durable profiles, persistent shared world
state, party multiplayer, lawful PvP, an authoritative ledger of public
history, and a richer presentation client. The deterministic transcript stays
the proof gate; the game is what those transcripts increasingly exercise.

## Setting

Working title: **The Ninth Gate of Aurelian**.

The game is set in an original late-imperial fantasy frontier: a Roman-like
empire holds a fortified border against a hostile magical domain beyond a
chain of unstable gates. Its frontier forces are mixed cohorts of shield
soldiers, oath-bound magical warriors, field wizards, scouts, engineers,
priests, and contracted hunters. Their authority is formal, audited, and
revocable: orders, route rights, gate keys, supply access, spell licenses, and
relic custody are all concrete grants.

The setting should emphasize duty, command culture, dangerous expeditionary
work, practical battlefield magic, and rivalry between imperial command,
temple witnesses, guild contractors, and licensed war mages. Those are broad
genre ingredients. The capOS version must keep its empire, factions, locations,
artifacts, NPCs, magic vocabulary, and plot original to capOS.

## Core Fantasy

The player is a junior imperial operator assigned to a frontier gate-fort after
a failed expedition. They are not a chosen-one archmage. They are useful
because they can hold and delegate unusual authority safely: command passes,
ward keys, evidence seals, squad orders, relic handles, and restricted gate
routes.

The fantasy is not "collect three objects in four rooms" and it is not
permission management with fantasy labels. The target fantasy is:

```text
I gain rare authority, use it to enter forbidden places, command trusted
agents, bind dangerous relics, expose corrupt actors, and reshape the
frontier.
```

That means:

- receive a narrow mission grant,
- choose writs, companions, relics, and supplies,
- inspect a dangerous frontier site,
- discover conflicts between military, temple, guild, rebel, and wizard
  authorities,
- fight, negotiate, delegate, expose, or revoke instead of only attacking,
- route capabilities to allies who can act on them,
- survive magical incidents with limited tools,
- return with proof, prisoners, recovered relics, or a sealed gate.

That maps cleanly to capOS. Every interesting magical or political permission
can be represented as a capability, and the player experience can expose the
same idea through in-world language.

The game shape is a compact expedition RPG first:

```text
accept mission
choose writs / companions / relics
enter dangerous site
discover authority conflicts
fight / negotiate / delegate / revoke
extract with loot, survivors, evidence, or consequences
upgrade rank, base, companions, and future authority
```

Every major RPG system should answer one question: how does this change what
the player is lawfully, socially, or supernaturally able to do? If a feature
only adds generic RPG numbers, cut it or make it authority-native.

## Design Goals

- Make the first ten minutes of any session engaging, and leave room for a
  long-running campaign across many sessions, profiles, and parties.
- Keep all game verbs backed by typed service calls.
- Use NPCs as processes with explicit caps, not scripted text pasted into the
  client.
- Make authority visible: the player should understand what they are allowed
  to do and why.
- Make revocation and delegation part of play without turning the UI into an
  OS lecture.
- Make the next useful command discoverable from room text, status text,
  NPC advice, or command completions instead of requiring source reading.
- Keep exact object and actor ids player-facing and stable, with aliases only
  as convenience paths to the canonical ids.
- Preserve deterministic QEMU transcript coverage for proof slices, even as
  the wider game grows seeded variation, persistent world state, and
  multiplayer.
- Demonstrate that the capability model is usable from more than one
  application language. Rust and Lua game code should both operate through
  typed caps; neither language should receive ambient authority.
- Treat the persistent shared world as a real product surface: profiles,
  ledgers, expedition checkpoints, faction history, market state, and
  contributor evidence all live in capability-bounded services with
  authoritative server ownership.

## Non-Goals

- A parser-combinator text adventure.
- Random combat outcomes inside the deterministic QEMU smoke proof. Variance
  in normal play is fine; transcript-critical paths must remain reproducible
  under a fixed mission seed.
- Copyright-compatible retelling of any source novel.
- Kernel-side game state. The kernel enforces capability authority; mission,
  profile, ledger, and world state belong in userspace services.
- A user-owned save blob as authority over public world facts. User-owned
  Drive/Firebase capsules may back up private profile and explicit expedition
  state, but ledger records, multiplayer outcomes, market receipts, and
  contributor rewards remain server-authoritative.

## Intuitiveness Layer

The current artifact exposes the right command categories but makes the
player do too much vocabulary discovery. The next phase should treat every
room view,
inspection result, and failure message as part of the control surface.

Principles:

- Always print canonical ids for objects, actors, mobs, writs, and exits.
- Accept forgiving aliases such as `livia`, `Livia`, and `magister` only after
  resolving them to one canonical id in the response text.
- When a command nearly matches a known id, return a suggestion:
  `No broker offers ward here. Did you mean request ward-writ?`
- When an actor cannot execute an order, list one or two valid tasks if the
  player has enough information:
  `Livia cannot execute guard. With ward-writ delegated, try order livia to dispel-sigil.`
- `look` should show the current objective, visible interactables, present
  actors, hostile mobs, and one short "lead" line when the player is stuck.
- `status` should separate survival state from mission state so players can
  scan it quickly:

```text
Status: hp 12/14, guard 5, fatigue 0
Mission: expose the tower sigil, defeat ward-wraith, seal gate
Held: ward-writ accepted
Delegated: ward-writ -> livia
Lead: Livia needs line of sight; stand in the signal tower and order dispel-sigil.
```

Failure text should preserve causality. A refusal should say whether the
missing piece is location, knowledge, authority, inventory, rank, cooldown,
or target state. That makes the game feel fair and also teaches the capability
model without naming kernel concepts.

Denial should usually reward the player with a lead. A blocked action can
reveal a missing witness, unknown jurisdiction, forged seal, rival grant,
corrupt actor, unsafe state, rank gate, or alternate route:

```text
The gate refuses your route grant. It names the tower road, not the aqueduct.
Mira notices an old witness mark beside the lock.
```

Secrets and incomplete jurisdiction knowledge are core RPG fuel. The player
should often discover that they are blocked because they do not yet understand
who has authority here, not because they lack a generic key.

The current text parser can implement the first half of this through canonical
ids, aliases, and suggestions. The later `CommandSession` path should expose
the same hints as dynamic completions rather than duplicating a parser.

## Scripting And NPC Brains

The kernel capability model should enforce authority. The adventure service,
Lua scripts, NPC processes, and any later agent runners are ordinary userspace
clients of that model. They should hold only the caps their role needs and
exercise world mutation through typed service calls.

Rust should remain the default for core service code, bounded simulation, and
proof-critical state transitions. Once
[Lua Scripting](lua-scripting-proposal.md) exists, Lua is a good fit for
deterministic scenario glue: mission beats, dialogue state machines,
quest-board text, debrief variants, and scripted NPC reactions. Lua scripts
should receive narrow host APIs and object caps; they should not receive raw
cap IDs, broad spawn authority, or a way to bypass Rust service validation.

This is useful for the game because it proves the capability model is not a
Rust-only convention. A transcript can show a Rust service and a Lua-scripted
NPC both using typed authority correctly, including one denied ungranted path.

For NPC behavior that does not need deterministic transcript output, the
[Language Models and Agent Runtime](llm-and-agent-proposal.md) design is the
better fit. LLM-backed NPCs can provide tavern chatter, optional hints, flavor
summaries, or reactive dialogue, but their output should be treated as data.
They must not decide mission-critical authority, relic custody, combat damage,
or policy denials, and they should not sit on the main QEMU proof path unless
served by a deterministic stub.

Long-lived or agent-controlled NPCs should also inherit the hosted-agent
harness constraints from
[capOS-Hosted Agent Swarms](hosted-agent-swarm-proposal.md). An NPC agent is a
task-like process with a workspace/memory scope, advertised tools, audit, and
budget, not an ambient identity. The adventure-specific budget should include
per-NPC, per-session, and per-game-day token quotas, tool-call quotas,
cooldowns, and model profiles. When quota, fatigue, sleep schedule, or policy
blocks an answer, the NPC should refuse in-world, for example:
`I'm tired. Going to sleep.` That refusal is part of gameplay state and audit,
not a transport failure. Any memory/reflection output from the agent remains
low-authority data until compiled into deterministic content or service-owned
state through reviewed rules.

## Player Loop

The 30-second loop is one meaningful command and one consequence:

1. Explore, inspect, fight, negotiate, unlock, delegate, or extract.
2. Receive at least one result: loot, map knowledge, danger, faction change,
   clue, shortcut, companion reaction, or new authority state.
3. Re-evaluate the site with better or worse information.

The 10-minute loop is a writ-backed expedition:

1. Briefing: an officer grants a mission writ and one restricted gate route.
2. Preparation: the player chooses route, companion, relic loadout, and helper
   authorities such as `ward-writ`, `scout-order`, `medic-token`, or
   `relic-seal`.
3. Expedition: the player enters two or three connected frontier locations.
4. Encounter: a surprise reveals an authority conflict, enemy trick, secret
   jurisdiction fact, companion risk, or faction demand.
5. Consequence: NPCs respond, a route opens or closes, and logs/evidence
   update.
6. Extraction: the player returns with survivors, relics, evidence, scars, or
   consequences.

The multi-session loop is frontier reshaping:

1. Increase rank and unlock new jurisdictions.
2. Upgrade the base, temple, archive, court, and other authority modules.
3. Build faction reputation and expose larger conspiracies.
4. Gain companions, alter their trust and doctrine, and decide who can safely
   hold delegated power.
5. Unlock future missions by expanding legal reach, not just damage and health.

Each loop should contain one deliberate choice, one reversible mistake, and
one visible consequence. For example, the player can spend coin to buy a safe
route, persuade the scout and keep the coin, or skip the route and risk an
ambush. The transcript remains deterministic, but the player sees that the
world is not a single locked command sequence.

The first implementation can cover one mission:

```text
Mission: recover the missing eagle standard from the ruined signal tower.

Complication:
- the tower gate is unstable,
- a wounded legionary is trapped behind a ward,
- a guild scout wants payment before sharing a safe route,
- a temple witness refuses to certify the relic unless the player has not used
  a forbidden oath rite.

Good outcomes:
- standard recovered,
- survivor evacuated,
- gate sealed,
- scout paid or persuaded,
- temple witness records clean custody.
```

## Narrative Model

The game should read like a compact expedition report unfolding through play,
not like a list of room fixtures. The server owns mission state; NPC processes
own voice, advice, rumors, and local reactions.

Use mission beats:

- `briefed`: Varro states the objective and offers two optional authorities.
- `crossed-gate`: the gate opens, chat switches from fort traffic to field
  traffic, and old fort chatter becomes history.
- `first-contact`: the first hostile sign teaches `inspect` and intent text.
- `complication`: a survivor, relic, or blocked route forces a tradeoff.
- `turning-point`: the player delegates, spends, steals, persuades, or fights.
- `extraction`: the player returns with relics, witnesses, prisoners, or
  sealed-route proof.
- `debrief`: rank marks, faction opinion, and audit records update.

Narrative should be stateful and short. A room description can have variants
before and after key facts are known, but it should not become walls of prose:

```text
Ashen Road
Signal ash drifts across the old paving stones. Maro has marked a narrow
ditch-route east.
Exits: west tower-east ditch-east
Actors: maro
Lead: ask maro about route, or inspect ash-tracks.
```

NPCs should surface stakes. Livia cares about unstable wards, Varro cares
about orders and casualties, Iunia cares about custody and forbidden rites,
and Maro cares about payment, favors, and survival. Their objections create
interesting command choices rather than static lore.

## World Model

Replace the current static room list with a small graph of `Site` records:

```text
site_id
title
description
region
threat_level
exits
visible_items
actors
active_wards
required_route_cap
```

Keep the first map small:

- `fort_aurelian`: command room, quartermaster, temple annex.
- `gate_yard`: portal control, squad muster, unstable gate.
- `ashen_road`: contested approach with scout and ambush traces.
- `signal_tower`: relic objective, wounded soldier, ward puzzle.
- `under_vault`: optional dangerous route with an oath-echo hook.

The wider game should grow this into multiple settlements and outposts rather
than a single hub with more rooms. `fort_aurelian` stays the first proof
settlement. Later content can add a civilian city, a temple-administered site,
a guild waystation, and resource-producing outposts such as mines, farms,
timber camps, shrines, salvage yards, gate-yards, and repair yards. Routes
between them carry distance, hazard, faction control, seasonal closure,
cargo-limit, and authority metadata. Outposts produce bounded resources and
consume supplies through service-owned state; user save capsules can back up
private profile data but cannot invent public production or market facts.

Items should become capabilities or evidence, not inert nouns:

- `eagle_standard`: relic custody cap; proves mission objective.
- `ward_writ`: authority to request ward changes, but logs every use.
- `scout_marker`: grants access to hidden route hints.
- `oath_echo`: one-use inherited rite; powerful but politically risky.
- `temple_seal`: certifies clean custody if conditions are met.

## Actors

NPCs should be separate processes where possible:

- **Centurion Varro:** mission issuer, grants route and squad authority.
- **Magister Livia:** battlefield wizard, can identify ward failures.
- **Acolyte Iunia:** temple witness, audits relic custody and forbidden magic.
- **Maro the Guild Scout:** knows routes, trades in favors, can withhold help.
- **Wounded Legionary:** rescue objective and source of battlefield facts.
- **Gate Echo:** hostile magical presence that can corrupt routes or chat.

Each actor should own only the caps that fit its role. For example, the scout
does not get relic custody, and the temple witness does not get squad command.

## Mechanics

### Authority As Inventory

The current inventory is just strings. Split the player-facing inventory view
into:

- `items`: physical objects visible in rooms,
- `writs`: mission and faction permissions,
- `relics`: dangerous objects with custody rules,
- `marks`: progression/rank state,
- `evidence`: facts or signed observations.

Player-facing commands can still say `inventory`, but output should show why
each entry matters:

```text
Writs:
  gate-route: tower approach, expires after return
  ward-writ: request imperial ward changes, audited
Relics:
  none
Evidence:
  broken sigil: tower ward failed from inside
```

This view must not imply that all entries are picked up with `take`. Physical
objects use `take` and `drop`. Authorities use explicit grant, delegation, or
custody verbs:

- `request <writ>` asks an actor or broker for a grant.
- `accept <writ>` receives a grant already offered by an actor.
- `delegate <writ> to <actor>` grants a scoped child or NPC authority.
- `revoke <writ>` withdraws authority when the holder allows it.

Failure text should distinguish object state from authority state:

```text
You can see the southern ward, but your mission writ names only the tower gate.
Centurion Varro has not offered squad command authority.
The relic can be carried only after a temple witness seals custody.
```

### Writs As Loot

Writs are RPG loot, not boring quest permissions. A writ is gear, skill tree,
access key, and social status at the same time:

| RPG concept | Aurelian version |
| --- | --- |
| Weapon | combat writ, relic mandate, dueling license |
| Armor | ward writ, sanctuary bond, witness shield |
| Skill | delegation pattern, seal-breaking rite, custody transfer |
| Key | route grant, gate mark, archive token |
| Reputation | rank seal, faction trust, lawful standing |
| Curse | corrupted grant, forged writ, hostile obligation |
| Legendary item | ancient relic with dangerous authority |

A good writ should feel like "this changes what I can do," not "this allows
the next quest step." Writs can carry bounded affixes and drawbacks:

```text
Route Grant of Urgency
- Allows passage through old aqueduct
- Expires after 40 turns
- Cannot be delegated
- +1 faction trust if survivor extracted

Custody Writ of Burden
- Allows carrying sealed relic
- Reduces combat initiative
- Requires witness before transfer
- Breaking custody causes temple penalty
```

The modifier set must remain deterministic under the mission seed. A writ must
make issuer, scope, expiry, allowed verbs, delegation rules, drawbacks, and
revocation conditions inspectable.

### Authority Archetypes

Classes are authority archetypes, not generic stat packages:

| Archetype | Legal, social, and supernatural power |
| --- | --- |
| Warden | protects people, escorts survivors, creates safe routes, specializes in wards and evacuation |
| Marshal | enforces law, arrests hostile agents, handles bounties, duels, raids, and frontier justice |
| Archivist | finds hidden evidence, preserves witness chains, decodes old grants, detects forged authority |
| Custodian | handles relics, dangerous artifacts, sealed rooms, containment failures, and temple politics |
| Factor | controls logistics, markets, supply lines, caravan permissions, construction, and regional influence |
| Heretic/Renegade | uses forbidden authority faster while risking corruption, exile, unreliable witnesses, and hostile audits |

Two archetypes may share combat numbers, but they should solve blocked
situations with different verbs. A Warden invokes sanctuary, a Factor proves a
supply right, an Archivist exposes the old seal, and a Heretic breaks the seal
at a cost.

### Delegation Buildcraft

Delegation is buildcraft. Companions are fallible agents, not portable stat
bonuses:

| Trait | Gameplay effect |
| --- | --- |
| Loyalty | obeys the spirit versus the letter of a writ |
| Ambition | may exploit broad authority for personal goals |
| Competence | handles dangerous grants safely |
| Reputation | affects faction trust when holding delegated power |
| Fear | may abandon delegated duty under pressure |
| Doctrine | interprets ambiguous orders through law, temple rule, guild practice, or renegade code |

The player's build is partly deciding which powers to keep, which to delegate,
and whom to trust. Carrying a relic personally may block entry to a polluted
shrine. Delegating custody may free the player to act, but the companion can
be bribed, frightened, corrupted, or forced to testify later. The service owns
the deterministic result and prints the cause.

### Item Use

Add explicit verbs:

- `use <thing>`
- `give <thing> to <actor>`
- `ask <actor> about <topic>`
- `inspect <thing>`
- `seal <site|gate|relic>`
- `request <writ>`
- `accept <writ>`
- `delegate <writ> to <actor>`
- `revoke <writ>`
- `order <actor> to <task>`

The service validates authority and state. Invalid actions should return
specific text, not just the unchanged room.

### Progression

Use a small rank model:

- `tiro`: recruit/operator, tutorial grants only.
- `signifer`: can carry relic custody.
- `centurion`: can issue squad orders.
- `legate`: future high-authority profile.

This is not a stats grind. Rank changes which capabilities the broker may
grant in later missions. Magic progression can mirror this with circles:

- first circle: detect wards,
- second circle: reinforce shields,
- third circle: stabilize a minor gate.

Progression should unlock reach, not only power:

```text
Can issue temporary ward writs
Can enter disputed shrines
Can appoint one field deputy
Can challenge forged grants
Can hold two relics in custody
Can revoke delegated authority remotely
Can negotiate with hostile jurisdictions
Can operate without local witness once per mission
```

Base modules should also create new verbs, not passive bonuses:

| Module | Function |
| --- | --- |
| Archive | stores evidence, unlocks old maps, verifies claims, exposes forged records |
| Temple vault | stores relics, enables custody upgrades, binds dangerous artifacts |
| Barracks | trains deputies and companions, improves command delegation |
| Court | resolves disputes, converts evidence into rank, revokes corrupt grants |
| Market hall | trades supplies and regional favors, supports escrow for ordinary goods |
| Signal tower | extends remote revocation and delegation range, reveals route hazards |
| Sanctuary | protects rescued NPCs and creates story consequences |

### Combat

Combat should exist, but it should stay tactical and bounded. The first
interesting version does not need a full roguelike engine, but it does need
enemies, danger, skills, spells, and readable outcomes.

Combat is turn-based at the command level. A fight starts when the player
enters a hostile site, triggers a ward, fails a negotiation, or chooses to
engage. Each turn the player picks one action, allied NPCs act if present, then
hostile mobs act. The transcript should stay deterministic for smoke coverage.
Combat should attack authority as well as HP. The distinctive tactical
question is whether the player can keep lawful control while under pressure.

Enemy types should interact with authority directly:

| Enemy | Threat |
| --- | --- |
| Forger | creates fake writs and causes false accusations |
| Null-priest | disables local grants or sanctuary bonds |
| Bandit captain | steals custody tokens or route proofs |
| Corrupt magistrate | revokes or contests authority mid-mission |
| Wraith | ignores physical defenses but obeys old seals |
| Spy | learns route grants and ambushes exits |
| Oathbreaker | turns delegated powers against the player |

Good tactical verbs include:

```text
inspect seal
challenge authority
bind relic
revoke grant
delegate ward to Mira
force witness
seal exit
expose forgery
claim custody
invoke sanctuary
```

Later combat can borrow a narrow set of Evil Islands-style tactical mechanics
without inheriting its real-time randomness or punitive retreat traps. The
grounding is recorded in
[Game Mechanics Prior Art](../research/game-mechanics-prior-art.md). The useful
ideas are visible preparation, careful fight selection, body-zone targeting,
damage-type and armor interaction, stealth openings, and cast-time risk.
Aurelian should translate those into deterministic command outcomes: scouting
reveals threat and intent, inspected enemies expose vulnerable zones, weapons
and spells target bounded zones, and failed positioning has explicit costs.

Player actions:

- shield a wounded soldier with `ward-writ`,
- call a legionary NPC if holding `squad-order`,
- use `oath_echo` to bypass a lock at political cost,
- attack with a weapon skill,
- cast a prepared spell,
- guard, retreat, seal a route, or order an ally.

This gives the player real decisions without turning combat into repeated
`attack` commands.

Targeted attacks should stay small and readable:

```text
attack ward-wraith head with spear
attack imp-scout legs
cast ember-dart at ghoul hands
```

Zone effects are deterministic and bounded:

- `head`: harder to land, can increase critical or disruption outcomes;
- `hands`: can reduce attack cadence, weapon use, or casting stability;
- `legs`: can slow pursuit, block retreat prevention, or weaken charge intent;
- `core`: the default reliable target, lower risk and lower swing.

Damage and mitigation should consider weapon type, spell type, zone armor,
ward state, and inspected knowledge. A spear against a lightly armored weak
point, a mace against armored limbs, or a ward spell against a revealed sigil
should feel different in transcript text and outcome. The service still owns
the exact result; clients do not roll hidden dice.

### Mobs

Mobs should be small state machines owned by the adventure service or by
separate actor processes once that split is useful. Initial mob types:

- `imp-scout`: weak, fast, tries to flee and report.
- `ash-ghoul`: slow melee enemy, punishes unguarded players.
- `ward-wraith`: ignores ordinary weapons until a ward is inspected or broken.
- `gate-hound`: blocks retreat unless stunned or distracted.
- `echo-centurion`: elite magical-warrior enemy used as a mission boss.

Each mob has:

```text
name
threat_level
hp
armor
zone_armor
ward
attack
morale
traits
intent
```

`intent` is visible when the player has scout or wizard support:

```text
The gate-hound lowers its head. Intent: lunge at the weakest target.
The ward-wraith gathers blue fire. Intent: break shield next turn.
```

This makes fights more interesting than hidden dice rolls.

Unknown enemies should not expose full mechanical truth immediately. A scout,
wizard, height advantage, prior codex evidence, or an inspection action can
upgrade the view from rough threat to exact armor/ward/intent/counter data.
That keeps stealth and observation relevant without forcing real-time mouse
precision.

### Basic Stats

Use a small stat block:

```text
vigor      physical endurance and wound tolerance
discipline morale, command, resistance to fear
edge       weapon accuracy and quick action
ward       magical defense and shield capacity
focus      spell control and ritual stability
```

Derived values:

```text
hp         8 + vigor * 2
guard      discipline + ward
initiative edge + focus
load       vigor + discipline
```

The player should see compact status:

```text
Status: hp 12/14, guard 5, fatigue 1
Ranks: warrior 2 stars, wizard 1 circle
Prepared: shield-bind, ember-dart
Writs: tower route, ward-writ
```

Stats are not the main reward system. They exist so combat and spell choices
are legible.

### Leveling And Reputation

Progression should reward mission outcomes rather than enemy grinding. A
successful debrief can grant:

- `rank marks`: unlocks brokered authorities such as relic custody or squad
  order;
- `warrior stars`: unlocks martial and command skills;
- `wizard circles`: unlocks prepared spells and restricted ritual caps;
- `faction standing`: changes prices, testimony, help, and PvP legal status;
- `codex entries`: records inspected wards, mobs, relics, and route hazards.

Progression inputs should be auditable mission facts:

```text
Recovered eagle-standard: +1 imperial standing
Evacuated wounded-legionary: +1 cohort standing
Used oath-echo: +1 breach power, -1 temple standing
Sealed gate with witness present: unlock relic-custody eligibility
```

Rank is therefore a policy input, not just a number. A player may be strong
enough to win a fight but still unable to receive `temple-seal` authority
after abusing forbidden magic.

### Stars And Circles

Use separate progression tracks for martial and magical competence.

Warrior stars:

| Stars | Meaning | Unlocks |
| --- | --- | --- |
| 0 | civilian or raw recruit | flee, guard, basic strike |
| 1 | trained legionary | shield wall, steady aim |
| 2 | proven frontier fighter | counter, command ally |
| 3 | veteran signifer | rally, hold line, relic carry |
| 4 | centurion-grade | issue squad order, tactical stance |
| 5 | heroic champion | break elite guard, inspire cohort |

Wizard circles:

| Circle | Meaning | Unlocks |
| --- | --- | --- |
| 0 | no formal spell license | use charged relics only |
| 1 | apprentice field magic | ember dart, detect ward |
| 2 | battlefield adept | shield-bind, mend wound |
| 3 | gate specialist | stabilize gate, dispel minor ward |
| 4 | war mage | dome shield, bind hostile spirit |
| 5 | archmage authority | rewrite route, seal major breach |

Stars and circles are player-facing rank labels, not copied external lore.
Implementation may rename them if a stronger capOS-specific vocabulary emerges.
Both are capability policy inputs. A `3-star` warrior can receive relic custody
that a recruit cannot. A `2-circle` wizard can receive a `ward-writ` but not a
`gate-rewrite` cap. The player-facing fiction is rank and training; the
system-facing implementation is brokered authority.

### Skills And Spells

Skills are martial or command actions:

- `strike`: basic weapon attack.
- `guard`: reduce incoming damage and protect one ally.
- `shield-wall`: requires 1 star and an allied legionary.
- `counter`: requires 2 stars; punish a missed melee attack.
- `rally`: requires 3 stars; restore morale and clear fear.
- `order`: requires appropriate writ; make an allied NPC act now.

Spells are prepared actions with fatigue or reagent costs:

- `ember-dart`: 1 circle; reliable ranged damage.
- `detect-ward`: 1 circle; reveals ward traits and mob intent.
- `shield-bind`: 2 circles; temporary guard bonus.
- `mend-wound`: 2 circles; stabilize or heal a wounded target.
- `stabilize-gate`: 3 circles; stops gate hazards or opens safe retreat.
- `dome-shield`: 4 circles; protects the whole party for one turn.

Forbidden or risky techniques:

- `oath-echo`: one-use inherited rite; strong effect, audit cost.
- `demon-brand`: hostile shortcut; should exist as a temptation, not an
  ordinary optimal play path.

Prepared spells should be visible in `status`. The first mission can grant only
`ember-dart`, `detect-ward`, and `shield-bind`.

### Fight Commands

Add combat commands:

- `attack <mob>`
- `skill <name> [target]`
- `cast <spell> [target]`
- `guard [ally]`
- `order <ally> to <action>`
- `retreat`
- `status`

Example:

```text
[combat:signal_tower]> cast detect-ward wraith
The ward-wraith is bound to the broken tower sigil.
Intent: break shield next turn.

[combat:signal_tower]> order livia to dispel-sigil
Magister Livia spends the ward-writ grant. The sigil cracks.

[combat:signal_tower]> attack wraith
Your gladius bites through the fading ward. 5 damage.
```

### Loot And Equipment

Loot should be sparse, inspectable, and tied to authority. The game should not
become a pile of random nouns.

Item categories:

- `supplies`: torches, bandages, reagents, gate-stabilizer parts.
- `equipment`: gladius, shield, bow, focus ring, warded cloak.
- `relics`: eagle standard, sealed tablets, oath-bound cores.
- `evidence`: ash traces, broken sigil sketches, witness statements.
- `trade goods`: coin, salvage bronze, guild favors, ration chits.

Every loot entry should have at least one of these uses:

- opens a route,
- changes a combat choice,
- helps an actor,
- sells for a predictable value,
- acts as evidence in debrief,
- is dangerous custody with audit consequences.

Equipment can remain simple:

```text
weapon: affects attack damage or skill unlocks
shield: affects guard and ally protection
focus: affects spell fatigue and ward inspection
cloak: affects stealth, ambush, or faction recognition
load: caps carried gear before fatigue penalties
```

Later equipment should support blueprint/artifact construction without turning
the game into unbounded loot rolling. A construction job names a blueprint,
materials, location/facility class, rank/star/circle gates, cost, expected
duration, and output bounds. The service reserves materials and currency,
validates the job, records it, and completes or releases it through the same
transaction discipline used by markets. Item properties are derived from the
base blueprint, material choices, crafter skill/rank, facility quality, and
paid cost. Enchantment is a constrained post-process: object type, enchanter
circle, lawful authority, and remaining enchantment slots determine valid
results. Artifact-scale outputs include witness-sealed relic cases, warded
cloaks, focus rings, route compasses, golem cores, and gate-stabilizer parts.
This construction direction is grounded in
[Game Mechanics Prior Art](../research/game-mechanics-prior-art.md), especially
the Evil Islands and EVE Online notes.

Relics are not ordinary loot. They require custody authority, may be move-only,
and should be visible in audit output. Dropping or trading a relic without the
right witness should be a meaningful failure.

### Buying, Selling, And Logistics

The shopkeeper should become a small economy service rather than ambient chat.
The first version can be deterministic and local:

- `buy <item> from <actor>`
- `sell <item> to <actor>`
- `quote <item> from <actor>`
- `trade <item> to <actor> for <item|favor>`
- `repair <item> at <actor>`

Markets should have roles:

- quartermaster: sells supplies for ration chits, requires imperial standing;
- guild scout: sells route hints and contraband for coin or favors;
- temple annex: certifies relic custody and sells lawful wards;
- field engineer: repairs gate parts, golems, and damaged equipment.

Prices should be legible and bounded:

```text
Maro offers ditch-route for 1 coin or scout-favor.
Quartermaster refuses focus-ring: requires wizard circle 1.
Iunia will certify eagle-standard only if oath-echo was not used.
```

Buying and selling maps naturally to capabilities. A shop can only sell what
its actor is authorized to transfer; the player can only receive items or
writs permitted by rank, faction standing, and mission state. Trade failures
should name the blocked authority, not pretend the item is missing.

The regional market target is closer to a brokered order book than a single
shop inventory. Market services should define market-eligible item classes,
regional buy orders, sell orders, price/time priority, immediate matching when
prices cross, expiry, fees, and ordered ledger receipts. Items that are not
market-eligible still move through explicit custody, barter, witness, or quest
flows. If several services own profile inventory, expedition cargo, outpost
stock, or cloud-backed records, the market coordinator needs reserve/escrow,
commit/release, stale-version rejection, idempotency keys, cancellation, retry,
and crash-recovery behavior before any player-visible two-party exchange is
treated as implemented.
This market direction is grounded in
[Game Mechanics Prior Art](../research/game-mechanics-prior-art.md), especially
the EVE Online notes.

### Randomization

Randomness should make repeated play feel alive without making QEMU coverage
fragile. Use seeded mission variation, not hidden unbounded dice. The legal
model remains deterministic and auditable: under the same seed and discovered
facts, authority grants, denials, revocations, custody outcomes, and faction
consequences must replay exactly.

The mission seed can choose:

- one of several mob placements,
- one optional route hazard,
- one mission complication,
- one faction demand,
- one shop inventory variant,
- one companion behavior pressure,
- one relic side effect,
- one enemy authority trick,
- one optional objective,
- one loot or writ modifier,
- one NPC rumor or personality line,
- one loot cache location,
- one debrief complication,
- a calendar state: season, day, weather/hazard class, seasonal resource table,
  festival/event hook, and routine variant.

The seed should be visible through debug or transcript mode, and smoke tests
should pass a fixed seed through the manifest or mission setup:

```text
Mission seed: 0x0000_aure_0009
Variant: ash-ghoul at ashen_road, focus-ring at under_vault
```

Combat randomness should be constrained by intent text. If an attack can miss,
the player should see why through guard, morale, terrain, fatigue, or a mob
trait. Critical swings should be optional flavor unless the seed is fixed.

Calendar variation should be similarly explicit. Four 28-day seasons are a
reasonable initial model. Seasonal crops, forage, fish, shops, route hazards,
and outpost production have bounded availability tables. Ordinary seasonal
crops and fragile goods expire or degrade at season change unless the content
declares them as multi-season. Festivals and military events can alter actor
routines, witness availability, shop stock, quests, gifts, and affection-style
standing records, but those effects must be ledger/profile facts rather than
client-local counters.
This calendar direction is grounded in
[Game Mechanics Prior Art](../research/game-mechanics-prior-art.md), especially
the Stardew Valley notes.

The implemented foundation keeps this deterministic for the smoke seed:
generated mission content carries a fixed season, day, weather, hazard class,
and bounded seasonal resource records for the proof categories. Status output
prints that calendar state. Production per-run seed selection, event/festival
records, actor routine changes, and gameplay consumption/expiry rules remain
future work.

Seeded generation should produce explicit world artifacts, not invisible
ambient randomness. The stable base game remains authored content: factions,
major sites, named relics, law, core routes, capability interfaces, and proof
missions. A production world can then select deterministic overlays from a
`WorldlineSeed`:

- local room/map variants under authored region constraints;
- optional hazards, mob placement, loot caches, and rumor/debrief variants;
- seasonal resource tables, route closures, outpost production, and shop stock;
- festival or military-event schedules;
- bounded NPC routine variants and non-critical chatter hooks;
- regional market starting books, subject to service-owned order-book rules.

Every generated artifact should carry enough provenance to be replayed or
rejected: content release id, worldline id, seed epoch, generator version, scope
label, and bounded output size. Services should persist selected artifacts once
admitted so later patches do not silently rewrite active worlds. Smoke runs keep
using fixed authored selections until the generator itself has pure tests and a
fixed-seed QEMU proof.

### Chat And Room Memory

Room chat should become diegetic:

- room channels are command, scout, temple, and expedition channels,
- NPC process messages are radio/runner/magic-slate traffic,
- history replay is labeled as "recent room record" if intentionally shown,
- private messages require a separate cap or actor relation.

That turns the current chat persistence quirk into a feature.

### Multiplayer

Multiplayer should be a first-class capability demonstration, not just several
clients sharing one room. The current local foundation keeps per-player state
keyed by live endpoint caller-session metadata and assigns service-local player
labels such as `player-1` for party commands. Those labels are not caller-chosen
badges, global principal ids, or portable identity. The adventure service can
add explicit shared expedition objects for parties, duels, trades, and
contested sites when the single-service state model stops being sufficient.

Co-op mechanics:

- `party create <name>` creates a shared expedition with a leader cap.
- `party invite <player>` sends a join offer; accepting grants a party member
  cap with scoped verbs.
- `party delegate <writ> to <player>` gives another player a narrow authority,
  such as route access, relic carry, or squad order.
- `assist <player> with <task>` contributes a skill, spell, item, or witness
  action to another player's command.
- `sync-turn` or mission turn barriers let QEMU scripts prove deterministic
  multi-client combat without racing terminal input.
- Split roles make co-op matter: scout reveals intents, wizard handles wards,
  warrior protects allies, witness certifies relic custody, quartermaster
  carries supplies.

Co-op failure should be interesting but bounded. A player can waste a shared
turn, drop supplies, or revoke a delegated route, but cannot mutate another
player's private inventory without an accepted trade, custody transfer, or
party rule.

Accepted trade and custody transfer must be service-mediated state transitions,
not independent edits to two player save blobs. If one service owns both
inventories, it should perform a single version-checked mutation and emit one
ordered receipt. If ownership is split across profile, expedition, market, or
cloud-backed stores, the `Trade`/`Market`/`Expedition` coordinator needs an
escrow or saga protocol: reserve the item and consideration with idempotency
keys, commit or release both sides, record an append-only ledger receipt, and
make stale offers, cancellation, retry, and crash recovery explicit. User-owned
Drive/Firebase save capsules cannot authorize these transfers; they may only
back up the resulting private state after the authoritative receipt exists.

PvP mechanics should be opt-in and lawful in the fiction:

- `duel challenge <player>` creates a temporary arena with agreed rules.
- `duel accept <player>` grants a duel-combat cap scoped to the arena.
- `spar <player>` allows nonlethal training damage and skill practice.
- `contest <site>` lets factions compete over a route, relic, or witness
  record when the mission explicitly allows it.
- `bounty mark <player>` can exist only as a future policy-backed authority,
  never as ambient attack permission.

PvP must not mean "any client can attack any badge." Harmful verbs require an
arena, duel, faction-war, or bounty capability. The service should reject
unauthorized attacks with a policy explanation:

```text
No lawful conflict grants target marcus. Challenge a duel or enter the contested yard.
```

Useful rich PvP/co-op surfaces:

- shared threat tables where guarding an ally changes mob target intent;
- formation commands that require two or more players to hold compatible
  ranks;
- witness challenges where one party audits another party's relic custody;
- contraband markets where guild standing helps one player but hurts temple
  reputation;
- route races where two parties can choose negotiation, sabotage, or legal
  contest depending on granted authorities;
- post-mission debriefs that record contribution, friendly fire, revocations,
  trades, and witness disputes.

Architecture:

- `Expedition` service owns shared party/site/combat state.
- `Adventure` keeps private player profile and inventory state.
- `Chat` carries room, party, duel, and faction channels.
- `Trade` or `Market` service owns two-party item/currency exchange, including
  reserve/escrow, commit/release, stale-offer cleanup, and replay-safe receipts.
- `Audit` records contested custody, PvP consent, and debrief evidence.

Near-term multiplayer should use live caller-session keys now and move to
broker-granted service facets or service-created player objects once those are
available. Manifest-issued receiver selectors are not a temporary Aurelian
identity bridge; user-facing shell syntax must not choose or relabel another
service identity. A useful QEMU proof uses two player objects or two distinct
live caller sessions, one shared party, one delegated `ward-writ`, and one
deterministic assist:

```text
player1: party create tower
player1: party invite player2
player2: party accept tower
player1: delegate ward-writ to player2
player2: assist player1 with detect-ward
player1: attack ward-wraith
```

That proof is more valuable than adding network transport first because it
exercises authority, shared state, and deterministic turn ordering locally.

Keep multiplayer scoped and desirable. Near-term multiplayer is cooperative
expedition pressure: shared sites, dangerous relic custody requiring multiple
witnesses, player deputies, faction-controlled regions, contested bounties,
asynchronous rescue contracts, and public proof of heroic or criminal actions.
Open ambient PvP is not the target; harmful verbs require explicit duel,
contest, bounty, or faction-war authority.

MMO-scale open economies, broad player construction seasons, LLM-driven
mission-critical NPCs, cross-instance federation, and worldline travel are
deferred until the compact expedition loop works as a local and cooperative
RPG.

Commit `335a9ee` at `2026-04-28 22:22 UTC` landed the first bounded Phase 12
foundation: the existing `Adventure` service now owns local party records for
`party create`, `party invite`, `party accept`, `party leave`, `party delegate`,
and `assist`. Party membership, pending invites, delegated `ward-writ`, and
assist records are deterministic service state keyed by service-local player
labels derived from caller-session keys, with transitions routed through the
unit-tested `adventure-content` party state. The initial
`assist <player> with detect-ward` path requires party membership and a
matching delegated `ward-writ`; it does not transfer items, currency, or
private inventory authority. A real one-client cap assertion covers the typed
party surface, while the two-client proof remains open until the manifest and
launcher/session APIs can run two real Adventure clients with distinct live
caller-session keys without faking them inside one process.

Commit `ac49375` at `2026-04-29 06:43 UTC` landed the next bounded Phase 12
transfer foundation and keeps transfer state inside the existing `Adventure`
service. The new typed
`Adventure.transfer(item, player)` path supports `transfer <item> to <player>`
for physical items only, derives both service-local player labels from live
caller-session keys, requires shared party membership, refuses relic custody
such as `eagle-standard`, and mutates source/target inventories atomically
through unit-tested `adventure-content` transfer logic. The scenario process
asserts one-client refusal paths without synthesizing a second session. Currency
escrow, market-scale two-party exchange, and successful two-client QEMU transfer
proof remain open.

### Parallel Universes And Cross-Instance Worlds

Parallel universes fit Aurelian better as sovereign worldlines than as one
shared mutable map. Each capOS instance can host one or more worldline services
that use the same content release but different `WorldlineSeed` values, calendar
epochs, market starts, event schedules, and generated regional overlays. Players
should experience those worlds as alternate Aurelian frontiers, while the
authority model treats each worldline as its own shard with its own ledger,
market, expedition, and profile policy.

This is feasible, but only after the local authority model is solid. Raw
capability slots, endpoint generations, session ids, and local player labels
cannot be portable authority across kernels. Cross-instance play needs a
federation gateway that presents narrow local facade caps backed by remote
protocol messages:

- `WorldlineDirectory`: lists known remote worlds by content release, worldline
  id, endpoint, policy, and current ledger head.
- `WorldlineVisit`: grants read/observe/chat/travel-preview authority for a
  remote site without importing inventory or mutation rights.
- `WorldlineExpedition`: creates a bounded cross-world expedition object with
  explicit participants, allowed verbs, timeout, and home-world settlement
  rules.
- `WorldlineTransfer`: coordinates item, currency, custody, or profile-state
  movement through reserve/escrow, commit/release, replay-safe receipts, and
  content-version checks.
- `WorldlineAudit`: verifies remote receipts, ledger-head continuity, content
  hashes, generated-artifact provenance, and policy compatibility.

The game should support several integration levels, each with a different
authority cost:

- **Echo view:** a player can inspect another worldline's public map state,
  rumors, market summaries, and public history. This is read-only and can land
  first.
- **Envoy visit:** the local world creates a temporary projected character in a
  remote worldline. The projection may chat, observe, or perform explicitly
  granted low-risk actions, but cannot spend home inventory directly.
- **Expedition bridge:** two worlds run a shared mission instance with a fixed
  seed and a coordinator receipt. Contributions are recorded in both ledgers
  only after commit.
- **Trade or custody transfer:** ordinary goods, relics, currencies, or
  reputation effects move only through a transfer coordinator. Partial failure
  releases reservations; retries are idempotent.
- **Worldline migration:** a profile moves or copies into another worldline
  under policy. Public achievements and custody claims are imported as
  verifiable receipts, not trusted client save blobs.

Parallel universes make seeded generation more important. If every worldline is
the same authored graph with the same resources and routines, federation is
mostly remote chat. Meaningful worldline differences should come from bounded
seeded overlays: seasonal economies, market starts, event schedules, route
hazards, outpost outputs, NPC routines, optional dungeons, and regional map
variants. The generator must not mint authority by accident. It can choose that
`guild_iron_mine` is closed in one worldline and open in another, but the
resulting travel, market, custody, and reward effects still flow through the
same service-owned capability and ledger paths.

Cross-world compatibility rules:

- A worldline advertises a content release id and generator version. Peers may
  reject incompatible worlds or fall back to echo-only mode.
- Generated artifacts are referenced by stable ids and provenance hashes, not by
  trusting remote prose.
- Remote markets expose authenticated order/receipt views; local UI hints are
  not authority.
- Cross-world transfers name both ledger heads and both worldline ids in the
  receipt, so replay into a different universe fails closed.
- Faction standing, rank, and contributor rewards should import as witnessed
  claims with local policy gates. A remote honor does not automatically grant a
  local writ.
- Clock/calendar drift is part of the design: worlds may have different seasons,
  festivals, or wars. Shared expeditions must pin an event epoch or name which
  world's calendar controls the mission.
- Failure modes are ordinary gameplay states: remote world unavailable, receipt
  stale, policy mismatch, content hash unknown, or escrow timeout. Each should
  have a deterministic denial path.

Near-term proof should not attempt full network-transparent play. A useful first
slice can run two worldline services on one capOS instance with different fixed
seeds and prove echo view plus a denied transfer:

```text
worldline list
worldline inspect aurelian-mirror
worldline echo aurelian-mirror fort_aurelian
worldline transfer eagle-standard to aurelian-mirror
```

The expected result is that public state can be observed with content/seed
metadata, while relic transfer is rejected until custody escrow, remote policy,
and dual-ledger receipts exist.

## Capability Mapping

The setting should teach capability ideas through play:

| Game concept | capOS concept |
| --- | --- |
| mission writ | restricted launcher or mission bundle |
| gate route | endpoint/router cap with revocation |
| ward writ | typed authority to request ward-state mutation |
| relic custody | move-only cap with audit trail |
| temple witness | audit/log service with policy checks |
| rank mark | session/profile metadata influencing broker grants |
| oath echo | sealed inherited state or one-use privileged cap |
| hostile magic | untrusted service/domain with strict schema boundary |

The player does not need to see cap IDs. The game text should make authority
concrete: "You cannot open the southern ward; your writ names only the tower
gate."

## Service Architecture

Target process split:

```mermaid
flowchart TD
    Shell[capos-shell] --> Client[adventure command client]
    Client --> Adventure[Adventure service]
    Client --> Chat[Chat service]
    Adventure --> Mission[Mission state service]
    Adventure --> Audit[Audit or witness service]
    NPC1[centurion process] --> Chat
    NPC2[scout process] --> Chat
    NPC3[temple witness process] --> Chat
    NPC1 --> Adventure
    NPC2 --> Adventure
    NPC3 --> Adventure
```

Near-term implementation can keep one `adventure-server` process and separate
NPC processes that only hold `console` and `chat`, matching the current
`system-adventure.cue` shape. NPCs that affect world state should initially do
so indirectly through player-visible offers and chat events. Direct NPC calls
into `Adventure` require session-bound service facets such as `AdventureNpc`,
or an equivalent broker-granted authority that cannot mutate unrelated mission
state. Receiver-selector compatibility grants are not NPC mutation authority.

Later, mission state, actor AI, and audit/witness behavior can split into
separate services.

## Player, World, And Game Persistence

Persistence should be explicit service state, not kernel process
checkpoint/restore. The adventure game needs several kinds of state with
different durability rules:

- **Session state:** foreground client state, prompt mode, transient command
  context, and chat cursors. This is per client and may disappear when the
  client exits.
- **Expedition state:** current site, active mobs, hp/fatigue, temporary effects,
  party membership, pending invites, turn ordering, and in-progress objective
  state. It is resumable only when the player explicitly resumes an expedition.
  Ordinary `run adventure-client` should start from the current profile but not
  silently continue a half-finished mission.
- **Profile state:** player id, display handle, rank marks, warrior stars,
  wizard circles, faction standing, cosmetics, contributor badges, title choices,
  and settings. This is durable player data and must survive client exit; once a
  durable store exists it should survive reboot.
- **Ledger state:** append-only mission facts, debrief records, relic custody,
  forbidden-rite use, witness certifications, market/trade receipts, reward
  mints, and revocations. This is the audit source for profile mutations and
  should be harder to rewrite than profile summary fields.
- **World/public state:** server-authoritative shared world data: persistent
  room history, public faction standing and consequences, quest-board state,
  market stock and prices, contested-site outcomes, ledger-derived public
  history, and shared campaign events. This is owned by game services, not by
  any one client, and is separate from private profile inventory. Smoke
  transcripts exercise a bounded slice of this state; production game-world
  instances grow it under capacity policy and shard boundaries rather than a
  fixed cap.
- **Content state:** mission definitions, generated content blobs, aliases,
  dialogue, map graph, and validation metadata. This is versioned read-only
  content selected by content hash or release id, not player-mutable state.
- **User-owned backup state:** encrypted save capsules stored through a browser
  session in the user's own Google Drive app data folder or Firebase-backed user
  document space. This is private backup/sync state, not an authoritative source
  for shared world facts, rewards, or multiplayer outcomes.

Internal service split:

```mermaid
flowchart TD
    Client[Adventure client] --> Adventure[Adventure service]
    Adventure --> Content[AdventureContentCatalog]
    Adventure --> Profile[AdventureProfileService]
    Adventure --> Expedition[AdventureExpeditionService]
    Adventure --> Ledger[AdventureLedger]
    Profile --> Save[AdventureSaveStore]
    Expedition --> Save
    Ledger --> Save
    Save --> Store[Store or CloudGameStore]
    Save --> Vault[UserOwnedSaveVault]
```

- `AdventureContentCatalog` exposes validated read-only mission content by
  content hash or release id and reports the generator/schema version used to
  build it.
- `AdventureProfileService` owns durable per-player profile summaries. The
  current pre-ledger substrate may expose direct bounded summary mutation for
  host-testable save/load behavior, but final reward, title, rank, faction,
  cosmetic, badge, and similar profile application must be ledger-backed once
  `AdventureLedger` exists.
- `AdventureExpeditionService` owns active mission/world instances. It can keep
  short-lived expeditions in memory, but explicit resume requires a checkpoint
  written through `AdventureSaveStore`.
- `AdventureLedger` is append-only from ordinary game clients. Correction and
  revocation require separate witness/admin authority and must leave a record
  rather than rewriting history.
- `AdventureSaveStore` serializes bounded Cap'n Proto save records to whichever
  backing service it was granted. It hides whether the backing is RAM, local disk
  `Store`/`Namespace`, or a cloud bridge.
- `CloudGameStore` is an optional bridge service, not a replacement for capOS
  storage semantics. It exposes the same save/load/append operations as the local
  store adapter and should be granted only to the profile, expedition, and ledger
  services that need it.
- `UserOwnedSaveVault` is a browser-mediated backup target. The browser receives
  an encrypted, signed save capsule and writes it using user-granted Drive or
  Firebase authority. Encryption keys follow the storage domain: local capOS
  storage uses local capOS-host key material, while GCP-backed game-world data
  uses Cloud KMS envelope encryption with a per-world or per-shard KEK wrapping
  service-owned DEKs. capOS and the adventure service do not receive the user's
  OAuth access token, Firebase refresh token, Drive file IDs beyond opaque
  handles, or provider credentials.

Recommended rollout:

1. **Volatile baseline:** keep current in-memory state keyed by the live
   endpoint caller-session scoped ref plus epoch, but define the profile,
   expedition, ledger, and content records as bounded structs and add host tests
   for encode/decode and migration rules. Normal shell launch/grant commands
   now omit legacy badge and receiver-selector syntax; explicit selectors are
   low-level compatibility or hostile-path fixtures, not the state identity
   model.
2. **Local store baseline:** use RAM-backed then disk-backed `Store`/`Namespace`
   caps to prove profile save/load, explicit expedition checkpoint/resume, and
   ledger append/replay. This is the offline and QEMU proof path.
3. **GCP-backed bridge:** run a narrow `CloudGameStore` bridge outside capOS or
   as a capOS service once networking is available. A practical GCP deployment
   uses Cloud Run for the bridge endpoint, Firestore Native mode for mutable
   profile/index documents and transactional updates, Cloud Storage with object
   versioning/lifecycle policy for immutable snapshots and evidence blobs, and
   Secret Manager for bridge-side service credentials. capOS clients still see
   only the `CloudGameStore` capability.
4. **User-owned browser vault:** for private player data, a web terminal or
   browser companion can store encrypted save capsules in Google Drive
   `appDataFolder` or a Firebase user document. This is useful before capOS has
   durable local disk or direct provider SDK support. It must be treated as
   user-controlled transport for game-world encrypted data: the user can delete,
   withhold, duplicate, or roll back blobs, but cannot decrypt or forge accepted
   state without the relevant local capOS key or game-world KMS authority. On
   restore, the game verifies signatures, schema/content hashes, profile id,
   monotonic capsule version, previous capsule hash, and policy bounds before
   accepting any state; decrypted ledger records still validate their own
   previous-record hash chains.
5. **Hybrid sync:** local `Store` remains the source for QEMU/offline proof
   paths, while `CloudGameStore` replicates selected profile/ledger objects. The
   sync boundary must be explicit: profile summaries may be overwritten through a
   checked version, ledger records append, and expedition checkpoints resolve
   conflicts by rejecting stale writes rather than merging combat state.

Minimum save record set:

```text
AdventureProfile {
  profile_id
  display_handle
  version
  ranks
  warrior_stars
  wizard_circles
  faction_standing
  cosmetics
  contributor_badges
  settings
  updated_at
}

AdventureExpeditionCheckpoint {
  expedition_id
  profile_id
  content_hash
  checkpoint_version
  site_id
  objective_state
  player_state
  party_state
  mob_state
  pending_events
  saved_at
}

AdventureLedgerRecord {
  record_id
  profile_id
  expedition_id
  content_hash
  kind
  previous_record_hash
  payload
  witness
  created_at
  revoked_by
}
```

User-owned save capsules wrap those records rather than replacing them:

```text
UserSaveCapsule {
  schema_version
  capsule_version
  profile_id
  device_id
  content_hash
  migration_policy
  record_kind
  record_version
  previous_capsule_hash
  plaintext_hash
  ciphertext
  aead_algorithm
  signature_algorithm
  signer_public_key_id
  signature
  created_at
}
```

Capsule encryption follows the same storage-domain rule as the backing store.
When state is stored locally on a capOS host, the encryption key is local
capOS-host key material and local backup/restore needs an explicit local key
recovery story. When state is stored in GCP services, Cloud KMS is the
key-encrypting-key service: it wraps or unwraps a capsule DEK, while the
game-world service decrypts and validates capsule plaintext internally using
the unwrapped DEK as service authority, modeled as a `SymmetricKey` capability.
The browser may transport ciphertext, wrapped DEKs, and opaque Drive/Firebase
handles, but it should not receive a plaintext DEK, `SymmetricKey` cap,
`KeySource` cap, KMS decrypt/unwrap grant, or provider-independent plaintext
authority unless a later explicit user-managed key export design adds that
mode. For GCP-backed worlds, access to unwrap and use the DEK is game-world
service authority mediated by KMS/IAM, not ownership of the Drive or Firebase
blob alone.

For the GCP path, each game-world instance or shard gets its own Cloud KMS key
ring and symmetric CryptoKey KEK. Runtime grants are scoped to the CryptoKey
where possible: encrypt-only writers use `roles/cloudkms.cryptoKeyEncrypter` to
wrap new DEKs, restore/migration readers use `roles/cloudkms.cryptoKeyDecrypter`
to unwrap existing DEKs, and only the small game-world service that must do both
uses `roles/cloudkms.cryptoKeyEncrypterDecrypter`. Rotation affects future DEK
wrapping but does not re-encrypt existing capsules or retire old key versions.
Re-encryption or rewrapping is a managed service operation: decrypt and validate
the capsule inside the game-world service, then write a new capsule with a new
DEK or a DEK rewrapped by the current primary KEK version. Old versions stay
enabled until no accepted wrapped DEK depends on them. Retiring a world removes
decrypt IAM first, may disable key versions to make protected capsules
inaccessible, and only schedules destruction after audit/recovery decisions
because completed key version destruction is irreversible.

Every persisted record needs a schema version, content hash or release id, size
limit, and migration rule. Save/load must fail closed when the content hash is
unknown, the record exceeds bounds, a capsule or ledger hash chain does not
match, or the caller lacks the profile/expedition authority.

Do not use user-owned Drive/Firebase blobs as authority for public state:

- contributor rewards still require `AdventureLedger` witness records;
- multiplayer outcomes and market trades still require service-side validation;
- public room history and shared world events should be stored by the game
  service or cloud bridge, not accepted from a user's private backup;
- rollback of a private backup may restore local profile cosmetics or an
  explicit expedition checkpoint, but it must not erase append-only public
  ledger facts.

## Interface Sequencing

Do not add new gameplay verbs only as ad hoc client text. Every verb that
changes world state needs a typed route before it is accepted as implemented.

For Phase 1 verbs, update these surfaces together:

- `schema/capos.capnp`: add methods or typed command records for `inspect`,
  `use`, `give`, `ask`, `order`, `seal`, `status`, and explicit authority
  verbs including `request`, `accept`, `delegate`, and `revoke`.
- `tools/generated/` and canonical generated bindings through the existing
  generated-code workflow.
- `demos/capos-chat`: add request encoders, result decoders, and DTOs for the
  new adventure methods.
- `demos/adventure-server`: validate state, authority, bounds, and failure
  text in server handlers.
- `demos/adventure-client`: keep parsing thin; convert user text to typed
  calls rather than duplicating game rules.
- `tools/qemu-shell-smoke.sh`: assert one success path and one failure path for
  each new state-changing method.

The future `CommandSession` interface can replace the text adapter, but it is
not a reason to add stringly world mutation in the interim.

## Resource Bounds And Determinism

Two distinct bound regimes apply: the deterministic QEMU smoke proof, which
must stay small and reproducible, and the production game-world instance,
which is bounded by service capacity, shard policy, and quotas rather than a
single fixed cap. The numeric limits below are the smoke-instance defaults;
production tuning belongs to the game-world deployment runbook and grows with
profile/ledger/expedition substrate, multiplayer authority, and persistent
world state.

Smoke-instance and per-shard rules:

- Per-instance `MAX_PLAYERS` stays explicit; every per-player map entry is
  removed on `leave` or process teardown.
- Cap per-player inventory entries, writs, relics, marks, evidence records,
  active effects, and remembered chat cursors.
- Cap per-site mobs, items, active wards, actors, and pending events.
- Cap combat transcript lines per turn and reject oversized action text before
  semantic parsing.
- Smoke transcripts use fixed encounter scripts. Production play may seed
  variation from mission state, but transcript-critical paths must still force
  a stable seed.
- Keep multiplayer parties, duels, trades, pending invites, and contested-site
  records bounded per mission/shard with explicit overflow behavior, not
  silent drop.
- Chat history must either be cursor-based per client or printed under an
  explicit "recent room record" header with a bounded line count for live
  views; persistent chat history may grow under retention policy in
  ledger/world-state services.
- The current `StdIO` adapter may accept 256-byte command lines, but typed ids
  inside service calls remain 64-byte ASCII ids unless a reviewed schema/runtime
  change raises that limit.
- Keep free-form text fields separate from ids: `say` text and future
  rest-of-line command text may use the command-line limit, while object ids,
  actor ids, mob ids, writ ids, directions, spell names, and skill names use the
  id limit.
- Generated mission content must define explicit bounds for titles,
  descriptions, lead text, aliases, dialogue, and debrief lines, and branches
  that check in generated content need a freshness check so generated Rust blobs
  cannot drift from source mission data.

Smoke-instance suggested limits (production shards may raise these under
capacity policy, but transcript-critical paths must run inside these bounds):

```text
players: 64
inventory entries per player: 16
writs per player: 8
evidence records per player: 16
active effects per player: 8
mobs per site: 8
party members: 4
pending trades per player: 4
pending invites per player: 4
chat history per room: 16 lines
command-line bytes: 256
typed id bytes: 64
room/site title bytes: 80
description bytes: 320
lead/failure-hint bytes: 160
actor dialogue/debrief line bytes: 320
```

## Command Surface

The current `StdIO` parser can grow the first mission quickly, but the target
should be the structured command session described in
[interactive-command-surface-proposal.md](interactive-command-surface-proposal.md).

Initial text commands:

- `look`
- `go <direction>`
- `inspect <thing>`
- `take <thing>`
- `use <thing>`
- `give <thing> to <actor>`
- `ask <actor> about <topic>`
- `request <writ>`
- `accept <writ>`
- `delegate <writ> to <actor>`
- `revoke <writ>`
- `order <actor> to <task>`
- `seal <target>`
- `inventory`
- `status`
- `say <text>`
- `quote <item> from <actor>`
- `buy <item> from <actor>`
- `sell <item> to <actor>`
- `trade <item> to <actor> for <item|favor>`
- `repair <item> at <actor>`
- `party <create|invite|accept|leave|delegate>`
- `assist <player> with <task>`
- `duel <challenge|accept|yield>`
- `spar <player>`
- `contest <site>`
- `quit`

Dynamic completions should come from room state:

- exits for `go`,
- visible items and held writs for `inspect` and `use`,
- present actors for `ask` and `give`,
- quoted shop inventory for `buy` and `sell`,
- party members and pending invites for `party` and `assist`,
- mission targets for `seal`.

## Rich Browser Client

A later browser client should be a real game presentation layer: pixel-art
locations, animated characters, inventory and authority panels, combat affordance
buttons, event feeds, and chat surfaces. It should not be a terminal emulator
with decorative art around `StdIO`.

The presentation model should be a 2D tilemap, not prose-only room cards.
World data sent to the browser can include maps, tilesets, tile layers, object
layers, collision/interaction zones, spawn points, actor paths, region/outpost
markers, and event triggers. Tiled JSON is a plausible authoring/export format
if the content validator rejects oversized maps, missing tiles, unknown layer
types, invalid object references, and presentation data that tries to carry
authority. PixiJS plus `@pixi/tilemap` is a reasonable first rendering
candidate because it targets WebGL 2D tile rendering with a canvas fallback.
That renderer choice must stay client-side; the game service remains the owner
of authoritative location, collision, interaction, market, custody, and combat
state.

That client can bypass `adventure-client`. The text client remains valuable for
QEMU proofs, scripted transcripts, and compatibility, but the browser UI should
talk to the adventure and chat services through WebShellGateway-held session
authority:

```text
Browser pixel-art UI
  -> WebShellGateway / web shell capability-call proxy
  -> session-scoped AdventurePlayer and ChatParticipant caps
  -> adventure-server and chat-server
```

The browser does not hold capOS capabilities directly. It holds opaque
web-session handles and sends typed UI actions such as movement, target
selection, inventory use, delegation, order, spell, skill, and chat requests.
The gateway maps those requests onto the real session-scoped capabilities and
returns structured view state or event records for rendering. Raw capOS
`CapId`s, badge selectors, game-world keys, provider credentials, broad network
authority, and shell spawn authority must not cross into browser JavaScript.

For the purpose-built adventure UI, a narrow `AdventurePlayer` /
`ChatParticipant` surface is a better primary ABI than generic terminal text:

```text
AdventurePlayer.look()
AdventurePlayer.go(direction)
AdventurePlayer.status()
AdventurePlayer.inventory()
AdventurePlayer.useItem(item, target)
AdventurePlayer.order(actor, task)
AdventurePlayer.cast(spell, target)
AdventurePlayer.skill(skill, target)
AdventurePlayer.delegate(writ, actor)
AdventurePlayer.pollEvents(cursor, maxEvents)

ChatParticipant.say(text)
ChatParticipant.history(cursor, maxLines)
```

`CommandSession` can still exist for terminal-like front ends, command palettes,
automation, and compatibility adapters. It is not required for a custom
pixel-art client whose UI already knows it is presenting the adventure game.
The non-negotiable boundary is that browser presentation never becomes
authority. Every action still flows through typed game capabilities, and the
server rejects invalid location, stale state, missing authority, bad custody,
combat restrictions, and oversized input.

This belongs well after the current game-depth phases. It depends on
WebShellGateway authentication/origin policy and teardown, session-bound
adventure/chat identity, persistent profile/checkpoint semantics, and a stable
core game loop. Asset manifests for sprites, portraits, tiles, VFX, UI sounds,
and animation ids should be explicit data. Asset presence or selection must not
grant game authority, and missing assets should fail as presentation errors
rather than mutating game state.

The browser harness should verify more than successful loading. It should drive
one deterministic mission through UI actions and check tilemap layer order,
actor placement, viewport/camera bounds, collision affordances, event-feed
updates, logout/tab-close teardown, and rejection of browser-side attempts to
mutate authoritative state without the typed gateway call.

## QEMU Proof Path

Keep a deterministic smoke path similar to `make run-adventure`, but make it
prove game mechanics:

```text
setup/login
run adventure-client
status
ask centurion about mission
request ward-writ
go gate
use ward-writ
go tower
inspect standard
recover eagle-standard
ask legionary about ward
give scout-marker to scout
go under-vault
seal gate
inventory
quit
exit
```

Assertions should check:

- launch grants remain explicit,
- no password leaks into logs,
- invalid action returns a specific failure,
- authority grant/delegation uses explicit verbs rather than `take`,
- item use changes world state,
- NPC process reacts to at least one player action,
- mission completion records an audit/witness line,
- replayed chat is either suppressed or labeled as history,
- at least one canonical-id suggestion for a near-miss command,
- one shop quote or rejected trade explains the authority or price gate,
- a fixed mission seed prints stable variant and calendar metadata once
  randomization lands,
- a two-client co-op proof can delegate one writ or assist one action without
  leaking private inventory authority.

Current implemented proof coverage is intentionally narrower than the eventual
target game, but it now follows the Aurelian mission path. `make
run-adventure` keeps the shell-driven `adventure-client` transcript focused on
representative interactive behavior: typed `inspect`, `status`, `attack`,
`skill`, `cast`, `give`, `ask`, `order`, `request`, `accept`, and `delegate`
calls; room-view mission, lead, actor, mob, writ, item, and canonical exit
context; categorized `Items`, `Writs`, `Relics`, `Marks`, and `Evidence`
output; a rejected invalid inspect input; canonical-id suggestions for
near-miss `ward` and `wraith` inputs; Maro route evidence on `ashen_road`; a
separate NPC process reaction; a failed attack against a warded mob; delegated
`order livia to dispel-sigil` exposing a ward; a resolved `Livia` actor alias
with an improved task hint; repeated `detect-ward` idempotence on an already
exposed ward; `ember-dart` spell damage; a 2-star warrior `strike`; and
`eagle-standard` recovery.

The complex custody path is covered by `adventure-scenario-test`, a real capOS
userspace process with only `Console` and `Adventure` caps. It calls
`AdventureClient` methods under QEMU and asserts initial categories,
`under_vault` denial before `temple-seal`, pre-recovery Iunia denial,
ward-writ route authority setup, ward-wraith defeat, relic recovery,
non-droppable relic behavior, missing-location custody denial, missing
ward-writ authority denial, unsafe-route witness refusal, survivor evacuation,
gate sealing, witness-certified `temple-seal` custody, final evidence tokens,
and `under_vault` access after custody.

The test strategy should stay split by risk. Pure deterministic game logic
should live in ordinary Rust unit tests where possible: calendar rollover,
seasonal availability, market matching, escrow state machines, blueprint
validation, artifact property derivation, enchantment limits, route
constraints, and agent quota accounting. Cross-service gameplay scenarios
should use a real Rust userspace test client process that calls game caps under
QEMU, as `adventure-scenario-test` already does for custody. The shell-driven
`adventure-client` transcript remains the basic command/client proof for
parser behavior, rendering, representative typed calls, and smoke-path
integration; it should not become the only coverage for complex market,
construction, economy, or agent-NPC state machines.

## Implementation Plan

### Phase 1: Player-Visible Mission Substrate

- Implemented so far:
  - typed `inspect`, `use`, `status`, `attack`, `skill`, `cast`, and `guard`
    methods across schema, generated bindings, client wrappers, server
    handlers, terminal parser, and QEMU transcript assertions,
  - typed `give`, `ask`, `order`, `seal`, `request`, `accept`, `delegate`,
    and `revoke` methods across the same schema/client/server/parser/proof
    path,
  - explicit result text for failed and successful `go`, `take`, and `drop`
    actions,
  - compact player combat stats in `status`: hp, guard, fatigue, warrior
    stars, wizard circles, prepared spells, and active mobs,
  - one deterministic ward-wraith encounter with a warded-mob failure path,
    spell reveal, spell damage, martial skill damage, guard effect, and mob
    defeat,
  - one explicit objective and completion condition tied to ward-wraith defeat,
  - minimal per-player authority state for `ward-writ` request, acceptance,
    delegation, revocation, and gate sealing,
  - bounded per-player evidence/effect storage surfaced in `status`,
  - replayed room chat labeled as history for later room joins,
  - bounded object-id validation for typed object inputs,
  - server-side canonical id normalization for common casing and title aliases,
    plus bounded near-miss suggestions for the current mission ids,
  - typed `AdventureRoomView` mission, lead, actor, mob, writ, item, and
    canonical exit context rendered by `look`,
  - structured status and inventory output split into survival, location,
    mission, physical items, writs, relic custody, marks, evidence, effects,
    and lead,
  - idempotent repeated spell behavior in the interactive transcript,
  - a dedicated `adventure-scenario-test` userspace process that calls the
    `Adventure` cap directly to prove relic custody denial, witness refusal,
    temple-seal certification, categorized evidence, and `under_vault` access.
- Current playable slice: the Aurelian gate-fort mission now comes from
  `demos/adventure-content/content/prototype.cue`, with checked-in generated
  Rust output consumed by the server and verified by `make
  generated-code-check`. State-changing behavior remains in Rust handlers, and
  `make run-adventure` proves the interactive `eagle-standard` recovery and
  replay-history path, while `adventure-scenario-test` proves survivor,
  gate-seal, and temple custody outcomes through real `Adventure` cap calls.
- Typed relic recovery: `recover eagle-standard` is the dedicated custody verb,
  with `take` and `drop` reserved for physical items.
- Local party foundation: `Adventure` owns the first deterministic party state
  for service-local player labels, pending invites, scoped `ward-writ`
  delegation, and `detect-ward` assist records. PvP consent, transfer escrow,
  and the two-client QEMU proof remain future work.
- Physical-item transfer foundation: `Adventure.transfer` performs same-party
  local item mutation for ordinary inventory items and leaves currency escrow,
  cross-service trade, relic custody transfer, and successful two-client proof
  as future work.

### Phase 2: Imperial Frontier Mission

- Replace current four-room content with the Aurelian gate-fort mission.
  Complete.
- Preserve objective/lead text in `look` and `status`, plus canonical-id
  suggestions for common near-miss commands.
- Add typed inventory categories: items, writs, relics, evidence, marks.
  Complete for player-facing status and inventory output.
- Add at least three actor processes with distinct chat/personality behavior;
  keep them chat-only unless explicit scoped `Adventure` grants and tests land
  in the same slice.
- Add one route requiring a capability-style permission.
- Add one objective with two acceptable outcomes.
- Add one narrative debrief that records rank, standing, evidence, and audit
  consequences.

### Phase 3: Persistent Profile And Ledger Substrate

- Define `AdventureProfile`, `AdventureExpeditionCheckpoint`, and
  `AdventureLedgerRecord` structs with schema versions, content hashes, size
  limits, and host migration tests.
- Add `AdventureProfileService`, `AdventureExpeditionService`,
  `AdventureLedger`, and `AdventureSaveStore` interfaces before persisting
  profile or world state in ad hoc server maps.
- Prove a local baseline first: profile save/load, ledger append/replay, and
  explicit expedition checkpoint/resume through RAM-backed or disk-backed
  `Store`/`Namespace`.
- Keep ordinary client launch fresh by default; require an explicit resume
  command or profile option before loading an active expedition checkpoint.
- Add one rejected stale-checkpoint write and one rejected wrong-profile load to
  QEMU or host-level proof coverage.

### Phase 4: User-Owned Browser Save Vault

- Define `UserSaveCapsule` and browser transport semantics for private encrypted
  profile, settings, and explicit expedition checkpoint backups.
- Use Google Drive `appDataFolder` or Firebase user documents as opaque capsule
  transports only; browser-held OAuth/Firebase tokens must not enter capOS game
  services.
- Add tamper, wrong-profile, stale-version, replay, unknown-content, and
  oversized-capsule rejection tests before real provider adapters.
- Keep public world state, multiplayer outcomes, reward witnesses, and market
  receipts out of user-owned blobs.

### Phase 5: Compact Authority-RPG Loop

The next implementation phase should build on the pure targeted-combat
foundation from commit `f149119`, not reopen broad calendar, market,
construction, agent-NPC, federation, or worldline systems. The goal is one
excellent expedition loop where authority is RPG power: choose writs and
companions, enter a dangerous site, discover authority conflict, fight or
negotiate under pressure, delegate or revoke power, extract, and gain reach for
future missions.

- Generate combat profiles from CUE for current mobs and validate malformed
  zones, damage kinds, alert groups, recognition thresholds, and stealth
  references through `make generated-code-check`.
- Integrate generated combat profiles into `adventure-server` so inspected
  attacks use deterministic zone damage, fatigue, interruption, recognition,
  and alert helpers. Clients must not submit computed damage.
- Extend parser/proof coverage only as needed for unambiguous authority-RPG
  commands: `attack <mob> [zone] [with gladius]`,
  `cast <spell> at <mob> [zone]`, and at least one authority-combat verb such
  as `inspect seal`, `challenge authority`, or `expose forgery`.
- Add one authority-attacking enemy behavior to the existing expedition: a
  forged route/custody claim, stolen custody token, seal conflict, corrupt
  revocation, or old-law wraith claim that can be inspected, exposed, bound,
  or revoked.
- Treat writs as loot. Add one fixed-seed or authored writ modifier with a
  meaningful drawback; print issuer, scope, expiry, delegation rules,
  revocation conditions, modifier, and drawback in inspect/status output, and
  enforce the drawback in service logic.
- Add one delegation-buildcraft proof using an existing companion. A trait such
  as loyalty, competence, fear, reputation, or doctrine should change how a
  delegated `ward-writ` or custody authority behaves and explain the cause.
- Add one reach-based debrief unlock, such as Archive evidence verification,
  Temple vault custody upgrade, Signal tower remote revocation, or appointing
  one field deputy. This should unlock a future verb or jurisdiction, not
  generic damage or health.
- Keep denial rewarding: at least one new authority denial should reveal a lead
  about hidden jurisdiction, forged authority, missing witness, rival claim,
  or alternate route.
- Prove the slice with pure Rust tests for deterministic rules and one
  `adventure-scenario-test` path covering inspected targeted attack, authority
  threat/lead, writ drawback, delegation consequence, and reach unlock. The
  shell transcript should remain representative parser and smoke coverage.

Broad systems remain deliberately demoted until this loop is strong:
calendar/season gameplay, regional market order books, construction jobs,
artifact/enchantment production, optional agent NPCs, MMO/open economy work,
federation, and worldlines should not be treated as next local sequencing
truth for implementation agents.

### Phase 6: Structured Command Session

- Move from app-owned `StdIO` parsing to `CommandSession`.
- Expose dynamic command metadata and completions.
- Keep a text adapter for QEMU scripts.

### Phase 7: Multiplayer Authority Proof

- Do not start this phase until Adventure and chat authority use session-bound
  caller identity, or future broker-granted service facets, rather than player
  receiver-selector identity. The first bounded slices key local player labels from live
  caller-session metadata.
- Add local multi-client party state keyed by service-created player objects,
  with explicit invite, accept, leave, and delegation commands.
- Add one deterministic co-op combat or ward puzzle where one player assists
  another without receiving unrelated inventory authority.
- Add one opt-in duel or sparring proof with scoped harmful authority and a
  rejected unauthorized attack path.
- Add bounded trade offers for ordinary loot and reject relic transfers unless
  custody authority permits them. The proof must show the transfer coordinator
  cannot duplicate, lose, or partially transfer an item when offers go stale,
  cancellation races with acceptance, or a retry repeats the same request.
- Extend QEMU scripting to drive two clients or two command sessions through
  a stable multiplayer transcript.

## Future Follow-Up: Golems, Gates, And Infrastructure

Golems should be imperial magotechnical infrastructure before they are enemies.
They fit the setting as labor frames, cargo haulers, bridge-builders, sentries,
field repair units, siege engines, and rare battlefield assets. Model each
golem as a body, a bound core, and an energy source: the body defines role, the
core defines identity and obedience, and the energy source defines endurance.

Initial golem types:

- `cargo-golem`: moves sealed supplies or heavy relics only when granted a
  matching route authority.
- `ward-golem`: guards a shrine, vault, or gate and recognizes proof tokens
  rather than passwords.
- `siege-golem`: breaks barriers but requires multiple grants, such as
  engineer approval plus energy access.
- `field-repair-golem`: restores damaged ward anchors when supplied with
  materials and repair authority.
- `corrupted-golem`: obeys malformed or stale authority, making revocation
  and audit behavior visible in play.

A golem should not become ordinary inventory. The player receives scoped
command authority over it: inspect, wake, route, repair, bind, delegate, audit,
or revoke. A useful rule of thumb: `order cargo-golem north-gate` succeeds only
when the player holds both `cargo-command` and `north-gate-route`.

Gates and portals should be imperial route infrastructure: roads made
executable. They move authority, troops, messengers, and supplies across the
frontier. Standing at a gate is not enough; use requires a physical anchor plus
a valid writ, seal, route token, ward key, or alignment state.

Gate components:

- `gate-anchor`: fixed legal endpoint.
- `route-writ`: temporary authority to open one path.
- `ward-key`: faction or office authorization.
- `stabilizer`: consumable or repairable part that bounds usage.
- `gate-log`: inspectable audit trail for deterministic investigation
  evidence.

Gate constraints should create missions rather than decoration:

- gates open only between known anchors,
- heavy constructs require freight routes rather than personal routes,
- damaged gates can misroute, refuse cargo, or leak hostile entities,
- emergency gates can open one-way and revoke the route after use.

Follow-up mission candidates:

- Gate repair: recover a stabilizer, prove engineer authority, order a repair
  golem, and open a bounded evacuation route.
- Golem command: delegate a narrow task to a ward golem after presenting the
  correct seal.
- Logistics: move medicine, grain, or signal crystals through gate routes with
  cargo-size and route-authority limits.
- Investigation: inspect gate logs, compare seals, and identify which faction
  abused or forged route authority.
- Siege: choose between spending rare siege-golem command, negotiating gate
  access, or repairing an old military road.
- Containment: seal a corrupted portal while wizard-circle spells stabilize
  the breach and warrior-star formations defend the site.

Typed verb candidates for these later slices include `bind`, `route`,
`repair`, `charge`, `open-gate`, `seal-gate`, `attune`, `stabilize`,
`trace-route`, and `audit-gate`. They should remain scoped and revocable, and
status output should expose active seals, bound routes, charged spells,
wounded formation members, unstable wards, and delegated golem tasks.

## Open Questions

- Should actor NPCs call the adventure service directly, or should they only
  communicate through chat in the first interesting version?
- How much randomized event timing can be allowed in production play before
  QEMU transcript coverage becomes brittle, given the smoke path runs under a
  fixed seed?
- Should shops and trades live inside `Adventure` at first, or split into a
  `Market` service once two-party trade exists?
- Should parties be mission-local objects, profile-level groups, or future
  session broker grants?
- What is the minimum PvP consent record that is useful for the game without
  overbuilding policy after the profile/ledger substrate exists?
- How are game-world shards/instances scoped: one shared world, one per
  campaign, one per party, or one per deployment? This determines whether
  faction standing, ledger history, and market state are global or per-shard.
- Where does the boundary sit between server-authoritative public history
  (visible to all players in a shard) and per-profile audit records that
  remain private even within the same shard?
- After the echo-only worldline proof, should the next federation slice be
  envoy visits, expedition bridges, market/custody transfer, or profile
  migration?
- What retention/archival policy applies to ledger records, debrief evidence,
  and chat history once the game runs long enough to accumulate them?

## Follow-Up Proposal

After the Aurelian adventure design is implemented well enough to support
stable profiles, ranks, evidence, debriefs, cosmetic items, and deterministic
proof coverage, the game can grow a separate contributor-facing layer.

That follow-up is tracked in
[Contributor Quest Mechanics](contributor-quest-mechanics-proposal.md). It
describes maintainer-witnessed "outer-world quests" for real capOS development
work, such as fixing a full GitHub issue URL or improving QEMU proofs, and
limits rewards to badges, temporary states, decorative items, and bounded
game-only perks. It must not grant repository authority, OS authority, or any
ability to mutate another player's profile.

## Design Grounding

Grounding files for this proposal:

- `CLAUDE.md`
- `README.md`
- `docs/proposals/index.md`
- `docs/proposals/interactive-command-surface-proposal.md`
- `docs/proposals/session-bound-invocation-context-proposal.md`
- `docs/proposals/shell-proposal.md`
- `docs/proposals/boot-to-shell-proposal.md`
- `docs/backlog/runtime-network-shell.md`
- `docs/proposals/service-object-capabilities-proposal.md`
- `docs/backlog/stage-6-capability-semantics.md`
- `docs/security/trust-boundaries.md`
- `docs/proposals/cryptography-and-key-management-proposal.md`
- `docs/proposals/volume-encryption-proposal.md`
- `docs/proposals/storage-and-naming-proposal.md`
- `docs/proposals/cloud-deployment-proposal.md`
- `docs/proposals/contributor-quest-mechanics-proposal.md`
- `docs/proposals/llm-and-agent-proposal.md`
- `docs/proposals/hosted-agent-swarm-proposal.md`
- `docs/proposals/capos-repo-harness-engineering-proposal.md`
- `docs/research/game-mechanics-prior-art.md`
- `docs/research/plan9-inferno.md`
- `docs/research/hosted-agent-harnesses.md`
- `docs/backlog/aurelian-frontier.md`
- `docs/backlog/hardware-boot-storage.md`
- `schema/capos.capnp`
- `system-adventure.cue`
- `tools/qemu-shell-smoke.sh`
- `demos/adventure-client/src/main.rs`
- `demos/adventure-server/src/main.rs`
- `demos/adventure-npc-wanderer/src/main.rs`
- `demos/adventure-npc-shopkeeper/src/main.rs`
- `demos/capos-chat/src/lib.rs`
