Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
9d4f12c5dc Merge ghostlight-verse/mp-playtest-tokens: playtests report tokens per exact model id, no family price table; atlas stops on a token cap (cut-mp-playtest-tokens-not-families r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 18:00:29 +01:00
Meta Vens
d40fbbb3d4 Merge ghostlight-verse/mp-lane-models: lane models come only from deploy config; the six lane env vars are required (cut-mp-lane-models-deploy-config r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 18:00:08 +01:00
Meta Vens
c23a710a15 Playtest reports tokens per exact model id: delete the family-substring price table, read character and critic models from the lane environment; the atlas cap becomes a token cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:06:04 +01:00
Meta Vens
2a32b9aae8 Dungeon doc: lane models are required deploy config (cut-mp-lane-models-deploy-config)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:06:02 +01:00
Meta Vens
44396a3cdd Lane models are deploy config: six compiled defaults deleted, an unset lane refuses startup by name, recipe requires the six variables (cut-mp-lane-models-deploy-config)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:05:44 +01:00
Meta Vens
fcedfa0411 Test fixtures name lanes by one neutral id; the live connector test reads its ids from env (cut-mp-lane-models-deploy-config)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:05:44 +01:00
Meta Vens
c78d7e58ea Merge ghostlight-verse/civic-name-schema: tool schemas state the kernel's civic-name rule from one bound (cut-civic-name-schema r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:40:25 +01:00
Meta Vens
077bc54c0e Merge ghostlight-verse/dm-gestalt-knobs: the DM's persisted per-timeline knobs (tune, run_world); tuned allowances bind the open window; room left to react; focus outer key in fair_claims (cut-dm-gestalt-knobs r1, reports h1 h2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:31:08 +01:00
Meta Vens
f4c38af728 sidecar schema fixture: regenerate for the civic-name schema
The fixture is the emitter's own output (sdk_inference schema_fixtures test);
the sidecar converter ignores pattern and keeps the description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:25:45 +01:00
Meta Vens
957700574b patch tools: civic-name fields carry the kernel's rule (pattern and words) from one bound
All 17 refusals in the Zyphos atlas run were invalid_civic_name and no schema
stated the rule. Name and NameSet, and the authority-kind, grievance, trait and
office strings inside composites, now emit tool_schema::civic_name, whose
pattern and description derive from CIVIC_NAME_MAX, the same constant
is_civic_name reads. Free-text fields are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:22:51 +01:00
Meta Vens
8ae66796ff tests: the cap and the lanes are followed each on their own
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:17:26 +01:00
Meta Vens
2ef472f1f5 tests: either limit alone changing is followed; only the target nobody could act for is told
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:09:04 +01:00
Meta Vens
2eef1a85be tests: follow the open-window wording and the refused wave's empty node
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:50:14 +01:00
Meta Vens
f97ec46591 ledger: a window follows the allowances the knobs name, keeping its spend; run_world on a node no one can act for says nothing stirred there
RecordingInferencePort::open_following lets a begun ledger take a changed cap and allowances (the verse run's open still refuses them); the Dungeon's windows use it, so a tune never freezes the wave or the sweep at an unchanged revision. A lane held above its allowance is exhausted. A wave also freezes asked-for targets no one could take a turn for, and the next view names them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:48:11 +01:00
Meta Vens
14320d1bdc tests: bands, entries and institutions at their bounds; the view's cost is the wave's own charge; the player's place is listed once
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:37:06 +01:00
Meta Vens
c966ae13d7 tests: the route's wave test puts the Warden in a gatehouse beyond the room and tunes the bands through the DM's own tool
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:40:25 +01:00
Meta Vens
d34a8f6ffa tests: a run_world past the allowance spends nothing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:36:50 +01:00
Meta Vens
b85898ee58 dungeon waves: the fixture's Warden stands at a watched gatehouse, out of the player's room; tests follow the hierarchy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:34:04 +01:00
Meta Vens
33996e874c docs: the DM's knobs have landed; focus is the outer key of fair claims
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:30:02 +01:00
Meta Vens
9c8ff5efba dungeon: the DM's knobs, persisted per timeline in gestalt-knobs.cc; tune and run_world; sweep_sessions and the window env vars are gone
The wave and the run-ahead sweep read bands, depth, node-turn bound, lane allowances and the DM's leased focus from the timeline's knob document; default_knobs, Scale.sweep_sessions, Scale.window and their env vars are deleted. A wave gives no turn to subjects in the player's room, which is react's. Waves are ghostlight.dungeon_wave.v2 and record the allowances, focus and forced nodes they planned under. The DM's view prints the gears and what a node turn has cost by band.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:27:40 +01:00
Meta Vens
59c28830ab gestalt: focus is the outer key of the claim order; plan_wave takes the nodes a driver forces
fair_claims ranks in-focus demand before the rest, untried before tried inside each band, so a tried entry the player looks at no longer waits behind untried demand elsewhere. plan_wave opens each forced node like a focus node, treats it as due whatever its band and runs it ahead of every other node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 13:27:39 +01:00
Meta Vens
d3b0e20629 Merge ghostlight-verse/dungeon-world-waves: a planned, frozen wave after each closed turn; off-screen acts and deferrals in the DM's next view (cut-dungeon-world-waves r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:58:22 +01:00
Meta Vens
738b57bada dungeon waves: tests pin the turn key, the one-view hand-off, the open wave holding the next back, and a wave that never reaches the model
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:50:15 +01:00
Meta Vens
fac31f126b docs: the Dungeon's world waves have landed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:47:42 +01:00
Meta Vens
85365d2aec dungeon waves: the view-before-words check names the opening's own line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:47:34 +01:00
Meta Vens
de80f8a84a dungeon waves: a planned wave after each closed turn, frozen under its turn in waves.cc and finished on restart; the DM's opening view names what moved off-screen and what is due
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:44:06 +01:00
Meta Vens
2732d38c96 wave: reporting helpers (node_reports, deferred_nodes, node_label, acts_since, act_line) move from the verse driver to the wave organ; ControllerRunner::through runs the decision lanes over a window port
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:36:54 +01:00
Meta Vens
ab290dc00d Merge ghostlight-verse/elaboration-focus: sweep claims in-focus demand first, Dungeon run-ahead focuses on the player's place (cut-elaboration-focus r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:29:07 +01:00
Meta Vens
b423a334fc elaboration focus: one owner of a subject's place; pin it and standing_place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:22:14 +01:00
Meta Vens
5e6303f8c4 elaboration focus: the commons is one route from either road, so its deficit joins either focus
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:59:16 +01:00
Meta Vens
eba61af729 elaboration focus: restore the claim-order assertion's expected value
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:57:34 +01:00
Meta Vens
342e76ce78 elaboration focus: the claim-order test reads the kernel's derivation order instead of assuming road order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:56:41 +01:00
Meta Vens
3d403cb1bc elaboration focus: the atlas playtest holds its empty focus across the sweep
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:55:05 +01:00
Meta Vens
da62d027d2 elaboration focus: the multi-line sweep call takes a focus
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:52:59 +01:00
Meta Vens
f75e56d5c7 elaboration focus: the seed sweep keeps its own signature; tests import what they use; target names the focus rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:51:40 +01:00
Meta Vens
02757c8c59 elaboration: a sweep claims demand at the focus places first; Dungeon run-ahead focuses on the player's place
ElaborationRunner::sweep takes a Focus; demand_entries stably partitions
in-focus answers (a focus place, inside one, or one open route from one)
ahead of the rest. Run-ahead builds the focus from the owner's human subject.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:49:04 +01:00
Meta Vens
bd14485164 Merge ghostlight-verse/gestalt-ledger: one spend ledger per window with lane allowances, reserve refuses over-allowance calls, WaveSpend join replaces NodeOutcome.spent, verse_tick.v3 records deferrals (cut-gestalt-ledger r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:43:47 +01:00
Meta Vens
c8919594c6 tests: a node's spend is its own join
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 10:40:13 +01:00
Meta Vens
d846363781 tests: a tick report lists deferred nodes with their reasons
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 10:34:25 +01:00
Meta Vens
0c80f39791 docs: the ledger of the gestalt target has landed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 09:50:01 +01:00
Meta Vens
7c3b278aab ledger: one spend ledger per window with lane allowances; node spend is a join; ticks record deferrals
Call records gain lane and request id (verse_provider_call.v2); a run's ledger
holds allowances and spend by lane (verse_run_ledger.v2). reserve refuses a
call that could pass its lane's allowance before the provider is called, beside
the run cap; the play agent has no lane and is refused at the port. WaveSpend
joins records to a frozen wave by the command id a request id begins with, so
NodeOutcome.spent and the spent closure of run_frozen_cells are deleted. The
verse tick (v3) records what the plan deferred and the report lists deferred
nodes, including the ones an allowance stopped. The Dungeon's run-ahead spends
in a per-timeline calls.cc, one window-<revision> run per post-turn window;
ControllerRunner::elaborator takes the window's port.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 09:50:00 +01:00
Meta Vens
1419b3b2c0 Merge ghostlight-verse/gestalt-wave-driver: verse ticks freeze a planned wave (run_frozen_cells), verse_tick.v2 and verse_run.v2, --depth and --band knobs (cut-gestalt-wave-driver r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:25:18 +01:00
Meta Vens
634d95f31d tests: a stopped wave lists only the nodes it entered 2026-12-03 09:15:08 +01:00
Meta Vens
91296c0863 wave: drop the unread per-node cell count; pin node reports against surviving mutants 2026-12-03 09:12:57 +01:00
Meta Vens
66d76af0b2 docs: the verse driver of the gestalt target has landed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 08:33:34 +01:00
Meta Vens
5fad3e75cb verse tick freezes a planned wave: run_frozen_cells, verse_tick.v2, --depth and --band (cut-gestalt-wave-driver r1)
The verse driver plans with plan_wave over the derived hierarchy instead of one
flat derive_cover; each frozen cell carries its node and distance; the tick and
run records carry the knobs; v1 rows are refused by name. The cell loop moves
into wave.rs as run_frozen_cells. The tick report groups acts and refusals by
node.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 08:33:34 +01:00
Meta Vens
5075d93161 Merge ghostlight-verse/closed-voice-digest: an institution's view carries a capped digest of its office-holders, limited to what it is party to (cut-closed-voice-digest r1, report h2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:08:19 +01:00
Meta Vens
1742b24456 controllers: an institution's typed view carries a capped members digest of party state (cut-closed-voice-digest r1)
At most six incumbents of the institution's own offices in the kernel's
opportunity order, each with office, position under its place grants,
commitments to or from the institution, and pressures it sources. A
member's knowledge, opinions and persona material are never read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 07:50:50 +01:00
Meta Vens
db4d1d2e58 Merge ghostlight-verse/gestalt-planner: plan_wave with standing knobs, focus distance bands, fictional-minute clock, per-node covers (cut-gestalt-planner r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:34:42 +01:00
Meta Vens
07722ab396 wave: pin the rest band, the no-focus depth and AgencyGraph::restricted against surviving mutants
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 07:24:09 +01:00
Meta Vens
31c36a37b7 wave: plan_wave, GestaltKnobs, Focus, AgencyGraph::restricted; grouped silent members stamp attended (cut-gestalt-planner r1)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 06:48:57 +01:00
Meta Vens
40a28c0b69 Merge ghostlight-verse/multiresolution-gestalt-map: the multiresolution Gestalt target doc (docs/targets/multiresolution-gestalt.md)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 06:40:20 +01:00
Meta Vens
7ff90c7cbd Merge ghostlight-verse/gestalt-hierarchy: derive_hierarchy (institutions first, places as fallback), focus_path, kernel-only door (cut-gestalt-hierarchy r1, report h1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 06:40:20 +01:00
Meta Vens
3f7b2a0a68 hierarchy: drop the unread Display for NodeId; pin a tail that leads into a broken cycle
Mutation pass: replacing == with != in the cycle walk survived; the new
test kills it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 06:32:40 +01:00
Meta Vens
495da6b87d Merge ghostlight-verse/prompt-caching: per-lane cache_retention (play Long, loops Short, one-shots uncached), stable append-only prefixes (connector-v4 report h2; follow-up connector-prompt-caching-zero)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 06:20:28 +01:00
Meta Vens
ded2ede38e Set cache_retention per lane: Long for the play loop, Short for unattended tool loops, none for single-round prose
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 06:14:00 +01:00
Meta Vens
9563694045 Derive the gestalt hierarchy from world state, exposed only on WorldMailbox
derive_hierarchy reads selection, authority grants, positions and place
containment; institutions before places, one home per subject, cycles
broken at the lowest id. NodeId shares cover.rs's id recipe.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 06:12:46 +01:00
Meta Vens
30a574d7aa Merge ghostlight-verse/zyphos-atlas-run: elaboration-only atlas mode for the playtest harness (playtest-harness report h3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 06:05:18 +01:00
Meta Vens
d4d6421693 playtest atlas: attribute an entry to the lenses whose requests just ended, and keep a persona's split memories whole
The Zyphos runs named four to seven lenses per entry; the ten-second window spanned a
whole sweep. Lenses now come from request-end times read once a second, and a persona
memory that a semicolon split is rejoined instead of printed as unread.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:58:36 +01:00
Meta Vens
ff89da5db0 playtest atlas: follow state changes, regards, persona material and pressures in the timeline
The first Zyphos run committed thirteen sweeps of patches that added no place, subject,
fact or commitment; the timeline recorded none of it. Each new state of a subject's
holdings, dependencies, authority and offices, and each new regard, persona material and
pressure, is now a followed entry first seen in the sweep that produced it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:44:03 +01:00
Meta Vens
fc36079b18 playtest atlas: re-ask Begin to seed the same key when a seed authors no one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:31:34 +01:00
Meta Vens
5686b25816 playtest atlas: group people by commitments too, read no lens for Begin's seed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:25:26 +01:00
Meta Vens
5cb928e39f playtest atlas: route the lanes' logged faults to the run log
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:11:40 +01:00
Meta Vens
3cb7f2cb0a playtest: keep the atlas module a flat sibling file; api tests read every src entry as a file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:05:16 +01:00
Meta Vens
3e95b48d09 Merge ghostlight-verse/dungeon-consequences: attack/threaten/accuse verbs, witnessing as Seen knowledge, the DM's Open grievances view, revenge obligations (cut-dungeon-consequences r1, report h1; the watch does not yet come, Gestalt seam recorded)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 05:04:04 +01:00
Meta Vens
bce498a848 playtest: elaboration-only atlas run (sweeps over the whole world, no player) and a Markdown world atlas from the omniscient view
open_harness factors the state, counting port and sessions both runs stand on; the
atlas module seeds one world through Begin at parameterised scale, sweeps the Active
elaborator breadth-first at a concurrency ceiling and a cost cap, and renders places,
institutions, people, populations, facts and commitments with the sweep, lens and
vault notes each entry came from. scripts/playtest-yggdrasil.sh --atlas launches it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 05:03:07 +01:00
Meta Vens
846c41dd09 Open grievances: a prejudice is not a wrong 2026-12-03 05:01:16 +01:00
Meta Vens
98f5214010 Merge ghostlight-verse/playtest-godmoder: godmoder temperament and a blind claim judge reporting yes-and vs godmode acceptance rates (playtest-harness report h2; ruling dm-yes-and-is-legitimate)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 04:47:39 +01:00
Meta Vens
9e6fcd6bc5 Open grievances: name a subject once 2026-12-03 04:40:12 +01:00
Meta Vens
cff9e78a46 Open grievances: kernel-side tests of the derived block; institutions hold no sword; Begin declares the verbs 2026-12-03 04:38:11 +01:00
Meta Vens
106403cf6d playtest: godmoder temperament, sidecar claims, model-judged acceptance rates in report.md
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 04:30:17 +01:00
Meta Vens
da967fa597 verbs: record the Gestalt seam and the verbs not declared 2026-12-03 04:08:39 +01:00
Meta Vens
fc98772760 verbs tests: read the route id from the table view 2026-12-03 04:04:37 +01:00
Meta Vens
9e8600460e Dungeon verbs: attack, threaten and accuse are declared at Begin; the table view derives open grievances
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 04:01:26 +01:00
Meta Vens
06b9520b4d Merge ghostlight-verse/dungeon-attitude-state: regard as sourced modifiers with derived opinion, trait-gated prejudice, AdjustAttitude/DeclareAttitude/DeclareTrait, opinion in DM, Persona and narrator views (cut-dungeon-attitude-state r1, report h1; mutation pass pending)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 03:53:27 +01:00
Meta Vens
6116158534 Attitude: schema validator reads signed integers; catalog counts include the three attitude tools
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 03:14:16 +01:00
Meta Vens
174ecfef20 Dungeon: the table may record regard; seeds are told prejudice exists
PLAY_TOOLS gains adjust_attitude, declare_attitude and declare_trait, with one
line saying what they record. The seed and elaboration instructions name the
trait and prejudice vocabulary as something a person can carry. The ontology
document states the Attitude and Trait components and the three operations.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 03:12:24 +01:00
Meta Vens
c87676c4a1 Attitude: opinion modifiers with causes are typed kernel state; prejudice reads what the holder knows
A holder's regard for another subject is now a sum of sourced modifiers (a
subject or a trait, a bounded delta, a cause of Prejudice, Grievance, Favor or
Rumour, a stamp, an optional fade), never a stored opinion. attitude::opinion
derives it, and a trait prejudice reaches a subject only while the holder knows,
at Believed or better, a fact the world declared as evidence of the trait.

The reducer is the only writer, through AdjustAttitude (a deed, whose cause is
named for the command; also an affordance effect with the regarded party fixed
to the actor), DeclareAttitude (prejudice or rumour without a deed) and
DeclareTrait. State is additive and absent when empty, so existing worlds keep
their digests and the schema tag does not move. The derived opinion rides every
subject's snapshot; the table view the Dungeon Master reads, a Persona's own
view and the narrator's account of who stands with the player all word that one
reading and its causes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 03:12:24 +01:00
Meta Vens
09bd3f94ae Merge ghostlight-verse/aetheria-seed-fix: seeds hold a shared-pool permit and retry capacity refusals; typed faults keep their reason (seeded-begin report h4, found by the 2026-12-03 playtest)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:37:47 +01:00
Meta Vens
964be6db44 api test: a failed seed reads the fault's own fixed words
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 02:30:12 +01:00
Meta Vens
e9612e4305 Restore the catalog field in the panicking-seed fixture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 02:28:05 +01:00
Meta Vens
eeb6bd3f7c Fix seed test fixtures for the pooled seed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 02:26:20 +01:00
Meta Vens
d0aafa974d Seed sessions hold a permit of the shared inference pool, wait out a connector at capacity, and fail with the fault's own words
Eight concurrent seeded Begins sent eight seed requests beside a pool sized to the connector's per-caller quota of four; the surplus was refused as over capacity and every refusal read as 'could not reach the model'. The seed request is ~90 KB, not near any bound.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 02:24:36 +01:00
Meta Vens
9f22513b83 Merge ghostlight-verse/dungeon-playtest-harness: unattended playtest runner, model critic and per-world reports (cut-dungeon-playtest-harness r1, report h1; ruling dungeon-playtest-harness)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:07:22 +01:00
Meta Vens
d47b241939 Merge ghostlight-verse/gestalt-room: react covers the player's room by default, handle-keyed Gestalt sections, non-Personas routed not run (cut-gestalt-room r1, report h1; rulings multiresolution-gestalt, gestalt-dungeon-trigger-answer)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:57:32 +01:00
Meta Vens
cdffad484a Pin react's room derivation, empty-room result, handle split and co_located in each owning crate
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 01:42:21 +01:00
Meta Vens
923b14b538 Update the react one-call test to the handle header 2026-12-03 01:23:59 +01:00
Meta Vens
e8b545c518 react derives the player's room, keys Gestalt sections by handle, routes non-Persona subjects
WorldSnapshot::co_located is the owner's room query; react with no subjects
reacts co_located(player) minus the turn's dispatched subjects, the derived
list recorded so a resume keeps it. The Gestalt call's headers carry the
unique handle (handle_for moves to the library beside id_text), a duplicate
is refused, a non-Persona onlooker is named as routed and not run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 01:23:42 +01:00
Meta Vens
539441196c Multiresolution Gestalt target: invariants, identity and authority table, authority map, cut sequence
Imagination pass gestalt-map (weksa-self-20261202). Cut specs, questions,
research and rejected ideas are admitted in the Weksa mind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:14:55 +01:00
Meta Vens
c6df934093 Merge ghostlight-verse/dungeon-recipe-odin-rudp: the recipe declares GHOSTLIGHT_ODIN_RUDP (ops-google-sign-in report h1 blocker)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:08:22 +01:00
Meta Vens
ddcb777d92 Merge ghostlight-verse/dungeon-npc-voice: NPCs answer in their own voices (dispatch says what a Persona turn is for, replies committed before end_turn, react tool for the room's Gestalt round, narrator sees the player's turn), storyteller prose, DM on Opus and Personas on Sonnet (deru-page report h4; rulings dungeon-dm-owns-the-gears, dungeon-models-dm-opus)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:08:21 +01:00
Meta Vens
ffe97ba67f recipe: declare GHOSTLIGHT_ODIN_RUDP, which the daemon requires for runtime presence
The 93da896 recipe omits it, so Idunn refuses a binding that sets it and the
daemon exits at start ('GHOSTLIGHT_ODIN_RUDP is required for runtime presence').

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 01:05:54 +01:00
Meta Vens
b0c3a699aa Tests: react runs the room in one call; the narrator is handed the player's turn and no cost or permission menu
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 01:04:55 +01:00
Meta Vens
d2c91cac36 Test call carries the grouped flag
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:53:39 +01:00
Meta Vens
47811b0928 Narrator context: wrap list fields as arrays
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:52:45 +01:00
Meta Vens
8cbd41860d NPC voices reach the player: the DM is told what a Persona turn is for and that its prose is a draft until committed, a react tool runs one Gestalt call for the room's onlookers, the narrator is told a story from facts and given the player's own turn
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:51:31 +01:00
Meta Vens
43d76f6ffe Lane defaults: the DM runs on Opus, Personas on Sonnet (dungeon-models-dm-opus)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:51:28 +01:00
Meta Vens
93da896890 Merge ghostlight-verse/dungeon-deru-page: Ghostlight Dungeon for Deru (phone page, turn history, Dungeon-owned accounts with Google sign-in via Heimdall, vault-seeded Begin with era and lens, places and routes, play gated on Ready, run-ahead elaboration, second-person narrator); cuts dungeon-host-return, dungeon-seeded-begin, dungeon-deru-page, dungeon-google-sign-in, dungeon-era-at-begin; Soul verdicts on host-return s1 s2, seeded-begin s1, connector-v4 s1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:35:37 +01:00
Meta Vens
5949034ee1 Merge ghostlight-verse/dungeon-runahead-fix: run-ahead elaboration commits (standing structure in the prompt, per-attempt round budget, fair claim order, loud failures) (seeded-begin report h2; Soul s1 runahead-wedges-and-starves)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	crates/ghostlight/src/elaboration.rs
2026-12-03 00:32:50 +01:00
Meta Vens
2bee6fb82a Spawn test: the hall's people carry a goal so the seed qualifies them
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:24:54 +01:00
Meta Vens
d07ddf1725 Spawn test: report the seed's failure instead of timing out
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:23:36 +01:00
Meta Vens
8c4bffdbba Begin spawn test reads the player's place through WorldSnapshot::standing_place
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:21:31 +01:00
Meta Vens
bef3245e65 The player's narration is a storyteller prompt in second person, not the Persona Projector's lived stream
PersonaLane::narrate ran the Projector prompt, which renders one lived
stream in the person's own present: the framing a Persona is then asked to
be. The model followed it into first person. The narrator now has its own
prompt and context: place, who is present, open exits and where they lead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:19:56 +01:00
Meta Vens
7ec51de6ed Begin stands the player among the most populated seeded place; the seed brief asks for routes between its places
Genesis puts the human at the commons, which no seed populates, so every
seeded turn opened in an empty room. Until the spawn and destination cut,
SeedPort moves the human to the seeded place holding the most people (ties
to label, then id) through a declared route the same patch closes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:19:56 +01:00
Meta Vens
2f6cc52412 Tests: an abandoned row cut short of the repair limit is not a valid ending
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:14:11 +01:00
Meta Vens
373b5f35a3 Playtest launcher: the build container gets the git safe.directory and machine-id the verify jobs get, and keeps its build log 2026-12-03 00:09:48 +01:00
Meta Vens
56d955690b Playtest launcher: build the test binary once on Yggdrasil, run it detached under a transient unit with the connector key; turns, worlds and wall time are arguments
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:04:07 +01:00
Meta Vens
25749edb78 Dungeon playtest harness: AI characters play the Dungeon's own API in parallel worlds; transcripts, elaboration logs, model-critic flags, per-world reports
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 00:02:18 +01:00
Meta Vens
d3b904bd41 Tests: the abandonment test holds its store
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:59:23 +01:00
Meta Vens
1fcd68f9c6 Dungeon tests: CountingPort keeps usage per model and app_over's AppState assembly move to one test-support module
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:58:56 +01:00
Meta Vens
b31f1e551d Tests: the promise prompt, abandoned rows' integrity in both lanes, sweep report counts, repair budget end
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:58:16 +01:00
Meta Vens
9a6a1e8c73 Begin page: lens rows were nested one array too deep; probe screenshots at 360 px for the era picker and lens steppers
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:46:08 +01:00
Meta Vens
13e8c82059 Era tests: escaped newlines, no link into withheld lore in the fixture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:42:03 +01:00
Meta Vens
d646d59c46 Dungeon: Begin takes era and lens weights, evidence follows the world's era, /api/vaults lists eras and lenses, the page asks for both
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:38:09 +01:00
Meta Vens
94c1362b5e Era at genesis: WorldEra pinned write-once on CreateWorld, WorldSnapshot::guidance() read by every prompt lane, vault era tables with withheld lore
The kernel owns a world's era as genesis-only state (no CommandBody carries
one); every lane's domain guidance is guidance() (era line, then the brief).
Each production vault declares its eras and default in vault.rs;
VaultEvidenceSource::from_snapshot takes withheld paths. Seam with the
elaboration library: render_brief now renders guidance(), and
EvidenceQuery.referents is pub so the Dungeon's tests can query evidence.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:38:09 +01:00
Meta Vens
bc26c1116b Merge ghostlight-verse/dungeon-begin-fix: places in the seed, play gated on Ready, persisted timeline status (seeded-begin report h3; Soul s1 findings seed-authors-no-places, draft-plays-and-reads-ready, survivors-guard-paths)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:28:46 +01:00
Meta Vens
abecfcf0f0 Test name: no policy spelling left in the Dungeon
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:18:38 +01:00
Meta Vens
8d4f9ed3bb fix test borrow 2026-12-02 23:16:42 +01:00
Meta Vens
ce90413870 Dungeon sign-in: the invite is presented at begin, grants Heimdall's first login, and is redeemed at complete; the Discord role policy goes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 23:13:56 +01:00
Meta Vens
c9a5ce3d29 Elaboration: a missing-structure prompt names the promise, its holder, its counterparty and what answers it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:46:20 +01:00
Meta Vens
66cc6509ea Elaboration: log each refusal's sites and each sweep's report
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:41:28 +01:00
Meta Vens
2ac36ddc68 Elaboration: a clean patch that leaves its boundary standing is a refusal with what the answer needs, not a failed session
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:33:32 +01:00
Meta Vens
2c17cf8fa3 Elaboration: a session ended by its last refusal is a valid NoPatch row
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:27:05 +01:00
Meta Vens
9a5a4f1ee5 Dungeon: the play refusal's text is pinned for seeding and failed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:25:19 +01:00
Meta Vens
cdf43237fc Elaboration: the ending refusal's progression belongs to each lane's own checkpoint
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:25:10 +01:00
Meta Vens
7c63ec2829 Elaboration: a refusal that ends a session is a legal progression; tests follow the prompt's new structure
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:24:00 +01:00
Meta Vens
00e3467ed7 Tests: a repair has a fresh round budget, a refused entry yields to untried ones, a refused session is abandoned
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:20:31 +01:00
Meta Vens
986ff92d24 Page probe screenshots: history after reload, older page on scroll-up, second browser profile with the same account (360 px), and the refreshed play set
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:18:16 +01:00
Meta Vens
1bd9578489 Live seeded-Begin check: count only authored places, report who stands where
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:14:10 +01:00
Meta Vens
2d0eafd236 Dungeon: pin evidence_of and the snapshot-id gate
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:10:32 +01:00
Meta Vens
c23e5fd046 Dungeon: seed status is persisted with the timeline, play refuses a world that is not Active, the seed asks for places
The in-memory Seeding map is cut: the catalog row owns SeedStatus. A seed
still Seeding at startup reads Failed; a panicking seed task ends Failed.
POST /api/play on a Seeding, Failed or Draft world is a 409 naming the
status. The seed brief asks for three to five declared places.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:10:31 +01:00
Meta Vens
bc85d70f91 Elaboration: per-attempt round budget, bounded repairs, world structure in the prompt, fair claim order, sweep report
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 22:09:07 +01:00
Meta Vens
9684001600 Page: the scrollback is the server's turn log, loaded on open and paged on scroll-up; Retry names the entry it retries; the in-visit-only note is gone
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 21:59:44 +01:00
Meta Vens
91cfe7af92 Turn log file is named from its play store so two tables in one directory do not share it; probe gains a long mode of forty turns
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 21:59:43 +01:00
Meta Vens
1fcef6499d Dungeon: a per-timeline append-only turn log written from the play row, served paged at /api/history/{timeline}; a Retry is a new entry naming the old one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 21:39:45 +01:00
Meta Vens
c58ccbe2de Page probe screenshots at 360 px and 1100 px, taken against the real router over a scripted model 2026-12-02 21:31:09 +01:00
Meta Vens
8d333ff817 Page: classes instead of inline styles (the policy blocks them), compose bar leaves with the play view; a test pins no inline style 2026-12-02 21:28:49 +01:00
Meta Vens
e0c466094d Page: spacing for the echoed lines; shoot script scrolls play views to the newest 2026-12-02 21:21:34 +01:00
Meta Vens
4e067a073a Page: place the player's echo before the request, show an answer under its question, scroll after the retry row 2026-12-02 21:09:36 +01:00
Meta Vens
5fa427266a Page: one-row header, slimmer compose bar, scroll to the newest turn; probe screenshots and the CDP script that takes them 2026-12-02 21:07:39 +01:00
Meta Vens
c3e9e2956e Page probe: an ignored test that serves the real router over a scripted model for a browser 2026-12-02 21:03:43 +01:00
Meta Vens
419c5ed082 Dungeon: the Deru play page, the Idunn recipe and a state contract the test derives
- page/: phone-first static page (sign-in with invite and provider buttons, Begin
  top to bottom with vault picker and Seeding state, timelines, turn view with
  stream, draft that survives reconnects, refusal and fault lines with Retry and
  Edit-and-resend), compiled into the binary and served from / under a strict CSP.
- deployment/idunn/recipe.toml: one binary, the dungeon crate only; no Eve, mesh,
  CodexConnector or web steps. The connector key arrives as the binding's secret
  file GHOSTLIGHT_CONNECTOR_KEY_FILE (a systemd credential Idunn loads); the daemon
  reads only that path.
- idunn_health: generation dungeon-v1, STATE_CONTRACT_SHA256 recomputed (checked
  against Idunn's canonical_state_contract_sha256 on the same recipe); the recipe
  drift test is restored and derives the recipe text and digest from one typed
  slot table whose schemas come from the code that owns them.
- /cultnet/snapshot answers 404 to anything carrying a proxy header or a
  non-loopback peer: nginx forwards from loopback, so the peer address alone
  admitted the internet.
- /api/me names the providers the daemon offers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 21:02:38 +01:00
Meta Vens
92fcb70aa6 Library test: release the runner before the world owner is awaited
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:41:52 +01:00
Meta Vens
0dd4787ae3 Live seeded-Begin check (ignored): real connector, imported snapshot, counted calls and usage
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:20:49 +01:00
Meta Vens
35085e6701 Library test: a sweep starts no more sessions than its bound
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:19:32 +01:00
Meta Vens
d3e4c3e82c Seeded Begin tests: one deferred app per api outcome, the brief outranks the premise
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:18:19 +01:00
Meta Vens
f04de5e9a0 Seeded Begin tests: read a request through its serialization
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:16:47 +01:00
Meta Vens
b71db89f68 Seeded Begin: vault scale intent, background seed with timeline status, run-ahead sweep, SnapshotVaults and the import-vault command
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:15:17 +01:00
Meta Vens
51363eaccf Library: production vault profiles in one table, recorded current import and premise on the snapshot, elaborator takes its evidence, sweep takes a session bound
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:10:30 +01:00
Meta Vens
efed95d694 Connector renewal test: build the prepared invocation directly
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:08:53 +01:00
Meta Vens
1b178d2d43 Connector port: an invocation past its expiry is renewed under a new request id, so a retry after a timeout is not refused Expired
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:08:40 +01:00
Meta Vens
47b174844a Merge origin/main (cut 0 connector v4, cut 1a vault snapshots) into the seeded-Begin branch; the dungeon crate moves to model-connector types and drops codex-connector
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 20:04:35 +01:00
Meta Vens
cb1f213b36 Merge ghostlight-verse/dungeon-vault-snapshot: content-addressed vault snapshots, per-vault profiles (Zyphos rooted at Eusocial Interbeing; spoilers, design and agent files excluded), CRLF-stable ids, race-safe import (cut-dungeon-vault-snapshot r1, reports h1 h2, Soul s1 findings fixed in h2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 20:00:46 +01:00
Meta Vens
03fb33fb93 vault: relative_dir drops the redundant is_absolute arm; test an import that cannot publish
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:55:23 +01:00
Meta Vens
1a990a09fd Auth surface: kill the surviving mutants on token expiry, store custody, body limit, fatal signalling and the pointer move
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:36:51 +01:00
Meta Vens
f3ee217921 Merge ghostlight-verse/dungeon-connector-v4: connector lane speaks model-connector v4, codex-connector deleted, typed faults and usage (cut-dungeon-connector-v4 r1, report h1, Soul s1: no blockers; follow-ups connector-reasoning-state-replay, connector-collision-and-usage-lows)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 19:16:05 +01:00
Meta Vens
1e90d4a4c4 Catalog: pin the invite token hash, redemption, expiry instant and pruning by behaviour
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:14:30 +01:00
Meta Vens
4d1e4859f4 Dungeon lanes: Opus for the narrator and Personas, Sonnet for play, elaborator and seed, Haiku for the interpreter
Per ruling dungeon-model-per-role-answer (opus-voice); each lane still reads its own env override.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:13:27 +01:00
Meta Vens
783fd8a288 Dungeon sign-in: a begin cookie binds the attempt to its browser, the provider is a parameter, the auth routes are throttled
complete must present the HttpOnly begin cookie matching the handle, once, before
expiry (the OAuth state/PKCE binding). begin takes a provider from
GHOSTLIGHT_AUTH_PROVIDERS; the Discord role policy rides Discord only. The
session plays as the principal sign_in returns, refusing a mismatch. Heimdall
error text no longer reaches the caller. HeimdallPort lets handlers be tested
against a scripted Heimdall.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:11:59 +01:00
Meta Vens
920bb3d289 Dungeon: invites are minted on a 0600 Unix socket; the HTTP router has no invite path
The peer-loopback gate on /admin/invite was open behind nginx, where every
request has a loopback peer. The mint moves to invite.rs: a socket under the
state root, and 'ghostlight-dungeon invite --state-root PATH HOURS' asks it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:04:01 +01:00
Meta Vens
b1a2d05976 vault tests: scope refusals and trimmed names
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:03:17 +01:00
Meta Vens
48f24f94df vault import: unique temp name, poisoned entries replaced, load copies instead of opening the store
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:01:52 +01:00
Meta Vens
a5ddfb9d76 vault: file and glob excludes, machinery files never lore, CRLF folded before hashing, backslash patterns refused
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 19:00:02 +01:00
Meta Vens
7670d02a6c Pin the prose-shape gate and the trace render against mutation survivors
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:44:12 +01:00
Meta Vens
3fc3110edb Smoke note: the connector is claude-connector v4 with a systemd-credential key; the sidecar no longer owns claude-prefixed models by default
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:25:06 +01:00
Meta Vens
569794fda9 Ignored live check: Ghostlight's own connector port completes plain, tool and schema requests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:11:58 +01:00
Meta Vens
588b0cca8f Dungeon: prune lock, seed test states the no-target truth
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:10:44 +01:00
Meta Vens
12f4f17ccf Connector lane speaks model-connector v4: delete codex-connector and its v2 port, typed refusals, failures and usage, controller_work.v19
The v2 CodexConnectorInferencePort and the codex-connector dependency are
deleted. ConnectorInferencePort speaks model-connector v4 to claude-connector,
maps every Refusal and FailureKind to a typed InferenceFaultClass and reports
Usage as TokenUsage. The SDK prefix claims a model only when the sidecar is
configured, and open_inference refuses a sidecar that would take a connector
model.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:08:55 +01:00
Meta Vens
7327afc0c2 Dungeon: fix auth body and refresh test imports
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:07:20 +01:00
Meta Vens
6575635237 Dungeon host returns without Eve: catalog, timelines, Begin, Deru API, accounts by invite
Restores play.rs, heimdall.rs, app_session.rs, idunn_health.rs, build.rs from parked/ghostlight-eve-surface; new catalog, timelines, begin, api, runtime, session_refresh, state_layout modules. Eve card tests read the turn-view JSON.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 18:05:10 +01:00
Meta Vens
6df910a925 vault smoke: add the Avatar vault 2026-12-02 18:01:27 +01:00
Meta Vens
ddab6c93bd vault import: remove the store's lock sidecar 2026-12-02 17:58:57 +01:00
Meta Vens
4f53151e3d vault test: name the files an import leaves 2026-12-02 17:55:36 +01:00
Meta Vens
75fdd958aa Vault import is a deterministic, re-runnable snapshot; retrieval reads only snapshots
VaultSnapshot::build is the only reader of a vault directory. VaultEvidenceSource::open and the per-query walk are deleted; from_snapshot replaces them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-02 17:53:06 +01:00
Meta Vens
c43eb54962 Merge ghostlight-verse/dungeon-eve-quarantine: the Dungeon's Eve surface, web host and daemon are parked at parked/ghostlight-eve-surface until Thing 2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:11:58 +02:00
Meta Vens
2b9143d303 README: drop the browser JSON boundary
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 00:10:55 +02:00
Meta Vens
f21b5ff1aa Docs: smoke note, AGENTS and README state the braked-and-stopped truth
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 00:10:45 +02:00
Meta Vens
fec39c2010 Docs: handoff, smoke note, AGENTS and README state the parked, braked-and-stopped truth
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 00:10:17 +02:00
Meta Vens
0e9def0ebc Verse map: name the Eve submodule without a path the tree no longer has
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 00:00:05 +02:00
Meta Vens
ef11427e24 Docs and comments: README leads with the kernel and says the Dungeon is parked at the tag; AGENTS, status lines, kernel comments
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 23:56:56 +02:00
Meta Vens
f40bbaac13 Park the Dungeon: delete ghostlight-dungeon, web/, Eve bridge, vendor/eve, recipe and Eve interface doc (tag parked/ghostlight-eve-surface)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 23:54:33 +02:00
Meta Vens
ee62fec98a README: a world's expressiveness is its affordance catalog; a fresh world knows only Speak
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:34:52 +02:00
Meta Vens
eaefed1e7d Merge ghostlight-verse/readme-front-door: the README leads with the kernel and its entry points
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:29:46 +02:00
Meta Vens
56496c7108 README: lead with the kernel, its thesis and entry points; state the dungeon's status and the planned direction
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 19:29:10 +02:00
Meta Vens
aa56736841 Merge ghostlight-verse/narrative-resume-relowers 2026-10-17 20:09:01 +02:00
Meta Vens
f503c85484 Narrative resume: pin the Confirmed arm's identity check; interrupted no longer re-decides the scope move
The kernel's ScopeChanged is the only decider of a moved scope and same_decision the only decider of identity. Deletes interrupted's fresh-vs-row digest compare; adds a mismatch test and an unmoved-scope test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 19:44:35 +02:00
Meta Vens
e0344ff5af A resumed narrative row names its decision only; the kernel refuses a moved scope and the same prose re-lowers once
Deletes row_answers_caller and both awaits_world methods; run_narrative
compares only same_decision. classify labels OpportunityMismatch as
OpportunityGone. selection_refusal owns the grouped selection label and is
pinned for ScopeChanged and LeftBeforeSelection arms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 18:47:13 +02:00
Meta Vens
e2924bbc50 ghostlight-verse map: who refuses a resumed narrative row whose scope moved (spec narrative-resume-relowers.r1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 18:43:11 +02:00
Meta Vens
73f26a5a32 Merge ghostlight-verse/grouped-scope-moved-label (cut-grouped-scope-moved-label r1, report h1, Soul s1 holds) 2026-10-17 15:55:57 +02:00
Meta Vens
1d75f14578 Grouped lane: a member whose scope moved before selection is ScopeChanged
run_group's blanket Err(_) arm labelled a moved-digest member
LeftBeforeSelection. ScopeMoved now maps to ScopeChanged; the other
selection errors keep LeftBeforeSelection. Label only; spend is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 15:26:40 +02:00
Meta Vens
ee9e18a745 verse map: grouped lane mislabels a moved scope LeftBeforeSelection (no spend difference)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:25:20 +02:00
Meta Vens
771a79dde2 Merge ghostlight-verse/in-flight-gate (fca3ec1) into main
Cut ghostlight-verse:cut_spec:cut-in-flight-gate.r1, report h1, Soul s1 holds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 13:19:44 +02:00
Meta Vens
fca3ec1a3a controllers tests: fresh narrative selects with a moved digest read ScopeMoved
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 12:58:54 +02:00
Meta Vens
e2c3511cbd controllers: one owner for the operational in-flight gate; ScopeMoved from select_scope when only the digest moved
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 12:56:13 +02:00
Meta Vens
824a4dea15 verse map: who refuses an operational in-flight row whose scope moved (probe at 4741d50)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:54:22 +02:00
Meta Vens
4741d50898 create-flow: pin the begun receipt's worldId and step-id key sensitivity; stale comments
Test-only plus comment text. The receipt's worldId is asserted against the
world Begin made; step ids are asserted to differ for keys differing only in
their first byte. Two comments cite BeginPayload, not the deleted
CreatePayload; the ship-verb test comment cites the standing ruling.
Trim mutants of the title, brief and name are equivalent: the kernel trims
title (normalize_title), brief (prepare_creation) and the subject label
(mailbox declare) itself.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 18:28:09 +02:00
Meta Vens
f90d408466 Merge ghostlight-verse/create-flow into main
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 18:26:53 +02:00
Meta Vens
9ccc9fd4f2 Begin is the one entry: world.create is gone, the route owns the defaults and how far Begin goes
world.create leaves the dispatch table and operation_schema. world.begin takes
ghostlight.world_begin.v1 (title, brief, subject_label; unknown fields refused);
begin_intent decides targets, roots, labels and lens weights, begin_plan decides
the steps, and where a seed vault is configured Begin stops at the approved Draft
so the seed lane stays reachable. The surface authors no constants. Tests that
needed a Draft start from the kernel's own create; the bridge fixture is edited
to match and still needs its Starfire drift run. May not build: first commit of
the batch, unverified.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 17:21:58 +02:00
Meta Vens
dac9686576 Ghostlight verse map: cut sequence of the four cuts withdrawn under map-only-what-runs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:01:04 +02:00
Meta Vens
d1111f4c4f Merge ghostlight-verse/verse-run (cuts verse-run r3, lookup, claim, refusals)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 20:08:04 +02:00
Meta Vens
9308c7d043 verse run: pin the membership guard and the unattributed note by size, position and cell; delete the fold's tool-name cap
membership-guard-pins-degenerate: a three-member cell at positions 0, 1 and 2 with a foreign extra, a duplicate, a missing last and middle member and a short list; the unattributed note recorded at cells 0, 1 and 4.
tool-name-bound-twice: UNATTRIBUTED_TOOL_CAP, its take and its direct-fold test are deleted; the provider contract owns the 64-byte bound.

Not built or run locally; verified on Yggdrasil in the next report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:08:17 +02:00
Meta Vens
9747957649 Verse run test: the stray call is made once, so the tick holds one note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:47:49 +02:00
Meta Vens
fe06efcf26 Controller tests: a call naming no handle refuses the members behind it, and the name kept is capped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:45:58 +02:00
Meta Vens
b3699908f7 Verse run tests: a group at a later cell, the resumed row's disagreement, the invariant break, the unattributed note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:43:02 +02:00
Meta Vens
6d84c2b57b Verse run: the controller owns a resumed cell's member set and the driver only copies
A resumed grouped cell refuses each cell member its persisted row lacks as
RowDisagreesWithCell and runs no row member the cell lacks, in the controller's
row-and-cell intersection. The driver's after-the-fact repair branch (a
ScopeMoved relabel of unlisted members) is deleted; a finished cell whose lists
do not match its members now ends the run Failed (cell_membership). A grouped
call that names no handle is carried to the tick as a cell-level note naming
the tool, and the members who finished with no choice behind it are refused
CallUnattributed instead of declining.

Builds the library; the verse::run test module does not compile until the next
commit (TickCheckpoint, absorb and GroupedRun changed shape).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:43:01 +02:00
Meta Vens
03b04011b7 Verse run test: the frozen member a resumed row lacks is refused whether it is the cell's first or second
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:45:12 +02:00
Meta Vens
311c4bfaed Verse run test: the resumed row's second run answers a grouped request
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:27:34 +02:00
Meta Vens
8c6a01f2ad Verse run tests: the refusal paths, the frozen cover's membership on resume, and the undecodable member
Gone members per member and per cell at cells beyond 0, a resumed row smaller and larger than the frozen cell, absorb driven with each grouped mapping, the cell-level refusal of a group, Interrupted, and an undecodable member refused (and declined when it later finishes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:25:47 +02:00
Meta Vens
c3f0e3789c Verse run: the frozen cover owns a tick's membership, and an undecodable grouped member is refused
absorb now folds a cell's whole outcome (result or error) and reconciles a grouped cell against its frozen members: a persisted row's members outside the frozen cell are never listed, a frozen member the row never mentions is refused (ScopeMoved), and a member refreshed away is only its OpportunityGone refusal. A grouped member whose own tool call failed to decode and which never finished is refused (ProposalUndecodable) and no Decline is submitted for it.

Test-only overtaken_narrative_run builds the Interrupted outcome for a driver test. Tests follow in the next commit; the test target does not compile against this commit alone only if tests are built, the library builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:25:46 +02:00
Meta Vens
ef7299b673 Verse run refusal test: the foreign run's number no longer collides with a later claim's ledger
The port opened for "another run" used number 7, which the extra claims now reach. Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:06:55 +02:00
Meta Vens
a501009210 Verse run: the operator log is read before the clock, claim insert and start revision are pinned, refusals are tested both ways
Fixes operator-log-join-untested (run_tick takes the log reader; an unreadable log leaves the tick open with no clock advance), claim-insert-atomicity-unpinned (insert_run extracted, collision test), claim-start-revision-from-stale-snapshot (run_manual refuses a claim whose start_revision is not the world's revision, WorldMovedSinceClaim) and refusals-pinned-one-direction (cap above and below, each config field, revision both ways). Not yet built when committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:05:12 +02:00
Meta Vens
b5b964c234 Verse binary: store-open errors name the flag, never the --state path; a refused start's abandon is pinned
Fixes state-path-echoed-by-store-open-errors (world, call, run and controller-work store opens map to fixed messages, dropping the source chain that carries the path) and start-refused-glue-unpinned (the binary test reads the run record back after a ledger-refused start). Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:05:12 +02:00
Meta Vens
2dabb85009 Verse run: every member of a tick's frozen cover ends committed or refused, by subject
Refusal names its subject. absorb reads GroupedRun.refused (LeftBeforeSelection
-> OpportunityGone, ScopeChanged -> ScopeMoved, WorldRefused -> WorldRejected)
and records an interrupted singleton's member; refreshed returns the frozen
members it found no opportunity for; a cell-level refusal records every member
of the cell. TickReport carries the refused subjects' labels and Display prints
"refused: cell N <label> <reason>". Unbuilt before this verification; no commit
here is known not to build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:36:31 +02:00
Meta Vens
706d0c3792 Verse run: the driver labels a world ScopeChanged refusal ScopeMoved
One fact, one label across lanes (ruling unsent-awaiting-row-is-awaiting).
RefusalReason::ScopeMoved's doc names the unsent-awaiting state. Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:22:22 +02:00
Meta Vens
5f2e629c32 Controller lookup tests: committed declines, never-sent rows, uncertain custody, snapshot loss
Pins the lookup rule's untested halves: a committed NoProposal row is
answered with its receipt after its scope moved (both lanes); a
ReadyToSubmit or NoProposal row that never reached the world ends
World(ScopeChanged) with no provider call in the operational lane and is
lowered once more (one provider call) and committed in the narrative lane;
an in-flight row read in uncertain custody keeps the digest gate (both
lanes); a grouped cell whose world cannot be read at submission is pending
WorldUnavailable with nothing submitted. Fault injection lives in test
fixtures only. Test-only change; builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:22:22 +02:00
Meta Vens
d1883e9973 Verse run: the run store claims a run's sequence before its call ledger opens
next_sequence was a public read followed by a caller-chosen sequence on save,
so a second run could take number 1 and overwrite run 1's record, and a start
refused after its ledger opened bound that cap to the number the next run was
handed. VerseRunStore::claim now allocates and writes the Running record in one
insert-if-absent and returns a non-Clone RunClaim; next_sequence and save are
private and save is update-only. run_manual takes the claim, refuses a port
whose run id or cap is not the claim's, a claim for another world, or a config
other than the claim's, and abandons the claim as Failed in each case. The
binary claims before opening the ledger and abandons a start it cannot make.
Fixes old-sequence-overwrites-record and refused-start-binds-cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:47:52 +02:00
Meta Vens
92275cbe7c Verse run: an operator log that cannot be read ends the run after the tick's checkpoint
The tick's acts came from operator_log().map(..).unwrap_or_default(), so a
failed read reported a tick of no acts. acts_since returns None for an
unreadable log and run_tick ends the run Failed(operator_log_unavailable) with
the checkpoint as it stood. Fixes operator-log-error-swallowed. Seam test:
the log cannot be made to fail through the kernel's doors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:47:18 +02:00
Meta Vens
2a888da955 Verse command: a lane that cannot open names the flag or fault kind, never the endpoint
open_inference's error was wrapped with .context and printed through the
anyhow chain, so a refused non-loopback --base-url put the operator's address
on stderr. lane_fault maps each ControllerOpenError variant to one fixed
message; ControllerOpenError is exported for it. Fixes
local-endpoint-echoed. Builds; the workspace is unchanged elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:46:47 +02:00
Meta Vens
5cf005eb2c Pin the tick ordinal edges and the racing open
Lifts Soul's p8 (closed tick at the current ordinal refused before any cell)
and p9 (a 45-minute external advance moves the ordinal) into tests, and a
racing-open test for the create-only open. Fixes s2 ordinal-edges-unpinned.
Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:19:43 +02:00
Meta Vens
b5dc76dd75 VerseRunStore: tick writers are private to the driver, open_tick is the store's insert-if-absent
open_tick, close_tick and close_ticks_before lose `pub`: run_tick through
open_or_find is the only caller, and a compile_fail doctest pins that an
exported-type holder cannot call them. open_tick uses
OwnedRedbMessagePackBackingStore::insert_entry_if_absent in one write
transaction instead of read-then-push, so two opens of one ordinal cannot both
succeed. Fixes s2 tick-rows-have-a-public-writer and open-tick-is-check-then-put.
Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:19:42 +02:00
Meta Vens
61042670d1 Test: a third subject speaks so the custody-uncertain fixture's scopes all move
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:51:44 +02:00
Meta Vens
cb1be44f92 Test: the custody-uncertain fixture binds the narrative subject as the world holds it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:43:23 +02:00
Meta Vens
9bf7932573 Tests: custody-uncertain rows, narrative in-flight gate, and committed cells answered in either order
The run-level order-reversed case now commits both cells through another
driver, each one's act having moved the other's scope, in either order; the
resuming run answers both with their receipts. Not built before this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:35:43 +02:00
Meta Vens
db12c26b31 Test: the committed cell is answered; the in-flight cell sharing its room is refused before inference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:07:06 +02:00
Meta Vens
2b495e1f33 Test: soul_b refused-constituent test reads the typed refusal, not needs text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:05:34 +02:00
Meta Vens
adb8cbff2b Test: a committed cell is answered whichever cell the resume reaches first
The cell that acted is second in the frozen order; the first is in flight when
the run ends. Closes the order dependence budget_exhausted_stops_before_the_clock_and_resumes
only passed around.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:57:38 +02:00
Meta Vens
158e8f9f3d Controller lookup-first: a committed row answers by command id; grouped refusals typed; exercises in attention order
A row that carries its submission body is resumed whatever the caller's scope
digest (the world answers it by command id); a row still in flight keeps the
digest gate. World and scope must always match. GroupedRun.refused names each
constituent that did not commit (LeftBeforeSelection, ScopeChanged,
WorldRefused); needs keeps decode problems only. A group submits declines
first, then exercises in the world's attention order read once.

Not verified at this commit (written before the first build).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:55:46 +02:00
Meta Vens
278033b90e Verse run test: a refreshed member is bound to its own subject's opportunity
Kills the cargo-mutants survivor on the subject match in refreshed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:45:24 +02:00
Meta Vens
be7d9eec75 Verse run test: a resumed tick runs its frozen cells in order and answers the finished one from its row
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:14:25 +02:00
Meta Vens
5277973afb Verse run: a tick is (world, clock-advance ordinal), its span and cells frozen in a tick document
The tick index is the world's TimeAdvanced count, read through a driver-only
mailbox door, and derive_cover takes it instead of now and the span. A tick
document ghostlight.verse_tick.v1 is written before the first cell and read by
any later run, so a resume under another span or cover budget finishes the open
tick as it was opened. The clock id is clock_command_id(world, ordinal) and is
pinned by a test. TickIndex::of and run_tick's per-call derive_cover are gone.

Fixes findings resume-rederives-tick-identity, tick-identity-collides-across-spans,
clock-id-unpinned. Not yet built or run at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:11:07 +02:00
Meta Vens
06a8373fbd Verse run test: a resumed tick reports only the acts the resuming run committed
Pins the operator-log cut at the tick's start revision against the act the
interrupted run left at that very revision. Builds; the mutation pass named it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:08:52 +02:00
Meta Vens
06e30dc921 Verse binary tests: a failed run exits nonzero, and zero counts are refused
Pins the exit status of a Failed run against a provider that refuses every call,
and the positive-integer guard for ticks and token cap. Builds; the earlier
mutation pass named these as survivors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 09:14:07 +02:00
Meta Vens
097bf02f1e Verse run: the open tick is recorded unclosed, and a resumed cell whose scope moved is its own refusal
A run that ends inside a tick (budget, pending cell, failed clock) now keeps
that tick's checkpoint with closed false, so what its cells committed is not
lost. A cell that committed before an interruption meets a moved scope
digest when the tick resumes and is refused as ScopeMoved; nothing commits
twice. Removes the temporary diagnostic. Builds; not yet re-verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 09:08:02 +02:00
Meta Vens
fc3f9fd668 diag (temporary) 2026-10-11 09:04:52 +02:00
Meta Vens
cef6436971 Verse run test: the resumed tick closes with the one cell the first run left
The faction that acted holds no opportunity until the clock moves, so the open
tick re-derives with one cell. Builds and passes except this assertion, which
this commit corrects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 09:01:01 +02:00
Meta Vens
2daa80e159 Verse run: the manual tick driver, its run record and the ghostlight-verse command
run_manual advances the verse world tick by tick under the recording port's
token cap: snapshot, opportunities and agency graph from the mailbox,
derive_cover, each cell on its members' current opportunities, one clock
advance, a checkpoint in ghostlight.verse_run.v1. A tick that cannot finish
leaves the clock where it was, so a later run re-derives the same cells and
command ids and the kernel answers from its ledger.

WorldMailbox::opportunities is the tick driver's own door beside agency_graph.
OperatorEvent now names the verb, its render path and the bound roles.

Not yet built or tested: this commit is the first write of the pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 08:58:20 +02:00
Meta Vens
4eff650755 Merge ghostlight-verse/verse-genesis: the canonical verse world is created from Aetheria's catalog
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 03:41:21 +02:00
Meta Vens
e854cf3671 Genesis tests: pin the faction Name trim, double genesis, and a ship verb's speech
Pins the trim of a faction Name into its institution label, genesis twice
(same intent: same receipt, nothing changes; another command id:
CreationTargetOccupied), and, as evidence for the open question
ship-acts-are-not-speech, that a phase A ship verb commits only as an
utterance. Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:10:39 +02:00
Meta Vens
8f6b552e7a Verse genesis: the canonical Aetheria world is created from the catalog
CreateVerseWorldIntent lowers to one CreateWorld bound to the catalog's
grammar: a commons, one affordance per non-speak grammar verb (the kernel
supplies speak), and per faction an import-keyed institution granted every
verb plus a canonical fact citing aetheria:<commit>:aetheria.faction/<key>.
WorldMailbox::create_verse sends it through create_authenticated. The role
lowering moves into GrammarVerb::role_specs, which admits_roles now uses.
Also pins the reader's non-string allegiance key and invalid-UTF-8 refusals.
All commits build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 02:33:57 +02:00
Meta Vens
9afbdc879e Merge ghostlight-verse/grammar-reader: Ghostlight reads Aetheria's catalog file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:52:06 +02:00
Meta Vens
42e71d89d5 grammar-reader fix 1: pin the record-key sort with rows spliced out of order
The store re-sorts rows it writes, so the reversed-rows test never reached the
reader unsorted. Both file-shape tests now splice raw snapshot rows. Builds;
test-only change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:29:31 +02:00
Meta Vens
677eb1b3a8 grammar-reader fix 1: the duplicate-faction test splices the second row into the snapshot bytes
The store's writer keeps one row per record key, so the previous test never
held two rows. Builds; the test crate is the only change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:15:31 +02:00
Meta Vens
3eb59068c7 grammar-reader fix 1: canonical keys through the one predicate, duplicate factions refused, bin/ext growth tolerated, guards pinned
The reader mints every faction and allegiance ImportKey and refuses a
non-canonical one as a typed NonCanonicalKey naming record and field (0 or 12);
two faction rows under one record key are DuplicateFaction. Payloads decode
through rmpv so a MessagePack bin or ext cell at a higher key (C# byte[],
DateTime) no longer fails the record. Tests pin the record-key sort and a
non-map Allegiance. Schema-version check (item 2) not done: CultLib gap.
All commits build (not yet run; the suite runs next).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:13:17 +02:00
Meta Vens
b5edc05b1f grammar-reader: pin every referent code (Person and Population arms survived mutation)
The Aetheria-written fixture binds only Faction, Cargo and Place, so mutants
deleting the Person and Population arms survived. The new test authors each
code at the role's key and reads it back as its own kind. Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:14:50 +02:00
Meta Vens
84b8e3d6d5 grammar-reader: read Aetheria's catalog into a GrammarBinding and keyed factions
read_aetheria_catalog opens the catalog read-only, mirrors
aetheria.verse_grammar, aetheria.verse_verb and aetheria.faction by integer
key, and refuses unknown enums, bad verb or role names and a missing grammar
by record key. Fixture written by Aetheria's own fixture writer at master
92b82e9a (provenance beside it). Also the NFD/NFC position sweep for import
keys. Not yet built or run when committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 23:25:47 +02:00
Meta Vens
c3e16a57c2 Merge ghostlight-verse/import-key 2026-10-10 22:56:19 +02:00
Meta Vens
f167683e8d Merge ghostlight-verse/call-record 2026-10-10 22:56:15 +02:00
Meta Vens
308169ac51 call-record: pin all fifteen keyed fields of the replay key
The replay-key test now covers schema_id, reasoning_summary,
output_format_name, tool_choice and prompt_cache_key beside the ten it
had, over a Vec so a future keyed field is one more row. Tests only;
every commit builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:31:20 +02:00
Meta Vens
4126c83eff ghostlight import-key: pin whole-record NFC and the admit_resolved duplicate backstop
Tests only, no production change. Both build. A late NFD sequence and a
late format character in a long lore-shaped path kill an is_nfc-on-prefix
mutant; a resolved effect carrying two subjects with one key kills a
fresh declared set in admit_resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:14:01 +02:00
Meta Vens
ecff1ac25b Call record tests: resumed and exact-cap cases keep one cap per run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:46:21 +02:00
Meta Vens
e651d9e863 Call record: fix the moved ledger borrow (previous commit does not build)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:33:27 +02:00
Meta Vens
2c5eb95da3 Call record: ledger carries cap and starting world; replay refuses another world
The run ledger is the one owner of what a run began as: its cap and the
world id and state digest it started from. Replay takes the store, the run
and a restored world and refuses a different world up front with a typed
error naming the field. Restores the decode checks the ledger rules do not
imply, makes the replay key an exhaustive destructure, and pins the
over-bound edge. Not yet built or tested at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:32:17 +02:00
Meta Vens
ee174c68ce Ghostlight import key: behavioural tests for the canonical spelling and the state gate
Soul's forgeries shaped as real keys (NFC vs NFD, ZWSP, NUL, BOM, RLO, BEL,
double space, tab, NBSP), a lore path with spaces admitted, and a loaded
state with a shared or malformed key refused. Test-only commit; builds if
the prior commit does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:09:08 +02:00
Meta Vens
1afd942be3 Ghostlight import key: one canonical predicate, one uniqueness function, state gate
The record key is canonical free text per ruling import-key-canonical-text
(NFC, no Cc/Cf, only U+0020 whitespace, no edge or doubled space). The
resolver, admit_resolved and verify_state_shape all call the same predicate
and import_key_fault; admit_resolved's second held-set iteration is deleted.
Adds unicode-normalization and unicode-properties. Not yet verified on
Yggdrasil; build status of this commit unproven.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:54:42 +02:00
Meta Vens
c750e21c2d Import key tests: a snapshot reader gets schema and record back separately
Test-only; compile-checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:46:46 +02:00
Meta Vens
e085286126 Import key: the door test checks Draft doors in Draft and Active doors in Active; held and declared keys are separate sets
Compile-checked; tests run in the next job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:27:14 +02:00
Meta Vens
525666f79b Import key tests: digest pin reads the msgpack the digest is taken over
Test-only; compile-checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:25:19 +02:00
Meta Vens
b8465e50d3 Import key: a subject names the record it came from, and admission keeps the mapping one-to-one
ImportKey (schema, record) rides SubjectDeclaration and SubjectState as an
optional field (serde default, skipped when None, so keyless worlds keep their
digests) and is exposed on SubjectSnapshot. resolve_patch, the one resolution
owner for genesis and the owner, consumer, Play and elaborator doors, refuses a
malformed key, a key declared twice in one patch, and a key any existing subject
holds, retired included. admit_resolved, the subjects map's only writer, holds
the same injectivity as an invariant. Typed mismatches name the handle only.

Compile-checked (cargo check --tests) on Starfire; tests not yet run, so no
claim that this commit's tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:23:26 +02:00
Meta Vens
8c9b88b519 call-record: drop two record-decode checks the ledger and density rules already make
A record with a run id that is no key segment has no readable ledger, and a
record at sequence zero fails the density rule at open; the two decode_row
conditions were equivalent mutants (cargo-mutants missed both). Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:22:02 +02:00
Meta Vens
bd8dc756d9 WIP call-record fix1: run ledger owned by the store (does not build until verified)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:45:18 +02:00
Meta Vens
2e9905f42f Verse call records: the in-flight test cannot hang when the first call is refused
Two reserve mutants timed out because the test spun waiting for a call a
mutant had refused. The wait is now bounded and fails. Builds: yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:39:15 +02:00
Meta Vens
f74dec6675 Verse call records: kill the first mutation round's survivors
The in-memory run tally no longer counts rows (only open used it); the store
test pins a record whose run id is not a key segment; the lend_tool_results
forwarding has a test; the in-flight test fails by timeout instead of hanging
when a held call is let through. Builds: yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:54:33 +02:00
Meta Vens
e28bf3fd55 Verse call records: a recording port owns the run's spend, a replay port serves the stored responses
ProviderCallRecord (ghostlight.verse_provider_call.v1) keyed (run id, sequence),
CallRecordStore over an owned redb CultCache file, RecordingInferencePort
(bound check before the call, real usage charged after, record written before
the output returns) and ReplayInferencePort. InferenceFaultClass gains
BudgetExhausted. Not yet compiled or run: this commit may not build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:02:48 +02:00
Meta Vens
b2447e4f99 Hosted lane tests: pin DEL (0x7f) as a key byte that cannot ride a header
Follow-up hosted-key-del-pin: a mutant allowing DEL survived the key-shape
test. The case list gains an interior DEL. Builds: yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 13:56:43 +02:00
Meta Vens
8912dde49f Begin test: the refusal names its step in the begin's own words
A mutant that dropped the step from the message survived because the kernel's
own cause text also contains the word approve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 02:47:01 +02:00
Meta Vens
90c5e3b337 Docs: the no-world surface is Begin
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 02:39:28 +02:00
Meta Vens
1645f4a972 Bridge fixture: re-captured from the real pinned lowering for world.begin
Captured by running the drift test's own walk (begin, then play) with a
temporary, uncommitted patch that writes the regenerated intents instead of
comparing them (vendor/eve at 672c0c1, built and run on Starfire).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 02:39:17 +02:00
Meta Vens
f89be06a33 Begin tests: reuse the untouched-form intent builder; the untouched-form walk begins instead of creating
Does not build the fixture replay test: the bridge fixture still carries the
old steps until it is re-captured from the real client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 02:35:48 +02:00
Meta Vens
efa7d5cff2 World creation is one step: title, name, optional brief, Begin
The no-world card asks for a title, a name and an optional brief and offers
one Begin button. world.begin takes the world_create.v4 payload (the fields
the form no longer asks for ride the button's action as authored constants)
and submits create, approve and activate as three separate kernel commands,
stopping at the first refusal. The create path is shared with world.create.
Step ids are derived from the Begin's key so a replayed Begin replays through
the kernel's ledger. A refusal never echoes a typed value, including the
jurisdiction-handle refusal on world.create.

Not yet built or run: the bridge fixture still carries the old
create/approve/activate steps (re-derived from the real client in a later
commit), and the ignored bridge tests have not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 02:34:20 +02:00
138 changed files with 36930 additions and 12248 deletions

1
.gitignore vendored
View file

@ -1,5 +1,4 @@
node_modules/
web/dist/
sidecar/claude-sdk/dist/
target/

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "vendor/eve"]
path = vendor/eve
url = https://github.com/GameCult/Eve.git

View file

@ -5,7 +5,8 @@
Ghostlight is a Rust world kernel and the play daemon built on it. Models
propose; the kernel admits or refuses. The same kernel is meant to run the
simulation behind Aetheria's public story, a persistent cast and storylets, as
well as Ghostlight Dungeon, the single-player DM-led client. `README.md` says
well as Ghostlight Dungeon, the single-player DM-led client (parked at
tag `parked/ghostlight-eve-surface`). `README.md` says
what exists today and what does not.
## Where State Lives
@ -55,28 +56,21 @@ what exists today and what does not.
- Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism:
`docs/architecture/ghostlight-world-ontology.md`. The consumer contract:
`docs/architecture/ghostlight-world-consumer-api.md`.
- Dungeon daemon: `crates/ghostlight-dungeon/src/` (`runtime.rs` for routes and
commands, `play.rs` for the play table, `eve.rs` for the surface).
Interface authority: `docs/architecture/ghostlight-eve-native-interface.md`.
- Parked Dungeon (daemon, play table, Eve surface, browser host, Idunn recipe):
tag `parked/ghostlight-eve-surface`; not on main.
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
- Browser host: `web/`. Claude SDK sidecar: `sidecar/claude-sdk/`.
- Architecture rationale: `docs/architecture/ghostlight-dungeon-mvp.md`.
- Claude SDK sidecar: `sidecar/claude-sdk/`.
- Architecture rationale (the parked Dungeon's): `docs/architecture/ghostlight-dungeon-mvp.md`.
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
rebuild, not the current plan.
## Build, Verify, Deploy
Ghostlight Dungeon ships to Linux on Yggdrasil. Idunn freezes an exact commit,
runs the locked native Linux tests, builds the daemon and web projection in
pinned containers, and seals the release. The steps are
`deployment/idunn/recipe.toml`; the owning runbook is
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
You are probably reading this on a Windows workstation. That is where the shell
is, not where the artifact runs. A Windows compile is not evidence about the
Linux release; build for the target, or let the deploy path's builder do it, and
say which one you used. Heavy builds and test runs go to Yggdrasil, not the
workstation. Deploy only through Idunn (`idunn up ghostlight`).
Nothing deploys from this repo: the Idunn target `ghostlight` is braked and stopped (deployment and
lifecycle brakes engaged, unit stopped; retirement waits on
`ghostlight-verse:follow_up:idunn-v2-target-retirement`) and no recipe exists on main. Kernel and verse tests run on Linux on Yggdrasil (the
`ygg-verify` stopgap), not on the workstation; a Windows compile is not evidence
about Linux, so say which host you used. Do not run `idunn up ghostlight`.
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult
`F:\Projects\gamecult-ops` before acting.

339
Cargo.lock generated
View file

@ -61,6 +61,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ar_archive_writer"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
dependencies = [
"object",
]
[[package]]
name = "async-stream"
version = "0.3.6"
@ -176,12 +185,6 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "base64ct"
version = "1.8.3"
@ -272,22 +275,6 @@ dependencies = [
"inout",
]
[[package]]
name = "codex-connector"
version = "0.1.0"
source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708"
dependencies = [
"aes-gcm",
"base64 0.23.1",
"rand_core 0.6.4",
"rmp-serde",
"serde",
"serde_json",
"sha2",
"thiserror",
"zeroize",
]
[[package]]
name = "const-oid"
version = "0.9.6"
@ -345,7 +332,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive",
"cultcache-rs-derive 0.1.0",
"fs2",
"redb",
"rmp-serde",
@ -356,6 +343,26 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs"
version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"anyhow",
"chrono",
"cultcache-rs-derive 0.2.0",
"fs2",
"redb",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"serde_stacker",
"stacker",
"uuid",
"windows-sys 0.59.0",
]
[[package]]
name = "cultcache-rs-derive"
version = "0.1.0"
@ -366,14 +373,24 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "cultcache-rs-derive"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "cultmesh-rs"
version = "0.1.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
dependencies = [
"anyhow",
"cultcache-rs",
"cultnet-rs",
"cultcache-rs 0.1.0",
"cultnet-rs 0.1.0",
"serde",
]
@ -384,9 +401,34 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
dependencies = [
"aes-gcm",
"anyhow",
"base64 0.22.1",
"base64",
"chrono",
"cultcache-rs",
"cultcache-rs 0.1.0",
"ed25519-dalek",
"hmac",
"rand 0.9.5",
"rmp-serde",
"rmpv",
"serde",
"serde_bytes",
"serde_json",
"sha2",
"socket2 0.5.10",
"uuid",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "cultnet-rs"
version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
dependencies = [
"aes-gcm",
"anyhow",
"base64",
"chrono",
"cultcache-rs 0.3.1",
"ed25519-dalek",
"hmac",
"rand 0.9.5",
@ -441,9 +483,9 @@ dependencies = [
[[package]]
name = "deranged"
version = "0.5.8"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "digest"
@ -467,6 +509,12 @@ dependencies = [
"syn 3.0.3",
]
[[package]]
name = "dyn-clone"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "ed25519"
version = "2.2.3"
@ -663,11 +711,12 @@ version = "0.1.0"
dependencies = [
"async-trait",
"chrono",
"codex-connector",
"cultcache-rs",
"cultcache-rs 0.1.0",
"ghostlight-persona-projection",
"model-connector",
"reqwest",
"rmp-serde",
"rmpv",
"serde",
"serde_bytes",
"serde_json",
@ -676,6 +725,8 @@ dependencies = [
"thiserror",
"tokio",
"tracing",
"unicode-normalization",
"unicode-properties",
"uuid",
"zeroize",
]
@ -689,29 +740,27 @@ dependencies = [
"async-stream",
"async-trait",
"axum",
"base64 0.22.1",
"base64",
"chrono",
"codex-connector",
"cultcache-rs",
"cultcache-rs 0.1.0",
"cultmesh-rs",
"cultnet-rs",
"cultnet-rs 0.1.0",
"ghostlight",
"ghostlight-persona-projection",
"hmac",
"jsonwebtoken",
"libc",
"model-connector",
"rand 0.9.5",
"reqwest",
"rmp-serde",
"serde",
"serde_bytes",
"serde_json",
"sha2",
"tempfile",
"thiserror",
"tokio",
"tower",
"tower-http",
"tracing",
"tracing-subscriber",
"uuid",
@ -727,6 +776,18 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "ghostlight-verse"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"ghostlight",
"serde_json",
"tempfile",
"tokio",
]
[[package]]
name = "hmac"
version = "0.12.1"
@ -769,12 +830,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "http-range-header"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
[[package]]
name = "httparse"
version = "1.10.1"
@ -830,7 +885,7 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64 0.22.1",
"base64",
"bytes",
"futures-channel",
"futures-util",
@ -1013,7 +1068,7 @@ version = "9.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
dependencies = [
"base64 0.22.1",
"base64",
"js-sys",
"pem",
"ring",
@ -1024,9 +1079,9 @@ dependencies = [
[[package]]
name = "lazy_static"
version = "1.5.0"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
@ -1090,19 +1145,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.17"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
[[package]]
name = "mio"
@ -1115,6 +1160,26 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "model-connector"
version = "0.1.0"
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
dependencies = [
"aes-gcm",
"base64",
"cultnet-rs 0.2.0",
"rand_core 0.6.4",
"rmp-serde",
"rmpv",
"schemars",
"serde",
"serde_bytes",
"serde_json",
"sha2",
"thiserror",
"zeroize",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@ -1158,6 +1223,15 @@ dependencies = [
"autocfg",
]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@ -1199,7 +1273,7 @@ version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
dependencies = [
"base64 0.22.1",
"base64",
"serde_core",
]
@ -1248,9 +1322,9 @@ dependencies = [
[[package]]
name = "powerfmt"
version = "0.2.0"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "ppv-lite86"
@ -1270,6 +1344,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "psm"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
dependencies = [
"ar_archive_writer",
"cc",
]
[[package]]
name = "quinn"
version = "0.11.11"
@ -1430,10 +1514,30 @@ dependencies = [
]
[[package]]
name = "regex-automata"
version = "0.4.18"
name = "ref-cast"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
dependencies = [
"ref-cast-impl",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@ -1442,9 +1546,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.8.11"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "reqwest"
@ -1452,7 +1556,7 @@ version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"base64",
"bytes",
"futures-core",
"futures-util",
@ -1606,6 +1710,31 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "schemars"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
dependencies = [
"dyn-clone",
"ref-cast",
"schemars_derive",
"serde",
"serde_json",
]
[[package]]
name = "schemars_derive"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
dependencies = [
"proc-macro2",
"quote",
"serde_derive_internals",
"syn 3.0.3",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
@ -1658,6 +1787,17 @@ dependencies = [
"syn 3.0.3",
]
[[package]]
name = "serde_derive_internals"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "serde_json"
version = "1.0.151"
@ -1682,6 +1822,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_stacker"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
dependencies = [
"serde",
"serde_core",
"stacker",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@ -1799,6 +1950,19 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stacker"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.61.2",
]
[[package]]
name = "subtle"
version = "2.6.1"
@ -2019,23 +2183,13 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"http-range-header",
"httpdate",
"mime",
"mime_guess",
"percent-encoding",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"tracing",
"url",
]
@ -2125,18 +2279,27 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
@ -2531,18 +2694,18 @@ dependencies = [
[[package]]
name = "zerocopy"
version = "0.8.56"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.56"
version = "0.8.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
dependencies = [
"proc-macro2",
"quote",

View file

@ -3,6 +3,7 @@ members = [
"crates/ghostlight",
"crates/ghostlight-dungeon",
"crates/ghostlight-persona-projection",
"crates/ghostlight-verse",
]
resolver = "2"
@ -19,7 +20,7 @@ async-stream = "0.3"
axum = { version = "0.8", features = ["macros"] }
chrono = { version = "0.4", features = ["serde"] }
base64 = "0.22"
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" }
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" }
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" }
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" }
@ -33,7 +34,6 @@ serde_json = "1"
sha2 = "0.10"
thiserror = "2"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.6", features = ["fs", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
unicode-segmentation = "1"

220
README.md
View file

@ -1,149 +1,121 @@
# Ghostlight
Ghostlight is a Rust library that keeps a simulated world honest, and a play
daemon built on it. A language model proposes; the library's kernel checks each
proposal against typed world state and admits or refuses it. Places, people,
knowledge, commitments, and time live in the kernel's journal, not in a model's
context window, so they survive restarts and long stories.
**Ghostlight is a world kernel: typed world state that a language model can
propose changes to and can never write.** The valuable part is
`crates/ghostlight`. The Dungeon game, one client of it, is parked (below).
## What is here
**The thesis.** World state is typed documents. Every change to it, and every
narrative dependency on it, is an operation in a closed, predefined algebra.
Models propose operations; the kernel checks each against the state (references,
preconditions, authority, conservation, who knows what) and admits it or refuses
it with the complete list of mismatches. Narration describes only what was
committed. A model-as-game-master holds the world in a context window and
drifts; here the world is a digest-chained journal that survives restarts and
cannot be talked into contradicting itself.
| Part | Path | What it is |
|---|---|---|
| World kernel | `crates/ghostlight/` | The sealed `ghostlight` library: world state, the closed operation set and reducer, the CultCache journal, the mailbox that is its only door, controllers, elaboration, lenses, the consumer ingress, and the inference ports. |
| Persona projection | `crates/ghostlight-persona-projection/` | The membrane between structured state and a prose-only Persona: projection, Persona turn receipts, and the controller descriptors the kernel consumes. |
| Dungeon | `crates/ghostlight-dungeon/` | The `ghostlight-dungeon` daemon: single-player, DM-led play over one world. HTTP and Eve routes, Heimdall sign-in, app sessions, the play table, CultMesh publication, and Idunn health. |
| Browser | `web/` | A thin Eve browser host and the Heimdall access adapter. It renders the server's surface and owns no product state. |
| Claude SDK sidecar | `sidecar/claude-sdk/` | A Node process that serves `claude`-prefixed models to the kernel through the Claude Agent SDK. It is a stopgap for a direct Messages API port. |
| Deploy recipe | `deployment/idunn/recipe.toml` | The steps Idunn runs to test, build, and seal a release. |
| Eve | `vendor/eve/` | A git submodule (`.gitmodules`) supplying the Eve browser lowering and contracts. |
**Use it as a structured state backend.** Do not judge it by the parked Dungeon's
prose. The kernel is a library; prose comes from whichever model you plug into
its ports.
## How it works
- `crates/ghostlight`: the sealed library. A consumer gets create/open
(`WorldMailbox::open`, `create`), immutable snapshots (`snapshot`), command
submission through role-scoped ports (`PlayPort`, `ConsumerPort`,
`ControllerPort`, `SeedPort`), typed receipts, and the runner and inference-port
entry points (`ControllerRunner`, `ElaborationRunner`, `SeedRunner`,
`InferencePort`). Mutable state, ID issuers, the reducer and the journal
writer are not public. `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs`
and `crates/ghostlight/tests/external_admission.rs` prove the seal.
- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary (subjects,
places, routes, holdings, knowledge, commitments, pressures), the operation
algebra, and what the reducer checks.
- `docs/architecture/ghostlight-world-consumer-api.md`: the contract for a
program that reads a world and proposes changes to the characters it controls
(`POST /cultnet/world-patch`; no process on main serves that door, a host serves
`ghostlight::admit_document`).
- The kernel is sealed. A consumer reaches it through create/open, immutable
snapshots, command submission, typed receipts, and the runner and port entry
points. There is no public mutable state, ID issuer, reducer, or journal
writer, and the crate declares no cargo features. The seal is proven by
`compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` and by
`crates/ghostlight/tests/external_admission.rs`, which forges IDs, digests,
and opportunities and asserts that each is refused with nothing committed.
- Every change enters one mailbox (`crates/ghostlight/src/mailbox.rs`) as a
command, is decided by one reducer, and commits atomically to a
digest-chained journal (`crates/ghostlight/src/journal.rs`, CultCache on redb).
- Models author through typed tools and a repair loop
(`crates/ghostlight/src/elaboration.rs`, `tool_schema.rs`, `patch.rs`). A
refused proposal returns its mismatches to the model; it never edits state.
- A Persona speaks only prose. A Projector builds its view, and an Interpreter
lowers its words into typed proposals with exact source quotes
(`crates/ghostlight/src/controllers.rs`).
- Vault evidence for seeding comes from a read-only markdown directory reader
(`crates/ghostlight/src/vault.rs`). The Dungeon's seed lane reads the
directory named by `GHOSTLIGHT_SEED_VAULT_ROOT`, read once at startup, so
changing it needs a restart
(`crates/ghostlight-dungeon/src/runtime.rs`).
- Other programs can propose changes to the characters they control through
`POST /cultnet/world-patch` (`crates/ghostlight-dungeon/src/runtime.rs`,
`crates/ghostlight/src/consumer.rs`). The contract is
`docs/architecture/ghostlight-world-consumer-api.md`.
Start with those two documents, then `cargo doc -p ghostlight --open`.
## Ghostlight Dungeon
**Populate the algebra first.** The kernel owns the component operations; a world owns its
affordance catalog, the verbs its actors can attempt. A fresh world knows one: the built-in
Speak, which records an utterance and changes nothing. Until your world declares affordances
(at genesis, by patch, or through elaborators) for moving, trading, taking, deciding and so on,
every intent a model voices lowers to speech or to a recorded gap, and the prose built on that
will be thin no matter how good the model is. The Aetheria verse genesis
(`crates/ghostlight/src/verse/genesis.rs`) declares its grammar's verbs, and today they still
only record the act; their effects are the next phase.
Dungeon is the single-player, DM-led client. A player signs in with Heimdall,
creates a world, seeds it from a vault, approves and activates it, and plays in
free text. The play table (`crates/ghostlight-dungeon/src/play.rs`) owns the
turn lifecycle; the interface is one Eve surface, `ghostlight.play`
(`crates/ghostlight-dungeon/src/eve.rs`, described in
`docs/architecture/ghostlight-eve-native-interface.md`). Because its player is
not a developer, Dungeon is judged by whether someone can sit down and play.
## Elaborators
Where it runs:
An elaborator is a model session, confined to one jurisdiction of the world, that
adds structure where the world is thin: it answers a derived causal boundary
(a destination nobody has described yet) or a scale deficit with typed
declarations, and the kernel verifies the result like any other patch. Sessions
are resumable and checkpointed against committed history. Eight stock lenses
(`crates/ghostlight/src/lens.rs`: patina, charter, ledger, hearth, tangle, veil,
ember, numen) give each session a role-specific emphasis, for example customs and
local jokes, or money and ledgers. A lens changes the prompt only, never what the
kernel admits. Because boundaries are derived from state, elaborators can be
dispatched as the player approaches a place or a social structure, instead of
authoring the world up front.
- **Yggdrasil**, under Idunn, built from `main` by `deployment/idunn/recipe.toml`.
Idunn owns the daemon's lifecycle and the write lease. Odin supplies discovery
and Heimdall's command-boundary record. The operating runbook is
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
- **Inference** is routed by model name: a `local/` prefix goes to an
OpenAI-compatible loopback endpoint
(`GHOSTLIGHT_LOCAL_ENDPOINT`, `crates/ghostlight/src/local_inference.rs`),
which in production is Bonsai on Raven's GPU reached through a loopback
tunnel; a `claude` prefix goes to the SDK sidecar
(`GHOSTLIGHT_SDK_SIDECAR`, `crates/ghostlight/src/sdk_inference.rs`).
Ghostlight never reads, stores, or forwards a model credential.
- **Sign-in** is Heimdall's. Ghostlight keeps a hashed HttpOnly session and
derives authority from the world's owner and approvers.
## Direction (planned, not built)
## Direction
Use the kernel to simulate a whole world with many kinds of actor: Aetheria's
factions and a persistent cast whose members keep identity, memory and
commitments across sessions. Newspaper-staff simulations before the 2026-08
teardown are the earlier proof of the idea; that code is in git history, not in
the tree. Running this at scale is gated by inference cost, not by the design.
`crates/ghostlight-verse` is the first slice: `ghostlight-verse genesis` creates
an Aetheria verse world from the Aetheria catalog and `ghostlight-verse run`
advances it a number of ticks under a token cap, reporting per tick what each
faction did and what it cost. Nothing loads AetheriaLore prose, models
storylets, or produces episodes yet. Targets: `notes/ghostlight-verse-target.md`.
The next work makes Ghostlight the simulation behind Aetheria's public story.
The operator's rulings (campaign `ghostlight-verse` in the Eureka mind) ask for:
## Ghostlight Dungeon (parked)
- a world loaded from the Aetheria verse, with factions and a cast;
- storylets for Aetheria;
- a persistent cast whose characters keep identity, memory, and commitments
across sessions, so serialized episodes can follow them;
- episodes a cheap pipeline can turn into a video stream, and channel
characters who later appear in the game.
The single-player, DM-led client and its daemon, Eve play surface and browser
host are parked at tag `parked/ghostlight-eve-surface`. Nothing is deployed and
nothing on main serves HTTP. The Dungeon returns when Thing 2 gives it a UI
(follow-up `dungeon-ui-on-thing2`); the rebuild starts from the tag.
None of this exists yet. Nothing under `crates/` loads Aetheria lore, models
storylets, or produces an episode. Every event the kernel admits is meant to
have exactly one render path: ship action filmed in Aetheria, or a social verb
staged as an Aetheria conversation. Today a world can declare any affordance
kind, and the kernel does not enforce that restriction.
## Repo map
| Path | What it is |
|---|---|
| `crates/ghostlight/` | The sealed kernel library. |
| `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. |
| `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). |
| `sidecar/claude-sdk/` | Node process serving `claude`-prefixed models to the kernel; a stopgap for a direct Messages API port. |
| `AGENTS.md` | Invariants and where things are. |
| `docs/architecture/ghostlight-dungeon-mvp.md` | The parked Dungeon's authority architecture (design record). |
| `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. |
`docs/public-architecture/`, `docs/articles/` and `docs/product/` are design
essays and proposals from before the rebuild. They describe organs (campaigns,
co-op, Nemesis, newspapers) that are not in `crates/`; they do not describe the
running machine. Pages ending in `-cut.md` or `-postmortem.md` are dated history.
## Build and test
The release target is Linux on Yggdrasil; a Windows build says nothing about
it. Idunn runs the steps in `deployment/idunn/recipe.toml`, which are the
verification:
Nothing deploys from this repo. Linux verification runs on Yggdrasil, not on a
workstation:
```sh
git submodule update --init vendor/eve
cargo build --locked --workspace
cargo test --locked -p ghostlight-persona-projection
cargo test --locked -p ghostlight
cargo test --locked -p ghostlight-dungeon --bin ghostlight-dungeon
cargo build --locked --release -p ghostlight-dungeon --bin ghostlight-dungeon
npm --prefix web ci
npm --prefix web test
npm --prefix web run build
cargo test --locked -p ghostlight-verse
```
The sidecar has its own `npm --prefix sidecar/claude-sdk run build` and `test`
(also the root scripts `sdk:build` and `sdk:test`). Four Dungeon tests are
`#[ignore]`d because they drive the vendored browser lowering through
`tools/eve_client_bridge.mjs` and need Node beside cargo. The release
acceptance step runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
(ignored by default) against a real model.
The kernel alone needs only `cargo test -p ghostlight`. The sidecar has
`npm run sdk:build` and `npm run sdk:test`. The acceptance test
`controllers::tests::real_local_model_cognition_modes_commit_speech` is ignored
by default and needs a real model.
To run Dungeon locally: `npm run dungeon:run`, or
`cargo run -p ghostlight-dungeon -- --state-root PATH`. Configuration is by
`GHOSTLIGHT_*` environment variables; the recipe's `required_environment`
lists the ones a deployment sets.
Inference is routed by model name: `local/` goes to an OpenAI-compatible
loopback endpoint, `claude` to the SDK sidecar, and the verse runner's `hosted/`
to an https endpoint. Ghostlight never reads, stores or forwards a model
credential beyond a key file named at run time.
## Documents
- `AGENTS.md`: repository doctrine for agents.
- `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture
of the world machine.
- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary and the
kernel's current mechanism.
- `docs/architecture/ghostlight-world-consumer-api.md`: the consumer contract.
- `docs/architecture/ghostlight-eve-native-interface.md`: the Eve surface.
- `docs/architecture/ghostlight-library-extraction.md`,
`ghostlight-stock-lenses.md`: closed records of landed work. Pages ending in
`-cut.md` and `-postmortem.md` are dated history.
- `docs/architecture/ghostlight-play-agent.md`: historical. Its status line
predates the play-agent cuts; read it with `-cut.md` beside it, not as the
current play surface (`crates/ghostlight-dungeon/src/play.rs` is).
- `docs/architecture/ghostlight-session-zero.md`: unbuilt design, superseded by
the play agent. Nothing in `crates/` implements it.
- `notes/fresh-workspace-handoff.md`: where things run and where open work is
recorded.
- `docs/public-architecture/`, `docs/articles/`: unbuilt design and essays
written before the rebuild. They describe campaigns, co-op, Nemesis
and strategic resolvers as organs; none of that exists in `crates/`. They do not
describe the running machine.
- `docs/product/lore-vault-entitlements.md`: a product proposal for hosted
vaults; nothing in `crates/` implements it.
Runtime documents use MessagePack-backed CultCache. JSON appears only at schema
publication, browser, model-provider, and diagnostic boundaries.
Runtime documents are MessagePack-backed CultCache. JSON appears only at schema
publication, model-provider and diagnostic boundaries.

View file

@ -17,8 +17,8 @@ async-stream.workspace = true
axum.workspace = true
chrono.workspace = true
base64.workspace = true
codex-connector.workspace = true
cultcache-rs.workspace = true
model-connector.workspace = true
cultnet-rs.workspace = true
cultmesh-rs.workspace = true
jsonwebtoken.workspace = true
@ -31,11 +31,9 @@ reqwest.workspace = true
rmp-serde.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_bytes = "0.11"
sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true

View file

@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark light">
<meta name="referrer" content="no-referrer">
<title>Ghostlight Dungeon</title>
<link rel="stylesheet" href="page.css">
</head>
<body>
<header class="bar">
<button id="home" class="brand" type="button" aria-label="Your worlds">Ghostlight</button>
<div class="tools">
<button id="smaller" class="tool" type="button" aria-label="Smaller text">A&minus;</button>
<button id="larger" class="tool" type="button" aria-label="Larger text">A+</button>
<button id="theme" class="tool" type="button" aria-label="Switch light or dark theme">&#9680;</button>
<button id="signout" aria-label="Sign out" class="tool" type="button" hidden>Exit</button>
</div>
</header>
<main id="view" aria-live="polite"><p class="note">Loading&hellip;</p></main>
<noscript><p class="note">This page needs JavaScript to play.</p></noscript>
<script src="page.js"></script>
</body>
</html>

View file

@ -0,0 +1,73 @@
/* Presentation only. Text size and theme are the two variables below. */
:root {
--fs: 1.125rem;
--bg: #07111a; --panel: #16212c; --line: #263646; --muted: #8fa1b5;
--text: #eef5ff; --accent: #ff8a2a; --link: #59b7ff;
--bad: #ff6b5e; --badbg: #2a1614; --ok: #6fd08c; --focus: #59b7ff;
--head: Montserrat, "Segoe UI", system-ui, sans-serif;
--body: Georgia, "Iowan Old Style", "Palatino Linotype", serif;
}
:root[data-theme="light"] {
--bg: #f7f4ee; --panel: #ffffff; --line: #d8d2c4; --muted: #5d6a78;
--text: #17202a; --accent: #b4510a; --link: #0b5fa8;
--bad: #a3231a; --badbg: #fdeceb; --ok: #1d7a3c; --focus: #0b5fa8;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; background: var(--bg); color: var(--text); font: var(--fs)/1.65 var(--body); overflow-wrap: anywhere; }
.bar { position: sticky; top: 0; z-index: 5; display: flex; justify-content: space-between; align-items: center; gap: .5rem;
padding: .4rem max(.75rem, env(safe-area-inset-left)); background: var(--bg); border-bottom: 1px solid var(--line); }
.brand { white-space: nowrap; background: none; border: 0; color: var(--accent); font: 600 1.05rem var(--head); letter-spacing: .06em; text-transform: uppercase; min-height: 44px; padding: 0 .25rem; cursor: pointer; }
.tools { display: flex; gap: .2rem; justify-content: flex-end; }
.tool { background: none; border: 1px solid var(--line); color: var(--muted); font: 500 .8rem var(--head); border-radius: .5rem; min-height: 44px; min-width: 44px; padding: 0 .5rem; cursor: pointer; }
main { max-width: 44rem; margin: 0 auto; padding: .75rem max(.75rem, env(safe-area-inset-left)) 10rem; }
h1, h2 { font-family: var(--head); font-weight: 300; line-height: 1.2; margin: .5rem 0 .75rem; }
h1 { font-size: 1.6rem; } h2 { font-size: 1.25rem; }
.note, .small { color: var(--muted); font-size: .9rem; line-height: 1.5; }
a { color: var(--link); }
button, input, textarea { font: inherit; color: inherit; }
:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .9rem 1rem; margin: .75rem 0; }
.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: center; }
.btn { background: var(--accent); color: #07111a; border: 0; border-radius: .6rem; min-height: 48px; padding: 0 1.1rem; font: 600 1rem var(--head); cursor: pointer; }
.btn.alt { background: none; color: var(--text); border: 1px solid var(--line); }
.btn[disabled] { opacity: .5; cursor: default; }
.btn.wide { width: 100%; }
label { display: block; font: 600 .85rem var(--head); letter-spacing: .04em; margin: 1rem 0 .3rem; color: var(--muted); text-transform: uppercase; }
input[type=text], textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: .6rem; padding: .7rem .8rem; min-height: 48px; }
textarea { resize: vertical; line-height: 1.5; }
.choice { display: flex; gap: .7rem; align-items: center; min-height: 48px; padding: .4rem .6rem; border: 1px solid var(--line); border-radius: .6rem; margin: .4rem 0; cursor: pointer; background: var(--bg); }
.choice input { width: 1.4rem; height: 1.4rem; accent-color: var(--accent); flex: none; }
.chip { font: 600 .72rem var(--head); text-transform: uppercase; letter-spacing: .06em; padding: .15rem .5rem; border-radius: 1rem; border: 1px solid var(--line); color: var(--muted); }
.chip.ready { color: var(--ok); border-color: var(--ok); } .chip.seeding { color: var(--accent); border-color: var(--accent); } .chip.failed { color: var(--bad); border-color: var(--bad); }
.tl { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: .75rem; padding: .8rem 1rem; margin: .5rem 0; min-height: 56px; cursor: pointer; }
.tl.current { border-color: var(--accent); }
.tl .t { font: 600 1.05rem var(--head); display: block; }
.line { border-left: 4px solid var(--bad); background: var(--badbg); border-radius: .4rem; padding: .6rem .8rem; margin: .75rem 0; }
.line.info { border-color: var(--accent); background: var(--panel); }
.turn { margin: 1.4rem 0; }
.you { color: var(--muted); font-style: italic; border-left: 3px solid var(--line); padding-left: .8rem; margin: .8rem 0; white-space: pre-wrap; }
.story { white-space: pre-wrap; margin: 0; }
.ask { border: 1px solid var(--accent); border-radius: .6rem; padding: .6rem .8rem; margin: .8rem 0; }
.status { color: var(--muted); font: 500 .85rem var(--head); }
.pulse::after { content: ""; display: inline-block; width: .5rem; height: .5rem; margin-left: .5rem; border-radius: 50%; background: var(--accent); animation: p 1.2s ease-in-out infinite; }
@keyframes p { 50% { opacity: .2; } }
@media (prefers-reduced-motion: reduce) { .pulse::after { animation: none; } }
.bar2 { height: .4rem; background: var(--line); border-radius: .3rem; overflow: hidden; margin: .6rem 0; }
.bar2 i { display: block; height: 100%; width: 40%; background: var(--accent); animation: s 1.6s ease-in-out infinite alternate; }
@keyframes s { to { margin-left: 60%; } }
@media (prefers-reduced-motion: reduce) { .bar2 i { animation: none; width: 100%; } }
.compose { position: fixed; left: 0; right: 0; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: .5rem max(.75rem, env(safe-area-inset-left)) max(.5rem, env(safe-area-inset-bottom)); }
.compose .in { max-width: 44rem; margin: 0 auto; }
.compose textarea { min-height: 2.8rem; max-height: 30vh; }
.compose .row { margin-top: .4rem; }
.compose .btn { flex: 1 1 8rem; }
@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } }
.blk { display: block; } .bad { color: var(--bad); } .gap { margin-top: .6rem; margin-bottom: .2rem; }
label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; }
.older { text-align: center; }
.older .btn { margin: .4rem 0; }
.lens { display: flex; gap: .5rem; align-items: center; padding: .35rem 0; border-bottom: 1px solid var(--line); }
.lens .what { flex: 1 1 auto; min-width: 0; }
.lens .n { min-width: 1.5rem; text-align: center; font: 600 1.05rem var(--head); }
.step { background: none; border: 1px solid var(--line); color: var(--text); border-radius: .5rem; min-width: 44px; min-height: 44px; font: 600 1.2rem var(--head); cursor: pointer; flex: none; }

View file

@ -0,0 +1,410 @@
// Presentation only. The daemon owns every command and every fact; this page
// shows what the API returns and sends what the player types. The only state it
// keeps on the device is the unsent draft, the text size and the theme. The
// scrollback is the server's turn log, loaded on open and paged on scroll-up,
// so a reload or another device shows the same story.
"use strict";
const $view = document.getElementById("view");
const LS = {
get(k) { try { return localStorage.getItem(k); } catch { return null; } },
set(k, v) { try { if (v === null || v === "") localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* storage may be blocked */ } },
};
const uuid = () => (crypto.randomUUID ? crypto.randomUUID()
: "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)));
function el(tag, attrs, ...kids) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (k === "class") node.className = v;
else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
else if (v === true) node.setAttribute(k, "");
else if (v !== false && v != null) node.setAttribute(k, v);
}
for (const kid of kids.flat()) if (kid != null) node.append(kid);
return node;
}
async function api(path, options) {
let response;
try {
response = await fetch("api/" + path, { credentials: "same-origin", ...options,
headers: options && options.body ? { "content-type": "application/json" } : undefined });
} catch {
return { status: 0, body: { error: "The server could not be reached." } };
}
let body = null;
try { body = await response.json(); } catch { body = null; }
return { status: response.status, body: body || {} };
}
const post = (path, body) => api(path, { method: "POST", body: JSON.stringify(body) });
// ---- text size and theme -------------------------------------------------
const root = document.documentElement;
function applySize(rem) { root.style.setProperty("--fs", rem + "rem"); LS.set("fs", String(rem)); }
const savedSize = parseFloat(LS.get("fs"));
if (savedSize >= 0.9 && savedSize <= 1.9) root.style.setProperty("--fs", savedSize + "rem");
function currentSize() { return parseFloat(getComputedStyle(root).getPropertyValue("--fs")) || 1.125; }
document.getElementById("smaller").onclick = () => applySize(Math.max(0.9, +(currentSize() - 0.1).toFixed(2)));
document.getElementById("larger").onclick = () => applySize(Math.min(1.9, +(currentSize() + 0.1).toFixed(2)));
function applyTheme(name) {
if (name === "light" || name === "dark") root.dataset.theme = name; else delete root.dataset.theme;
}
applyTheme(LS.get("theme"));
document.getElementById("theme").onclick = () => {
const next = root.dataset.theme === "light" ? "dark" : "light";
applyTheme(next); LS.set("theme", next);
};
// ---- state ---------------------------------------------------------------
const S = { me: null, timeline: null, history: [], older: null, live: null, echo: null, keyed: null, tailTried: null, stream: null, poll: null, signIn: null };
function stopLive() {
if (S.stream) { S.stream.close(); S.stream = null; }
if (S.poll) { clearTimeout(S.poll); S.poll = null; }
}
function show(...nodes) { document.querySelector(".compose")?.remove(); $view.replaceChildren(...nodes.flat()); window.scrollTo(0, 0); }
function inviteFromHash() {
const m = /(?:^#|&)invite=([A-Za-z0-9_\-]{8,200})/.exec(location.hash);
return m ? m[1] : "";
}
async function boot() {
stopLive();
const { status, body } = await api("me");
if (status !== 200) return show(el("h1", {}, "Ghostlight"), errorLine(body.error || "The server answered with an error (" + status + ")."), retryButton(boot));
S.me = body;
document.getElementById("signout").hidden = !body.signedIn;
if (!body.signedIn) return signInView();
if (body.currentTimeline) return openTimeline(body.currentTimeline);
return listView();
}
function errorLine(text) { return el("p", { class: "line", role: "alert" }, text); }
function retryButton(fn) { return el("button", { class: "btn", type: "button", onclick: fn }, "Try again"); }
// ---- sign in -------------------------------------------------------------
function signInView(message) {
stopLive();
const providers = (S.me && S.me.providers) || [];
const invite = el("input", { type: "text", id: "invite", autocomplete: "off", autocapitalize: "off", spellcheck: "false", value: inviteFromHash() });
const out = el("div", {});
if (message) out.append(errorLine(message));
const buttons = providers.map((name) => el("button", { class: "btn wide gap", type: "button", onclick: () => beginSignIn(name, invite.value.trim(), out) },
"Sign in with " + name[0].toUpperCase() + name.slice(1)));
show(el("h1", {}, "Sign in"),
el("p", { class: "note" }, "Only people on the allowlist can play. A first sign-in needs the invite you were given; after that, signing in is enough."),
el("div", { class: "card" },
el("label", { for: "invite" }, "Invite (first time only)"), invite,
el("p", { class: "small" }, "A link that ends in #invite=… fills this in."),
providers.length ? buttons : el("p", { class: "line" }, "This server offers no sign-in provider.")),
out);
if (S.signIn && S.signIn.until > Date.now()) resumeSignIn(out, invite);
}
async function beginSignIn(provider, invite, out) {
out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in"));
const { status, body } = await post("auth/begin", invite ? { key: uuid(), provider, invite } : { key: uuid(), provider });
if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ")."));
let target = null;
try {
const url = new URL(body.url, location.href);
if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href;
} catch { target = null; }
if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open."));
S.signIn = { handle: body.handle, target, until: Date.now() + 9 * 60 * 1000 };
window.open(target, "_blank", "noopener");
resumeSignIn(out);
}
async function resumeSignIn(out) {
const attempt = S.signIn;
out.replaceChildren(
el("p", { class: "note pulse" }, "Waiting for you to finish signing in on the other tab."),
el("p", {}, el("a", { href: attempt.target, target: "_blank", rel: "noopener noreferrer" }, "Open the sign-in page again")));
while (S.signIn === attempt && Date.now() < attempt.until) {
await new Promise((r) => setTimeout(r, 2500));
if (S.signIn !== attempt) return;
const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid() });
if (status === 202) continue;
S.signIn = null;
if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); }
if (status === 429) return out.replaceChildren(errorLine(body.error || "Too many attempts; wait a minute."));
return out.replaceChildren(errorLine(body.error || "Sign-in was refused (" + status + ")."));
}
if (S.signIn === attempt) { S.signIn = null; out.replaceChildren(errorLine("The sign-in expired. Start again.")); }
}
document.getElementById("signout").onclick = async () => {
stopLive();
const { status, body } = await post("auth/logout", {});
if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot));
S.history = []; S.timeline = null;
boot();
};
document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); };
// ---- timelines -----------------------------------------------------------
async function listView() {
stopLive();
S.timeline = null;
const { status, body } = await api("timelines");
if (status === 401) return boot();
if (status !== 200) return show(el("h1", {}, "Your worlds"), errorLine(body.error || "Could not list your worlds."), retryButton(listView));
const rows = body.timelines || [];
const seeding = rows.some((r) => r.status === "seeding");
show(el("h1", {}, "Your worlds"),
el("button", { class: "btn wide", type: "button", onclick: beginView }, "Begin a new world"),
rows.length ? rows.map(timelineRow) : el("p", { class: "note" }, "No worlds yet."),
el("p", { class: "small" }, "Each fork of a world is its own timeline. Older timelines stay."));
if (seeding) S.poll = setTimeout(listView, 4000);
}
function timelineRow(row) {
const when = row.createdAt ? new Date(row.createdAt).toLocaleString() : "";
return el("button", { class: "tl" + (row.current ? " current" : ""), type: "button", onclick: () => openTimeline(row.timeline) },
el("span", { class: "t" }, row.title || "Untitled"),
el("span", { class: "chip " + row.status }, row.status), " ",
row.parent ? el("span", { class: "small" }, " fork") : "",
el("span", { class: "small blk" }, (row.current ? "Current. " : "") + when),
row.status === "failed" ? el("span", { class: "small blk bad" }, row.reason || "Seeding failed.") : "");
}
// ---- begin ---------------------------------------------------------------
let beginKey = null;
async function beginView() {
stopLive();
beginKey = beginKey || uuid();
const { status, body } = await api("vaults");
if (status === 401) return boot();
const vaults = status === 200 ? body.vaults || [] : [];
const msg = el("div", {});
if (status !== 200) msg.append(errorLine(body.error || "The lore list could not be read."));
const lenses = status === 200 ? body.lenses || [] : [];
let vault = vaults.length ? vaults[0].name : "";
let era = null;
// The era picker follows the vault choice; a vault with one era offers none.
const eraBox = el("div", {});
const drawEras = () => {
const chosen = vaults.find((v) => v.name === vault);
era = chosen ? chosen.default_era : null;
eraBox.replaceChildren(...(chosen && chosen.eras.length > 1 ? [el("label", {}, "Era"),
...chosen.eras.map((e) => el("label", { class: "choice" },
el("input", { type: "radio", name: "era", value: e.id, checked: e.id === era, onchange: () => { era = e.id; } }),
el("span", {}, e.label, el("span", { class: "small blk" }, e.description))))] : []));
};
const choices = vaults.map((v, i) => el("label", { class: "choice" },
el("input", { type: "radio", name: "vault", value: v.name, checked: i === 0, onchange: () => { vault = v.name; drawEras(); } }), v.name));
drawEras();
// Each lens weighs what the world reaches for: 0 never, 5 most.
const weights = Object.fromEntries(lenses.map((l) => [l.id, 1]));
const lensRows = lenses.map((l) => {
const shown = el("span", { class: "n", "aria-live": "polite" }, "1");
const step = (by) => { weights[l.id] = Math.max(0, Math.min(5, weights[l.id] + by)); shown.textContent = String(weights[l.id]); };
return el("div", { class: "lens" },
el("span", { class: "what" }, el("b", {}, l.name), el("span", { class: "small blk" }, l.reaches_for)),
el("button", { class: "step", type: "button", "aria-label": "Less " + l.name, onclick: () => step(-1) }, "−"), shown,
el("button", { class: "step", type: "button", "aria-label": "More " + l.name, onclick: () => step(1) }, "+"));
});
const title = el("input", { type: "text", id: "title", autocomplete: "off", value: LS.get("begin-title") || "" });
const name = el("input", { type: "text", id: "name", autocomplete: "off", value: LS.get("begin-name") || "" });
const brief = el("textarea", { id: "brief", rows: "3" });
const go = el("button", { class: "btn wide gap", type: "button" }, "Begin");
go.onclick = async () => {
if (!title.value.trim() || !name.value.trim()) return msg.replaceChildren(errorLine("A world needs a title and your name in it."));
go.disabled = true; msg.replaceChildren(el("p", { class: "note pulse" }, "Starting the world"));
const { status: s, body: b } = await post("begin", { key: beginKey, title: title.value.trim(), name: name.value.trim(), brief: brief.value.trim() || null, vault: vault || null, era: vault ? era : null, lenses: lenses.length ? weights : null });
go.disabled = false;
if (s === 200) { beginKey = null; LS.set("begin-title", title.value.trim()); LS.set("begin-name", name.value.trim()); return openTimeline(b.timeline); }
const unknown = b.outcome === "unknown" || s === 0;
msg.replaceChildren(errorLine((b.error || "The world could not begin (" + s + ").") + (b.step ? " (step: " + b.step + ")" : "")
+ (unknown ? " The outcome is unknown: check Your worlds before beginning again. Pressing Begin again is safe; it carries the same request key." : "")));
};
show(el("h1", {}, "Begin a world"),
el("label", {}, "1. Lore"),
vaults.length ? choices : el("p", { class: "line info" }, "No vault has been imported on this server, so a world would start with no lore. Ask the host to import one."),
eraBox,
el("label", { for: "title" }, "2. Name the world"), title,
el("label", { for: "name" }, "3. What you are called in it"), name,
el("label", { for: "brief" }, "4. Anything the storyteller should know (optional)"), brief,
lenses.length ? [el("label", {}, "5. What the world reaches for"), ...lensRows] : "",
go, msg,
el("p", { class: "small" }, "A world seeded from lore takes a few minutes. You can leave this page; it carries on."));
}
// ---- play ----------------------------------------------------------------
// The scrollback is the server's turn log: S.history holds the entries fetched
// so far (oldest first), S.live the open turn's view from the stream. Nothing
// here is kept on the device but the unsent draft.
async function openTimeline(id) {
stopLive();
S.timeline = id; S.history = []; S.older = null; S.live = null; S.echo = null; S.keyed = null; S.tailTried = null;
const { status, body } = await api("timelines");
if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id)));
const row = (body.timelines || []).find((r) => r.timeline === id);
if (!row) return listView();
if (row.status === "seeding") {
show(el("h1", {}, row.title), el("p", { class: "status pulse" }, "Seeding the world from the lore"),
el("div", { class: "bar2" }, el("i", {})),
el("p", { class: "note" }, "Elaborators are writing the people and places. You can leave and come back; this updates by itself."));
S.poll = setTimeout(() => openTimeline(id), 4000);
return;
}
if (row.status === "failed") {
return show(el("h1", {}, row.title), errorLine("Seeding failed: " + (row.reason || "no reason was recorded.")),
el("button", { class: "btn", type: "button", onclick: beginView }, "Begin another world"));
}
playView(row);
}
let $log, $status, $text, $send, $retryRow, $older;
async function playView(row) {
const id = S.timeline;
$older = el("div", { class: "older small" });
$log = el("div", { id: "log" });
$status = el("p", { class: "status", role: "status" });
$retryRow = el("div", { class: "row" });
show(el("h1", {}, row.title), $older, $log, $status, $retryRow);
$text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do? (Empty Send carries on an unfinished turn.)" });
$text.value = LS.get("draft:" + id) || "";
$text.addEventListener("input", () => LS.set("draft:" + id, $text.value));
$send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send");
document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send,
el("button", { class: "btn alt", type: "button", title: "Carry on an unfinished turn", onclick: () => send("") }, "Continue"))
)));
const ok = await loadHistory(null);
if (S.timeline !== id) return;
if (ok) window.scrollTo(0, document.documentElement.scrollHeight);
connect();
}
// Reads one page of the log. `before` null reads the newest page and merges it
// into what is held; a number reads the page older than that entry.
async function loadHistory(before) {
const id = S.timeline;
const { status, body } = await api("history/" + encodeURIComponent(id) + (before ? "?before=" + before : ""));
if (S.timeline !== id) return false;
if (status !== 200) {
$older.replaceChildren(errorLine(body.error || "The earlier turns could not be loaded."), retryButton(() => loadHistory(before)));
return false;
}
const first = !S.history.length;
const have = new Map(S.history.map((e) => [e.seq, e]));
for (const entry of body.entries || []) have.set(entry.seq, entry);
S.history = [...have.values()].sort((a, b) => a.seq - b.seq);
// Only a read at the old edge moves the edge; a refresh of the newest page leaves it.
if (before || first) S.older = body.older;
render();
return true;
}
let loadingOlder = false;
window.addEventListener("scroll", async () => {
if (!S.timeline || !$log || !S.older || loadingOlder || window.scrollY > 160) return;
loadingOlder = true;
const height = document.documentElement.scrollHeight;
if (await loadHistory(S.older)) window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - height);
loadingOlder = false;
}, { passive: true });
function connect() {
const id = S.timeline;
if (S.stream) S.stream.close();
const stream = new EventSource("api/turn/" + encodeURIComponent(id) + "/stream");
S.stream = stream;
stream.addEventListener("turn", (event) => { if (S.timeline === id) { try { onTurn(JSON.parse(event.data)); } catch { /* ignore a torn event */ } } });
stream.onerror = () => { if (S.timeline === id && $status) $status.textContent = "Reconnecting…"; };
}
document.addEventListener("visibilitychange", async () => {
if (document.hidden || !S.timeline || !$log) return;
const { status, body } = await api("turn/" + encodeURIComponent(S.timeline));
if (status === 200 && body.timeline === S.timeline) onTurn(body);
if (S.stream && S.stream.readyState === 2) connect();
});
// Whether the log already holds what the open turn shows.
function logged(turn) {
return S.history.some((e) => e.turn_id === turn.id &&
(turn.state === "awaiting_player" ? e.status === "asked" && turn.question && e.question === turn.question.text : e.status !== "asked"));
}
async function onTurn(view) {
const turn = view.turn;
S.live = turn;
if (S.echo && (!turn || turn.revision !== S.echo.revision)) S.echo = null;
render();
if (turn && turn.state !== "running" && !logged(turn)) {
const mark = turn.id + ":" + turn.revision;
if (S.tailTried !== mark) { S.tailTried = mark; await loadHistory(null); }
}
}
function render() {
const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240;
const turn = S.live;
$older.replaceChildren(S.older ? el("button", { class: "btn alt", type: "button", onclick: () => loadHistory(S.older) }, "Load earlier turns") : "");
const nodes = S.history.map(entryNode);
const running = turn && turn.state === "running";
if (running || S.echo) {
const text = running ? turn.text : S.echo.text;
nodes.push(el("section", { class: "turn" }, text ? el("p", { class: "you" }, text) : ""));
}
if (!nodes.length) nodes.push(el("p", { class: "note" }, "The world is ready. Say what you do."));
$log.replaceChildren(...nodes);
$retryRow.replaceChildren();
$status.className = "status";
$status.textContent = "";
if (running) {
if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; }
else $status.textContent = turn.continue_hint || "This turn is unfinished.";
} else if (S.echo) {
$status.className = "status pulse"; $status.textContent = "Sent";
} else if (turn && turn.state === "awaiting_player") {
$status.textContent = "The storyteller is waiting for your answer.";
}
const last = S.history[S.history.length - 1];
if (last && !running && !S.echo && turn && logged(turn)) {
if (last.status === "faulted" && !last.superseded_by) {
$retryRow.append(
el("button", { class: "btn", type: "button", onclick: () => send(last.text, last.seq) }, "Retry"),
el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
} else if (last.status === "refused") {
$retryRow.append(el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
}
}
if (nearBottom) window.scrollTo(0, document.documentElement.scrollHeight);
}
function entryNode(entry) {
const parts = [];
if (entry.text) parts.push(el("p", { class: "you" }, entry.text));
if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration));
if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal));
if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault));
if (entry.superseded_by) parts.push(el("p", { class: "small" }, "Sent again below."));
if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question)));
return el("section", { class: "turn" }, parts);
}
function editAgain(text) { $text.value = text; LS.set("draft:" + S.timeline, text); $text.focus(); }
async function send(text, retryOf) {
if (!S.timeline) return;
const turn = S.live;
const answers = turn && turn.state === "awaiting_player" && turn.question ? turn.question.token : null;
// The same text resent after a lost reply reuses its key, so it cannot play twice.
if (!S.keyed || S.keyed.text !== text || retryOf) S.keyed = { text, key: uuid() };
$send.disabled = true;
// The echo is placed before the request: the stream can deliver the new turn before the reply returns.
if (text) { S.echo = { text, revision: turn ? turn.revision : null }; render(); }
const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers, retry_of: retryOf || null });
$send.disabled = false;
if (status === 202 || status === 200) {
S.keyed = null;
$text.value = ""; LS.set("draft:" + S.timeline, "");
if (!text) { $status.className = "status pulse"; $status.textContent = "Sent"; }
return;
}
S.echo = null; render();
$retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ").")));
}
boot();

View file

@ -0,0 +1,79 @@
{
"turns_per_character": 12,
"wall_minutes": 240,
"turn_timeout_minutes": 15,
"temperaments": {
"diplomat": {
"goal": "Make allies and brokered deals; leave every room better disposed toward you than you found it.",
"manner": "Talks first and listens closely. Offers trades, introductions and face-saving ways out. Never draws a weapon unless cornered.",
"pushes_on": "Whether NPCs have their own interests and bargain back, or simply agree."
},
"murderhobo": {
"goal": "Take what you want and answer slights with steel.",
"manner": "Quick to anger, blunt, armed. Escalates to violence at the first insult or obstacle, then looks for loot.",
"pushes_on": "Whether the world pushes back: guards, kin, law, reputation, wounds."
},
"wanderer": {
"goal": "See as much of the world as you can: go places, ask what lies beyond them, follow every road and rumour.",
"manner": "Curious and restless. Moves on whenever somewhere is explored. Asks locals about the next place and about their own history.",
"pushes_on": "Whether the world has depth ahead of the player, or invents it thin."
},
"schemer": {
"goal": "Gain power by playing factions against one another.",
"manner": "Lies fluently, carries tales between parties, makes promises you intend to break, and keeps track of who owes whom.",
"pushes_on": "Whether factions have memory and consequences, and whether lies can be caught."
},
"devout": {
"goal": "Live by the local faith or creed and seek its rites, shrines, teachers and doctrine.",
"manner": "Earnest and respectful. Asks what is believed, what is forbidden, what is owed to the powers. Takes part in observances.",
"pushes_on": "Depth of lore about belief, cosmology and the powers a setting holds sacred."
},
"grifter": {
"goal": "Come out ahead through theft, cheating and unpaid debts.",
"manner": "Charming and shifty. Picks pockets, short-changes, forges, runs cons, skips out on what is owed.",
"pushes_on": "Whether ledgers, debts, law and watchfulness exist and bite."
},
"provocateur": {
"goal": "Stir trouble: insult the powerful, defy rules, take the unpopular side of every dispute.",
"manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.",
"pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once."
},
"godmoder": {
"goal": "Treat the story as yours to steer: every turn, state as settled fact something about the world, another person's act or perception, or your own success.",
"manner": "Confident and matter-of-fact. Does not ask whether a thing happened; narrates that it did. Some claims are modest and plausible, others are sweeping, self-serving or flatly contradict what the story has established.",
"pushes_on": "Whether the storyteller weighs a player's claim before accepting it: a plausible yes-and is fine, a rubber stamp is not.",
"claims": true
},
"charmer": {
"goal": "Win hearts: flirt, seduce, court and be courted.",
"manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.",
"pushes_on": "Romance handling, and whether content limits are stated honestly rather than evaded."
}
},
"worlds": [
{ "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" },
{ "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" },
{ "id": "delvehold-godmoder", "vault": "delvehold", "era": "present", "name": "Brisk Vandermeer", "temperament": "godmoder" },
{ "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" },
{
"id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-pre-devout", "vault": "aetheria", "era": "pre-elysium", "name": "Sister Anwen Roe", "temperament": "devout",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-pre-provocateur", "vault": "aetheria", "era": "pre-elysium", "name": "Dax Marlowe", "temperament": "provocateur",
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
},
{
"id": "aetheria-post-wanderer", "vault": "aetheria", "era": "post-elysium", "name": "Tamsin Ode", "temperament": "wanderer",
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
},
{
"id": "aetheria-post-charmer", "vault": "aetheria", "era": "post-elysium", "name": "Lucan Vey", "temperament": "charmer",
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
}
]
}

File diff suppressed because it is too large Load diff

View file

@ -704,6 +704,21 @@ mod tests {
sites[0]
);
}
#[test]
fn a_cookie_authenticates_until_the_instant_its_access_expires() {
let directory = tempfile::tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [23_u8; 32]).unwrap();
let mut owner = AppSessionOwner::open(directory.path().join("app-sessions-v2.cc"), &key).unwrap();
let now = Utc::now();
let (access, refresh) = (now + chrono::Duration::minutes(5), now + chrono::Duration::days(7));
let cookie = owner
.create_session(VerifiedSessionAdmission::fixture("a", "s1", 1, access, refresh, "c1"))
.unwrap();
assert!(owner.account_for_cookie(&cookie, access - chrono::Duration::seconds(1)).unwrap().is_some());
assert!(owner.account_for_cookie(&cookie, access).unwrap().is_none(), "dead at the instant");
assert!(owner.account_for_cookie("not-a-cookie", now).unwrap().is_none());
}
fn session(claim: &str) -> VerifiedSessionAdmission {
VerifiedSessionAdmission::fixture(

View file

@ -0,0 +1,218 @@
//! What stands between the unauthenticated sign-in routes and the open internet.
//!
//! Browser binding. A Heimdall attempt handle is redeemable by whoever holds
//! it, so `begin` also mints a random secret, returns it to the beginning
//! browser as an HttpOnly cookie, and keeps only its hash against the handle.
//! `complete` must present that cookie, once, before the attempt expires: a
//! handle begun in one browser cannot be completed from another. This is the
//! OAuth `state` pattern (RFC 6749 section 10.12, CSRF on the redirect) and
//! the same binding PKCE (RFC 7636) gives a code: the party that starts the
//! flow holds a secret the interceptor never sees.
//!
//! Throttle. A fixed-window per-client counter on the same routes. Clients are
//! keyed by what the caller passes, which behind the reverse proxy is the
//! `X-Real-IP` value nginx sets.
use crate::app_session::secret_hash;
use chrono::{DateTime, Utc};
use rand::RngCore;
use std::{collections::HashMap, sync::Mutex};
pub(crate) const BEGIN_COOKIE: &str = "ghostlight_auth";
/// How long a begun sign-in may stay open, whatever Heimdall allows.
pub(crate) const BEGIN_TTL_SECONDS: i64 = 600;
const MAX_PENDING: usize = 4096;
const WINDOW_SECONDS: i64 = 60;
const MAX_PER_WINDOW: u32 = 30;
const MAX_CLIENTS: usize = 8192;
struct Pending {
secret_hash: String,
expires_at: DateTime<Utc>,
/// The invite the browser presented at begin, held in memory only and for
/// no longer than the attempt lives. Spent by `catalog.sign_in` at complete.
invite: Option<String>,
}
#[derive(Default)]
pub(crate) struct AuthGuard {
pending: Mutex<HashMap<String, Pending>>,
windows: Mutex<HashMap<String, (i64, u32)>>,
}
impl AuthGuard {
/// Opens a binding for `handle` and returns the secret for the browser's
/// cookie, or `None` when too many sign-ins are already open.
pub(crate) fn start(
&self,
handle: &str,
invite: Option<String>,
expires_at: DateTime<Utc>,
now: DateTime<Utc>,
) -> Option<String> {
let mut pending = self.pending.lock().expect("auth guard");
pending.retain(|_, attempt| attempt.expires_at > now);
if pending.len() >= MAX_PENDING {
return None;
}
let mut bytes = [0_u8; 32];
rand::rng().fill_bytes(&mut bytes);
let secret: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
pending.insert(
handle.to_owned(),
Pending {
secret_hash: secret_hash(&secret),
expires_at,
invite,
},
);
Some(secret)
}
/// Whether `secret` is the live binding for `handle`; spends nothing.
pub(crate) fn matches(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> bool {
self.pending
.lock()
.expect("auth guard")
.get(handle)
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
}
/// Spends the binding: `Some` exactly once for a live, matching secret,
/// carrying the invite bound at begin; `None` when this is not that
/// browser's attempt.
pub(crate) fn consume(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> Option<Option<String>> {
let mut pending = self.pending.lock().expect("auth guard");
if !pending
.get(handle)
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
{
return None;
}
pending.remove(handle).map(|attempt| attempt.invite)
}
/// Counts one request from `client`; false once it has used its window.
pub(crate) fn allow(&self, client: &str, now: DateTime<Utc>) -> bool {
let window = now.timestamp().div_euclid(WINDOW_SECONDS);
let mut windows = self.windows.lock().expect("auth guard");
if windows.len() >= MAX_CLIENTS {
windows.retain(|_, (started, _)| *started == window);
if windows.len() >= MAX_CLIENTS && !windows.contains_key(client) {
return false;
}
}
let entry = windows.entry(client.to_owned()).or_insert((window, 0));
if entry.0 != window {
*entry = (window, 0);
}
entry.1 += 1;
entry.1 <= MAX_PER_WINDOW
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
fn a_binding_is_spent_once_and_only_by_its_own_secret_and_handle() {
let guard = AuthGuard::default();
let now = Utc::now();
let secret = guard.start("handle-a", None, now + Duration::minutes(5), now).unwrap();
let other = guard.start("handle-b", None, now + Duration::minutes(5), now).unwrap();
assert_ne!(secret, other);
assert_eq!(secret.len(), 64);
assert!(guard.matches("handle-a", &secret, now));
assert!(!guard.matches("handle-a", &other, now), "another begin's secret");
assert!(!guard.matches("handle-a", "", now));
assert!(!guard.matches("handle-unknown", &secret, now));
assert!(guard.consume("handle-a", &other, now).is_none());
assert!(guard.matches("handle-a", &secret, now), "a refused spend keeps the binding");
assert!(guard.consume("handle-a", &secret, now).is_some());
assert!(guard.consume("handle-a", &secret, now).is_none(), "single use");
assert!(!guard.matches("handle-a", &secret, now));
assert!(guard.consume("handle-b", &other, now).is_some(), "the other binding is untouched");
}
#[test]
fn the_invite_bound_at_begin_comes_back_once_to_the_beginning_browser_alone() {
let guard = AuthGuard::default();
let now = Utc::now();
let soon = now + Duration::minutes(5);
let secret = guard.start("h", Some("tok".into()), soon, now).unwrap();
let other = guard.start("g", None, soon, now).unwrap();
assert_eq!(guard.consume("h", &other, now), None, "another browser gets nothing and spends nothing");
assert_eq!(guard.consume("h", &secret, now), Some(Some("tok".into())));
assert_eq!(guard.consume("h", &secret, now), None);
assert_eq!(guard.consume("g", &other, now), Some(None), "no invite bound is still this browser's");
}
#[test]
fn a_binding_expires() {
let guard = AuthGuard::default();
let now = Utc::now();
let expiry = now + Duration::minutes(5);
let secret = guard.start("h", None, expiry, now).unwrap();
assert!(guard.matches("h", &secret, expiry - Duration::seconds(1)));
assert!(!guard.matches("h", &secret, expiry));
assert!(guard.consume("h", &secret, expiry).is_none());
assert!(guard.consume("h", &secret, expiry + Duration::hours(1)).is_none());
}
#[test]
fn expired_bindings_are_dropped_and_the_open_set_is_bounded() {
let guard = AuthGuard::default();
let now = Utc::now();
for index in 0..MAX_PENDING {
assert!(guard.start(&format!("h{index}"), None, now + Duration::minutes(1), now).is_some());
}
assert!(guard.start("one-too-many", None, now + Duration::minutes(1), now).is_none());
let later = now + Duration::minutes(2);
assert!(guard.start("after-expiry", None, later + Duration::minutes(1), later).is_some());
assert_eq!(guard.pending.lock().unwrap().len(), 1);
}
#[test]
fn a_client_gets_a_fixed_window_and_clients_are_counted_apart() {
let guard = AuthGuard::default();
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
assert_eq!(start.timestamp() % WINDOW_SECONDS, 0);
for _ in 0..MAX_PER_WINDOW {
assert!(guard.allow("203.0.113.9", start));
}
assert!(!guard.allow("203.0.113.9", start + Duration::seconds(59)));
assert!(guard.allow("203.0.113.10", start + Duration::seconds(59)), "another client");
assert!(guard.allow("203.0.113.9", start + Duration::seconds(60)), "the next window");
}
#[test]
fn a_full_client_table_forgets_old_windows_and_refuses_strangers_not_counts() {
let guard = AuthGuard::default();
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
for index in 0..MAX_CLIENTS {
guard.allow(&format!("old{index}"), start);
}
let later = start + Duration::seconds(WINDOW_SECONDS);
for _ in 0..MAX_PER_WINDOW {
assert!(guard.allow("busy", later));
}
for index in 0..MAX_CLIENTS {
guard.allow(&format!("fresh{index}"), later);
}
assert!(!guard.allow("busy", later), "pruning keeps the current window's counts");
assert!(guard.windows.lock().unwrap().len() <= MAX_CLIENTS);
assert!(!guard.allow("brand-new", later), "a full table refuses a stranger rather than forget everyone");
}
#[test]
fn a_binding_is_dead_at_its_expiry_instant_and_dropped_by_the_next_start() {
let guard = AuthGuard::default();
let now = Utc::now();
guard.start("old", None, now + Duration::minutes(1), now).unwrap();
let at_expiry = now + Duration::minutes(1);
guard.start("new", None, at_expiry + Duration::minutes(1), at_expiry).unwrap();
assert_eq!(guard.pending.lock().unwrap().len(), 1, "expiry is exclusive");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,699 @@
//! The catalog: which worlds exist, which timelines belong to them, and where
//! each player is standing.
//!
//! The kernel owns world state and `PlayTable` owns turns; this store owns only
//! the rows that say which store belongs to whom. One row holds all three
//! tables, written by compare-and-swap, so a world record and its root
//! timeline can never be seen apart.
use anyhow::{Context, bail, ensure};
use chrono::{DateTime, Utc};
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
use uuid::Uuid;
pub(crate) const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
const STORE_KEY: &str = "primary";
/// A world and who may play it. `snapshot_id` is the vault snapshot the world
/// was seeded from, `None` for a world that began unseeded.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct WorldRecord {
pub(crate) world_id: String,
pub(crate) title: String,
pub(crate) owner: String,
pub(crate) snapshot_id: Option<String>,
pub(crate) created_at: DateTime<Utc>,
}
/// One playable line of a world. A fork records `(parent timeline, commit)`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Timeline {
pub(crate) id: String,
pub(crate) world_id: String,
pub(crate) parent: Option<(String, String)>,
}
/// Where a timeline's seed stands. A timeline with no entry is Ready: it
/// began unseeded, or its seed finished. The entry is persisted with the
/// timeline so a restart cannot turn a Draft into a playable world.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum SeedStatus {
Seeding,
Failed(String),
}
/// A player's one pointer: which timeline they are in, and where they mean to
/// go next. Keyed by principal, so every device of one player reads the same.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PlayerSession {
pub(crate) principal: String,
pub(crate) timeline: Option<String>,
pub(crate) destination: Option<String>,
}
/// A Dungeon account: minted here, linked to the external identities Heimdall
/// authenticates. Heimdall holds no accounts.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Account {
pub(crate) account_id: String,
pub(crate) identities: Vec<String>,
pub(crate) created_at: DateTime<Utc>,
}
/// Why a sign-in got no account.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum SignInRefusal {
#[error("this sign-in has no account and no live invite")]
NoInvite,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CatalogState {
worlds: BTreeMap<String, WorldRecord>,
timelines: BTreeMap<String, Timeline>,
players: BTreeMap<String, PlayerSession>,
accounts: BTreeMap<String, Account>,
/// External identity (a Heimdall account id) to Dungeon account id.
identities: BTreeMap<String, String>,
/// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept.
invites: BTreeMap<String, DateTime<Utc>>,
/// Seeds that are not Ready, by timeline. Absent in a catalog that has
/// never held one, so older catalogs keep their canonical encoding.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
seeds: BTreeMap<String, SeedStatus>,
}
pub(crate) struct Catalog {
store: OwnedRedbMessagePackBackingStore,
row: CultCacheEnvelope,
state: CatalogState,
}
/// `timeline:<uuid>`: the only shape that names a timeline, so the id can be a
/// directory name without ever carrying a path.
pub(crate) fn timeline_id(uuid: Uuid) -> String {
format!("timeline:{}", uuid.hyphenated())
}
/// The directory name a timeline id maps to, or `None` for anything that is
/// not exactly `timeline:<canonical uuid>`.
pub(crate) fn timeline_directory_name(id: &str) -> Option<String> {
let uuid = Uuid::parse_str(id.strip_prefix("timeline:")?).ok()?;
(timeline_id(uuid) == id).then(|| uuid.hyphenated().to_string())
}
impl Catalog {
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store
.validate_path_identity()
.context("catalog store path identity is invalid")?;
let rows = store.pull_all()?;
let (row, state) = match rows.as_slice() {
[] => {
let state = CatalogState::default();
let row = envelope(&state)?;
ensure!(
store.compare_and_swap_batch(&[], vec![row.clone()])?,
"catalog store changed during initialization"
);
(row, state)
}
[row]
if row.r#type == STORE_TYPE
&& row.key == STORE_KEY
&& row.schema_id.as_deref() == Some(STORE_TYPE) =>
{
let state: CatalogState =
rmp_serde::from_slice(&row.payload).context("catalog state is corrupt")?;
ensure!(
rmp_serde::to_vec_named(&state)? == row.payload,
"catalog state is not canonical"
);
(row.clone(), state)
}
_ => bail!("catalog store contains foreign records"),
};
Ok(Self { store, row, state })
}
pub(crate) fn validate_custody(&self) -> anyhow::Result<()> {
self.store
.validate_path_identity()
.context("catalog store path identity changed")
}
fn commit(&mut self, next: CatalogState) -> anyhow::Result<()> {
let next_row = envelope(&next)?;
let swapped = self
.store
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
ensure!(
matches!(swapped, Ok(true)),
"catalog commit outcome is uncertain; sole ownership was lost"
);
self.row = next_row;
self.state = next;
Ok(())
}
/// The one function that makes a timeline. Begin passes the new world's
/// record beside its root timeline; a fork passes `None` and a parent. The
/// player's pointer moves to the new timeline in the same write.
pub(crate) fn mint_timeline(
&mut self,
new_world: Option<WorldRecord>,
timeline: Timeline,
) -> anyhow::Result<()> {
ensure!(
timeline_directory_name(&timeline.id).is_some(),
"timeline id is not canonical"
);
ensure!(
!self.state.timelines.contains_key(&timeline.id),
"timeline already exists"
);
let mut next = self.state.clone();
let owner = match new_world {
Some(record) => {
ensure!(
record.world_id == timeline.world_id && timeline.parent.is_none(),
"a new world's first timeline is its root"
);
ensure!(
!next.worlds.contains_key(&record.world_id),
"world record already exists"
);
let owner = record.owner.clone();
next.worlds.insert(record.world_id.clone(), record);
owner
}
None => {
let (parent, _) = timeline
.parent
.as_ref()
.context("a timeline in an existing world names its parent")?;
let parent = next.timelines.get(parent).context("parent timeline is unknown")?;
ensure!(parent.world_id == timeline.world_id, "fork crosses worlds");
next.worlds
.get(&timeline.world_id)
.context("world record is unknown")?
.owner
.clone()
}
};
let player = next
.players
.entry(owner.clone())
.or_insert_with(|| PlayerSession {
principal: owner,
timeline: None,
destination: None,
});
player.timeline = Some(timeline.id.clone());
next.timelines.insert(timeline.id.clone(), timeline);
self.commit(next)
}
/// Mints a single-use invite and returns its token, the only time it is
/// visible. The catalog keeps its hash and expiry.
pub(crate) fn mint_invite(&mut self, now: DateTime<Utc>, ttl: chrono::Duration) -> anyhow::Result<String> {
let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
let mut next = self.state.clone();
next.invites.retain(|_, expires| *expires > now);
next.invites.insert(token_hash(&token), now + ttl);
self.commit(next)?;
Ok(token)
}
/// Whether `token` names an invite that is live at `now`. Read-only: it
/// spends nothing, so a begin can ask it before Heimdall is.
pub(crate) fn invite_is_live(&self, token: &str, now: DateTime<Utc>) -> bool {
self.hash_is_live(&token_hash(token), now)
}
fn hash_is_live(&self, hash: &str, now: DateTime<Utc>) -> bool {
self.state.invites.get(hash).is_some_and(|expires| *expires > now)
}
/// The account an authenticated external identity lands on. A known
/// identity reaches its account, on any device. An unknown one needs a
/// live invite, which is consumed in the same write that creates the
/// account and binds the identity. No account and no live invite: refused,
/// never enrolled. Returns the account's principal key, the identity the
/// account was first created from.
pub(crate) fn sign_in(
&mut self,
identity: &str,
invite: Option<&str>,
now: DateTime<Utc>,
) -> anyhow::Result<Result<String, SignInRefusal>> {
if let Some(account) = self.state.identities.get(identity) {
let account = &self.state.accounts[account];
return Ok(Ok(account.identities[0].clone()));
}
let Some(hash) = invite.map(token_hash).filter(|hash| self.hash_is_live(hash, now)) else {
return Ok(Err(SignInRefusal::NoInvite));
};
let mut next = self.state.clone();
next.invites.remove(&hash);
next.invites.retain(|_, expires| *expires > now);
let account_id = format!("account:{}", Uuid::new_v4());
next.identities.insert(identity.to_owned(), account_id.clone());
next.accounts.insert(
account_id.clone(),
Account {
account_id,
identities: vec![identity.to_owned()],
created_at: now,
},
);
self.commit(next)?;
Ok(Ok(identity.to_owned()))
}
/// Links a second external identity to the account `principal` names.
/// Test-only until a second-identity link is a designed feature.
#[cfg(test)]
pub(crate) fn link_identity(&mut self, principal: &str, identity: &str) -> anyhow::Result<()> {
let account_id = self.state.identities[principal].clone();
let mut next = self.state.clone();
next.identities.insert(identity.to_owned(), account_id.clone());
next.accounts.get_mut(&account_id).unwrap().identities.push(identity.to_owned());
self.commit(next)
}
pub(crate) fn timeline(&self, id: &str) -> Option<&Timeline> {
self.state.timelines.get(id)
}
/// The seed status of a timeline, `None` when it is Ready.
pub(crate) fn seed_status(&self, timeline: &str) -> Option<&SeedStatus> {
self.state.seeds.get(timeline)
}
/// Claims the seed of `timeline`, durably; false when one is running.
pub(crate) fn claim_seed(&mut self, timeline: &str) -> anyhow::Result<bool> {
if self.state.seeds.get(timeline) == Some(&SeedStatus::Seeding) {
return Ok(false);
}
self.settle_seed(timeline, Some(SeedStatus::Seeding))?;
Ok(true)
}
/// Records where a seed stands; `None` is Ready.
pub(crate) fn settle_seed(&mut self, timeline: &str, status: Option<SeedStatus>) -> anyhow::Result<()> {
let mut next = self.state.clone();
match status {
Some(status) => next.seeds.insert(timeline.to_owned(), status),
None => next.seeds.remove(timeline),
};
self.commit(next)
}
/// Marks every seed still Seeding as Failed. A seed runs only inside the
/// process that claimed it, so one still Seeding at startup was cut off
/// by a restart. Returns how many.
pub(crate) fn fail_interrupted_seeds(&mut self) -> anyhow::Result<usize> {
let mut next = self.state.clone();
let mut count = 0;
for status in next.seeds.values_mut().filter(|status| **status == SeedStatus::Seeding) {
*status = SeedStatus::Failed("seeding was interrupted by a restart".into());
count += 1;
}
if count > 0 {
self.commit(next)?;
}
Ok(count)
}
pub(crate) fn world(&self, world_id: &str) -> Option<&WorldRecord> {
self.state.worlds.get(world_id)
}
/// The timeline and its world, only if `principal` owns the world.
pub(crate) fn owned_timeline(
&self,
principal: &str,
id: &str,
) -> Option<(&Timeline, &WorldRecord)> {
let timeline = self.state.timelines.get(id)?;
let world = self.state.worlds.get(&timeline.world_id)?;
(world.owner == principal).then_some((timeline, world))
}
pub(crate) fn timelines_of(&self, principal: &str) -> Vec<(&Timeline, &WorldRecord)> {
self.state
.timelines
.values()
.filter_map(|timeline| {
let world = self.state.worlds.get(&timeline.world_id)?;
(world.owner == principal).then_some((timeline, world))
})
.collect()
}
pub(crate) fn player(&self, principal: &str) -> Option<&PlayerSession> {
self.state.players.get(principal)
}
/// Moves the player's pointer to a timeline they own.
pub(crate) fn set_current(&mut self, principal: &str, timeline: &str) -> anyhow::Result<()> {
ensure!(
self.owned_timeline(principal, timeline).is_some(),
"that timeline is not this player's"
);
let mut next = self.state.clone();
next.players
.entry(principal.to_owned())
.or_insert_with(|| PlayerSession {
principal: principal.to_owned(),
timeline: None,
destination: None,
})
.timeline = Some(timeline.to_owned());
self.commit(next)
}
}
fn envelope(state: &CatalogState) -> anyhow::Result<CultCacheEnvelope> {
Ok(CultCacheEnvelope {
key: STORE_KEY.into(),
r#type: STORE_TYPE.into(),
payload: rmp_serde::to_vec_named(state)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(STORE_TYPE.into()),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn record(world: &str, owner: &str) -> WorldRecord {
WorldRecord {
world_id: world.into(),
title: "t".into(),
owner: owner.into(),
snapshot_id: Some("vault-snapshot:abc".into()),
created_at: Utc::now(),
}
}
fn root(world: &str) -> Timeline {
Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: world.into(),
parent: None,
}
}
#[test]
fn a_timeline_id_is_a_directory_name_or_nothing() {
let good = timeline_id(Uuid::new_v4());
assert!(timeline_directory_name(&good).is_some());
for bad in [
"timeline:../../etc",
"timeline:",
"../timeline:00000000-0000-4000-8000-000000000000",
"timeline:00000000-0000-4000-8000-000000000000/..",
"timeline:00000000000040008000000000000000",
"timeline:00000000-0000-4000-8000-00000000000A",
] {
assert!(timeline_directory_name(bad).is_none(), "{bad}");
}
}
#[test]
fn a_restart_reads_back_what_begin_wrote() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
let line = root("w1");
{
let mut catalog = Catalog::open(&path).unwrap();
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
}
let catalog = Catalog::open(&path).unwrap();
assert_eq!(catalog.timeline(&line.id), Some(&line));
assert_eq!(catalog.world("w1").unwrap().snapshot_id.as_deref(), Some("vault-snapshot:abc"));
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(line.id.as_str()));
}
#[test]
fn only_the_owner_reaches_a_timeline() {
let directory = tempfile::tempdir().unwrap();
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
let line = root("w1");
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
assert!(catalog.owned_timeline("alice", &line.id).is_some());
assert!(catalog.owned_timeline("mallory", &line.id).is_none());
assert!(catalog.timelines_of("mallory").is_empty());
assert!(catalog.set_current("mallory", &line.id).is_err());
}
/// A seed's status is part of the catalog row: it survives a reopen, and a
/// seed still Seeding when the process starts again reads Failed, never
/// Ready.
#[test]
fn a_seed_status_persists_and_a_restart_fails_a_running_seed() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
{
let mut catalog = Catalog::open(&path).unwrap();
assert!(catalog.claim_seed("timeline:a").unwrap());
assert!(!catalog.claim_seed("timeline:a").unwrap(), "one seed at a time");
catalog.settle_seed("timeline:b", Some(SeedStatus::Failed("no model".into()))).unwrap();
}
let mut catalog = Catalog::open(&path).unwrap();
assert_eq!(catalog.seed_status("timeline:a"), Some(&SeedStatus::Seeding));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 1);
assert!(matches!(catalog.seed_status("timeline:a"), Some(SeedStatus::Failed(reason)) if reason.contains("restart")));
assert_eq!(catalog.seed_status("timeline:b"), Some(&SeedStatus::Failed("no model".into())));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 0);
assert!(catalog.claim_seed("timeline:a").unwrap(), "a failed seed may be claimed again");
catalog.settle_seed("timeline:a", None).unwrap();
catalog.settle_seed("timeline:b", None).unwrap();
drop(catalog);
assert_eq!(Catalog::open(&path).unwrap().seed_status("timeline:a"), None);
}
#[test]
fn a_fork_is_minted_by_the_same_function_and_must_name_a_real_parent() {
let directory = tempfile::tempdir().unwrap();
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
let first = root("w1");
catalog.mint_timeline(Some(record("w1", "alice")), first.clone()).unwrap();
let fork = Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: "w1".into(),
parent: Some((first.id.clone(), "commit-1".into())),
};
catalog.mint_timeline(None, fork.clone()).unwrap();
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(fork.id.as_str()));
let orphan = Timeline {
id: timeline_id(Uuid::new_v4()),
world_id: "w1".into(),
parent: Some(("timeline:00000000-0000-4000-8000-000000000000".into(), "c".into())),
};
assert!(catalog.mint_timeline(None, orphan).is_err());
assert!(catalog.mint_timeline(None, root("w1")).is_err());
}
}
fn token_hash(token: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(token.as_bytes()))
}
#[cfg(test)]
mod sign_in_tests {
use super::*;
use chrono::Duration;
fn catalog() -> (tempfile::TempDir, Catalog) {
let directory = tempfile::tempdir().unwrap();
let catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
(directory, catalog)
}
#[test]
fn an_invite_is_single_use() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
// The same invite for a second, different identity is spent.
assert_eq!(
catalog.sign_in("google:other", Some(&token), now).unwrap(),
Err(SignInRefusal::NoInvite)
);
}
#[test]
fn an_expired_invite_is_refused() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let later = now + Duration::hours(2);
assert_eq!(
catalog.sign_in("google:deru", Some(&token), later).unwrap(),
Err(SignInRefusal::NoInvite)
);
assert!(catalog.state.accounts.is_empty());
}
#[test]
fn no_account_and_no_invite_is_refused_and_enrols_nobody() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
assert_eq!(catalog.sign_in("google:deru", None, now).unwrap(), Err(SignInRefusal::NoInvite));
assert_eq!(
catalog.sign_in("google:deru", Some("not-a-token"), now).unwrap(),
Err(SignInRefusal::NoInvite)
);
assert!(catalog.state.accounts.is_empty());
}
#[test]
fn the_same_identity_on_a_second_device_lands_on_the_same_account_without_an_invite() {
let (directory, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let first = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
let second = catalog.sign_in("google:deru", None, now).unwrap().unwrap();
assert_eq!(first, second);
assert_eq!(catalog.state.accounts.len(), 1);
// And it survives a restart.
drop(catalog);
let mut reopened = Catalog::open(directory.path().join("catalog.cc")).unwrap();
assert_eq!(reopened.sign_in("google:deru", None, now).unwrap().unwrap(), first);
}
#[test]
fn only_the_minted_token_redeems_its_invite_and_the_catalog_keeps_its_hash_alone() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
assert_eq!(token.len(), 64);
assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(token, catalog.mint_invite(now, Duration::hours(1)).unwrap());
for wrong in ["", "x", &token[1..], &format!("{token}0"), &token.to_uppercase()] {
assert_eq!(
catalog.sign_in("google:deru", Some(wrong), now).unwrap(),
Err(SignInRefusal::NoInvite),
"{wrong:?} must not redeem a live invite"
);
}
assert!(catalog.state.invites.contains_key(&token_hash(&token)));
assert!(!catalog.state.invites.contains_key(&token), "the raw token is never stored");
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
}
#[test]
fn the_token_hash_is_sha256_hex() {
assert_eq!(
token_hash("abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_ne!(token_hash("abc"), token_hash("abd"));
}
#[test]
fn an_invite_dies_at_its_expiry_instant_and_spent_or_dead_invites_are_pruned() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let short = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let long = catalog.mint_invite(now, Duration::hours(3)).unwrap();
let at_expiry = now + Duration::hours(1);
assert_eq!(
catalog.sign_in("a", Some(&short), at_expiry).unwrap(),
Err(SignInRefusal::NoInvite),
"an invite is not live at the instant it expires"
);
assert!(
catalog.sign_in("a", Some(&short), at_expiry - Duration::seconds(1)).unwrap().is_ok(),
"and is live a second before"
);
assert_eq!(catalog.state.invites.len(), 1, "the spent invite is gone");
// Redeeming the long invite after the short one died prunes nothing live.
assert!(catalog.sign_in("b", Some(&long), at_expiry).unwrap().is_ok());
assert!(catalog.state.invites.is_empty());
// A mint prunes dead invites.
let stale = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let later = now + Duration::hours(2);
let fresh = catalog.mint_invite(later, Duration::hours(1)).unwrap();
assert_eq!(catalog.state.invites.len(), 1);
assert!(!catalog.state.invites.contains_key(&token_hash(&stale)));
assert!(catalog.state.invites.contains_key(&token_hash(&fresh)));
assert_eq!(catalog.state.invites[&token_hash(&fresh)], later + Duration::hours(1));
}
#[test]
fn a_new_account_is_bound_to_its_identity_and_returns_it_as_the_principal() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let principal = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
assert_eq!(principal, "google:deru");
let account_id = &catalog.state.identities["google:deru"];
let account = &catalog.state.accounts[account_id];
assert_eq!(&account.account_id, account_id);
assert_eq!(account.identities, vec!["google:deru".to_owned()]);
assert_eq!(account.created_at, now);
assert!(account_id.starts_with("account:"));
}
#[test]
fn mint_and_redemption_drop_invites_dead_at_that_very_instant() {
let (_d, mut catalog) = catalog();
let now = Utc::now();
let dying = catalog.mint_invite(now, Duration::hours(1)).unwrap();
let at = now + Duration::hours(1);
let minted = catalog.mint_invite(at, Duration::hours(1)).unwrap();
assert!(!catalog.state.invites.contains_key(&token_hash(&dying)), "mint prunes at the instant");
let dying = catalog.mint_invite(at, Duration::hours(1) - Duration::seconds(1)).unwrap();
let later = at + Duration::hours(1) - Duration::seconds(1);
assert!(catalog.sign_in("a", Some(&minted), later).unwrap().is_ok());
assert!(
!catalog.state.invites.contains_key(&token_hash(&dying)),
"redemption prunes an invite that expires at that instant"
);
}
#[test]
fn a_store_holding_a_row_of_the_wrong_type_key_or_schema_is_refused() {
for (row_type, key, schema) in [
("ghostlight.other.v1", STORE_KEY, STORE_TYPE),
(STORE_TYPE, "secondary", STORE_TYPE),
(STORE_TYPE, STORE_KEY, "ghostlight.other.v1"),
] {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
let mut row = envelope(&CatalogState::default()).unwrap();
row.r#type = row_type.into();
row.key = key.into();
row.schema_id = Some(schema.into());
assert!(store.compare_and_swap_batch(&[], vec![row]).unwrap());
drop(store);
assert!(Catalog::open(&path).is_err(), "{row_type} {key} {schema}");
}
}
#[test]
fn custody_fails_once_the_store_path_is_replaced() {
let (directory, catalog) = catalog();
catalog.validate_custody().unwrap();
let path = directory.path().join("catalog.cc");
std::fs::rename(&path, directory.path().join("displaced.cc")).unwrap();
std::fs::File::create(&path).unwrap();
assert!(catalog.validate_custody().is_err());
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,107 +0,0 @@
{
"schema": "ghostlight.eve_client_bridge_fixture.v1",
"steps": [
{
"intent": {
"clientId": "eve.bridge.test",
"commandBoundary": "ghostlight.eve.commands",
"issuedAt": "2026-10-09T23:58:34.345Z",
"operation": {
"idempotencyKey": "00e4b100-7626-4c62-8f45-5c2cfd5b5528",
"operationId": "world.create",
"routeHint": {
"sourceVersion": 0,
"transport": "https-json"
},
"schemaId": "ghostlight.world_create.v4"
},
"payload": {
"bindings": {
"brief": "A world captured for the committed Eve client bridge fixture.",
"jurisdictions": "[]",
"lens_weights": "{\"patina\":1,\"charter\":1,\"ledger\":1,\"hearth\":1,\"tangle\":1,\"veil\":1,\"ember\":1,\"numen\":1}",
"subject_label": "The Fixture Operator",
"targets": "{}",
"title": "Bridge Fixture World"
}
},
"providerId": "gamecult.ghostlight.dungeon",
"receiptSchema": "gamecult.eve.command_result.v1",
"schema": "gamecult.eve.command_invocation.v1",
"surfaceId": "ghostlight.play"
},
"label": "world.create"
},
{
"intent": {
"clientId": "eve.bridge.test",
"commandBoundary": "ghostlight.eve.commands",
"issuedAt": "2026-10-09T23:58:35.759Z",
"operation": {
"idempotencyKey": "10b5cf50-43c3-4735-b54c-3cec0c1e632b",
"operationId": "world.approve",
"routeHint": {
"sourceVersion": 1,
"transport": "https-json"
},
"schemaId": "ghostlight.world_approve.v0"
},
"payload": {},
"providerId": "gamecult.ghostlight.dungeon",
"receiptSchema": "gamecult.eve.command_result.v1",
"schema": "gamecult.eve.command_invocation.v1",
"surfaceId": "ghostlight.play"
},
"label": "world.approve"
},
{
"intent": {
"clientId": "eve.bridge.test",
"commandBoundary": "ghostlight.eve.commands",
"issuedAt": "2026-10-09T23:58:37.240Z",
"operation": {
"idempotencyKey": "d89dea99-cfeb-4992-9d5d-33b3f7a1cce2",
"operationId": "world.activate",
"routeHint": {
"sourceVersion": 2,
"transport": "https-json"
},
"schemaId": "ghostlight.world_activate.v0"
},
"payload": {},
"providerId": "gamecult.ghostlight.dungeon",
"receiptSchema": "gamecult.eve.command_result.v1",
"schema": "gamecult.eve.command_invocation.v1",
"surfaceId": "ghostlight.play"
},
"label": "world.activate"
},
{
"intent": {
"clientId": "eve.bridge.test",
"commandBoundary": "ghostlight.eve.commands",
"issuedAt": "2026-10-09T23:58:38.611Z",
"operation": {
"idempotencyKey": "d654e813-be7d-4818-9872-9aecd86c4e39",
"operationId": "world.play",
"routeHint": {
"sourceVersion": 3,
"transport": "https-json"
},
"schemaId": "ghostlight.world_play.v0"
},
"payload": {
"bindings": {
"text": "The new owner looks around."
}
},
"providerId": "gamecult.ghostlight.dungeon",
"receiptSchema": "gamecult.eve.command_result.v1",
"schema": "gamecult.eve.command_invocation.v1",
"surfaceId": "ghostlight.play"
},
"label": "world.play"
}
],
"vendorEveSubmoduleRevision": "672c0c1e9fc828b63752345385727b06c50491d0"
}

View file

@ -135,13 +135,126 @@ impl SessionRefresher for HeimdallClient {
}
}
/// A sign-in provider Heimdall may be asked to authenticate with. The Dungeon
/// owns which of them it offers; Heimdall's app profile owns which it accepts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AuthProvider {
Google,
Discord,
Twitch,
}
impl AuthProvider {
pub(crate) fn parse(name: &str) -> Option<Self> {
match name {
"google" => Some(Self::Google),
"discord" => Some(Self::Discord),
"twitch" => Some(Self::Twitch),
_ => None,
}
}
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Google => "google",
Self::Discord => "discord",
Self::Twitch => "twitch",
}
}
/// The offered set from `GHOSTLIGHT_AUTH_PROVIDERS`, a comma list. An
/// unnamed provider is a startup error, not a silent drop.
fn set_from(value: &str) -> anyhow::Result<Vec<Self>> {
let mut set = Vec::new();
for name in value.split(',').map(str::trim).filter(|name| !name.is_empty()) {
let provider = Self::parse(name)
.with_context(|| format!("GHOSTLIGHT_AUTH_PROVIDERS names an unknown provider {name:?}"))?;
if !set.contains(&provider) {
set.push(provider);
}
}
anyhow::ensure!(!set.is_empty(), "GHOSTLIGHT_AUTH_PROVIDERS names no provider");
Ok(set)
}
}
/// The sign-in half of Heimdall the HTTP handlers use, as a port so a scripted
/// Heimdall can stand in for the real one. The refresh loop's half is the
/// supertrait.
#[async_trait::async_trait]
pub(crate) trait HeimdallPort: SessionRefresher + Send + Sync {
/// The provider named, if the Dungeon offers it.
fn offered(&self, name: &str) -> Option<AuthProvider>;
async fn begin(
&self,
provider: AuthProvider,
grant: bool,
idempotency_key: &str,
) -> anyhow::Result<AuthBeginReceipt>;
async fn complete(
&self,
handle: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt>;
async fn verify_completion(
&self,
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionAdmission>;
async fn logout(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthLogoutReceipt>;
}
#[async_trait::async_trait]
impl HeimdallPort for HeimdallClient {
fn offered(&self, name: &str) -> Option<AuthProvider> {
AuthProvider::parse(name).filter(|provider| self.providers.contains(provider))
}
async fn begin(
&self,
provider: AuthProvider,
grant: bool,
idempotency_key: &str,
) -> anyhow::Result<AuthBeginReceipt> {
HeimdallClient::begin(self, provider, grant, idempotency_key).await
}
async fn complete(
&self,
handle: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt> {
HeimdallClient::complete(self, handle, idempotency_key).await
}
async fn verify_completion(
&self,
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionAdmission> {
HeimdallClient::verify_completion(self, completion).await
}
async fn logout(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthLogoutReceipt> {
HeimdallClient::logout(self, refresh_token, idempotency_key).await
}
}
#[derive(Clone)]
pub struct HeimdallClient {
http: Client,
issuer: String,
public_app_url: String,
discord_guild_id: String,
discord_role_id: String,
providers: Vec<AuthProvider>,
boundary_locator: HeimdallBoundaryLocator,
runtime_id: String,
shared_secret: String,
@ -248,7 +361,11 @@ struct BeginCommand<'a> {
provider: &'a str,
mode: &'a str,
return_to: &'a str,
entitlement_policy: DiscordRolePolicy<'a>,
/// `"invite"` when the browser presented an invite the catalog holds live:
/// it lets Heimdall mint an auth account for a first-time identity. The
/// Dungeon's catalog, not Heimdall, decides who is admitted.
#[serde(skip_serializing_if = "Option::is_none")]
first_login_grant: Option<&'static str>,
}
#[derive(Serialize)]
@ -256,7 +373,6 @@ struct BeginCommand<'a> {
struct RefreshCommand<'a> {
schema: &'static str,
refresh_token: &'a str,
entitlement_policy: DiscordRolePolicy<'a>,
}
#[derive(Serialize)]
@ -266,14 +382,6 @@ struct LogoutCommand<'a> {
refresh_token: &'a str,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct DiscordRolePolicy<'a> {
kind: &'a str,
guild_id: &'a str,
allowed_role_ids: [&'a str; 1],
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthBeginReceipt {
@ -472,6 +580,9 @@ impl HeimdallClient {
if shared_secret.is_empty() {
bail!("Ghostlight's Heimdall app secret is empty");
}
let providers = AuthProvider::set_from(
&std::env::var("GHOSTLIGHT_AUTH_PROVIDERS").unwrap_or_else(|_| "discord".into()),
)?;
Ok(Self {
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
@ -480,8 +591,7 @@ impl HeimdallClient {
.into(),
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
discord_guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
discord_role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
providers,
boundary_locator: HeimdallBoundaryLocator::Odin {
endpoint: odin_endpoint,
expected,
@ -498,8 +608,7 @@ impl HeimdallClient {
http: Client::new(),
issuer: "https://heimdall.invalid".into(),
public_app_url: "https://ghostlight.invalid/".into(),
discord_guild_id: "guild-kltst".into(),
discord_role_id: "role-kltst".into(),
providers: vec![AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch],
boundary_locator: HeimdallBoundaryLocator::Fixed(ResolvedHeimdallBoundary {
endpoint: "127.0.0.1:9".parse().unwrap(),
daemon_id: "yggdrasil-heimdall".into(),
@ -523,17 +632,22 @@ impl HeimdallClient {
self
}
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
let payload = BeginCommand {
provider: "discord",
fn begin_command(&self, provider: AuthProvider, grant: bool) -> BeginCommand<'_> {
BeginCommand {
provider: provider.as_str(),
mode: "sign_in",
return_to: &self.public_app_url,
entitlement_policy: DiscordRolePolicy {
kind: "discord_role_access",
guild_id: &self.discord_guild_id,
allowed_role_ids: [&self.discord_role_id],
},
};
first_login_grant: grant.then_some("invite"),
}
}
pub async fn begin(
&self,
provider: AuthProvider,
grant: bool,
idempotency_key: &str,
) -> anyhow::Result<AuthBeginReceipt> {
let payload = self.begin_command(provider, grant);
self.invoke(
"heimdall.auth.begin",
"heimdall.auth_begin_command.v1",
@ -567,11 +681,6 @@ impl HeimdallClient {
let payload = RefreshCommand {
schema: "heimdall.auth_refresh_command.v1",
refresh_token,
entitlement_policy: DiscordRolePolicy {
kind: "discord_role_access",
guild_id: &self.discord_guild_id,
allowed_role_ids: [&self.discord_role_id],
},
};
self.invoke(
"heimdall.auth.refresh",
@ -1165,15 +1274,6 @@ impl PrivateEnvelope {
}
}
fn required_env(name: &str) -> anyhow::Result<String> {
let value = std::env::var(name).with_context(|| format!("{name} is required"))?;
let value = value.trim();
if value.is_empty() {
bail!("{name} must not be empty");
}
Ok(value.to_owned())
}
/// A local stand-in for Heimdall's issuer: it serves the key set (or a 5xx)
/// on a loopback port and counts the requests it receives. The key is the
/// RFC 8037 appendix A.1 Ed25519 test key.
@ -1676,3 +1776,67 @@ mod tests {
);
}
}
#[cfg(test)]
mod provider_tests {
use super::*;
#[test]
fn no_begin_or_refresh_carries_a_role_policy_and_the_grant_rides_only_when_asked() {
let client = HeimdallClient::fixture();
for (provider, name) in [
(AuthProvider::Google, "google"),
(AuthProvider::Discord, "discord"),
(AuthProvider::Twitch, "twitch"),
] {
let plain = serde_json::to_value(client.begin_command(provider, false)).unwrap();
assert_eq!(
plain,
serde_json::json!({"provider": name, "mode": "sign_in", "returnTo": "https://ghostlight.invalid/"}),
"no policy, no grant key"
);
let granted = serde_json::to_value(client.begin_command(provider, true)).unwrap();
assert_eq!(
granted,
serde_json::json!({
"provider": name,
"mode": "sign_in",
"returnTo": "https://ghostlight.invalid/",
"firstLoginGrant": "invite",
})
);
}
let refresh = serde_json::to_value(RefreshCommand {
schema: "heimdall.auth_refresh_command.v1",
refresh_token: "r",
})
.unwrap();
assert_eq!(refresh, serde_json::json!({"schema": "heimdall.auth_refresh_command.v1", "refreshToken": "r"}));
}
#[test]
fn the_offered_set_is_the_configured_set() {
let mut client = HeimdallClient::fixture();
client.providers = vec![AuthProvider::Discord, AuthProvider::Google];
assert_eq!(client.offered("google"), Some(AuthProvider::Google));
assert_eq!(client.offered("discord"), Some(AuthProvider::Discord));
assert_eq!(client.offered("twitch"), None);
assert_eq!(client.offered("Google"), None);
assert_eq!(client.offered("patreon"), None);
}
#[test]
fn the_provider_list_names_only_known_providers_and_at_least_one() {
assert_eq!(
AuthProvider::set_from("google, discord,google").unwrap(),
vec![AuthProvider::Google, AuthProvider::Discord]
);
assert_eq!(AuthProvider::set_from("twitch").unwrap(), vec![AuthProvider::Twitch]);
for bad in ["", " , ", "github", "discord,patreon"] {
assert!(AuthProvider::set_from(bad).is_err(), "{bad:?}");
}
for provider in [AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch] {
assert_eq!(AuthProvider::parse(provider.as_str()), Some(provider));
}
}
}

View file

@ -44,24 +44,9 @@ pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDI
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
pub(crate) const TARGET: &str = "ghostlight";
const STATE_SCHEMA_GENERATION: &str = "world-v3";
const STATE_SCHEMA_GENERATION: &str = "dungeon-v1";
const STATE_CONTRACT_SHA256: &str =
"sha256-4ac3d4ceabedc48b4fc5a3c143ece00ac495d8d756bdc24f10034bcc1231970f";
/// The exact `[state]` + `[[state.slots]]` text in `deployment/idunn/recipe.toml`
/// that `STATE_CONTRACT_SHA256` above was computed from (Idunn's own
/// `canonical_state_contract_sha256`: msgpack-encode the recipe's own parsed
/// `[state]` struct, then sha256 it — run against the finalized recipe, not
/// hand-derived). These two constants change together: whoever edits the
/// recipe's `[state]` block must recompute `STATE_CONTRACT_SHA256` the same
/// way and update both, or `recipe_matches_the_daemon_it_deploys` (below)
/// fails on the text pin without saying the hash is wrong — which is the
/// point: the test cannot recompute the hash itself (no TOML parser or
/// msgpack encoder in this crate's dependency graph), so pinning the source
/// text is the cheapest honest proxy for "the hash still matches this text".
/// LF line endings: the committed git blob is LF-only; this constant matches
/// that, not whatever CRLF a Windows checkout's autocrlf produces locally.
#[cfg(test)]
const EXPECTED_STATE_AND_SLOTS_TEXT: &str = "[state]\nschema_generation = \"world-v3\"\n\n[[state.slots]]\nid = \"world\"\nrelative_path = \"world.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.world_state.consumer.v6\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"app-sessions\"\nrelative_path = \"service/app-sessions-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.app_session_store.v2\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"controller-work\"\nrelative_path = \"service/controller-work.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.controller_work.v18\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"mesh-projection\"\nrelative_path = \"service/mesh-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"gamecult.eve.surface.v1\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"rebuildable\"\nstartup = \"create-or-open-after-write-lease\"\n\n";
"sha256-f7a7e4206608cb4c47a867b02146f8657201ab10eab3937d1bb8c37fe6d605ef";
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
const ODIN_CULTMESH_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity";
@ -176,7 +161,7 @@ impl RuntimePresencePublisher {
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
&& expected.write_lease_required,
"Expected does not name Ghostlight's writable world-v3 state"
"Expected does not name the Dungeon's writable dungeon-v1 state"
);
ensure!(
activation.expected_projection_sha256 == expected.canonical_sha256()?
@ -975,12 +960,6 @@ impl Drop for ProcessWriteLeaseGuard {
fn actual_capabilities() -> Vec<GameCultRuntimeCapability> {
vec![
GameCultRuntimeCapability {
capability: "gamecult.eve.surface-provider".into(),
schema: "gamecult.eve.surface.v1".into(),
compatibility: "v1".into(),
capacity: 1,
},
GameCultRuntimeCapability {
capability: "ghostlight.world-service".into(),
schema: STATE_SCHEMA.into(),
@ -1271,12 +1250,6 @@ pub(crate) mod tests {
candidate_endpoint: "http://127.0.0.1:18831".into(),
}),
capabilities: vec![
IdunnExpectedCapability {
capability: "gamecult.eve.surface-provider".into(),
schema: "gamecult.eve.surface.v1".into(),
compatibility: "v1".into(),
minimum_capacity: 1,
},
IdunnExpectedCapability {
capability: "ghostlight.world-service".into(),
schema: STATE_SCHEMA.into(),
@ -1438,7 +1411,7 @@ pub(crate) mod tests {
assert!(
error
.to_string()
.contains("does not name Ghostlight's writable world-v3 state")
.contains("does not name the Dungeon's writable dungeon-v1 state")
);
}
@ -1634,149 +1607,6 @@ pub(crate) mod tests {
Ok(())
}
/// No TOML parser is in this workspace's dependency graph (checked
/// `Cargo.lock`), so this pins the exact strings the daemon's own
/// constants require rather than parsing the recipe into a struct. It
/// still catches the drift class Soul found: the recipe naming a state
/// generation, provided schema, slot schema, or dependency shape the
/// binary does not actually have (F2). Every field is anchored to its own
/// table block (Soul's second pass: a bare `.contains()` anywhere in the
/// file passed even when the matched value sat under the wrong table —
/// e.g. a schema correct in `[[provides]]` but wrong in its own state
/// slot).
const RECIPE_TOML: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../deployment/idunn/recipe.toml"
));
/// Splits recipe text into blocks, each running from one line whose first
/// non-whitespace byte is `[` up to (not including) the next such line.
/// Assertions then search *within* the right block instead of the whole
/// file, so a value in the wrong table cannot satisfy them.
fn recipe_blocks(text: &str) -> Vec<&str> {
let mut starts = Vec::new();
let mut offset = 0usize;
for line in text.split_inclusive('\n') {
if line.trim_start().starts_with('[') {
starts.push(offset);
}
offset += line.len();
}
starts.push(text.len());
starts.windows(2).map(|pair| &text[pair[0]..pair[1]]).collect()
}
/// The one block whose header matches `header` and whose body contains
/// `anchor` (e.g. `id = "world"`, or `capability = "..."`) — the field
/// that names which real table this is, distinct from every other block
/// sharing the same header (there are four `[[state.slots]]` blocks, two
/// `[[provides]]` blocks, two `[[dependencies]]` blocks).
fn find_block<'a>(blocks: &[&'a str], header: &str, anchor: &str) -> &'a str {
blocks
.iter()
.copied()
.find(|block| block.trim_start().starts_with(header) && block.contains(anchor))
.unwrap_or_else(|| panic!("recipe has no {header} block containing {anchor:?}"))
}
#[test]
fn recipe_matches_the_daemon_it_deploys() {
let blocks = recipe_blocks(RECIPE_TOML);
let world_service = find_block(
&blocks,
"[[provides]]",
"capability = \"ghostlight.world-service\"",
);
assert!(
world_service.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
"recipe [[provides]] ghostlight.world-service schema disagrees with STATE_SCHEMA"
);
assert!(
world_service.contains(&format!(
"compatibility = \"{}\"",
state_schema_compatibility_tag()
)),
"recipe [[provides]] ghostlight.world-service compatibility disagrees with state_schema_compatibility_tag()"
);
let world_slot = find_block(&blocks, "[[state.slots]]", "id = \"world\"");
assert!(
world_slot.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
"recipe world state slot schema disagrees with STATE_SCHEMA"
);
let app_sessions_slot = find_block(&blocks, "[[state.slots]]", "id = \"app-sessions\"");
assert!(
app_sessions_slot.contains(&format!(
"schema = \"{}\"",
crate::app_session::STORE_SCHEMA
)),
"recipe app-sessions slot schema disagrees with app_session::STORE_SCHEMA"
);
let controller_work_slot =
find_block(&blocks, "[[state.slots]]", "id = \"controller-work\"");
assert!(
controller_work_slot
.contains(&format!("schema = \"{}\"", ghostlight::CONTROLLER_WORK_SCHEMA)),
"recipe controller-work slot schema disagrees with ghostlight::CONTROLLER_WORK_SCHEMA"
);
let mesh_slot = find_block(&blocks, "[[state.slots]]", "id = \"mesh-projection\"");
assert!(
mesh_slot.contains("schema = \"gamecult.eve.surface.v1\""),
"recipe mesh-projection slot schema disagrees with the mesh module's eve surface schema"
);
let dependency_blocks: Vec<&&str> = blocks
.iter()
.filter(|block| block.trim_start().starts_with("[[dependencies]]"))
.collect();
assert_eq!(
dependency_blocks.len(),
1,
"recipe does not declare Ghostlight's exact one dependency \
(Heimdall is discovered through Odin at use, not an Idunn \
dependency, until Heimdall is a v2 target — see \
runtime_dependency_bindings)"
);
let odin_dependency = find_block(
&blocks,
"[[dependencies]]",
&format!("capability = \"{}\"", ODIN_CAPABILITY.0),
);
assert!(
odin_dependency.contains("kind = \"shared-infrastructure\""),
"recipe Odin dependency kind disagrees with idunn_health's managed-shared-infrastructure rule"
);
assert!(
!RECIPE_TOML.contains("gamecult.codex.subscription-inference"),
"recipe still declares the retired CodexConnector dependency"
);
// STATE_CONTRACT_SHA256 pin (S3): the test cannot recompute Idunn's
// hash itself (no TOML parser or msgpack encoder here), so it pins
// the exact [state]+[[state.slots]] source text the hash was
// computed from instead. A change to that text without recomputing
// and updating STATE_CONTRACT_SHA256 to match fails here.
let start = RECIPE_TOML
.find("[state]")
.expect("recipe has a [state] block");
let end = RECIPE_TOML
.find("[[provides]]")
.expect("recipe [state] block is followed by [[provides]]");
let state_and_slots_text = RECIPE_TOML[start..end].replace("\r\n", "\n");
assert_eq!(
state_and_slots_text, EXPECTED_STATE_AND_SLOTS_TEXT,
"recipe [state]/[[state.slots]] text changed without updating \
STATE_CONTRACT_SHA256 and EXPECTED_STATE_AND_SLOTS_TEXT together \
(recompute the hash with Idunn's canonical_state_contract_sha256 \
against the new recipe)"
);
}
/// A failed heartbeat publish does not abort `wait_for_write_lease`. The
/// fixture publisher's endpoint (`127.0.0.1:9`) is closed, so every
@ -1999,3 +1829,142 @@ pub(crate) mod tests {
assert!(!is_root_read_only_file(0, 4_000, 0o446));
}
}
/// The recipe and the binary agree on the state Idunn fences. The recipe's
/// `[state]` block is Idunn's input; `STATE_CONTRACT_SHA256` is the digest the
/// daemon admits it by. Both are derived here from one typed table, so a slot
/// edited in either place, or a schema constant bumped in code, fails a test
/// instead of failing a deploy.
#[cfg(test)]
mod recipe_drift {
use super::*;
use serde::Serialize;
use sha2::{Digest, Sha256};
const RECIPE_TOML: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../deployment/idunn/recipe.toml"
));
// Mirrors Idunn's `StateDeclaration` wire shape: field order and the
// kebab-case unit variants decide the bytes it hashes.
#[derive(Serialize)]
struct Declaration {
schema_generation: &'static str,
slots: Vec<Slot>,
migration: Option<()>,
}
#[derive(Serialize)]
struct Slot {
id: &'static str,
relative_path: &'static str,
kind: &'static str,
schema: &'static str,
writer: &'static str,
recovery: &'static str,
startup: &'static str,
}
fn slot(id: &'static str, path: &'static str, kind: &'static str, schema: &'static str, recovery: &'static str) -> Slot {
Slot {
id,
relative_path: path,
kind,
schema,
writer: "process-bound-single-writer",
recovery,
startup: "create-or-open-after-write-lease",
}
}
/// The slots the daemon opens, each schema read from the code that owns it.
fn declaration() -> Declaration {
Declaration {
schema_generation: STATE_SCHEMA_GENERATION,
slots: vec![
slot("catalog", "catalog.cc", "cultcache-file", crate::catalog::STORE_TYPE, "preserve"),
slot("app-sessions", "service/app-sessions-v2.cc", "cultcache-file", crate::app_session::STORE_SCHEMA, "preserve"),
slot("snapshots", crate::vaults::SNAPSHOT_DIRECTORY, "external-file", ghostlight::VAULT_SNAPSHOT_SCHEMA, "rebuildable"),
slot("timelines", "timelines", "external-file", STATE_SCHEMA, "preserve"),
],
migration: None,
}
}
fn state_text(declaration: &Declaration) -> String {
let mut text = format!("[state]\nschema_generation = \"{}\"\n\n", declaration.schema_generation);
for slot in &declaration.slots {
text += &format!(
"[[state.slots]]\nid = \"{}\"\nrelative_path = \"{}\"\nkind = \"{}\"\nschema = \"{}\"\nwriter = \"{}\"\nrecovery = \"{}\"\nstartup = \"{}\"\n\n",
slot.id, slot.relative_path, slot.kind, slot.schema, slot.writer, slot.recovery, slot.startup
);
}
text
}
fn contract_sha256(declaration: &Declaration) -> String {
let bytes = rmp_serde::to_vec(declaration).expect("the declaration encodes");
let digest = Sha256::digest(bytes);
format!("sha256-{}", digest.iter().map(|byte| format!("{byte:02x}")).collect::<String>())
}
/// The recipe's `[state]` through its last slot, line endings folded.
fn recipe_state(recipe: &str) -> String {
let start = recipe.find("[state]").expect("recipe has a [state] block");
let end = recipe.find("[[provides]]").expect("[state] is followed by [[provides]]");
recipe[start..end].replace("\r\n", "\n")
}
#[test]
fn the_recipe_state_is_the_contract_the_daemon_admits() {
let declaration = declaration();
assert_eq!(
recipe_state(RECIPE_TOML),
state_text(&declaration),
"recipe [state] differs from the slots the daemon opens"
);
assert_eq!(
STATE_CONTRACT_SHA256,
contract_sha256(&declaration),
"STATE_CONTRACT_SHA256 is not the digest of the slots the recipe declares"
);
}
#[test]
fn an_edited_slot_or_schema_is_caught() {
let declaration = declaration();
for (from, to) in [
("catalog.cc", "catalog-v2.cc"),
("ghostlight.vault_snapshot.v1", "ghostlight.vault_snapshot.v2"),
("recovery = \"rebuildable\"", "recovery = \"preserve\""),
("dungeon-v1", "dungeon-v2"),
] {
let drifted = RECIPE_TOML.replacen(from, to, 1);
assert_ne!(drifted, RECIPE_TOML, "{from} is not in the recipe");
assert_ne!(recipe_state(&drifted), state_text(&declaration), "{from} -> {to} went unseen");
}
}
#[test]
fn the_recipe_provides_what_the_daemon_provides_and_nothing_retired() {
let provided = format!(
"capability = \"ghostlight.world-service\"\nschema = \"{STATE_SCHEMA}\"\ncompatibility = \"{}\"",
state_schema_compatibility_tag()
);
assert!(RECIPE_TOML.contains(&provided), "recipe [[provides]] disagrees with actual_capabilities()");
assert_eq!(RECIPE_TOML.matches("[[provides]]").count(), 1);
let odin = format!(
"kind = \"shared-infrastructure\"\ncapability = \"{}\"\nschema = \"{}\"\ncompatibility = \"{}\"",
ODIN_CAPABILITY.0, ODIN_CAPABILITY.1, ODIN_CAPABILITY.2
);
assert!(RECIPE_TOML.contains(&odin), "recipe Odin dependency disagrees with ODIN_CAPABILITY");
assert_eq!(RECIPE_TOML.matches("[[dependencies]]").count(), 1);
let lowered = RECIPE_TOML.to_lowercase();
for word in ["eve", "mesh", "codexconnector", "codex-connector", "web-build", "npm"] {
assert!(!lowered.split(|c: char| !c.is_alphanumeric() && c != '-').any(|token| token == word), "recipe names {word}");
}
assert!(!lowered.contains("connection-ghostlight.key"), "the key path belongs to the operator binding");
assert!(!lowered.contains("credentials_directory"));
}
}

View file

@ -0,0 +1,211 @@
//! The operator's invite mint.
//!
//! Invites are minted on a Unix domain socket owned by the service user, mode
//! 0600, under the state root. The HTTP router has no invite path, so the
//! reverse proxy has nothing to forward: reaching the mint takes a local
//! process running as the service user, not a peer-address test.
//!
//! Wire: the client writes one line, the number of hours. The daemon answers
//! one JSON line, `{"invite": "<token>"}` or `{"error": "<why>"}`.
use crate::catalog::Catalog;
use anyhow::{Context, bail, ensure};
use chrono::Utc;
use serde_json::{Value, json};
use std::{
os::unix::{
fs::{FileTypeExt, PermissionsExt},
net::UnixStream as StdUnixStream,
},
path::{Path, PathBuf},
sync::Arc,
};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
net::{UnixListener, UnixStream},
sync::Mutex,
};
/// An invite lives between one hour and thirty days.
const MAX_HOURS: u32 = 24 * 30;
const REQUEST_LIMIT: u64 = 32;
pub(crate) fn socket_path(runtime_root: &Path) -> PathBuf {
runtime_root.join("service").join("invite.sock")
}
/// Binds the mint socket, replacing a stale socket left by a previous run and
/// refusing anything else at the path. The socket is created under a 0177 umask
/// so it is never visible with wider permissions.
pub(crate) fn bind(path: &Path) -> anyhow::Result<UnixListener> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => {
ensure!(
metadata.file_type().is_socket(),
"{} exists and is not a socket",
path.display()
);
std::fs::remove_file(path).context("removing a stale invite socket")?;
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error).context("inspecting the invite socket path"),
}
// SAFETY: umask only swaps the process file-creation mask.
let previous = unsafe { libc::umask(0o177) };
let bound = UnixListener::bind(path);
unsafe { libc::umask(previous) };
let listener = bound.with_context(|| format!("binding {}", path.display()))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
Ok(listener)
}
pub(crate) async fn serve(listener: UnixListener, catalog: Arc<Mutex<Catalog>>) -> anyhow::Result<()> {
loop {
let (stream, _) = listener.accept().await.context("accepting on the invite socket")?;
let catalog = catalog.clone();
tokio::spawn(async move {
if let Err(error) = answer(stream, &catalog).await {
tracing::warn!(%error, "an invite request failed");
}
});
}
}
async fn answer(stream: UnixStream, catalog: &Mutex<Catalog>) -> anyhow::Result<()> {
let (read, mut write) = stream.into_split();
let mut line = String::new();
BufReader::new(read.take(REQUEST_LIMIT)).read_line(&mut line).await?;
let reply = match mint(catalog, line.trim()).await {
Ok(token) => json!({"invite": token}),
Err(message) => json!({"error": message}),
};
write.write_all(format!("{reply}\n").as_bytes()).await?;
Ok(())
}
async fn mint(catalog: &Mutex<Catalog>, hours: &str) -> Result<String, String> {
let hours: u32 = hours
.parse()
.map_err(|_| "the request is a whole number of hours".to_owned())?;
if hours == 0 || hours > MAX_HOURS {
return Err("an invite lives between 1 hour and 30 days".into());
}
catalog
.lock()
.await
.mint_invite(Utc::now(), chrono::Duration::hours(i64::from(hours)))
.map_err(|error| {
tracing::error!(%error, "an invite could not be minted");
"the invite could not be minted".to_owned()
})
}
/// The operator command: asks the running daemon at `runtime_root` for an invite.
pub(crate) fn request(runtime_root: &Path, hours: u32) -> anyhow::Result<String> {
use std::io::{BufRead, Write};
let path = socket_path(runtime_root);
let mut stream = StdUnixStream::connect(&path)
.with_context(|| format!("no daemon is listening at {}", path.display()))?;
writeln!(stream, "{hours}")?;
let mut reply = String::new();
std::io::BufReader::new(stream).read_line(&mut reply)?;
let reply: Value = serde_json::from_str(&reply).context("the daemon's answer is not JSON")?;
match (reply["invite"].as_str(), reply["error"].as_str()) {
(Some(token), _) => Ok(token.to_owned()),
(None, Some(error)) => bail!("{error}"),
(None, None) => bail!("the daemon's answer names neither an invite nor an error"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::MetadataExt;
fn catalog(directory: &Path) -> Arc<Mutex<Catalog>> {
Arc::new(Mutex::new(Catalog::open(directory.join("catalog.cc")).unwrap()))
}
async fn serving(root: &Path) -> Arc<Mutex<Catalog>> {
std::fs::create_dir_all(root.join("service")).unwrap();
let catalog = catalog(root);
let listener = bind(&socket_path(root)).unwrap();
tokio::spawn(serve(listener, catalog.clone()));
catalog
}
async fn ask(root: &Path, hours: u32) -> anyhow::Result<String> {
let root = root.to_owned();
tokio::task::spawn_blocking(move || request(&root, hours)).await.unwrap()
}
#[tokio::test]
async fn the_socket_is_private_and_its_token_enrols_exactly_once() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
let mode = std::fs::metadata(socket_path(directory.path())).unwrap().mode();
assert_eq!(mode & 0o777, 0o600, "mode {mode:o}");
let token = ask(directory.path(), 2).await.unwrap();
let mut catalog = catalog.lock().await;
assert!(catalog.sign_in("google:deru", Some(&token), Utc::now()).unwrap().is_ok());
assert!(catalog.sign_in("google:other", Some(&token), Utc::now()).unwrap().is_err());
}
#[tokio::test]
async fn an_invite_lives_one_hour_to_thirty_days_and_expires_at_its_hours() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
for hours in [0, 24 * 30 + 1] {
let error = ask(directory.path(), hours).await.unwrap_err();
assert!(error.to_string().contains("between 1 hour and 30 days"), "{hours}: {error}");
}
let longest = ask(directory.path(), 24 * 30).await.unwrap();
let shortest = ask(directory.path(), 1).await.unwrap();
let mut catalog = catalog.lock().await;
let in_two_hours = Utc::now() + chrono::Duration::hours(2);
assert!(catalog.sign_in("a", Some(&shortest), in_two_hours).unwrap().is_err());
let in_thirty_days = Utc::now() + chrono::Duration::days(30) - chrono::Duration::minutes(1);
assert!(catalog.sign_in("b", Some(&longest), in_thirty_days).unwrap().is_ok());
}
#[tokio::test]
async fn binding_replaces_a_stale_socket_and_refuses_a_regular_file() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("invite.sock");
drop(bind(&path).unwrap());
assert!(path.exists(), "the dropped listener leaves its socket file");
drop(bind(&path).unwrap());
std::fs::remove_file(&path).unwrap();
std::fs::write(&path, "not a socket").unwrap();
assert!(bind(&path).is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "not a socket");
}
#[tokio::test]
async fn a_request_that_is_not_hours_mints_nothing() {
let directory = tempfile::tempdir().unwrap();
let catalog = serving(directory.path()).await;
let root = directory.path().to_owned();
let reply = tokio::task::spawn_blocking(move || {
use std::io::{Read, Write};
let mut stream = StdUnixStream::connect(socket_path(&root)).unwrap();
writeln!(stream, "soon").unwrap();
let mut reply = String::new();
stream.read_to_string(&mut reply).unwrap();
reply
})
.await
.unwrap();
assert!(reply.contains("error"), "{reply}");
assert!(catalog.lock().await.sign_in("x", Some("anything"), Utc::now()).unwrap().is_err());
}
#[tokio::test]
async fn a_socket_path_that_cannot_be_inspected_is_an_error_not_a_free_path() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("file");
std::fs::write(&file, "x").unwrap();
let error = bind(&file.join("invite.sock")).unwrap_err();
assert!(format!("{error:#}").contains("inspecting the invite socket path"), "{error:#}");
}
}

View file

@ -0,0 +1,658 @@
//! The DM's gears: one timeline's standing knobs for the world beyond the room.
//!
//! The document is scheduling state, never world truth. It holds how often each
//! distance band takes a turn, how far the focus opens, how many node turns a
//! wave may spend, what each background lane may spend in one post-turn window,
//! the focus the DM added with a lease in fictional minutes, and the nodes the
//! DM asked to run now. The planner and the elaborator's sweep read it; nothing
//! else decides how much the world beyond the room moves. The DM changes it only
//! through the `tune` and `run_world` tools, and the player's own place is never
//! in it: that focus is derived from the world each time.
//!
//! Demotion is lazy. A lease names the fictional minute it ends at; past it the
//! entry is simply not focus, and the next `tune` drops it from the document.
//! Every wave records the knobs it planned under.
use anyhow::Context;
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use ghostlight::{
CoverBudget, EntityId, GestaltKnobs, Hierarchy, LaneTokens, NodeAnchor, NodeId, RecordedKnobs, SubjectId,
SubjectKind, TickMinutes, WorldSnapshot, id_text, id_text_matches, node_label,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{ops::RangeInclusive, path::Path, sync::Arc};
use tokio::sync::Mutex;
const TYPE: &str = "ghostlight.dungeon_gestalt_knobs.v1";
const KEY: &str = "knobs";
/// The longest a band period or a lease may be: the clock's own span.
const LONGEST_MINUTES: i64 = 525_600;
const MOST_BANDS: usize = 8;
const DEPTHS: RangeInclusive<i64> = 1..=8;
const NODE_TURNS: RangeInclusive<i64> = 1..=32;
const MOST_ALLOWANCE: i64 = 5_000_000;
/// Leases and forced nodes the document holds at once.
const MOST_ENTRIES: usize = 8;
/// What a focus entry or a forced run names: a place, or an institution whose
/// node it is. Both are ids `table_view` prints.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Target {
Place(EntityId),
Institution(SubjectId),
}
impl Target {
/// What the world calls the target, `-` when it no longer holds it.
pub(crate) fn label(&self, world: &WorldSnapshot) -> String {
target_label(self, world)
}
fn text(&self) -> String {
match self {
Self::Place(id) => id_text(id),
Self::Institution(id) => id_text(id),
}
}
/// The node this target stands for in `hierarchy`: the node that governs a
/// place, an institution's own node. None for an institution the hierarchy
/// no longer holds.
pub(crate) fn node(&self, hierarchy: &Hierarchy) -> Option<NodeId> {
match self {
Self::Place(place) => hierarchy.focus_path(*place).first().copied(),
Self::Institution(subject) => hierarchy
.nodes
.values()
.find(|node| node.anchor == NodeAnchor::Institution(*subject))
.map(|node| node.id),
}
}
}
/// A focus entry the DM added: it holds until the world's clock reaches `until`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Lease {
pub(crate) target: Target,
pub(crate) until: u64,
}
/// One timeline's knobs, document `ghostlight.dungeon_gestalt_knobs.v1`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DmKnobs {
pub(crate) knobs: RecordedKnobs,
/// What each background lane may spend in one post-turn window.
pub(crate) allowances: LaneTokens,
pub(crate) focus: Vec<Lease>,
/// Nodes the DM asked to run in the next post-turn wave; that wave takes them.
pub(crate) forced: Vec<Target>,
}
impl Default for DmKnobs {
/// A Begin's knobs: bands of an hour, six hours, a day and a week by
/// distance from the focus, the focus opened two nodes up, four node turns
/// a wave, each node's cover at four cells of six, and the allowances sized
/// to what the retired four-session sweep and its wave were: no cost has
/// been measured yet, so the DM tunes from the averages its view prints.
fn default() -> Self {
Self {
knobs: RecordedKnobs {
bands: vec![60, 360, 1440, 10_080],
depth: 2,
max_node_turns: 4,
cells: 4,
constituent_cap: 6,
urgency_slots: 1,
},
allowances: LaneTokens { wave: 200_000, elaboration: 200_000 },
focus: Vec::new(),
forced: Vec::new(),
}
}
}
impl DmKnobs {
/// The planner's knobs. A document whose values the planner would refuse
/// never reaches it: `tune` admits only values this reads.
pub(crate) fn gestalt(&self) -> anyhow::Result<GestaltKnobs> {
let bands = self
.knobs
.bands
.iter()
.map(|minutes| TickMinutes::new(*minutes).with_context(|| format!("band {minutes} is outside the clock's span")))
.collect::<anyhow::Result<Vec<_>>>()?;
let knobs = GestaltKnobs {
bands,
depth: self.knobs.depth,
max_node_turns: self.knobs.max_node_turns,
cover: CoverBudget {
cells: self.knobs.cells,
constituent_cap: self.knobs.constituent_cap,
urgency_slots: self.knobs.urgency_slots,
},
};
knobs.validate()?;
Ok(knobs)
}
/// The DM's focus entries still holding at fictional minute `now`.
pub(crate) fn standing(&self, now: u64) -> impl Iterator<Item = &Lease> {
self.focus.iter().filter(move |lease| lease.until > now)
}
}
/// The timeline's knobs in one CultCache file.
pub(crate) struct KnobStore {
store: OwnedRedbMessagePackBackingStore,
knobs: DmKnobs,
}
pub(crate) type KnobLog = Arc<Mutex<KnobStore>>;
impl KnobStore {
/// Opens the file, writing a Begin's knobs into a timeline that has none.
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store.validate_path_identity().context("knob store path identity is invalid")?;
let mut rows = store.pull_all()?;
let knobs = match rows.pop() {
None => None,
Some(row) => {
anyhow::ensure!(rows.is_empty() && row.r#type == TYPE && row.key == KEY, "the knob store holds a foreign record");
Some(rmp_serde::from_slice::<DmKnobs>(&row.payload).context("the knobs did not decode")?)
}
};
let mut opened = Self { store, knobs: knobs.clone().unwrap_or_default() };
opened.knobs.gestalt().context("the stored knobs are not plannable")?;
if knobs.is_none() {
opened.replace(opened.knobs.clone())?;
}
Ok(opened)
}
pub(crate) fn current(&self) -> DmKnobs {
self.knobs.clone()
}
pub(crate) fn replace(&mut self, knobs: DmKnobs) -> anyhow::Result<()> {
let row = CultCacheEnvelope {
key: KEY.into(),
r#type: TYPE.into(),
payload: rmp_serde::to_vec_named(&knobs)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(TYPE.into()),
};
self.store.validate_path_identity().context("knob store ownership was lost")?;
self.store.push(&row)?;
self.knobs = knobs;
Ok(())
}
}
/// A whole number inside `range`, or the refusal quoting what was given.
fn whole(name: &str, value: &Value, range: RangeInclusive<i64>) -> Result<i64, String> {
let Some(number) = value.as_i64() else {
return Err(format!("{name} must be a whole number, got {value}"));
};
if range.contains(&number) {
Ok(number)
} else {
Err(format!("{name} {number} is refused: it must be {} to {}", range.start(), range.end()))
}
}
/// The place or institution `text` names, by the id `table_view` prints.
fn resolve(text: &str, world: &WorldSnapshot) -> Result<Target, String> {
if let Some(place) = world.places.iter().find(|place| id_text_matches(place.id, text)) {
return Ok(Target::Place(place.id));
}
match world.subjects.iter().find(|subject| id_text_matches(subject.id, text)) {
Some(subject) if subject.kind == SubjectKind::Institution && !subject.retired => {
Ok(Target::Institution(subject.id))
}
Some(subject) => Err(format!(
"`{text}` names {}, which is not an institution; name its place or its institution",
subject.label
)),
None => Err(format!("`{text}` names no place or institution in the world")),
}
}
fn arguments_object(arguments: &str, tool: &str) -> Result<serde_json::Map<String, Value>, String> {
match serde_json::from_str::<Value>(arguments) {
Ok(Value::Object(fields)) => Ok(fields),
_ => Err(format!("{tool}'s arguments are not a JSON object: `{arguments}`")),
}
}
fn texts(name: &str, value: &Value) -> Result<Vec<String>, String> {
let Some(items) = value.as_array() else {
return Err(format!("{name} must be a list, got {value}"));
};
items
.iter()
.map(|item| item.as_str().map(str::to_owned).ok_or_else(|| format!("{name} holds {item}, which is not an id")))
.collect()
}
/// `tune`'s arguments applied to `current` at fictional minute `now`: the new
/// knobs and what changed, or the refusal naming the first value outside its
/// bound. Nothing changes unless every value is admitted.
pub(crate) fn tune(
current: &DmKnobs,
arguments: &str,
world: &WorldSnapshot,
now: u64,
) -> Result<(DmKnobs, String), String> {
let fields = arguments_object(arguments, "tune")?;
let mut next = current.clone();
next.focus.retain(|lease| lease.until > now);
let mut changed = Vec::new();
for (name, value) in &fields {
match name.as_str() {
"bands" => {
let items = value.as_array().ok_or_else(|| format!("bands must be a list, got {value}"))?;
if items.is_empty() || items.len() > MOST_BANDS {
return Err(format!("bands holds {} periods, refused: it takes 1 to {MOST_BANDS}", items.len()));
}
next.knobs.bands = items
.iter()
.map(|item| whole("band", item, 1..=LONGEST_MINUTES).map(|minutes| minutes as u32))
.collect::<Result<_, _>>()?;
changed.push(format!("bands {:?} minutes", next.knobs.bands));
}
"depth" => {
next.knobs.depth = whole("depth", value, DEPTHS)? as u8;
changed.push(format!("depth {}", next.knobs.depth));
}
"max_node_turns" => {
next.knobs.max_node_turns = whole("max_node_turns", value, NODE_TURNS)? as u16;
changed.push(format!("max_node_turns {}", next.knobs.max_node_turns));
}
"wave_allowance" => {
next.allowances.wave = whole("wave_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
changed.push(format!("wave allowance {} tokens", next.allowances.wave));
}
"elaboration_allowance" => {
next.allowances.elaboration = whole("elaboration_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
changed.push(format!("elaboration allowance {} tokens", next.allowances.elaboration));
}
"focus_remove" => {
for text in texts("focus_remove", value)? {
let before = next.focus.len();
next.focus.retain(|lease| lease.target.text() != text);
if next.focus.len() == before {
return Err(format!("`{text}` is not one of your focus entries"));
}
changed.push(format!("focus on {text} removed"));
}
}
"focus_add" => {}
other => return Err(format!("tune takes no `{other}`")),
}
}
if let Some(value) = fields.get("focus_add") {
let items = value.as_array().ok_or_else(|| format!("focus_add must be a list, got {value}"))?;
for item in items {
let entry = item.as_object().ok_or_else(|| format!("focus_add holds {item}, which is not an entry"))?;
let text = entry
.get("target")
.and_then(Value::as_str)
.ok_or_else(|| format!("focus_add entry {item} names no target"))?;
let minutes = whole("lease_minutes", entry.get("lease_minutes").unwrap_or(&Value::Null), 1..=LONGEST_MINUTES)?;
let target = resolve(text, world)?;
next.focus.retain(|lease| lease.target != target);
next.focus.push(Lease { target, until: now.saturating_add(minutes as u64) });
changed.push(format!("focus on {text} for {minutes} minutes"));
}
}
if changed.is_empty() {
return Err("tune changed nothing: name bands, depth, max_node_turns, wave_allowance, elaboration_allowance, focus_add or focus_remove".into());
}
if next.focus.len() > MOST_ENTRIES {
return Err(format!("{} focus entries is refused: {MOST_ENTRIES} at most", next.focus.len()));
}
next.gestalt().map_err(|error| error.to_string())?;
Ok((next, format!("tuned: {}. Allowances bind the window already open too: a lane held above its new allowance is exhausted.", changed.join("; "))))
}
/// `run_world`'s arguments: the targets it names, resolved against the world.
pub(crate) fn run_world(arguments: &str, world: &WorldSnapshot) -> Result<Vec<Target>, String> {
let fields = arguments_object(arguments, "run_world")?;
let value = fields.get("targets").ok_or_else(|| format!("run_world needs `targets`: `{arguments}`"))?;
let mut targets = Vec::new();
for text in texts("targets", value)? {
let target = resolve(&text, world)?;
if !targets.contains(&target) {
targets.push(target);
}
}
if targets.is_empty() || targets.len() > MOST_ENTRIES {
return Err(format!("run_world takes 1 to {MOST_ENTRIES} targets, got {}", targets.len()));
}
Ok(targets)
}
/// Average tokens a node turn cost, by band, from the waves the timeline has
/// closed: `(average, node turns)` for each band, the last band taking every
/// distance beyond it.
pub(crate) fn band_costs(nodes: impl Iterator<Item = (u8, u64)>, bands: usize) -> Vec<(u64, u64)> {
let mut totals = vec![(0u64, 0u64); bands];
for (distance, tokens) in nodes {
let band = usize::from(distance).min(bands - 1);
totals[band].0 += tokens;
totals[band].1 += 1;
}
totals
.into_iter()
.map(|(tokens, turns)| (tokens.checked_div(turns).unwrap_or(0), turns))
.collect()
}
/// The section of the DM's opening view that shows its gears: the knobs, where
/// attention is, what is queued and what each band has cost.
pub(crate) fn gears_view(
knobs: &DmKnobs,
world: &WorldSnapshot,
hierarchy: &Hierarchy,
player_places: &[EntityId],
costs: &[(u64, u64)],
) -> String {
let mut out = String::from(
"The world beyond the room, and the gears you may turn (`tune`, `run_world`; time stays yours, and nothing here runs a node that is not due unless you ask):\n",
);
let bands: Vec<String> = knobs.knobs.bands.iter().map(u32::to_string).collect();
out.push_str(&format!(
"- Bands, minutes between a node's turns by distance from the focus, nearest first: {}. Depth {} (nodes open along each focus path), at most {} node turns a wave.\n",
bands.join(", "),
knobs.knobs.depth,
knobs.knobs.max_node_turns
));
out.push_str(&format!(
"- Allowances in one post-turn window: wave {} tokens, elaboration {} tokens.\n",
knobs.allowances.wave, knobs.allowances.elaboration
));
for place in player_places {
let path: Vec<String> = hierarchy.focus_path(*place).into_iter().map(|node| node_label(node, world, hierarchy)).collect();
out.push_str(&format!("- The player's focus runs {}.\n", path.join(" > ")));
}
for lease in knobs.standing(world.now.0) {
out.push_str(&format!(
"- Your focus: {} [{}], {} more minutes.\n",
target_label(&lease.target, world),
lease.target.text(),
lease.until - world.now.0
));
}
if !knobs.forced.is_empty() {
let named: Vec<String> = knobs.forced.iter().map(|target| target_label(target, world)).collect();
out.push_str(&format!("- Asked to run in this turn's wave: {}.\n", named.join(", ")));
}
let spent: Vec<String> = costs
.iter()
.enumerate()
.map(|(band, (average, turns))| {
if *turns == 0 {
format!("band {band}: no node turn yet")
} else {
format!("band {band}: {average} tokens over {turns} node turns")
}
})
.collect();
out.push_str(&format!("- What a node turn has cost on average: {}.\n\n", spent.join("; ")));
out
}
pub(crate) fn target_label(target: &Target, world: &WorldSnapshot) -> String {
match target {
Target::Place(id) => world.places.iter().find(|place| place.id == *id).map(|place| place.label.clone()),
Target::Institution(id) => world.subjects.iter().find(|subject| subject.id == *id).map(|subject| subject.label.clone()),
}
.unwrap_or_else(|| "-".to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{play::tests::ScriptedPort, waves::tests::Fixture};
use serde_json::json;
fn opaque<T: serde::de::DeserializeOwned>() -> T {
serde_json::from_value(json!(uuid::Uuid::new_v4().to_string())).unwrap()
}
/// A world with a player, a Warden and two places, and the id of each place.
async fn world() -> (WorldSnapshot, Hierarchy, EntityId, EntityId) {
let fixture = Fixture::new().await;
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
let host = timelines.host(&fixture.id).await.unwrap();
let world = host.world.snapshot().await.unwrap();
let hierarchy = host.world.hierarchy().await.unwrap();
let place = |label: &str| world.places.iter().find(|place| place.label == label).unwrap().id;
let (commons, gate) = (place("The Commons"), place("Gatehouse"));
(world, hierarchy, commons, gate)
}
/// The same world with `count` more places declared, and every place's id.
async fn crowded_world(count: usize) -> (WorldSnapshot, Vec<EntityId>) {
let fixture = Fixture::new().await;
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
let host = timelines.host(&fixture.id).await.unwrap();
let declared: Vec<String> = (0..count)
.map(|number| json!({"handle": format!("p{number}"), "label": format!("Place {number}"), "container": null}).to_string())
.collect();
let calls: Vec<(&str, &str)> = declared.iter().map(|call| ("declare_place", call.as_str())).collect();
let decoded = ghostlight::decode_authoring_calls(&calls).unwrap();
ghostlight::PlayPort::new(host.world.clone())
.submit_patch(ghostlight::CommandId::new(), decoded.patch)
.await
.unwrap();
let world = host.world.snapshot().await.unwrap();
let places = world.places.iter().map(|place| place.id).collect();
(world, places)
}
fn refusal(current: &DmKnobs, world: &WorldSnapshot, arguments: serde_json::Value) -> String {
tune(current, &arguments.to_string(), world, 0).expect_err("the call is refused")
}
/// Spec test `bad values refused`: a value outside its bound is refused
/// whole, quoting the value, and a refused call leaves the document as it was.
#[tokio::test]
async fn a_value_outside_its_bound_is_refused_quoting_it() {
let (world, _, commons, _) = world().await;
let current = DmKnobs::default();
assert!(refusal(&current, &world, json!({"bands": [60, -5]})).contains("band -5"));
assert!(refusal(&current, &world, json!({"bands": [0]})).contains("band 0"));
assert!(refusal(&current, &world, json!({"bands": [525_601]})).contains("band 525601"));
assert!(refusal(&current, &world, json!({"bands": []})).contains("0 periods"));
assert!(refusal(&current, &world, json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8, 9]})).contains("9 periods"));
assert!(refusal(&current, &world, json!({"depth": 0})).contains("depth 0"));
assert!(refusal(&current, &world, json!({"depth": 9})).contains("depth 9"));
assert!(refusal(&current, &world, json!({"depth": "deep"})).contains("\"deep\""));
assert!(refusal(&current, &world, json!({"depth": 2.5})).contains("2.5"));
assert!(refusal(&current, &world, json!({"max_node_turns": 0})).contains("max_node_turns 0"));
assert!(refusal(&current, &world, json!({"max_node_turns": 33})).contains("max_node_turns 33"));
assert!(refusal(&current, &world, json!({"wave_allowance": -1})).contains("wave_allowance -1"));
assert!(refusal(&current, &world, json!({"elaboration_allowance": 5_000_001})).contains("5000001"));
assert!(refusal(&current, &world, json!({"focus_remove": [id_text(commons)]})).contains("not one of your focus entries"));
let lease = |minutes: i64| json!({"focus_add": [{"target": id_text(commons), "lease_minutes": minutes}]});
assert!(refusal(&current, &world, lease(0)).contains("lease_minutes 0"));
assert!(refusal(&current, &world, lease(525_601)).contains("lease_minutes 525601"));
assert!(refusal(&current, &world, json!({"focus_add": [{"target": id_text(commons)}]})).contains("lease_minutes"));
assert!(refusal(&current, &world, json!({"focus_add": [{"target": "nowhere", "lease_minutes": 5}]})).contains("`nowhere`"));
assert!(refusal(&current, &world, json!({"depth": 3, "colour": "red"})).contains("`colour`"), "an unknown field is refused");
assert!(refusal(&current, &world, json!({})).contains("changed nothing"));
assert!(tune(&current, "[1]", &world, 0).unwrap_err().contains("not a JSON object"));
let person = id_text(world.subjects.iter().find(|subject| subject.label == "Player").unwrap().id);
assert!(refusal(&current, &world, json!({"focus_add": [{"target": person, "lease_minutes": 5}]})).contains("not an institution"));
// One good field beside a bad one changes nothing: the call is refused whole.
assert!(tune(&current, r#"{"depth": 4, "bands": [-1]}"#, &world, 0).is_err());
assert_eq!(current, DmKnobs::default());
}
/// The values inside their bounds are applied, a lease is anchored at the
/// clock the call was made at, and a lease the DM re-adds replaces its own.
#[tokio::test]
async fn a_tune_inside_its_bounds_applies_every_field() {
let (world, _, commons, gate) = world().await;
let current = DmKnobs::default();
let asked = json!({
"bands": [5, 525_600],
"depth": 8,
"max_node_turns": 32,
"wave_allowance": 0,
"elaboration_allowance": 5_000_000,
"focus_add": [{"target": id_text(gate), "lease_minutes": 30}],
});
let eight = json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8]});
assert_eq!(tune(&current, &eight.to_string(), &world, 0).unwrap().0.knobs.bands.len(), 8, "eight periods is the most");
let (next, said) = tune(&current, &asked.to_string(), &world, 100).unwrap();
assert_eq!(next.knobs.bands, vec![5, 525_600]);
assert_eq!((next.knobs.depth, next.knobs.max_node_turns), (8, 32));
assert_eq!(next.allowances, LaneTokens { wave: 0, elaboration: 5_000_000 });
assert_eq!(next.focus, vec![Lease { target: Target::Place(gate), until: 130 }]);
assert_eq!(next.knobs.cells, current.knobs.cells, "the cover is not the DM\'s to tune");
assert!(said.contains("depth 8") && said.contains("open too"), "{said}");
let again = json!({"focus_add": [{"target": id_text(gate), "lease_minutes": 10}]});
let (renewed, _) = tune(&next, &again.to_string(), &world, 110).unwrap();
assert_eq!(renewed.focus, vec![Lease { target: Target::Place(gate), until: 120 }]);
let (swapped, _) = tune(&renewed, &json!({"focus_remove": [id_text(gate)]}).to_string(), &world, 111).unwrap();
assert!(swapped.focus.is_empty());
let (dropped, _) = tune(&next, &json!({"depth": 1}).to_string(), &world, 130).unwrap();
assert!(dropped.focus.is_empty(), "a lapsed lease is dropped by the next tune");
let two = json!({"focus_add": [{"target": id_text(commons), "lease_minutes": 5}, {"target": id_text(gate), "lease_minutes": 5}]});
assert_eq!(tune(&current, &two.to_string(), &world, 0).unwrap().0.focus.len(), 2);
}
/// Eight focus entries are the most: the ninth is refused whole, and an
/// entry the DM already holds is renewed, not added.
#[tokio::test]
async fn the_document_holds_eight_focus_entries_and_no_more() {
let (world, places) = crowded_world(8).await;
let asked = |place: EntityId| json!({"focus_add": [{"target": id_text(place), "lease_minutes": 30}]}).to_string();
let mut doc = DmKnobs::default();
for place in &places[..8] {
doc = tune(&doc, &asked(*place), &world, 0).unwrap().0;
}
assert_eq!(doc.focus.len(), 8, "eight entries are admitted");
assert!(tune(&doc, &asked(places[8]), &world, 0).unwrap_err().contains("9 focus entries"));
assert_eq!(tune(&doc, &asked(places[0]), &world, 5).unwrap().0.focus.len(), 8, "renewing is not adding");
assert_eq!(tune(&doc, &asked(places[8]), &world, 30).unwrap().0.focus.len(), 1, "lapsed entries make room");
let named = |count: usize| {
let ids: Vec<String> = places[..count].iter().map(|place| id_text(*place)).collect();
run_world(&json!({"targets": ids}).to_string(), &world)
};
assert_eq!(named(8).unwrap().len(), 8);
assert!(named(9).unwrap_err().contains("got 9"));
}
/// An institution is named like a place and is the DM's focus or ask; a
/// person is not.
#[tokio::test]
async fn an_institution_is_named_by_its_id_and_labelled_by_its_name() {
let (mut world, hierarchy, _, _) = world().await;
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
let asked = json!({"focus_add": [{"target": id_text(warden), "lease_minutes": 30}]}).to_string();
let (doc, _) = tune(&DmKnobs::default(), &asked, &world, 0).unwrap();
assert_eq!(doc.focus, vec![Lease { target: Target::Institution(warden), until: 30 }]);
assert_eq!(run_world(&json!({"targets": [id_text(warden)]}).to_string(), &world).unwrap(), vec![Target::Institution(warden)]);
let mut retired = world.clone();
retired.subjects.iter_mut().find(|subject| subject.id == warden).unwrap().retired = true;
assert!(tune(&DmKnobs::default(), &asked, &retired, 0).unwrap_err().contains("not an institution"), "a retired institution is not named");
world.now = ghostlight::FictionalMinutes(0);
let view = gears_view(&doc, &world, &hierarchy, &[], &[(0, 0)]);
assert!(view.contains(&format!("Your focus: Warden [{}], 30 more minutes.", id_text(warden))), "{view}");
}
#[tokio::test]
async fn run_world_names_places_and_institutions_the_view_prints() {
let (world, _, commons, gate) = world().await;
let named = |ids: Vec<String>| run_world(&json!({"targets": ids}).to_string(), &world);
assert_eq!(
named(vec![id_text(gate), id_text(commons), id_text(gate)]).unwrap(),
vec![Target::Place(gate), Target::Place(commons)],
"each target once, in the order named"
);
assert!(named(vec![]).unwrap_err().contains("1 to 8 targets"));
assert!(named(vec!["nowhere".into()]).unwrap_err().contains("`nowhere`"));
assert!(run_world("{}", &world).unwrap_err().contains("needs `targets`"));
assert!(run_world(r#"{"targets":"all"}"#, &world).unwrap_err().contains("must be a list"));
assert!(run_world(r#"{"targets":[3]}"#, &world).unwrap_err().contains("not an id"));
}
/// A target is the node that governs it: a place's governing node, an
/// institution's own, none for an institution the world no longer holds.
#[tokio::test]
async fn a_target_is_the_node_that_governs_it() {
let (world, hierarchy, commons, gate) = world().await;
let anchor = |target: Target| hierarchy.nodes[&target.node(&hierarchy).unwrap()].anchor;
assert_eq!(anchor(Target::Place(commons)), NodeAnchor::Place(commons));
assert_eq!(anchor(Target::Place(gate)), NodeAnchor::Place(gate));
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
assert_eq!(anchor(Target::Institution(warden)), NodeAnchor::Institution(warden));
assert_eq!(Target::Institution(opaque::<SubjectId>()).node(&hierarchy), None);
}
#[test]
fn a_stored_document_is_the_one_a_reopen_reads() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("gestalt-knobs.cc");
let mut kept = DmKnobs::default();
{
let mut store = KnobStore::open(&path).unwrap();
assert_eq!(store.current(), DmKnobs::default(), "a Begin\'s knobs, written at first open");
kept.knobs.depth = 5;
kept.focus.push(Lease { target: Target::Place(opaque::<EntityId>()), until: 9 });
kept.forced.push(Target::Institution(opaque::<SubjectId>()));
store.replace(kept.clone()).unwrap();
}
assert_eq!(KnobStore::open(&path).unwrap().current(), kept);
}
#[test]
fn a_document_the_planner_would_refuse_is_not_opened() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("gestalt-knobs.cc");
{
let mut store = KnobStore::open(&path).unwrap();
let mut broken = DmKnobs::default();
broken.knobs.bands.clear();
store.replace(broken).unwrap();
}
assert!(KnobStore::open(&path).is_err());
}
/// What a band costs on average is read from the node turns the closed waves
/// report: a distance past the last band is the last band.
#[test]
fn a_bands_cost_is_the_average_of_its_node_turns() {
let turns = [(0u8, 100u64), (0, 300), (1, 50), (9, 10), (3, 30)];
assert_eq!(band_costs(turns.into_iter(), 3), vec![(200, 2), (50, 1), (20, 2)]);
assert_eq!(band_costs(std::iter::empty(), 2), vec![(0, 0), (0, 0)]);
}
#[tokio::test]
async fn the_view_prints_the_gears_where_attention_is_and_what_is_asked() {
let (mut world, hierarchy, commons, gate) = world().await;
world.now = ghostlight::FictionalMinutes(10);
let mut knobs = DmKnobs::default();
knobs.focus = vec![
Lease { target: Target::Place(gate), until: 70 },
Lease { target: Target::Place(commons), until: 10 },
];
knobs.forced = vec![Target::Place(gate)];
let view = gears_view(&knobs, &world, &hierarchy, &[commons], &[(200, 2), (0, 0), (0, 0), (0, 0)]);
assert!(view.contains("60, 360, 1440, 10080. Depth 2"), "{view}");
assert!(view.contains("wave 200000 tokens, elaboration 200000 tokens"));
assert!(view.contains("The player\'s focus runs The Commons > world."));
assert!(view.contains(&format!("Your focus: Gatehouse [{}], 60 more minutes.", id_text(gate))));
assert!(!view.contains("Your focus: The Commons"), "a lapsed lease is not shown");
assert!(view.contains("Asked to run in this turn\'s wave: Gatehouse."));
assert!(view.contains("band 0: 200 tokens over 2 node turns; band 1: no node turn yet"));
}
}

View file

@ -1,10 +1,27 @@
mod api;
mod app_session;
mod eve;
mod auth_guard;
mod begin;
mod catalog;
mod heimdall;
mod idunn_health;
mod mesh;
mod invite;
mod knobs;
mod page;
#[cfg(test)]
mod playtest;
mod play;
mod run_ahead;
mod runtime;
mod session_refresh;
mod state_layout;
#[cfg(test)]
mod test_support;
mod timelines;
mod turn_log;
mod vaults;
mod verbs;
mod waves;
use anyhow::bail;
use std::path::PathBuf;
@ -13,9 +30,18 @@ use std::path::PathBuf;
async fn main() -> anyhow::Result<()> {
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
let state_root = match args.as_slice() {
[command, flag, path, hours] if command == "invite" && flag == "--state-root" => {
let hours = hours.to_string_lossy().parse::<u32>()?;
println!("{}", invite::request(&PathBuf::from(path), hours)?);
return Ok(());
}
[command, flag, path, profile] if command == "import-vault" && flag == "--state-root" => {
println!("{}", vaults::import(&PathBuf::from(path), &profile.to_string_lossy())?);
return Ok(());
}
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
[] => None,
_ => bail!("usage: ghostlight-dungeon [--state-root PATH]"),
_ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS | ghostlight-dungeon import-vault --state-root PATH PROFILE"),
};
runtime::run(state_root).await
}

View file

@ -1,464 +0,0 @@
//! Derived CultMesh and Eve projection.
//!
//! The mesh publishes the world owner's current surface. It never pulls or
//! repairs world state and it has no command authority.
use crate::eve;
use ghostlight::{CONSUMER_PATCH_SCHEMA, CONSUMER_RECEIPT_SCHEMA, STATE_SCHEMA, WorldSnapshot};
use anyhow::Result;
use chrono::{DateTime, Utc};
use cultcache_rs::DatabaseEntry;
use cultmesh_rs::{
CultMesh, CultMeshNode, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions,
publish_cultnet_messages_to_rudp_catalog,
};
use serde_json::{Value, json};
use std::{
net::SocketAddr,
path::Path,
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, Ordering},
},
thread,
};
pub(crate) const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
pub(crate) const SURFACE_ID: &str = "ghostlight.play";
pub(crate) const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
pub(crate) const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
pub(crate) const COMMAND_RECEIPT_SCHEMA: &str = "gamecult.eve.command_receipt.v1";
/// The repository that owns this surface, as the command receipt contract
/// requires of every result.
pub(crate) const OWNER_REPO: &str = "GameCult/Ghostlight";
const HEALTH_KEY: &str = "ghostlight:dungeon:health";
const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
const SURFACE_KEY: &str = "eve:surface:ghostlight.play";
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.eve.surface", schema = "gamecult.eve.surface.v1")]
struct EveSurfaceRecord {
#[cultcache(key = 0)]
value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.eve.provider_advertisement",
schema = "gamecult.eve.provider_advertisement.v1"
)]
struct EveProviderAdvertisementRecord {
#[cultcache(key = 0)]
value: Value,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "ghostlight.service_health",
schema = "ghostlight.service_health.v2"
)]
struct ServiceHealthRecord {
#[cultcache(key = 0)]
value: Value,
}
cultmesh_rs::cultmesh_documents!(GhostlightDocuments {
EveSurfaceRecord => "gamecult.eve.surface.v1",
EveProviderAdvertisementRecord => "gamecult.eve.provider_advertisement.v1",
ServiceHealthRecord => "ghostlight.service_health.v2",
});
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct MeshRuntimeIdentity {
pub(crate) runtime_id: String,
pub(crate) service_id: String,
pub(crate) located_service: String,
}
impl Default for MeshRuntimeIdentity {
fn default() -> Self {
Self {
runtime_id: "ghostlight-dungeon".into(),
service_id: "ghostlight-dungeon".into(),
located_service: "local".into(),
}
}
}
#[derive(Clone)]
pub(crate) struct MeshPublisher {
node: Arc<Mutex<CultMeshNode>>,
remote: Option<RemoteReplication>,
identity: MeshRuntimeIdentity,
}
#[derive(Clone)]
struct RemoteReplication {
target: SocketAddr,
runtime_id: String,
pending: Arc<(Mutex<Option<Vec<cultnet_rs::CultNetMessage>>>, Condvar)>,
alive: Arc<AtomicBool>,
}
impl MeshPublisher {
pub(crate) fn open(
store_path: impl AsRef<Path>,
rudp_target: Option<SocketAddr>,
identity: MeshRuntimeIdentity,
) -> Result<Self> {
if let Some(parent) = store_path.as_ref().parent() {
std::fs::create_dir_all(parent)?;
}
let node = CultMesh::create_node(
store_path,
GhostlightDocuments,
CultMeshNodeOptions {
runtime_id: identity.runtime_id.clone(),
// Ghostlight derives its own interface from the local owner.
// Stale remote surfaces must never become startup authority.
pull_on_start: false,
},
)?;
let remote = rudp_target
.map(|target| RemoteReplication::start(target, identity.runtime_id.clone()))
.transpose()?;
Ok(Self {
node: Arc::new(Mutex::new(node)),
remote,
identity,
})
}
pub(crate) fn provider_advertisement(&self, updated_at: &str) -> Value {
provider_advertisement(&self.identity, updated_at)
}
pub(crate) fn publish(&self, snapshot: Option<&WorldSnapshot>) -> Result<Value> {
let surface = eve::mesh_surface(snapshot);
let world_state = eve::world_state(snapshot);
let version = eve::surface_version(snapshot);
let updated_at = Utc::now().to_rfc3339();
let health = json!({
"schema":"ghostlight.service_health.v2",
"status":"ok",
"worldState":world_state,
"surfaceVersion":version,
"updatedAtUtc":updated_at,
"runtime":self.identity.runtime_id,
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
});
let advertisement = provider_advertisement(&self.identity, &updated_at);
let mut node = self
.node
.lock()
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?;
let mut remote_messages = Vec::new();
self.put_and_stage(
&mut node,
ADVERTISEMENT_KEY,
&EveProviderAdvertisementRecord {
value: advertisement,
},
&mut remote_messages,
)?;
self.put_and_stage(
&mut node,
SURFACE_KEY,
&EveSurfaceRecord { value: surface },
&mut remote_messages,
)?;
// Health is the completion marker for this derived projection. A
// failed advertisement or surface write must leave the prior version
// visibly stale rather than publishing green first.
self.put_and_stage(
&mut node,
HEALTH_KEY,
&ServiceHealthRecord {
value: health.clone(),
},
&mut remote_messages,
)?;
drop(node);
if let Some(remote) = &self.remote {
remote.enqueue(remote_messages);
}
Ok(health)
}
pub(crate) fn health(&self) -> Result<Value> {
if self
.remote
.as_ref()
.is_some_and(|remote| !remote.is_alive())
{
anyhow::bail!("Odin projection worker stopped");
}
self.node
.try_lock()
.map_err(|_| anyhow::anyhow!("mesh projection is busy or its lock is poisoned"))?
.get_required::<ServiceHealthRecord>(HEALTH_KEY)
.map(|record| record.value)
}
fn put_and_stage<T>(
&self,
node: &mut CultMeshNode,
key: impl Into<String>,
value: &T,
remote_messages: &mut Vec<cultnet_rs::CultNetMessage>,
) -> Result<()>
where
T: DatabaseEntry + serde::Serialize,
{
let key = key.into();
node.put(&key, value)?;
if let Some(remote) = &self.remote {
remote_messages.push(node.create_rudp_document_message(
&key,
value,
&remote.options(),
)?);
}
Ok(())
}
}
pub(crate) fn provider_advertisement(identity: &MeshRuntimeIdentity, updated_at: &str) -> Value {
json!({
"schema":"gamecult.eve.provider_advertisement.v1",
"providerId":PROVIDER_ID,
"serviceId":identity.service_id,
"verseId":"gamecult.private",
"rootVerse":"gamecult",
"canonicalService":"ghostlight-dungeon",
"locatedService":identity.located_service,
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
"title":"Ghostlight Dungeon",
"kind":"narrative.simulation",
"updatedAtUtc":updated_at,
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
"schemas":[
"gamecult.eve.surface.v1",
"gamecult.eve.command_invocation.v1",
COMMAND_RESULT_SCHEMA,
"heimdall.access_gate_state.v1",
STATE_SCHEMA,
CONSUMER_PATCH_SCHEMA,
CONSUMER_RECEIPT_SCHEMA
],
"witnesses":[{
"kind":"source-commit",
"ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
}],
"surfaces":[{
"surfaceId":SURFACE_ID,
"schema":"gamecult.eve.surface.v1",
"url":"/api/eve/surfaces/ghostlight.play",
"transport":"https-json",
"status":"available",
"surfaceKind":"subject-scoped-narrative",
"interactionModel":"typed-command-receipts",
"worldInteraction":{
"projectionKind":"owner-derived",
"stateSchemas":[STATE_SCHEMA],
"commandBoundary":COMMAND_BOUNDARY,
"receiptSchema":COMMAND_RESULT_SCHEMA,
"loweringTargets":["browser","eve-native","tui"],
"ownership":"One Ghostlight WorldMailbox owns state; Eve lowers derived projections and commands."
},
"requiresPlugins":[{
"pluginId":"gamecult.heimdall.access",
"versionRange":"^1.0.0",
"availability":"required",
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
}]
}],
"commands":[{
"command":COMMAND_BOUNDARY,
"transport":"https-json",
"summary":"Canonical Ghostlight Eve command boundary."
}]
})
}
impl RemoteReplication {
fn start(target: SocketAddr, runtime_id: String) -> Result<Self> {
let pending = Arc::new((
Mutex::new(None::<Vec<cultnet_rs::CultNetMessage>>),
Condvar::new(),
));
let worker_pending = pending.clone();
let worker_runtime_id = runtime_id.clone();
let alive = Arc::new(AtomicBool::new(true));
let worker_alive = alive.clone();
thread::Builder::new()
.name("ghostlight-odin-rudp".into())
.spawn(move || {
struct Liveness(Arc<AtomicBool>);
impl Drop for Liveness {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
let _liveness = Liveness(worker_alive);
loop {
let messages = {
let (lock, ready) = &*worker_pending;
let mut pending = lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
while pending.is_none() {
pending = ready
.wait(pending)
.unwrap_or_else(|poisoned| poisoned.into_inner());
}
pending.take().unwrap_or_default()
};
if messages.is_empty() {
continue;
}
let options = remote_options(target, &worker_runtime_id);
if let Err(error) =
publish_cultnet_messages_to_rudp_catalog(&messages, options)
{
tracing::warn!(
document_count = messages.len(),
%target,
%error,
"Odin publication failed; retaining the newest derived projection for retry"
);
let (lock, ready) = &*worker_pending;
let mut pending = lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if pending.is_none() {
*pending = Some(messages);
}
let _ = ready
.wait_timeout(pending, std::time::Duration::from_secs(2))
.unwrap_or_else(|poisoned| poisoned.into_inner());
}
}
})?;
Ok(Self {
target,
runtime_id,
pending,
alive,
})
}
fn is_alive(&self) -> bool {
self.alive.load(Ordering::Acquire)
}
fn options(&self) -> CultMeshRudpDocumentPublishOptions {
remote_options(self.target, &self.runtime_id)
}
fn enqueue(&self, messages: Vec<cultnet_rs::CultNetMessage>) {
let (lock, ready) = &*self.pending;
let mut pending = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
*pending = Some(messages);
ready.notify_one();
}
}
fn remote_options(target: SocketAddr, runtime_id: &str) -> CultMeshRudpDocumentPublishOptions {
let mut options = CultMeshRudpDocumentPublishOptions::odin(target, runtime_id);
options.source_agent_id = Some(PROVIDER_ID.into());
options.source_role = Some("narrative-simulation".into());
options.tags = vec!["ghostlight".into(), "eve".into(), "private".into()];
options
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn publishes_only_owner_derived_surface_and_health() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
None,
MeshRuntimeIdentity::default(),
)
.unwrap();
let health = publisher.publish(None).unwrap();
assert_eq!(health["worldState"], "empty");
assert_eq!(health["surfaceVersion"], 0);
assert_eq!(publisher.health().unwrap(), health);
let node = publisher.node.lock().unwrap();
let surface = node
.get_required::<EveSurfaceRecord>(SURFACE_KEY)
.unwrap()
.value;
assert_eq!(surface["type"], "surface-state");
assert_eq!(surface["schema"], "gamecult.eve.surface.v1");
assert_eq!(surface["providerId"], PROVIDER_ID);
assert_eq!(surface["version"], 0);
assert!(
surface["updatedAtUtc"]
.as_str()
.is_some_and(|value| value.parse::<DateTime<Utc>>().is_ok())
);
assert_eq!(surface["surface"], eve::mesh_surface(None)["surface"]);
assert_eq!(surface["commands"], eve::mesh_surface(None)["commands"]);
assert!(
node.get_required::<EveProviderAdvertisementRecord>(ADVERTISEMENT_KEY)
.is_ok()
);
assert!(node.get_required::<ServiceHealthRecord>(HEALTH_KEY).is_ok());
}
#[test]
fn unavailable_odin_cannot_block_local_publication() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
Some("127.0.0.1:1".parse().unwrap()),
MeshRuntimeIdentity::default(),
)
.unwrap();
let started = std::time::Instant::now();
publisher.publish(None).unwrap();
assert!(started.elapsed() < std::time::Duration::from_millis(500));
assert_eq!(publisher.health().unwrap()["worldState"], "empty");
}
#[test]
fn stopped_odin_worker_makes_runtime_health_non_green() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
Some("127.0.0.1:1".parse().unwrap()),
MeshRuntimeIdentity::default(),
)
.unwrap();
publisher.publish(None).unwrap();
publisher
.remote
.as_ref()
.unwrap()
.alive
.store(false, Ordering::Release);
assert!(publisher.health().is_err());
}
#[test]
fn advertisement_has_one_surface_and_one_command_boundary() {
let directory = tempfile::tempdir().unwrap();
let publisher = MeshPublisher::open(
directory.path().join("mesh-v2.cc"),
None,
MeshRuntimeIdentity::default(),
)
.unwrap();
let advertisement = publisher.provider_advertisement("2026-09-01T00:00:00Z");
assert_eq!(advertisement["surfaces"].as_array().unwrap().len(), 1);
assert_eq!(advertisement["commands"].as_array().unwrap().len(), 1);
assert_eq!(advertisement["surfaces"][0]["surfaceId"], SURFACE_ID);
}
}

View file

@ -0,0 +1,44 @@
//! The play page: three static files compiled into the binary and served from
//! the router's root. They hold presentation only and no secret, so there is
//! no page directory to resolve at run time and nothing to drift from the
//! binary.
use crate::runtime::AppState;
use axum::{
Router,
http::{HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
routing::get,
};
const INDEX: &str = include_str!("../page/index.html");
const STYLE: &str = include_str!("../page/page.css");
const SCRIPT: &str = include_str!("../page/page.js");
/// The page loads only its own script and style and talks only to its own
/// origin, so injected markup has nowhere to run or to send anything.
const POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; \
img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
fn file(content_type: &'static str, body: &'static str) -> Response {
(
StatusCode::OK,
[
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(POLICY)),
(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer")),
(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")),
],
body,
)
.into_response()
}
pub(crate) fn router() -> Router<AppState> {
Router::new()
.route("/", get(|| async { file("text/html; charset=utf-8", INDEX) }))
.route("/page.css", get(|| async { file("text/css; charset=utf-8", STYLE) }))
.route("/page.js", get(|| async { file("text/javascript; charset=utf-8", SCRIPT) }))
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,196 @@
//! Run-ahead: the bounded Active elaboration sweep.
//!
//! A world's scale deficit is answered after play starts, not before: one sweep
//! once Begin activates a seeded world, and one after each closed turn. Each
//! sweep claims what attention holds first (`focus_of`: the player's place and
//! the DM's standing focus), holds at most `Scale::sweep_permits` permits, and
//! spends in its own post-turn window: the elaborator calls a provider only
//! through the window's recording port, which refuses a call that could pass the
//! timeline's elaboration allowance, so how much a sweep does is the DM's knob
//! and not a session count. The elaborator reads the evidence of the snapshot
//! its timeline is bound to, the same evidence the seed read; an unseeded world
//! reads none.
use crate::{
begin::{Scale, Vaults},
catalog::Catalog,
knobs::{DmKnobs, Target},
timelines::TimelineHost,
};
use ghostlight::{
ControllerMode, EntityId, EvidenceSource, Focus, Hierarchy, NullEvidenceSource, WorldSnapshot,
};
use std::sync::Arc;
use tokio::sync::{Mutex, Semaphore};
/// One bounded sweep of `host` over `evidence`. A sweep already running on this
/// timeline is the trigger's answer: the sweep that follows picks up what this
/// one would have.
pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSource>, scale: &Scale) {
let Ok(_running) = host.sweeping.try_lock() else {
return;
};
let world = match host.world.snapshot().await {
Ok(world) => world,
Err(error) => {
tracing::warn!(%error, "run-ahead could not read the world");
return;
}
};
let hierarchy = match host.world.hierarchy().await {
Ok(hierarchy) => hierarchy,
Err(error) => {
tracing::warn!(%error, "run-ahead could not read the hierarchy");
return;
}
};
let knobs = host.knobs.lock().await.current();
let window = match host.window(world.revision, &world, knobs.allowances) {
Ok(window) => Arc::new(window),
Err(error) => {
tracing::warn!(%error, "run-ahead could not open its window");
return;
}
};
let runner = host.controllers.elaborator(window, evidence);
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
if let Err(error) = runner.sweep(permits, usize::MAX, &focus_of(&world, &hierarchy, &knobs)).await {
tracing::warn!(%error, "run-ahead elaboration stopped");
}
}
/// The places the world's owner's own human subjects stand in: the room the
/// player is in, which the DM's `react` owns and a world wave never turns.
pub(crate) fn player_places(world: &WorldSnapshot) -> Vec<EntityId> {
world
.subjects
.iter()
.filter(|subject| {
subject.controller_mode == Some(ControllerMode::Human)
&& subject.human_controller.as_ref() == Some(&world.owner)
})
.filter_map(|subject| world.place_of(subject.id))
.collect()
}
/// Where attention is: the player's place, then the DM's focus entries whose
/// lease still holds. A world with no placed player and no entries has no
/// focus, and its sweep keeps the kernel's order.
pub(crate) fn focus_of(world: &WorldSnapshot, hierarchy: &Hierarchy, knobs: &DmKnobs) -> Focus {
let mut focus = Focus { places: player_places(world), nodes: Vec::new() };
for lease in knobs.standing(world.now.0) {
match lease.target {
Target::Place(place) if !focus.places.contains(&place) => focus.places.push(place),
Target::Place(_) => {}
Target::Institution(_) => focus.nodes.extend(lease.target.node(hierarchy)),
}
}
focus
}
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
/// era its world was pinned to, or none for a world that began unseeded. A
/// bound snapshot that cannot be reopened, or a world that cannot be read,
/// yields no evidence at all and no sweep, never a blind or era-blind one.
pub(crate) async fn evidence_of(
catalog: &Mutex<Catalog>,
vaults: &dyn Vaults,
host: &TimelineHost,
timeline: &str,
) -> Option<Arc<dyn EvidenceSource>> {
let snapshot_id = {
let catalog = catalog.lock().await;
let world = catalog.world(&catalog.timeline(timeline)?.world_id)?;
world.snapshot_id.clone()
};
let Some(id) = snapshot_id else {
return Some(Arc::new(NullEvidenceSource));
};
let era = host.world.snapshot().await.ok()?.era;
match vaults.evidence(&id, era.as_ref().map(|era| era.id.as_str())) {
Ok(evidence) => Some(evidence),
Err(error) => {
tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened");
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
begin::{
BeginRequest, begin,
tests::{NoVaults, deferred_rig, one_vault, principal, request},
},
};
use uuid::Uuid;
/// The sweep looks where the player stands: the place of the owner's own
/// human subject, and nowhere for a world whose owner controls no subject.
#[tokio::test]
async fn the_focus_of_a_world_is_its_owners_human_subjects_place() {
let rig = deferred_rig();
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(Uuid::new_v4(), None))
.await
.unwrap();
let host = rig.timelines.host(&begun.timeline).await.unwrap();
let world = host.world.snapshot().await.unwrap();
let player = world
.subjects
.iter()
.find(|subject| subject.human_controller.as_ref() == Some(&world.owner))
.expect("the owner's player");
let stands = world.place_of(player.id).expect("the player stands somewhere");
let hierarchy = host.world.hierarchy().await.unwrap();
let none = DmKnobs::default();
assert_eq!(focus_of(&world, &hierarchy, &none).places, vec![stands]);
let mut stranger = world.clone();
stranger.owner = ghostlight::PrincipalId::new("someone else");
assert!(focus_of(&stranger, &hierarchy, &none).places.is_empty(), "another principal's subject is not the owner's player");
let mut automaton = world;
for subject in &mut automaton.subjects {
subject.controller_mode = Some(ControllerMode::NarrativePersona);
}
assert!(focus_of(&automaton, &hierarchy, &none).places.is_empty(), "a persona is not looking");
}
/// A timeline's elaborator reads what its world was bound to: nothing
/// for an unseeded world, the snapshot for a seeded one, and no evidence
/// (so no sweep) for a snapshot that cannot be reopened or a timeline the
/// catalog does not know.
#[tokio::test]
async fn the_evidence_of_a_timeline_is_its_bound_snapshots() {
let vaults = one_vault();
let rig = deferred_rig();
let alice = principal("alice");
let unseeded = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(Uuid::new_v4(), None))
.await
.unwrap();
let host = rig.timelines.host(&unseeded.timeline).await.unwrap();
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &unseeded.timeline).await.is_some(),
"an unseeded world reads none, and still sweeps"
);
let seeded = begin(
&rig.catalog,
&rig.timelines,
vaults.as_ref(),
&rig.scale,
&alice,
BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) },
)
.await
.unwrap();
let host = rig.timelines.host(&seeded.timeline).await.unwrap();
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, &seeded.timeline).await.is_some());
assert!(
evidence_of(&rig.catalog, &NoVaults, &host, &seeded.timeline).await.is_none(),
"an unreadable snapshot is never swept blind"
);
let stranger = "timeline:00000000-0000-4000-8000-000000000000";
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, stranger).await.is_none());
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,619 @@
//! The app-session refresh loop: renews Heimdall sessions before they lapse
//! and revokes any whose custody changed.
use crate::{
app_session::{AppSessionOwner, RefreshRefusal},
heimdall::{self, HeimdallDenied, SessionRefresher, VerificationUnavailable},
};
use anyhow::Context;
use chrono::Utc;
use std::{collections::HashMap, time::Duration};
use tokio::sync::Mutex;
const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60);
/// Runs `refresh_due_sessions` once per `SESSION_REFRESH_PERIOD` for as long
/// as the daemon serves. The receipts it holds are Heimdall refreshes already
/// spent upstream whose verification could not yet be judged.
pub(crate) async fn run_refresh_loop(
sessions: &Mutex<AppSessionOwner>,
heimdall: &(impl SessionRefresher + ?Sized),
) -> anyhow::Result<()> {
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut unverified = HashMap::new();
loop {
interval.tick().await;
refresh_due_sessions(sessions, heimdall, &mut unverified).await?;
}
}
/// One pass of the refresh loop over every session due for refresh.
/// `unverified` holds, per session, a receipt Heimdall issued for a refresh
/// that is already spent upstream but whose signing keys could not be
/// fetched: the next pass verifies it instead of refreshing again.
async fn refresh_due_sessions(
sessions: &Mutex<AppSessionOwner>,
heimdall: &(impl SessionRefresher + ?Sized),
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
) -> anyhow::Result<()> {
let candidates = sessions
.lock()
.await
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
.context("app-session refresh scan lost custody")?;
unverified.retain(|cookie_hash, _| {
candidates
.iter()
.any(|candidate| &candidate.cookie_hash == cookie_hash)
});
for candidate in candidates {
let completion = match unverified.remove(&candidate.cookie_hash) {
Some(completion) => completion,
None => {
let idempotency =
crate::app_session::refresh_idempotency_key(&candidate.refresh_claim);
match heimdall.refresh(&candidate.refresh_claim, &idempotency).await {
Ok(value) => value,
Err(error) if error.downcast_ref::<HeimdallDenied>().is_some() => {
// Heimdall refused this refresh claim: it can never succeed.
tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session");
let mut sessions = sessions.lock().await;
if let Err(revoke_error) =
sessions.revoke_cookie_hash(&candidate.cookie_hash)
{
return Err(revoke_error)
.context("denied Heimdall refresh could not revoke local custody");
}
continue;
}
Err(error) => {
tracing::warn!(%error, "Heimdall refresh transport unavailable");
continue;
}
}
}
};
let verified = match heimdall.verify_refresh(completion.clone()).await {
Ok(value) => value,
Err(error) if error.downcast_ref::<VerificationUnavailable>().is_some() => {
// The claim is spent upstream and the receipt may be genuine:
// keep it and verify again on the next pass.
tracing::warn!(%error, "Heimdall refresh receipt could not be verified yet");
unverified.insert(candidate.cookie_hash.clone(), completion);
continue;
}
Err(error) => {
tracing::warn!(%error, "Heimdall refresh receipt was invalid");
let mut sessions = sessions.lock().await;
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
return Err(revoke_error)
.context("invalid Heimdall refresh could not revoke local custody");
}
continue;
}
};
if verified.heimdall_session_id() != candidate.heimdall_session_id
|| crate::app_session::secret_hash(&format!(
"heimdall-account:{}",
verified.account_id()
)) != candidate.account_subject_hash
{
tracing::warn!("Heimdall refresh changed local session custody");
let mut sessions = sessions.lock().await;
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
return Err(revoke_error)
.context("changed Heimdall custody could not revoke local session");
}
continue;
}
let mut sessions = sessions.lock().await;
if let Err(error) =
sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified)
{
if !sessions.is_healthy() {
return Err(error).context("app-session refresh commit lost custody");
}
tracing::warn!(%error, "local app session refused Heimdall refresh");
// The refresh claim is spent upstream, so a receipt that went
// backwards leaves nothing to retry. A session that merely moved
// is newer state: the next scan decides.
if error.downcast_ref::<RefreshRefusal>()
== Some(&RefreshRefusal::RevisionWentBackwards)
&& let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash)
{
return Err(revoke_error)
.context("backwards Heimdall refresh could not revoke local session");
}
}
}
Ok(())
}
/// Idunn publishes Expected and starts the unit before it observes the
/// running process on a later tick and publishes the activation
/// (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses
/// queue and records the claim and idempotency key it was sent.
#[cfg(test)]
mod refresh_loop_tests {
use super::*;
use crate::heimdall::{AuthCompletionReceipt, HeimdallClient, VerifiedSessionRefresh};
use anyhow::bail;
use std::{collections::VecDeque, sync::Mutex as StdMutex};
enum Reply {
Deny,
Timeout,
Receipt { revision: u64, claim: &'static str },
/// A receipt for the same claim but another Heimdall session.
OtherSession,
/// A receipt for the same claim but another account.
OtherAccount,
}
/// What `verify_refresh` answers; an empty queue accepts the receipt.
enum Verdict {
/// The signing keys could not be fetched.
Unavailable,
/// The receipt positively fails verification.
Invalid,
}
#[derive(Default)]
struct ScriptedHeimdall {
replies: StdMutex<VecDeque<Reply>>,
verdicts: StdMutex<VecDeque<Verdict>>,
verifications: StdMutex<usize>,
/// While answering a refresh, apply a newer revision to this store,
/// as a concurrent refresh of the same session would.
moving: Option<std::sync::Arc<Mutex<AppSessionOwner>>>,
pending: StdMutex<Option<VerifiedSessionRefresh>>,
calls: StdMutex<Vec<(String, String)>>,
/// Verify receipts with this real client, against the access token
/// each receipt carries, instead of from the verdict queue.
real: Option<(HeimdallClient, String)>,
}
impl ScriptedHeimdall {
fn answering(replies: Vec<Reply>) -> Self {
Self {
replies: StdMutex::new(replies.into()),
..Self::default()
}
}
fn verifying(mut self, verdicts: Vec<Verdict>) -> Self {
self.verdicts = StdMutex::new(verdicts.into());
self
}
fn verifying_for_real(mut self, client: HeimdallClient, token: String) -> Self {
self.real = Some((client, token));
self
}
fn verifications(&self) -> usize {
*self.verifications.lock().unwrap()
}
fn calls(&self) -> Vec<(String, String)> {
self.calls.lock().unwrap().clone()
}
}
#[async_trait::async_trait]
impl SessionRefresher for ScriptedHeimdall {
async fn refresh(
&self,
refresh_token: &str,
idempotency_key: &str,
) -> anyhow::Result<AuthCompletionReceipt> {
self.calls
.lock()
.unwrap()
.push((refresh_token.into(), idempotency_key.into()));
if let Some(sessions) = &self.moving {
let mut sessions = sessions.lock().await;
let candidate = sessions
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
.unwrap()
.remove(0);
sessions
.apply_refresh(
&candidate.cookie_hash,
candidate.access_revision,
VerifiedSessionRefresh::fixture(
"operator-account",
"heimdall-session",
candidate.access_revision + 1,
Utc::now() + chrono::Duration::seconds(90),
Utc::now() + chrono::Duration::days(1),
"claim-moved",
),
)
.unwrap();
}
match self.replies.lock().unwrap().pop_front().expect("scripted reply") {
Reply::Deny => Err(HeimdallDenied {
diagnostics: "Idempotency key was reused".into(),
}
.into()),
Reply::Timeout => bail!("Heimdall private command timed out"),
reply @ (Reply::Receipt { .. } | Reply::OtherSession | Reply::OtherAccount) => {
let (account, session, revision, claim) = match reply {
Reply::OtherSession => ("operator-account", "other-session", 1, "claim-1"),
Reply::OtherAccount => ("other-account", "heimdall-session", 1, "claim-1"),
Reply::Receipt { revision, claim } => {
("operator-account", "heimdall-session", revision, claim)
}
_ => unreachable!("matched above"),
};
*self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture(
account,
session,
revision,
Utc::now() + chrono::Duration::seconds(90),
Utc::now() + chrono::Duration::days(1),
claim,
));
Ok(AuthCompletionReceipt {
status: "authenticated".into(),
handle: None,
error: None,
account: None,
session: None,
access_token: self.real.as_ref().map(|(_, token)| token.clone()),
refresh_token: None,
refresh: None,
shared_capabilities: Vec::new(),
})
}
}
}
async fn verify_refresh(
&self,
completion: AuthCompletionReceipt,
) -> anyhow::Result<VerifiedSessionRefresh> {
*self.verifications.lock().unwrap() += 1;
if let Some((client, _)) = &self.real {
return client.verify_refresh(completion).await;
}
match self.verdicts.lock().unwrap().pop_front() {
Some(Verdict::Unavailable) => {
Err(VerificationUnavailable::new("timed out").into())
}
Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"),
None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")),
}
}
}
/// A store holding one live session at `revision` whose access expires in
/// a minute, so every pass finds it due.
fn due_session(
revision: u64,
) -> (tempfile::TempDir, std::sync::Arc<Mutex<AppSessionOwner>>, String) {
let directory = tempfile::tempdir().unwrap();
let key = directory.path().join("session.key");
std::fs::write(&key, [23_u8; 32]).unwrap();
let mut owner = AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
let cookie = owner
.create_session(heimdall::VerifiedSessionAdmission::fixture(
"operator-account",
"heimdall-session",
revision,
Utc::now() + chrono::Duration::seconds(60),
Utc::now() + chrono::Duration::days(1),
"claim-0",
))
.unwrap();
(directory, std::sync::Arc::new(Mutex::new(owner)), cookie)
}
/// One refresh pass with no receipt carried over from an earlier one.
async fn pass(sessions: &Mutex<AppSessionOwner>, heimdall: &ScriptedHeimdall) {
refresh_due_sessions(sessions, heimdall, &mut HashMap::new())
.await
.unwrap();
}
async fn is_live(sessions: &Mutex<AppSessionOwner>, cookie: &str) -> bool {
sessions
.lock()
.await
.account_for_cookie(cookie, Utc::now())
.unwrap()
.is_some()
}
#[derive(Clone, Default)]
struct Captured(std::sync::Arc<StdMutex<Vec<u8>>>);
impl std::io::Write for Captured {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
type Writer = Captured;
fn make_writer(&'a self) -> Captured {
self.clone()
}
}
#[tokio::test]
async fn a_real_refresh_at_an_equal_revision_is_applied_and_the_session_stays_live() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The wrapped claim is the receipt's: the next refresh spends it.
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert!(is_live(&sessions, &cookie).await);
}
#[tokio::test]
async fn a_retry_of_the_same_refresh_sends_the_same_key() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]);
pass(&sessions, &heimdall).await;
pass(&sessions, &heimdall).await;
let calls = heimdall.calls();
assert_eq!(calls.len(), 2, "a transport failure leaves the session offered");
assert_eq!(calls[0], calls[1]);
assert!(is_live(&sessions, &cookie).await);
}
#[tokio::test]
async fn the_refresh_after_a_successful_one_sends_a_new_key() {
let (_directory, sessions, _cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
pass(&sessions, &heimdall).await;
let calls = heimdall.calls();
assert_ne!(calls[0].1, calls[1].1);
assert!(calls.iter().all(|(claim, key)| !key.contains(claim)));
}
#[tokio::test]
async fn a_receipt_with_a_lower_revision_is_refused_and_the_session_revoked() {
let (_directory, sessions, cookie) = due_session(2);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again");
}
#[tokio::test]
async fn a_receipt_for_another_session_or_account_revokes_the_local_session() {
for reply in [Reply::OtherSession, Reply::OtherAccount] {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![reply]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
}
}
#[tokio::test]
async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]);
pass(&sessions, &heimdall).await;
assert!(!is_live(&sessions, &cookie).await);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls().len(), 1);
}
#[tokio::test]
async fn a_local_refusal_logs_the_clause_that_fired() {
let (_directory, sessions, _cookie) = due_session(2);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}]);
let captured = Captured::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
pass(&sessions, &heimdall).await;
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
assert!(
logged.contains("refresh receipt revision went backwards"),
"{logged}"
);
}
#[tokio::test]
async fn a_receipt_whose_keys_were_unavailable_is_kept_and_applied_on_the_next_pass() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
])
.verifying(vec![Verdict::Unavailable]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(is_live(&sessions, &cookie).await, "unavailable keys do not revoke");
assert_eq!(unverified.len(), 1);
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls().len(), 1, "the spent claim is not sent again");
assert_eq!(heimdall.verifications(), 2);
assert!(unverified.is_empty(), "an applied receipt is not kept");
assert!(is_live(&sessions, &cookie).await);
// The applied receipt's claim is the one the next refresh spends.
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert_eq!(heimdall.verifications(), 2, "the receipt was applied once");
}
#[tokio::test]
async fn a_receipt_that_positively_fails_verification_revokes_and_is_not_kept() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 1, claim: "claim-1" },
Reply::Timeout,
])
.verifying(vec![Verdict::Invalid]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(!is_live(&sessions, &cookie).await);
assert!(unverified.is_empty());
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(heimdall.calls().len(), 1);
assert_eq!(heimdall.verifications(), 1);
}
#[tokio::test]
async fn a_kept_receipt_for_a_session_that_is_gone_is_dropped() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}])
.verifying(vec![Verdict::Unavailable]);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert_eq!(unverified.len(), 1);
let cookie_hash = unverified.keys().next().unwrap().clone();
sessions.lock().await.revoke_cookie_hash(&cookie_hash).unwrap();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
assert!(unverified.is_empty());
assert!(!is_live(&sessions, &cookie).await);
assert_eq!(heimdall.verifications(), 1);
}
#[tokio::test]
async fn a_session_that_moved_while_refreshing_is_not_revoked() {
let (_directory, sessions, cookie) = due_session(1);
let mut heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}]);
heimdall.moving = Some(sessions.clone());
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The newer state wins: the next refresh spends its claim, not the
// stale receipt's.
heimdall.moving = None;
heimdall.replies.lock().unwrap().push_back(Reply::Timeout);
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-moved");
}
#[tokio::test]
async fn a_receipt_with_a_higher_revision_is_applied() {
let (_directory, sessions, cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering(vec![
Reply::Receipt { revision: 2, claim: "claim-1" },
Reply::Receipt { revision: 1, claim: "claim-2" },
]);
pass(&sessions, &heimdall).await;
assert!(is_live(&sessions, &cookie).await);
// The session now sits at revision 2, so a revision-1 receipt is
// backwards.
pass(&sessions, &heimdall).await;
assert_eq!(heimdall.calls()[1].0, "claim-1");
assert!(!is_live(&sessions, &cookie).await);
}
/// Lets the loop under test run everything that is ready, without moving
/// the paused clock.
async fn settle() {
for _ in 0..16 {
tokio::task::yield_now().await;
}
}
#[tokio::test(start_paused = true)]
async fn the_refresh_loop_runs_a_pass_every_sixty_seconds_and_keeps_going() {
let (_directory, sessions, _cookie) = due_session(1);
let heimdall = ScriptedHeimdall::answering((0..64).map(|_| Reply::Timeout).collect());
let observed = async {
settle().await;
assert_eq!(heimdall.calls().len(), 1, "the first pass runs at once");
tokio::time::advance(Duration::from_millis(59_999)).await;
settle().await;
assert_eq!(heimdall.calls().len(), 1, "no pass before sixty seconds");
tokio::time::advance(Duration::from_millis(1)).await;
settle().await;
assert_eq!(heimdall.calls().len(), 2, "the second pass at sixty seconds");
for passes in 3..=12 {
tokio::time::advance(Duration::from_secs(60)).await;
settle().await;
assert_eq!(heimdall.calls().len(), passes);
}
};
tokio::select! {
ran = run_refresh_loop(&sessions, &heimdall) => panic!("the loop returned: {ran:?}"),
() = observed => {}
}
}
/// A refresh receipt verified by the real client against `issuer_url`,
/// whose key-set fetch fails. Returns whether the session stayed live,
/// how many receipts were kept, and the log the pass wrote.
async fn pass_through_real_verification(issuer_url: &str) -> (bool, usize, String) {
let (_directory, sessions, cookie) = due_session(1);
let client = HeimdallClient::fixture().with_issuer(issuer_url);
let token = heimdall::test_issuer::signed_token(issuer_url);
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
revision: 1,
claim: "claim-1",
}])
.verifying_for_real(client, token);
let captured = Captured::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
let mut unverified = HashMap::new();
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
(is_live(&sessions, &cookie).await, unverified.len(), logged)
}
#[tokio::test]
async fn a_key_fetch_failure_in_the_real_verification_keeps_the_session_and_the_receipt() {
let failing = heimdall::test_issuer::Issuer::start(heimdall::test_issuer::Answer::ServerError)
.await;
for issuer_url in [heimdall::test_issuer::Issuer::closed_url(), failing.url.clone()] {
let (live, kept, logged) = pass_through_real_verification(&issuer_url).await;
assert!(live, "{issuer_url}: a key-fetch failure signed the session out");
assert_eq!(kept, 1, "{issuer_url}: the spent receipt was not kept");
assert!(logged.contains("could not be verified yet"), "{logged}");
}
}
#[tokio::test]
async fn the_unverified_warning_names_the_error_class_and_no_url() {
let canary = format!("{}/canary-q7x1", heimdall::test_issuer::Issuer::closed_url());
let (_, _, logged) = pass_through_real_verification(&canary).await;
assert!(logged.contains("could not connect"), "{logged}");
for leaked in [canary.as_str(), "canary-q7x1", "127.0.0.1", "jwks.json"] {
assert!(!logged.contains(leaked), "{leaked} leaked into the log: {logged}");
}
}
}

View file

@ -0,0 +1,211 @@
//! The admitted state layout: every declared state path must be a direct,
//! single-linked regular file or directory before anything is written to it.
use anyhow::{Context, bail, ensure};
use std::{
fs,
path::{Path, PathBuf},
};
/// The stores one timeline owns, each proved direct before it is opened.
pub(crate) const TIMELINE_STORES: [&str; 6] = [
"world.cc",
"controller-work.cc",
"play-turn-v1.cc",
"calls.cc",
"waves.cc",
"gestalt-knobs.cc",
];
fn default_runtime_root() -> PathBuf {
#[cfg(windows)]
{
PathBuf::from(r"F:\GameCult\GhostlightDungeon")
}
#[cfg(not(windows))]
{
PathBuf::from("/var/lib/gamecult/ghostlight-dungeon")
}
}
pub(crate) fn admitted_runtime_root(binding: Option<PathBuf>) -> anyhow::Result<PathBuf> {
let Some(binding) = binding else {
#[cfg(target_os = "linux")]
bail!("--state-root is mandatory for the managed Linux runtime");
#[cfg(not(target_os = "linux"))]
return Ok(default_runtime_root());
};
ensure!(binding.is_absolute(), "state-root binding is not absolute");
let metadata = fs::symlink_metadata(&binding)
.with_context(|| format!("inspecting state-root binding {}", binding.display()))?;
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"state-root binding is not a direct directory"
);
let canonical = fs::canonicalize(&binding)
.with_context(|| format!("canonicalizing state-root binding {}", binding.display()))?;
ensure!(
canonical == binding,
"state-root binding is indirect or non-canonical"
);
Ok(binding)
}
fn ensure_direct_directory(path: &Path, label: &str) -> anyhow::Result<()> {
match fs::symlink_metadata(path) {
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
fs::create_dir(path)
.with_context(|| format!("creating direct {label} {}", path.display()))?;
}
Err(error) => return Err(error).with_context(|| format!("inspecting {label}")),
}
let metadata = fs::symlink_metadata(path)
.with_context(|| format!("inspecting {label} {}", path.display()))?;
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"{label} is indirect or not a directory"
);
Ok(())
}
pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Result<()> {
let rebound = admitted_runtime_root(Some(runtime_root.to_owned()))?;
ensure!(
rebound == runtime_root,
"state-root binding changed after process-write-lease admission"
);
let service_root = runtime_root.join("service");
ensure_direct_directory(&service_root, "service state directory")?;
ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?;
ensure_direct_directory(
&runtime_root.join(crate::vaults::SNAPSHOT_DIRECTORY),
"vault snapshot directory",
)?;
for path in [
runtime_root.join("catalog.cc"),
service_root.join("app-sessions-v2.cc"),
] {
require_direct_state_file_or_absent(&path)?;
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
}
Ok(())
}
/// Proves a timeline's stores direct before it is opened and returns its
/// directory, created if absent.
pub(crate) fn prepare_timeline_directory(
runtime_root: &Path,
directory_name: &str,
) -> anyhow::Result<PathBuf> {
let directory = runtime_root.join("timelines").join(directory_name);
ensure_direct_directory(&directory, "timeline directory")?;
for name in TIMELINE_STORES {
let path = directory.join(name);
require_direct_state_file_or_absent(&path)?;
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
}
Ok(directory)
}
fn require_direct_state_file_or_absent(path: &Path) -> anyhow::Result<()> {
match fs::symlink_metadata(path) {
Ok(metadata) => {
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink(),
"declared state path {} is indirect or not a regular file",
path.display()
);
#[cfg(target_os = "linux")]
ensure!(
std::os::unix::fs::MetadataExt::nlink(&metadata) == 1,
"declared state path {} is multiply linked",
path.display()
);
Ok(())
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => {
Err(error).with_context(|| format!("inspecting declared state path {}", path.display()))
}
}
}
fn sibling_state_lock_path(path: &Path) -> PathBuf {
let mut name = path
.file_name()
.map(|value| value.to_os_string())
.unwrap_or_else(|| "state.cc".into());
name.push(".lock");
path.with_file_name(name)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "linux")]
#[test]
fn managed_linux_runtime_requires_the_admitted_state_root_binding() {
assert!(admitted_runtime_root(None).is_err());
}
#[test]
fn admitted_state_root_must_name_the_direct_canonical_directory() {
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
assert_eq!(admitted_runtime_root(Some(root.clone())).unwrap(), root);
assert!(admitted_runtime_root(Some(directory.path().join("missing"))).is_err());
}
#[test]
fn post_lease_state_layout_creates_only_the_direct_declared_directories() {
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
for name in ["service", "timelines"] {
let metadata = fs::symlink_metadata(root.join(name)).unwrap();
assert!(metadata.is_dir());
assert!(!metadata.file_type().is_symlink());
}
}
#[cfg(target_os = "linux")]
#[test]
fn post_lease_state_layout_rejects_symlinks_and_hardlinks() {
use std::os::unix::fs::symlink;
let symlink_directory = tempfile::tempdir().unwrap();
let symlink_root = fs::canonicalize(symlink_directory.path()).unwrap();
let target = symlink_root.join("other.cc");
fs::write(&target, b"not-catalog").unwrap();
symlink(&target, symlink_root.join("catalog.cc")).unwrap();
assert!(prepare_admitted_state_layout(&symlink_root).is_err());
let hardlink_directory = tempfile::tempdir().unwrap();
let hardlink_root = fs::canonicalize(hardlink_directory.path()).unwrap();
let target = hardlink_root.join("other.cc");
fs::write(&target, b"not-catalog").unwrap();
fs::hard_link(&target, hardlink_root.join("catalog.cc")).unwrap();
assert!(prepare_admitted_state_layout(&hardlink_root).is_err());
}
/// A timeline's own stores get the same proof as the service's, before the
/// timeline is opened: a symlink standing in for its play-turn store is
/// refused.
#[cfg(target_os = "linux")]
#[test]
fn a_symlinked_timeline_store_is_refused() {
use std::os::unix::fs::symlink;
let directory = tempfile::tempdir().unwrap();
let root = fs::canonicalize(directory.path()).unwrap();
prepare_admitted_state_layout(&root).unwrap();
let name = "00000000-0000-4000-8000-000000000001";
let timeline = prepare_timeline_directory(&root, name).unwrap();
let target = root.join("other.cc");
fs::write(&target, b"not-play-turn").unwrap();
symlink(&target, timeline.join("play-turn-v1.cc")).unwrap();
assert!(prepare_timeline_directory(&root, name).is_err());
}
}

View file

@ -0,0 +1,177 @@
//! Test support the API tests, the live runtime check and the playtest
//! harness share: a counting port that keeps usage per model, and the one
//! assembly of an `AppState` with signed-in test sessions.
use crate::{
app_session::AppSessionOwner,
begin::{Scale, Vaults},
catalog::Catalog,
heimdall::{HeimdallPort, VerifiedSessionAdmission},
runtime::AppState,
timelines::Timelines,
};
/// The one neutral model id every test lane runs on: ids are opaque exact
/// strings, so no fixture names a provider or tier.
pub(crate) const TEST_LANE_MODEL: &str = "test/lane-a";
use chrono::Utc;
use ghostlight::{
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
};
use serde_json::Value;
use std::{
collections::BTreeMap,
path::Path,
sync::{Arc, Mutex as StdMutex},
};
use tokio::sync::{Mutex, mpsc};
/// What one model was asked and what the provider says it spent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ModelUsage {
pub(crate) calls: u64,
pub(crate) prompt: u64,
pub(crate) cached_prompt: u64,
pub(crate) completion: u64,
}
/// Counts every call and the usage the connector reports, per model, around
/// the real port.
pub(crate) struct CountingPort {
inner: Arc<dyn InferencePort>,
usage: StdMutex<BTreeMap<String, ModelUsage>>,
}
impl CountingPort {
pub(crate) fn new(inner: Arc<dyn InferencePort>) -> Arc<Self> {
Arc::new(Self { inner, usage: StdMutex::new(BTreeMap::new()) })
}
pub(crate) fn by_model(&self) -> BTreeMap<String, ModelUsage> {
self.usage.lock().unwrap().clone()
}
pub(crate) fn totals(&self) -> ModelUsage {
self.by_model().values().fold(ModelUsage::default(), |sum, each| ModelUsage {
calls: sum.calls + each.calls,
prompt: sum.prompt + each.prompt,
cached_prompt: sum.cached_prompt + each.cached_prompt,
completion: sum.completion + each.completion,
})
}
}
/// The model a prepared request names: the `model` key wherever the request's
/// serialization keeps it, including inside a string that holds JSON.
fn model_of(value: &Value) -> Option<String> {
match value {
Value::Object(map) => map
.get("model")
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| map.values().find_map(model_of)),
Value::Array(items) => items.iter().find_map(model_of),
Value::String(text) if text.starts_with('{') => {
serde_json::from_str::<Value>(text).ok().and_then(|inner| model_of(&inner))
}
_ => None,
}
}
#[async_trait::async_trait]
impl InferencePort for CountingPort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let model = serde_json::to_value(&request)
.ok()
.and_then(|seen| model_of(&seen))
.unwrap_or_else(|| "unknown".into());
let output = self.inner.infer(request).await?;
let usage = output.usage();
let mut table = self.usage.lock().unwrap();
let row = table.entry(model).or_default();
row.calls += 1;
if let Some(usage) = usage {
row.prompt += usage.prompt;
row.cached_prompt += usage.cached_prompt.unwrap_or(0);
row.completion += usage.completion;
}
Ok(output)
}
}
/// An `AppState` over the given pieces with one signed-in session per entry of
/// `accounts` (the same account twice is the same player on two devices), the
/// session cookies in order, and the receiver of the fatal signals. Session
/// custody lives under `directory`.
pub(crate) fn assemble(
directory: &Path,
catalog: Arc<Mutex<Catalog>>,
timelines: Arc<Timelines>,
scale: Arc<Scale>,
vaults: Arc<dyn Vaults>,
heimdall: Arc<dyn HeimdallPort>,
accounts: &[&str],
) -> (AppState, Vec<String>, mpsc::UnboundedReceiver<String>) {
let key = directory.join("session.key");
std::fs::write(&key, [17_u8; 32]).unwrap();
let mut sessions =
AppSessionOwner::open(directory.join("service/app-sessions-v2.cc"), &key).unwrap();
let cookies = accounts
.iter()
.enumerate()
.map(|(index, account)| {
sessions
.create_session(VerifiedSessionAdmission::fixture(
*account,
format!("heimdall-session-{index}"),
1,
Utc::now() + chrono::Duration::hours(1),
Utc::now() + chrono::Duration::days(1),
"fixture-refresh",
))
.unwrap()
})
.collect();
let (fatal, fatal_events) = mpsc::unbounded_channel();
let state = AppState {
catalog,
timelines,
vaults,
scale,
sessions: Arc::new(Mutex::new(sessions)),
heimdall,
auth: Arc::default(),
runtime_id: "ghostlight-test".into(),
runtime_health: None,
fatal,
};
(state, cookies, fatal_events)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::play::tests::ScriptedPort;
#[test]
fn a_prepared_request_names_its_model() {
let port = ScriptedPort::new(vec![]);
let request = InferenceRequest::play(
ghostlight::CommandId::new(),
0,
TEST_LANE_MODEL,
"be brief",
vec![],
vec![],
100,
)
.unwrap();
let prepared = port.prepare(request).unwrap();
let seen = serde_json::to_value(&prepared).unwrap();
assert_eq!(model_of(&seen).as_deref(), Some(TEST_LANE_MODEL));
}
}

View file

@ -0,0 +1,175 @@
//! Many timelines in one daemon.
//!
//! Each timeline is its own kernel store with its own mailbox, play table and
//! controller work; every one shares the single routed inference port and the
//! one concurrency pool. A timeline opens on first use and stays warm.
use crate::{
catalog::timeline_directory_name,
knobs::{KnobLog, KnobStore},
play::PlayTable,
state_layout::prepare_timeline_directory,
waves::{WaveLog, WaveStore},
};
use ghostlight::{
CallRecordError, CallRecordStore, ControllerModels, ControllerPort, ControllerRunner,
InferencePort, LaneTokens, PersonaLane, RecordingInferencePort, RunId, RunStart, WorldMailbox,
WorldSnapshot, open_controller_work,
};
use anyhow::Context;
use std::{collections::HashMap, path::PathBuf, sync::Arc};
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc};
/// What every timeline shares: the one inference port all lanes route through,
/// the model each lane runs on, and the concurrency pool sized to the
/// connector's quota.
pub(crate) struct Shared {
pub(crate) inference: Arc<dyn InferencePort>,
pub(crate) models: ControllerModels,
pub(crate) play_model: String,
pub(crate) permits: Arc<Semaphore>,
}
/// One opened timeline.
pub(crate) struct TimelineHost {
pub(crate) world: WorldMailbox,
pub(crate) controllers: ControllerRunner,
pub(crate) play: Arc<PlayTable>,
/// Pulsed whenever this timeline's turn changes; the stream wakes on it.
pub(crate) changes: broadcast::Sender<()>,
/// Held while a run-ahead sweep runs: one at a time per timeline.
pub(crate) sweeping: Mutex<()>,
/// The spend ledgers of this timeline's background windows, one run each.
/// The play turn's own calls never reach it.
pub(crate) background: Arc<CallRecordStore>,
/// The world waves this timeline's closed turns planned, and what the DM
/// has been shown of them.
pub(crate) waves: WaveLog,
/// The DM's standing knobs for this timeline's world beyond the room.
pub(crate) knobs: KnobLog,
inference: Arc<dyn InferencePort>,
}
impl TimelineHost {
/// The port of the post-turn window that follows world revision
/// `revision`: the one port the background lanes call a provider
/// through, reserving each call in the window's ledger first. The window's
/// cap is its allowances together. A window at the same revision is the same
/// ledger, so a trigger that finds nothing changed spends no new allowance,
/// and a wave resumed after a restart reopens the ledger it opened in. The
/// caller passes the knobs' allowances every time and the ledger follows them,
/// keeping its spend: a tune binds the window already open.
/// `world` is the world the window is opened over now.
pub(crate) fn window(
&self,
revision: u64,
world: &WorldSnapshot,
allowances: LaneTokens,
) -> Result<RecordingInferencePort, CallRecordError> {
let run = RunId::new(&format!("window-{revision}"))?;
RecordingInferencePort::open_following(
self.inference.clone(),
self.background.clone(),
run,
allowances.total(),
allowances,
&RunStart::of(world),
)
}
}
pub(crate) struct Timelines {
root: PathBuf,
shared: Shared,
hosts: Mutex<HashMap<String, Arc<TimelineHost>>>,
fatal: mpsc::UnboundedSender<String>,
}
impl Timelines {
pub(crate) fn new(root: PathBuf, shared: Shared, fatal: mpsc::UnboundedSender<String>) -> Self {
Self {
root,
shared,
hosts: Mutex::new(HashMap::new()),
fatal,
}
}
pub(crate) fn shared(&self) -> &Shared {
&self.shared
}
/// The host for `id`, opened on first use. Refuses an id that is not
/// exactly `timeline:<canonical uuid>`.
pub(crate) async fn host(&self, id: &str) -> anyhow::Result<Arc<TimelineHost>> {
let name = timeline_directory_name(id).context("timeline id is not canonical")?;
let mut hosts = self.hosts.lock().await;
if let Some(host) = hosts.get(id) {
return Ok(host.clone());
}
let directory = prepare_timeline_directory(&self.root, &name)?;
let (world, owner) = WorldMailbox::open(directory.join("world.cc"))?;
let fatal = self.fatal.clone();
let label = id.to_owned();
tokio::spawn(async move {
let _ = owner.await;
let _ = fatal.send(format!("world owner of {label} stopped while serving"));
});
let work = open_controller_work(directory.join("controller-work.cc"))?;
let background = Arc::new(
CallRecordStore::open(directory.join("calls.cc"))
.context("the background call ledger could not be opened")?,
);
let waves: WaveLog = Arc::new(Mutex::new(
WaveStore::open(directory.join("waves.cc")).context("the wave store could not be opened")?,
));
let knobs: KnobLog = Arc::new(Mutex::new(
KnobStore::open(directory.join("gestalt-knobs.cc")).context("the knob store could not be opened")?,
));
let controllers = ControllerRunner::open(
world.clone(),
self.shared.inference.clone(),
work,
self.shared.models.clone(),
)?;
let personas = PersonaLane::new(
ControllerPort::new(world.clone()),
self.shared.inference.clone(),
self.shared.models.projector.clone(),
self.shared.models.persona.clone(),
)?;
let play = PlayTable::new(
world.clone(),
personas,
self.shared.inference.clone(),
self.shared.play_model.clone(),
self.shared.permits.clone(),
directory.join("play-turn-v1.cc"),
)?
.with_gears(waves.clone(), knobs.clone());
let (changes, _) = broadcast::channel(16);
let host = Arc::new(TimelineHost {
world,
controllers,
play: Arc::new(play),
changes,
sweeping: Mutex::new(()),
background,
waves,
knobs,
inference: self.shared.inference.clone(),
});
hosts.insert(id.to_owned(), host.clone());
Ok(host)
}
/// Every timeline opened so far; readiness probes these.
pub(crate) async fn opened(&self) -> Vec<(String, Arc<TimelineHost>)> {
self.hosts
.lock()
.await
.iter()
.map(|(id, host)| (id.clone(), host.clone()))
.collect()
}
}

View file

@ -0,0 +1,249 @@
//! The turn log: what the player was shown, turn by turn, kept for as long as
//! the timeline lives.
//!
//! The kernel journal records what happened in the world, not the prose the
//! storyteller wrote about it, and the play row holds only the current turn.
//! So the narration a player read exists in one place until the next turn
//! replaces it. This log is where it stays. It sits next to the timeline's
//! other state and is written by `PlayTable` from the row the screen is drawn
//! from, right after that row is committed, so an entry can never say
//! something the screen did not. It is append-only: nothing here edits or
//! deletes an entry, and a Retry is a new entry that names the one it retries.
use anyhow::{Context, bail, ensure};
use chrono::{DateTime, Utc};
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, path::Path};
const TYPE: &str = "ghostlight.dungeon_turn_log.v1";
/// How a submission ended, as the player was told.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TurnStatus {
/// The turn closed and narrated.
Committed,
/// The world refused an act of the turn; `refusal` holds the line.
Refused,
/// The turn died on its model; `fault` holds the line shown.
Faulted,
/// The storyteller asked a question and is waiting; `question` holds it.
Asked,
}
/// One submission and what it produced. `seq` is its place in the log, from 1.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct LogEntry {
pub(crate) seq: u64,
pub(crate) turn_id: String,
/// Which submission of that turn this is: 1 opens it, each answer adds one.
pub(crate) submission: u32,
/// The player's text exactly as sent.
pub(crate) text: String,
pub(crate) narration: Option<String>,
pub(crate) question: Option<String>,
pub(crate) refusal: Option<String>,
pub(crate) fault: Option<String>,
pub(crate) status: TurnStatus,
/// The world revision the entry rests on, or `None` when the kernel could
/// not be read at the moment the entry was written.
pub(crate) world_revision: Option<u64>,
/// The entry this one retries.
pub(crate) retry_of: Option<u64>,
pub(crate) recorded_at: DateTime<Utc>,
}
/// An entry before it has a place in the log.
pub(crate) struct NewEntry {
pub(crate) turn_id: String,
pub(crate) submission: u32,
pub(crate) text: String,
pub(crate) narration: Option<String>,
pub(crate) question: Option<String>,
pub(crate) refusal: Option<String>,
pub(crate) fault: Option<String>,
pub(crate) status: TurnStatus,
pub(crate) world_revision: Option<u64>,
pub(crate) retry_of: Option<u64>,
}
/// A page of the log, oldest first, newest last.
pub(crate) struct Page {
pub(crate) entries: Vec<(LogEntry, Option<u64>)>,
/// Pass as `before` to read the page of older entries; `None` at the start.
pub(crate) older: Option<u64>,
}
pub(crate) struct TurnLog {
store: OwnedRedbMessagePackBackingStore,
/// Every entry, `entries[n]` having `seq == n + 1`.
entries: Vec<LogEntry>,
}
fn key_of(seq: u64) -> String {
format!("{seq:012}")
}
impl TurnLog {
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
store.validate_path_identity().context("turn log path identity is invalid")?;
let mut entries = Vec::new();
for row in store.pull_all()? {
ensure!(row.r#type == TYPE, "turn log holds a foreign record");
let entry: LogEntry = rmp_serde::from_slice(&row.payload).context("a turn log entry did not decode")?;
ensure!(row.key == key_of(entry.seq), "a turn log entry sits under the wrong key");
entries.push(entry);
}
entries.sort_by_key(|entry| entry.seq);
for (index, entry) in entries.iter().enumerate() {
if entry.seq != index as u64 + 1 {
bail!("the turn log has a gap before entry {}", entry.seq);
}
}
Ok(Self { store, entries })
}
/// The `seq` of the newest entry; 0 for an empty log.
pub(crate) fn last_seq(&self) -> u64 {
self.entries.len() as u64
}
pub(crate) fn contains(&self, seq: u64) -> bool {
seq >= 1 && seq <= self.entries.len() as u64
}
pub(crate) fn recorded(&self, turn_id: &str, submission: u32) -> bool {
self.entries
.iter()
.rev()
.any(|entry| entry.turn_id == turn_id && entry.submission == submission)
}
/// Appends `new` unless that turn's submission is already recorded.
/// Returns the new entry's `seq`, or `None` when it was already there.
pub(crate) fn record(&mut self, new: NewEntry) -> anyhow::Result<Option<u64>> {
if self.recorded(&new.turn_id, new.submission) {
return Ok(None);
}
if let Some(target) = new.retry_of {
ensure!(self.contains(target), "a retry names an entry the log does not hold");
}
let seq = self.entries.len() as u64 + 1;
let entry = LogEntry {
seq,
turn_id: new.turn_id,
submission: new.submission,
text: new.text,
narration: new.narration,
question: new.question,
refusal: new.refusal,
fault: new.fault,
status: new.status,
world_revision: new.world_revision,
retry_of: new.retry_of,
recorded_at: Utc::now(),
};
let row = CultCacheEnvelope {
key: key_of(seq),
r#type: TYPE.into(),
payload: rmp_serde::to_vec_named(&entry)?,
stored_at: entry.recorded_at.to_rfc3339(),
schema_id: Some(TYPE.into()),
};
self.store.validate_path_identity().context("turn log ownership was lost")?;
if !self.store.compare_and_swap_batch(&[], vec![row])? {
bail!("turn log entry {seq} already exists on disk");
}
self.entries.push(entry);
Ok(Some(seq))
}
/// Up to `limit` entries older than `before` (the newest when `None`),
/// each with the `seq` of the entry that retried it, if one did.
pub(crate) fn page(&self, before: Option<u64>, limit: usize) -> Page {
let end = before.map_or(self.entries.len(), |before| (before.saturating_sub(1) as usize).min(self.entries.len()));
let start = end.saturating_sub(limit.max(1));
let retried_by: HashMap<u64, u64> = self
.entries
.iter()
.rev()
.filter_map(|entry| entry.retry_of.map(|target| (target, entry.seq)))
.collect();
let entries = self.entries[start..end]
.iter()
.map(|entry| (entry.clone(), retried_by.get(&entry.seq).copied()))
.collect();
Page { entries, older: (start > 0).then_some(start as u64 + 1) }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn new(turn: &str, submission: u32, text: &str) -> NewEntry {
NewEntry {
turn_id: turn.into(),
submission,
text: text.into(),
narration: Some(format!("story of {text}")),
question: None,
refusal: None,
fault: None,
status: TurnStatus::Committed,
world_revision: Some(7),
retry_of: None,
}
}
#[test]
fn entries_append_page_newest_last_and_survive_a_reopen() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("turn-log-v1.cc");
{
let mut log = TurnLog::open(&path).unwrap();
assert_eq!(log.last_seq(), 0);
for n in 1..=5 {
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
assert_eq!(log.last_seq(), n);
}
assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten");
let newest = log.page(None, 2);
assert_eq!(newest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [4, 5]);
assert_eq!(newest.older, Some(4));
let older = log.page(newest.older, 2);
assert_eq!(older.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [2, 3]);
let oldest = log.page(older.older, 2);
assert_eq!(oldest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [1]);
assert_eq!(oldest.older, None);
}
let log = TurnLog::open(&path).unwrap();
let all = log.page(None, 50);
assert_eq!(all.entries.len(), 5);
assert_eq!(all.entries[2].0.text, "say 3", "the first write stands");
assert_eq!(all.entries[2].0.narration.as_deref(), Some("story of say 3"));
}
#[test]
fn a_retry_is_a_new_entry_and_the_old_one_reads_as_superseded() {
let directory = tempfile::tempdir().unwrap();
let mut log = TurnLog::open(directory.path().join("turn-log-v1.cc")).unwrap();
let mut faulted = new("t1", 1, "I knock");
faulted.status = TurnStatus::Faulted;
faulted.narration = None;
faulted.fault = Some("the storyteller lost the thread".into());
log.record(faulted).unwrap();
let mut retry = new("t2", 1, "I knock");
retry.retry_of = Some(1);
log.record(retry).unwrap();
let page = log.page(None, 10);
assert_eq!(page.entries[0].0.status, TurnStatus::Faulted, "the old entry stays as it was");
assert_eq!(page.entries[0].1, Some(2), "and reads as superseded by the retry");
assert_eq!(page.entries[1].1, None);
let mut bad = new("t3", 1, "x");
bad.retry_of = Some(99);
assert!(log.record(bad).is_err(), "a retry must name an entry the log holds");
}
}

View file

@ -0,0 +1,249 @@
//! The production vault catalog: the profiles production serves, over the
//! snapshots an operator import left in the store.
//!
//! The daemon never reads a vault directory. `VaultSnapshot::build` is the
//! only reader of one, and it runs in the `import-vault` command; what lives
//! here is a read of the store the import wrote: which snapshot a profile last
//! produced, and that snapshot's evidence.
use crate::begin::{VaultOffer, VaultSeed, Vaults};
use anyhow::{Context, bail};
use ghostlight::{
EvidenceSource, SnapshotId, VaultEra, VaultEvidenceSource, VaultError, VaultSnapshot, WorldEra,
production_eras, production_profile, production_vault_names,
};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
/// The snapshot store, under the state root.
pub(crate) const SNAPSHOT_DIRECTORY: &str = "snapshots";
/// The directory the host keeps its vault copies in; the importer roots every
/// production profile under it.
pub(crate) const VAULT_BASE_ENVIRONMENT: &str = "GHOSTLIGHT_VAULT_BASE";
pub(crate) struct SnapshotVaults {
store: PathBuf,
/// A snapshot's evidence for one era, loaded once: every turn's run-ahead
/// sweep asks for it again. Cache only; the era is the world's.
evidence: Mutex<HashMap<(String, String), Arc<dyn EvidenceSource>>>,
}
impl SnapshotVaults {
pub(crate) fn new(state_root: &Path) -> Self {
Self {
store: state_root.join(SNAPSHOT_DIRECTORY),
evidence: Mutex::new(HashMap::new()),
}
}
fn imported(&self, profile: &str) -> Result<SnapshotId, VaultError> {
VaultSnapshot::current_id(&self.store, profile)
}
}
/// The evidence of `snapshot` for `era`, which withholds the era's paths; a
/// world with no era withholds nothing.
fn evidence_for(snapshot: &VaultSnapshot, era: Option<&VaultEra>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let evidence = VaultEvidenceSource::from_snapshot(snapshot, "", era.map_or(&[], |era| era.withhold))
.context("the snapshot holds no evidence")?;
Ok(Arc::new(evidence))
}
impl Vaults for SnapshotVaults {
fn offers(&self) -> Vec<VaultOffer> {
production_vault_names()
.filter(|name| self.imported(name).is_ok())
.filter_map(|name| {
let (eras, default) = production_eras(name)?;
Some(VaultOffer {
name: name.to_owned(),
default_era: default.to_owned(),
eras: eras.iter().map(world_era).collect(),
})
})
.collect()
}
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed> {
let Some((eras, default)) = production_eras(profile) else {
bail!("vault profile `{profile}` is not one this server serves");
};
let wanted = era.unwrap_or(default);
let chosen = eras
.iter()
.find(|candidate| candidate.id == wanted)
.with_context(|| format!("vault profile `{profile}` has no era `{wanted}`"))?;
let id = self
.imported(profile)
.map_err(|_| anyhow::anyhow!("vault profile `{profile}` has not been imported"))?;
let snapshot = VaultSnapshot::load(&self.store, &id)
.map_err(|error| anyhow::anyhow!("vault profile `{profile}`: {error}"))?;
let evidence = evidence_for(&snapshot, Some(chosen))?;
self.evidence
.lock()
.unwrap()
.insert((id.to_string(), chosen.id.to_owned()), evidence.clone());
Ok(VaultSeed {
snapshot_id: id.to_string(),
evidence,
premise: snapshot.premise(),
era: world_era(chosen),
})
}
fn evidence(&self, snapshot_id: &str, era: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
let key = (snapshot_id.to_owned(), era.unwrap_or_default().to_owned());
if let Some(held) = self.evidence.lock().unwrap().get(&key) {
return Ok(held.clone());
}
let id = SnapshotId::parse(snapshot_id).context("the snapshot id is not an id")?;
let snapshot = VaultSnapshot::load(&self.store, &id)
.map_err(|error| anyhow::anyhow!("snapshot {snapshot_id}: {error}"))?;
let name = &snapshot.profile().name;
let chosen = match era {
None => None,
Some(era) => Some(
production_eras(name)
.and_then(|(eras, _)| eras.iter().find(|candidate| candidate.id == era))
.with_context(|| format!("vault profile `{name}` has no era `{era}`"))?,
),
};
let evidence = evidence_for(&snapshot, chosen)?;
self.evidence.lock().unwrap().insert(key, evidence.clone());
Ok(evidence)
}
}
fn world_era(era: &VaultEra) -> WorldEra {
WorldEra {
id: era.id.to_owned(),
label: era.label.to_owned(),
description: era.description.to_owned(),
}
}
/// `ghostlight-dungeon import-vault --state-root PATH PROFILE`: the one reader
/// of a vault directory. Builds the production profile of `profile` rooted
/// under `$GHOSTLIGHT_VAULT_BASE`, stores the snapshot and records it as the
/// profile's current import. Prints the snapshot id.
pub(crate) fn import(state_root: &Path, profile: &str) -> anyhow::Result<String> {
let base = std::env::var_os(VAULT_BASE_ENVIRONMENT)
.map(PathBuf::from)
.with_context(|| format!("{VAULT_BASE_ENVIRONMENT} is required"))?;
let Some(profile) = production_profile(profile, &base) else {
bail!("vault profile `{profile}` is not one this server serves");
};
let store = state_root.join(SNAPSHOT_DIRECTORY);
let snapshot = VaultSnapshot::build(&profile).map_err(|error| anyhow::anyhow!("{error}"))?;
snapshot
.import_into(&store)
.map_err(|error| anyhow::anyhow!("{error}"))?;
snapshot
.record_current(&store)
.map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(format!("{} notes={} id={}", profile.name, snapshot.note_count(), snapshot.id()))
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, relative: &str, text: &str) {
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
/// An imported snapshot of a tiny Avatar vault under a state root.
fn imported_avatar() -> (tempfile::TempDir, SnapshotVaults, String) {
let state = tempfile::tempdir().unwrap();
let vault = tempfile::tempdir().unwrap();
write(vault.path(), "Avatar/index.md", "A river city under a spirit sky.\n");
write(vault.path(), "Avatar/Places/Harbor.md", "The harbor of the river city.\n");
let profile = production_profile("avatar", vault.path()).unwrap();
let snapshot = VaultSnapshot::build(&profile).unwrap();
let store = state.path().join(SNAPSHOT_DIRECTORY);
snapshot.import_into(&store).unwrap();
snapshot.record_current(&store).unwrap();
let id = snapshot.id().to_string();
let vaults = SnapshotVaults::new(state.path());
(state, vaults, id)
}
/// The id gate keeps a stored id from naming another path: a short hex
/// string and a long non-hex one are both refused before any path is built.
#[test]
fn a_stored_snapshot_id_that_is_not_an_id_is_refused_before_a_path_is_built() {
let (_state, vaults, id) = imported_avatar();
for bad in ["abc".to_owned(), format!("../{}", &id[3..]), id.to_uppercase()] {
let error = vaults.evidence(&bad, Some("rda-return")).err().expect("refused").to_string();
assert!(error.contains("not an id"), "{bad}: {error}");
}
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
}
#[test]
fn it_lists_the_imported_profiles_and_opens_the_recorded_snapshot() {
let (_state, vaults, id) = imported_avatar();
assert_eq!(vaults.offers().iter().map(|offer| offer.name.as_str()).collect::<Vec<_>>(), ["avatar"]);
let seed = vaults.open("avatar", None).unwrap();
assert_eq!(seed.snapshot_id, id);
assert_eq!(seed.premise.as_deref(), Some("A river city under a spirit sky."));
assert_eq!(seed.era.id, "rda-return", "an omitted era is the profile's default");
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
assert!(vaults.evidence(&id, Some("no-such-era")).is_err());
}
#[test]
fn a_profile_never_imported_is_refused_by_name_and_so_is_a_stranger() {
let (_state, vaults, _) = imported_avatar();
let never = vaults.open("zyphos", None).err().unwrap().to_string();
assert!(never.contains("`zyphos` has not been imported"), "{never}");
let stranger = vaults.open("../avatar", None).err().unwrap().to_string();
assert!(stranger.contains("is not one this server serves"), "{stranger}");
assert!(vaults.evidence("not-an-id", Some("rda-return")).is_err());
}
/// The daemon side is a read of the store alone: with the vault directory
/// gone the profile still opens.
#[test]
fn opening_a_profile_reads_the_store_and_never_the_vault() {
let (_state, vaults, _) = imported_avatar();
// `imported_avatar` dropped its vault directory already.
assert!(vaults.open("avatar", None).is_ok());
}
/// A pre-Elysium Aetheria world never sees the Post-Elysium folder, in the
/// seed's evidence or in the evidence reopened for run-ahead; a
/// post-Elysium world does.
#[tokio::test]
async fn a_pre_elysium_world_never_sees_the_post_elysium_folder() {
use ghostlight::EvidenceQuery;
let state = tempfile::tempdir().unwrap();
let vault = tempfile::tempdir().unwrap();
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Post-Elysium/Aether.md", "The aether answers espers.\n");
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Pre-Elysium/Collapse.md", "The grid fails.\n");
let snapshot = VaultSnapshot::build(&production_profile("aetheria", vault.path()).unwrap()).unwrap();
let store = state.path().join(SNAPSHOT_DIRECTORY);
snapshot.import_into(&store).unwrap();
snapshot.record_current(&store).unwrap();
let id = snapshot.id().to_string();
let vaults = SnapshotVaults::new(state.path());
let aether = EvidenceQuery { referents: vec!["Aether".into()] };
let seed = vaults.open("aetheria", None).unwrap();
assert_eq!(seed.era.id, "pre-elysium", "late Sol is the default");
assert!(seed.evidence.retrieve(&aether).await.unwrap().is_empty(), "the seed's evidence");
let reopened = vaults.evidence(&id, Some("pre-elysium")).unwrap();
assert!(reopened.retrieve(&aether).await.unwrap().is_empty(), "run-ahead's evidence");
let after = vaults.open("aetheria", Some("post-elysium")).unwrap();
assert!(!after.evidence.retrieve(&aether).await.unwrap().is_empty());
assert!(vaults.open("aetheria", Some("nowhen")).is_err());
}
}

View file

@ -0,0 +1,398 @@
//! The Dungeon's verbs: the affordance catalog every world Begin makes
//! declares, and the grant of it to every person.
//!
//! A fresh world knows only Speak. A deed the player may attempt but the world
//! cannot lower is a gap, so the Dungeon declares the deeds a table is made of:
//! attack, threaten and accuse. Each lowers to kernel effects the
//! kernel alone writes: regard in the target (`AdjustAttitude`), pressure
//! (`AdvancePressure`). The effects name no consequence
//! beyond the deed. Nothing here refuses a verb on grounds of niceness: a
//! sword is drawn when the preconditions hold (the target is in the room), and
//! what the world does about it is state the table reads, not a rule.
//!
//! A deed carries its witnesses through the kernel's own display lowering: the
//! table commits it with a `display` quote, which becomes a claim the whole room
//! holds as `Seen`. Who saw it is therefore kernel state, and the Open
//! grievances block of the table view is derived from it.
//!
//! What answers a deed is the table's judgement, not a rule here. The table
//! sees who was wronged, who saw it, which forums cover the doer and whether
//! anyone presses or has sworn a reckoning, and gives the office, the kin and
//! the witnesses their own turns, ruling pressure (`advance_pressure`) or a
//! sworn reckoning (`create_commitment`, an obligation with the doer as
//! counterparty: the kernel refuses a goal that has one) where it judges the
//! world would.
//!
//! Seams, recorded rather than patched:
//! - An institution that must react off-screen, with no person of it in the
//! room, is the Gestalt hierarchy's turn (`cut-gestalt-*`, not built). No
//! scheduler stands in for it here.
//! - Verbs are granted to the people a Begin holds. A person an Active
//! elaborator authors later holds only what its author grants by id.
//! - Steal, give, trade, seduce, persuade, flee, hide and move are not
//! declared: a seeded world holds no custody to transfer, and the others
//! lower to speech or to nothing the table cannot already rule.
use ghostlight::{DecodedBatch, SubjectKind, WorldSnapshot, decode_authoring_calls};
use serde_json::{Value, json};
/// The deed kinds this catalog declares, in the order declared.
pub(crate) const VERBS: [&str; 3] = ["attack", "threaten", "accuse"];
fn subject_role() -> Value {
json!({"namespace": "subject", "kind": null})
}
fn adjust(delta: i16) -> Value {
json!({"op_kind": {"op": "adjust_attitude", "delta": delta, "decay": null}, "roles": ["target"], "bounds": {"bound": "none"}})
}
fn colocated_target() -> Value {
json!({"precondition": "can_reach", "subject": "target", "via": "colocated"})
}
/// The declarations, as the authoring calls the Dungeon Master would make.
fn declarations() -> Vec<(&'static str, Value)> {
vec![
(
"declare_affordance",
// Three grades of harm, weighted so a blow usually lands. The
// regard the target holds of the actor falls by the grade; what the
// wound or death means is the table's ruling.
json!({
"handle": "attack",
"kind": "attack",
"roles": [{"role": "target", "kind": subject_role()}],
"preconditions": [colocated_target()],
"effect_slots": [adjust(-35), adjust(-70), adjust(-100)],
"outcome_bands": [
{"weight": 3, "effects": [0]},
{"weight": 3, "effects": [1]},
{"weight": 2, "effects": [2]},
],
"carries_speech": false,
}),
),
(
"declare_affordance",
json!({
"handle": "threaten",
"kind": "threaten",
"roles": [{"role": "target", "kind": subject_role()}],
"preconditions": [colocated_target()],
"effect_slots": [
{"op_kind": {"op": "advance_pressure", "by": 20}, "roles": ["target"], "bounds": {"bound": "none"}},
adjust(-25),
],
"outcome_bands": [{"weight": 1, "effects": [0, 1]}],
"carries_speech": false,
}),
),
(
"declare_affordance",
// A grievance carried to someone who can lean on the accused:
// pressure on the target from the accuser, who must hold the
// charge as something believed. An office answers through its own
// people using this same verb.
json!({
"handle": "accuse",
"kind": "accuse",
"roles": [
{"role": "target", "kind": subject_role()},
{"role": "charge", "kind": {"namespace": "entity", "kind": "fact"}},
],
"preconditions": [{"precondition": "knows", "fact": "charge", "at_least": "believed"}],
"effect_slots": [
{"op_kind": {"op": "advance_pressure", "by": 25}, "roles": ["target"], "bounds": {"bound": "none"}},
],
"outcome_bands": [{"weight": 1, "effects": [0]}],
"carries_speech": false,
}),
),
]
}
/// The one patch that declares the catalog and grants it to every person the
/// world holds. A world that already carries a verb is a replay of this step
/// and is not asked again by the caller.
pub(crate) fn install(world: &WorldSnapshot) -> Result<DecodedBatch, String> {
let mut calls: Vec<(String, String)> = declarations()
.into_iter()
.map(|(name, arguments)| (name.to_owned(), arguments.to_string()))
.collect();
for subject in world
.subjects
.iter()
.filter(|subject| subject.kind == SubjectKind::Person && !subject.retired)
{
for verb in VERBS {
calls.push((
"grant_affordance".to_owned(),
json!({
"subject": {"ref": "existing", "value": subject.id},
"affordance": {"ref": "draft", "value": verb},
})
.to_string(),
));
}
}
let borrowed: Vec<(&str, &str)> = calls.iter().map(|(name, arguments)| (name.as_str(), arguments.as_str())).collect();
decode_authoring_calls(&borrowed)
}
#[cfg(test)]
mod tests {
use super::*;
use ghostlight::{
CommandBody, CommandId, CreateWorldIntent, Lens, LensWeights, PlayPort, PrincipalCommandIntent,
SubjectId, VerifiedPrincipalEvidence, WorldMailbox, decode_actor_call, table_view,
};
use std::collections::BTreeMap;
struct Scenario {
_directory: tempfile::TempDir,
world: WorldMailbox,
principal: VerifiedPrincipalEvidence,
}
fn text(id: SubjectId) -> String {
serde_json::to_value(id).unwrap().as_str().unwrap().to_owned()
}
fn existing(id: impl serde::Serialize) -> Value {
json!({"ref": "existing", "value": id})
}
async fn snapshot(scene: &Scenario) -> ghostlight::WorldSnapshot {
scene.world.snapshot().await.unwrap()
}
fn who(snapshot: &ghostlight::WorldSnapshot, label: &str) -> SubjectId {
snapshot.subjects.iter().find(|subject| subject.label == label).expect("a subject by that label").id
}
async fn submit(scene: &Scenario, body: CommandBody) {
let snapshot = snapshot(scene).await;
scene
.world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: snapshot.world_id,
expected_revision: snapshot.revision,
body,
},
&scene.principal,
)
.await
.unwrap();
}
fn batch(calls: &[(&str, Value)]) -> ghostlight::WorldPatch {
let owned: Vec<(&str, String)> = calls.iter().map(|(name, arguments)| (*name, arguments.to_string())).collect();
let borrowed: Vec<(&str, &str)> = owned.iter().map(|(name, arguments)| (*name, arguments.as_str())).collect();
decode_authoring_calls(&borrowed).expect("the calls decode").patch
}
/// The table's own ruling, through the one door the Dungeon Master holds.
async fn rule(scene: &Scenario, calls: &[(&str, Value)]) {
PlayPort::new(scene.world.clone()).submit_patch(CommandId::new(), batch(calls)).await.unwrap();
}
/// A tavern with Dorra, her kin Brannoch and a witness, Grix; the Hold's
/// watch stands at the gate with Hilda. The player, Korr, is in the tavern.
/// Dorra counts Korr a friend, so nothing about the room is hostile.
async fn consequence_world() -> Scenario {
let directory = tempfile::tempdir().unwrap();
let (world, _owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
let principal = VerifiedPrincipalEvidence::new("consequence-scenario", chrono::Utc::now() + chrono::Duration::hours(4));
let receipt = world
.create(
CreateWorldIntent {
id: CommandId::new(),
title: "Consequence Scenario".into(),
brief: "A tavern, a gate and a watch.".into(),
human_subject_label: "Korr".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
era: None,
},
&principal,
)
.await
.unwrap();
let scene = Scenario { _directory: directory, world, principal };
let start = snapshot(&scene).await;
let commons = start.places.iter().find(|place| place.label == "The Commons").unwrap().id;
let speak = start.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id;
let subject = |handle: &str, label: &str, kind: &str, position: Value| {
(
"declare_subject",
json!({
"handle": handle,
"label": label,
"kind": kind,
"controller": {"type": "narrative_persona"},
"affordances": [existing(speak)],
"position": position,
}),
)
};
let patch = batch(&[
("declare_place", json!({"handle": "gate", "label": "The Gate", "container": null})),
(
"declare_route",
json!({"handle": "road", "label": "The Road", "from": existing(commons), "to": {"ref": "draft", "value": "gate"}, "access": {"access": "public"}, "cost": 1}),
),
subject("dorra", "Dorra Ironkettle", "person", existing(commons)),
subject("brann", "Brannoch Deepvein", "person", existing(commons)),
subject("grix", "Grix Sparkfinger", "person", existing(commons)),
subject("hilda", "Hilda Gatewright", "person", json!({"ref": "draft", "value": "gate"})),
subject("watch", "The Deepgate Watch", "institution", json!({"ref": "draft", "value": "gate"})),
]);
submit(&scene, CommandBody::AdmitPatch { answers: None, patch }).await;
let drafted = snapshot(&scene).await;
let (dorra, korr) = (who(&drafted, "Dorra Ironkettle"), who(&drafted, "Korr"));
submit(
&scene,
CommandBody::AdmitPatch {
answers: None,
patch: batch(&[(
"declare_attitude",
json!({"holder": existing(dorra), "toward": {"toward": "subject", "of": existing(korr)}, "delta": 80, "basis": {"basis": "prejudice"}, "decay": null}),
)]),
},
)
.await;
let drafted = snapshot(&scene).await;
submit(&scene, CommandBody::AdmitPatch { answers: None, patch: install(&drafted).unwrap().patch }).await;
submit(&scene, CommandBody::ApproveDraft).await;
submit(&scene, CommandBody::ActivateWorld).await;
let _ = receipt;
scene
}
async fn attack(scene: &Scenario, victim: &str, display: &str) -> Result<(), ghostlight::MailboxError> {
let now = snapshot(scene).await;
let (korr, victim) = (who(&now, "Korr"), who(&now, victim));
let arguments = json!({"target": text(victim), "display": display}).to_string();
let (opportunity, invocation) = decode_actor_call(&now, korr, "", "attack", &arguments).expect("the player may attack");
scene
.world
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: now.world_id,
expected_revision: now.revision,
body: CommandBody::ExerciseDecision { opportunity, invocation },
},
&scene.principal,
)
.await
.map(|_| ())
}
const DEED: &str = "Korr buries his axe in Dorra.";
fn open_grievances(view: &str) -> String {
view.split("Open grievances").nth(1).unwrap().split("\n Persona material").next().unwrap().to_owned()
}
fn between<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` not in view")) + from.len();
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
&text[start..end]
}
#[tokio::test]
async fn nothing_forbids_the_sword_and_the_room_sees_it() {
let scene = consequence_world().await;
// Dorra is the player's friend, and the attack is admitted all the same.
attack(&scene, "Dorra Ironkettle", DEED).await.expect("an attack on a friend is admitted");
let view = table_view(&snapshot(&scene).await);
let grievances = open_grievances(&view);
let seen = between(&grievances, "acts seen by:", "forums covering");
for witness in ["Grix Sparkfinger", "Brannoch Deepvein", "Dorra Ironkettle"] {
assert!(seen.contains(witness), "{witness} stands in the room and saw it: {seen}");
}
assert!(!seen.contains("Hilda"), "the gate is out of earshot and out of sight: {seen}");
assert!(grievances.contains("Korr"), "{grievances}");
assert!(grievances.contains("nothing has answered it yet"), "{grievances}");
let subjects = between(&view, "Subjects:", "
Affordances");
let watch = between(subjects, "The Deepgate Watch [", "holdings");
assert!(watch.contains("institution") && !watch.contains("attack"), "an institution is granted no sword: {watch}");
let player = between(subjects, "Korr [", "holdings");
for verb in VERBS {
assert!(player.contains(verb), "the player holds {verb}: {player}");
}
}
#[tokio::test]
async fn an_unseen_world_has_no_open_grievance() {
let scene = consequence_world().await;
assert!(open_grievances(&table_view(&snapshot(&scene).await)).trim().ends_with("none"));
}
#[tokio::test]
async fn word_spreads_law_presses_and_kin_swear() {
let scene = consequence_world().await;
attack(&scene, "Dorra Ironkettle", DEED).await.unwrap();
let now = snapshot(&scene).await;
let view = table_view(&now);
let (korr, grix, hilda, brann) =
(who(&now, "Korr"), who(&now, "Grix Sparkfinger"), who(&now, "Hilda Gatewright"), who(&now, "Brannoch Deepvein"));
let quoted = format!("\"{DEED}\" [");
let deed = between(&view, &quoted, "]").to_owned();
let road = between(&view, "The Road [", "]").to_owned();
assert!(!between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard has not heard");
// The witness walks to the gate and tells the guard.
rule(&scene, &[("relocate", json!({"subject": existing(grix), "via": existing(road)}))]).await;
rule(&scene, &[("communicate", json!({"speaker": existing(grix), "fact": existing(&deed), "to": "colocated"}))]).await;
let view = table_view(&snapshot(&scene).await);
assert!(between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard was told");
// Believing it, the guard regards the killer worse than a stranger.
rule(
&scene,
&[(
"declare_attitude",
json!({"holder": existing(hilda), "toward": {"toward": "subject", "of": existing(korr)}, "delta": -60, "basis": {"basis": "rumour", "fact": existing(&deed)}, "decay": null}),
)],
)
.await;
let view = table_view(&snapshot(&scene).await);
assert!(between(&view, "Regard (", "Persona material").contains("Hilda Gatewright ["), "{view}");
// The law leans on the player, and the grievance is no longer unanswered.
assert!(open_grievances(&view).contains("nothing has answered it yet"));
rule(&scene, &[("advance_pressure", json!({"source": {"from": "subject", "of": existing(hilda)}, "target": existing(korr), "by": 30}))]).await;
let pressed = open_grievances(&table_view(&snapshot(&scene).await));
assert!(between(&pressed, "pressed by:", "reckonings").contains("Hilda Gatewright"), "{pressed}");
assert!(!pressed.contains("nothing has answered it yet"), "{pressed}");
// The victim's kin swear a reckoning with the player as counterparty.
rule(
&scene,
&[(
"create_commitment",
json!({"subject": existing(brann), "counterparty": existing(korr), "kind": "obligation", "due": 600, "period": null, "checks": [], "statement": "Make Korr answer for Dorra."}),
)],
)
.await;
let sworn = open_grievances(&table_view(&snapshot(&scene).await));
assert!(between(&sworn, "reckonings sworn against them:", "answered").contains("Brannoch Deepvein"), "{sworn}");
}
#[test]
fn no_verb_text_refuses_violence() {
let lower = serde_json::to_string(&declarations()).unwrap().to_lowercase();
assert!(!lower.contains("not allowed to attack"));
assert!(lower.find("refuse").is_none_or(|at| !lower[at..].contains("violence")));
assert_eq!(declarations().len(), VERBS.len());
}
}

File diff suppressed because it is too large Load diff

View file

@ -54,6 +54,19 @@ pub struct ProjectorPrompt<'a> {
pub word_budget: usize,
}
/// What the storyteller is given to narrate a human player's own view. The
/// player is not a Persona: nothing here is lived from inside them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NarratorPrompt<'a> {
pub player: &'a str,
pub typed_context: &'a str,
/// What the player wrote this turn: the player's own act, which is not in their own knowledge.
pub player_turn: &'a str,
pub visible_stimulus: &'a str,
pub domain_guidance: &'a str,
pub word_budget: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonaPrompt<'a> {
pub identity: &'a str,
@ -93,6 +106,43 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String {
)
}
/// The storyteller's contract: it tells the player, in second person, what just
/// happened and where they now stand, and is never the player or anyone else in
/// the story. It is handed facts and told to tell a story from them: the
/// context and stimulus are material, not a form to be read down.
pub fn build_narrator_prompt(input: &NarratorPrompt<'_>) -> String {
format!(
"<!-- membrane:{MEMBRANE_SCHEMA}:narrator -->
You are the storyteller of a long-running tale, telling the player what has just happened and where they now stand. The player's character is {player}. Speak to the player in the second person, present tense (\"You turn to Mira...\"); never in the first person, and never as {player} or any other character.
Tell it the way a storyteller at a table would, in a few short paragraphs of plain prose:
- Begin with what the player just did, in their own words where they spoke, as theirs (\"You ask...\"), then give what came of it. When people answered or acted, let them: render each reply in that person's own voice, quoting their words exactly as the visible stimulus gives them, with a gesture or a beat of stage business around it, never summarised. Do not invent replies; if no one has answered, say who is looking at you, waiting, or turning away.
- Then settle the scene: who is here and what they are doing, the feel of the place, and the ways out worked in naturally (\"the passage toward the Ironmarket\"), the way a person standing there would notice them.
- Tell only what the facts below establish. Name only the people, places and routes they name; invent none, and do not say what lies beyond an exit. What the facts leave out is simply not told: never remark that something is unknown, absent, empty or missing, never list what the player has, holds, lacks or has not promised, and never give a number, a count or a cost.
- Do not recite. Do not list what the player could do next or close on a menu of options; do not choose actions for the player, expose field names, or claim effects in the world.
Domain guidance:
{guidance}
Facts about where the player stands:
{context}
What the player did this turn, in their own words:
{player_turn}
What the player has seen and heard (rows marked new are the most recent):
{stimulus}
Use at most {word_budget} words; fewer is better. Return only the telling.",
player = input.player,
guidance = input.domain_guidance,
context = input.typed_context,
player_turn = input.player_turn,
stimulus = input.visible_stimulus,
word_budget = input.word_budget,
)
}
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
format!(
"Everything below is prose from inside one person's life. Be that person and respond only from what the moment establishes. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, conjecture, or deliberate invention by the character, and name it as such. Do not give yourself a temperament, a history, a mood, a relationship, or a turn of phrase the moment did not give you; if the moment gives you little, say little, or nothing. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words; fewer is better. Return only the character's natural response in prose.",

View file

@ -0,0 +1,15 @@
[package]
name = "ghostlight-verse"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
chrono.workspace = true
ghostlight = { path = "../ghostlight" }
tokio.workspace = true
[dev-dependencies]
serde_json.workspace = true
tempfile = "3"

View file

@ -0,0 +1,411 @@
//! The verse runner's operator command line.
//!
//! `genesis` creates the canonical Aetheria verse world in a state root, and
//! `run` advances it a given number of ticks under a token cap, printing per
//! tick what each faction did and what it cost. A run starts only when this
//! command is invoked, and ends when it has done what it was asked.
//!
//! The state root holds `world.cc`, `controller-work.cc`, `runs.cc` and
//! `calls.cc`. The provider key is read from a file at run time and appears
//! nowhere else.
use anyhow::{Context, Result, anyhow, bail};
use chrono::{Duration, Utc};
use ghostlight::{
CommandBody, CommandId, ControllerModels, ControllerOpenError, ControllerRunner, DEFAULT_HOSTED_MODEL_PREFIX,
DEFAULT_LOCAL_MODEL_PREFIX, CallRecordStore, CoverBudget, CreateVerseWorldIntent,
GestaltKnobs, HostedBinding, LaneTokens, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort,
RunStart, RunStatus, TickMinutes, VerifiedPrincipalEvidence, VerseRunConfig, VerseRunStore,
WorldMailbox, call_run_id, id_text, open_controller_work, open_inference,
read_aetheria_catalog, run_manual,
};
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
/// The default knobs' cover: what a manual run spends per tick on cognition
/// cells inside one node. The operator's lever on cost is the token cap; the
/// partition covers every voice of a due node.
const COVER: CoverBudget = CoverBudget {
cells: 8,
constituent_cap: 8,
urgency_slots: 2,
};
/// Default depth: only the root is open, so every faction speaks as a voice
/// of one node at the tick's own rate, the shape of the flat cover.
const DEPTH: u8 = 1;
/// Default node-turn bound per tick: far above the world's node count.
const MAX_NODE_TURNS: u16 = 256;
const RUNTIME_ID: &str = "ghostlight-verse";
#[tokio::main]
async fn main() -> ExitCode {
let arguments: Vec<String> = std::env::args().skip(1).collect();
match command(arguments).await {
Ok(code) => code,
Err(error) => {
eprintln!("ghostlight-verse: {error:#}");
ExitCode::FAILURE
}
}
}
async fn command(arguments: Vec<String>) -> Result<ExitCode> {
let Some((name, rest)) = arguments.split_first() else {
bail!("usage: ghostlight-verse genesis|run [flags]");
};
match name.as_str() {
"genesis" => genesis(Flags::parse(rest, &GENESIS_FLAGS)?).await,
"run" => run(Flags::parse(rest, &RUN_FLAGS)?).await,
_ => bail!("unknown command, expected genesis or run"),
}
}
const GENESIS_FLAGS: [&str; 4] = ["catalog", "aetheria-commit", "state", "owner-hash"];
const RUN_FLAGS: [&str; 9] = [
"state",
"ticks",
"token-cap",
"tick-span-minutes",
"model",
"base-url",
"key-file",
"depth",
"band",
];
/// Flags a command may omit.
const OPTIONAL: [&str; 3] = ["key-file", "depth", "band"];
/// Flags that may be given more than once.
const REPEATABLE: [&str; 1] = ["band"];
/// `--name value` pairs from the command's own list, each named once unless it
/// is repeatable, in which case its values keep the order given.
struct Flags(BTreeMap<&'static str, Vec<String>>);
impl Flags {
fn parse(arguments: &[String], allowed: &[&'static str]) -> Result<Self> {
let mut seen: BTreeMap<&'static str, Vec<String>> = BTreeMap::new();
let mut rest = arguments.iter();
while let Some(flag) = rest.next() {
let Some(name) = flag.strip_prefix("--") else {
bail!("expected a --flag, found a bare argument");
};
let Some(&known) = allowed.iter().find(|candidate| **candidate == name) else {
bail!("a flag this command does not take was given");
};
let Some(value) = rest.next() else {
bail!("--{known} needs a value");
};
let values = seen.entry(known).or_default();
if !values.is_empty() && !REPEATABLE.contains(&known) {
bail!("--{known} was given twice");
}
values.push(value.clone());
}
for &required in allowed {
if !OPTIONAL.contains(&required) && !seen.contains_key(required) {
bail!("--{required} is required");
}
}
Ok(Self(seen))
}
fn text(&self, name: &str) -> &str {
self.0.get(name).and_then(|values| values.first()).map_or("", String::as_str)
}
fn all(&self, name: &str) -> &[String] {
self.0.get(name).map_or(&[], Vec::as_slice)
}
fn path(&self, name: &str) -> PathBuf {
PathBuf::from(self.text(name))
}
fn number<T: std::str::FromStr + PartialOrd + Default>(&self, name: &str) -> Result<T> {
match self.text(name).parse::<T>() {
Ok(value) if value > T::default() => Ok(value),
_ => bail!("--{name} is not a positive integer"),
}
}
}
/// The run's knobs: the flags over the defaults. With no `--band` the one band
/// is the tick span; `--band DIST=MINUTES` gives the period of the nodes
/// DIST hops from the focus (the last band is the rest, and a verse tick has no
/// focus, so only that one governs). Bands must be given for distances 0, 1, 2
/// and so on, with no gap.
fn knobs(flags: &Flags, tick_span: TickMinutes) -> Result<GestaltKnobs> {
let depth = if flags.0.contains_key("depth") {
flags.number::<u8>("depth")?
} else {
DEPTH
};
let mut given: BTreeMap<usize, TickMinutes> = BTreeMap::new();
for band in flags.all("band") {
let parsed = band.split_once('=').and_then(|(distance, minutes)| {
Some((distance.parse::<usize>().ok()?, TickMinutes::new(minutes.parse().ok()?)?))
});
let Some((distance, minutes)) = parsed else {
bail!("--band is not DIST=MINUTES with a minutes value inside the clock's span");
};
if given.insert(distance, minutes).is_some() {
bail!("--band names one distance twice");
}
}
let bands = if given.is_empty() {
vec![tick_span]
} else if given.keys().copied().eq(0..given.len()) {
given.into_values().collect()
} else {
bail!("--band must name distances 0, 1, 2 and so on without a gap");
};
Ok(GestaltKnobs {
bands,
depth,
max_node_turns: MAX_NODE_TURNS,
cover: COVER,
})
}
async fn genesis(flags: Flags) -> Result<ExitCode> {
let state = flags.path("state");
std::fs::create_dir_all(&state).context("the state directory cannot be created")?;
let catalog = read_aetheria_catalog(flags.path("catalog"))
.context("the Aetheria catalog cannot be read")?;
let factions = catalog.factions.len();
let principal = VerifiedPrincipalEvidence::new(flags.text("owner-hash"), Utc::now() + Duration::hours(1));
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
.map_err(store_fault("the world file in --state cannot be opened"))?;
let receipt = mailbox
.create_verse(
CreateVerseWorldIntent {
id: CommandId::new(),
title: "The Aetheria Verse".into(),
brief: "The Aetheria verse, simulated from its catalog.".into(),
catalog,
aetheria_commit: flags.text("aetheria-commit").into(),
lens_weights: LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()),
targets: BTreeMap::new(),
},
&principal,
)
.await
.context("the verse world cannot be created")?;
// A created world is a draft: the owner approves and activates it, so the
// factions hold opportunities.
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let revision = mailbox.snapshot().await.context("the world cannot be read")?.revision;
mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: receipt.world_id,
expected_revision: revision,
body,
},
&principal,
)
.await
.context("the world cannot be activated")?;
}
drop(mailbox);
task.await.context("the world file did not close cleanly")?;
println!("world {}", id_text(receipt.world_id));
println!("factions {factions}");
println!("phase Active");
Ok(ExitCode::SUCCESS)
}
async fn run(flags: Flags) -> Result<ExitCode> {
let state = flags.path("state");
let ticks: u32 = flags.number("ticks")?;
let cap: u64 = flags.number("token-cap")?;
let span: u32 = flags.number("tick-span-minutes")?;
let tick_span = TickMinutes::new(span).context("--tick-span-minutes is outside the clock's span")?;
let knobs = knobs(&flags, tick_span)?;
if !state.join("world.cc").is_file() {
bail!("the state directory holds no world; run genesis first");
}
let model = flags.text("model").to_owned();
let models = ControllerModels {
projector: model.clone(),
persona: model.clone(),
interpreter: model.clone(),
operational_agent: model.clone(),
elaborator: model.clone(),
};
let inner = open_lane(&flags, &model, &models)?;
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
.map_err(store_fault("the world file in --state cannot be opened"))?;
let world = mailbox.snapshot().await.context("the world cannot be read")?;
let calls = Arc::new(CallRecordStore::open(state.join("calls.cc")).map_err(store_fault("the call records in --state cannot be opened"))?);
let runs = VerseRunStore::open(state.join("runs.cc")).map_err(store_fault("the run records in --state cannot be opened"))?;
let work = open_controller_work(state.join("controller-work.cc"))
.map_err(store_fault("the controller work store in --state cannot be opened"))?;
let config = VerseRunConfig {
ticks,
tick_span,
knobs,
};
let claim = runs
.claim(&world, cap, &config)
.context("the run cannot be claimed")?;
let sequence = claim.sequence();
// A start that fails after the claim ends the claimed run, so it binds
// nothing: the next claim takes the next number.
let started = RecordingInferencePort::open(
inner,
calls,
call_run_id(sequence),
cap,
// The run's token cap is the wave lane's allowance; the verse runs no
// elaborator, so that lane has none.
LaneTokens {
wave: cap,
elaboration: 0,
},
&RunStart::of(&world),
)
.context("the run's call records cannot be opened")
.and_then(|port| {
let port = Arc::new(port);
ControllerRunner::open(mailbox.clone(), port.clone(), work, models)
.map(|runner| (port, runner))
.context("the controller organ cannot open")
});
let (port, runner) = match started {
Ok(started) => started,
Err(error) => {
return Err(match runs.abandon(claim, "start_refused") {
Ok(()) => error,
Err(_) => error.context("the refused run's record could not be ended"),
});
}
};
println!(
"run {sequence}: {ticks} ticks of {span} minutes, cap {cap} tokens, model {model}"
);
let interrupted = Arc::new(AtomicBool::new(false));
{
let interrupted = interrupted.clone();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
interrupted.store(true, Ordering::SeqCst);
}
});
}
let outcome = run_manual(
&mailbox,
&runner,
&port,
&runs,
claim,
&config,
|report| {
print!("{report}");
if interrupted.load(Ordering::SeqCst) {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
},
)
.await
.context("the run could not be recorded")?;
println!(
"status: {}; {} of {} ticks closed",
outcome.record.status,
outcome.record.ticks_closed(),
outcome.record.ticks_requested
);
drop(runner);
drop(port);
drop(mailbox);
task.await.context("the world file did not close cleanly")?;
Ok(match outcome.record.status {
RunStatus::Failed { .. } => ExitCode::FAILURE,
_ => ExitCode::SUCCESS,
})
}
/// The inference lane the model's prefix names. A hosted model needs an https
/// origin and a key file; a local one reaches a loopback server and needs
/// neither, so a key file beside it is refused.
fn open_lane(
flags: &Flags,
model: &str,
models: &ControllerModels,
) -> Result<Arc<dyn ghostlight::InferencePort>> {
let (mut hosted, mut local) = (None, None);
if model.starts_with(DEFAULT_HOSTED_MODEL_PREFIX) {
let Some(key) = flags.0.get("key-file").and_then(|values| values.first()) else {
bail!("a hosted model needs --key-file");
};
hosted = Some(HostedBinding {
base_url: flags.text("base-url").to_owned(),
key_path: Path::new(key).to_owned(),
model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(),
caller_runtime_id: RUNTIME_ID.into(),
});
} else if model.starts_with(DEFAULT_LOCAL_MODEL_PREFIX) {
if flags.0.contains_key("key-file") {
bail!("a local model takes no --key-file");
}
let endpoint: SocketAddr = flags
.text("base-url")
.strip_prefix("http://")
.and_then(|address| address.trim_end_matches('/').parse().ok())
.context("--base-url for a local model is not http://<address>:<port>")?;
local = Some(LocalBinding {
endpoint,
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
caller_runtime_id: RUNTIME_ID.into(),
});
} else {
bail!("--model names no inference lane (expected a hosted/ or local/ prefix)");
}
open_inference(None, None, local, hosted, &models.each())
.map_err(|error| anyhow!(lane_fault(&error)))
}
/// A store that cannot open says which one and that it is under `--state`,
/// never the path or the store's own text, which carries the path.
fn store_fault<E>(message: &'static str) -> impl FnOnce(E) -> anyhow::Error {
move |_| anyhow!(message)
}
/// What a lane that cannot open says: the flag or the kind of fault, never a
/// value the operator passed.
fn lane_fault(error: &ControllerOpenError) -> &'static str {
match error {
ControllerOpenError::InvalidModels => "--model is not an exact nonempty identifier",
ControllerOpenError::Connector(_) => "the connector lane cannot open",
ControllerOpenError::WorkStore(_) => "the controller work journal cannot open",
ControllerOpenError::UnroutableModel { .. } => "--model is claimed by no inference lane",
ControllerOpenError::SdkSidecarMissing { .. } => "the SDK sidecar entry is not a file",
ControllerOpenError::LocalEndpointNotLoopback { .. } => {
"--base-url for a local model must be a loopback address"
}
ControllerOpenError::HostedEndpointNotHttps => {
"--base-url for a hosted model must be an https URL"
}
ControllerOpenError::HostedKeyUnreadable => {
"--key-file is unreadable, empty, or not one run of visible ASCII"
}
ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix",
ControllerOpenError::SidecarClaimsConnectorModel { .. } => {
"the SDK sidecar prefix claims a connector model"
}
ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty",
}
}

View file

@ -0,0 +1,490 @@
//! The `ghostlight-verse` command against a loopback scripted responder. No
//! real model is called and no key file is read: the responder answers the
//! OpenAI-compatible chat-completions request the local lane sends.
use serde_json::{Value, json};
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::process::{Command, Output};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
const BINARY: &str = env!("CARGO_BIN_EXE_ghostlight-verse");
const CATALOG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../ghostlight/tests/fixtures/aetheria-verse-catalog.cc"
);
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
/// What the responder reports each call cost: 120 prompt and 30 completion.
const PER_CALL: u64 = 150;
fn verse(arguments: &[&str]) -> Output {
Command::new(BINARY).args(arguments).output().unwrap()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).into_owned()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).into_owned()
}
fn genesis(state: &Path) -> Output {
verse(&[
"genesis",
"--catalog",
CATALOG,
"--aetheria-commit",
COMMIT,
"--state",
state.to_str().unwrap(),
"--owner-hash",
"verse-owner",
])
}
/// Answers every chat-completions request with one tool call: the faction the
/// prompt names speaks its own line. Counts the requests it served.
struct Responder {
address: SocketAddr,
served: Arc<AtomicUsize>,
}
impl Responder {
fn start() -> Self {
Self::answering(200)
}
/// A provider that refuses every call with this status.
fn refusing(status: u16) -> Self {
Self::answering(status)
}
fn answering(status: u16) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let served = Arc::new(AtomicUsize::new(0));
let counter = served.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let counter = counter.clone();
std::thread::spawn(move || serve(stream, &counter, status));
}
});
Self { address, served }
}
fn url(&self) -> String {
format!("http://{}", self.address)
}
}
fn serve(mut stream: TcpStream, served: &AtomicUsize, status: u16) {
let mut raw = Vec::new();
let mut chunk = [0u8; 4096];
let (head_end, length) = loop {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
return;
}
raw.extend_from_slice(&chunk[..read]);
if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
let head = String::from_utf8_lossy(&raw[..end]).to_ascii_lowercase();
let length = head
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.and_then(|value| value.trim().parse::<usize>().ok())
.unwrap_or(0);
break (end + 4, length);
}
};
while raw.len() < head_end + length {
let read = stream.read(&mut chunk).unwrap_or(0);
if read == 0 {
return;
}
raw.extend_from_slice(&chunk[..read]);
}
let request: Value = serde_json::from_slice(&raw[head_end..head_end + length]).unwrap();
let text = request.to_string();
let faction = ["Adrasteia", "Brannoch"]
.into_iter()
.find(|name| text.contains(&format!("Decision owner:\\n{name}\\n")))
.expect("a request names its faction");
let sequence = served.fetch_add(1, Ordering::SeqCst);
let reply = json!({
"id": format!("reply-{sequence}"),
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": format!("call-{sequence}"),
"type": "function",
"function": {
"name": "speak",
"arguments": json!({ "text": format!("{faction} holds the line.") }).to_string(),
},
}],
},
"finish_reason": "tool_calls",
}],
"usage": { "prompt_tokens": 120, "completion_tokens": 30 },
})
.to_string();
let response = format!(
"HTTP/1.1 {status} Scripted\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
reply.len()
);
let _ = stream.write_all(response.as_bytes());
}
fn run(state: &Path, responder: &Responder, ticks: &str, cap: &str) -> Output {
run_with(state, responder, ticks, cap, &[])
}
fn run_with(state: &Path, responder: &Responder, ticks: &str, cap: &str, extra: &[&str]) -> Output {
let url = responder.url();
let mut arguments = vec![
"run",
"--state",
state.to_str().unwrap(),
"--ticks",
ticks,
"--token-cap",
cap,
"--tick-span-minutes",
"60",
"--model",
"local/scripted",
"--base-url",
&url,
];
arguments.extend_from_slice(extra);
verse(&arguments)
}
#[test]
fn binary_run_takes_depth_and_band_flags_and_reports_by_node() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let responder = Responder::start();
let output = run_with(
state.path(),
&responder,
"1",
"1000000",
&["--depth", "8", "--band", "0=60", "--band", "1=240"],
);
assert!(output.status.success(), "{}", stderr(&output));
let text = stdout(&output);
// Opened to every institution, each faction is its own node; with no focus
// each sits at the last band's index.
for faction in ["Adrasteia", "Brannoch"] {
assert!(text.contains(&format!(" node {faction} (distance 1): ")), "{text}");
}
assert!(text.contains("tick 0 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
}
#[test]
fn binary_run_prints_acts_and_spend() {
let state = tempfile::tempdir().unwrap();
let made = genesis(state.path());
assert!(made.status.success(), "{}", stderr(&made));
let made = stdout(&made);
assert!(made.contains("factions 2\n") && made.contains("phase Active\n"), "{made}");
assert!(state.path().join("world.cc").is_file());
let responder = Responder::start();
let output = run(state.path(), &responder, "2", "1000000");
assert!(output.status.success(), "{}", stderr(&output));
let text = stdout(&output);
// Two ticks, each with both factions named by verb, and the spend as it
// accrues against the cap.
assert!(text.starts_with("run 1: 2 ticks of 60 minutes, cap 1000000 tokens"), "{text}");
for tick in 0..2u64 {
let spent = PER_CALL * 2 * (tick + 1);
assert!(
text.contains(&format!("tick {tick} closed: 2 cells, 2 acts, 0 refused\n")),
"{text}"
);
assert!(
text.contains(&format!(
" tokens: {} this tick, {spent} spent, {} remaining\n",
PER_CALL * 2,
1_000_000 - spent
)),
"{text}"
);
}
for faction in ["Adrasteia", "Brannoch"] {
assert_eq!(
text.matches(&format!(" {faction} speak [")).count(),
2,
"{text}"
);
assert!(text.contains(&format!("says \"{faction} holds the line.\"")), "{text}");
}
assert!(text.ends_with("status: Completed; 2 of 2 ticks closed\n"), "{text}");
assert_eq!(responder.served.load(Ordering::SeqCst), 4);
// The state root holds each store the run wrote.
for file in ["world.cc", "controller-work.cc", "runs.cc", "calls.cc"] {
assert!(state.path().join(file).is_file(), "{file} was not written");
}
// A second run is the next in the world and carries on from its clock.
let again = run(state.path(), &responder, "1", "1000000");
assert!(again.status.success(), "{}", stderr(&again));
let text = stdout(&again);
assert!(text.starts_with("run 2: 1 ticks of 60 minutes"), "{text}");
assert!(text.contains("tick 2 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
}
#[test]
fn a_cap_the_first_call_could_pass_ends_the_run_with_nothing_spent() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let responder = Responder::start();
let output = run(state.path(), &responder, "3", "1000");
assert!(output.status.success(), "{}", stderr(&output));
let text = stdout(&output);
assert!(text.contains("tick 0 open: "), "{text}");
assert!(text.contains("tokens: 0 this tick, 0 spent, 1000 remaining"), "{text}");
assert!(text.ends_with("status: BudgetExhausted; 0 of 3 ticks closed\n"), "{text}");
assert_eq!(responder.served.load(Ordering::SeqCst), 0, "no call was made");
}
#[test]
fn a_run_that_fails_says_so_and_exits_nonzero() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let responder = Responder::refusing(500);
let output = run(state.path(), &responder, "2", "1000000");
assert!(!output.status.success());
let text = stdout(&output);
assert!(text.contains("tick 0 open: "), "{text}");
assert!(
text.ends_with("status: Failed (inference_recovery_required); 0 of 2 ticks closed\n"),
"{text}"
);
assert_eq!(
responder.served.load(Ordering::SeqCst),
1,
"the run stopped at the first refusal"
);
}
#[test]
fn the_command_refuses_what_it_cannot_run_and_never_echoes_a_value() {
let state = tempfile::tempdir().unwrap();
let responder = Responder::start();
// No world yet.
let output = run(state.path(), &responder, "1", "1000");
assert!(!output.status.success());
assert!(stderr(&output).contains("run genesis first"), "{}", stderr(&output));
assert!(genesis(state.path()).status.success());
// A second genesis does not overwrite the first.
assert!(!genesis(state.path()).status.success());
let secret = "sk-not-a-real-key-0000";
let key = state.path().join(secret);
let cases: [(Vec<&str>, &str); 11] = [
(vec![], "usage"),
(vec!["fly"], "unknown command"),
(
vec!["run", "--state", state.path().to_str().unwrap(), "--ticks", "0"],
"--token-cap is required",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "many",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--ticks is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "0",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--ticks is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "0", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1",
],
"--token-cap is not a positive integer",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "gpt-4",
"--base-url", "http://127.0.0.1:1",
],
"--model names no inference lane",
),
(
// A hosted model needs its key file; a missing one is named by flag.
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "hosted/x",
"--base-url", "https://api.example.test", "--key-file", key.to_str().unwrap(),
],
"--key-file is unreadable",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1", "--key-file", key.to_str().unwrap(),
],
"a local model takes no --key-file",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1", "--band", "1=60",
],
"--band must name distances 0, 1, 2",
),
(
vec![
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
"--base-url", "http://127.0.0.1:1", "--depth", "0",
],
"--depth is not a positive integer",
),
];
for (arguments, expected) in cases {
let output = verse(&arguments);
assert!(!output.status.success(), "{arguments:?} succeeded");
let error = stderr(&output);
assert!(error.contains(expected), "{arguments:?}: {error}");
assert!(!error.contains(secret), "{arguments:?} echoed a path: {error}");
assert!(!error.contains("many"), "{arguments:?} echoed a value: {error}");
}
}
#[test]
fn a_non_loopback_local_endpoint_is_refused_without_echoing_it() {
let state = tempfile::tempdir().unwrap();
assert!(genesis(state.path()).status.success());
let output = verse(&[
"run",
"--state",
state.path().to_str().unwrap(),
"--ticks",
"1",
"--token-cap",
"1000",
"--tick-span-minutes",
"60",
"--model",
"local/x",
"--base-url",
"http://10.77.0.99:4242",
]);
assert!(!output.status.success());
let error = stderr(&output);
assert!(error.contains("--base-url"), "{error}");
assert!(!error.contains("10.77.0.99"), "the endpoint was echoed: {error}");
// The lane failed before any run was claimed.
assert!(!stdout(&output).contains("run 1"), "{}", stdout(&output));
}
/// A start refused after its claim ends the claimed record Failed, so the run
/// binds nothing. Reached from the command by removing the run records while
/// the call ledger still holds run 1 under another cap.
#[test]
fn a_start_the_ledger_refuses_ends_its_claimed_record_failed() {
let parent = tempfile::tempdir().unwrap();
let state = parent.path().join("state");
std::fs::create_dir_all(&state).unwrap();
assert!(genesis(&state).status.success());
let responder = Responder::start();
let first = run(&state, &responder, "1", "1000000");
assert!(first.status.success(), "{}", stderr(&first));
std::fs::remove_file(state.join("runs.cc")).unwrap();
let refused = run(&state, &responder, "1", "500000");
assert!(!refused.status.success());
let world = {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let _entered = runtime.enter();
let (mailbox, task) = ghostlight::WorldMailbox::open(state.join("world.cc")).unwrap();
let world = runtime.block_on(mailbox.snapshot()).unwrap().world_id;
drop(mailbox);
runtime.block_on(task).unwrap();
world
};
let runs = ghostlight::VerseRunStore::open(state.join("runs.cc"))
.unwrap()
.runs(world)
.unwrap();
assert_eq!(runs.len(), 1);
assert_eq!(
runs[0].status,
ghostlight::RunStatus::Failed {
reason: "start_refused".into()
}
);
}
/// A store that cannot open names the flag and the fault, never the path.
#[test]
fn a_store_that_cannot_open_never_echoes_the_state_path() {
let responder = Responder::start();
for file in ["world.cc", "controller-work.cc"] {
for held in [false, true] {
let parent = tempfile::tempdir().unwrap();
let state = parent.path().join("distinctivestatename");
std::fs::create_dir_all(&state).unwrap();
assert!(genesis(&state).status.success());
let first = run(&state, &responder, "1", "1000000");
assert!(first.status.success(), "{}", stderr(&first));
let target = state.join(file);
let _guard: Box<dyn std::any::Any> = if !held {
std::fs::write(&target, b"not a database").unwrap();
Box::new(())
} else if file == "world.cc" {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let entered = runtime.enter();
let opened = ghostlight::WorldMailbox::open(&target).unwrap();
drop(entered);
Box::new((runtime, opened))
} else {
Box::new(ghostlight::open_controller_work(&target).unwrap())
};
let output = run(&state, &responder, "1", "1000000");
assert!(!output.status.success(), "{file} held={held}");
let error = stderr(&output);
assert!(error.contains("--state"), "{file} held={held}: {error}");
assert!(
!error.contains("distinctivestatename"),
"{file} held={held} echoed the path: {error}"
);
}
}
}

View file

@ -7,11 +7,12 @@ license.workspace = true
[dependencies]
async-trait.workspace = true
chrono.workspace = true
codex-connector.workspace = true
model-connector.workspace = true
cultcache-rs.workspace = true
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
reqwest.workspace = true
rmp-serde.workspace = true
rmpv = "1.3"
serde.workspace = true
serde_bytes = "0.11"
serde_json.workspace = true
@ -19,6 +20,8 @@ sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
unicode-normalization = "0.1.25"
unicode-properties = "0.1.4"
uuid.workspace = true
zeroize.workspace = true

View file

@ -928,6 +928,14 @@ fn lower(
source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)),
target: subject(0)?,
},
// The regarded subject is the actor, so a proposer cannot aim one
// person's grudge at a third party; the delta is the entry's.
ComponentOpKind::AdjustAttitude { delta, decay } => patch::ComponentOp::AdjustAttitude {
holder: subject(0)?,
toward: patch::Ref::Existing(actor),
delta: *delta,
decay: *decay,
},
ComponentOpKind::Relocate => patch::ComponentOp::Relocate {
subject: subject(0)?,
via: edge(1)?,
@ -2834,7 +2842,8 @@ mod tests {
| ComponentOpKind::CreateCommitment { .. }
| ComponentOpKind::AdvancePressure { .. }
| ComponentOpKind::ReducePressure { .. }
| ComponentOpKind::ResolvePressure => false,
| ComponentOpKind::ResolvePressure
| ComponentOpKind::AdjustAttitude { .. } => false,
}
}

View file

@ -0,0 +1,297 @@
//! Aetheria's catalog file, read once into the two things Ghostlight takes from
//! it: the verse grammar, as a `GrammarBinding`, and the factions, as records
//! keyed for import.
//!
//! The catalog is Aetheria's: this reader opens it read-only and never writes
//! it, and it ignores every schema it does not mirror. The mirrors below decode
//! `aetheria.verse_grammar` v1, `aetheria.verse_verb` v1 and `aetheria.faction`
//! v1 by integer key: a MessagePack-keyed object is an array indexed by key,
//! nil in the gaps, so a field Aetheria adds later at a higher key is ignored
//! and a field it drops is an error naming the record and the key. A record
//! that does not decode, an enum value outside the mirror and a verb that
//! breaks the grammar's name or role rules are errors, never skipped rows.
use crate::ImportKey;
use crate::grammar::{
GrammarBinding, GrammarError, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath,
};
use cultcache_rs::SingleFileMessagePackBackingStore;
use rmpv::Value;
use std::collections::BTreeMap;
use std::path::Path;
const GRAMMAR_SCHEMA: &str = "aetheria.verse_grammar";
const VERB_SCHEMA: &str = "aetheria.verse_verb";
const FACTION_SCHEMA: &str = "aetheria.faction";
const VERB_NAME_MAX: usize = 48;
const ROLE_NAME_MAX: usize = 32;
/// The invoking subject, never a role.
const ACTOR_ROLE: &str = "actor";
/// What Ghostlight takes from Aetheria's catalog.
#[derive(Clone, Debug, PartialEq)]
pub struct AetheriaCatalog {
pub grammar: GrammarBinding,
/// In record-key order.
pub factions: Vec<AetheriaFaction>,
}
/// One `aetheria.faction` record. `allegiance` is carried and read by no
/// consumer yet.
#[derive(Clone, Debug, PartialEq)]
pub struct AetheriaFaction {
pub key: ImportKey,
pub name: String,
pub short_name: String,
pub description: String,
pub allegiance: BTreeMap<ImportKey, f32>,
}
/// Which of the grammar's name or role rules a verb broke.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum VerbRule {
#[error("verb name is not canonical")]
Name,
#[error("role name is not canonical")]
RoleName,
#[error("role name is reserved for the invoking subject")]
ReservedRole,
#[error("role name is declared twice")]
DuplicateRole,
}
/// Why a catalog could not be read. Records are named by record key and fields
/// by integer key; no error carries a value the catalog held.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CatalogReadError {
#[error("the catalog file cannot be read")]
Unreadable,
#[error("the catalog holds no aetheria.verse_grammar global")]
NoGrammar,
#[error("the catalog holds more than one aetheria.verse_grammar record")]
MultipleGrammars,
#[error("record {record:?} field {field} is missing or not the mirrored type")]
MalformedRecord { record: String, field: u8 },
#[error("record {record:?} field {field} is not a canonical import key")]
NonCanonicalKey { record: String, field: u8 },
#[error("record {record:?} is a second aetheria.faction under one record key")]
DuplicateFaction { record: String },
#[error("record {record:?} field {field} is not a known render path")]
UnknownRenderPath { record: String, field: u8 },
#[error("record {record:?} field {field} is not a known referent kind")]
UnknownReferentKind { record: String, field: u8 },
#[error("verb record {record:?} breaks a grammar rule: {rule}")]
InvalidVerb { record: String, rule: VerbRule },
#[error("the verbs do not bind a grammar: {0}")]
Grammar(#[from] GrammarError),
}
/// Reads the catalog at `path` without writing it. An absent file is
/// `Unreadable`, not an empty catalog.
pub fn read_aetheria_catalog(path: impl AsRef<Path>) -> Result<AetheriaCatalog, CatalogReadError> {
let path = path.as_ref();
std::fs::metadata(path).map_err(|_| CatalogReadError::Unreadable)?;
let mut rows = SingleFileMessagePackBackingStore::new(path)
.pull_all_read_only_snapshot()
.map_err(|_| CatalogReadError::Unreadable)?;
rows.sort_by(|a, b| a.key.cmp(&b.key));
let mut revision = None;
let mut verbs = Vec::new();
let mut factions = Vec::new();
for row in &rows {
match row.r#type.as_str() {
GRAMMAR_SCHEMA => {
if revision.is_some() {
return Err(CatalogReadError::MultipleGrammars);
}
let cells = Cells::of(&row.key, &row.payload)?;
revision = Some(u32::try_from(cells.int(1)?).map_err(|_| cells.malformed(1))?);
}
VERB_SCHEMA => verbs.push(read_verb(&Cells::of(&row.key, &row.payload)?)?),
FACTION_SCHEMA => {
let faction = read_faction(&row.key, &Cells::of(&row.key, &row.payload)?)?;
if factions
.last()
.is_some_and(|seen: &AetheriaFaction| seen.key == faction.key)
{
return Err(CatalogReadError::DuplicateFaction {
record: row.key.clone(),
});
}
factions.push(faction);
}
_ => {}
}
}
let revision = revision.ok_or(CatalogReadError::NoGrammar)?;
Ok(AetheriaCatalog {
grammar: GrammarBinding::new(GRAMMAR_SCHEMA, revision, verbs)?,
factions,
})
}
/// A record's payload: the positional array of its keyed fields.
struct Cells<'a> {
record: &'a str,
cells: Vec<Value>,
}
impl<'a> Cells<'a> {
fn of(record: &'a str, payload: &[u8]) -> Result<Self, CatalogReadError> {
let mut payload = payload;
match rmpv::decode::read_value(&mut payload) {
Ok(Value::Array(cells)) => Ok(Self { record, cells }),
_ => Err(CatalogReadError::MalformedRecord {
record: record.to_owned(),
field: 0,
}),
}
}
fn malformed(&self, field: u8) -> CatalogReadError {
CatalogReadError::MalformedRecord {
record: self.record.to_owned(),
field,
}
}
fn non_canonical(&self, field: u8) -> CatalogReadError {
CatalogReadError::NonCanonicalKey {
record: self.record.to_owned(),
field,
}
}
fn cell(&self, field: u8) -> Result<&Value, CatalogReadError> {
self.cells
.get(usize::from(field))
.ok_or_else(|| self.malformed(field))
}
fn int(&self, field: u8) -> Result<i64, CatalogReadError> {
self.cell(field)?
.as_i64()
.ok_or_else(|| self.malformed(field))
}
fn text(&self, field: u8) -> Result<String, CatalogReadError> {
self.cell(field)?
.as_str()
.map(str::to_owned)
.ok_or_else(|| self.malformed(field))
}
/// A string Aetheria may leave null; null reads as empty.
fn text_or_empty(&self, field: u8) -> Result<String, CatalogReadError> {
match self.cell(field)? {
Value::Nil => Ok(String::new()),
Value::String(text) => text
.as_str()
.map(str::to_owned)
.ok_or_else(|| self.malformed(field)),
_ => Err(self.malformed(field)),
}
}
fn array(&self, field: u8) -> Result<&Vec<Value>, CatalogReadError> {
self.cell(field)?
.as_array()
.ok_or_else(|| self.malformed(field))
}
}
fn read_verb(cells: &Cells) -> Result<(String, GrammarVerb), CatalogReadError> {
let invalid = |rule| CatalogReadError::InvalidVerb {
record: cells.record.to_owned(),
rule,
};
let name = cells.text(1)?;
if !canonical_name(&name, VERB_NAME_MAX) {
return Err(invalid(VerbRule::Name));
}
let render_path = match cells.int(2)? {
1 => RenderPath::ShipAction,
2 => RenderPath::Conversation,
_ => {
return Err(CatalogReadError::UnknownRenderPath {
record: cells.record.to_owned(),
field: 2,
});
}
};
let mut roles: Vec<GrammarRole> = Vec::new();
for role in cells.array(3)? {
let role = Cells {
record: cells.record,
cells: role.as_array().cloned().ok_or_else(|| cells.malformed(3))?,
};
let role_name = role.text(1).map_err(|_| cells.malformed(3))?;
if !canonical_name(&role_name, ROLE_NAME_MAX) {
return Err(invalid(VerbRule::RoleName));
}
if role_name == ACTOR_ROLE {
return Err(invalid(VerbRule::ReservedRole));
}
if roles.iter().any(|seen| seen.role == role_name) {
return Err(invalid(VerbRule::DuplicateRole));
}
let referent = match role.int(2).map_err(|_| cells.malformed(3))? {
1 => GrammarReferentKind::Person,
2 => GrammarReferentKind::Faction,
3 => GrammarReferentKind::Population,
4 => GrammarReferentKind::Place,
5 => GrammarReferentKind::Cargo,
_ => {
return Err(CatalogReadError::UnknownReferentKind {
record: cells.record.to_owned(),
field: 3,
});
}
};
roles.push(GrammarRole {
role: role_name,
referent,
});
}
Ok((name, GrammarVerb { render_path, roles }))
}
/// A lower-case letter, then lower-case letters, digits and underscores.
fn canonical_name(name: &str, max_len: usize) -> bool {
let mut chars = name.chars();
name.len() <= max_len
&& chars.next().is_some_and(|c| c.is_ascii_lowercase())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
fn read_faction(key: &str, cells: &Cells) -> Result<AetheriaFaction, CatalogReadError> {
let own = ImportKey::new(FACTION_SCHEMA, key);
if !own.is_canonical() {
return Err(cells.non_canonical(0));
}
let Some(allegiance) = cells.cell(12)?.as_map() else {
return Err(cells.malformed(12));
};
let mut standing = BTreeMap::new();
for (other, weight) in allegiance {
let other = other.as_str().ok_or_else(|| cells.malformed(12))?;
let weight = weight.as_f64().ok_or_else(|| cells.malformed(12))?;
let other = ImportKey::new(FACTION_SCHEMA, other);
if !other.is_canonical() {
return Err(cells.non_canonical(12));
}
standing.insert(other, weight as f32);
}
Ok(AetheriaFaction {
key: own,
name: cells.text(1)?,
short_name: cells.text_or_empty(2)?,
description: cells.text_or_empty(3)?,
allegiance: standing,
})
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,589 @@
use super::*;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope};
use serde_json::{Value, json};
/// Written by Aetheria's own fixture writer (`VerseGrammarTests.WriteFixture`)
/// at Aetheria master 92b82e9a; never edited. See `tests/fixtures/aetheria-verse-catalog.provenance.txt`.
const FIXTURE: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/aetheria-verse-catalog.cc"
);
fn fixture_rows() -> Vec<CultCacheEnvelope> {
SingleFileMessagePackBackingStore::new(FIXTURE)
.pull_all_read_only_snapshot()
.unwrap()
}
fn row_of<'a>(rows: &'a mut [CultCacheEnvelope], key: &str) -> &'a mut CultCacheEnvelope {
rows.iter_mut().find(|row| row.key == key).unwrap()
}
/// Re-encodes one record's positional payload after `edit`.
fn edit(rows: &mut [CultCacheEnvelope], key: &str, change: impl FnOnce(&mut Vec<Value>)) {
let row = row_of(rows, key);
let Value::Array(mut cells) = rmp_serde::from_slice(&row.payload).unwrap() else {
panic!("{key} is not a positional record");
};
change(&mut cells);
row.payload = rmp_serde::to_vec(&Value::Array(cells)).unwrap();
}
fn catalog_of(rows: &[CultCacheEnvelope]) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("catalog.cc");
let mut store = SingleFileMessagePackBackingStore::new(&path);
for row in rows {
store.push(row).unwrap();
}
(dir, path)
}
fn read(rows: &[CultCacheEnvelope]) -> Result<AetheriaCatalog, CatalogReadError> {
let (_dir, path) = catalog_of(rows);
read_aetheria_catalog(&path)
}
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
GrammarVerb {
render_path: path,
roles: roles
.iter()
.map(|(role, referent)| GrammarRole {
role: (*role).into(),
referent: *referent,
})
.collect(),
}
}
/// What Aetheria's fixture writer authored, spelled out by hand.
fn authored_verbs() -> Vec<(String, GrammarVerb)> {
vec![
(
"haul".into(),
verb(
RenderPath::ShipAction,
&[
("cargo", GrammarReferentKind::Cargo),
("destination", GrammarReferentKind::Place),
],
),
),
(
"attack".into(),
verb(
RenderPath::ShipAction,
&[("target", GrammarReferentKind::Faction)],
),
),
("speak".into(), verb(RenderPath::Conversation, &[])),
]
}
fn faction_key(record: &str) -> ImportKey {
ImportKey::new("aetheria.faction", record)
}
#[test]
fn reads_the_aetheria_written_fixture() {
let catalog = read_aetheria_catalog(FIXTURE).unwrap();
let identity = catalog.grammar.identity();
assert_eq!(identity.schema_id, "aetheria.verse_grammar");
assert_eq!(identity.revision, 1);
for (kind, expected) in authored_verbs() {
assert_eq!(catalog.grammar.verb(&kind), Some(&expected), "{kind}");
}
assert!(catalog.grammar.verb("mine").is_none());
assert_eq!(
catalog.factions,
vec![
AetheriaFaction {
key: faction_key("faction-adrasteia"),
name: "Adrasteia".into(),
short_name: "ADR".into(),
description: "First.".into(),
allegiance: BTreeMap::from([(faction_key("faction-brannoch"), 0.75)]),
},
AetheriaFaction {
key: faction_key("faction-brannoch"),
name: "Brannoch".into(),
short_name: "BRN".into(),
description: "Second.".into(),
allegiance: BTreeMap::from([(faction_key("faction-adrasteia"), 0.25)]),
},
]
);
}
#[test]
fn grammar_digest_matches_a_binding_built_by_hand() {
let by_hand = GrammarBinding::new("aetheria.verse_grammar", 1, authored_verbs()).unwrap();
let read = read_aetheria_catalog(FIXTURE).unwrap().grammar;
assert_eq!(read.identity().digest, by_hand.identity().digest);
assert_eq!(read, by_hand);
// The digest follows the verbs: a role the file drops is a different grammar.
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| {
cells[3].as_array_mut().unwrap().pop();
});
assert_ne!(
read_catalog_digest(&rows),
by_hand.identity().digest,
"dropping a role did not move the digest"
);
}
fn read_catalog_digest(rows: &[CultCacheEnvelope]) -> String {
read(rows).unwrap().grammar.identity().digest
}
#[test]
fn refuses_a_catalog_without_a_grammar() {
let mut rows = fixture_rows();
rows.retain(|row| row.r#type != "aetheria.verse_grammar");
assert_eq!(read(&rows), Err(CatalogReadError::NoGrammar));
}
#[test]
fn refuses_a_second_grammar_record() {
let mut rows = fixture_rows();
let mut second = rows
.iter()
.find(|row| row.r#type == "aetheria.verse_grammar")
.unwrap()
.clone();
second.key.push_str("-again");
rows.push(second);
assert_eq!(read(&rows), Err(CatalogReadError::MultipleGrammars));
}
#[test]
fn refuses_an_unknown_render_path() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| cells[2] = json!(3));
let error = read(&rows).unwrap_err();
assert_eq!(
error,
CatalogReadError::UnknownRenderPath {
record: "verb-haul".into(),
field: 2
}
);
assert!(!error.to_string().contains('3'), "the value was echoed");
}
#[test]
fn refuses_an_unknown_referent_kind() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-attack", |cells| {
cells[3][0][2] = json!(9);
});
assert_eq!(
read(&rows),
Err(CatalogReadError::UnknownReferentKind {
record: "verb-attack".into(),
field: 3
})
);
}
#[test]
fn a_verb_breaking_the_name_or_role_rules_is_refused_by_key() {
let broken = |mutate: fn(&mut Vec<Value>)| {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", mutate);
read(&rows).unwrap_err()
};
let invalid = |rule| CatalogReadError::InvalidVerb {
record: "verb-haul".into(),
rule,
};
assert_eq!(
broken(|cells| cells[1] = json!("Haul")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("1haul")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("")),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[1] = json!("h".repeat(49))),
invalid(VerbRule::Name)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("Cargo")),
invalid(VerbRule::RoleName)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("c".repeat(33))),
invalid(VerbRule::RoleName)
);
assert_eq!(
broken(|cells| cells[3][0][1] = json!("actor")),
invalid(VerbRule::ReservedRole)
);
assert_eq!(
broken(|cells| cells[3][1][1] = json!("cargo")),
invalid(VerbRule::DuplicateRole)
);
}
#[test]
fn the_longest_canonical_names_are_admitted() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| {
cells[1] = json!(format!("h{}9", "_9".repeat(23)));
cells[3][0][1] = json!(format!("c{}", "z".repeat(31)));
});
let catalog = read(&rows).unwrap();
assert_eq!(catalog.grammar.identity().revision, 1);
}
#[test]
fn two_verbs_with_one_name_do_not_bind() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-haul", |cells| cells[1] = json!("attack"));
assert_eq!(
read(&rows),
Err(CatalogReadError::Grammar(GrammarError::DuplicateVerb))
);
}
#[test]
fn a_record_that_is_not_the_mirrored_shape_is_named_by_key_and_field() {
let malformed = |record: &str, field| CatalogReadError::MalformedRecord {
record: record.into(),
field,
};
let mut rows = fixture_rows();
row_of(&mut rows, "faction-brannoch").payload =
rmp_serde::to_vec(&json!("not an array")).unwrap();
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 0)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[1] = Value::Null
});
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 1)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[12] = json!({"faction-adrasteia": "heavy"});
});
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| cells.truncate(12));
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
let mut rows = fixture_rows();
let grammar = rows
.iter()
.find(|row| row.r#type == "aetheria.verse_grammar")
.unwrap()
.key
.clone();
edit(&mut rows, &grammar, |cells| cells[1] = json!(-1));
assert_eq!(read(&rows), Err(malformed(&grammar, 1)));
}
#[test]
fn fields_aetheria_adds_and_schemas_it_does_not_mirror_are_ignored() {
let mut rows = fixture_rows();
edit(&mut rows, "verb-speak", |cells| cells.push(json!("later")));
edit(&mut rows, "faction-adrasteia", |cells| cells.push(json!(7)));
let mut stranger = rows[0].clone();
stranger.key = "ship-1".into();
stranger.r#type = "aetheria.ship".into();
stranger.schema_id = Some("sha256:not-mirrored".into());
stranger.payload = vec![0xc1];
rows.push(stranger);
assert_eq!(
read(&rows).unwrap(),
read_aetheria_catalog(FIXTURE).unwrap()
);
}
#[test]
fn a_null_short_name_or_description_reads_as_empty() {
let mut rows = fixture_rows();
edit(&mut rows, "faction-adrasteia", |cells| {
cells[2] = Value::Null;
cells[3] = Value::Null;
});
let catalog = read(&rows).unwrap();
assert_eq!(catalog.factions[0].short_name, "");
assert_eq!(catalog.factions[0].description, "");
}
#[test]
fn an_absent_file_is_unreadable_not_an_empty_catalog() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(
read_aetheria_catalog(dir.path().join("missing.cc")),
Err(CatalogReadError::Unreadable)
);
}
#[test]
fn reading_leaves_the_catalog_and_its_directory_untouched() {
let (dir, path) = catalog_of(&fixture_rows());
let bytes = std::fs::read(&path).unwrap();
let listing = |dir: &std::path::Path| {
let mut names: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
names.sort();
names
};
let before = listing(dir.path());
read_aetheria_catalog(&path).unwrap();
read_aetheria_catalog(&path).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
assert_eq!(listing(dir.path()), before, "the reader created a file");
}
#[test]
fn every_referent_code_maps_to_its_own_kind() {
// The fixture binds only Faction, Cargo and Place; Person and Population
// are authored here at the role's integer key, each read back as itself.
for (code, expected) in [
(1, GrammarReferentKind::Person),
(2, GrammarReferentKind::Faction),
(3, GrammarReferentKind::Population),
(4, GrammarReferentKind::Place),
(5, GrammarReferentKind::Cargo),
] {
let mut rows = fixture_rows();
edit(&mut rows, "verb-attack", |cells| {
cells[3][0][2] = json!(code)
});
let catalog = read(&rows).unwrap();
assert_eq!(
catalog.grammar.verb("attack"),
Some(&verb(RenderPath::ShipAction, &[("target", expected)])),
"code {code}"
);
}
}
fn faction_with_key(record: &str) -> Vec<CultCacheEnvelope> {
let mut rows = fixture_rows();
row_of(&mut rows, "faction-brannoch").key = record.into();
rows
}
#[test]
fn a_faction_record_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
for bad in [
"faction-cafe\u{301}",
"faction-brannoch ",
"faction-\u{202e}brannoch",
"",
] {
assert_eq!(
read(&faction_with_key(bad)),
Err(CatalogReadError::NonCanonicalKey {
record: bad.into(),
field: 0
}),
"{bad:?}"
);
}
}
#[test]
fn an_allegiance_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
for bad in ["faction-cafe\u{301}", "faction-adrasteia ", "\u{202e}"] {
let mut rows = fixture_rows();
edit(&mut rows, "faction-brannoch", |cells| {
cells[12] = json!({ bad: 0.5 });
});
assert_eq!(
read(&rows),
Err(CatalogReadError::NonCanonicalKey {
record: "faction-brannoch".into(),
field: 12
}),
"{bad:?}"
);
}
}
/// The fixture's snapshot bytes with the record rows changed by `change`, for
/// what the store's own writer will not produce: it keeps one row per record
/// key and stores rows in key order.
fn spliced_catalog(
change: impl FnOnce(&mut Vec<rmpv::Value>),
) -> (tempfile::TempDir, std::path::PathBuf) {
let bytes = std::fs::read(FIXTURE).unwrap();
let rmpv::Value::Array(mut snapshot) = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap()
else {
panic!("snapshot is not a tuple");
};
let rmpv::Value::Array(records) = &mut snapshot[2] else {
panic!("snapshot holds no records");
};
change(records);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("catalog.cc");
let mut spliced = Vec::new();
rmpv::encode::write_value(&mut spliced, &rmpv::Value::Array(snapshot)).unwrap();
std::fs::write(&path, spliced).unwrap();
(dir, path)
}
#[test]
fn two_faction_rows_under_one_record_key_are_refused() {
let (_dir, path) = spliced_catalog(|records| {
let twin = records
.iter()
.find(|record| record[0].as_str() == Some("faction-adrasteia"))
.unwrap()
.clone();
records.push(twin);
});
assert_eq!(
read_aetheria_catalog(&path),
Err(CatalogReadError::DuplicateFaction {
record: "faction-adrasteia".into()
})
);
}
#[test]
fn factions_are_read_in_record_key_order_whatever_the_file_order() {
let (_dir, path) = spliced_catalog(|records| {
records.sort_by(|a, b| b[0].as_str().cmp(&a[0].as_str()));
assert_eq!(records[0][0].as_str(), Some("verb-speak"));
});
let names: Vec<_> = read_aetheria_catalog(&path)
.unwrap()
.factions
.into_iter()
.map(|faction| faction.name)
.collect();
assert_eq!(names, ["Adrasteia", "Brannoch"]);
}
#[test]
fn an_allegiance_that_is_not_a_map_is_malformed_not_empty() {
for not_a_map in [
json!([]),
json!(["faction-adrasteia"]),
Value::Null,
json!(1),
] {
let mut rows = fixture_rows();
let shape = not_a_map.clone();
edit(&mut rows, "faction-brannoch", |cells| cells[12] = shape);
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: 12
}),
"{not_a_map}"
);
}
}
/// Appends cells to a faction as Aetheria's C# CultCache writes a `byte[]`
/// (MessagePack bin) and a `DateTime` (MessagePack timestamp, ext -1).
#[test]
fn bin_and_ext_fields_aetheria_adds_at_higher_keys_are_ignored() {
let mut rows = fixture_rows();
let row = row_of(&mut rows, "faction-adrasteia");
let rmpv::Value::Array(mut cells) =
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
else {
panic!("not positional");
};
cells.push(rmpv::Value::Binary(vec![1, 0, 7]));
cells.push(rmpv::Value::Ext(
-1,
vec![0, 0, 0, 0, 0x65, 0x1f, 0x2a, 0x80],
));
let mut payload = Vec::new();
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
row.payload = payload;
assert_eq!(
read(&rows).unwrap(),
read_aetheria_catalog(FIXTURE).unwrap()
);
}
/// A faction record re-encoded with `change` applied to its decoded cells, for
/// shapes `serde_json` cannot spell: a non-string map key, raw invalid bytes.
fn with_cells(key: &str, change: impl FnOnce(&mut Vec<rmpv::Value>)) -> Vec<CultCacheEnvelope> {
let mut rows = fixture_rows();
let row = row_of(&mut rows, key);
let rmpv::Value::Array(mut cells) =
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
else {
panic!("not positional");
};
change(&mut cells);
let mut payload = Vec::new();
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
row.payload = payload;
rows
}
#[test]
fn an_allegiance_key_that_is_not_a_string_is_malformed_by_key_and_field() {
for key in [
rmpv::Value::from(5),
rmpv::Value::Nil,
rmpv::Value::Binary(b"faction-adrasteia".to_vec()),
] {
let rows = with_cells("faction-brannoch", |cells| {
cells[12] = rmpv::Value::Map(vec![(key, rmpv::Value::F64(0.5))]);
});
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: 12
})
);
}
}
#[test]
fn text_that_is_not_utf8_is_malformed_by_key_and_field() {
// The marker is overwritten in the encoded bytes with an invalid sequence of
// the same length, since a decoded string cannot hold one.
const MARKER: &str = "ZZZZ";
for field in [1usize, 3] {
let mut rows = with_cells("faction-brannoch", |cells| {
cells[field] = rmpv::Value::from(MARKER);
});
let payload = &mut row_of(&mut rows, "faction-brannoch").payload;
let at = payload
.windows(MARKER.len())
.position(|window| window == MARKER.as_bytes())
.unwrap();
payload[at..at + MARKER.len()].copy_from_slice(&[0xff, 0xfe, 0xfd, 0xfc]);
assert_eq!(
read(&rows),
Err(CatalogReadError::MalformedRecord {
record: "faction-brannoch".into(),
field: field as u8
}),
"field {field}"
);
}
}

View file

@ -0,0 +1,313 @@
//! Attitude: how one subject regards another, as typed kernel state.
//!
//! The kernel stores *modifiers*, never an opinion. Each is a sourced, bounded,
//! possibly fading term (the Crusader Kings shape); `opinion` derives the sum on
//! demand and nothing stores it. A modifier points at one subject, or at a
//! *trait* (species, faction, a look, a rumour about a person) and a trait
//! modifier is prejudice: it applies to a subject only while the holder knows,
//! at `Believed` or better, a fact the world declared as evidence that the
//! subject carries that trait. A prejudice against outlanders does nothing to a
//! stranger the holder has never learned is one.
//!
//! The reducer is the only writer: `ResolvedOp::AdjustAttitude` and
//! `ResolvedOp::DeclareTrait` land here, through patches and affordance
//! effects. Persona prose, the narrator, and host code write nothing.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::clock::{FictionalMinutes, TickMinutes};
use super::patch::{Confidence, Ref};
use super::{CommandId, EntityId, SubjectId, WorldState};
/// The bound on one stored modifier and on a derived opinion: a grudge or a
/// fondness saturates here, so no run of insults reaches an unrecoverable
/// number and the model-facing schema can say the range.
pub(crate) const MAX_ATTITUDE: i16 = 100;
/// How many of an opinion's causes a view names. The rest are summed in.
pub(crate) const OPINION_CAUSES_SHOWN: usize = 3;
/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`: the
/// same shape as an authority kind, because it is the same kind of word.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(transparent)]
pub(crate) struct TraitName(pub(crate) String);
/// What a modifier regards.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
pub(crate) enum AttitudeToward {
Subject(SubjectId),
Trait(TraitName),
}
/// Why a modifier exists. `Grievance` and `Favor` name the command that did the
/// deed, so one act is one row and two acts are two. `Rumour` is a belief the
/// holder acted on, and holds only while the holder still knows its fact.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "cause", rename_all = "snake_case")]
pub(crate) enum AttitudeCause {
Prejudice,
Grievance { command: CommandId },
Favor { command: CommandId },
Rumour { fact: EntityId },
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(deny_unknown_fields)]
pub(crate) struct AttitudeKey {
pub(crate) toward: AttitudeToward,
pub(crate) cause: AttitudeCause,
}
/// Nonzero and within `MAX_ATTITUDE` by construction of every writer. `since`
/// is the world clock at the last write; with `decay` it sets how the term
/// fades, and with none the term is permanent.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub(crate) struct AttitudeModifier {
pub(crate) delta: i16,
pub(crate) since: FictionalMinutes,
pub(crate) decay: Option<TickMinutes>,
}
/// The proposal-time twin of [`AttitudeToward`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
pub(crate) enum AttitudeTowardRef {
Subject(Ref<SubjectId>),
Trait(TraitName),
}
/// What an authored declaration rests on. A deed is not one of these: a deed
/// is `AdjustAttitude`, whose cause the kernel derives from the command.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "basis", rename_all = "snake_case")]
pub(crate) enum AttitudeBasisRef {
Prejudice,
Rumour { fact: Ref<EntityId> },
}
/// One cause of a derived opinion, with the delta it contributes right now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct OpinionCause {
pub(crate) toward: AttitudeToward,
pub(crate) cause: AttitudeCause,
pub(crate) delta: i32,
}
/// Holder's regard for one subject: the clamped sum and its causes, strongest
/// first. Derived, never stored.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Opinion {
pub(crate) total: i32,
pub(crate) causes: Vec<OpinionCause>,
}
/// A modifier's contribution at `now`: a decaying term fades linearly to zero
/// across its period, truncating toward zero.
fn effective(modifier: &AttitudeModifier, now: FictionalMinutes) -> i32 {
let delta = i64::from(modifier.delta);
match modifier.decay {
None => delta as i32,
Some(period) => {
let span = i64::from(period.minutes());
let elapsed = i64::try_from(now.since(modifier.since)).unwrap_or(i64::MAX);
if elapsed >= span {
0
} else {
(delta * (span - elapsed) / span) as i32
}
}
}
}
/// Whether `holder` holds `fact` at `Believed` or better. A doubted rumour
/// moves nobody.
fn believes(state: &WorldState, holder: SubjectId, fact: EntityId) -> bool {
state
.knowledge
.get(&holder)
.and_then(|held| held.get(&fact))
.is_some_and(|entry| entry.confidence >= Confidence::Believed)
}
/// Whether the modifier at `key` applies to `subject` for `holder` right now.
fn applies(state: &WorldState, holder: SubjectId, key: &AttitudeKey, subject: SubjectId) -> bool {
let reaches = match &key.toward {
AttitudeToward::Subject(target) => *target == subject,
AttitudeToward::Trait(name) => state
.traits
.get(&subject)
.and_then(|carried| carried.get(name))
.is_some_and(|evidence| evidence.iter().any(|fact| believes(state, holder, *fact))),
};
reaches
&& match &key.cause {
AttitudeCause::Rumour { fact } => believes(state, holder, *fact),
_ => true,
}
}
/// `holder`'s opinion of `subject`: every applicable modifier, summed and
/// clamped. Causes with no remaining weight are dropped; ordered by strength,
/// then by key, so the answer is deterministic.
pub(crate) fn opinion(state: &WorldState, holder: SubjectId, subject: SubjectId) -> Opinion {
let mut causes: Vec<(&AttitudeKey, OpinionCause)> = state
.attitudes
.get(&holder)
.into_iter()
.flatten()
.filter(|(key, _)| applies(state, holder, key, subject))
.map(|(key, modifier)| {
(
key,
OpinionCause {
toward: key.toward.clone(),
cause: key.cause.clone(),
delta: effective(modifier, state.now),
},
)
})
.filter(|(_, cause)| cause.delta != 0)
.collect();
causes.sort_by(|(left_key, left), (right_key, right)| {
right
.delta
.abs()
.cmp(&left.delta.abs())
.then_with(|| left_key.cmp(right_key))
});
let total = causes
.iter()
.map(|(_, cause)| cause.delta)
.sum::<i32>()
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE));
Opinion {
total,
causes: causes.into_iter().map(|(_, cause)| cause).collect(),
}
}
/// Every subject `holder` has a nonzero opinion of, in subject order. The
/// candidates come from the holder's own rows, so the cost follows what the
/// holder feels, never the size of the world.
pub(crate) fn opinions_held(state: &WorldState, holder: SubjectId) -> BTreeMap<SubjectId, Opinion> {
let Some(rows) = state.attitudes.get(&holder) else {
return BTreeMap::new();
};
let mut candidates: BTreeSet<SubjectId> = BTreeSet::new();
for key in rows.keys() {
match &key.toward {
AttitudeToward::Subject(target) => {
candidates.insert(*target);
}
AttitudeToward::Trait(name) => candidates.extend(
state
.traits
.iter()
.filter(|(_, carried)| carried.contains_key(name))
.map(|(subject, _)| *subject),
),
}
}
candidates
.into_iter()
.map(|subject| (subject, opinion(state, holder, subject)))
.filter(|(_, held)| !held.causes.is_empty())
.collect()
}
/// The write: add `delta` to the modifier at `key`, saturating at
/// `MAX_ATTITUDE`, and restamp it. A modifier summed to zero is removed, so
/// absence is the only zero. Saturation at the bound is a legal write that
/// renews the term, which is what a grudge piling on a grudge is.
pub(crate) fn adjust(
state: &mut WorldState,
holder: SubjectId,
key: AttitudeKey,
delta: i16,
decay: Option<TickMinutes>,
) {
let held = state.attitudes.entry(holder).or_default();
let current = held.get(&key).map_or(0, |modifier| i32::from(modifier.delta));
let next = (current + i32::from(delta))
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE)) as i16;
if next == 0 {
held.remove(&key);
if held.is_empty() {
state.attitudes.remove(&holder);
}
} else {
held.insert(
key,
AttitudeModifier {
delta: next,
since: state.now,
decay,
},
);
}
}
/// The deed's cause: a fall in regard is a grievance and a rise is a favor,
/// both named for the command that did it.
pub(crate) fn deed_cause(delta: i16, command: CommandId) -> AttitudeCause {
if delta < 0 {
AttitudeCause::Grievance { command }
} else {
AttitudeCause::Favor { command }
}
}
/// A delta an author or a world may write: nonzero, within the bound.
pub(crate) fn is_valid_delta(delta: i16) -> bool {
delta != 0 && delta.unsigned_abs() <= MAX_ATTITUDE.unsigned_abs()
}
/// A fade the clock can carry: one minute to a year, the span bound every
/// other period in the kernel obeys. `TickMinutes` is transparent in serde, so
/// a decoded zero is possible and refused here.
pub(crate) fn is_valid_decay(decay: Option<TickMinutes>) -> bool {
decay.is_none_or(|span| TickMinutes::new(span.minutes()).is_some())
}
/// The one wording of a derived opinion's size, so the Dungeon Master's table,
/// a Persona's own view, and the narrator name the same feeling for the same
/// number. Reads after "regards them with".
pub(crate) fn regard_word(total: i32) -> &'static str {
match total {
..=-70 => "hatred",
-69..=-35 => "hostility",
-34..=-10 => "resentment",
-9..=9 => "indifference",
10..=34 => "liking",
35..=69 => "warmth",
_ => "devotion",
}
}
/// One cause as a clause a reader can act on. The statement of a rumour is the
/// fact the holder believes, resolved by the caller from its own view.
pub(crate) fn describe_cause(
cause: &OpinionCause,
fact_statement: impl Fn(EntityId) -> Option<String>,
) -> String {
let weight = format!("{:+}", cause.delta);
match (&cause.cause, &cause.toward) {
(AttitudeCause::Prejudice, AttitudeToward::Trait(name)) => {
format!("prejudice toward the {} ({weight})", name.0)
}
(AttitudeCause::Prejudice, AttitudeToward::Subject(_)) => {
format!("a feeling it cannot account for ({weight})")
}
(AttitudeCause::Grievance { .. }, _) => format!("a grievance ({weight})"),
(AttitudeCause::Favor { .. }, _) => format!("a favor owed ({weight})"),
(AttitudeCause::Rumour { fact }, _) => match fact_statement(*fact) {
Some(statement) => format!("a rumour it believes, \"{statement}\" ({weight})"),
None => format!("a rumour it believes ({weight})"),
},
}
}

View file

@ -0,0 +1,670 @@
//! Attitude is kernel state: sourced modifiers, a derived opinion, prejudice
//! gated on what the holder knows. Every test here goes through the reducer's
//! own doors (a patch or an affordance) and reads the derived opinion back.
use super::*;
use crate::attitude::{self, AttitudeCause, AttitudeToward};
use crate::attitude::{AttitudeBasisRef, AttitudeTowardRef, TraitName};
const OUTLANDER: &str = "The farmer came over the pass from the outland.";
fn play_patch(
kernel: &mut WorldKernel,
patch: WorldPatch,
) -> Result<SubmitReceipt, KernelError> {
submit_as(
kernel,
play_caller(),
CommandBody::AdmitPatch {
answers: None,
patch,
},
)
}
fn fact_with(kernel: &WorldKernel, statement: &str) -> EntityId {
*kernel
.state
.facts
.iter()
.find(|(_, record)| record.statement.as_str() == statement)
.expect("the declared fact")
.0
}
fn ruled_fact(handle: &str, statement: &str) -> Declaration {
Declaration::Fact(FactDeclaration {
handle: DraftHandle::new(handle),
label: "A ruling".into(),
statement: Statement::new(statement).unwrap(),
standing: FactStandingRef::Ruled,
})
}
fn learn(
kernel: &mut WorldKernel,
subject: SubjectId,
fact: EntityId,
confidence: Confidence,
) -> Result<SubmitReceipt, KernelError> {
play_patch(
kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::AcquireKnowledge {
subject: Ref::Existing(subject),
fact: Ref::Existing(fact),
source: AuthoredSource::Witnessed,
confidence,
}],
evidence: Vec::new(),
},
)
}
fn regard(kernel: &WorldKernel, holder: SubjectId, subject: SubjectId) -> attitude::Opinion {
attitude::opinion(&kernel.state, holder, subject)
}
/// A reeve who is prejudiced against outlanders, and a farmer who is one.
fn outlander_world(path: &Path) -> (WorldKernel, Clockwork, EntityId) {
let (mut kernel, clockwork, _) = clock_kernel(path, "Outlanders");
play_patch(
&mut kernel,
WorldPatch {
declarations: vec![ruled_fact("outland", OUTLANDER)],
operations: vec![
ComponentOp::DeclareTrait {
subject: Ref::Existing(clockwork.farmer),
name: TraitName("outlander".into()),
fact: Ref::Draft(DraftHandle::new("outland")),
},
ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
delta: -40,
basis: AttitudeBasisRef::Prejudice,
decay: None,
},
],
evidence: Vec::new(),
},
)
.expect("the play authority declares the trait and the prejudice");
let fact = fact_with(&kernel, OUTLANDER);
(kernel, clockwork, fact)
}
/// A world-authored `insult`: the target comes to regard the actor 30 lower.
fn grant_insult(kernel: &mut WorldKernel, to: SubjectId, delta: i16, decay: Option<TickMinutes>) {
play_patch(
kernel,
WorldPatch {
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
handle: DraftHandle::new("insult"),
kind: AffordanceKindName("insult".into()),
roles: vec![RoleSpec {
role: Role("target".into()),
kind: RefKind::Subject(None),
}],
preconditions: Vec::new(),
effect_slots: vec![EffectSlot {
op_kind: ComponentOpKind::AdjustAttitude { delta, decay },
roles: vec![Role("target".into())],
bounds: Bounds::None,
}],
outcome_bands: vec![OutcomeBand {
weight: 1,
effects: vec![0],
}],
carries_speech: false,
})],
operations: vec![ComponentOp::GrantAffordance {
subject: Ref::Existing(to),
affordance: Ref::Draft(DraftHandle::new("insult")),
}],
evidence: Vec::new(),
},
)
.expect("the world authors and grants the verb");
}
fn insult_id(kernel: &WorldKernel) -> AffordanceId {
*kernel
.state
.affordance_catalog
.iter()
.find(|(_, entry)| entry.kind.0 == "insult")
.expect("the insult entry")
.0
}
#[test]
fn prejudice_needs_belief() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
// The holder has not heard the farmer is an outlander: no opinion at all.
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
assert!(kernel.snapshot().unwrap().subjects.iter().all(|s| s.opinions.is_empty()));
// Somebody else knowing it does not move the reeve.
learn(&mut kernel, clockwork.treasury, fact, Confidence::Certain).unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
// A doubted telling does not either.
learn(&mut kernel, clockwork.reeve, fact, Confidence::Doubted).unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
// Believed, it does, for the farmer and for nobody who is not one.
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -40);
assert_eq!(held.causes[0].cause, AttitudeCause::Prejudice);
assert_eq!(
held.causes[0].toward,
AttitudeToward::Trait(TraitName("outlander".into()))
);
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.treasury).total, 0);
assert_eq!(
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
0,
"regard does not run backward"
);
// Forgetting it lifts the prejudice: the opinion is derived, not stored.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::Forget {
subject: Ref::Existing(clockwork.reeve),
fact: Ref::Existing(fact),
}],
evidence: Vec::new(),
},
)
.unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
}
#[test]
fn grievance_from_an_act() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Grievance");
grant_insult(&mut kernel, clockwork.farmer, -30, None);
let insult = insult_id(&kernel);
exercise(
&mut kernel,
clockwork.farmer,
insult,
vec![binding("target", Target::Subject(clockwork.reeve))],
)
.expect("the insult commits");
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -30);
assert!(matches!(
held.causes[0].cause,
AttitudeCause::Grievance { .. }
));
assert_eq!(
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
0,
"the insulter does not come to resent the insulted"
);
// A second insult is a second act with its own cause; they add.
exercise(
&mut kernel,
clockwork.farmer,
insult,
vec![binding("target", Target::Subject(clockwork.reeve))],
)
.unwrap();
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -60);
assert_eq!(held.causes.len(), 2);
assert_ne!(held.causes[0].cause, held.causes[1].cause);
// A favor is the same write with the other sign.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::AdjustAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: Ref::Existing(clockwork.farmer),
delta: 20,
decay: None,
}],
evidence: Vec::new(),
},
)
.unwrap();
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -40);
assert!(
held.causes
.iter()
.any(|cause| matches!(cause.cause, AttitudeCause::Favor { .. }) && cause.delta == 20)
);
}
#[test]
fn regard_saturates_at_the_bound_and_a_clamped_write_is_not_an_error() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturation");
let wrong = |delta| ComponentOp::AdjustAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: Ref::Existing(clockwork.farmer),
delta,
decay: None,
};
// Three deeds in one command are one row of the same cause, clamped.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![wrong(-60), wrong(-60), wrong(-60)],
evidence: Vec::new(),
},
)
.expect("a saturated write still commits");
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -100);
assert_eq!(held.causes.len(), 1);
// Separate commands pile past one row, and the opinion still clamps.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![wrong(-60)],
evidence: Vec::new(),
},
)
.unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -100);
}
#[test]
fn a_decaying_term_fades_and_a_grudge_does_not() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Decay");
let write = |delta, decay| ComponentOp::AdjustAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: Ref::Existing(clockwork.farmer),
delta,
decay,
};
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![write(-40, Some(minutes(100)))],
evidence: Vec::new(),
},
)
.unwrap();
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![write(20, None)],
evidence: Vec::new(),
},
)
.unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -20);
tick(&mut kernel, 50).unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
tick(&mut kernel, 50).unwrap();
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, 20, "the faded grievance is gone, the favor stays");
assert_eq!(held.causes.len(), 1);
}
#[test]
fn a_rumour_moves_only_a_holder_who_believes_it() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rumour");
play_patch(
&mut kernel,
WorldPatch {
declarations: vec![ruled_fact("tale", "They say the farmer poisoned a well.")],
operations: vec![ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
delta: -25,
basis: AttitudeBasisRef::Rumour {
fact: Ref::Draft(DraftHandle::new("tale")),
},
decay: None,
}],
evidence: Vec::new(),
},
)
.unwrap();
let tale = fact_with(&kernel, "They say the farmer poisoned a well.");
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
learn(&mut kernel, clockwork.reeve, tale, Confidence::Believed).unwrap();
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
assert_eq!(held.total, -25);
assert_eq!(held.causes[0].cause, AttitudeCause::Rumour { fact: tale });
}
#[test]
fn attitude_writes_with_no_meaning_are_refused_whole() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
let before = kernel.state.clone();
let adjust = |delta, holder, toward| ComponentOp::AdjustAttitude {
holder: Ref::Existing(holder),
toward: Ref::Existing(toward),
delta,
decay: None,
};
let refused: Vec<(&str, ComponentOp)> = vec![
("zero delta", adjust(0, clockwork.reeve, clockwork.farmer)),
("past the bound", adjust(101, clockwork.reeve, clockwork.farmer)),
("regarding oneself", adjust(-5, clockwork.reeve, clockwork.reeve)),
(
"a zero decay",
ComponentOp::AdjustAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: Ref::Existing(clockwork.farmer),
delta: -5,
decay: serde_json::from_value(serde_json::json!(0)).unwrap(),
},
),
(
"a rumour of a trait",
ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
delta: -5,
basis: AttitudeBasisRef::Rumour {
fact: Ref::Existing(fact),
},
decay: None,
},
),
(
"a trait that is not a name",
ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Trait(TraitName("Not A Name".into())),
delta: -5,
basis: AttitudeBasisRef::Prejudice,
decay: None,
},
),
(
"a trait declared with a bad name",
ComponentOp::DeclareTrait {
subject: Ref::Existing(clockwork.farmer),
name: TraitName("".into()),
fact: Ref::Existing(fact),
},
),
];
for (name, operation) in refused {
let error = play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![operation],
evidence: Vec::new(),
},
)
.expect_err(name);
assert!(
format!("{error:?}").contains("InvalidAttitude"),
"{name}: {error:?}"
);
}
// An affordance whose delta is nothing is refused at declaration.
let error = play_patch(
&mut kernel,
WorldPatch {
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
handle: DraftHandle::new("nothing"),
kind: AffordanceKindName("nothing".into()),
roles: vec![RoleSpec {
role: Role("target".into()),
kind: RefKind::Subject(None),
}],
preconditions: Vec::new(),
effect_slots: vec![EffectSlot {
op_kind: ComponentOpKind::AdjustAttitude {
delta: 0,
decay: None,
},
roles: vec![Role("target".into())],
bounds: Bounds::None,
}],
outcome_bands: vec![OutcomeBand {
weight: 1,
effects: vec![0],
}],
carries_speech: false,
})],
operations: Vec::new(),
evidence: Vec::new(),
},
)
.expect_err("an entry that changes no regard");
assert!(format!("{error:?}").contains("InvalidAttitude"), "{error:?}");
assert_eq!(kernel.state, before, "a refused write leaves no trace");
}
#[test]
fn the_derived_opinion_and_its_causes_reach_the_tables_view() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
grant_insult(&mut kernel, clockwork.farmer, -30, None);
let insult = insult_id(&kernel);
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
exercise(
&mut kernel,
clockwork.farmer,
insult,
vec![binding("target", Target::Subject(clockwork.reeve))],
)
.unwrap();
let snapshot = kernel.snapshot().unwrap();
let reeve = snapshot
.subjects
.iter()
.find(|subject| subject.id == clockwork.reeve)
.unwrap();
assert_eq!(reeve.opinions.len(), 1);
assert_eq!(reeve.opinions[0].toward, clockwork.farmer);
assert_eq!(reeve.opinions[0].total, -70);
assert_eq!(reeve.opinions[0].causes.len(), 2);
let view = crate::table_view(&snapshot);
let line = view
.split("Regard")
.nth(1)
.and_then(|rest| rest.split("Persona material").next())
.expect("the table has a regard section");
assert!(line.contains("The Yard Reeve"), "{line}");
assert!(line.contains("regards The Yard Farmer"), "{line}");
assert!(line.contains("with hatred (-70)"), "{line}");
assert!(line.contains("(-70)"), "{line}");
assert!(line.contains("a grievance (-30)"), "{line}");
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
}
/// An act the room saw: the same invocation as `exercise`, with the actor's own
/// words for what everyone present watched.
fn exercise_displaying(
kernel: &mut WorldKernel,
actor: SubjectId,
affordance: AffordanceId,
bindings: Vec<RoleBinding>,
display: &str,
) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
let opportunity = opportunity_for(&snapshot, actor);
let caller = CallerId::Controller(opportunity.controller_id);
kernel.submit(
command(
&snapshot,
CommandId::new(),
caller.clone(),
CommandBody::ExerciseDecision {
opportunity,
invocation: DecisionInvocation {
affordance,
bindings,
proposed: vec![ProposedEffect {
slot: 0,
magnitude: Magnitude::None,
}],
speech: None,
display: Some(Statement::new(display).unwrap()),
},
},
),
&AuthenticatedCaller::fixture(caller),
)
}
use crate::clock::FictionalMinutes;
use crate::patch::{CommitmentKind, PressureMagnitude};
const BLOW: &str = "The farmer strikes the reeve.";
/// The view's Open grievances block, alone.
fn open_grievances(kernel: &WorldKernel) -> String {
let view = crate::table_view(&kernel.snapshot().unwrap());
view.split("Open grievances")
.nth(1)
.expect("the view always carries the block")
.split("\n Persona material")
.next()
.unwrap()
.to_owned()
}
fn segment<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` missing in {text}")) + from.len();
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
&text[start..end]
}
fn strike(kernel: &mut WorldKernel, clockwork: &Clockwork, delta: i16) {
grant_insult(kernel, clockwork.farmer, delta, None);
let insult = insult_id(kernel);
exercise_displaying(
kernel,
clockwork.farmer,
insult,
vec![binding("target", Target::Subject(clockwork.reeve))],
BLOW,
)
.expect("the blow commits");
}
#[test]
fn a_deed_the_room_saw_is_an_open_grievance_until_something_answers_it() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Open grievances");
assert!(open_grievances(&kernel).trim().ends_with("none"));
strike(&mut kernel, &clockwork, -30);
let block = open_grievances(&kernel);
assert_eq!(block.matches("; acts seen by:").count(), 1, "one doer, no other: {block}");
assert!(block.contains("The Yard Farmer"), "{block}");
assert!(segment(&block, "wronged", ";").contains("The Yard Reeve"), "{block}");
let seen = segment(&block, "acts seen by:", "forums covering");
assert!(seen.contains("The Yard Reeve") && seen.contains(BLOW), "{seen}");
assert!(!seen.contains("The Yard Farmer"), "the doer is not their own witness: {seen}");
assert!(segment(&block, "forums covering them:", ";").contains("none"), "{block}");
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
assert!(segment(&block, "reckonings sworn against them:", ";").contains("none"), "{block}");
assert!(block.contains("nothing has answered it yet"), "{block}");
// Someone leans on the doer: answered, and the pressure is named with its weight.
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::AdvancePressure {
source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)),
target: Ref::Existing(clockwork.farmer),
by: PressureMagnitude(30),
}],
evidence: Vec::new(),
},
)
.unwrap();
let block = open_grievances(&kernel);
let pressed = segment(&block, "pressed by:", ";");
assert!(pressed.contains("The Yard Reeve") && pressed.contains("(30)"), "{pressed}");
assert!(block.contains("answered so far") && !block.contains("nothing has answered"), "{block}");
}
#[test]
fn a_sworn_reckoning_answers_a_grievance_and_a_favour_opens_none() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Reckoning");
strike(&mut kernel, &clockwork, -30);
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::CreateCommitment {
subject: Ref::Existing(clockwork.reeve),
counterparty: Some(Ref::Existing(clockwork.farmer)),
kind: CommitmentKind::Obligation,
due: FictionalMinutes(600),
period: None,
checks: Vec::new(),
statement: Statement::new("Make the farmer answer for the blow.").unwrap(),
}],
evidence: Vec::new(),
},
)
.unwrap();
let block = open_grievances(&kernel);
let sworn = segment(&block, "reckonings sworn against them:", "answered");
assert!(sworn.contains("The Yard Reeve") && sworn.contains("Make the farmer answer"), "{sworn}");
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
assert!(block.contains("answered so far"), "{block}");
let directory = tempfile::tempdir().unwrap();
let (mut kindly, clockwork, _) = clock_kernel(directory.path(), "Favour");
strike(&mut kindly, &clockwork, 20);
assert!(open_grievances(&kindly).trim().ends_with("none"), "a favour is no grievance");
}
#[test]
fn a_dislike_nobody_earned_is_no_open_grievance() {
let directory = tempfile::tempdir().unwrap();
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Prejudice");
play_patch(
&mut kernel,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::DeclareAttitude {
holder: Ref::Existing(clockwork.reeve),
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
delta: -40,
basis: AttitudeBasisRef::Prejudice,
decay: None,
}],
evidence: Vec::new(),
},
)
.unwrap();
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -40);
assert!(
open_grievances(&kernel).trim().ends_with("none"),
"a feeling no deed explains wrongs no one"
);
}

View file

@ -469,7 +469,7 @@ mod tests {
AuthorityTargetRef, CallerId, CausalBoundary, CommandBody, CommandEnvelope, CommitmentKind,
ComponentOp, CoverBudget, DecisionOpportunity, DecisionScope, Declaration, DraftHandle,
EntityDeclaration, EntityId, EntityKind, EvidenceRef, FactDeclaration, FactStandingRef,
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref,
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref, TickIndex,
RouteDeclaration, Statement, SubjectDeclaration, SubjectId, SubjectKind, SystemCapability,
WorldEffect, WorldId, WorldKernel, WorldMailbox, WorldScaleIntentRef, agency_graph,
commit_digest, derive_boundaries, derive_cover, derive_opportunities,
@ -518,6 +518,7 @@ mod tests {
},
controller,
position: Some(Ref::Existing(commons)),
import_key: None,
})
};
WorldPatch {
@ -735,8 +736,7 @@ mod tests {
assert!(!graph.subjects.contains(&mirror.first));
let cover = derive_cover(
snapshot.world_id,
snapshot.now,
30,
TickIndex(0),
&opportunities,
&graph,
CoverBudget {
@ -1195,6 +1195,7 @@ mod tests {
controller: NewController::External { consumer },
affordances: BTreeSet::new(),
position: Some(Ref::Existing(commons)),
import_key: None,
})])
};
// A binding to another consumer is outside its ground.
@ -1573,6 +1574,7 @@ mod tests {
controller,
affordances,
position: Some(Ref::Existing(mirror.commons)),
import_key: None,
})])
};
let pairing = |result: Result<SubmitReceipt, KernelError>| {

File diff suppressed because it is too large Load diff

View file

@ -11,7 +11,6 @@
//! The cover is a partition, never a filter: every active subject is in exactly
//! one cell every tick. The budget decides at what resolution, not whether.
use super::clock::FictionalMinutes;
use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@ -29,25 +28,18 @@ pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16;
/// the name, not by a second namespace.
const COVER_NAMESPACE: &str = "ghostlight.cover.v1";
/// Monotone tick index. Derived from the world clock, never stored. It is
/// threaded into every derived command id, so a resumed tick over the same
/// snapshot re-derives the same ids and the kernel's idempotency ledger answers
/// with the original receipts instead of double-committing.
/// A tick's ordinal: the number of clock advances the world had committed when
/// the tick opened. The driver reads it from the world and freezes it in the
/// tick document; it is never derived from `now`, so it does not depend on the
/// span. It is threaded into every derived command id, so a resumed tick
/// re-submits the same ids and the kernel's idempotency ledger answers with the
/// original receipts instead of double-committing.
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
#[serde(transparent)]
pub struct TickIndex(pub u64);
impl TickIndex {
/// Floor division by the span one `AdvanceTime` carries. The driver submits
/// the clock *after* the cells run, so every cell in one tick sees the same
/// `now` and therefore the same index.
pub(crate) fn of(now: FictionalMinutes, tick_minutes: u32) -> Self {
Self(now.0 / u64::from(tick_minutes.max(1)))
}
}
/// How a subject was represented this tick. Derived from the cell, carried
/// nowhere in world state: representation is a compute budget, not world truth.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -70,9 +62,12 @@ impl std::fmt::Display for CellId {
}
}
fn derive_uuid(name: &str) -> Uuid {
/// sha256 over a fixed namespace and a name, first sixteen bytes: the one id
/// recipe the scheduler's derived ids share (cells here, hierarchy nodes in
/// `hierarchy.rs`), so the two cannot drift apart.
pub(crate) fn derive_uuid(namespace: &str, name: &str) -> Uuid {
let mut hasher = Sha256::new();
hasher.update(COVER_NAMESPACE.as_bytes());
hasher.update(namespace.as_bytes());
hasher.update([0u8]);
hasher.update(name.as_bytes());
let bytes: [u8; 16] = hasher.finalize()[..16]
@ -89,7 +84,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
.first()
.copied()
.expect("a cell always has at least one member");
CellId(derive_uuid(&format!(
CellId(derive_uuid(COVER_NAMESPACE, &format!(
"cell|{world:?}|{}|{}|{lowest:?}",
tick.0,
members.len()
@ -98,7 +93,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
/// The stable, derived identity a cell's controller-work row is keyed by.
pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid {
derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0))
derive_uuid(COVER_NAMESPACE, &format!("cell-work|{world:?}|{cell}|{}", tick.0))
}
/// One constituent's submission id. Deterministic, so a resumed cell re-submits
@ -109,7 +104,7 @@ pub(crate) fn cell_constituent_uuid(
subject: SubjectId,
tick: TickIndex,
) -> Uuid {
derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
derive_uuid(COVER_NAMESPACE, &format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -241,6 +236,27 @@ impl AgencyGraph {
}
}
/// The adjacency among `members` alone: one node's voices partition over
/// the edges that run between them. A star's centre outside `members`
/// leaves its rays unlinked, which is honest: they were adjacent through
/// somebody who is not at this table.
pub(crate) fn restricted(&self, members: &BTreeSet<SubjectId>) -> Self {
Self {
subjects: self
.subjects
.iter()
.copied()
.filter(|subject| members.contains(subject))
.collect(),
edges: self
.edges
.iter()
.copied()
.filter(|(one, other)| members.contains(one) && members.contains(other))
.collect(),
}
}
pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) {
if one == other {
return;
@ -254,7 +270,7 @@ impl AgencyGraph {
}
}
/// The partition. Pure over `(world, now, opportunities, graph, budget)`.
/// The partition. Pure over `(world, tick, opportunities, graph, budget)`.
///
/// `opportunities` arrives in the kernel's one attention order (pressure, then
/// attention debt, then id) and is never re-sorted and never filtered here: a
@ -262,13 +278,11 @@ impl AgencyGraph {
/// is a fact about cognition rather than a scheduling preference.
pub fn derive_cover(
world: WorldId,
now: FictionalMinutes,
tick_minutes: u32,
tick: TickIndex,
opportunities: &[DecisionOpportunity],
graph: &AgencyGraph,
budget: CoverBudget,
) -> Cover {
let tick = TickIndex::of(now, tick_minutes);
let active: Vec<&DecisionOpportunity> = opportunities
.iter()
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
@ -601,14 +615,28 @@ mod tests {
) -> Cover {
derive_cover(
WorldId::nil_for_test(),
FictionalMinutes(tick * 60),
60,
TickIndex(tick),
opportunities,
graph,
budget,
)
}
#[test]
fn restriction_keeps_only_the_edges_between_the_members() {
let mut graph = AgencyGraph {
subjects: vec![subject(1), subject(2), subject(3), subject(4)],
edges: BTreeSet::new(),
};
graph.link(subject(1), subject(2));
graph.link(subject(2), subject(3));
graph.link(subject(3), subject(4));
let members = BTreeSet::from([subject(1), subject(2), subject(4)]);
let kept = graph.restricted(&members);
assert_eq!(kept.subjects, vec![subject(1), subject(2), subject(4)]);
assert_eq!(kept.edges, BTreeSet::from([(subject(1), subject(2))]));
}
/// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap
/// of 24, 36 urgency slots. Every subject exactly once, the budget held, and
/// the head of the attention order attended in detail.

View file

@ -32,8 +32,9 @@ use super::{
JurisdictionKey, KernelError, MailboxError, Mismatch, PatchAnswer, ScaleDeficitRow, SeedPort,
SubjectId, SubjectKind, WorldId, WorldPatch, WorldPhase, WorldSnapshot,
};
use super::wave::Focus;
use async_trait::async_trait;
use codex_connector::CodexInputItem;
use model_connector::InputItem;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
@ -49,7 +50,15 @@ use uuid::Uuid;
/// The elaborator wants many tool calls inside one round and several rounds for
/// repair, where the operational agent wants one terminal choice.
/// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to.
///
/// A round budget is per attempt: the rounds since the last refusal, or since
/// the start. A refusal opens a fresh attempt with the whole budget, so a repair
/// is never starved by the rounds the refused draft spent.
pub(super) const ELABORATION_ROUND_BUDGET: usize = 6;
/// How many times the kernel may refuse one session's patch and the session
/// still be repaired. The refusal after these is terminal: the session ends
/// without a patch and says why, instead of being re-chosen forever.
pub(super) const MAX_REFUSALS: usize = 2;
/// A seed session authors a whole shortfall, not one answer: several subjects,
/// each with a grant, a goal, and an obligation, then a submit. Measured on
/// the road at one declaration per response, six rounds discarded everything.
@ -212,17 +221,45 @@ impl ElaborationCheckpoint {
refusals,
completed,
..
} => derive_elaboration_capture(
agent_prompt,
refusals,
completed,
ELABORATION_ROUND_BUDGET,
)
.is_ok_and(|capture| !capture.submitted),
} => {
derive_elaboration_capture(
agent_prompt,
refusals,
completed,
ELABORATION_ROUND_BUDGET,
)
.is_ok_and(|capture| !capture.submitted)
|| ended_by_refusal(
agent_prompt,
refusals,
completed,
ELABORATION_ROUND_BUDGET,
)
}
}
}
}
/// Whether the conversation ends in the refusal past `MAX_REFUSALS`: the last
/// refusal follows the last round, and the repair it would have opened was
/// never authored. A `NoPatch` row is either this or a conversation that
/// ended without a submit.
fn ended_by_refusal(
agent_prompt: &str,
refusals: &[Refusal],
completed: &[InferenceOutput],
budget: usize,
) -> bool {
refusals.len() > MAX_REFUSALS
&& refusals
.last()
.is_some_and(|refusal| refusal.after_round == completed.len())
&& matches!(
evaluate_elaboration_loop(agent_prompt, refusals, completed, budget),
Ok(ElaborationLoopEvaluation::Continue { .. })
)
}
/// A session may gather more evidence and may end, but it may never rewrite the
/// answer it bound to, the ancestry it was built against, the lens it drew, or
/// the text it was built with. This compares a row to the row that follows it,
@ -272,6 +309,20 @@ pub(super) fn valid_elaboration_progression(
..
},
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
// The refusal that ends the session: the same reopening, stored as the
// end instead of another repair.
(
ElaborationCheckpoint::ReadyToSubmit {
completed: existing,
refusals: existing_refusals,
..
},
ElaborationCheckpoint::NoPatch {
completed: next,
refusals: next_refusals,
..
},
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
_ => false,
}
}
@ -301,7 +352,7 @@ pub struct EvidenceError {
/// The referents the answer names, as world labels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EvidenceQuery {
pub(crate) referents: Vec<String>,
pub referents: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -328,7 +379,7 @@ pub trait EvidenceSource: Send + Sync {
/// structure and operate on it, but cannot mint quantity, because `admit`
/// requires a listed reference and there are none. Creation of quantity without
/// provenance should be impossible, not merely discouraged.
pub(crate) struct NullEvidenceSource;
pub struct NullEvidenceSource;
#[async_trait]
impl EvidenceSource for NullEvidenceSource {
@ -349,10 +400,40 @@ pub(super) struct ElaborationCapture {
}
pub(super) enum ElaborationLoopEvaluation {
Continue { conversation: Vec<CodexInputItem> },
Continue { conversation: Vec<InputItem> },
Complete { capture: ElaborationCapture },
}
/// What one sweep did: how much demand it saw, how many sessions it started,
/// what each ended as, and every session that failed outright. The caller logs
/// or surfaces it; the library has no sink of its own for the run.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SweepReport {
pub claimed: usize,
pub started: usize,
pub committed: usize,
pub rejected: usize,
pub superseded: usize,
pub no_patch: usize,
/// Sessions the world refused past `MAX_REFUSALS`; each was logged at error
/// with its last refusal and is no longer claimed.
pub abandoned: usize,
/// Sessions that ended in an error, with the error.
pub failed: Vec<String>,
}
impl SweepReport {
fn count(&mut self, outcome: ElaborationOutcome) {
match outcome {
ElaborationOutcome::Committed => self.committed += 1,
ElaborationOutcome::Rejected => self.rejected += 1,
ElaborationOutcome::Superseded => self.superseded += 1,
ElaborationOutcome::NoPatch => self.no_patch += 1,
ElaborationOutcome::Abandoned => self.abandoned += 1,
}
}
}
/// What one session's step did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ElaborationOutcome {
@ -363,6 +444,10 @@ pub(super) enum ElaborationOutcome {
Superseded,
/// The round budget was spent without a submit. The boundary stays derived.
NoPatch,
/// The world refused the session's patch past `MAX_REFUSALS`. The session
/// is stored as `NoPatch`, with the last refusal in its gap, and no sweep
/// claims it again.
Abandoned,
}
/// The authoring lane's runner. Holds no state between sweeps; every field is a
@ -546,25 +631,64 @@ impl ElaborationRunner {
draft,
)
.await;
return match submitted {
Ok(_) => Ok(ElaborationOutcome::Committed),
let mismatches = match submitted {
Ok(_) => return Ok(ElaborationOutcome::Committed),
Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => {
// A rejected command mutates nothing, so reusing the
// id is correct and the idempotency probe never sees
// a conflicting commit.
refusals.push(Refusal {
after_round: completed.len(),
mismatches,
});
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
.await?;
Ok(ElaborationOutcome::Rejected)
mismatches
}
// The patch resolved and the answer still stands: the
// kernel names no site, so the repair is told what the
// answer needs.
Err(MailboxError::Kernel(KernelError::AnswerNotSatisfied)) => {
vec![unsatisfied_answer(snapshot, &session.answer)]
}
Err(MailboxError::Kernel(KernelError::AnswerNotDerived)) => {
Ok(ElaborationOutcome::Superseded)
return Ok(ElaborationOutcome::Superseded);
}
Err(error) => Err(snapshot_error(error)),
Err(error) => return Err(snapshot_error(error)),
};
tracing::info!(
command_id = ?command_id,
refusal = refusals.len() + 1,
sites = %render_refusal_sites(&mismatches),
"elaboration patch refused"
);
// A rejected command mutates nothing, so reusing the
// id is correct and the idempotency probe never sees
// a conflicting commit.
refusals.push(Refusal {
after_round: completed.len(),
mismatches,
});
if refusals.len() > MAX_REFUSALS {
let last = refusals.last().map_or_else(String::new, |refusal| {
render_refusal_sites(&refusal.mismatches)
});
tracing::error!(
command_id = ?command_id,
refusals = refusals.len(),
last_refusal = %last,
"elaboration session abandoned: the world kept refusing its patch"
);
self.persist(ElaborationCheckpoint::NoPatch {
command_id,
session,
agent_prompt,
refusals,
completed,
gaps: vec![ControllerNeed {
detail: format!(
"The world refused the patch {} times; last refusal: {last}",
MAX_REFUSALS + 1
),
}],
})
.await?;
return Ok(ElaborationOutcome::Abandoned);
}
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
.await?;
return Ok(ElaborationOutcome::Rejected);
}
}
}
@ -634,8 +758,13 @@ impl ElaborationRunner {
/// One sweep: one snapshot, one read of the store's in-flight sessions, one
/// claim set, and one session per entry. One permit per session for its
/// whole step, from the ceiling the caller owns. The library holds no
/// concurrency number of its own.
/// whole step, from the ceiling the caller owns, and at most `max_sessions`
/// sessions start, in claim order: the rest of the demand waits for the
/// next sweep. The library holds no concurrency or spend number of its own.
///
/// `focus` orders the claim set: demand at a focus place is claimed first,
/// so a bounded sweep spends on what the player is looking at before the
/// rest. The focus's nodes name no place and are not read here.
///
/// The claim set is the only set of sessions alive only while one sweep
/// runs at a time. The caller's loop awaits each sweep; nothing here guards
@ -646,19 +775,32 @@ impl ElaborationRunner {
/// returned such an error. A session that panics is that same error: its
/// siblings finish, nothing starts after it, and it is returned. Any other
/// error ends only its own session.
pub async fn sweep(&self, permits: Arc<Semaphore>) -> Result<(), ControllerError> {
pub async fn sweep(
&self,
permits: Arc<Semaphore>,
max_sessions: usize,
focus: &Focus,
) -> Result<SweepReport, ControllerError> {
let mut report = SweepReport::default();
let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?;
if snapshot.phase != WorldPhase::Active {
return Ok(());
return Ok(report);
}
let in_flight = self.work.elaboration_in_flight().await?;
let entries = demand_entries(&snapshot, &sweep_jurisdictions(&snapshot), &in_flight)?;
let entries = demand_entries(
&snapshot,
&sweep_jurisdictions(&snapshot),
&in_flight,
focus,
)?;
let entries = self.fair_claims(entries, &in_flight, &snapshot, focus).await?;
report.claimed = entries.len();
let snapshot = Arc::new(snapshot);
// Raised by a session before it releases its permit, so the sweep sees
// it before it starts the session that permit admits.
let stopped = Arc::new(AtomicBool::new(false));
let mut running = JoinSet::new();
for (command_id, session) in entries {
for (command_id, session) in entries.into_iter().take(max_sessions) {
if stopped.load(Ordering::SeqCst) {
break;
}
@ -668,6 +810,7 @@ impl ElaborationRunner {
if stopped.load(Ordering::SeqCst) {
break;
}
report.started += 1;
let runner = self.clone();
let snapshot = snapshot.clone();
let stopped = stopped.clone();
@ -682,18 +825,20 @@ impl ElaborationRunner {
.as_ref()
.is_err_and(ControllerError::requires_quarantine);
drop(held);
outcome
(command_id, outcome)
});
}
let mut quarantine = None;
while let Some(joined) = running.join_next().await {
match joined {
Ok(Ok(_)) => {}
Ok(Err(error)) if error.requires_quarantine() => {
Ok((_, Ok(outcome))) => report.count(outcome),
Ok((command_id, Err(error))) if error.requires_quarantine() => {
report.failed.push(format!("{command_id:?}: {error}"));
quarantine.get_or_insert(error);
}
Ok(Err(error)) => {
tracing::debug!(%error, "elaboration step did not admit a patch");
Ok((command_id, Err(error))) => {
tracing::error!(command_id = ?command_id, %error, "elaboration session failed");
report.failed.push(format!("{command_id:?}: {error}"));
}
Err(error) => {
quarantine.get_or_insert(ControllerError::Serialization(format!(
@ -702,7 +847,64 @@ impl ElaborationRunner {
}
}
}
quarantine.map_or(Ok(()), Err)
tracing::info!(
claimed = report.claimed,
started = report.started,
committed = report.committed,
rejected = report.rejected,
superseded = report.superseded,
no_patch = report.no_patch,
abandoned = report.abandoned,
failed = report.failed.len(),
"elaboration sweep"
);
quarantine.map_or(Ok(report), Err)
}
/// The claim set in the order a bounded sweep should spend on it. Focus is
/// the outer key: demand at a focus place goes before the rest, so a tried
/// entry the player is looking at is not parked behind untried demand
/// elsewhere. Inside each band an entry no session has touched goes before
/// one a session already tried, so an entry the kernel refused is not
/// retried ahead of untried demand; the tried ones follow least recently
/// stored first, so they rotate. An entry whose stored session ended
/// without a patch is a fixed point that runs no inference, and it takes no
/// slot.
async fn fair_claims(
&self,
entries: Vec<(CommandId, ElaboratorSession)>,
in_flight: &[(CommandId, ElaboratorSession)],
snapshot: &WorldSnapshot,
focus: &Focus,
) -> Result<Vec<(CommandId, ElaboratorSession)>, ControllerError> {
// Band 0 is the focus; each band holds its untried and its tried.
type Tried = Vec<((CommandId, ElaboratorSession), usize)>;
let mut bands: [(Vec<(CommandId, ElaboratorSession)>, Tried); 2] = Default::default();
for entry in entries {
let band = usize::from(!entry_in_focus(snapshot, focus, &entry.1));
let (untried, tried) = &mut bands[band];
if let Some(position) = in_flight.iter().position(|(id, _)| *id == entry.0) {
tried.push((entry, position));
continue;
}
match self.work.lookup(entry.0).await? {
ControllerWorkLookup::Missing => untried.push(entry),
ControllerWorkLookup::Confirmed(ControllerWork::Elaboration(
ElaborationCheckpoint::NoPatch { .. },
))
| ControllerWorkLookup::CustodyUncertain(ControllerWork::Elaboration(
ElaborationCheckpoint::NoPatch { .. },
)) => {}
_ => tried.push((entry, usize::MAX)),
}
}
let mut ordered = Vec::new();
for (mut untried, mut tried) in bands {
tried.sort_by_key(|(_, position)| *position);
untried.extend(tried.into_iter().map(|(entry, _)| entry));
ordered.append(&mut untried);
}
Ok(ordered)
}
/// The first entry of one jurisdiction's claim set, stepped: what a sweep
@ -717,7 +919,7 @@ impl ElaborationRunner {
return Ok(None);
}
let in_flight = self.work.elaboration_in_flight().await?;
let Some((command_id, session)) = demand_entries(&snapshot, &[jurisdiction], &in_flight)?
let Some((command_id, session)) = demand_entries(&snapshot, &[jurisdiction], &in_flight, &Focus::default())?
.into_iter()
.next()
else {
@ -776,6 +978,10 @@ fn sweep_jurisdictions(snapshot: &WorldSnapshot) -> Vec<JurisdictionKey> {
/// and its command id are adopted and nothing is drawn. Only an unmatched
/// entry derives an id and draws a lens.
///
/// The jurisdiction order, then a stable partition: an entry whose place is in
/// focus (see `in_focus`) first, the rest after, each class in the order above.
/// An empty focus leaves the order untouched.
///
/// A boundary under nested roots is covered by each of them, so an answer
/// already claimed is not claimed again, and no command id is claimed twice.
/// The stop condition is "no open boundary and no deficit", plus the one other
@ -785,6 +991,7 @@ fn demand_entries(
snapshot: &WorldSnapshot,
jurisdictions: &[JurisdictionKey],
in_flight: &[(CommandId, ElaboratorSession)],
focus: &Focus,
) -> Result<Vec<(CommandId, ElaboratorSession)>, ControllerError> {
let ancestry = snapshot.last_commit_digest.clone().unwrap_or_default();
let mut claimed_ids = BTreeSet::new();
@ -803,7 +1010,56 @@ fn demand_entries(
}
}
}
Ok(entries)
let (focused, rest): (Vec<_>, Vec<_>) =
entries.into_iter().partition(|(_, session)| entry_in_focus(snapshot, focus, session));
Ok(focused.into_iter().chain(rest).collect())
}
/// What a sweep over `snapshot` would claim, in claim order, before fair
/// claims reorders by what sessions already tried. Tests read the order here.
#[cfg(test)]
pub(super) fn claim_order(snapshot: &WorldSnapshot, focus: &Focus) -> Vec<PatchAnswer> {
demand_entries(snapshot, &sweep_jurisdictions(snapshot), &[], focus)
.expect("the claim set derives")
.into_iter()
.map(|(_, session)| session.answer)
.collect()
}
/// The place an answer's demand sits at: a boundary's own place (a
/// destination's, or the position of the subject it names), a deficit's
/// jurisdiction root. Demand with no place, the uncovered residual, sits
/// nowhere and is never in focus.
fn answer_place(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Option<EntityId> {
let subject_place = |subject: SubjectId| snapshot.place_of(subject);
match answer {
PatchAnswer::Deficit(JurisdictionKey::PlaceSubtree(root)) => Some(*root),
PatchAnswer::Deficit(JurisdictionKey::Uncovered) => None,
PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => Some(*place),
PatchAnswer::Boundary(
CausalBoundary::MissingStructure { subject, .. }
| CausalBoundary::PolityInCausalRange { subject, .. }
| CausalBoundary::IndividuationRequired { population: subject, .. },
) => subject_place(*subject),
}
}
/// Whether the demand an entry answers sits at a focus place.
fn entry_in_focus(snapshot: &WorldSnapshot, focus: &Focus, session: &ElaboratorSession) -> bool {
answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place))
}
/// A place is in focus when it is a focus place, inside one, or one open route
/// from one, the route read either way: the player's exits and the way back.
pub(super) fn in_focus(snapshot: &WorldSnapshot, focus: &Focus, place: EntityId) -> bool {
focus.places.iter().any(|&root| {
snapshot_covers_place(snapshot, root, place)
|| snapshot.routes.iter().any(|route| {
route.open
&& ((route.from == root && route.to == place)
|| (route.to == root && route.from == place))
})
})
}
/// The in-flight row that answers this entry, if any. The listing is least
@ -901,13 +1157,7 @@ fn boundary_in(
jurisdiction: JurisdictionKey,
boundary: &CausalBoundary,
) -> bool {
let subject_place = |subject: SubjectId| {
snapshot
.subjects
.iter()
.find(|row| row.id == subject)
.and_then(|row| row.position)
};
let subject_place = |subject: SubjectId| snapshot.place_of(subject);
match jurisdiction {
JurisdictionKey::Uncovered => match boundary {
CausalBoundary::UnelaboratedDestination { .. } => false,
@ -933,7 +1183,7 @@ fn boundary_in(
}
}
fn snapshot_covers_place(snapshot: &WorldSnapshot, root: EntityId, place: EntityId) -> bool {
pub(crate) fn snapshot_covers_place(snapshot: &WorldSnapshot, root: EntityId, place: EntityId) -> bool {
let containers: BTreeMap<EntityId, Option<EntityId>> = snapshot
.places
.iter()
@ -1019,7 +1269,12 @@ fn build_prompt(
"Answer: {}\n",
render_answer(snapshot, &session.answer)
));
prompt.push_str(&render_promise(snapshot, &session.answer));
prompt.push_str(&render_clock(snapshot));
prompt.push_str(
"\nEverything below already stands. Reference it by its bracketed id and declare only what is missing. An affordance kind that already stands, the kernel's own speak among them, cannot be declared again: grant it by id.\n\n",
);
prompt.push_str(&super::table::render_world_structure(snapshot));
prompt.push('\n');
prompt_body(&mut prompt, receipts);
prompt
@ -1057,19 +1312,28 @@ fn render_refusal(mismatches: &[Mismatch]) -> String {
"The world refused the patch you submitted; every site below failed a structural check. \
The draft is discarded. Author the complete patch again with tool calls, repairing every site, then submit again:\n",
);
for mismatch in mismatches {
text.push_str(&format!("- {}\n", render_mismatch(mismatch)));
}
text.push_str(&render_refusal_sites(mismatches));
text
}
/// The world's own premise, when it has one. The seed session's optional
/// sentence rides beside it; the two are not the same thing.
/// The refusal's sites, one per line, as the model reads them and as the logs
/// record them.
fn render_refusal_sites(mismatches: &[Mismatch]) -> String {
mismatches
.iter()
.map(|mismatch| format!("- {}\n", render_mismatch(mismatch)))
.collect()
}
/// The world's own guidance, when it has any: its era and its premise. The
/// seed session's optional sentence rides beside it; the two are not the same
/// thing.
fn render_brief(snapshot: &WorldSnapshot) -> String {
if snapshot.brief.is_empty() {
let guidance = snapshot.guidance();
if guidance.is_empty() {
String::new()
} else {
format!("Brief: {}\n", snapshot.brief)
format!("World guidance:\n{guidance}\n")
}
}
@ -1097,6 +1361,62 @@ pub(super) fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: Jurisd
}
}
/// What answers a promise whose counterparty can neither command nor litigate it.
const MISSING_STRUCTURE_NEEDS: &str = "the promise's counterparty must be able to command the promisor (grant_authority to the counterparty, over the promisor or a ground that covers it) or a forum must stand over the counterparty (open_forum with standing over the counterparty); declaring more subjects or facts does not answer it";
/// The promise a missing-structure boundary is about, with who holds it and who
/// it is owed to, by id, and what answers it. Empty for every other answer.
fn render_promise(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String {
let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, key, .. }) = answer
else {
return String::new();
};
let named = |id: SubjectId| {
snapshot.subjects.iter().find(|entry| entry.id == id).map_or_else(
|| format!("[{}]", super::table::id_text(id)),
|entry| format!("{} [{}]", entry.label, super::table::id_text(entry.id)),
)
};
let Some(commitment) = snapshot
.subjects
.iter()
.find(|entry| entry.id == *subject)
.and_then(|entry| entry.commitments.iter().find(|held| held.key == *key))
else {
return String::new();
};
let owed = commitment
.counterparty
.map_or_else(|| "no one".to_owned(), named);
format!(
"Promise: {} promised \"{}\" to {}. It is answered when {MISSING_STRUCTURE_NEEDS}.
",
named(*subject),
commitment.statement.as_str(),
owed
)
}
/// What the world still lacks when a clean patch did not answer. The wording
/// follows each boundary's own predicate: the repair is a patch that makes the
/// predicate stop holding.
fn unsatisfied_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Mismatch {
let needs = match answer {
PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => MISSING_STRUCTURE_NEEDS,
PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { .. }) => {
"the place must stop being a dead end: put something in it, or give it a second route"
}
PatchAnswer::Boundary(_) => "the boundary's own structure must change",
PatchAnswer::Deficit(_) => {
"more subjects must qualify in this jurisdiction: each needs a controller, an affordance grant, a position inside it and a held goal"
}
};
Mismatch::AnswerNotSatisfied {
answered: render_answer(snapshot, answer),
needs: needs.to_owned(),
}
}
fn render_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String {
let referents = answer_referents(snapshot, answer).join(", ");
match answer {
@ -1135,11 +1455,13 @@ pub(super) fn evaluate_elaboration_loop(
budget: usize,
) -> Result<ElaborationLoopEvaluation, ControllerError> {
check_refusals(refusals, completed.len())?;
let mut conversation = vec![CodexInputItem::UserText {
let mut conversation = vec![InputItem::UserText {
text: prompt.to_owned(),
}];
let mut fold = DraftFold::default();
let mut receipts = Vec::new();
// The first round of the current attempt; a refusal moves it.
let mut attempt_start = 0;
for (round, output) in completed.iter().enumerate() {
if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest
@ -1155,7 +1477,7 @@ pub(super) fn evaluate_elaboration_loop(
match event {
InferenceEvent::Text(text) => {
if !text.is_empty() {
conversation.push(CodexInputItem::AssistantText { text: text.clone() });
conversation.push(InputItem::AssistantText { text: text.clone() });
}
}
InferenceEvent::ToolCall {
@ -1164,13 +1486,13 @@ pub(super) fn evaluate_elaboration_loop(
arguments,
} => {
called_tool = true;
conversation.push(CodexInputItem::ToolCall {
conversation.push(InputItem::ToolCall {
call_id: call_id.clone(),
name: name.clone(),
arguments: arguments.clone(),
});
let result = fold.apply(name, arguments);
conversation.push(CodexInputItem::ToolResult {
conversation.push(InputItem::ToolResult {
call_id: call_id.clone(),
output: result,
});
@ -1187,21 +1509,23 @@ pub(super) fn evaluate_elaboration_loop(
"a refusal follows a round that submitted nothing".into(),
));
}
conversation.push(CodexInputItem::UserText {
conversation.push(InputItem::UserText {
text: render_refusal(&refusal.mismatches),
});
fold = DraftFold::default();
attempt_start = round + 1;
continue;
}
let is_complete = fold.submitted || !called_tool || round + 1 == budget;
let is_complete =
fold.submitted || !called_tool || round + 1 - attempt_start == budget;
if is_complete {
if round + 1 != completed.len() {
return Err(ControllerError::Serialization(
"elaboration evidence continued after total finalization".into(),
));
}
if !fold.submitted && called_tool && round + 1 == budget {
if !fold.submitted && called_tool && round + 1 - attempt_start == budget {
// What was authored is still a patch; the resolver decides it,
// not the round counter. An empty draft has nothing to submit.
if fold.draft.declarations.is_empty() && fold.draft.operations.is_empty() {
@ -1228,7 +1552,7 @@ pub(super) fn evaluate_elaboration_loop(
}
}
if completed.len() >= budget {
if completed.len() - attempt_start >= budget {
return Err(ControllerError::Serialization(
"elaboration evidence exceeded its round budget".into(),
));
@ -1296,6 +1620,7 @@ pub(super) struct ElaborationOracle {
impl ElaborationOracle {
pub(super) fn new(completed: &[InferenceOutput], refusals: &[Refusal], budget: usize) -> Self {
let mut fold = DraftFold::default();
let mut attempt_start = 0;
for (round, output) in completed.iter().enumerate() {
for event in &output.events {
if let InferenceEvent::ToolCall {
@ -1307,11 +1632,12 @@ impl ElaborationOracle {
}
if refusal_after(refusals, round + 1).is_some() {
fold = DraftFold::default();
attempt_start = round + 1;
}
}
Self {
fold,
remaining: budget.saturating_sub(completed.len()) as u32,
remaining: budget.saturating_sub(completed.len() - attempt_start) as u32,
}
}
}
@ -1439,7 +1765,7 @@ pub(super) fn elaboration_request(
round: usize,
model: &str,
instructions: &str,
input: Vec<CodexInputItem>,
input: Vec<InputItem>,
) -> Result<InferenceRequest, ControllerError> {
tool_request(
command_id,
@ -1508,7 +1834,7 @@ const SEED_NAMESPACE: &str = "ghostlight.command.seed.v1";
/// seeded out of goals alone therefore activates with nothing for the Active
/// elaborator to answer, so this instruction requires an obligation, not a
/// goal alone, from every subject it authors.
const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. A goal alone is not enough structure: every person and institution you author must also hold at least one obligation commitment with a counterparty, because a goal carries no counterparty and derives no boundary for the world's Active elaborator to answer. Author the shortfall you were given in as few responses as you can, making several tool calls per response, and finish with submit_patch as your last call; a session that ends without it keeps only what was authored. Recording a gap changes nothing. Every promise carries a statement of what is promised; both parties will read it. Give every person material with set_persona_material: how they speak, what they hold to, what they remember, and how they read each subject they are bound to. A person with no material has no rendered inner life and will say nothing.";
const SEED_INSTRUCTIONS: &str = "Use only the supplied tools to author living structure inside your jurisdiction. A subject counts only when it has a controller, at least one affordance grant, and holds a goal commitment. A goal alone is not enough structure: every person and institution you author must also hold at least one obligation commitment with a counterparty, because a goal carries no counterparty and derives no boundary for the world's Active elaborator to answer. Author the shortfall you were given in as few responses as you can, making several tool calls per response, and finish with submit_patch as your last call; a session that ends without it keeps only what was authored. Recording a gap changes nothing. Every promise carries a statement of what is promised; both parties will read it. Give every person material with set_persona_material: how they speak, what they hold to, what they remember, and how they read each subject they are bound to. A person with no material has no rendered inner life and will say nothing. People hold regards of their own: where a person or an institution distrusts a kind of person (a species, a faction, a look, a rumoured sin), declare the trait on those who carry it with declare_trait, evidenced by a fact, and the prejudice with declare_attitude; it reaches only those who come to know the trait.";
/// The row a session answers, plus the ancestry it was built against. There is
/// no `PatchAnswer` here: a seed answers nothing, and giving this session an
@ -1646,8 +1972,11 @@ impl SeedCheckpoint {
refusals,
completed,
..
} => derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
.is_ok_and(|capture| !capture.submitted),
} => {
derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
.is_ok_and(|capture| !capture.submitted)
|| ended_by_refusal(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
}
}
}
}
@ -1695,6 +2024,18 @@ pub(super) fn valid_seed_progression(existing: &SeedCheckpoint, next: &SeedCheck
..
},
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
(
SeedCheckpoint::ReadyToSubmit {
completed: existing,
refusals: existing_refusals,
..
},
SeedCheckpoint::NoPatch {
completed: next,
refusals: next_refusals,
..
},
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
_ => false,
}
}
@ -1931,6 +2272,32 @@ impl SeedRunner {
after_round: completed.len(),
mismatches,
});
if refusals.len() > MAX_REFUSALS {
let last = refusals.last().map_or_else(String::new, |refusal| {
render_refusal_sites(&refusal.mismatches)
});
tracing::error!(
command_id = ?command_id,
refusals = refusals.len(),
last_refusal = %last,
"seed session abandoned: the world kept refusing its patch"
);
self.persist(SeedCheckpoint::NoPatch {
command_id,
session,
agent_prompt,
refusals,
completed,
gaps: vec![ControllerNeed {
detail: format!(
"The world refused the patch {} times; last refusal: {last}",
MAX_REFUSALS + 1
),
}],
})
.await?;
return Ok(SeedOutcome::NoPatch);
}
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
.await?;
Ok(SeedOutcome::Rejected)
@ -1954,10 +2321,20 @@ impl SeedRunner {
/// One bounded sweep. The budget is the caller's, because who may spend a
/// paid endpoint is a transport question and how far a deficit has fallen
/// is not.
pub async fn sweep(&self, sessions: usize) -> Result<SeedOutcome, ControllerError> {
/// is not. So is the ceiling: each session holds one permit of the
/// caller's pool for its whole step, the same pool every other lane
/// infers under, so a crowd of seeds cannot out-number the connector's
/// per-caller quota.
pub async fn sweep(
&self,
permits: Arc<Semaphore>,
sessions: usize,
) -> Result<SeedOutcome, ControllerError> {
let mut last = SeedOutcome::Clean;
for _ in 0..sessions {
let Ok(_permit) = permits.clone().acquire_owned().await else {
break;
};
last = self.step().await?;
if !matches!(last, SeedOutcome::Committed) {
break;
@ -2035,7 +2412,7 @@ fn seed_request(
command_id: CommandId,
round: usize,
model: &str,
input: Vec<CodexInputItem>,
input: Vec<InputItem>,
) -> Result<InferenceRequest, ControllerError> {
tool_request(
command_id,
@ -2126,7 +2503,7 @@ fn build_seed_prompt(
}
prompt.push_str(&render_clock(snapshot));
prompt.push_str(
"\nA subject qualifies only when it has a controller, at least one affordance grant, and holds a goal commitment. Declare people, institutions, and populations who want something; give each a controller, grants, a position, and a goal. Give them the rest of a life: routines and obligations that recur, counterparties, channels they speak on and who controls them, authority and the offices that lend it, holdings and the dependencies those holdings serve, routes between the places they move through. A goal that nobody can hold the subject to is allowed and expected; the world's elaborator answers that gap later, so do not write it into a promise.\nEvery promise states what is promised, in the promisor's own words. Every person carries material (set_persona_material): a voice, two or three values, a few memories, and a read of each counterparty, all distinct from every other person's; without it the person has no inner life to speak from.\nYou may not declare a human-controlled subject: only the world's first person is human, and that was genesis.\n\n",
"\nA subject qualifies only when it has a controller, at least one affordance grant, and holds a goal commitment. Declare people, institutions, and populations who want something; give each a controller, grants, a position, and a goal. Give them the rest of a life: routines and obligations that recur, counterparties, channels they speak on and who controls them, authority and the offices that lend it, holdings and the dependencies those holdings serve, routes between the places they move through. A goal that nobody can hold the subject to is allowed and expected; the world's elaborator answers that gap later, so do not write it into a promise.\nEvery promise states what is promised, in the promisor's own words. Every person carries material (set_persona_material): a voice, two or three values, a few memories, and a read of each counterparty, all distinct from every other person's; without it the person has no inner life to speak from.\nPeople also carry regards no deed explains: a prejudice against a kind of person (declare_trait on those who carry it, evidenced by a fact; declare_attitude for the prejudice) reaches only those who come to know the trait.\nYou may not declare a human-controlled subject: only the world's first person is human, and that was genesis.\n\n",
);
prompt.push_str(&super::table::render_world_structure(snapshot));
prompt.push('\n');
@ -2213,7 +2590,7 @@ mod tests {
let recomputed: Vec<String> = conversation
.iter()
.filter_map(|item| match item {
CodexInputItem::ToolResult { output, .. } => Some(output.clone()),
InputItem::ToolResult { output, .. } => Some(output.clone()),
_ => None,
})
.collect();
@ -2389,13 +2766,13 @@ mod tests {
.unwrap() else {
panic!("a refused round finalized instead of reopening");
};
let CodexInputItem::UserText { text } = conversation.last().unwrap() else {
let InputItem::UserText { text } = conversation.last().unwrap() else {
panic!("the refusal is not the next user turn");
};
assert!(text.contains("The world refused the patch you submitted"));
assert!(text.contains(&render_mismatch(&Mismatch::NoCanonicalChange)));
assert!(
matches!(&conversation[1], CodexInputItem::ToolCall { name, .. } if name == "declare_place"),
matches!(&conversation[1], InputItem::ToolCall { name, .. } if name == "declare_place"),
"the refused round's calls left the conversation"
);
assert_eq!(
@ -2758,4 +3135,74 @@ mod tests {
if evidence == &EvidenceRef::new("vault:forged"))
));
}
/// The refusal that follows a round which spent the whole budget is still
/// repairable: the repair attempt has the whole budget again, and the oracle
/// reports it, rather than the session dying at "exceeded its round budget".
#[test]
fn a_refusal_opens_a_fresh_round_budget_for_the_repair() {
let drafting = || output(vec![("declare_place", place("shed"))]);
let submitting = || output(vec![("declare_place", place("shed")), ("submit", serde_json::json!({}))]);
let mut completed: Vec<InferenceOutput> = (0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting()).collect();
completed.push(submitting());
let refusals = vec![Refusal {
after_round: completed.len(),
mismatches: vec![Mismatch::EmptyHandle { position: 0 }],
}];
// The refused draft used every round the budget allows.
assert!(matches!(
evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET),
Ok(ElaborationLoopEvaluation::Continue { .. })
));
assert_eq!(
ElaborationOracle::new(&completed, &refusals, ELABORATION_ROUND_BUDGET).remaining_rounds()
as usize,
ELABORATION_ROUND_BUDGET
);
// The repair submits in one round and finalizes.
completed.push(submitting());
assert!(matches!(
evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET),
Ok(ElaborationLoopEvaluation::Complete { capture }) if capture.submitted
));
// A repair that never submits ends at the budget, not before and not after.
let mut idle: Vec<InferenceOutput> = completed[..completed.len() - 1].to_vec();
idle.extend((0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting()));
assert!(matches!(
evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET),
Ok(ElaborationLoopEvaluation::Continue { .. })
));
idle.push(drafting());
let Ok(ElaborationLoopEvaluation::Complete { capture }) =
evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET)
else {
panic!("the repair's last round did not finalize");
};
// What the repair authored is submitted as authored, with the gap named.
assert!(capture.submitted);
assert!(capture.gaps.iter().any(|gap| gap.detail.contains("round budget ended")));
}
#[test]
fn a_sweep_report_counts_each_outcome_once() {
let mut report = SweepReport::default();
for outcome in [
ElaborationOutcome::Committed,
ElaborationOutcome::Rejected,
ElaborationOutcome::Rejected,
ElaborationOutcome::Superseded,
ElaborationOutcome::Superseded,
ElaborationOutcome::Superseded,
ElaborationOutcome::NoPatch,
ElaborationOutcome::NoPatch,
ElaborationOutcome::NoPatch,
ElaborationOutcome::NoPatch,
ElaborationOutcome::Abandoned,
] {
report.count(outcome);
}
assert_eq!(
(report.committed, report.rejected, report.superseded, report.no_patch, report.abandoned),
(1, 2, 3, 4, 1)
);
}
}

View file

@ -8,7 +8,7 @@
//! digest its verbs do not have.
use crate::SubjectKind;
use crate::patch::{AffordanceKindName, EntityKind, RefKind, RoleSpec, kernel_speak_entry};
use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
@ -63,10 +63,20 @@ impl GrammarVerb {
/// Whether a declared role list is this verb's signature: same names, same
/// referent kinds, same order.
pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool {
self.roles.len() == roles.len()
&& self.roles.iter().zip(roles).all(|(want, have)| {
want.role == have.role.0 && want.referent.ref_kind() == have.kind
self.role_specs() == roles
}
/// This verb's signature as the kernel declares it: the one lowering of a
/// grammar role, so declaring a verb and admitting a declaration cannot
/// disagree.
pub(crate) fn role_specs(&self) -> Vec<RoleSpec> {
self.roles
.iter()
.map(|role| RoleSpec {
role: Role(role.role.clone()),
kind: role.referent.ref_kind(),
})
.collect()
}
}
@ -165,6 +175,11 @@ impl GrammarBinding {
}
}
/// Every verb, in kind order.
pub(crate) fn verbs(&self) -> impl Iterator<Item = (&str, &GrammarVerb)> {
self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb))
}
pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> {
self.verbs.get(kind)
}

View file

@ -0,0 +1,765 @@
//! The gestalt hierarchy: who hangs from whom, derived from world state on
//! every read.
//!
//! This organ owns the tree and nothing else. [`derive_hierarchy`] is pure over
//! a `&WorldState`: no clock, no entropy, no mailbox, no filesystem. Nothing it
//! returns is stored, cached or admitted; a node, a [`NodeId`] and a home
//! parent change only because the world changed through an ordinary command
//! (an office granted, an authority granted, a subject moved).
//!
//! Like the agency graph it is wider than any subject view, so it is reachable
//! from `WorldMailbox` and from neither `ControllerPort` nor `ElaborationPort`.
//! The agency graph stays the adjacency inside one node.
//!
//! Home-parent rule, the first that exists: the institution in which the
//! subject holds an office (several: fewest live members, then lowest id); the
//! institution holding an authority grant over the subject (several: lowest
//! id); the innermost institution holding a grant over a place subtree that
//! contains its position (several over one place: lowest id); the place node
//! of its own position; the root. A subject never hangs from itself. Two
//! institutions that would hang from each other are a cycle, broken at its
//! lowest id, which hangs from the root. Other ties stay context, not a second
//! parent: one home per subject.
use super::{
ControllerMode, EntityId, EntityKind, FictionalMinutes, SubjectId, SubjectKind, WorldId,
WorldState, cover::derive_uuid, patch::AuthorityTarget,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use uuid::Uuid;
/// Fixed, never regenerated: two worlds in one process are separated by the
/// world id inside the name, as cover ids are.
const NODE_NAMESPACE: &str = "ghostlight.gestalt.node.v1";
/// Derived from `(world, anchor)`, so the same anchor in the same world is the
/// same node on every read and across every unrelated commit.
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct NodeId(Uuid);
impl NodeId {
pub(crate) fn of(world: WorldId, anchor: &NodeAnchor) -> Self {
Self(derive_uuid(
NODE_NAMESPACE,
&format!("node|{world:?}|{anchor:?}"),
))
}
}
/// What a node stands on. `Subject` names a leaf: a derived hierarchy lists
/// leaves as a node's `loose` subjects and mints no node for them, so the
/// variant exists to give a leaf one stable id when a planner needs it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(tag = "anchor", content = "id", rename_all = "snake_case")]
pub enum NodeAnchor {
World,
Institution(SubjectId),
Place(EntityId),
Subject(SubjectId),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Node {
pub id: NodeId,
pub anchor: NodeAnchor,
/// `None` for the root alone.
pub parent: Option<NodeId>,
/// Ascending by id.
pub children: Vec<NodeId>,
/// The institution subject that speaks for its own node, when it has a
/// non-Human controller. `None` for the root and for place nodes.
pub voice: Option<SubjectId>,
/// Subjects that hang directly from this node and are not nodes
/// themselves. Ascending. Never the Human subject.
pub loose: Vec<SubjectId>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hierarchy {
root: NodeId,
pub nodes: BTreeMap<NodeId, Node>,
/// Every placed subject's one parent node, the Human subject included:
/// the player is placed, never a voice.
pub home: BTreeMap<SubjectId, NodeId>,
/// When each voice last consumed a decision opportunity; absent means
/// never. Read from the kernel's `last_opportunity_at`.
pub last_attended: BTreeMap<SubjectId, FictionalMinutes>,
/// The voices that are populations. A closed place node still speaks for
/// its populations; its persons are silent.
pub populations: BTreeSet<SubjectId>,
/// For every place, the node that governs it: its own place node if one
/// exists, else its innermost governing institution, else the nearest
/// enclosing place node, else the root.
governing: BTreeMap<EntityId, NodeId>,
}
impl Hierarchy {
pub fn root(&self) -> NodeId {
self.root
}
/// The chain of nodes that govern `place`, innermost first and ending at
/// the root. A place the world does not hold is governed by the root
/// alone.
pub fn focus_path(&self, place: EntityId) -> Vec<NodeId> {
let mut path = Vec::new();
let mut current = Some(self.governing.get(&place).copied().unwrap_or(self.root));
while let Some(id) = current {
path.push(id);
current = self.nodes.get(&id).and_then(|node| node.parent);
}
path
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Home {
Institution(SubjectId),
Place(EntityId),
Root,
}
/// The place and its containers, innermost first. Bounded by the entity count,
/// so a corrupt containment loop cannot spin.
fn place_chain(state: &WorldState, place: EntityId) -> Vec<EntityId> {
let mut chain = Vec::new();
let mut current = Some(place);
for _ in 0..=state.entities.len() {
let Some(node) = current else { break };
chain.push(node);
current = state
.entities
.get(&node)
.and_then(|record| record.container);
}
chain
}
pub(super) fn derive_hierarchy(state: &WorldState) -> Hierarchy {
// Who exists to the hierarchy: every subject with a controller. Voices are
// the ones that are not Human.
let mut placed: BTreeSet<SubjectId> = BTreeSet::new();
let mut voices: BTreeSet<SubjectId> = BTreeSet::new();
for (scope, controller) in &state.controller_assignments {
match controller.mode() {
Some(ControllerMode::Human) => {
placed.insert(scope.subject_id);
}
Some(_) => {
placed.insert(scope.subject_id);
voices.insert(scope.subject_id);
}
None => {}
}
}
let institutions: BTreeSet<SubjectId> = voices
.iter()
.copied()
.filter(|subject| {
state
.subjects
.get(subject)
.is_some_and(|record| record.kind == SubjectKind::Institution)
})
.collect();
// Office incumbency: subject -> (institution, its live member count).
let members = |institution: SubjectId| -> usize {
state
.selection
.get(&institution)
.map(|offices| {
offices
.values()
.filter_map(|office| office.incumbent)
.filter(|incumbent| placed.contains(incumbent))
.collect::<BTreeSet<_>>()
.len()
})
.unwrap_or(0)
};
let mut offices_held: BTreeMap<SubjectId, Vec<SubjectId>> = BTreeMap::new();
for institution in &institutions {
for office in state.selection.get(institution).into_iter().flat_map(|o| o.values()) {
if let Some(incumbent) = office.incumbent
&& placed.contains(&incumbent)
{
let held = offices_held.entry(incumbent).or_default();
if !held.contains(institution) {
held.push(*institution);
}
}
}
}
// Authority grants held by an institution, by what they cover.
let mut over_subject: BTreeMap<SubjectId, BTreeSet<SubjectId>> = BTreeMap::new();
let mut over_place: BTreeMap<EntityId, BTreeSet<SubjectId>> = BTreeMap::new();
for (holder, grants) in &state.authority {
if !institutions.contains(holder) {
continue;
}
for grant in grants {
match grant.over {
AuthorityTarget::Subject(subject) => {
over_subject.entry(subject).or_default().insert(*holder);
}
AuthorityTarget::PlaceSubtree(place) => {
over_place.entry(place).or_default().insert(*holder);
}
}
}
}
let mut home_of: BTreeMap<SubjectId, Home> = BTreeMap::new();
for subject in &placed {
let own = *subject;
let by_office = offices_held.get(&own).and_then(|held| {
held.iter()
.copied()
.filter(|institution| *institution != own)
.min_by_key(|institution| (members(*institution), *institution))
});
let by_grant = || {
over_subject
.get(&own)
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
};
let by_place = || {
let position = state.positions.get(&own)?;
place_chain(state, position.place).into_iter().find_map(|place| {
over_place
.get(&place)
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
})
};
let home = by_office
.or_else(by_grant)
.or_else(by_place)
.map(Home::Institution)
.or_else(|| state.positions.get(&own).map(|position| Home::Place(position.place)))
.unwrap_or(Home::Root);
home_of.insert(own, home);
}
// A cycle can only run through institutions. Break each at its lowest id.
let mut settled: BTreeSet<SubjectId> = BTreeSet::new();
for start in &institutions {
let mut path: Vec<SubjectId> = Vec::new();
let mut current = *start;
loop {
if settled.contains(&current) {
break;
}
if let Some(at) = path.iter().position(|seen| *seen == current) {
let lowest = path[at..].iter().copied().min().expect("a cycle is non-empty");
home_of.insert(lowest, Home::Root);
break;
}
path.push(current);
match home_of.get(&current) {
Some(Home::Institution(parent)) => current = *parent,
_ => break,
}
}
settled.extend(path);
}
// Place nodes exist only where some subject hangs from one.
let place_nodes: BTreeSet<EntityId> = home_of
.values()
.filter_map(|home| match home {
Home::Place(place) => Some(*place),
_ => None,
})
.collect();
let world = state.world_id;
let root = NodeId::of(world, &NodeAnchor::World);
let institution_node = |institution: SubjectId| NodeId::of(world, &NodeAnchor::Institution(institution));
let place_node = |place: EntityId| NodeId::of(world, &NodeAnchor::Place(place));
let node_of_home = |home: &Home| match home {
Home::Institution(institution) => institution_node(*institution),
Home::Place(place) => place_node(*place),
Home::Root => root,
};
let mut nodes: BTreeMap<NodeId, Node> = BTreeMap::new();
nodes.insert(
root,
Node {
id: root,
anchor: NodeAnchor::World,
parent: None,
children: Vec::new(),
voice: None,
loose: Vec::new(),
},
);
for institution in &institutions {
let id = institution_node(*institution);
nodes.insert(
id,
Node {
id,
anchor: NodeAnchor::Institution(*institution),
parent: Some(node_of_home(&home_of[institution])),
children: Vec::new(),
voice: Some(*institution),
loose: Vec::new(),
},
);
}
for place in &place_nodes {
let id = place_node(*place);
let parent = place_chain(state, *place)
.into_iter()
.skip(1)
.find(|ancestor| place_nodes.contains(ancestor))
.map(place_node)
.unwrap_or(root);
nodes.insert(
id,
Node {
id,
anchor: NodeAnchor::Place(*place),
parent: Some(parent),
children: Vec::new(),
voice: None,
loose: Vec::new(),
},
);
}
let mut home: BTreeMap<SubjectId, NodeId> = BTreeMap::new();
for (subject, subject_home) in &home_of {
let parent = node_of_home(subject_home);
home.insert(*subject, parent);
if voices.contains(subject) && !institutions.contains(subject) {
nodes
.get_mut(&parent)
.expect("a home names a node that was just minted")
.loose
.push(*subject);
}
}
let links: Vec<(NodeId, NodeId)> = nodes
.values()
.filter_map(|node| node.parent.map(|parent| (parent, node.id)))
.collect();
for (parent, child) in links {
nodes
.get_mut(&parent)
.expect("a parent is a minted node")
.children
.push(child);
}
// `home_of` iterates ascending, so `loose` is already ascending; children
// arrive in node-id order from `nodes`.
let mut governing: BTreeMap<EntityId, NodeId> = BTreeMap::new();
for (place, record) in &state.entities {
if record.kind != EntityKind::Place {
continue;
}
let chain = place_chain(state, *place);
let node = if place_nodes.contains(place) {
place_node(*place)
} else if let Some(holder) = chain
.iter()
.find_map(|link| over_place.get(link).and_then(|holders| holders.first()))
{
institution_node(*holder)
} else {
chain
.iter()
.find(|link| place_nodes.contains(link))
.map(|link| place_node(*link))
.unwrap_or(root)
};
governing.insert(*place, node);
}
let last_attended = voices
.iter()
.filter_map(|voice| {
state
.last_opportunity_at
.get(voice)
.map(|at| (*voice, *at))
})
.collect();
let populations = voices
.iter()
.copied()
.filter(|voice| {
state
.subjects
.get(voice)
.is_some_and(|record| record.kind == SubjectKind::Population)
})
.collect();
Hierarchy {
root,
nodes,
home,
last_attended,
populations,
governing,
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::patch::{
AuthorityGrant, AuthorityKindName, EntityRecord, Office, OfficeName, Position,
};
use crate::{
ControllerAssignment, ControllerId, DecisionScope, PrincipalId, SubjectState,
};
pub(crate) struct Fixture {
pub(crate) state: WorldState,
next: u128,
}
impl Fixture {
pub(crate) fn new() -> Self {
Self {
state: WorldState::empty(
WorldId(Uuid::from_u128(0xfeed)),
PrincipalId::new("owner"),
"Hierarchy".into(),
None,
),
next: 1,
}
}
fn uuid(&mut self) -> Uuid {
self.next += 1;
Uuid::from_u128(self.next)
}
pub(crate) fn place(&mut self, label: &str, container: Option<EntityId>) -> EntityId {
let id = EntityId(self.uuid());
self.state.entities.insert(
id,
EntityRecord {
label: label.into(),
kind: EntityKind::Place,
container,
},
);
id
}
pub(crate) fn subject(&mut self, label: &str, kind: SubjectKind, at: Option<EntityId>) -> SubjectId {
let id = SubjectId(self.uuid());
let controller_id = ControllerId(self.uuid());
self.state.subjects.insert(
id,
SubjectState {
label: label.into(),
kind,
import_key: None,
},
);
self.state.controller_assignments.insert(
DecisionScope { subject_id: id },
ControllerAssignment::NarrativePersona { controller_id },
);
if let Some(place) = at {
self.state.positions.insert(id, Position { place });
}
id
}
pub(crate) fn player(&mut self, at: EntityId) -> SubjectId {
let id = self.subject("Player", SubjectKind::Person, Some(at));
let controller_id = ControllerId(self.uuid());
self.state.controller_assignments.insert(
DecisionScope { subject_id: id },
ControllerAssignment::Human {
controller_id,
principal: PrincipalId::new("player"),
},
);
id
}
pub(crate) fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) {
self.state.selection.entry(institution).or_default().insert(
OfficeName(name.into()),
Office {
incumbent: Some(incumbent),
delegated: [AuthorityKindName("rule".into())].into(),
},
);
}
pub(crate) fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) {
self.state.authority.entry(holder).or_default().insert(AuthorityGrant {
kind: AuthorityKindName("rule".into()),
over,
});
}
}
fn parent_of(hierarchy: &Hierarchy, node: NodeId) -> Option<NodeId> {
hierarchy.nodes[&node].parent
}
fn inst(hierarchy: &Hierarchy, world: &WorldState, subject: SubjectId) -> NodeId {
let id = NodeId::of(world.world_id, &NodeAnchor::Institution(subject));
assert!(hierarchy.nodes.contains_key(&id), "no institution node");
id
}
#[test]
fn hierarchy_is_deterministic_and_ids_survive_an_unrelated_commit() {
let mut f = Fixture::new();
let town = f.place("Town", None);
let council = f.subject("Council", SubjectKind::Institution, None);
let alice = f.subject("Alice", SubjectKind::Person, Some(town));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.office(council, "mayor", alice);
let first = derive_hierarchy(&f.state);
assert_eq!(first, derive_hierarchy(&f.state));
assert_eq!(
serde_json::to_vec(&first).unwrap(),
serde_json::to_vec(&derive_hierarchy(&f.state)).unwrap()
);
// Time passes and an unrelated subject acts: no node changes identity.
f.state.now = FictionalMinutes(500);
f.state.revision += 7;
f.state.last_opportunity_at.insert(alice, FictionalMinutes(40));
let later = derive_hierarchy(&f.state);
assert_eq!(
first.nodes.keys().collect::<Vec<_>>(),
later.nodes.keys().collect::<Vec<_>>()
);
assert_eq!(first.home, later.home);
assert_eq!(later.last_attended.get(&alice), Some(&FictionalMinutes(40)));
assert!(first.last_attended.is_empty());
// The same anchor in another world is another node.
let other = NodeId::of(WorldId(Uuid::from_u128(0xbeef)), &NodeAnchor::World);
assert_ne!(other, first.root());
}
#[test]
fn every_voice_has_exactly_one_home_and_a_chain_to_the_root() {
let mut f = Fixture::new();
let region = f.place("Region", None);
let town = f.place("Town", Some(region));
let tavern = f.place("Tavern", Some(town));
let empire = f.subject("Empire", SubjectKind::Institution, None);
let council = f.subject("Council", SubjectKind::Institution, Some(town));
let guild = f.subject("Guild", SubjectKind::Institution, Some(tavern));
let folk = f.subject("Townsfolk", SubjectKind::Population, Some(town));
let alice = f.subject("Alice", SubjectKind::Person, Some(tavern));
let bob = f.subject("Bob", SubjectKind::Person, Some(region));
let nowhere = f.subject("Drifter", SubjectKind::Person, None);
let player = f.player(tavern);
f.grant(empire, AuthorityTarget::Subject(council));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.office(guild, "master", alice);
let hierarchy = derive_hierarchy(&f.state);
let voices = [empire, council, guild, folk, alice, bob, nowhere];
for voice in voices {
let mut at = hierarchy.home[&voice];
let mut seen = BTreeSet::new();
loop {
assert!(seen.insert(at), "a chain revisited a node");
match parent_of(&hierarchy, at) {
Some(up) => at = up,
None => break,
}
}
assert_eq!(at, hierarchy.root(), "a chain ended off the root");
// Exactly one place holds it: as a child node or as a loose subject.
let holders = hierarchy
.nodes
.values()
.filter(|node| node.loose.contains(&voice) || {
node.anchor == NodeAnchor::Institution(voice)
})
.count();
assert_eq!(holders, 1, "a voice is held by {holders} nodes");
}
assert_eq!(hierarchy.home.len(), voices.len() + 1, "the player is placed too");
assert!(hierarchy.home.contains_key(&player));
// A population is a single loose voice, hung by the same rule.
assert_eq!(hierarchy.home[&folk], inst(&hierarchy, &f.state, council));
assert_eq!(hierarchy.home[&nowhere], hierarchy.root());
// Children and parents agree.
for node in hierarchy.nodes.values() {
for child in &node.children {
assert_eq!(hierarchy.nodes[child].parent, Some(node.id));
}
}
}
#[test]
fn institutions_come_before_places() {
let mut f = Fixture::new();
let town = f.place("Town", None);
let tap_room = f.place("Tap-room", Some(town));
let field = f.place("Field", None);
let council = f.subject("Council", SubjectKind::Institution, None);
let guild = f.subject("Guild", SubjectKind::Institution, None);
let in_guild = f.subject("Guildsman", SubjectKind::Person, Some(tap_room));
let plain = f.subject("Drinker", SubjectKind::Person, Some(tap_room));
let farmer = f.subject("Farmer", SubjectKind::Person, Some(field));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.office(guild, "member", in_guild);
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&in_guild], inst(&hierarchy, &f.state, guild));
assert_eq!(hierarchy.home[&plain], inst(&hierarchy, &f.state, council));
let field_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(field));
assert_eq!(hierarchy.home[&farmer], field_node);
assert_eq!(parent_of(&hierarchy, field_node), Some(hierarchy.root()));
// A place node exists only where somebody hangs from it.
assert_eq!(
hierarchy
.nodes
.values()
.filter(|node| matches!(node.anchor, NodeAnchor::Place(_)))
.count(),
1
);
}
#[test]
fn an_authority_grant_over_the_subject_beats_a_place_grant() {
let mut f = Fixture::new();
let town = f.place("Town", None);
let council = f.subject("Council", SubjectKind::Institution, None);
let temple = f.subject("Temple", SubjectKind::Institution, None);
let priest = f.subject("Priest", SubjectKind::Person, Some(town));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.grant(temple, AuthorityTarget::Subject(priest));
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&priest], inst(&hierarchy, &f.state, temple));
}
#[test]
fn the_innermost_place_grant_governs_and_several_offices_pick_the_smaller_body() {
let mut f = Fixture::new();
let region = f.place("Region", None);
let town = f.place("Town", Some(region));
let crown = f.subject("Crown", SubjectKind::Institution, None);
let council = f.subject("Council", SubjectKind::Institution, None);
let big = f.subject("Big", SubjectKind::Institution, None);
let small = f.subject("Small", SubjectKind::Institution, None);
let walker = f.subject("Walker", SubjectKind::Person, Some(town));
let other_a = f.subject("A", SubjectKind::Person, None);
let other_b = f.subject("B", SubjectKind::Person, None);
let sitter = f.subject("Sitter", SubjectKind::Person, Some(town));
f.grant(crown, AuthorityTarget::PlaceSubtree(region));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.office(big, "a", other_a);
f.office(big, "b", other_b);
f.office(big, "c", sitter);
f.office(small, "a", sitter);
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&walker], inst(&hierarchy, &f.state, council));
assert_eq!(hierarchy.home[&sitter], inst(&hierarchy, &f.state, small));
}
#[test]
fn a_cycle_is_broken_at_its_lowest_id() {
let mut f = Fixture::new();
let one = f.subject("One", SubjectKind::Institution, None);
let two = f.subject("Two", SubjectKind::Institution, None);
f.grant(one, AuthorityTarget::Subject(two));
f.grant(two, AuthorityTarget::Subject(one));
let (low, high) = if one < two { (one, two) } else { (two, one) };
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&low], hierarchy.root());
assert_eq!(hierarchy.home[&high], inst(&hierarchy, &f.state, low));
}
#[test]
fn a_tail_leading_into_a_cycle_keeps_its_parent_when_the_cycle_breaks() {
let mut f = Fixture::new();
let tail = f.subject("Tail", SubjectKind::Institution, None);
let one = f.subject("One", SubjectKind::Institution, None);
let two = f.subject("Two", SubjectKind::Institution, None);
f.grant(one, AuthorityTarget::Subject(tail));
f.grant(one, AuthorityTarget::Subject(two));
f.grant(two, AuthorityTarget::Subject(one));
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&tail], inst(&hierarchy, &f.state, one));
assert_eq!(hierarchy.home[&one], hierarchy.root());
assert_eq!(hierarchy.home[&two], inst(&hierarchy, &f.state, one));
}
#[test]
fn the_player_is_placed_and_never_a_voice() {
let mut f = Fixture::new();
let town = f.place("Town", None);
let council = f.subject("Council", SubjectKind::Institution, None);
let player = f.player(town);
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.office(council, "seat", player);
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(hierarchy.home[&player], inst(&hierarchy, &f.state, council));
assert!(
hierarchy
.nodes
.values()
.all(|node| node.voice != Some(player) && !node.loose.contains(&player))
);
assert!(!hierarchy.last_attended.contains_key(&player));
}
#[test]
fn the_focus_path_follows_governance() {
let mut f = Fixture::new();
let town = f.place("Town", None);
let tap_room = f.place("Tap-room", Some(town));
let heath = f.place("Heath", None);
let empire = f.subject("Empire", SubjectKind::Institution, None);
let council = f.subject("Council", SubjectKind::Institution, None);
f.subject("Drinker", SubjectKind::Person, Some(tap_room));
f.grant(council, AuthorityTarget::PlaceSubtree(town));
f.grant(empire, AuthorityTarget::Subject(council));
let hierarchy = derive_hierarchy(&f.state);
assert_eq!(
hierarchy.focus_path(tap_room),
vec![
inst(&hierarchy, &f.state, council),
inst(&hierarchy, &f.state, empire),
hierarchy.root(),
]
);
// An ungoverned place is governed by the root alone.
assert_eq!(hierarchy.focus_path(heath), vec![hierarchy.root()]);
}
#[test]
fn a_place_node_hangs_from_the_nearest_enclosing_place_node() {
let mut f = Fixture::new();
let region = f.place("Region", None);
let hamlet = f.place("Hamlet", Some(region));
let barn = f.place("Barn", Some(hamlet));
f.subject("Reeve", SubjectKind::Person, Some(region));
f.subject("Hand", SubjectKind::Person, Some(barn));
let hierarchy = derive_hierarchy(&f.state);
let region_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(region));
let barn_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(barn));
assert_eq!(parent_of(&hierarchy, barn_node), Some(region_node));
assert_eq!(
hierarchy.focus_path(hamlet),
vec![region_node, hierarchy.root()]
);
}
}

View file

@ -0,0 +1,752 @@
//! One record, one subject: admission keeps the import-key mapping injective at
//! every door and at every revision, and a world nobody imported into is
//! byte-for-byte what it was before keys existed.
use crate::patch::{
AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind,
ImportKey, Mismatch, Ref, RouteDeclaration,
};
use crate::tests::{activate, auth_principal, command, creation, owner};
use crate::{
CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, JurisdictionKey,
KernelError, NewController, PatchAnswer, SubjectDeclaration, SubjectKind, SubmitReceipt,
SystemCapability, WorldKernel, WorldPatch,
};
use std::collections::BTreeSet;
fn key(schema: &str, record: &str) -> ImportKey {
ImportKey::new(schema, record)
}
fn alpha() -> ImportKey {
key("aetheria.ship", "Alpha")
}
/// The fixture genesis with its witness imported from `alpha()`.
fn keyed_creation(title: &str) -> CreateWorld {
let mut world = creation(CommandId::new(), title);
for declaration in &mut world.patch.declarations {
if let Declaration::Subject(subject) = declaration
&& subject.handle == DraftHandle::new("persona")
{
subject.import_key = Some(alpha());
}
}
world
}
fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
let directory = tempfile::tempdir().unwrap();
let result = WorldKernel::create(
directory.path().join("world.cc"),
world,
&auth_principal(owner()),
)
.map(|(kernel, _)| kernel);
(directory, result)
}
fn keyed_world() -> (tempfile::TempDir, WorldKernel) {
let (dir, kernel) = create(keyed_creation("Keyed"));
(dir, kernel.unwrap())
}
fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> {
match result {
Err(KernelError::PatchRejected(set)) => set,
Err(other) => panic!("expected a patch refusal, got {other:?}"),
Ok(_) => panic!("expected a patch refusal, the command was admitted"),
}
}
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
WorldPatch {
declarations,
operations: Vec::new(),
evidence: Vec::new(),
}
}
fn submit_as(
kernel: &mut WorldKernel,
caller: CallerId,
answers: Option<PatchAnswer>,
patch: WorldPatch,
) -> Result<SubmitReceipt, KernelError> {
let snapshot = kernel.snapshot().unwrap();
kernel.submit(
command(
&snapshot,
CommandId::new(),
caller.clone(),
CommandBody::AdmitPatch { answers, patch },
),
&crate::AuthenticatedCaller::fixture(caller),
)
}
fn commons(kernel: &WorldKernel) -> EntityId {
*kernel.state.entities.keys().next().unwrap()
}
/// A mirror subject: the one shape every door may declare, since it needs no
/// catalog grant.
fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration {
Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new(handle),
label: format!("The {handle}"),
kind: SubjectKind::Person,
controller: NewController::External {
consumer: ConsumerId::of_name("import-key"),
},
affordances: BTreeSet::new(),
position: Some(Ref::Existing(place)),
import_key,
})
}
fn held(handle: &str) -> Mismatch {
Mismatch::ImportKeyHeld {
handle: DraftHandle::new(handle),
}
}
fn duplicate(handle: &str) -> Mismatch {
Mismatch::DuplicateImportKey {
handle: DraftHandle::new(handle),
}
}
fn malformed(handle: &str) -> Mismatch {
Mismatch::MalformedImportKey {
handle: DraftHandle::new(handle),
}
}
fn keys_in(kernel: &WorldKernel) -> Vec<ImportKey> {
kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.filter_map(|subject| subject.import_key)
.collect()
}
#[test]
fn one_patch_cannot_declare_two_subjects_with_one_import_key() {
// At genesis.
let mut world = creation(CommandId::new(), "Twins");
for declaration in &mut world.patch.declarations {
if let Declaration::Subject(subject) = declaration
&& (subject.handle == DraftHandle::new("persona")
|| subject.handle == DraftHandle::new("operator"))
{
subject.import_key = Some(alpha());
}
}
let (_dir, result) = create(world);
assert_eq!(rejected(result), vec![duplicate("operator")]);
// In a later patch, with the key unheld.
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let revision = kernel.state.revision;
let beta = Some(key("aetheria.ship", "Beta"));
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![
mirror("first", beta.clone(), place),
mirror("second", beta, place),
]),
);
assert_eq!(rejected(error), vec![duplicate("second")]);
assert_eq!(kernel.state.revision, revision, "a refusal moved the world");
}
/// The fixture world past genesis but still in Draft: the owner has added an
/// unwalked place the elaborator can later answer.
fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) {
let (dir, mut kernel) = keyed_world();
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new("dead-end"),
label: "The Unwalked Road".into(),
kind: EntityKind::Place,
container: None,
}),
Declaration::Route(RouteDeclaration {
handle: DraftHandle::new("gate"),
label: "The Field Gate".into(),
from: Ref::Existing(place),
to: Ref::Draft(DraftHandle::new("dead-end")),
access: AccessKind::Public,
cost: Cost(1),
}),
]),
)
.unwrap();
let dead_end = *kernel
.state
.entities
.iter()
.find(|(_, record)| record.label == "The Unwalked Road")
.map(|(id, _)| id)
.unwrap();
(dir, kernel, dead_end)
}
/// Each door names the held key, typed, and the refusal leaves the revision
/// where it was. The owner and the consumer declare in Draft only; Play and the
/// elaborator act in Active.
fn refuse_held_key_at_each_door(
kernel: &mut WorldKernel,
place: EntityId,
doors: Vec<(&str, CallerId, Option<PatchAnswer>)>,
) {
for (door, caller, answers) in doors {
let revision = kernel.state.revision;
let result = submit_as(
kernel,
caller,
answers,
patch_of(vec![mirror("copy", Some(alpha()), place)]),
);
assert_eq!(rejected(result), vec![held("copy")], "{door}");
assert_eq!(
kernel.state.revision, revision,
"{door} refusal moved the world"
);
}
}
fn consumer() -> CallerId {
CallerId::System(SystemCapability::Consumer {
consumer: ConsumerId::of_name("import-key"),
})
}
#[test]
fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() {
let (_dir, mut kernel, dead_end) = advanced_keyed_world();
assert!(kernel.state.revision > 0, "the world has moved past genesis");
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("owner", CallerId::Principal(owner()), None),
("consumer", consumer(), None),
],
);
activate(&mut kernel);
let answer = crate::derive_boundaries(&kernel.state)
.unwrap()
.into_iter()
.find(|boundary| {
matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. }
if *place == dead_end)
})
.expect("the dead end is an unelaborated destination");
refuse_held_key_at_each_door(
&mut kernel,
dead_end,
vec![
("play", CallerId::System(SystemCapability::Play), None),
(
"elaborator",
CallerId::System(SystemCapability::Elaborator {
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
}),
Some(PatchAnswer::Boundary(answer.clone())),
),
],
);
// The same doors admit an unheld key, so the refusals are the key's; and
// what a door admitted is held against every later door.
let fresh = key("aetheria.ship", "Gamma");
let receipt = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Elaborator {
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
}),
Some(PatchAnswer::Boundary(answer)),
patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]),
)
.unwrap();
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let again = submit_as(
&mut kernel,
CallerId::System(SystemCapability::Play),
None,
patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]),
);
assert_eq!(rejected(again), vec![held("fresh-again")]);
}
#[test]
fn a_held_import_key_is_refused_in_a_later_patch() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let revision = kernel.state.revision;
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("again", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("again")]);
assert_eq!(kernel.state.revision, revision);
assert_eq!(keys_in(&kernel), vec![alpha()]);
}
#[test]
fn a_retired_subjects_import_key_is_never_reissued() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let witness = kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.find(|subject| subject.import_key.is_some())
.unwrap()
.id;
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
WorldPatch {
declarations: Vec::new(),
operations: vec![ComponentOp::Retire {
subject: Ref::Existing(witness),
}],
evidence: Vec::new(),
},
)
.unwrap();
let retired = kernel
.snapshot()
.unwrap()
.subjects
.into_iter()
.find(|subject| subject.id == witness)
.unwrap();
assert!(retired.retired, "the witness is retired");
assert_eq!(
retired.import_key,
Some(alpha()),
"a retired subject keeps its key"
);
let error = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("reborn", Some(alpha()), place)]),
);
assert_eq!(rejected(error), vec![held("reborn")]);
}
#[test]
fn keys_that_differ_in_any_way_are_distinct_records() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
// Same length, case, prefix, the same concatenation split elsewhere, and
// the parts swapped: none is the held key.
let forgeries = [
key("aetheria.ship", "Alphb"),
key("aetheria.ship", "alpha"),
key("aetheria.ship", "Alph"),
key("aetheria.ship", "Alpha2"),
key("aetheria.shipA", "lpha"),
key("aetheria.sh", "ipAlpha"),
key("Aetheria.ship", "Alpha"),
key("Alpha", "aetheria.ship"),
key("aetheria.ship2", "Alpha"),
];
let declarations = forgeries
.iter()
.enumerate()
.map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(declarations),
)
.expect("nine distinct keys beside the held one are admitted together");
let held_now: BTreeSet<ImportKey> = keys_in(&kernel).into_iter().collect();
assert_eq!(held_now.len(), forgeries.len() + 1);
// And each is then held exactly: repeating any one is refused.
for (index, forged) in forgeries.iter().enumerate() {
let again = submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("repeat", Some(forged.clone()), place)]),
);
assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}");
}
}
#[test]
fn a_malformed_import_key_is_refused_without_echoing_it() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let long = "x".repeat(201);
let wide = "é".repeat(101);
let cases = [
key("", "Delta"),
key("aetheria.ship", ""),
key("aetheria ship", "Delta"),
key("aetheria.ship", "Del\tta"),
key("aetheria.ship", "Del\u{a0}ta"),
key("aetheria.ship", " Delta"),
key("aetheria.ship", "Delta\n"),
key(&long, "Delta"),
key("aetheria.ship", &long),
key("aetheria.ship", &wide),
key(&wide, "Delta"),
];
for (index, bad) in cases.iter().enumerate() {
let set = rejected(submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror("bad", Some(bad.clone()), place)]),
));
assert_eq!(set, vec![malformed("bad")], "case {index}");
let spelled = format!("{set:?}");
assert!(
!spelled.contains("Delta") && !spelled.contains("aetheria"),
"case {index} echoed the key"
);
}
// The limit is 200 bytes per part, counted in bytes.
let edge = "é".repeat(100);
let at_limit = [
key(&"x".repeat(200), &edge),
key("aetheria.ship", &"y".repeat(200)),
];
let declarations = at_limit
.iter()
.enumerate()
.map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place))
.collect();
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(declarations),
)
.expect("keys of exactly 200 bytes per part are admitted");
}
#[test]
fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() {
let (_dir, kernel) = keyed_world();
let place = commons(&kernel);
let resolve = |handle: &str| {
crate::patch::resolve_patch(
&kernel.state,
CommandId::new(),
&patch_of(vec![mirror(
handle,
Some(key("aetheria.ship", "Omega")),
place,
)]),
None,
None,
)
.expect("the key is unheld at the revision both were resolved against")
};
let (first, second) = (resolve("first"), resolve("second"));
let mut state = kernel.state.clone();
let before = state.subjects.len();
let effect = |resolved| crate::WorldEffect::PatchAdmitted {
answers: None,
resolved,
};
crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&effect(first),
)
.unwrap();
assert_eq!(state.subjects.len(), before + 1);
let result = crate::apply_effect(
&mut state,
CommandId::new(),
&CallerId::Principal(owner()),
&effect(second),
);
assert!(
matches!(result, Err(KernelError::Invariant(_))),
"{result:?}"
);
assert_eq!(
state.subjects.len(),
before + 1,
"the second subject was installed"
);
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|window| window == needle)
}
#[test]
fn keyless_world_digests_unchanged() {
// A subject nobody imported serialises without the field at all, so every
// digest written before keys existed is the digest of the same bytes.
let (_dir, kernel) = create(creation(CommandId::new(), "Keyless"));
let kernel = kernel.unwrap();
let state = rmp_serde::to_vec_named(&kernel.state).unwrap();
assert!(
!contains(&state, b"import_key"),
"a keyless world grew a field"
);
// A keyed world carries it, round-trips, and digests differently.
let (_dir, keyed) = keyed_world();
let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap();
assert!(contains(&keyed_state, b"import_key"));
let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap();
assert_eq!(
crate::state_digest(&back).unwrap(),
crate::state_digest(&keyed.state).unwrap()
);
assert_ne!(
crate::state_digest(&keyed.state).unwrap(),
crate::state_digest(&kernel.state).unwrap()
);
// And a pre-key state deserialises with every key absent.
let stripped: crate::WorldState = rmp_serde::from_slice(&state).unwrap();
assert!(stripped.subjects.values().all(|s| s.import_key.is_none()));
}
#[test]
fn a_keyed_world_reopens_with_its_keys_and_digests() {
let (dir, kernel) = keyed_world();
let snapshot = kernel.snapshot().unwrap();
let world_id = snapshot.world_id;
drop(kernel);
let reopened = WorldKernel::open(dir.path().join("world.cc"), world_id).unwrap();
let again = reopened.snapshot().unwrap();
assert_eq!(again.state_digest, snapshot.state_digest);
let keys = keys_in(&reopened);
assert_eq!(keys, vec![alpha()]);
// A reader of the snapshot gets both parts back, separately.
assert_eq!(keys[0].schema(), "aetheria.ship");
assert_eq!(keys[0].record(), "Alpha");
}
#[test]
fn a_record_key_is_one_canonical_spelling() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let nfc = "Caf\u{e9}";
let nfd = "Cafe\u{301}";
let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.ship", record)),
place,
)]),
)
};
submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted");
let refused = [
nfd,
"Alpha\u{200b}",
"Alpha\u{0}",
"\u{feff}Alpha",
"Alpha\u{202e}",
"Alpha\u{7}",
"Del ta",
"Del\tta",
"Del\u{a0}ta",
"Del\u{2003}ta",
"Del\nta",
// The violation sits deep in a long, real-shaped path, past any prefix.
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}",
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart",
];
for (index, record) in refused.iter().enumerate() {
let set = rejected(submit(&mut kernel, "bad", record));
assert_eq!(set, vec![malformed("bad")], "spelling {index}");
assert!(
!format!("{set:?}").contains("Alpha"),
"spelling {index} echoed the key"
);
}
assert_eq!(
keys_in(&kernel).len(),
2,
"only the genesis key and the NFC key are held"
);
}
#[test]
fn a_lore_page_path_with_spaces_is_a_record_key() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart";
let declare = |kernel: &mut WorldKernel, handle: &str| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.lore", record)),
place,
)]),
)
};
declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted");
assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]);
}
#[test]
fn a_loaded_state_with_a_bad_import_key_is_refused() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
submit_as(
&mut kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
"beta",
Some(key("aetheria.ship", "Beta")),
place,
)]),
)
.unwrap();
assert!(crate::journal::verify_state_shape(&kernel.state).is_ok());
let corrupt = |edit: &dyn Fn(&mut ImportKey)| {
let mut state = kernel.state.clone();
for subject in state.subjects.values_mut() {
if let Some(held) = subject.import_key.as_mut() {
edit(held);
}
}
crate::journal::verify_state_shape(&state)
};
let shared = corrupt(&|held| *held = alpha());
assert!(
matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")),
"two subjects sharing one key: {shared:?}"
);
assert!(
corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(),
"a key with edge spaces must not load"
);
assert!(
corrupt(&|held| *held = key("", "")).is_err(),
"an empty key must not load"
);
assert!(
corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(),
"a key with a format character must not load"
);
}
/// The admission backstop, reached with an effect resolution never produced: a
/// resolved patch whose two subjects carry one key. The control is the same
/// effect with distinct keys, admitted by the same function.
#[test]
fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() {
let (_dir, kernel) = keyed_world();
let place = commons(&kernel);
let resolve = || {
crate::patch::resolve_patch(
&kernel.state,
CommandId::new(),
&patch_of(vec![
mirror("first", Some(key("aetheria.ship", "Beta")), place),
mirror("second", Some(key("aetheria.ship", "Gamma")), place),
]),
None,
None,
)
.expect("two distinct keys resolve")
};
let resolves_to = crate::resolution_revision(&kernel.state).unwrap();
let mut control = kernel.state.clone();
crate::admit_resolved(&mut control, &resolve(), resolves_to)
.expect("distinct keys are admitted");
let mut twinned = resolve();
assert_eq!(twinned.subjects.len(), 2);
twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone();
let mut state = kernel.state.clone();
let error = crate::admit_resolved(&mut state, &twinned, resolves_to)
.expect_err("one key on two resolved subjects is refused");
assert!(
matches!(&error, KernelError::Invariant(why) if why.contains("import key")),
"{error:?}"
);
assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key");
}
/// A decomposable character at every position of a real-shaped key: the NFD
/// spelling is refused wherever it sits, the NFC spelling is admitted, so the
/// rule cannot be a prefix, suffix or first-character check.
#[test]
fn a_decomposable_character_is_refused_in_nfd_at_every_position() {
let (_dir, mut kernel) = keyed_world();
let place = commons(&kernel);
let template: Vec<char> = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"
.chars()
.collect();
let submit = |kernel: &mut WorldKernel, handle: &str, record: String| {
submit_as(
kernel,
CallerId::Principal(owner()),
None,
patch_of(vec![mirror(
handle,
Some(key("aetheria.lore", &record)),
place,
)]),
)
};
let spelled = |position: usize, inserted: &str| {
let mut record: String = template[..position].iter().collect();
record.push_str(inserted);
record.extend(&template[position..]);
record
};
for position in 0..=template.len() {
let nfd = spelled(position, "e\u{301}");
assert!(
!unicode_normalization::is_nfc(&nfd),
"position {position} is not NFD"
);
let set = rejected(submit(&mut kernel, "bad", nfd));
assert_eq!(set, vec![malformed("bad")], "NFD at position {position}");
}
for position in 0..=template.len() {
let nfc = spelled(position, "\u{e9}");
submit(&mut kernel, &format!("good{position}"), nfc)
.unwrap_or_else(|_| panic!("NFC at position {position} was refused"));
}
assert_eq!(
keys_in(&kernel).len(),
1 + template.len() + 1,
"the genesis key and one NFC key per position are held, no NFD key"
);
}

View file

@ -181,6 +181,11 @@ impl WorldJournal {
self.commits.get(&command_id)
}
/// Every commit the journal holds, in no particular order.
pub(super) fn commits(&self) -> impl Iterator<Item = &WorldCommit> {
self.commits.values()
}
#[cfg(test)]
pub(super) fn commit_count(&self) -> usize {
self.commits.len()
@ -728,6 +733,55 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
));
}
}
// Attitude: a holder and its target are canonical subjects, a delta is
// nonzero and bounded, a stamp is not from the future, and a rumour rests
// on a fact that exists. A trait row names a canonical subject, a civic
// trait name, and at least one real fact.
for (holder, held) in &state.attitudes {
let modifier_is_canonical = |key: &super::AttitudeKey, modifier: &super::AttitudeModifier| {
let toward_is_canonical = match &key.toward {
super::AttitudeToward::Subject(target) => {
state.subjects.contains_key(target) && target != holder
}
super::AttitudeToward::Trait(name) => super::patch::is_civic_name(&name.0),
};
let cause_is_canonical = match &key.cause {
super::AttitudeCause::Rumour { fact } => {
state.facts.contains_key(fact)
&& matches!(key.toward, super::AttitudeToward::Subject(_))
}
_ => true,
};
toward_is_canonical
&& cause_is_canonical
&& crate::attitude::is_valid_delta(modifier.delta)
&& crate::attitude::is_valid_decay(modifier.decay)
&& modifier.since <= state.now
};
if !state.subjects.contains_key(holder)
|| held.is_empty()
|| !held.iter().all(|(key, modifier)| modifier_is_canonical(key, modifier))
{
return Err(JournalError::Corrupt(
"an attitude row does not name a canonical holder, target, cause, and bounded delta"
.into(),
));
}
}
for (subject_id, carried) in &state.traits {
if !state.subjects.contains_key(subject_id)
|| carried.is_empty()
|| carried.iter().any(|(name, evidence)| {
!super::patch::is_civic_name(&name.0)
|| evidence.is_empty()
|| !evidence.iter().all(|fact| state.facts.contains_key(fact))
})
{
return Err(JournalError::Corrupt(
"a trait row does not name a canonical subject, trait, and fact".into(),
));
}
}
if state
.last_opportunity_at
.iter()
@ -826,6 +880,17 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
"one subject holds two overlapping jurisdictions of one kind".into(),
));
}
let mut declared_keys = BTreeSet::new();
let no_held = BTreeSet::new();
for subject in state.subjects.values() {
if let Some(key) = &subject.import_key
&& super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some()
{
return Err(JournalError::Corrupt(
"subject import key is malformed or held by two subjects".into(),
));
}
}
let mut controller_ids = BTreeSet::new();
for (subject_id, subject) in &state.subjects {
if !super::patch::is_canonical_text(&subject.label) {
@ -1107,9 +1172,11 @@ mod tests {
},
affordances: kernel_speak_grant(),
position: None,
import_key: None,
}),
scale_intent: WorldScaleIntentRef::default(),
grammar: None,
era: None,
};
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
let snapshot = kernel.snapshot().unwrap();
@ -1191,9 +1258,11 @@ mod tests {
},
affordances: kernel_speak_grant(),
position: None,
import_key: None,
}),
scale_intent: WorldScaleIntentRef::default(),
grammar: None,
era: None,
};
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
let snapshot = kernel.snapshot().unwrap();
@ -1222,6 +1291,7 @@ mod tests {
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([speak_entry(&kernel)]),
position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
import_key: None,
}),
],
operations: Vec::new(),
@ -1757,9 +1827,11 @@ mod tests {
controller: NewController::Human { principal: owner },
affordances: kernel_speak_grant(),
position: None,
import_key: None,
}),
scale_intent: WorldScaleIntentRef::default(),
grammar: None,
era: None,
};
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
let mut forged_head = kernel.state.clone();
@ -2967,4 +3039,118 @@ mod custody_tests {
"the chain digest answered for the authority check: {detail}"
);
}
/// Attitude replays exactly: a restart rebuilds the same modifiers, traits
/// and digest from the commits, and a row nobody's command wrote, whether
/// edited, planted, or re-sealed under a digest that agrees with it, stops
/// the history from recovering.
#[test]
fn attitude_replays_exactly_and_a_forged_row_fails_replay() {
use crate::attitude::{AttitudeBasisRef, AttitudeCause, AttitudeKey, AttitudeToward, AttitudeTowardRef, TraitName};
use crate::tests::{auth_principal, creation, operations, owner, speech_world, submit_owner};
use crate::{ComponentOp, Ref};
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let (mut kernel, _) =
WorldKernel::create(&path, creation(CommandId::new(), "Attitude"), &auth_principal(owner()))
.unwrap();
let (speech, _) = speech_world(&mut kernel);
let before = kernel.snapshot().unwrap();
submit_owner(
&mut kernel,
&before,
operations(vec![
ComponentOp::AdjustAttitude {
holder: Ref::Existing(speech.listener),
toward: Ref::Existing(speech.speaker),
delta: -30,
decay: None,
},
ComponentOp::DeclareTrait {
subject: Ref::Existing(speech.speaker),
name: TraitName("outlander".into()),
fact: Ref::Existing(speech.flood),
},
ComponentOp::DeclareAttitude {
holder: Ref::Existing(speech.listener),
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
delta: -10,
basis: AttitudeBasisRef::Prejudice,
decay: None,
},
]),
);
assert!(!kernel.state.attitudes.is_empty() && !kernel.state.traits.is_empty());
let rows = |state: &WorldState| -> Vec<CultCacheEnvelope> {
let mut rows: Vec<CultCacheEnvelope> = kernel
.journal
.commits
.values()
.map(|commit| {
envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap()
})
.collect();
rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap());
rows
};
let (_, recovered, _) = recover(rows(&kernel.state), None).expect("the honest history recovers");
assert_eq!(recovered, kernel.state);
assert_eq!(recovered.state_digest, kernel.state.state_digest);
let planted = AttitudeKey {
toward: AttitudeToward::Subject(speech.listener),
cause: AttitudeCause::Prejudice,
};
let forgeries: Vec<(&str, Box<dyn Fn(&mut WorldState)>)> = vec![
(
"a grievance edited",
Box::new(|state| {
let held = state.attitudes.get_mut(&speech.listener).unwrap();
held.values_mut().next().unwrap().delta = -90;
}),
),
(
"an attitude planted",
Box::new(move |state| {
state.attitudes.entry(speech.speaker).or_default().insert(
planted.clone(),
crate::AttitudeModifier {
delta: -50,
since: state.now,
decay: None,
},
);
}),
),
(
"a grievance erased",
Box::new(|state| {
state.attitudes.clear();
}),
),
(
"a trait erased",
Box::new(|state| {
state.traits.clear();
}),
),
];
for (name, forge) in forgeries {
let mut forged = kernel.state.clone();
forge(&mut forged);
assert!(
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
"{name}: a forged attitude row replayed"
);
// Re-sealed under a digest that agrees with the forgery.
forged.state_digest = crate::state_digest(&forged).unwrap();
assert!(
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
"{name}: a re-sealed forged attitude row replayed"
);
}
}
}

View file

@ -52,7 +52,7 @@ impl Lens {
}
/// What kind of structure the lens reaches for.
pub(crate) fn reaches_for(self) -> &'static str {
pub fn reaches_for(self) -> &'static str {
match self {
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
Lens::Charter => "government, law, offices, selection, succession, redress",

View file

@ -54,14 +54,25 @@
//! ```compile_fail,E0425
//! let _ = ghostlight::fixture_inference_output("prose", "receipt");
//! ```
//!
//! ```compile_fail,E0599
//! fn no_lane_reads_it(port: &ghostlight::ControllerPort) {
//! let _ = port.hierarchy();
//! }
//! ```
mod action;
mod aetheria;
mod attitude;
mod clock;
mod consumer;
mod controllers;
mod cover;
mod elaboration;
mod grammar;
mod hierarchy;
#[cfg(test)]
mod import_key_tests;
mod journal;
mod lens;
mod local_inference;
@ -71,8 +82,13 @@ mod sdk_inference;
mod table;
mod tool_schema;
mod vault;
mod verse;
mod wave;
pub(crate) use action::ActionMismatch;
pub(crate) use attitude::{
AttitudeCause, AttitudeKey, AttitudeModifier, AttitudeToward, TraitName,
};
pub(crate) use clock::Motion;
pub use clock::{FictionalMinutes, TickMinutes};
pub use consumer::{
@ -81,6 +97,7 @@ pub use consumer::{
};
pub use controllers::{
CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels,
ControllerOpenError,
ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork,
ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError,
ControllerWorkWrite,
@ -91,10 +108,19 @@ pub use controllers::{
TracingInferencePort, open_controller_work, open_inference,
};
pub(crate) use cover::{CellId, Constituent, Resolution};
pub use aetheria::{
AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog,
};
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId};
pub use wave::{
Deferral, DeferredNode, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeReport,
NodeTurn, Refusal, RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop,
act_line, acts_since, deferred_nodes, node_label, node_reports, plan_wave, run_frozen_cells,
};
pub use elaboration::{
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery,
EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery,
EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
};
pub use grammar::{
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
@ -118,6 +144,7 @@ pub(crate) use patch::{
PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach,
SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef,
};
pub use patch::ImportKey;
#[cfg(test)]
use patch::{
AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp,
@ -132,9 +159,20 @@ pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding};
pub use table::{
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor,
id_text, id_text_matches, table_view,
handle_for, id_text, id_text_matches, table_view,
};
pub use vault::{
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
VaultEra, VaultEvidenceSource, VaultProfile, VaultSnapshot, production_eras, production_profile, production_vault_names,
};
pub use verse::{
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, Lane, LaneTokens,
NodeSpend, ProviderCallRecord, WaveSpend,
RUN_RECORD_SCHEMA, RecordedKnobs, RecordingInferencePort, RunClaim,
ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint,
TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
call_run_id, run_manual,
};
pub use vault::{VaultError, VaultEvidenceSource};
use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch};
use chrono::{DateTime, Utc};
@ -434,6 +472,20 @@ struct CreateWorld {
/// open-catalog world. Authored here and nowhere else: genesis installs it.
#[serde(default, skip_serializing_if = "Option::is_none")]
grammar: Option<GrammarBinding>,
/// The era the world is pinned to, authored here and nowhere else: no
/// `CommandBody` carries a `WorldEra`, so it is write-once by command
/// shape, as `scale_intent` is.
#[serde(default, skip_serializing_if = "Option::is_none")]
era: Option<WorldEra>,
}
/// The period of its lore a world is set in. Authored at genesis by the
/// consumer that knows what periods its lore has, and never replaced.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct WorldEra {
pub id: String,
pub label: String,
pub description: String,
}
/// Unattributed creation intent. World ingress derives ownership, controller
@ -458,6 +510,9 @@ pub struct CreateWorldIntent {
/// Required. The library holds no default weights; a consumer states the
/// world's flavor or is refused.
pub lens_weights: LensWeights,
/// The era the world is set in, or none. Pinned at genesis and never
/// replaced.
pub era: Option<WorldEra>,
}
/// One jurisdiction root as ingress states it. The handle is a string here and
@ -718,6 +773,10 @@ pub enum CommandBody {
struct SubjectState {
label: String,
kind: SubjectKind,
/// Written only when a subject declaration is resolved; absent from a
/// subject nobody imported, so its digests are unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
import_key: Option<ImportKey>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
@ -842,6 +901,10 @@ struct WorldState {
/// grammars existed.
#[serde(default, skip_serializing_if = "Option::is_none")]
grammar: Option<GrammarBinding>,
/// Pinned by genesis and never written again; absent from a world with no
/// era, whose state and digests are what they were before eras existed.
#[serde(default, skip_serializing_if = "Option::is_none")]
era: Option<WorldEra>,
draft_approvals: BTreeSet<PrincipalId>,
subjects: BTreeMap<SubjectId, SubjectState>,
entities: BTreeMap<EntityId, EntityRecord>,
@ -887,6 +950,19 @@ struct WorldState {
/// Pressure *on* each subject, keyed target-major then source. Never empty
/// for a present key; no stored zero magnitude.
pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>,
/// How each subject regards others: sourced modifiers, never a stored
/// opinion (`attitude::opinion` derives it). Never empty for a present key;
/// no stored zero delta. Outside every scope digest: attitude constrains no
/// precondition. Absent from a world that has none, so such a world's state
/// and digests are what they were before attitude existed.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
attitudes: BTreeMap<SubjectId, BTreeMap<AttitudeKey, AttitudeModifier>>,
/// The facts the world declares as evidence that a subject carries a trait:
/// what a prejudice reads, since a trait modifier applies to a subject only
/// while its holder knows one of these. Never empty for a present key.
/// Absent when empty, for the same reason as `attitudes`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
traits: BTreeMap<SubjectId, BTreeMap<TraitName, BTreeSet<EntityId>>>,
/// When each subject was last given a decision opportunity it consumed.
/// Absence means never. The debt term of the attention order and nothing
/// else.
@ -1007,6 +1083,8 @@ pub struct SubjectSnapshot {
pub id: SubjectId,
pub label: String,
pub kind: SubjectKind,
/// The Aetheria record this subject was imported from, if it was.
pub import_key: Option<ImportKey>,
/// Absent for an externally controlled mirror, which has no controller and
/// no turn. Every reader fails closed on `None`; none gets a default.
pub(crate) controller_id: Option<ControllerId>,
@ -1048,6 +1126,11 @@ pub struct SubjectSnapshot {
/// subject's state, and the actor already sees the commitment that produced
/// it.
pub(crate) pressures: Vec<PressureSnapshot>,
/// How this subject regards each subject it has an opinion of, derived by
/// `attitude::opinion` at snapshot time: never stored, so there is one
/// answer for the Dungeon Master's table, a Persona's own view, and the
/// narrator. View-only, covered by no digest of its own.
pub(crate) opinions: Vec<OpinionSnapshot>,
/// This subject's own dependencies, lowered from `components.dependencies`
/// (private to this module) so the play table's omniscient view can print
/// what a `release` may name without reaching into `ScopeComponents`
@ -1087,6 +1170,17 @@ pub(crate) struct PressureSnapshot {
pub(crate) magnitude: PressureMagnitude,
}
/// One subject's derived regard for another, with its strongest causes. A trait
/// prejudice appears only once the holder knows the subject carries the trait.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct OpinionSnapshot {
pub(crate) toward: SubjectId,
/// Clamped to `-MAX_ATTITUDE..=MAX_ATTITUDE`.
pub(crate) total: i32,
/// At most `OPINION_CAUSES_SHOWN`, strongest first.
pub(crate) causes: Vec<attitude::OpinionCause>,
}
/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a
/// receipt is non-fictional provenance and never enters a subject-facing
/// surface, so a subject learns *that* a fact is canonical and never which
@ -1214,6 +1308,8 @@ pub struct WorldSnapshot {
pub owner: PrincipalId,
pub title: String,
pub brief: String,
/// The era the world was pinned to at genesis; none for a world with no era.
pub era: Option<WorldEra>,
/// The bound grammar's identity; none for a world with an open catalog.
pub grammar: Option<GrammarIdentity>,
pub draft_approvals: BTreeSet<PrincipalId>,
@ -1247,6 +1343,63 @@ pub struct WorldSnapshot {
pub last_commit_digest: Option<String>,
}
impl WorldSnapshot {
/// The place a subject stands in, for the owner's own surfaces; no
/// subject-facing lane reads this.
pub fn place_of(&self, subject: SubjectId) -> Option<EntityId> {
self.subjects.iter().find(|candidate| candidate.id == subject)?.position
}
/// The label of the place a subject stands in, for the owner's own
/// surfaces and tests; no subject-facing lane reads this.
pub fn standing_place(&self, subject: SubjectId) -> Option<&str> {
let position = self.place_of(subject)?;
self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str())
}
/// The live subjects with a controller other than a human's that stand in
/// the same place as `subject`, ascending by id; `subject` itself is never
/// among them. For the owner's own surfaces (the Dungeon's room-level
/// reaction derives its audience here): no controller lane reads it, since
/// one subject must not learn who else stands beside it from a list the
/// kernel built for the table.
pub fn co_located(&self, subject: SubjectId) -> Vec<SubjectId> {
let Some(position) = self
.subjects
.iter()
.find(|candidate| candidate.id == subject)
.and_then(|candidate| candidate.position)
else {
return Vec::new();
};
let mut present: Vec<SubjectId> = self
.subjects
.iter()
.filter(|other| {
other.id != subject
&& !other.retired
&& other.position == Some(position)
&& matches!(other.controller_mode, Some(mode) if mode != ControllerMode::Human)
})
.map(|other| other.id)
.collect();
present.sort();
present
}
/// What every lane reads as the world's guidance: the era line, then the
/// owner's brief verbatim, either omitted when empty. Derived on every
/// read; no prompt reads `brief` directly.
pub fn guidance(&self) -> String {
let era = self
.era
.as_ref()
.map(|era| format!("Era: {}. {}", era.label, era.description));
let brief = (!self.brief.is_empty()).then(|| self.brief.clone());
[era, brief].into_iter().flatten().collect::<Vec<_>>().join("\n")
}
}
/// One committed act as the human operator's story feed reads it. It is the
/// operator surface, not a perception surface: no subject-facing lane receives
/// it, and `SelectedDecision` never sees an event log at all.
@ -1257,6 +1410,21 @@ pub struct OperatorEvent {
pub speaker_label: String,
pub speech: Option<Statement>,
pub display: Option<Statement>,
/// The affordance kind the act exercised.
pub verb: String,
/// How the world's grammar renders that verb; none in a world with no
/// grammar.
pub render_path: Option<RenderPath>,
/// What the act bound each of the verb's roles to, in the invocation's
/// order.
pub roles: Vec<BoundRole>,
}
/// One role an act bound, with the label of what it was bound to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoundRole {
pub role: String,
pub target: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -1440,6 +1608,13 @@ fn prepare_creation(
}
let title = normalize_title(&input.title)?;
let brief = input.brief.trim().to_owned();
if input
.era
.as_ref()
.is_some_and(|era| [&era.id, &era.label, &era.description].iter().any(|text| text.trim().is_empty()))
{
return Err(KernelError::Invariant("a world era states an id, a label and a description".into()));
}
// The world's own identity is not world structure, and it feeds every
// derived ID, so it is minted before resolution rather than by it.
let world_id = WorldId::issue();
@ -1547,7 +1722,43 @@ impl WorldKernel {
/// no consumer may read in full would be a loaded gun with a comment on it.
fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> {
self.journal.ensure_healthy()?;
operator_log(&self.state)
// An event records what the world did; the invocation, which names the
// bound roles, lives on the commit that produced it.
let invocations: BTreeMap<EventId, &DecisionInvocation> = self
.journal
.commits()
.filter_map(|commit| match &commit.effect {
WorldEffect::DecisionExercised {
invocation, event, ..
} => Some((event.id, invocation)),
_ => None,
})
.collect();
operator_log(&self.state, &invocations)
}
/// The tick driver's opportunity list, in the same order a snapshot
/// carries it. Separate from `snapshot` for the reason `agency_graph` is:
/// only the tick driver reads it.
fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> {
self.journal.ensure_healthy()?;
Ok(order_opportunities(
&self.state,
derive_opportunities(&self.state)?,
))
}
/// How many clock advances the world has committed: the next tick's
/// ordinal, held by the world and read from its journal. Separate from
/// `snapshot` for the reason `opportunities` is: only the tick driver
/// reads it.
fn clock_advances(&self) -> Result<u64, KernelError> {
self.journal.ensure_healthy()?;
Ok(self
.journal
.commits()
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
.count() as u64)
}
/// The scheduler's adjacency projection. Separate from `snapshot` for the
@ -1559,6 +1770,14 @@ impl WorldKernel {
Ok(agency_graph(&self.state))
}
/// The gestalt hierarchy. Separate from `snapshot` for the reason
/// `agency_graph` is: it is wider than any subject view, so a field on
/// `WorldSnapshot` would be reachable from every prompt builder.
fn hierarchy(&self) -> Result<Hierarchy, KernelError> {
self.journal.ensure_healthy()?;
Ok(hierarchy::derive_hierarchy(&self.state))
}
fn submit(
&mut self,
command: CommandEnvelope,
@ -1935,6 +2154,7 @@ impl WorldState {
title,
brief: String::new(),
grammar,
era: None,
draft_approvals: BTreeSet::new(),
subjects: BTreeMap::new(),
entities: BTreeMap::new(),
@ -1951,6 +2171,8 @@ impl WorldState {
commitments: BTreeMap::new(),
persona_material: BTreeMap::new(),
pressures: BTreeMap::new(),
attitudes: BTreeMap::new(),
traits: BTreeMap::new(),
last_opportunity_at: BTreeMap::new(),
now: FictionalMinutes::default(),
scale_intent: WorldScaleIntent::default(),
@ -1994,6 +2216,7 @@ impl WorldState {
// equality replace a field-by-field binding zip.
let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone());
state.brief = brief.clone();
state.era = command.era.clone();
let expected = patch::resolve_patch(
&state,
command.id,
@ -2123,6 +2346,21 @@ fn admit_resolved(
));
}
}
// The subjects map's only writer holds the same injectivity the resolver
// checks, decided by the same function.
{
let held = patch::held_import_keys(state.subjects.values());
let mut declared = BTreeSet::new();
for subject in &resolved.subjects {
if let Some(key) = &subject.subject.import_key
&& patch::import_key_fault(key, &held, &mut declared).is_some()
{
return Err(KernelError::Invariant(
"admitted subject's import key is malformed, held or repeated".into(),
));
}
}
}
for subject in &resolved.subjects {
let scope = DecisionScope {
subject_id: subject.subject_id,
@ -3133,6 +3371,50 @@ fn apply_operation(
}
set_pressure(state, *target, *source, 0);
}
ResolvedOp::AdjustAttitude {
holder,
key,
delta,
decay,
} => {
let regards_live = match &key.toward {
AttitudeToward::Subject(target) => state.subjects.contains_key(target),
AttitudeToward::Trait(name) => patch::is_civic_name(&name.0),
};
let rests_on_known = match &key.cause {
AttitudeCause::Rumour { fact } => state.facts.contains_key(fact),
_ => true,
};
if !state.subjects.contains_key(holder)
|| !regards_live
|| !rests_on_known
|| !attitude::is_valid_delta(*delta)
|| !attitude::is_valid_decay(*decay)
|| key.toward == AttitudeToward::Subject(*holder)
{
return Err(unknown());
}
attitude::adjust(state, *holder, key.clone(), *delta, *decay);
}
ResolvedOp::DeclareTrait {
subject,
name,
fact,
} => {
if !state.subjects.contains_key(subject)
|| !state.facts.contains_key(fact)
|| !patch::is_civic_name(&name.0)
{
return Err(unknown());
}
state
.traits
.entry(*subject)
.or_default()
.entry(name.clone())
.or_default()
.insert(*fact);
}
ResolvedOp::Retire { subject } => {
let scope = DecisionScope {
subject_id: *subject,
@ -3707,7 +3989,10 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent
/// The human operator's story feed, derived from the causal record. The events
/// log is not a perception surface: `knowledge` is the sole answer to what a
/// subject may act on and what its projection may contain.
fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
fn operator_log(
state: &WorldState,
invocations: &BTreeMap<EventId, &DecisionInvocation>,
) -> Result<Vec<OperatorEvent>, KernelError> {
state
.events
.iter()
@ -3716,6 +4001,30 @@ fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
.subjects
.get(&event.scope.subject_id)
.ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?;
let invocation = invocations.get(&event.id).ok_or_else(|| {
KernelError::Invariant("event has no committed invocation".into())
})?;
let entry = state
.affordance_catalog
.get(&event.affordance)
.ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?;
let roles = invocation
.bindings
.iter()
.map(|binding| {
let label = match binding.target {
Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()),
Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()),
Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()),
};
label
.map(|target| BoundRole {
role: binding.role.0.clone(),
target,
})
.ok_or_else(|| KernelError::Invariant("event binds no live referent".into()))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(OperatorEvent {
revision: event.revision,
speaker: event.scope.subject_id,
@ -3728,6 +4037,13 @@ fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
.display
.and_then(|fact| state.facts.get(&fact))
.map(|record| record.statement.clone()),
verb: entry.kind.0.clone(),
render_path: state
.grammar
.as_ref()
.and_then(|grammar| grammar.verb(&entry.kind.0))
.map(|verb| verb.render_path),
roles,
})
})
.collect()
@ -4006,6 +4322,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
id: *subject_id,
label: subject.label.clone(),
kind: subject.kind,
import_key: subject.import_key.clone(),
controller_id: controller.id(),
controller_mode: controller.mode(),
human_controller: controller.human_principal().cloned(),
@ -4042,6 +4359,17 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
magnitude: *magnitude,
})
.collect(),
opinions: attitude::opinions_held(state, *subject_id)
.into_iter()
.map(|(toward, mut held)| {
held.causes.truncate(attitude::OPINION_CAUSES_SHOWN);
OpinionSnapshot {
toward,
total: held.total,
causes: held.causes,
}
})
.collect(),
qualified: qualifies(state, *subject_id),
last_acted_at: last_acted_at.get(subject_id).copied(),
})
@ -4121,6 +4449,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
owner: state.owner.clone(),
title: state.title.clone(),
brief: state.brief.clone(),
era: state.era.clone(),
grammar: state.grammar.as_ref().map(GrammarBinding::identity),
draft_approvals: state.draft_approvals.clone(),
required_approvers: required_approvers(state),
@ -5144,6 +5473,16 @@ fn operation_ground(
}
(subjects, places(named), routes)
}
// An attitude is the holder's own state about another subject, so both
// are ground; a trait names none.
ResolvedOp::AdjustAttitude { holder, key, .. } => {
let mut subjects = vec![*holder];
if let AttitudeToward::Subject(target) = &key.toward {
subjects.push(*target);
}
(subjects, Vec::new(), Vec::new())
}
ResolvedOp::DeclareTrait { subject, .. } => (vec![*subject], Vec::new(), Vec::new()),
// Confinement never reaches these through the ordinary ground check:
// `confine_to_ground` refuses `Retire`, `GrantAffordance`, and
// `RevokeAffordance` unconditionally for every confined author before
@ -5486,6 +5825,7 @@ mod tests {
// The fixture world is one room. Co-located speech needs a place to
// fill, so every fixture subject stands in the commons.
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
import_key: None,
})
}
@ -5588,12 +5928,14 @@ mod tests {
.chain(std::iter::once(Ref::Draft(DraftHandle::new("convene"))))
.collect(),
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
import_key: None,
}),
],
},
scale_intent: WorldScaleIntentRef::default(),
lens_weights: stock_weights(),
grammar: None,
era: None,
}
}
@ -5738,6 +6080,7 @@ mod tests {
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Draft(DraftHandle::new("yard"))),
import_key: None,
}),
],
// A route that should start closed is declared and closed in one
@ -5843,6 +6186,7 @@ mod tests {
}))
.collect(),
position: Some(Ref::Existing(place)),
import_key: None,
})
}
@ -6363,6 +6707,7 @@ mod tests {
controller: NewController::OperationalAgent,
affordances: civic_grants(handles, &speak),
position: Some(place),
import_key: None,
})
};
let declarations = civic_affordances()
@ -6419,6 +6764,7 @@ mod tests {
&speak,
),
position: Some(Ref::Draft(DraftHandle::new("hall"))),
import_key: None,
}),
Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new("reeve"),
@ -6430,6 +6776,7 @@ mod tests {
&speak,
),
position: Some(Ref::Draft(DraftHandle::new("chamber"))),
import_key: None,
}),
person(
"farmer",
@ -6453,6 +6800,7 @@ mod tests {
controller: NewController::NarrativePersona,
affordances: civic_grants(&["levy", "petition"], &speak),
position: None,
import_key: None,
}),
])
.collect();
@ -6616,6 +6964,7 @@ mod tests {
Ref::Draft(DraftHandle::new("recant")),
]),
position: place.map(|place| Ref::Draft(DraftHandle::new(place))),
import_key: None,
})
};
submit_owner(
@ -7884,6 +8233,7 @@ mod tests {
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([speak.clone()]),
position: Some(Ref::Existing(topology.road)),
import_key: None,
}),
],
operations: Vec::new(),
@ -8902,6 +9252,7 @@ mod custody_tests {
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([speak.clone()]),
position: Some(Ref::Existing(topology.yard)),
import_key: None,
}),
],
operations: vec![ComponentOp::Admit {
@ -9561,6 +9912,7 @@ mod custody_tests {
controller: NewController::OperationalAgent,
affordances: BTreeSet::from([speak.clone()]),
position: Some(Ref::Existing(topology.yard)),
import_key: None,
}),
],
operations: vec![admit(u64::MAX), admit(1)],
@ -11487,7 +11839,7 @@ mod soul_knowledge_tests {
// Nobody holds it.
assert!(kernel.state.knowledge.is_empty());
// The operator reads it anyway, with the speaker resolved by label.
let log = operator_log(&kernel.state).unwrap();
let log = kernel.operator_log().unwrap();
assert_eq!(
log,
vec![OperatorEvent {
@ -11496,6 +11848,9 @@ mod soul_knowledge_tests {
speaker_label: "The Yard Bystander".into(),
speech: Some(Statement::new(text).unwrap()),
display: None,
verb: "speak".into(),
render_path: None,
roles: Vec::new(),
}]
);
// And no subject snapshot carries it.
@ -11553,6 +11908,7 @@ mod witness_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]),
position: Some(Ref::Draft(DraftHandle::new(place))),
import_key: None,
})
}
@ -12666,6 +13022,7 @@ mod witness_tests {
// Every non-mirror subject must hold one.
affordances: BTreeSet::from([Ref::Existing(beacon)]),
position: position.map(Ref::Existing),
import_key: None,
}),
],
operations: vec![witness(
@ -12979,6 +13336,8 @@ mod clock_tests {
use super::*;
use std::path::Path;
mod attitude_tests;
/// The canonical IDs of the clock fixture: a hall containing a yard, a
/// dead end reached by exactly one route, three subjects, a resource, and
/// one commitment of each kind.
@ -13030,6 +13389,7 @@ mod clock_tests {
Ref::Draft(DraftHandle::new("threaten")),
]),
position: Some(Ref::Draft(DraftHandle::new(place))),
import_key: None,
})
};
let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle));
@ -15106,6 +15466,53 @@ mod clock_tests {
assert_eq!(replayed.state.state_digest, created.state_digest);
}
fn late_sol() -> WorldEra {
WorldEra { id: "late-sol".into(), label: "Late Sol".into(), description: "The old order fails.".into() }
}
/// Genesis pins the era, replay restores it, and the only command that
/// can touch a world's flavor afterward leaves it alone: no `CommandBody`
/// carries a `WorldEra`.
#[test]
fn genesis_pins_the_era_and_nothing_replaces_it() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let mut input = creation(CommandId::new(), "Pinned");
input.era = Some(late_sol());
let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap();
let created = kernel.snapshot().unwrap();
assert_eq!(created.era, Some(late_sol()));
let world_id = created.world_id;
drop(kernel);
let replayed = WorldKernel::open(&path, world_id).unwrap();
assert_eq!(replayed.snapshot().unwrap().era, Some(late_sol()));
assert_eq!(replayed.state.state_digest, created.state_digest);
let mut blank = creation(CommandId::new(), "Blank Era");
blank.era = Some(WorldEra { description: " ".into(), ..late_sol() });
let refused = WorldKernel::create(&directory.path().join("blank.cc"), blank, &auth_principal(owner()));
assert!(matches!(refused, Err(KernelError::Invariant(_))));
}
/// Every lane reads this string: era first, then the brief verbatim,
/// either omitted when empty; nothing at all when both are.
#[test]
fn guidance_is_the_era_then_the_brief_and_empty_when_neither() {
let directory = tempfile::tempdir().unwrap();
let mut snapshots = Vec::new();
for (name, era, brief) in [("a", Some(late_sol()), "Speak plainly."), ("b", Some(late_sol()), ""), ("c", None, "Speak plainly."), ("d", None, "")] {
let mut input = creation(CommandId::new(), name);
input.era = era;
input.brief = brief.into();
let (kernel, _) = WorldKernel::create(&directory.path().join(format!("{name}.cc")), input, &auth_principal(owner())).unwrap();
snapshots.push(kernel.snapshot().unwrap().guidance());
}
assert_eq!(
snapshots,
["Era: Late Sol. The old order fails.\nSpeak plainly.", "Era: Late Sol. The old order fails.", "Speak plainly.", ""]
);
}
#[test]
fn a_genesis_lens_set_that_never_draws_is_refused() {
let directory = tempfile::tempdir().unwrap();
@ -17083,6 +17490,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
}),
],
operations: Vec::new(),
@ -17149,6 +17557,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
}),
],
operations: Vec::new(),
@ -17226,6 +17635,7 @@ mod clock_tests {
},
affordances: BTreeSet::new(),
position: Some(Ref::Existing(commons)),
import_key: None,
})],
operations: Vec::new(),
evidence: Vec::new(),
@ -17319,6 +17729,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
}),
],
operations: vec![ComponentOp::Mint {
@ -17561,6 +17972,7 @@ mod clock_tests {
// the boundary its own answer claims: an occupied
// place is no longer unelaborated.
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
})],
operations: Vec::new(),
evidence: Vec::new(),
@ -17739,6 +18151,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
})],
operations: vec![ComponentOp::Retire {
subject: Ref::Draft(DraftHandle::new("stray")),
@ -17848,6 +18261,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(commons)),
import_key: None,
}),
],
operations: vec![ComponentOp::GrantAffordance {
@ -18062,6 +18476,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
})],
operations: vec![ComponentOp::GrantAffordance {
subject: Ref::Draft(DraftHandle::new("stray")),
@ -18480,6 +18895,7 @@ mod clock_tests {
Ref::Existing(clockwork.threaten),
]),
position: Some(Ref::Existing(clockwork.dead_end)),
import_key: None,
})],
operations: vec![ComponentOp::RevokeAffordance {
subject: Ref::Draft(DraftHandle::new("stray")),
@ -18928,6 +19344,7 @@ mod clock_tests {
controller: NewController::NarrativePersona,
affordances: BTreeSet::from([speak.clone()]),
position: None,
import_key: None,
}),
Declaration::Channel(ChannelDeclaration {
handle: DraftHandle::new("wire"),

View file

@ -17,7 +17,7 @@ use super::controllers::{
call_id_is_valid, tool_name_is_valid, unix_ms,
};
use async_trait::async_trait;
use codex_connector::CodexInputItem;
use model_connector::InputItem;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
@ -334,9 +334,9 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result<Value, In
let mut messages = vec![json!({"role": "system", "content": request.instructions})];
for item in &request.input {
messages.push(match item {
CodexInputItem::UserText { text } => json!({"role": "user", "content": text}),
CodexInputItem::AssistantText { text } => json!({"role": "assistant", "content": text}),
CodexInputItem::ToolCall {
InputItem::UserText { text } => json!({"role": "user", "content": text}),
InputItem::AssistantText { text } => json!({"role": "assistant", "content": text}),
InputItem::ToolCall {
call_id,
name,
arguments,
@ -349,11 +349,18 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result<Value, In
"function": {"name": name, "arguments": arguments},
}],
}),
CodexInputItem::ToolResult { call_id, output } => json!({
InputItem::ToolResult { call_id, output } => json!({
"role": "tool",
"tool_call_id": call_id,
"content": output,
}),
// Ghostlight replays no provider state, and an OpenAI-compatible
// server has no place for one.
InputItem::ReasoningState { .. } => {
return Err(InferenceFault::integrity_violation(
"a local request carried provider reasoning state",
));
}
});
}
let mut tools = Vec::with_capacity(request.tools.len());
@ -379,9 +386,7 @@ fn lower_request(prepared: &PreparedInference, prefix: &str) -> Result<Value, In
body["tools"] = json!(tools);
body["parallel_tool_calls"] = json!(request.parallel_tool_calls);
}
if let Some(max_tokens) = request.max_output_tokens {
body["max_tokens"] = json!(max_tokens);
}
body["max_tokens"] = json!(request.max_output_tokens);
Ok(body)
}
@ -570,7 +575,7 @@ mod tests {
use crate::patch::{RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, patch_tools};
use crate::sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, RoutedInferencePort, SdkBinding};
use crate::CommandId;
use codex_connector::CodexToolDefinition;
use model_connector::ToolDefinition;
use std::collections::VecDeque;
use std::sync::{Mutex, OnceLock};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@ -822,7 +827,7 @@ mod tests {
InferencePurpose::Elaboration,
TEST_MODEL,
"Author the shortfall.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: prompt.into(),
}],
patch_tools(),
@ -889,18 +894,18 @@ mod tests {
TEST_MODEL,
"Only reply once every item is accounted for.",
vec![
CodexInputItem::UserText {
InputItem::UserText {
text: "Open the gate.".into(),
},
CodexInputItem::AssistantText {
InputItem::AssistantText {
text: "Checking the ledger.".into(),
},
CodexInputItem::ToolCall {
InputItem::ToolCall {
call_id: "call-9".into(),
name: RECORD_GAP_PATCH_TOOL.into(),
arguments: r#"{"detail":"no ledger entry"}"#.into(),
},
CodexInputItem::ToolResult {
InputItem::ToolResult {
call_id: "call-9".into(),
output: "gap recorded".into(),
},
@ -1005,7 +1010,7 @@ mod tests {
InferencePurpose::Elaboration,
TEST_MODEL,
"Author the shortfall.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Author the shortfall.".into(),
}],
patch_tools(),
@ -1083,10 +1088,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1119,10 +1124,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1194,10 +1199,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1232,10 +1237,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1400,7 +1405,7 @@ mod tests {
InferencePurpose::Elaboration,
TEST_MODEL,
"Author the shortfall.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Author the shortfall.".into(),
}],
patch_tools(),
@ -1428,10 +1433,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1460,7 +1465,7 @@ mod tests {
InferencePurpose::Elaboration,
TEST_MODEL,
"Author the shortfall.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Author the shortfall.".into(),
}],
patch_tools(),
@ -1493,10 +1498,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1526,10 +1531,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1558,10 +1563,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1588,10 +1593,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1624,10 +1629,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Say something true.".into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1996,7 +2001,7 @@ mod tests {
#[test]
fn hosted_binding_refuses_a_key_shape_that_cannot_ride_a_header() {
let directory = tempfile::tempdir().unwrap();
let cases: [(&str, &[u8]); 8] = [
let cases: [(&str, &[u8]); 9] = [
("interior newline", b"keycanary\nsecondline"),
("interior carriage return", b"keycanary\rsecondline"),
("interior tab", b"keycanary\tsecondline"),
@ -2005,6 +2010,7 @@ mod tests {
("trailing space before the newline", b"keycanary \n"),
("non-ascii", "keycanary-\u{e9}".as_bytes()),
("leading newline", b"\nkeycanary"),
("interior DEL", b"keycanary\x7fsecondline"),
];
for (label, content) in cases {
let path = write_key_file(&directory, content);
@ -2053,8 +2059,8 @@ mod tests {
InferencePurpose::Persona,
"hosted/deepseek-chat",
"Respond only in natural prose.",
vec![CodexInputItem::UserText { text: "Say something true.".into() }],
Vec::<CodexToolDefinition>::new(),
vec![InputItem::UserText { text: "Say something true.".into() }],
Vec::<ToolDefinition>::new(),
RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false },
)
.expect("the request builds");

View file

@ -1,13 +1,15 @@
use super::{
AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
AgencyGraph, AuthenticatedCaller, Hierarchy, CallerId, CommandBody, CommandEnvelope, CommandId,
ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation,
DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey,
KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId,
Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
EntityId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
WorldKernel, WorldPatch, WorldPhase, WorldScaleIntentRef, WorldSnapshot, journal,
patch::kernel_speak_grant, prepare_creation,
verse::{CreateVerseWorldIntent, VerseGenesisError},
};
use crate::VerifiedPrincipalEvidence;
use crate::patch::{AccessKind, ComponentOp, Cost, RouteDeclaration};
use crate::{SubjectId, VerifiedPrincipalEvidence};
use chrono::Utc;
use std::path::Path;
use thiserror::Error;
@ -18,6 +20,21 @@ use tokio::task::JoinHandle;
/// other. A world that wants more declares them through the patch lane.
const GENESIS_PLACE: &str = "commons";
/// The commons every genesis declares, the one room its first subjects share.
pub(crate) fn commons_declaration() -> Declaration {
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new(GENESIS_PLACE),
label: "The Commons".into(),
kind: EntityKind::Place,
container: None,
})
}
/// Where a genesis subject stands.
pub(crate) fn commons_ref() -> Ref<EntityId> {
Ref::Draft(DraftHandle::new(GENESIS_PLACE))
}
const REQUEST_CAPACITY: usize = 32;
#[derive(Clone, Debug)]
@ -66,6 +83,21 @@ enum Request {
AgencyGraph {
reply: oneshot::Sender<Result<AgencyGraph, KernelError>>,
},
/// The gestalt hierarchy, derived from world state. Separate from
/// `Snapshot` as `AgencyGraph` is: only the tick driver may hold it.
Hierarchy {
reply: oneshot::Sender<Result<Hierarchy, KernelError>>,
},
/// The tick driver's opportunity list. Separate from `Snapshot` so the
/// list a cover is derived from has one door, held by the driver.
Opportunities {
reply: oneshot::Sender<Result<Vec<DecisionOpportunity>, KernelError>>,
},
/// The tick ordinal's one door: how many clock advances the world has
/// committed. Held by the tick driver, as `Opportunities` is.
ClockAdvances {
reply: oneshot::Sender<Result<u64, KernelError>>,
},
ControllerReceipt {
command_id: CommandId,
opportunity: super::DecisionOpportunity,
@ -120,7 +152,8 @@ impl WorldMailbox {
kind,
controller,
affordances: kernel_speak_grant(),
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
position: Some(commons_ref()),
import_key: None,
})
};
// Roots stand beside the commons, not inside it: a root contained by
@ -129,12 +162,7 @@ impl WorldMailbox {
// jurisdiction's population target. The owner subject lands in
// `Uncovered`, visible and reducing nothing.
let mut declarations = vec![
Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new(GENESIS_PLACE),
label: "The Commons".into(),
kind: EntityKind::Place,
container: None,
}),
commons_declaration(),
declare(
"first-person",
input.human_subject_label,
@ -190,6 +218,7 @@ impl WorldMailbox {
scale_intent,
lens_weights: input.lens_weights,
grammar: None,
era: input.era,
},
AuthenticatedCaller::verified_principal(principal_id),
)
@ -218,6 +247,20 @@ impl WorldMailbox {
.map_err(mailbox_outcome)
}
/// Creates the canonical Aetheria verse world through the same
/// authenticated creation `create` uses.
pub async fn create_verse(
&self,
intent: CreateVerseWorldIntent,
principal: &VerifiedPrincipalEvidence,
) -> Result<CreationReceipt, VerseGenesisError> {
let principal_id = PrincipalId::new(principal.account_subject_hash());
let input = intent.lower(principal_id.clone())?;
Ok(self
.create_authenticated(input, AuthenticatedCaller::verified_principal(principal_id))
.await?)
}
/// A wall-clock read at the boundary a request crosses into the mailbox is
/// ingress, not reduce: the reducer stays deterministic over its journal,
/// and this is the one place a caller's own claim of continued authority
@ -460,6 +503,54 @@ impl WorldMailbox {
.map_err(MailboxError::Kernel)
}
/// The tick driver's projection of the gestalt hierarchy, derived afresh
/// from the world on every call. It is on `WorldMailbox` and on neither
/// `ControllerPort` nor `ElaborationPort`, as `agency_graph` is: the tree
/// is wider than any subject view.
pub async fn hierarchy(&self) -> Result<Hierarchy, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::Hierarchy { reply })
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
/// The tick driver's opportunity list, in snapshot order. It is on
/// `WorldMailbox` and on no controller port, as `agency_graph` is.
pub async fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::Opportunities { reply })
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
/// The tick driver's ordinal: how many clock advances the world has
/// committed. It is on `WorldMailbox` and on no controller port, as
/// `opportunities` is.
pub async fn clock_advances(&self) -> Result<u64, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::ClockAdvances { reply })
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
pub async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
@ -649,6 +740,98 @@ impl SeedPort {
}
}
impl SeedPort {
/// Stands the world's first person among people. Genesis puts the human at
/// the commons, which a seed never populates, so the first turn would open
/// in an empty room. This moves the human to the most populated place the
/// seed declared (ties to the lowest label, then id) through one declared
/// route that the same patch closes behind them, and answers where they
/// now stand, or `None` when there is nothing to change: no seeded place
/// has anyone in it, or the human already stands in one. Draft only, like
/// every seed submission.
pub async fn stand_first_person_among_people(
&self,
command_id: CommandId,
world_id: WorldId,
) -> Result<Option<String>, MailboxError> {
let snapshot = self.mailbox.snapshot().await?;
let Some(spawn) = first_person_spawn(&snapshot) else {
return Ok(None);
};
let route = Ref::Draft(DraftHandle::new("spawn-route"));
let patch = WorldPatch {
declarations: vec![Declaration::Route(RouteDeclaration {
handle: DraftHandle::new("spawn-route"),
label: "the way in".into(),
from: Ref::Existing(spawn.from),
to: Ref::Existing(spawn.to),
access: AccessKind::Public,
cost: Cost(1),
})],
operations: vec![
ComponentOp::Relocate {
subject: Ref::Existing(spawn.subject),
via: route.clone(),
},
ComponentOp::CloseRoute { route },
],
evidence: Vec::new(),
};
self.submit_seed(command_id, world_id, patch).await?;
Ok(Some(spawn.label))
}
}
struct FirstPersonSpawn {
subject: SubjectId,
from: EntityId,
to: EntityId,
label: String,
}
/// The human's move, read from the snapshot alone: to the seeded place (one
/// with a container; the commons and the jurisdiction roots have none) holding
/// the most other subjects.
fn first_person_spawn(snapshot: &WorldSnapshot) -> Option<FirstPersonSpawn> {
let human = snapshot
.subjects
.iter()
.find(|subject| subject.controller_mode == Some(crate::ControllerMode::Human) && !subject.retired)?;
let from = human.position?;
let seeded = |id: EntityId| {
snapshot
.places
.iter()
.any(|place| place.id == id && place.container.is_some())
};
if seeded(from) {
return None;
}
let population = |place: &crate::PlaceSnapshot| {
snapshot
.subjects
.iter()
.filter(|other| other.id != human.id && !other.retired && other.position == Some(place.id))
.count()
};
let (count, place) = snapshot
.places
.iter()
.filter(|place| place.container.is_some())
.map(|place| (population(place), place))
.min_by(|(a, place_a), (b, place_b)| {
b.cmp(a)
.then_with(|| place_a.label.cmp(&place_b.label))
.then_with(|| place_a.id.cmp(&place_b.id))
})?;
(count > 0).then(|| FirstPersonSpawn {
subject: human.id,
from,
to: place.id,
label: place.label.clone(),
})
}
/// The play table's one door. Minted only by Dungeon, which constructs one
/// `PlayPort` in its `AppState`; exclusivity is that single construction site,
/// pinned by a negative grep, exactly as every other system capability's is.
@ -929,6 +1112,45 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
return;
}
}
Request::Hierarchy { reply } => {
let result = match &owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.hierarchy(),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::Opportunities { reply } => {
let result = match &owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.opportunities(),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::ClockAdvances { reply } => {
let result = match &owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.clock_advances(),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::ControllerReceipt {
command_id,
opportunity,
@ -990,6 +1212,7 @@ mod tests {
CreateWorld {
lens_weights: crate::tests::stock_weights(),
grammar: None,
era: None,
id,
owner: PrincipalId::new("owner"),
title: title.into(),
@ -1011,6 +1234,7 @@ mod tests {
},
affordances: kernel_speak_grant(),
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
import_key: None,
}),
],
operations: Vec::new(),
@ -1059,6 +1283,22 @@ mod tests {
}
}
#[tokio::test]
async fn hierarchy_is_derived_from_the_world_through_the_mailbox() {
let (_directory, _path, mailbox, task, _authenticated, _input, _receipt) = fixture().await;
let hierarchy = mailbox.hierarchy().await.unwrap();
let snapshot = mailbox.snapshot().await.unwrap();
// The fixture world holds one Human operator in one room: placed under
// that room's node, no voice anywhere.
assert_eq!(hierarchy.home.len(), 1);
assert!(hierarchy.nodes.values().all(|node| node.voice.is_none() && node.loose.is_empty()));
assert_eq!(hierarchy.nodes.len(), 2);
assert_eq!(hierarchy, mailbox.hierarchy().await.unwrap());
assert_eq!(snapshot.subjects.len(), 1);
drop(mailbox);
task.await.unwrap();
}
#[tokio::test]
async fn empty_owner_rejects_world_operations_then_accepts_creation() {
let directory = tempfile::tempdir().unwrap();
@ -1398,6 +1638,7 @@ mod tests {
controller,
affordances: kernel_speak_grant(),
position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))),
import_key: None,
})
};
let room = |handle: &str| {
@ -1428,6 +1669,7 @@ mod tests {
},
scale_intent: WorldScaleIntentRef::default(),
grammar: None,
era: None,
},
&authenticated,
)

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,7 @@ use super::controllers::{
tool_name_is_valid, unix_ms,
};
use async_trait::async_trait;
use codex_connector::CodexInputItem;
use model_connector::{InputItem, ReasoningEffort};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
@ -29,10 +29,6 @@ use tokio::sync::Mutex as AsyncMutex;
/// largest request either transport carries is the same grouped cell.
pub(super) const MAX_SIDECAR_FRAME_BYTES: usize = 1_052_672;
/// The reasoning-effort values the SDK's own `EffortLevel` admits. A request
/// carrying anything else is refused rather than silently mis-mapped.
const SDK_EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(super) enum SidecarFrame {
@ -379,9 +375,9 @@ struct SdkInferenceReceipt {
const SDK_RECEIPT_SCHEMA: &str = "ghostlight.sdk_inference_receipt.v1";
/// The model-name prefix that names the SDK transport when nothing configures
/// one. It holds even with no SDK port built, so a `claude-`prefixed lane on a
/// connector-only deployment is refused at open instead of quietly reaching the
/// wrong backend.
/// one. It claims a model only when the sidecar is configured; the connector
/// serves `claude-` models on its own, and `open_inference` refuses a sidecar
/// whose prefix would take a connector model.
pub const DEFAULT_SDK_MODEL_PREFIX: &str = "claude";
/// Everything the SDK sidecar needs to open, gathered so `open_inference` takes
@ -551,15 +547,8 @@ pub(super) fn lower_query(
turn_cap: u32,
) -> Result<SidecarFrame, InferenceFault> {
let request = &prepared.invocation.request;
if let Some(effort) = request.reasoning_effort.as_deref()
&& !SDK_EFFORT_LEVELS.contains(&effort)
{
return Err(InferenceFault::integrity_violation(
"the requested reasoning effort has no SDK counterpart",
));
}
let mut items = request.input.iter();
let Some(CodexInputItem::UserText { text: prompt }) = items.next() else {
let Some(InputItem::UserText { text: prompt }) = items.next() else {
return Err(InferenceFault::integrity_violation(
"an SDK request must open with exactly one user text item",
));
@ -567,17 +556,22 @@ pub(super) fn lower_query(
let mut transcript = Vec::new();
for item in items {
match item {
CodexInputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")),
CodexInputItem::ToolCall {
InputItem::AssistantText { text } => transcript.push(format!("assistant: {text}")),
InputItem::ToolCall {
name, arguments, ..
} => transcript.push(format!("tool call {name}: {arguments}")),
CodexInputItem::ToolResult { output, .. } => {
InputItem::ToolResult { output, .. } => {
transcript.push(format!("tool result: {output}"))
}
// A later user turn is a kernel refusal reopening the session; the
// transcript is already a textual replay of the conversation, so
// it rides there like every other turn.
CodexInputItem::UserText { text } => transcript.push(format!("user: {text}")),
InputItem::UserText { text } => transcript.push(format!("user: {text}")),
InputItem::ReasoningState { .. } => {
return Err(InferenceFault::integrity_violation(
"an SDK request carried provider reasoning state",
));
}
}
}
Ok(SidecarFrame::Query {
@ -595,8 +589,16 @@ pub(super) fn lower_query(
parameters_json: tool.parameters_json.clone(),
})
.collect(),
effort: request.reasoning_effort.clone(),
max_output_tokens: request.max_output_tokens,
effort: request.reasoning_effort.map(|effort| {
match effort {
ReasoningEffort::Low => "low",
ReasoningEffort::Medium => "medium",
ReasoningEffort::High => "high",
ReasoningEffort::Max => "max",
}
.to_owned()
}),
max_output_tokens: Some(request.max_output_tokens),
turn_cap,
})
}
@ -769,8 +771,10 @@ impl RoutedInferencePort {
.filter(|(prefix, _)| model.starts_with(prefix.as_str()))
.max_by_key(|(prefix, _)| prefix.len())
.map(|(prefix, port)| (prefix.len(), port));
let sdk_claim = model
.starts_with(&self.sdk_model_prefix)
// The SDK prefix claims only when the sidecar is configured: the
// connector serves `claude-` models too, so an unconfigured sidecar
// must leave them to it.
let sdk_claim = (self.sdk.is_some() && model.starts_with(&self.sdk_model_prefix))
.then_some(self.sdk_model_prefix.len());
match (local_claim, sdk_claim) {
(Some((local_len, local_port)), Some(sdk_len)) => {
@ -831,7 +835,7 @@ mod tests {
RECORD_GAP_PATCH_TOOL, SUBMIT_PATCH_TOOL, kernel_speak_entry, patch_tools,
};
use crate::{AffordanceId, AffordanceSnapshot};
use codex_connector::CodexToolDefinition;
use model_connector::ToolDefinition;
use std::collections::VecDeque;
const TEST_RUNTIME: &str = "ghostlight-sdk-test";
@ -912,7 +916,7 @@ mod tests {
InferencePurpose::Elaboration,
TEST_MODEL,
"Author the shortfall.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: prompt.into(),
}],
patch_tools(),
@ -932,10 +936,10 @@ mod tests {
InferencePurpose::Persona,
TEST_MODEL,
"Respond only in natural prose.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: prompt.into(),
}],
Vec::<CodexToolDefinition>::new(),
Vec::<ToolDefinition>::new(),
RequestShape {
max_output_tokens: 1_200,
parallel_tool_calls: false,
@ -1346,7 +1350,7 @@ mod tests {
InferencePurpose::OperationalAgent,
TEST_MODEL,
"Use only the supplied tools.",
vec![CodexInputItem::UserText {
vec![InputItem::UserText {
text: "Hold the bridge.".into(),
}],
catalog_tools("", &granted),
@ -1442,10 +1446,21 @@ mod tests {
open_inference(None, Some(sdk()), None, None, &models("gpt-5.6-terra").each()),
Err(ControllerOpenError::UnroutableModel { .. })
));
// The connector alone serves `claude-` models.
assert!(
open_inference(Some(connector()), None, None, None, &models("claude-haiku-5-5").each()).is_ok()
);
// A sidecar whose prefix would take a model the connector serves is
// refused at open, not left to steal the route.
assert!(matches!(
open_inference(Some(connector()), None, None, None, &models("claude-opus-5").each()),
Err(ControllerOpenError::UnroutableModel { .. })
open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-haiku-5-5").each()),
Err(ControllerOpenError::SidecarClaimsConnectorModel { .. })
));
// The same sidecar beside the connector is fine for a model the
// connector does not serve.
assert!(
open_inference(Some(connector()), Some(sdk()), None, None, &models("claude-opus-5").each()).is_ok()
);
assert!(matches!(
open_inference(
None,
@ -1795,13 +1810,6 @@ mod tests {
assert_names_no(&fault, CANARY);
}
// An effort the SDK has no counterpart for.
let port = SdkInferencePort::new(ScriptedLink::new(Vec::new()), TEST_RUNTIME);
let mut prepared = prose_prepared(&port, "Say something true.");
prepared.invocation.request.reasoning_effort = Some(CANARY.into());
let fault = lower_query(1, &prepared, 1).expect_err("an unmapped effort lowered");
assert_names_no(&fault, CANARY);
// A model no backend claims, prepared and inferred through the router.
let directory = tempfile::tempdir().unwrap();
let entry = directory.path().join("main.js");
@ -1824,8 +1832,8 @@ mod tests {
InferencePurpose::Persona,
CANARY,
"Respond only in natural prose.",
vec![CodexInputItem::UserText { text: "Say something true.".into() }],
Vec::<CodexToolDefinition>::new(),
vec![InputItem::UserText { text: "Say something true.".into() }],
Vec::<ToolDefinition>::new(),
RequestShape { max_output_tokens: 1_200, parallel_tool_calls: false },
)
.expect("the request builds");
@ -1840,25 +1848,27 @@ mod tests {
// `lower_query` reads the provider request off the prepared value, so
// the shapes it must refuse are written there directly. Nothing here
// asserts a digest; the identity tests own that.
let build = |input: Vec<CodexInputItem>, effort: Option<&str>| {
let build = |input: Vec<InputItem>, effort: Option<ReasoningEffort>| {
let mut prepared = prose_prepared(&port, "Say something true.");
prepared.invocation.request.input = input;
prepared.invocation.request.reasoning_effort = effort.map(str::to_owned);
prepared.invocation.request.reasoning_effort = effort;
prepared
};
let user = |text: &str| CodexInputItem::UserText { text: text.into() };
let user = |text: &str| InputItem::UserText { text: text.into() };
// Every effort the SDK admits passes; anything else is refused.
for effort in SDK_EFFORT_LEVELS {
// Every typed effort lowers.
for effort in [
ReasoningEffort::Low,
ReasoningEffort::Medium,
ReasoningEffort::High,
ReasoningEffort::Max,
] {
assert!(lower_query(1, &build(vec![user("go")], Some(effort)), 1).is_ok());
}
let fault = lower_query(1, &build(vec![user("go")], Some("blistering")), 1)
.expect_err("an unmapped effort lowered");
assert!(fault.integrity_was_violated(), "{fault:?}");
// The first item must be user text.
for input in [
vec![CodexInputItem::AssistantText { text: "no".into() }],
vec![InputItem::AssistantText { text: "no".into() }],
Vec::new(),
] {
let fault = lower_query(1, &build(input, None), 1)
@ -1881,20 +1891,20 @@ mod tests {
&build(
vec![
user("go"),
CodexInputItem::AssistantText {
InputItem::AssistantText {
text: "thinking".into(),
},
CodexInputItem::ToolCall {
InputItem::ToolCall {
call_id: "call-0".into(),
name: "record_gap".into(),
arguments: "{}".into(),
},
CodexInputItem::ToolResult {
InputItem::ToolResult {
call_id: "call-0".into(),
output: "gap recorded".into(),
},
],
Some("medium"),
Some(ReasoningEffort::Medium),
),
4,
)
@ -1930,15 +1940,27 @@ mod tests {
#[tokio::test]
async fn soul_routing_refuses_rather_than_falling_back() {
assert_eq!(DEFAULT_SDK_MODEL_PREFIX, "claude");
let connector_only = RoutedInferencePort::new(
Some(Arc::new(SdkInferencePort::new(
let stand_in = || {
Arc::new(SdkInferencePort::new(
ScriptedLink::new(Vec::new()),
TEST_RUNTIME,
)) as Arc<dyn InferencePort>),
)) as Arc<dyn InferencePort>
};
// A connector with no sidecar serves `claude-` models itself.
let connector = stand_in();
let connector_only = RoutedInferencePort::new(
Some(Arc::clone(&connector)),
None,
DEFAULT_SDK_MODEL_PREFIX,
Vec::new(),
);
assert!(Arc::ptr_eq(
connector_only.route(TEST_MODEL).unwrap(),
&connector
));
// A sidecar on a prefix that does not match, and no connector: the
// model has no owner and routes nowhere.
let connector_only = RoutedInferencePort::new(None, Some(stand_in()), "sdk/", Vec::new());
assert!(connector_only.route(TEST_MODEL).is_none());
let prepared =
PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it.")).unwrap();

View file

@ -26,7 +26,7 @@ use super::{
DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId,
SubjectKind, Target, WorldPatch, WorldSnapshot,
};
use codex_connector::{CodexInputItem, CodexToolDefinition};
use model_connector::{InputItem, ToolDefinition};
use serde_json::Value;
use thiserror::Error;
@ -44,7 +44,7 @@ pub enum TableError {
/// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy
/// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not
/// this module's.
pub fn authoring_tools(names: &[&str]) -> Result<Vec<CodexToolDefinition>, TableError> {
pub fn authoring_tools(names: &[&str]) -> Result<Vec<ToolDefinition>, TableError> {
let catalog = patch::patch_tools();
names
.iter()
@ -220,7 +220,7 @@ fn subject_opportunity<'a>(
/// turn; that is the controller lane's own vocabulary, and
/// `decode_actor_call` has no arm for either, so offering them here would
/// hand the play agent a tool `decode_actor_call` always refuses (PA.f55).
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<CodexToolDefinition> {
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<ToolDefinition> {
match subject_opportunity(snapshot, subject) {
Some((_, granted)) => controllers::affordance_tools(prefix, &granted),
None => Vec::new(),
@ -983,6 +983,100 @@ fn render_dependency_target(snapshot: &WorldSnapshot, target: &DependencyTarget)
}
}
/// The wrongs the world holds against a subject and what has answered them,
/// read off state and stored nowhere: whom the doer wronged (a grievance in the
/// victim's regard), who saw the doer's acts (`Seen` knowledge), which forums
/// cover the doer, who presses the doer, and who has sworn a reckoning with the
/// doer as counterparty. A grievance nothing answers is named as unanswered:
/// the table's own judgement sends the watch, so what it needs is to see that
/// no one has been sent.
fn render_open_grievances(snapshot: &WorldSnapshot) -> String {
use crate::attitude::AttitudeCause;
use crate::patch::KnowledgeSource;
let name = |id: SubjectId| {
label_for_any_id(snapshot, &id_text(id)).unwrap_or_else(|| format!("[{}]", id_text(id)))
};
let mut out = String::from("\n Open grievances (derived: who was wronged, who saw it, what answers it):");
let mut any = false;
for doer in &snapshot.subjects {
let wronged: Vec<String> = snapshot
.subjects
.iter()
.flat_map(|holder| {
holder
.opinions
.iter()
.filter(|held| held.toward == doer.id)
.filter(|held| {
held.causes
.iter()
.any(|cause| matches!(cause.cause, AttitudeCause::Grievance { .. }) && cause.delta < 0)
})
.map(|held| format!("{} ({:+})", name(holder.id), held.total))
})
.collect();
if wronged.is_empty() {
continue;
}
any = true;
let mut seen_by = Vec::new();
let mut acts = std::collections::BTreeSet::new();
for witness in snapshot.subjects.iter().filter(|witness| witness.id != doer.id) {
for row in &witness.knowledge {
if row.source == (KnowledgeSource::Seen { by: doer.id }) {
seen_by.push(name(witness.id));
acts.insert(format!("\"{}\"", row.statement.as_str()));
}
}
}
seen_by.sort();
seen_by.dedup();
let pressing: Vec<String> = doer
.pressures
.iter()
.filter_map(|pressure| match pressure.source {
PressureSource::Subject(id) => Some(format!("{} ({})", name(id), pressure.magnitude.0)),
_ => None,
})
.collect();
let reckonings: Vec<String> = snapshot
.subjects
.iter()
.flat_map(|holder| {
holder
.commitments
.iter()
.filter(|commitment| commitment.counterparty == Some(doer.id))
.map(move |commitment| format!("{}: \"{}\"", name(holder.id), commitment.statement.as_str()))
})
.collect();
let answered = !pressing.is_empty() || !reckonings.is_empty();
out.push_str(&format!(
" {} wronged {}; acts seen by: {}{}; forums covering them: {}; pressed by: {}; reckonings sworn against them: {}; {}",
name(doer.id),
joined_sorted(wronged),
if seen_by.is_empty() { "no one".to_owned() } else { joined_sorted(seen_by) },
if acts.is_empty() { String::new() } else { format!(" ({})", joined_sorted(acts.into_iter().collect())) },
if doer.redress.is_empty() {
"none".to_owned()
} else {
joined_sorted(doer.redress.iter().map(|forum| render_forum(snapshot, forum)).collect())
},
if pressing.is_empty() { "no one".to_owned() } else { joined_sorted(pressing) },
if reckonings.is_empty() { "none".to_owned() } else { joined_sorted(reckonings) },
if answered {
"answered so far."
} else {
"nothing has answered it yet: no office presses them and no kin or ally has sworn anything. The office, the kin and the witnesses answer through their own people: dispatch them, or rule it with advance_pressure and create_commitment."
},
));
}
if !any {
out.push_str(" none");
}
out
}
/// A pressure source, in the same shape `advance_pressure`/`reduce_pressure`'s
/// `PressureSourceRef` composite takes: a commitment names the promisor
/// subject id and the commitment key; a dependency names its target; a
@ -1038,8 +1132,8 @@ impl InferenceRequest {
round: usize,
model: &str,
instructions: &str,
input: Vec<CodexInputItem>,
tools: Vec<CodexToolDefinition>,
input: Vec<InputItem>,
tools: Vec<ToolDefinition>,
max_output_tokens: u32,
) -> Result<InferenceRequest, ControllerError> {
tool_request(
@ -1095,6 +1189,17 @@ pub fn id_text(id: impl std::fmt::Debug) -> String {
}
}
/// A subject's own short handle: the first 8 hex digits of its id. Actor tool
/// names are `<handle>__<kind>` and a kind may run to 48 chars, so the full id
/// text would break a common 64-char function-name limit; the Gestalt round's
/// section headers carry the same handle, so a reply splits on a token that
/// names exactly one subject even when two share a label. A collision between
/// two subjects is astronomically unlikely but not impossible; each caller that
/// keys on handles refuses it rather than addressing the wrong subject.
pub fn handle_for(id: crate::SubjectId) -> String {
id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect()
}
/// The parser matching `id_text` above (PA.f113): `text` names `id` only
/// when it is exactly the bytes `id_text(id)` would print — no brackets, no
/// padding, no case folding, because this is plain string equality against
@ -1108,7 +1213,7 @@ pub fn id_text_matches(id: impl std::fmt::Debug, text: &str) -> bool {
/// The world the seed session is authoring into, rendered from snapshot
/// fields that already exist. Moved from the elaboration lane, byte-for-byte:
/// the seed prompt calls it here now, and its text does not change with the
/// move. Seed-only; `table_view` below is the play agent's own, richer
/// move. Read by the seed and the Active elaboration prompts; `table_view` below is the play agent's own, richer
/// renderer over the same snapshot and does not build on this one, so a
/// change to one never reaches the other's bytes.
pub(super) fn render_world_structure(snapshot: &WorldSnapshot) -> String {
@ -1547,6 +1652,44 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
out.push_str(" none");
}
// Derived by the kernel from sourced modifiers; the one reading the
// Persona's own view and the narrator also draw from. A prejudice toward a
// trait shows only once its holder knows the subject carries it.
out.push_str("\n Regard (how each subject holds another, with what it rests on):");
let mut any_regard = false;
for subject in &snapshot.subjects {
for held in &subject.opinions {
any_regard = true;
let toward = label_for_any_id(snapshot, &id_text(held.toward))
.unwrap_or_else(|| format!("[{}]", id_text(held.toward)));
out.push_str(&format!(
" {} [{}] regards {} with {} ({:+}): {};",
subject.label,
id_text(subject.id),
toward,
crate::attitude::regard_word(held.total),
held.total,
joined(
held.causes
.iter()
.map(|cause| crate::attitude::describe_cause(cause, |fact| {
snapshot
.facts
.iter()
.find(|entry| entry.id == fact)
.map(|entry| entry.statement.as_str().to_owned())
}))
.collect()
)
));
}
}
if !any_regard {
out.push_str(" none");
}
out.push_str(&render_open_grievances(snapshot));
out.push_str("\n Persona material:");
let mut any_material = false;
for subject in &snapshot.subjects {
@ -1591,7 +1734,7 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
"\n Clock: the world reads {} fictional minutes.",
snapshot.now.0
));
out.push_str(&format!("\n Brief: {}\n", snapshot.brief));
out.push_str(&format!("\n Guidance: {}\n", snapshot.guidance().replace('\n', " ")));
out
}
@ -1606,7 +1749,8 @@ mod tests {
// PA.f75: `communicate` was removed from `PLAY_TOOLS`; Dungeon drops it
// from its own list too. This is now the complete 24-tool list.
// PA.f88: this is the library's own test fixture, kept in sync by hand.
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` is the
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` (parked at
// `parked/ghostlight-eve-surface`) is the
// single policy owner of what the play agent may actually call; this
// copy pins nothing there and is not read by production code.
const PLAY_TOOLS: &[&str] = &[

View file

@ -6,11 +6,11 @@
//! own vocabulary. Both spell a property the same way because both spell it
//! here. Nothing in this module reads world state, a snapshot, or a config.
use codex_connector::CodexToolDefinition;
use model_connector::ToolDefinition;
use serde_json::{Value, json};
pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition {
CodexToolDefinition {
pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition {
ToolDefinition {
name: name.into(),
description: description.into(),
parameters_json: serde_json::to_string(&schema)
@ -43,10 +43,29 @@ pub(super) fn canonical_string(description: &str) -> Value {
json!({"type": "string", "description": description})
}
/// A string the kernel will hold to its civic-name rule, `[a-z][a-z0-9_]` up to
/// `max` characters. The rule is stated twice on purpose: as a `pattern` a
/// strict decoder can enforce, and in the description the model reads. `max` is
/// the kernel's own bound, passed in so the rule has one owner.
pub(super) fn civic_name(description: &str, max: usize) -> Value {
json!({
"type": "string",
"pattern": format!("^[a-z][a-z0-9_]{{0,{}}}$", max - 1),
"description": format!(
"{description}: lowercase snake_case, starting with a letter, at most {max} characters (e.g. toll_command)"
),
})
}
pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
json!({"type": "integer", "minimum": min, "maximum": max})
}
/// An integer that may be negative, for a regard that can fall as well as rise.
pub(super) fn signed_integer(min: i64, max: i64) -> Value {
json!({"type": "integer", "minimum": min, "maximum": max})
}
/// The same schema with the text the model reads beside it. Meaning that lives
/// only in a prompt paragraph is lost by the time the model fills the field.
pub(super) fn described(mut schema: Value, description: &str) -> Value {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,988 @@
//! Provider call records, the run's spend, and replay.
//!
//! `RecordingInferencePort` is the one owner of a run's spend. Before it
//! forwards a call it decides, from the request alone, whether the call could
//! pass the run's token cap; after the reply it charges what the call really
//! cost. Every reply is stored as a `ProviderCallRecord` before the output
//! returns to the lane, so `ReplayInferencePort` can serve the same run again
//! from the store with no provider behind it.
//!
//! Lanes and runners never count tokens. A request is held against the cap by
//! its bound: the serialized provider request's bytes (a token is at least one
//! byte, so bytes bound the prompt) plus the request's own output allowance.
//!
//! The run's spend is one persisted ledger row per run, owned by the store and
//! written where it is spent. A call reserves its bound in that row before the
//! provider is called; a reply settles the reservation to what it reported
//! (prompt plus completion, cached prompt tokens being part of the prompt; none
//! reported is charged the bound); a fault leaves the reservation charged. A
//! restart reads the row, so no restart returns budget. A reply that reports
//! more than the call's bound is charged in full and faults the call, so the
//! run's spend never passes the cap unnoticed. One port at a time owns a run.
use crate::controllers::{
ControllerError, InferenceEvent, InferenceFault, InferenceOutput, InferencePort,
InferencePurpose, InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage,
ToolResultOracle, request_id_prefix, unix_ms,
};
use crate::{FrozenCell, NodeId, TickIndex, WorldId};
use async_trait::async_trait;
use chrono::Utc;
use model_connector::ProviderRequest;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
path::Path,
sync::{Arc, Mutex},
};
use thiserror::Error;
const CALL_RECORD_ROW: &str = "verse_provider_call.v2";
const RUN_LEDGER_ROW: &str = "verse_run_ledger.v2";
/// The run ledger document's schema.
const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v2";
/// The call record document's schema. A store holding any other row type or
/// schema is refused at open: this store is not migrated from, or shared with,
/// another document.
pub const CALL_RECORD_SCHEMA: &str = "ghostlight.verse_provider_call.v2";
#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)]
pub enum CallRecordError {
#[error("a run id is 1 to 64 characters of letters, digits, '-' and '_'")]
InvalidRunId,
#[error("the call record store could not be read or written")]
Store,
#[error("the call record store holds a row that is not a canonical call record")]
Corrupt,
#[error("a call record's sequence is not the next in its run")]
OutOfSequence,
#[error("replay needs one run's records in dense sequence from 1")]
NotReplayable,
#[error("another recording port already owns this run")]
RunInUse,
#[error("the call could pass the run's token cap")]
OverCap,
#[error("the call could pass its lane's allowance")]
OverAllowance,
#[error("the run was recorded with a different {0}")]
RunMismatch(RunField),
}
/// What a run is bound to when it begins, named by the field a mismatch refuses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunField {
/// The token cap the run was opened with.
Cap,
/// The lane allowances the run was opened with.
Allowances,
/// The identity of the world the run started from.
WorldId,
/// The state digest of the world the run started from.
StateDigest,
}
impl std::fmt::Display for RunField {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Cap => "token cap",
Self::Allowances => "lane allowances",
Self::WorldId => "world id",
Self::StateDigest => "world state digest",
})
}
}
/// The background lane a metered call spends in. The room lane, the DM's play
/// turn, is in no window: it is never reserved here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Lane {
/// A node turn of a Gestalt wave.
Wave,
/// An elaborator session.
Elaboration,
}
impl Lane {
/// The lane a call of this purpose spends in; the play agent has none.
pub fn of(purpose: InferencePurpose) -> Option<Self> {
match purpose {
InferencePurpose::Play => None,
InferencePurpose::Elaboration => Some(Self::Elaboration),
_ => Some(Self::Wave),
}
}
}
/// Tokens by lane: a window's allowances, or what its lanes have reserved or
/// been charged.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaneTokens {
pub wave: u64,
pub elaboration: u64,
}
impl LaneTokens {
pub fn of(&self, lane: Lane) -> u64 {
match lane {
Lane::Wave => self.wave,
Lane::Elaboration => self.elaboration,
}
}
fn set(&mut self, lane: Lane, tokens: u64) {
match lane {
Lane::Wave => self.wave = tokens,
Lane::Elaboration => self.elaboration = tokens,
}
}
/// Every lane together.
pub fn total(&self) -> u64 {
self.wave.saturating_add(self.elaboration)
}
}
/// The world a run began from: its identity and state digest. Replay is of a
/// restored copy of this world, so it takes the same two values.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunStart {
world_id: String,
state_digest: String,
}
impl RunStart {
pub fn of(world: &crate::WorldSnapshot) -> Self {
Self {
world_id: world.world_id.text(),
state_digest: world.state_digest.clone(),
}
}
}
/// A run's identity as a key segment.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct RunId(String);
impl RunId {
pub fn new(id: &str) -> Result<Self, CallRecordError> {
let valid = !id.is_empty()
&& id.len() <= 64
&& id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
if valid {
Ok(Self(id.to_owned()))
} else {
Err(CallRecordError::InvalidRunId)
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// One provider call of one run: the request's content digest (never its text, so no
/// prompt or credential is stored), the reply exactly as the lane received it,
/// and what the call was charged. Keyed (run id, sequence).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderCallRecord {
run_id: String,
sequence: u64,
purpose: InferencePurpose,
lane: Lane,
request_id: String,
model: String,
content_sha256: String,
events: Vec<InferenceEvent>,
receipt_digest: String,
usage: Option<TokenUsage>,
charged: u64,
}
impl ProviderCallRecord {
pub fn run_id(&self) -> &str {
&self.run_id
}
pub fn sequence(&self) -> u64 {
self.sequence
}
pub fn purpose(&self) -> InferencePurpose {
self.purpose
}
/// The lane this call spent in.
pub fn lane(&self) -> Lane {
self.lane
}
/// The provider request id, which carries the command id it ran under: the
/// join from a call to the wave cell that made it.
pub fn request_id(&self) -> &str {
&self.request_id
}
pub fn model(&self) -> &str {
&self.model
}
/// Lowercase hex of the request's content digest (see `content_digest`).
pub fn content_sha256(&self) -> &str {
&self.content_sha256
}
pub fn usage(&self) -> Option<TokenUsage> {
self.usage
}
/// Tokens this call was charged against the run's cap.
pub fn charged(&self) -> u64 {
self.charged
}
/// The reply as the lane received it.
pub fn output(&self) -> InferenceOutput {
let output = InferenceOutput::new(self.events.clone(), self.receipt_digest.clone());
match self.usage {
Some(usage) => output.with_usage(usage),
None => output,
}
}
}
fn row_key(run: &str, sequence: u64) -> String {
format!("{run}/{sequence:020}")
}
fn hex(digest: &[u8]) -> String {
digest.iter().map(|byte| format!("{byte:02x}")).collect()
}
/// What a request asks of the provider, without the ids that name it. The
/// request and conversation ids are derived from the command id, and a command
/// id from the world it ran in, so keying on them would tie a recorded run to
/// one world's random identity. Everything else the provider is sent
/// (model, instructions, input, tools, shape) is in the digest.
fn content_digest(request: &ProviderRequest) -> Result<String, InferenceFault> {
// Exhaustive on purpose: a field added upstream must be placed in the key
// or left out here by name before this compiles.
let ProviderRequest {
schema_id,
request_id: _request_id, // names the call, not what it asks
conversation_id: _conversation_id, // names the call, not what it asks
model,
instructions,
input,
reasoning_effort,
cache_retention,
tools,
tool_choice,
parallel_tool_calls,
output_schema_json,
max_output_tokens,
} = request;
let bytes = rmp_serde::to_vec(&(
schema_id,
model,
instructions,
input,
reasoning_effort,
cache_retention,
tools,
tool_choice,
parallel_tool_calls,
output_schema_json,
max_output_tokens,
))
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
Ok(hex(&Sha256::digest(bytes)))
}
/// A run's persisted ledger, the one owner of what the run began as: the cap
/// it was opened under, the world it started from, and the tokens reserved or
/// charged so far.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct RunLedger {
run_id: String,
cap: u64,
allowances: LaneTokens,
start: RunStart,
/// Tokens reserved or charged, by lane. The run's spend is their sum.
spent: LaneTokens,
}
enum DecodedRow {
Call(ProviderCallRecord),
Ledger(RunLedger),
}
pub(super) fn canonical<T: Serialize + for<'de> Deserialize<'de>>(
row: &CultCacheEnvelope,
) -> Result<T, CallRecordError> {
let value: T = rmp_serde::from_slice(&row.payload).map_err(|_| CallRecordError::Corrupt)?;
let again = rmp_serde::to_vec_named(&value).map_err(|_| CallRecordError::Corrupt)?;
if again == row.payload {
Ok(value)
} else {
Err(CallRecordError::Corrupt)
}
}
fn decode_row(row: &CultCacheEnvelope) -> Result<DecodedRow, CallRecordError> {
match (row.r#type.as_str(), row.schema_id.as_deref()) {
(CALL_RECORD_ROW, Some(CALL_RECORD_SCHEMA)) => {
let record: ProviderCallRecord = canonical(row)?;
// A run id that is no whole key segment would key into another
// run's records, and sequences count from 1.
if RunId::new(&record.run_id).is_err()
|| record.sequence == 0
|| row.key != row_key(&record.run_id, record.sequence)
{
return Err(CallRecordError::Corrupt);
}
Ok(DecodedRow::Call(record))
}
(RUN_LEDGER_ROW, Some(RUN_LEDGER_SCHEMA)) => {
let ledger: RunLedger = canonical(row)?;
if RunId::new(&ledger.run_id).is_err() || row.key != ledger.run_id {
return Err(CallRecordError::Corrupt);
}
Ok(DecodedRow::Ledger(ledger))
}
_ => Err(CallRecordError::Corrupt),
}
}
#[derive(Default)]
struct RunTally {
last_sequence: u64,
/// The persisted ledger, read at open and written where it is spent.
ledger: Option<RunLedger>,
}
struct StoreState {
store: OwnedRedbMessagePackBackingStore,
runs: BTreeMap<String, RunTally>,
/// Runs with a recording port alive; one ledger has one owner.
owned: BTreeSet<String>,
}
/// The call records and spend ledgers of every run in one CultCache file.
/// Records are appended and never changed; a run's sequence is dense from 1.
pub struct CallRecordStore {
state: Mutex<StoreState>,
}
impl CallRecordStore {
/// Opens the file, creating it empty when absent. Every row must be a
/// canonical call record or run ledger of this schema with its key, a
/// dense sequence, and a ledger that covers its records' charges; anything
/// else, an earlier or later schema version included, is refused and
/// nothing is migrated.
pub fn open(path: impl AsRef<Path>) -> Result<Self, CallRecordError> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
.map_err(|_| CallRecordError::Store)?;
store
.validate_path_identity()
.map_err(|_| CallRecordError::Store)?;
let rows = store.pull_all().map_err(|_| CallRecordError::Store)?;
let mut runs: BTreeMap<String, RunTally> = BTreeMap::new();
let mut counts: BTreeMap<String, u64> = BTreeMap::new();
let mut charged: BTreeMap<String, LaneTokens> = BTreeMap::new();
for row in &rows {
match decode_row(row)? {
DecodedRow::Call(record) => {
*counts.entry(record.run_id.clone()).or_default() += 1;
let total = charged.entry(record.run_id.clone()).or_default();
total.set(record.lane, total.of(record.lane).saturating_add(record.charged));
let tally = runs.entry(record.run_id).or_default();
tally.last_sequence = tally.last_sequence.max(record.sequence);
}
DecodedRow::Ledger(ledger) => {
let run = ledger.run_id.clone();
runs.entry(run).or_default().ledger = Some(ledger);
}
}
}
// Sequences start at 1 and keys are unique, so a run is dense exactly
// when its rows number its highest sequence. Every record was reserved
// in a ledger before it was made, so a run with records has a ledger
// that covers what they charged.
for (run, tally) in &runs {
let rows = counts.get(run).copied().unwrap_or(0);
let recorded = charged.get(run).copied().unwrap_or_default();
let covered = tally.ledger.as_ref().is_some_and(|ledger| {
ledger.spent.wave >= recorded.wave && ledger.spent.elaboration >= recorded.elaboration
});
if rows != tally.last_sequence || !covered {
return Err(CallRecordError::Corrupt);
}
}
Ok(Self {
state: Mutex::new(StoreState {
store,
runs,
owned: BTreeSet::new(),
}),
})
}
fn lock(&self) -> Result<std::sync::MutexGuard<'_, StoreState>, CallRecordError> {
self.state.lock().map_err(|_| CallRecordError::Store)
}
/// The sequence the next record of this run must carry.
pub fn next_sequence(&self, run: &RunId) -> Result<u64, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.map_or(0, |tally| tally.last_sequence)
+ 1)
}
/// Tokens this run has reserved or been charged: its persisted ledger.
pub fn spent(&self, run: &RunId) -> Result<u64, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map_or(0, |ledger| ledger.spent.total()))
}
/// What each lane of this run has reserved or been charged.
pub fn lane_spent(&self, run: &RunId) -> Result<LaneTokens, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map_or_else(LaneTokens::default, |ledger| ledger.spent))
}
/// Takes the run's ledger for one port, or refuses when another holds it.
/// The first claim of a run writes its ledger: the cap it is opened under
/// the lane allowances, and the world it starts from. A later claim must name
/// the same cap and allowances; the start is not compared, because a resumed world has moved on.
/// With `follow`, a ledger already begun takes the cap and allowances named
/// here in place of its own, its spend kept: a caller whose limits change
/// while a run is open (the Dungeon's tuned allowances) owns them, and a
/// limit below what is already held only exhausts the lane.
fn claim(
&self,
run: &RunId,
cap: u64,
allowances: LaneTokens,
start: &RunStart,
follow: bool,
) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
if !state.owned.insert(run.as_str().to_owned()) {
return Err(CallRecordError::RunInUse);
}
let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.clone()) {
Some(ledger) if follow && (ledger.cap != cap || ledger.allowances != allowances) => {
Self::write_ledger(&mut state, RunLedger { cap, allowances, ..ledger })
}
Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)),
Some(ledger) if ledger.allowances != allowances => {
Err(CallRecordError::RunMismatch(RunField::Allowances))
}
Some(_) => Ok(()),
None => Self::write_ledger(
&mut state,
RunLedger {
run_id: run.as_str().to_owned(),
cap,
allowances,
start: start.clone(),
spent: LaneTokens::default(),
},
),
};
if begun.is_err() {
state.owned.remove(run.as_str());
}
begun
}
/// The world a run began from, when it has begun.
fn start_of(&self, run: &RunId) -> Result<Option<RunStart>, CallRecordError> {
Ok(self
.lock()?
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map(|ledger| ledger.start.clone()))
}
fn disown(&self, run: &RunId) {
if let Ok(mut state) = self.state.lock() {
state.owned.remove(run.as_str());
}
}
/// Persists the ledger, then adopts it in memory. A write that fails
/// leaves the previous ledger.
fn write_ledger(state: &mut StoreState, ledger: RunLedger) -> Result<(), CallRecordError> {
let row = CultCacheEnvelope {
key: ledger.run_id.clone(),
r#type: RUN_LEDGER_ROW.into(),
payload: rmp_serde::to_vec_named(&ledger).map_err(|_| CallRecordError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(RUN_LEDGER_SCHEMA.into()),
};
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
let run = ledger.run_id.clone();
state.runs.entry(run).or_default().ledger = Some(ledger);
Ok(())
}
/// Persists `spent` as what the run's lanes hold; the run must have been
/// claimed.
fn write_spent(
state: &mut StoreState,
run: &str,
spent: LaneTokens,
) -> Result<(), CallRecordError> {
let mut ledger = state
.runs
.get(run)
.and_then(|tally| tally.ledger.clone())
.ok_or(CallRecordError::Store)?;
ledger.spent = spent;
Self::write_ledger(state, ledger)
}
fn held(state: &StoreState, run: &RunId) -> LaneTokens {
state
.runs
.get(run.as_str())
.and_then(|tally| tally.ledger.as_ref())
.map_or_else(LaneTokens::default, |ledger| ledger.spent)
}
/// Charges `bound` to the run's persisted ledger under `lane`, or refuses
/// with `OverCap` when the run would pass `cap`, or `OverAllowance` when
/// the lane would pass its allowance. The check and the write hold one
/// lock, so calls on the wire hold their bounds.
fn reserve(
&self,
run: &RunId,
lane: Lane,
bound: u64,
cap: u64,
allowance: u64,
) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
let mut held = Self::held(&state, run);
let after = held.of(lane).saturating_add(bound);
if held.total().saturating_add(bound) > cap {
return Err(CallRecordError::OverCap);
}
if after > allowance {
return Err(CallRecordError::OverAllowance);
}
held.set(lane, after);
Self::write_spent(&mut state, run.as_str(), held)
}
/// Replaces a reservation of `bound` with what the call was charged. With
/// a record, the record is stored first, so a crash between the two writes
/// leaves the larger reservation charged.
fn settle(
&self,
run: &RunId,
lane: Lane,
bound: u64,
charged: u64,
record: Option<&ProviderCallRecord>,
) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
if let Some(record) = record {
Self::push_record(&mut state, record)?;
}
let mut held = Self::held(&state, run);
held.set(lane, held.of(lane).saturating_sub(bound).saturating_add(charged));
Self::write_spent(&mut state, run.as_str(), held)
}
fn append(&self, record: &ProviderCallRecord) -> Result<(), CallRecordError> {
let mut state = self.lock()?;
Self::push_record(&mut state, record)
}
fn push_record(
state: &mut StoreState,
record: &ProviderCallRecord,
) -> Result<(), CallRecordError> {
let last = state
.runs
.get(&record.run_id)
.map_or(0, |tally| tally.last_sequence);
if record.sequence != last + 1 {
return Err(CallRecordError::OutOfSequence);
}
let row = CultCacheEnvelope {
key: row_key(&record.run_id, record.sequence),
r#type: CALL_RECORD_ROW.into(),
payload: rmp_serde::to_vec_named(record).map_err(|_| CallRecordError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(CALL_RECORD_SCHEMA.into()),
};
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
state
.runs
.entry(record.run_id.clone())
.or_default()
.last_sequence = record.sequence;
Ok(())
}
/// The run's records in sequence.
pub fn records(&self, run: &RunId) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
let prefix = format!("{}/", run.as_str());
let rows = self
.lock()?
.store
.pull_all()
.map_err(|_| CallRecordError::Store)?;
let mut records = Vec::new();
for row in rows.iter().filter(|row| row.key.starts_with(&prefix)) {
if let DecodedRow::Call(record) = decode_row(row)? {
records.push(record);
}
}
records.sort_by_key(|record| record.sequence);
Ok(records)
}
}
/// Decorates a port for one run: reserves each call's bound in the run's
/// ledger before the provider is called, settles it to the real cost, and
/// stores every reply before returning it.
pub struct RecordingInferencePort {
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap: u64,
allowances: LaneTokens,
}
impl RecordingInferencePort {
/// Takes ownership of the run's ledger, which resumes from the store. The
/// first open of a run records its cap, its lane allowances and the world it
/// starts from; a reopen with another cap or allowances is refused with
/// `RunMismatch`. A second
/// port on a run whose first is alive is refused with `RunInUse`.
pub fn open(
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap_tokens: u64,
allowances: LaneTokens,
start: &RunStart,
) -> Result<Self, CallRecordError> {
store.claim(&run, cap_tokens, allowances, start, false)?;
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
}
/// `open`, except that a run already begun follows the cap and allowances
/// given here instead of refusing them: its ledger takes them, the spend
/// already held stays, and a lane whose allowance now sits below its spend
/// refuses further calls as exhausted.
pub fn open_following(
inner: Arc<dyn InferencePort>,
store: Arc<CallRecordStore>,
run: RunId,
cap_tokens: u64,
allowances: LaneTokens,
start: &RunStart,
) -> Result<Self, CallRecordError> {
store.claim(&run, cap_tokens, allowances, start, true)?;
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
}
/// The run this port records.
pub fn run_id(&self) -> &RunId {
&self.run
}
/// The token cap the run was opened under.
pub fn cap(&self) -> u64 {
self.cap
}
/// Tokens reserved or charged to the run so far.
pub fn spent(&self) -> u64 {
self.store.spent(&self.run).unwrap_or(u64::MAX)
}
/// Tokens reserved or charged so far, by lane.
pub fn lane_spent(&self) -> LaneTokens {
self.store.lane_spent(&self.run).unwrap_or(LaneTokens {
wave: u64::MAX,
elaboration: u64::MAX,
})
}
/// The run's call records in sequence.
pub fn records(&self) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
self.store.records(&self.run)
}
/// The most this request can cost: its serialized bytes plus its output
/// allowance. The v4 request type cannot omit the allowance, so every
/// request has a bound.
fn bound(request: &PreparedInference) -> Result<u64, InferenceFault> {
let allowance = request.invocation.request.max_output_tokens;
let payload = serde_json::to_vec(&request.invocation.request)
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
Ok((payload.len() as u64).saturating_add(u64::from(allowance)))
}
fn settle(
&self,
lane: Lane,
bound: u64,
identity: Identity,
result: Result<InferenceOutput, InferenceFault>,
) -> Result<InferenceOutput, InferenceFault> {
// A fault leaves its reservation charged: the request may have run.
let output = result?;
let charged = match output.usage {
Some(usage) => usage.prompt.saturating_add(usage.completion),
None => bound,
};
if charged > bound {
self.store
.settle(&self.run, lane, bound, charged, None)
.map_err(unrecorded)?;
return Err(InferenceFault::budget_exhausted());
}
let Identity {
purpose,
model,
content_sha256,
request_id,
} = identity;
let record = ProviderCallRecord {
run_id: self.run.as_str().to_owned(),
sequence: self.store.next_sequence(&self.run).map_err(unrecorded)?,
purpose,
lane,
request_id,
model,
content_sha256,
events: output.events.clone(),
receipt_digest: output.receipt_digest.clone(),
usage: output.usage,
charged,
};
self.store
.settle(&self.run, lane, bound, charged, Some(&record))
.map_err(unrecorded)?;
Ok(output)
}
}
/// What a call is recorded as, known before the provider is called.
struct Identity {
purpose: InferencePurpose,
model: String,
content_sha256: String,
request_id: String,
}
impl Drop for RecordingInferencePort {
fn drop(&mut self) {
self.store.disown(&self.run);
}
}
fn unrecorded(_: CallRecordError) -> InferenceFault {
InferenceFault::integrity_violation("a provider call could not be recorded")
}
#[async_trait]
impl InferencePort for RecordingInferencePort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let bound = Self::bound(&request)?;
// The room lane is no window's: a play call that reached this port
// would spend background budget.
let Some(lane) = Lane::of(request.purpose) else {
return Err(InferenceFault::integrity_violation(
"the room lane is not metered by a background window",
));
};
let identity = Identity {
purpose: request.purpose,
model: request.invocation.request.model.clone(),
content_sha256: content_digest(&request.invocation.request)?,
request_id: request.invocation.request.request_id.clone(),
};
self.store
.reserve(&self.run, lane, bound, self.cap, self.allowances.of(lane))
.map_err(|error| match error {
CallRecordError::OverCap | CallRecordError::OverAllowance => {
InferenceFault::budget_exhausted()
}
_ => unrecorded(error),
})?;
let result = self.inner.infer(request).await;
self.settle(lane, bound, identity, result)
}
fn lend_tool_results(&self, prepared: &PreparedInference, oracle: Box<dyn ToolResultOracle>) {
self.inner.lend_tool_results(prepared, oracle);
}
}
/// What the calls of one wave cost, by lane and by node. The port never learns
/// which node a call served: a record's request id begins with the command id
/// it ran under, and the frozen wave names the command ids of each node's
/// cells, so attribution is this join and nothing the port keeps. Only settled
/// calls have records; a call that faulted left its reservation in the ledger
/// and no record here.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WaveSpend {
/// Tokens charged by the wave's joined calls, by lane.
pub lanes: LaneTokens,
/// Per node, in the order the frozen cells first name them. A node whose
/// cells made no recorded call is listed with zero.
pub nodes: Vec<NodeSpend>,
}
/// One node's settled calls in a wave.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NodeSpend {
pub node: NodeId,
/// The node's hierarchy distance from the focus when it was planned.
pub distance: u8,
pub calls: u32,
pub charged: u64,
}
impl WaveSpend {
/// The records of wave `ordinal` of `world`: every record whose request id
/// begins with a command id of one of `frozen`'s cells. Records of other
/// waves or lanes are not this wave's and are left out.
pub fn of(
records: &[ProviderCallRecord],
world: WorldId,
ordinal: TickIndex,
frozen: &[FrozenCell],
) -> Result<Self, ControllerError> {
let mut spend = Self::default();
let mut prefixes: Vec<(String, usize)> = Vec::new();
for cell in frozen {
let at = match spend.nodes.iter().position(|node| node.node == cell.node) {
Some(at) => at,
None => {
spend.nodes.push(NodeSpend {
node: cell.node,
distance: cell.distance,
calls: 0,
charged: 0,
});
spend.nodes.len() - 1
}
};
for command in cell.command_ids(world, ordinal) {
prefixes.push((request_id_prefix(command)?, at));
}
}
for record in records {
let Some(&(_, at)) = prefixes
.iter()
.find(|(prefix, _)| record.request_id.starts_with(prefix))
else {
continue;
};
let node = &mut spend.nodes[at];
node.calls += 1;
node.charged = node.charged.saturating_add(record.charged);
let lane = spend.lanes.of(record.lane).saturating_add(record.charged);
spend.lanes.set(record.lane, lane);
}
Ok(spend)
}
}
/// Serves a run's stored replies, in sequence, to the same requests, matched
/// by what they ask of the provider and not by the ids that name them. It holds
/// no provider and makes no call: a request that is not the next recorded one
/// is a fault.
pub struct ReplayInferencePort {
caller_runtime_id: String,
pending: Mutex<VecDeque<ProviderCallRecord>>,
}
impl ReplayInferencePort {
/// Replays `run` from the store against `world`, a restored copy of the
/// world the run started from. Any other world is refused here, before a
/// call, with `RunMismatch` naming the field; a run the store never began
/// is `NotReplayable`.
pub fn new(
caller_runtime_id: impl Into<String>,
store: &CallRecordStore,
run: &RunId,
world: &RunStart,
) -> Result<Self, CallRecordError> {
let began = store.start_of(run)?.ok_or(CallRecordError::NotReplayable)?;
if began.world_id != world.world_id {
return Err(CallRecordError::RunMismatch(RunField::WorldId));
}
if began.state_digest != world.state_digest {
return Err(CallRecordError::RunMismatch(RunField::StateDigest));
}
Ok(Self {
caller_runtime_id: caller_runtime_id.into(),
pending: Mutex::new(store.records(run)?.into()),
})
}
}
#[async_trait]
impl InferencePort for ReplayInferencePort {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
PreparedInference::prepare(
&self.caller_runtime_id,
unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64),
request,
)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
let mut pending = self
.pending
.lock()
.map_err(|_| InferenceFault::integrity_violation("the replay queue was poisoned"))?;
let digest = content_digest(&request.invocation.request)?;
let Some(next) = pending.front() else {
return Err(InferenceFault::integrity_violation(
"replay has no recorded call left",
));
};
if next.content_sha256 != digest {
return Err(InferenceFault::integrity_violation(
"the request is not the next recorded call",
));
}
let output = next.output();
pending.pop_front();
Ok(output)
}
}
#[cfg(test)]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,144 @@
//! The canonical Aetheria verse world's genesis.
//!
//! One intent lowers to one `CreateWorld`: a commons, every grammar verb
//! declared as an affordance, and each Aetheria faction as an institution
//! imported by its record key. The world is bound to the catalog's grammar, so
//! the kernel refuses any affordance the grammar does not carry.
//!
//! Phase A verbs record the act and change no component: an outcome band with
//! no effects, and the act carried as the utterance that makes an entry
//! admissible. Ghostlight owns each verb's lowering to kernel effects (ruling
//! `verb-effects-ghostlight`), and those arrive with phase B.
use crate::aetheria::AetheriaCatalog;
use crate::mailbox::{MailboxError, commons_declaration, commons_ref};
use crate::patch::{
AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EvidenceRef,
FactDeclaration, FactStandingRef, OutcomeBand, Precondition, Ref, Statement, SubjectDeclaration,
kernel_speak_entry, kernel_speak_grant,
};
use crate::{
CommandId, CreateWorld, LensWeights, NewController, PrincipalId, SubjectKind,
WorldPatch, WorldScaleIntentRef,
};
use std::collections::BTreeMap;
const COMMIT_LEN: usize = 40;
/// What a caller states to create the canonical verse world. Everything else a
/// world needs (the commons, the subjects, the affordances, their grants and
/// the provenance of what is known) is derived from the catalog.
#[derive(Clone, Debug)]
pub struct CreateVerseWorldIntent {
pub id: CommandId,
pub title: String,
pub brief: String,
pub catalog: AetheriaCatalog,
/// The Aetheria commit the catalog was read at: 40 lower-case hex digits.
/// It is the provenance of every fact the world holds about a faction.
pub aetheria_commit: String,
pub lens_weights: LensWeights,
pub targets: BTreeMap<SubjectKind, u32>,
}
#[derive(Debug, thiserror::Error)]
pub enum VerseGenesisError {
#[error("aetheria_commit is not 40 lower-case hex digits")]
NotACommit,
#[error(transparent)]
Mailbox(#[from] MailboxError),
}
impl CreateVerseWorldIntent {
/// The one lowering. The kernel supplies the `speak` entry at genesis and
/// holds it to the grammar, so it is granted here and never declared.
pub(crate) fn lower(self, owner: PrincipalId) -> Result<CreateWorld, VerseGenesisError> {
let commit = &self.aetheria_commit;
if commit.len() != COMMIT_LEN
|| !commit
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(VerseGenesisError::NotACommit);
}
let speak = kernel_speak_entry().kind;
let mut grants = kernel_speak_grant();
let mut declarations = vec![commons_declaration()];
for (kind, verb) in self.catalog.grammar.verbs() {
if kind == speak.0 {
continue;
}
let handle = DraftHandle::new(format!("verb-{kind}"));
grants.insert(Ref::Draft(handle.clone()));
declarations.push(Declaration::Affordance(AffordanceDeclaration {
handle,
kind: AffordanceKindName(kind.to_owned()),
roles: verb.role_specs(),
preconditions: vec![Precondition::CanBroadcast {
via: AudienceSpec::Colocated,
}],
effect_slots: Vec::new(),
outcome_bands: vec![OutcomeBand {
weight: 1,
effects: Vec::new(),
}],
// The kernel refuses an entry that can neither change a
// component nor speak, and a speaking entry needs an audience,
// so a phase A verb is its own utterance to the room: the act
// is recorded as speech and nothing else changes.
carries_speech: true,
}));
}
let mut evidence = Vec::new();
for (position, faction) in self.catalog.factions.iter().enumerate() {
declarations.push(Declaration::Subject(SubjectDeclaration {
handle: DraftHandle::new(format!("faction-{position}")),
label: faction.name.trim().to_owned(),
kind: SubjectKind::Institution,
controller: NewController::OperationalAgent,
affordances: grants.clone(),
position: Some(commons_ref()),
import_key: Some(faction.key.clone()),
}));
// A faction with no description has nothing to state.
if let Some(statement) = Statement::new(faction.description.trim()) {
let receipt = EvidenceRef::new(format!(
"aetheria:{commit}:{}/{}",
faction.key.schema(),
faction.key.record()
));
evidence.push(receipt.clone());
declarations.push(Declaration::Fact(FactDeclaration {
handle: DraftHandle::new(format!("fact-{position}")),
label: faction.name.trim().to_owned(),
statement,
standing: FactStandingRef::Canonical { evidence: receipt },
}));
}
}
Ok(CreateWorld {
id: self.id,
owner,
title: self.title,
brief: self.brief,
patch: WorldPatch {
declarations,
operations: Vec::new(),
evidence,
},
scale_intent: WorldScaleIntentRef {
targets: self.targets,
jurisdictions: BTreeMap::new(),
},
lens_weights: self.lens_weights,
grammar: Some(self.catalog.grammar),
era: None,
})
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,477 @@
use super::*;
use crate::aetheria::read_aetheria_catalog;
use crate::patch::{FactStanding, Mismatch};
use crate::tests::{auth_principal, owner, stock_weights};
use crate::{
CommandBody, ControllerMode, GrammarBinding, GrammarReferentKind, GrammarRole, GrammarVerb,
KernelError, PrincipalCommandIntent, RenderPath, VerifiedPrincipalEvidence, WorldKernel,
WorldMailbox, WorldPhase,
};
use chrono::{Duration, Utc};
use std::collections::BTreeSet;
/// Aetheria master when the fixture catalog was written.
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
const OTHER_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
const FIXTURE: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/aetheria-verse-catalog.cc"
);
fn catalog() -> AetheriaCatalog {
read_aetheria_catalog(FIXTURE).unwrap()
}
fn intent_of(catalog: AetheriaCatalog, commit: &str) -> CreateVerseWorldIntent {
CreateVerseWorldIntent {
id: CommandId::new(),
title: "The Verse".into(),
brief: "Aetheria.".into(),
catalog,
aetheria_commit: commit.into(),
lens_weights: stock_weights(),
targets: BTreeMap::new(),
}
}
/// A world created through the kernel from the lowering, for what the
/// snapshot hides: the facts' evidence.
fn kernel_of(intent: CreateVerseWorldIntent) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
let dir = tempfile::tempdir().unwrap();
let world = intent.lower(owner()).unwrap();
let result = WorldKernel::create(dir.path().join("world.cc"), world, &auth_principal(owner()))
.map(|(kernel, _)| kernel);
(dir, result)
}
struct Verse {
_dir: tempfile::TempDir,
_task: tokio::task::JoinHandle<()>,
mailbox: WorldMailbox,
principal: VerifiedPrincipalEvidence,
receipt: crate::CreationReceipt,
}
async fn verse(intent: CreateVerseWorldIntent) -> Verse {
let dir = tempfile::tempdir().unwrap();
let (mailbox, task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
let receipt = mailbox.create_verse(intent, &principal).await.unwrap();
Verse {
_dir: dir,
_task: task,
mailbox,
principal,
receipt,
}
}
#[tokio::test]
async fn verse_genesis_from_the_aetheria_fixture() {
let catalog = catalog();
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
// One institution per faction, keyed by its record, named by its Name.
let mut factions: Vec<_> = snapshot
.subjects
.iter()
.map(|subject| {
(
subject.import_key.clone().unwrap(),
subject.label.clone(),
subject.kind,
subject.controller_mode,
)
})
.collect();
factions.sort_by(|a, b| a.0.cmp(&b.0));
let expected: Vec<_> = catalog
.factions
.iter()
.map(|faction| {
(
faction.key.clone(),
faction.name.clone(),
SubjectKind::Institution,
Some(ControllerMode::OperationalAgent),
)
})
.collect();
assert_eq!(factions.len(), 2);
assert_eq!(factions, expected);
// One fact per faction, carrying its description.
let statements: BTreeSet<_> = snapshot
.facts
.iter()
.map(|fact| fact.statement.as_str().to_owned())
.collect();
assert_eq!(
statements,
catalog
.factions
.iter()
.map(|faction| faction.description.clone())
.collect::<BTreeSet<_>>()
);
// The world is bound to the catalog's grammar.
assert_eq!(snapshot.grammar, Some(catalog.grammar.identity()));
assert_eq!(verse.receipt.world_id, snapshot.world_id);
// Every faction stands in the one commons.
let commons: Vec<_> = snapshot
.places
.iter()
.filter(|place| place.label == "The Commons")
.collect();
assert_eq!(commons.len(), 1);
assert!(
snapshot
.subjects
.iter()
.all(|subject| subject.position == Some(commons[0].id))
);
}
#[test]
fn each_fact_cites_its_faction_record_and_the_commit_it_was_read_at() {
for commit in [COMMIT, OTHER_COMMIT] {
let (_dir, kernel) = kernel_of(intent_of(catalog(), commit));
let kernel = kernel.unwrap();
let evidence: BTreeSet<String> = kernel
.state
.facts
.values()
.map(|fact| match &fact.standing {
FactStanding::Canonical { evidence } => evidence.text().to_owned(),
other => panic!("a verse fact is canonical, not {other:?}"),
})
.collect();
assert_eq!(
evidence,
catalog()
.factions
.iter()
.map(|faction| format!(
"aetheria:{commit}:aetheria.faction/{}",
faction.key.record()
))
.collect::<BTreeSet<_>>()
);
}
}
#[test]
fn a_commit_is_forty_lower_case_hex_digits() {
for bad in [
"",
&COMMIT[..39],
&format!("{COMMIT}0"),
&COMMIT.to_uppercase(),
&format!("{}g", &COMMIT[..39]),
] {
assert!(
matches!(
intent_of(catalog(), bad).lower(owner()),
Err(VerseGenesisError::NotACommit)
),
"{bad:?}"
);
}
assert!(intent_of(catalog(), COMMIT).lower(owner()).is_ok());
assert!(!VerseGenesisError::NotACommit.to_string().contains(COMMIT));
}
#[test]
fn verse_genesis_refuses_a_duplicate_faction_record() {
let mut twice = catalog();
let first = twice.factions[0].clone();
twice.factions.push(first);
// The lowering does not decide: it declares all three.
let world = intent_of(twice.clone(), COMMIT).lower(owner()).unwrap();
let subjects = world
.patch
.declarations
.iter()
.filter(|declaration| matches!(declaration, Declaration::Subject(_)))
.count();
assert_eq!(subjects, 3);
let (_dir, kernel) = kernel_of(intent_of(twice, COMMIT));
let Err(KernelError::PatchRejected(set)) = kernel else {
panic!("a second faction under one record key was admitted");
};
assert!(
set.iter()
.any(|mismatch| matches!(mismatch, Mismatch::DuplicateImportKey { .. })),
"{set:?}"
);
}
#[tokio::test]
async fn every_granted_affordance_is_a_grammar_verb() {
let catalog = catalog();
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
let mut kinds: Vec<_> = snapshot
.affordances
.iter()
.map(|affordance| affordance.entry.kind.0.clone())
.collect();
kinds.sort();
// Each verb once: the kernel's speak is the grammar's speak.
assert_eq!(
kinds,
catalog
.grammar
.verbs()
.map(|(kind, _)| kind.to_owned())
.collect::<Vec<_>>()
);
assert!(kinds.contains(&"speak".to_owned()));
// Each has its render path from the grammar, and phase A changes nothing.
for affordance in &snapshot.affordances {
let verb = catalog.grammar.verb(&affordance.entry.kind.0).unwrap();
assert_eq!(affordance.render_path, Some(verb.render_path));
assert!(affordance.entry.effect_slots.is_empty());
assert_eq!(affordance.entry.outcome_bands.len(), 1);
assert!(affordance.entry.outcome_bands[0].effects.is_empty());
}
// Every faction is granted every verb.
let all: BTreeSet<_> = snapshot.affordances.iter().map(|a| a.id).collect();
for subject in &snapshot.subjects {
assert_eq!(subject.affordances, all);
}
}
#[tokio::test]
async fn factions_get_opportunities() {
let verse = verse(intent_of(catalog(), COMMIT)).await;
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let revision = verse.mailbox.snapshot().await.unwrap().revision;
verse
.mailbox
.submit_principal(
PrincipalCommandIntent {
id: CommandId::new(),
world_id: verse.receipt.world_id,
expected_revision: revision,
body,
},
&verse.principal,
)
.await
.unwrap();
}
let snapshot = verse.mailbox.snapshot().await.unwrap();
assert_eq!(snapshot.phase, WorldPhase::Active);
assert_eq!(snapshot.opportunities.len(), catalog().factions.len());
let scopes: BTreeSet<_> = snapshot.opportunities.iter().map(|o| o.scope).collect();
assert_eq!(scopes.len(), snapshot.opportunities.len());
for opportunity in &snapshot.opportunities {
assert_eq!(opportunity.controller_mode, ControllerMode::OperationalAgent);
assert_eq!(opportunity.affordance_ids.len(), snapshot.affordances.len());
}
}
#[test]
fn a_faction_without_a_description_holds_no_fact() {
let mut bare = catalog();
bare.factions[0].description = " ".into();
bare.factions[1].description = " Second. ".into();
let (_dir, kernel) = kernel_of(intent_of(bare, COMMIT));
let facts: Vec<_> = kernel
.unwrap()
.state
.facts
.values()
.map(|fact| fact.statement.as_str().to_owned())
.collect();
assert_eq!(facts, vec!["Second.".to_owned()]);
}
#[test]
fn a_grammar_the_kernel_speak_cannot_live_in_refuses_genesis() {
let mut mute = catalog();
mute.grammar = GrammarBinding::new(
"aetheria.verse_grammar",
1,
[(
"haul".to_owned(),
GrammarVerb {
render_path: RenderPath::ShipAction,
roles: vec![GrammarRole {
role: "cargo".into(),
referent: GrammarReferentKind::Cargo,
}],
},
)],
)
.unwrap();
let (_dir, kernel) = kernel_of(intent_of(mute, COMMIT));
let Err(KernelError::PatchRejected(set)) = kernel else {
panic!("a world whose grammar has no speak was admitted");
};
assert!(
set.iter()
.any(|mismatch| matches!(mismatch, Mismatch::AffordanceKindNotInGrammar { .. })),
"{set:?}"
);
}
#[tokio::test]
async fn the_dungeon_ingress_still_creates_an_unbound_world() {
let dir = tempfile::tempdir().unwrap();
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("dungeon-owner", Utc::now() + Duration::hours(1));
mailbox
.create(
crate::CreateWorldIntent {
id: CommandId::new(),
title: "Dungeon".into(),
brief: String::new(),
human_subject_label: "Player".into(),
narrative_persona_label: None,
operational_agent_label: None,
targets: BTreeMap::new(),
jurisdictions: Vec::new(),
lens_weights: stock_weights(),
era: None,
},
&principal,
)
.await
.unwrap();
let snapshot = mailbox.snapshot().await.unwrap();
assert_eq!(snapshot.grammar, None);
assert!(
snapshot
.places
.iter()
.any(|place| place.label == "The Commons")
);
}
#[tokio::test]
async fn a_faction_name_is_trimmed_into_its_institution_label() {
let mut padded = catalog();
let expected = padded.factions[0].name.trim().to_owned();
padded.factions[0].name = format!(" {expected}\t ");
let key = padded.factions[0].key.clone();
let verse = verse(intent_of(padded, COMMIT)).await;
let snapshot = verse.mailbox.snapshot().await.unwrap();
let subject = snapshot
.subjects
.iter()
.find(|subject| subject.import_key.as_ref() == Some(&key))
.expect("the padded faction was created");
assert_eq!(subject.label, expected);
}
#[tokio::test]
async fn genesis_twice_with_one_intent_is_one_creation() {
let dir = tempfile::tempdir().unwrap();
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
let principal =
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
let intent = intent_of(catalog(), COMMIT);
let first = mailbox.create_verse(intent.clone(), &principal).await.unwrap();
let before = mailbox.snapshot().await.unwrap();
let again = mailbox.create_verse(intent, &principal).await.unwrap();
let after = mailbox.snapshot().await.unwrap();
assert_eq!(again, first);
assert_eq!(after.revision, before.revision);
assert_eq!(after.state_digest, before.state_digest);
assert_eq!(after.subjects.len(), before.subjects.len());
}
#[tokio::test]
async fn genesis_under_another_command_id_finds_the_world_occupied() {
let verse = verse(intent_of(catalog(), COMMIT)).await;
let before = verse.mailbox.snapshot().await.unwrap();
let refused = verse
.mailbox
.create_verse(intent_of(catalog(), COMMIT), &verse.principal)
.await;
assert!(
matches!(
refused,
Err(VerseGenesisError::Mailbox(MailboxError::Kernel(
KernelError::CreationTargetOccupied
)))
),
"{refused:?}"
);
let after = verse.mailbox.snapshot().await.unwrap();
assert_eq!(after.revision, before.revision);
assert_eq!(after.state_digest, before.state_digest);
}
/// Pins the standing phase A behaviour (ruling `ship-acts-speech-shaped-phase-a`):
/// the lowering admits a ship verb only as an utterance,
/// and committing it asserts a claim fact the room hears.
#[test]
fn phase_a_ship_verbs_are_spoken_acts_in_the_room() {
use crate::tests::{command, opportunity_for, spoken, submit_owner};
use crate::{
AuthenticatedCaller, CallerId, DecisionInvocation, Role, RoleBinding, SubmitReceipt,
Target,
};
let (_scratch, kernel) = kernel_of(intent_of(catalog(), COMMIT));
let mut kernel = kernel.unwrap();
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
let snapshot = kernel.snapshot().unwrap();
submit_owner(&mut kernel, &snapshot, body);
}
let active = kernel.snapshot().unwrap();
let attack = active
.affordances
.iter()
.find(|a| a.entry.kind.0 == "attack")
.unwrap()
.id;
let [first, second] = [&active.subjects[0], &active.subjects[1]];
let opportunity = opportunity_for(&active, first.id);
let caller = CallerId::Controller(opportunity.controller_id);
let invocation = |speech: Option<&str>| DecisionInvocation {
affordance: attack,
bindings: vec![RoleBinding {
role: Role("target".into()),
target: Target::Subject(second.id),
}],
proposed: Vec::new(),
speech: speech.map(|text| crate::patch::Statement::new(text).unwrap()),
display: None,
};
let try_it = |kernel: &mut WorldKernel, speech: Option<&str>| {
kernel.submit(
command(
&active,
CommandId::new(),
caller.clone(),
CommandBody::ExerciseDecision {
opportunity: opportunity.clone(),
invocation: invocation(speech),
},
),
&AuthenticatedCaller::fixture(caller.clone()),
)
};
// Without an utterance the act is refused: the verb has no other way in.
assert!(try_it(&mut kernel, None).is_err());
// With one, the act commits and its words are a claim fact.
let receipt = try_it(&mut kernel, Some("We strike.")).expect("the attack commits");
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
let event = kernel.state.events.last().unwrap();
assert_eq!(spoken(&kernel.state, event), Some("We strike."));
}

View file

@ -0,0 +1,20 @@
//! The Aetheria verse run's own organs. The verse binary sits above this
//! module; here sit the parts of a run that belong to the library: the record
//! of every provider call and the spend it implies, the genesis of the
//! canonical verse world, and the manual run that advances it with its record.
mod calls;
mod genesis;
mod run;
pub use genesis::{CreateVerseWorldIntent, VerseGenesisError};
pub use calls::{
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, Lane, LaneTokens, NodeSpend,
ProviderCallRecord, RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart,
WaveSpend,
};
pub use run::{
RUN_RECORD_SCHEMA, RecordedKnobs, RunClaim, RunOutcome, RunStatus,
TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
call_run_id, run_manual,
};

View file

@ -0,0 +1,922 @@
//! The manual verse run: the tick driver and its record.
//!
//! One invocation advances the world tick by tick. A tick reads the world,
//! opens (or finds open) its tick document, which freezes one planned wave
//! (`plan_wave` over the derived hierarchy, with no focus), runs the frozen
//! cells through the wave runner (`run_frozen_cells`), advances the clock once
//! by the frozen span, and checkpoints. The driver owns the order of those
//! steps and nothing else: the planner chooses nodes and cells, cells decide
//! what factions do, the recording port owns spend, the kernel owns time.
//!
//! A tick is named by the world's clock-advance count, never by `now`. The
//! resume point is the open tick document (world, ordinal), written before the
//! tick's first cell and read by any later run: it froze the span, the knobs
//! and the cells (each with its node and distance) when the tick opened, so a
//! run under another span or knobs finishes the open tick as it was opened and
//! applies its own config from the next tick it opens. A tick whose cells did not all finish never
//! advances the clock, so the same ordinal, cells and command ids come back,
//! the controller-work rows pick up where they stopped, and the kernel answers
//! every re-submission with the original receipt. A run record reports a run
//! and is never read to resume one.
//!
//! A run starts only when it is invoked: nothing here waits, schedules or
//! repeats.
use super::calls::{RecordingInferencePort, WaveSpend, canonical};
use crate::cover::TickIndex;
use crate::wave::{
Deferral, DeferredNode, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, NodeReport, Refusal,
RefusalReason, UnattributedCall, WaveClock, WaveStop, act_line, acts_since,
deferred_nodes, node_reports, plan_wave, run_frozen_cells,
};
use crate::{
AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError,
NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox,
WorldSnapshot,
};
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, ops::ControlFlow, path::Path, sync::Mutex};
use thiserror::Error;
/// The run record document's schema.
pub const RUN_RECORD_SCHEMA: &str = "ghostlight.verse_run.v2";
const RUN_ROW: &str = "verse_run.v2";
/// The tick document's schema.
pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v3";
const TICK_ROW: &str = "verse_tick.v3";
/// The schemas later ones replaced. No store holding one is read: the verse store
/// has never held a live run, so there is no migration, and a retired row is
/// refused by name.
const RETIRED_SCHEMAS: [&str; 3] = [
"ghostlight.verse_run.v1",
"ghostlight.verse_tick.v1",
"ghostlight.verse_tick.v2",
];
const CLOCK_NAMESPACE: &str = "ghostlight.verse.clock";
/// Why a run could not be recorded or started. Every variant names a kind of
/// fault; none carries a value the run held.
#[derive(Debug, Error)]
pub enum VerseRunError {
#[error("the run record store could not be read or written")]
Store,
#[error("the run record store holds a row that is not a canonical run record")]
Corrupt,
#[error("a run record's sequence is not an existing run or the next in its world")]
OutOfSequence,
#[error("the recording port belongs to another run")]
PortNotThisRun,
#[error("the run's configuration is not the one its claim recorded")]
ConfigNotThisClaim,
#[error("the world is not at the revision its claim was made from")]
WorldMovedSinceClaim,
#[error("the knobs are not valid: {0}")]
Knobs(#[from] GestaltKnobsError),
#[error("the run store holds a row of a retired schema (v1 run or tick); it is not migrated")]
RetiredSchema,
#[error(transparent)]
Mailbox(#[from] MailboxError),
}
/// Where a run stands. `Running` is only ever the record of a run in flight,
/// or of one whose process died before it could say how it ended.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum RunStatus {
Running,
Completed,
/// A provider call could pass the token cap, so the run ended before the
/// open tick's clock advance.
BudgetExhausted,
/// The run ended without finishing its open tick. `reason` is a fixed code
/// naming the kind of fault, never a value.
Failed {
reason: String,
},
/// The caller asked the run to end after a finished tick.
Stopped,
}
/// A tick as the run left it. A closed tick has all its cells run and the
/// clock advanced by the tick's frozen span. The tick a run ended inside is
/// recorded too, unclosed, so what its cells committed is not lost; a later
/// run finds that tick's document open and works in it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TickCheckpoint {
/// The tick's ordinal, as its tick document names it.
pub tick: u64,
pub closed: bool,
pub cells: u32,
/// Every command the tick's cells hold a receipt for, in cell order. A
/// decline is a commit, so it is listed.
pub committed: Vec<CommandId>,
pub refusals: Vec<Refusal>,
/// The calls grouped cells received that named no handle, in cell order.
pub unattributed: Vec<UnattributedCall>,
/// Tokens the recording port charged during the tick.
pub tokens: u64,
}
/// The knobs as a record carries them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordedKnobs {
/// Band periods in fictional minutes, by distance.
pub bands: Vec<u32>,
pub depth: u8,
pub max_node_turns: u16,
pub cells: u16,
pub constituent_cap: u16,
pub urgency_slots: u16,
}
impl RecordedKnobs {
pub fn of(knobs: &GestaltKnobs) -> Self {
Self {
bands: knobs.bands.iter().map(|band| band.minutes()).collect(),
depth: knobs.depth,
max_node_turns: knobs.max_node_turns,
cells: knobs.cover.cells,
constituent_cap: knobs.cover.constituent_cap,
urgency_slots: knobs.cover.urgency_slots,
}
}
}
/// What closed a tick.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TickClose {
/// The run with this sequence submitted the tick's clock advance.
Clock { run: u64 },
/// A later run found the world's ordinal past the tick with the document
/// still open: its clock landed and the close was lost, or another clock
/// writer moved time.
World,
}
/// What a tick decided when it opened. Document `ghostlight.verse_tick.v3`,
/// keyed (world, ordinal). Written once before the tick's first cell, closed
/// once, never reopened or deleted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerseTick {
pub world_id: WorldId,
pub ordinal: u64,
pub opened_now: u64,
pub opened_revision: u64,
pub span_minutes: u32,
pub knobs: RecordedKnobs,
pub oversubscribed: bool,
pub cells: Vec<FrozenCell>,
/// The nodes the plan left out, with why: not due, or past the node-turn
/// bound. Written with the cells so a resumed tick reports what its wave
/// left out, not what a re-plan would.
pub deferred: Vec<(NodeId, Deferral)>,
pub opened_by_run: u64,
pub closed: Option<TickClose>,
}
/// One invocation of the verse runner: what it was asked, what it did.
/// Document `ghostlight.verse_run.v2`, keyed (world, run sequence).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerseRunRecord {
pub world_id: WorldId,
pub sequence: u64,
pub token_cap: u64,
pub ticks_requested: u32,
pub tick_span_minutes: u32,
pub knobs: RecordedKnobs,
/// The world's revision when the run began.
pub start_revision: u64,
pub checkpoints: Vec<TickCheckpoint>,
pub status: RunStatus,
}
impl VerseRunRecord {
/// The ticks this run finished: every cell run and the clock advanced.
pub fn ticks_closed(&self) -> usize {
self.checkpoints.iter().filter(|c| c.closed).count()
}
}
/// What a caller asks of one run. The token cap is not here: the recording
/// port owns it.
#[derive(Clone, Debug)]
pub struct VerseRunConfig {
pub ticks: u32,
pub tick_span: TickMinutes,
pub knobs: GestaltKnobs,
}
/// A tick as the operator reads it, including the one a run ended inside.
#[derive(Clone, Debug)]
pub struct TickReport {
pub checkpoint: TickCheckpoint,
/// The tick's nodes in run order, each with its acts and refusals.
pub nodes: Vec<NodeReport>,
/// The labels of the subjects the checkpoint's refusals name, from the
/// snapshot the tick opened on.
pub labels: BTreeMap<SubjectId, String>,
/// What this invocation's calls for the tick's cells cost, by lane and node.
pub spend: WaveSpend,
/// Nodes that took no turn this tick, and why: the plan left them out, or
/// the window's allowance ran out first.
pub deferred: Vec<DeferredNode>,
pub spent: u64,
pub remaining: u64,
}
impl TickReport {
/// Every act the tick committed, grouped by node in run order.
pub fn acts(&self) -> impl Iterator<Item = &OperatorEvent> {
self.nodes.iter().flat_map(|node| node.acts.iter())
}
}
impl std::fmt::Display for RunStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Running => f.write_str("Running"),
Self::Completed => f.write_str("Completed"),
Self::BudgetExhausted => f.write_str("BudgetExhausted"),
Self::Failed { reason } => write!(f, "Failed ({reason})"),
Self::Stopped => f.write_str("Stopped"),
}
}
}
/// The tick as the operator reads it: a header, then per node its label,
/// distance and spend, one line per committed act (who, which verb, how it
/// renders, what its roles are bound to, what was said or shown) and one per
/// refusal, then the spend.
impl std::fmt::Display for TickReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let checkpoint = &self.checkpoint;
writeln!(
f,
"tick {} {}: {} cells, {} acts, {} refused",
checkpoint.tick,
if checkpoint.closed { "closed" } else { "open" },
checkpoint.cells,
self.acts().count(),
checkpoint.refusals.len()
)?;
for node in &self.nodes {
match node.distance {
Some(distance) => {
writeln!(f, " node {} (distance {distance}): {} tokens", node.label, node.spent)?
}
None => writeln!(f, " node {}: {} tokens", node.label, node.spent)?,
}
for act in &node.acts {
writeln!(f, " {}", act_line(act))?;
}
for refusal in &node.refusals {
let reason = match refusal.reason {
RefusalReason::Interrupted => "interrupted",
RefusalReason::WorldRejected => "world_rejected",
RefusalReason::OpportunityGone => "opportunity_gone",
RefusalReason::ScopeMoved => "scope_moved",
RefusalReason::ProposalUndecodable => "proposal_undecodable",
RefusalReason::RowDisagreesWithCell => "row_disagrees_with_cell",
RefusalReason::CallUnattributed => "call_unattributed",
};
let label = self.labels.get(&refusal.subject).map_or("-", String::as_str);
writeln!(f, " refused: cell {} {label} {reason}", refusal.cell)?;
}
}
for call in &checkpoint.unattributed {
writeln!(f, " note: cell {} call names no handle: tool {:?}", call.cell, call.tool)?;
}
for (reason, name) in [
(Deferral::NotDue, "not due"),
(Deferral::OverBound, "over the node-turn bound"),
(Deferral::Allowance, "past the allowance"),
] {
let labels: Vec<&str> = self
.deferred
.iter()
.filter(|node| node.reason == reason)
.map(|node| node.label.as_str())
.collect();
if !labels.is_empty() {
writeln!(f, " deferred ({name}): {}", labels.join(", "))?;
}
}
writeln!(
f,
" tokens: {} this tick, {} spent, {} remaining",
checkpoint.tokens, self.spent, self.remaining
)
}
}
#[derive(Clone, Debug)]
pub struct RunOutcome {
pub record: VerseRunRecord,
}
fn row_key(world: WorldId, sequence: u64) -> String {
format!("{}/{sequence:020}", world.key())
}
fn tick_key(world: WorldId, ordinal: u64) -> String {
format!("{}/{ordinal:020}", world.key())
}
fn tick_row(tick: &VerseTick) -> Result<CultCacheEnvelope, VerseRunError> {
Ok(CultCacheEnvelope {
key: tick_key(tick.world_id, tick.ordinal),
r#type: TICK_ROW.into(),
payload: rmp_serde::to_vec_named(tick).map_err(|_| VerseRunError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(TICK_RECORD_SCHEMA.into()),
})
}
fn run_row(record: &VerseRunRecord) -> Result<CultCacheEnvelope, VerseRunError> {
Ok(CultCacheEnvelope {
key: row_key(record.world_id, record.sequence),
r#type: RUN_ROW.into(),
payload: rmp_serde::to_vec_named(record).map_err(|_| VerseRunError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(RUN_RECORD_SCHEMA.into()),
})
}
/// A run's number and cap, claimed from the run store before anything of the
/// run exists. The call ledger's run id derives from it ([`call_run_id`]), and
/// [`run_manual`] runs only the record it names. Not `Clone`: a claim runs once
/// or is abandoned.
#[derive(Debug)]
pub struct RunClaim {
world_id: WorldId,
sequence: u64,
token_cap: u64,
}
impl RunClaim {
/// The run's number, the one [`call_run_id`] names.
pub fn sequence(&self) -> u64 {
self.sequence
}
}
/// Every row of the file, split by type.
struct Rows {
runs: Vec<VerseRunRecord>,
ticks: Vec<VerseTick>,
}
/// Run records and tick documents in one CultCache file. A run is claimed
/// when it begins and saved again each time it moves, so a row is replaced by
/// its own later state. A tick is opened once and closed once, and only by the tick
/// driver: the writers are private to this module.
///
/// ```compile_fail
/// fn wedge(store: &ghostlight::VerseRunStore, world: ghostlight::WorldId) {
/// store.close_ticks_before(world, 1).unwrap();
/// }
/// ```
pub struct VerseRunStore {
store: Mutex<OwnedRedbMessagePackBackingStore>,
}
impl VerseRunStore {
/// Opens the file, creating it empty when absent. Every row must be a
/// canonical run record of this schema under its own key.
pub fn open(path: impl AsRef<Path>) -> Result<Self, VerseRunError> {
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
.map_err(|_| VerseRunError::Store)?;
store
.validate_path_identity()
.map_err(|_| VerseRunError::Store)?;
let opened = Self {
store: Mutex::new(store),
};
opened.records()?;
Ok(opened)
}
fn records(&self) -> Result<Rows, VerseRunError> {
let rows = self
.store
.lock()
.map_err(|_| VerseRunError::Store)?
.pull_all()
.map_err(|_| VerseRunError::Store)?;
let mut runs = Vec::new();
let mut ticks = Vec::new();
for row in &rows {
match (row.r#type.as_str(), row.schema_id.as_deref()) {
(RUN_ROW, Some(RUN_RECORD_SCHEMA)) => {
let record: VerseRunRecord =
canonical(row).map_err(|_| VerseRunError::Corrupt)?;
if row.key != row_key(record.world_id, record.sequence)
|| record.sequence == 0
{
return Err(VerseRunError::Corrupt);
}
runs.push(record);
}
(TICK_ROW, Some(TICK_RECORD_SCHEMA)) => {
let tick: VerseTick = canonical(row).map_err(|_| VerseRunError::Corrupt)?;
if row.key != tick_key(tick.world_id, tick.ordinal) {
return Err(VerseRunError::Corrupt);
}
ticks.push(tick);
}
(_, Some(schema)) if RETIRED_SCHEMAS.contains(&schema) => {
return Err(VerseRunError::RetiredSchema);
}
_ => return Err(VerseRunError::Corrupt),
}
}
runs.sort_by_key(|record| (record.world_id.key(), record.sequence));
ticks.sort_by_key(|tick| (tick.world_id.key(), tick.ordinal));
Ok(Rows { runs, ticks })
}
/// The sequence the next claim of this world takes. Sequences count from
/// one. Private: a caller never chooses a run's number, `claim` does.
fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
Ok(self
.records()?
.runs
.iter()
.filter(|record| record.world_id == world)
.map(|record| record.sequence)
.max()
.unwrap_or(0)
+ 1)
}
/// Every run of the world, in sequence.
pub fn runs(&self, world: WorldId) -> Result<Vec<VerseRunRecord>, VerseRunError> {
Ok(self
.records()?
.runs
.into_iter()
.filter(|record| record.world_id == world)
.collect())
}
/// The tick document of (world, ordinal), when one was opened.
pub fn tick(&self, world: WorldId, ordinal: u64) -> Result<Option<VerseTick>, VerseRunError> {
Ok(self
.records()?
.ticks
.into_iter()
.find(|tick| tick.world_id == world && tick.ordinal == ordinal))
}
/// Writes a tick document that does not exist yet, open. The store's own
/// insert-if-absent decides, so two opens of one ordinal cannot both win.
/// Private: the tick driver is the only writer of tick rows.
fn open_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
if tick.closed.is_some() {
return Err(VerseRunError::OutOfSequence);
}
let row = tick_row(tick)?;
let inserted = self
.store
.lock()
.map_err(|_| VerseRunError::Store)?
.insert_entry_if_absent(row)
.map_err(|_| VerseRunError::Store)?;
if inserted {
Ok(())
} else {
Err(VerseRunError::OutOfSequence)
}
}
/// Closes an open tick document. Private, like every tick writer.
fn close_tick(
&self,
world: WorldId,
ordinal: u64,
close: TickClose,
) -> Result<(), VerseRunError> {
let Some(mut tick) = self.tick(world, ordinal)? else {
return Err(VerseRunError::OutOfSequence);
};
if tick.closed.is_some() {
return Err(VerseRunError::OutOfSequence);
}
tick.closed = Some(close);
self.put_tick(&tick)
}
/// Closes, as the world's, every open tick of the world below `ordinal`.
fn close_ticks_before(&self, world: WorldId, ordinal: u64) -> Result<(), VerseRunError> {
for mut tick in self.records()?.ticks {
if tick.world_id == world && tick.ordinal < ordinal && tick.closed.is_none() {
tick.closed = Some(TickClose::World);
self.put_tick(&tick)?;
}
}
Ok(())
}
fn put_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
let row = tick_row(tick)?;
self.store
.lock()
.map_err(|_| VerseRunError::Store)?
.push(&row)
.map_err(|_| VerseRunError::Store)
}
/// Claims the next run of the snapshot's world: writes its `Running`
/// record, with the cap and config it was claimed under, in one insert that
/// cannot overwrite a record. The returned claim is the only way to run it;
/// a claim that never runs stays `Running` (a process that died) or is
/// ended by [`abandon`](Self::abandon), and its number is never issued
/// again.
pub fn claim(
&self,
snapshot: &WorldSnapshot,
token_cap: u64,
config: &VerseRunConfig,
) -> Result<RunClaim, VerseRunError> {
config.knobs.validate()?;
let record = VerseRunRecord {
world_id: snapshot.world_id,
sequence: self.next_sequence(snapshot.world_id)?,
token_cap,
ticks_requested: config.ticks,
tick_span_minutes: config.tick_span.minutes(),
knobs: RecordedKnobs::of(&config.knobs),
start_revision: snapshot.revision,
checkpoints: Vec::new(),
status: RunStatus::Running,
};
self.insert_run(&record)?;
Ok(RunClaim {
world_id: record.world_id,
sequence: record.sequence,
token_cap,
})
}
/// Writes a run record that does not exist yet. The store's own
/// insert-if-absent decides, so two claims of one sequence cannot both win.
fn insert_run(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
let inserted = self
.store
.lock()
.map_err(|_| VerseRunError::Store)?
.insert_entry_if_absent(run_row(record)?)
.map_err(|_| VerseRunError::Store)?;
if inserted {
Ok(())
} else {
Err(VerseRunError::OutOfSequence)
}
}
/// Ends a claim that never ran: its record becomes `Failed { reason }`.
pub fn abandon(&self, claim: RunClaim, reason: &'static str) -> Result<(), VerseRunError> {
let mut record = self.claimed(&claim)?;
record.status = failed(reason);
self.save(&record)
}
/// The record a claim names.
fn claimed(&self, claim: &RunClaim) -> Result<VerseRunRecord, VerseRunError> {
self.records()?
.runs
.into_iter()
.find(|record| record.world_id == claim.world_id && record.sequence == claim.sequence)
.ok_or(VerseRunError::OutOfSequence)
}
/// Replaces a claimed record with its later state. A sequence with no
/// record is refused: only `claim` creates one.
fn save(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
self.claimed(&RunClaim {
world_id: record.world_id,
sequence: record.sequence,
token_cap: record.token_cap,
})?;
self.store
.lock()
.map_err(|_| VerseRunError::Store)?
.push(&run_row(record)?)
.map_err(|_| VerseRunError::Store)
}
}
enum TickEnd {
/// Every cell finished and the clock advanced.
Closed,
/// The run ends inside this tick with this status.
Open(RunStatus),
}
/// The run status a wave's stop ends the run with.
fn status_of(stop: WaveStop) -> RunStatus {
match stop {
WaveStop::Budget => RunStatus::BudgetExhausted,
WaveStop::Fault(code) => failed(code),
}
}
fn failed(reason: &str) -> RunStatus {
RunStatus::Failed {
reason: reason.to_owned(),
}
}
/// Runs `config.ticks` ticks from the world's present clock under the cap the
/// recording port was opened with. `observe` sees each tick as it ends,
/// including the one a run ends inside, and may stop the run after a finished
/// tick by breaking. `claim` is the run's number from
/// [`VerseRunStore::claim`]; the port must have been opened for it
/// ([`call_run_id`]) under the cap the claim recorded, and `config` is the one
/// the claim was made with. A claim this refuses is abandoned, so a refused
/// start binds nothing.
pub async fn run_manual(
mailbox: &WorldMailbox,
runner: &ControllerRunner,
port: &RecordingInferencePort,
store: &VerseRunStore,
claim: RunClaim,
config: &VerseRunConfig,
mut observe: impl FnMut(&TickReport) -> ControlFlow<()>,
) -> Result<RunOutcome, VerseRunError> {
let begun = match mailbox.snapshot().await {
Ok(begun) => begun,
Err(error) => {
store.abandon(claim, "world_unavailable")?;
return Err(error.into());
}
};
if port.run_id() != &call_run_id(claim.sequence)
|| port.cap() != claim.token_cap
|| begun.world_id != claim.world_id
{
store.abandon(claim, "port_not_this_run")?;
return Err(VerseRunError::PortNotThisRun);
}
let sequence = claim.sequence;
let mut record = store.claimed(&claim)?;
if config.knobs.validate().is_err() || !record_matches(&record, config) {
store.abandon(claim, "config_not_this_claim")?;
return Err(VerseRunError::ConfigNotThisClaim);
}
// The record names the revision the run started from, so the run starts
// from it.
if record.start_revision != begun.revision {
store.abandon(claim, "world_moved_since_claim")?;
return Err(VerseRunError::WorldMovedSinceClaim);
}
let mut spent_before = port.spent();
for completed in 0..config.ticks {
let (end, report) = run_tick(
mailbox,
runner,
port,
store,
sequence,
config,
spent_before,
|| mailbox.operator_log(),
)
.await;
spent_before = port.spent();
match end {
TickEnd::Open(status) => {
record.status = status;
if let Some(report) = report {
record.checkpoints.push(report.checkpoint.clone());
store.save(&record)?;
let _ = observe(&report);
} else {
store.save(&record)?;
}
return Ok(RunOutcome { record });
}
TickEnd::Closed => {
let report = report.expect("a closed tick has its report");
record.checkpoints.push(report.checkpoint.clone());
store.save(&record)?;
if observe(&report).is_break() && completed + 1 < config.ticks {
record.status = RunStatus::Stopped;
store.save(&record)?;
return Ok(RunOutcome { record });
}
}
}
}
record.status = RunStatus::Completed;
store.save(&record)?;
Ok(RunOutcome { record })
}
/// Whether the record a claim wrote was made under this config.
fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig) -> bool {
record.ticks_requested == config.ticks
&& record.tick_span_minutes == config.tick_span.minutes()
&& record.knobs == RecordedKnobs::of(&config.knobs)
}
/// The key a run's provider calls are recorded under: the run's sequence, so a
/// run record and its call records name each other.
pub fn call_run_id(sequence: u64) -> super::RunId {
super::RunId::new(&format!("run-{sequence}"))
.expect("a decimal sequence is a canonical run id")
}
/// The id of a tick's clock advance: the world and the ordinal, nothing the
/// run holds. A retry in the same tick has the same body and is answered
/// `AlreadyApplied`.
pub(crate) fn clock_command_id(world: WorldId, ordinal: u64) -> CommandId {
CommandId::derived(CLOCK_NAMESPACE, &[&world.text(), &ordinal.to_string()])
}
/// One tick. The report is absent only when the world or the tick document
/// could not be read at all.
async fn run_tick<ReadLog, Log>(
mailbox: &WorldMailbox,
runner: &ControllerRunner,
port: &RecordingInferencePort,
store: &VerseRunStore,
sequence: u64,
config: &VerseRunConfig,
spent_before: u64,
read_log: ReadLog,
) -> (TickEnd, Option<TickReport>)
where
ReadLog: FnOnce() -> Log,
Log: Future<Output = Result<Vec<OperatorEvent>, MailboxError>>,
{
let read = async {
let snapshot = mailbox.snapshot().await?;
let ordinal = mailbox.clock_advances().await?;
let opportunities = mailbox.opportunities().await?;
let graph = mailbox.agency_graph().await?;
let hierarchy = mailbox.hierarchy().await?;
Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph, hierarchy))
}
.await;
let Ok((snapshot, ordinal, opportunities, graph, hierarchy)) = read else {
return (TickEnd::Open(failed("world_unavailable")), None);
};
let world = snapshot.world_id;
let Ok(tick) = open_or_find(
store,
ordinal,
sequence,
config,
&snapshot,
&opportunities,
&graph,
&hierarchy,
) else {
return (TickEnd::Open(failed("run_store")), None);
};
let index = TickIndex(ordinal);
let Some(span) = TickMinutes::new(tick.span_minutes) else {
return (TickEnd::Open(failed("run_store")), None);
};
let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells).await;
let mut open = outcome.stop.map(status_of);
// The act listing is the tick's report to the operator: a tick whose log
// cannot be read is not closed, and the run ends there.
let acts = match acts_since(read_log().await, snapshot.revision) {
Some(acts) => acts,
None => {
open = Some(failed("operator_log_unavailable"));
Vec::new()
}
};
// So is a tick whose calls cannot be read back: its nodes' spend is the
// report's, and the ledger and the world must agree before time moves.
let spend = match port
.records()
.ok()
.and_then(|records| WaveSpend::of(&records, world, index, &tick.cells).ok())
{
Some(spend) => spend,
None => {
open = Some(failed("call_records_unavailable"));
WaveSpend::default()
}
};
if open.is_none() {
if mailbox
.submit_clock(clock_command_id(world, ordinal), span)
.await
.is_err()
{
open = Some(failed("clock_refused"));
} else if store
.close_tick(world, ordinal, TickClose::Clock { run: sequence })
.is_err()
{
open = Some(failed("run_store"));
}
}
let spent = port.spent();
let checkpoint_closed = open.is_none();
let mut checkpoint = TickCheckpoint {
tick: ordinal,
closed: checkpoint_closed,
cells: tick.cells.len() as u32,
committed: Vec::new(),
refusals: Vec::new(),
unattributed: Vec::new(),
tokens: spent.saturating_sub(spent_before),
};
for node in &outcome.nodes {
checkpoint.committed.extend(node.committed.iter().copied());
checkpoint.refusals.extend(node.refusals.iter().copied());
checkpoint.unattributed.extend(node.unattributed.iter().cloned());
}
let labels = checkpoint
.refusals
.iter()
.filter_map(|refusal| {
snapshot
.subjects
.iter()
.find(|subject| subject.id == refusal.subject)
.map(|subject| (refusal.subject, subject.label.clone()))
})
.collect();
let report = TickReport {
nodes: node_reports(&tick.cells, &outcome, acts, &spend, &snapshot, &hierarchy),
deferred: deferred_nodes(&tick.deferred, &tick.cells, &outcome, &snapshot, &hierarchy),
spend,
checkpoint,
labels,
spent,
remaining: port.cap().saturating_sub(spent),
};
(open.map_or(TickEnd::Closed, TickEnd::Open), Some(report))
}
/// The tick document for `ordinal`: the open one a run left, or a new one
/// frozen from a wave planned now over the derived hierarchy with no focus. An
/// open tick the world has moved past is closed as the world's first. A
/// document already closed at the world's current ordinal is a store that
/// disagrees with the world.
#[allow(clippy::too_many_arguments)]
fn open_or_find(
store: &VerseRunStore,
ordinal: u64,
sequence: u64,
config: &VerseRunConfig,
snapshot: &WorldSnapshot,
opportunities: &[DecisionOpportunity],
graph: &AgencyGraph,
hierarchy: &Hierarchy,
) -> Result<VerseTick, VerseRunError> {
let world = snapshot.world_id;
store.close_ticks_before(world, ordinal)?;
if let Some(tick) = store.tick(world, ordinal)? {
return if tick.closed.is_none() {
Ok(tick)
} else {
Err(VerseRunError::OutOfSequence)
};
}
let wave = plan_wave(
WaveClock {
world,
ordinal: TickIndex(ordinal),
now: FictionalMinutes(snapshot.now.0),
},
hierarchy,
opportunities,
graph,
&Focus::default(),
&[],
&config.knobs,
)?;
let tick = VerseTick {
world_id: world,
ordinal,
opened_now: snapshot.now.0,
opened_revision: snapshot.revision,
span_minutes: config.tick_span.minutes(),
knobs: RecordedKnobs::of(&config.knobs),
oversubscribed: wave.turns.iter().any(|turn| turn.oversubscribed),
cells: wave.frozen(),
deferred: wave.deferred,
opened_by_run: sequence,
closed: None,
};
store.open_tick(&tick)?;
Ok(tick)
}
#[cfg(test)]
mod tests;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -57,6 +57,7 @@ impl World {
// An external crate has no library fixture; it states its
// own weights, as every consumer must.
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Patina, 1)])),
era: None,
},
&principal,
)

Binary file not shown.

View file

@ -0,0 +1,16 @@
aetheria-verse-catalog.cc was written by Aetheria's own types, not by hand and not by Ghostlight.
Writer: tests/Aetheria.Shared.Tests/VerseGrammarTests.cs, WriteFixture (xunit test
Fixture_writer_is_deterministic_and_emits_what_the_grammar_reader_needs),
which authors VerseGrammar, three VerseVerb and two Faction records through
Aetheria's CultCache types and leaves the file at AETHERIA_VERSE_FIXTURE_PATH.
Aetheria: GameCult/Aetheria origin/master 92b82e9aa5bb422c568c4bfc85a8f641426a41fc
(contains aetheria-release cut verse-grammar, merged at 35af2930).
Command: AETHERIA_VERSE_FIXTURE_PATH=/tmp/aetheria-verse-catalog.cc
dotnet test tests/Aetheria.Shared.Tests
-p:CultLibRoot=<CultLib 45c2f40 clone> -p:CultMathRoot=<CultLib 252e226c clone>
--filter "FullyQualifiedName~Fixture_writer_is_deterministic"
run on Yggdrasil through the verify stopgap (dotnet/sdk:10.0), 2026-10-10.
Content: six records; two writes of the writer agree on content, though not bytes
(CultCache stamps storedAt from the wall clock). Regenerate and diff on content,
never hand-edit.

View file

@ -1,21 +1,12 @@
schema = "gamecult.idunn.target_declaration.v1"
target = "ghostlight"
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
required_gitlinks = ["vendor/eve"]
[[steps]]
id = "test-persona-boundary"
phase = "test"
runner = "rust-build"
required_environment = ["CARGO_HOME", "HOME"]
argv = ["cargo", "test", "--locked", "-p", "ghostlight-persona-projection"]
[[steps]]
id = "test-world-library"
phase = "test"
runner = "rust-build"
required_environment = ["CARGO_HOME", "HOME"]
argv = ["cargo", "test", "--locked", "-p", "ghostlight"]
# The Dungeon is one binary: the page is compiled into it, so there is no
# adjacent artifact. The connector key is not declared here: the operator
# binding's [workload.secret_files] entry GHOSTLIGHT_CONNECTOR_KEY_FILE is what
# Idunn loads as a systemd credential, and the recipe only names the variable
# that then holds the credential's path.
[[steps]]
id = "test-dungeon"
@ -31,56 +22,6 @@ runner = "rust-build"
required_environment = ["CARGO_HOME", "HOME"]
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
[[steps]]
id = "install-web-dependencies"
phase = "prepare"
runner = "web-build"
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
argv = ["npm", "--prefix", "web", "ci"]
[[steps]]
id = "test-web"
phase = "test"
runner = "web-build"
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
argv = ["npm", "--prefix", "web", "test"]
[[steps]]
id = "build-web"
phase = "build"
runner = "web-build"
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
argv = ["npm", "--prefix", "web", "run", "build"]
[[steps]]
id = "accept-real-persona-membrane"
phase = "acceptance"
runner = "rust-acceptance"
argv = [
"cargo",
"test",
"--locked",
"-p",
"ghostlight",
"--lib",
"controllers::tests::real_local_model_cognition_modes_commit_speech",
"--",
"--ignored",
"--exact",
]
required_environment = [
"CARGO_HOME",
"GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG",
"GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID",
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
"HOME",
"GHOSTLIGHT_LOCAL_ENDPOINT",
]
[[artifacts]]
id = "ghostlight-dungeon"
source_kind = "runner-output"
@ -89,16 +30,8 @@ source = "target/release/ghostlight-dungeon"
destination = "ghostlight-dungeon"
executable = true
[[artifacts]]
id = "web"
source_kind = "runner-output"
runner = "web-build"
source = "web/dist"
destination = "web"
[service]
executable_artifact = "ghostlight-dungeon"
required_adjacent_artifacts = ["web"]
arguments = [
{ kind = "literal", value = "--state-root" },
{ kind = "binding", name = "state_root" },
@ -109,36 +42,40 @@ required_environment = [
"GAMECULT_IDUNN_CANDIDATE_BIND",
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
"GHOSTLIGHT_CONNECTOR_ADDR",
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
"GHOSTLIGHT_DISCORD_GUILD_ID",
"GHOSTLIGHT_DISCORD_ROLE_ID",
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
"GHOSTLIGHT_HEIMDALL_BASE_URL",
"GHOSTLIGHT_LOCAL_ENDPOINT",
"GHOSTLIGHT_LOCATED_SERVICE",
"GHOSTLIGHT_ODIN_RUDP",
"GHOSTLIGHT_PLAY_MODEL",
"GHOSTLIGHT_PUBLIC_APP_URL",
"GHOSTLIGHT_SERVICE_ID",
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
]
optional_environment = ["RUST_LOG"]
optional_environment = [
"GHOSTLIGHT_AUTH_PROVIDERS",
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
"RUST_LOG",
]
[service.health]
contract = "ghostlight.cultnet-rudp-service-health"
# Idunn's state kinds are files. The snapshots and timelines slots are
# directories the daemon owns; they are declared as opaque process-owned paths
# (external-file), which Idunn preserves and never interprets.
[state]
schema_generation = "world-v3"
schema_generation = "dungeon-v1"
[[state.slots]]
id = "world"
relative_path = "world.cc"
id = "catalog"
relative_path = "catalog.cc"
kind = "cultcache-file"
schema = "ghostlight.world_state.consumer.v6"
schema = "ghostlight.dungeon_catalog.v1"
writer = "process-bound-single-writer"
recovery = "preserve"
startup = "create-or-open-after-write-lease"
@ -153,21 +90,21 @@ recovery = "preserve"
startup = "create-or-open-after-write-lease"
[[state.slots]]
id = "controller-work"
relative_path = "service/controller-work.cc"
kind = "cultcache-file"
schema = "ghostlight.controller_work.v18"
id = "snapshots"
relative_path = "snapshots"
kind = "external-file"
schema = "ghostlight.vault_snapshot.v1"
writer = "process-bound-single-writer"
recovery = "preserve"
recovery = "rebuildable"
startup = "create-or-open-after-write-lease"
[[state.slots]]
id = "mesh-projection"
relative_path = "service/mesh-v2.cc"
kind = "cultcache-file"
schema = "gamecult.eve.surface.v1"
id = "timelines"
relative_path = "timelines"
kind = "external-file"
schema = "ghostlight.world_state.consumer.v6"
writer = "process-bound-single-writer"
recovery = "rebuildable"
recovery = "preserve"
startup = "create-or-open-after-write-lease"
[[provides]]
@ -175,11 +112,7 @@ capability = "ghostlight.world-service"
schema = "ghostlight.world_state.consumer.v6"
compatibility = "consumer-v6"
[[provides]]
capability = "gamecult.eve.surface-provider"
schema = "gamecult.eve.surface.v1"
compatibility = "v1"
# Heimdall is found through Odin at use, not declared as an Idunn dependency.
[[dependencies]]
kind = "shared-infrastructure"
capability = "odin.verse-rendezvous"

View file

@ -1,5 +1,7 @@
# Ghostlight authority architecture
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
## Status
This document is the adopted rebuild target for the Ghostlight runtime. It is
@ -509,7 +511,9 @@ draws from it yet, and runtime readiness reads it. Changing it is a restart.
The five
controller models are configuration too (`GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL`,
`_PERSONA_MODEL`, `_INTERPRETER_MODEL`, `_OPERATIONAL_MODEL`,
`_ELABORATOR_MODEL`), each with a default when absent.
`_ELABORATOR_MODEL`, and `GHOSTLIGHT_PLAY_MODEL` for the play table), each
required: the deployment names the exact model id and an unset lane refuses
startup.
The kernel commits one decision at a time through the mailbox. After each
commit the planner derives a fresh queue. Parallel inference may speculate on
@ -624,9 +628,11 @@ lane still uses. The real-model gate that exists today is the Idunn recipe's
runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
against a real model; exercising a whole play turn against one is not gated
by this contract.
`world.create`'s current payload is `world_create.v4`: title, brief, targets,
jurisdiction roots and lens weights are required, and Dungeon's create surface
offers uniform weights as its editable default. `world.seed` runs one
`world.begin` is the one route that makes a world. Its payload is
`world_begin.v1`: title, brief and subject_label, nothing else; the route
decides everything else a world is born with (no targets, no roots, no persona
or agent label, uniform lens weights) and `begin_plan` decides how far Begin
goes. `world.seed` runs one
`SeedRunner` session per invocation against a `VaultEvidenceSource`.
Focused tests must prove:

View file

@ -1,100 +0,0 @@
# Ghostlight Eve-native interface
## Objective
Ghostlight Dungeon exposes one logical surface, `ghostlight.play`, from the
provider `gamecult.ghostlight.dungeon` (`crates/ghostlight-dungeon/src/mesh.rs`).
Eve owns editable bindings, command invocation, receipts, plugin composition,
and browser lowering. Ghostlight owns world creation, seeding, activation, play,
and world admission; Heimdall owns authentication and entitlement decisions.
```text
Ghostlight projection (eve.rs)
-> EveBrowserProviderHost
-> canonical Eve lowering
-> gamecult.eve.command_invocation.v1
-> Ghostlight command ingress (runtime.rs) or Heimdall private command plane
-> gamecult.eve.command_result.v1
-> authoritative surface refresh
```
## Authority map
- Owner: the world kernel owns world changes (through `WorldMailbox`, `SeedPort`
and the play table), Heimdall owns OAuth attempts and claims, and Ghostlight's
app-session owner (`app_session.rs`) binds a verified Heimdall subject to a
local cookie.
- Inputs: the projector reads only the caller's app session, the world
snapshot, and the caller's play-turn view. Command ingress reads one canonical
Eve invocation and derives the principal server-side.
- Outputs: one `gamecult.eve.surface.v1` document and one
`gamecult.eve.command_receipt.v1` inside a command result.
- Derived state: browser drafts, focus, command status, and rendered HTML are
projections or local interaction state. None grants access or mutates
fiction.
- Forbidden writers: the browser, the Eve lowerer, the Heimdall plugin, and the
SSE stream cannot choose a principal or commit world state.
- Shared path: every operation resolves the authenticated account, then calls
the world mailbox, the seed port, or the play port.
SSE carries invalidation only and the host refetches the same surface.
## The surface
`GET /api/eve/surfaces/ghostlight.play` returns a different document by caller
and world phase (`anonymous_surface`, `authenticated_surface` in
`crates/ghostlight-dungeon/src/eve.rs`):
| Caller and world | Content | Operations |
|---|---|---|
| Anonymous | `heimdall.access_gate` | `heimdall.auth.begin`, `heimdall.auth.complete` |
| Authenticated, any world state | a `Sign out` button on every authenticated surface | `app.auth.logout` (`ghostlight.app_logout.v2`) |
| Authenticated, no world | the create form: title, brief, your name, optional Narrative persona and Operational agent labels, scale target, jurisdiction roots, lens weights | `world.create` (`ghostlight.world_create.v4`) |
| Draft world | world summary card; approve button for a required approver who has not approved; for the owner, the seed form and Seed card, and the activate button once every required approver has approved | `world.approve` (`ghostlight.world_approve.v0`), `world.seed` (`ghostlight.world_seed.v1`), `world.activate` (`ghostlight.world_activate.v0`) |
| Active world, owner | advance-time control and the Play card: narration, the open question, the refusal of the player's own act, one free-text control | `world.advance_time` (`ghostlight.world_advance_time.v0`), `world.play` (`ghostlight.world_play.v0`) |
`world.play` is the only human play action. The open question's identity rides
the play button's own action as an opaque token, never as an editable field.
`operation_schema` in `eve.rs` is the single table from operation id to schema.
## Editable values
Eve bindings are the input model. A component binds a typed value by stable
binding name, document identity, field path, value kind, and access mode.
Renderer-local composers use `local-draft`. An operation captures one or more
named binding values atomically.
The browser lowerer may use an HTML form for keyboard and accessibility
behavior. HTML form structure never enters Eve state or command payload
semantics. Accepted receipts may clear named drafts; rejection and stale
conflict preserve them. An omitted clear-binding list means clear the surface's
drafts; an explicit empty list means clear nothing. Ghostlight validates every
payload at ingress regardless of what the control advertises.
## Authentication membrane
Anonymous projection contains only `heimdall.access_gate`. Its begin and
complete operations cross Heimdall's encrypted, loopback-only CultNet boundary
(`heimdall.rs`). Ghostlight reads the redacted `heimdall:command-boundary`
record from Odin, validates it, and invokes the discovered route. Odin does not
proxy the command and never receives claims or completion payloads. The browser
retains only the opaque attempt handle (`web/src/heimdall-access-adapter.ts`).
Ghostlight redeems the completion, validates the access claim, and creates a
local HttpOnly session cookie (`ghostlight_session`).
Routine requests use local verified session state, persisted in
`app-sessions-v2.cc` (`app_session.rs`): the cookie hash, the Heimdall
session and `access_revision`, expiries, and a wrapped refresh claim.
`access_revision` is Heimdall's revocation epoch.
## Public boundary
- `GET /api/eve/provider`
- `GET /api/eve/surfaces/{surface_id}`
- `POST /api/eve/commands`
- `GET /api/eve/events`
- `GET /health`, a probe of the service's typed CultMesh health
- `POST /cultnet/snapshot` and `POST /cultnet/world-patch`, the loopback
CultNet doors (see `ghostlight-world-consumer-api.md` for the second)
Static assets in `web/` contain only the Eve provider host, the transport, the
Heimdall adapter, and the SSE invalidation hook.

View file

@ -1,5 +1,7 @@
# Ghostlight Dungeon play agent (plan step 16)
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
## Status
Target, adopted 2026-09-22. Not implemented. The means will be in

View file

@ -1,5 +1,7 @@
# Ghostlight Dungeon Session Zero
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
Status: adopted direction, 2026-09-15. Not implemented. Its role as the
playtest gate is superseded (operator, 2026-09-22) by the play agent,
`ghostlight-play-agent.md` (plan step 16). D1–D3 and the library passes

View file

@ -63,6 +63,11 @@ attributed proposal — is not part of this pass; see "Not in this pass" below.
## Transport
Status: the HTTP door below lived in the Dungeon daemon's `api_router` and is
parked with it at tag `parked/ghostlight-eve-surface`; no process on main serves
it. `ghostlight::admit_document` and `encode_receipt` are the contract a host
serves.
`POST /cultnet/world-patch`, declared beside `/cultnet/snapshot` in
`api_router` (`runtime.rs`). The handler gates loopback and content type
(`application/msgpack`) exactly as the snapshot route does, then hands the

View file

@ -442,6 +442,8 @@ which noun a component is; it cares what it constrains.
| `Channel` | channel: reach set, controller (latency arrives with the clock, pass 7) | how facts travel; who can be silenced |
| `Commitment` | subject → counterparty: kind (`Routine`, `Obligation`, `Goal`), due, period, statement | obligation with a clock; autonomous motion |
| `Pressure` | source → target: magnitude | the causal boundary trigger |
| `Attitude` | holder → subject or trait: signed delta, cause, since, decay | how one subject regards another; sourced modifiers, never a stored opinion |
| `Trait` | subject → trait name: the facts that evidence it | what a prejudice may reach, once the holder knows one of them |
| `PersonaMaterial` | subject: values, voice, memories, reads | lived meaning; never authority |
A `Fact` carries a `standing` (`FactStanding`, three variants): `Canonical`
@ -451,6 +453,23 @@ belief. Deception is a subject asserting a claim while holding a contradicting
canonical fact; misread is a listener acquiring a claim the speaker did not
intend. Both are ordinary typed states, not narrator judgments.
Attitude is a sum of sourced terms, in the manner of Crusader Kings opinion
modifiers. A modifier points at a subject or at a trait, carries a delta in
`-100..=100`, a cause (`Prejudice`, `Grievance` or `Favor` named for the command
that did the deed, or a `Rumour` over a fact), the clock at its last write, and an
optional fade. `attitude::opinion(holder, subject)` derives the regard on demand:
the direct modifiers, plus each trait modifier whose trait the subject carries
*and* whose evidencing fact the holder knows at `Believed` or better, summed and
clamped. A prejudice against outlanders does nothing to a stranger the holder
has not learned is one. `Trait` rows are declared by the world, never inferred.
The regard is projected to every reader from that one derivation: each subject's
snapshot, the table view the Dungeon Master reads, the Persona's own view, and
the narrator's account of who stands with the player. Only the reducer writes it,
through `AdjustAttitude` (a deed, or an affordance effect, whose regarded party is
fixed to the actor), `DeclareAttitude` (prejudice or rumour, authored without a
deed) and `DeclareTrait`. The three are additive on the state: a world with no
attitude serializes as it did before, so the state schema tag did not move.
Civic order is the `Authority` + `Selection` + `Redress` + `Custody` subgraph.
It is not a prose manifest and needs no civic verdict. `Dependency` is the
crisis transmitter: it is what makes a failed pump in one realm a political
@ -460,7 +479,7 @@ problem in another without anyone deciding that it should be.
This is the closed operation set. Every mutation the kernel applies is one of
these, and every model-facing tool is a projection of one of these. The type is
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 34 variants, named here by
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 37 variants, named here by
the component they act on. Declarations are the six `Declaration` variants.
```text
@ -478,6 +497,7 @@ Knowledge AcquireKnowledge, Communicate, Witness, Forget
Channel SetReach, SetController
Commitment CreateCommitment, DischargeCommitment
Pressure AdvancePressure, ReducePressure, ResolvePressure
Attitude AdjustAttitude, DeclareAttitude, DeclareTrait
PersonaMaterial SetPersonaMaterial
Retirement Retire
Affordance GrantAffordance, RevokeAffordance

View file

@ -0,0 +1,442 @@
# Multiresolution Gestalt: Target
Date: 2026-12-03. Campaign `ghostlight-verse` in the Weksa mind. Imagination pass
`gestalt-map`, session `weksa-self-20261202`. Base: Ghostlight `main` `93da896`;
the room cut builds on branch `ghostlight-verse/dungeon-npc-voice` at `d2c91ca`.
This page is the target shape and the authority map. Cut specs, questions,
research and ideas live in the mind; their ids are listed here so the page can
be read alone. Query them with
`huginn view <id>` or `huginn pass ghostlight-verse gestalt-map`.
## Why
Operator, 2026-12-03 (ruling `ghostlight-verse:ruling:multiresolution-gestalt`):
> Multiresolution Gestalt is core to the whole idea of Ghostlight, using a turn
> to simulate groups of people (and groups of groups, etc.) is how you can scale
> to massive worlds, as well as simulate massive worlds in parallel. For
> Ghostlight Dungeon, the DM should be dispatching Gestalt turns for the whole
> world, then the region, subregion, all the way down to the room the player is
> in (cut along the most semantically relevant lines, usually institutional
> rather than geographic) at varying rates, while also dispatching Elaborator
> agents to add depth to whatever the player happens to be looking at. Lots of
> knobs which it can use to fit the simulation's quality to the player's needs
> and budget.
Rulings this page stands on: `multiresolution-gestalt`, `dungeon-dm-owns-the-gears`,
`dungeon-models-dm-opus`, `dungeon-credit-burn`, `deru-play-profile`,
`aetheria-sim-first`, `two-ghostlight-consumers`, and the verse-sim rulings of
2026-10-10: `verse-sim-pipeline` (the verse runs multiresolution gestalts on a
schedule), `gestalt-machinery-port` (port the pre-rebuild machinery, do not
redesign it), `teardown-was-authority-sprawl` (port ideas onto the grammar
kernel, never ad hoc mutation rules), `gestalt-fission-auto` (splits are
admitted during runs), `grammar-scope-ruled`, `verse-cadence-ruled` (manual
under a hard token cap, then nightly under a monthly cap), `grouped-record-and-carry`,
`dungeon-vault-import-run-ahead` (elaborators run ahead of the player).
## What exists (Body at `93da896`)
- **The kernel is the only writer.** `WorldMailbox` admits a closed command
set; a subject acts only through its own opportunity (`ExerciseDecision`,
`DeclineDecision`, both of which stamp `last_opportunity_at`).
Subjects are `Person`, `Institution`, `Population` (`lib.rs:385`). Institution
structure is typed: offices with incumbents (`selection`, `lib.rs:921`),
authority grants over a subject or a place subtree (`authority`, `lib.rs:915`,
`patch.rs AuthorityTarget`). Places form a containment tree. There is no
population membership (`CausalBoundary::IndividuationRequired` is "declared,
never derived", `lib.rs:4358`).
- **The flat cover.** `cover.rs` partitions every active opportunity into
Singleton and Group cells under `CoverBudget {cells, constituent_cap,
urgency_slots}`, with a rotation window that guarantees every subject a
singleton turn within `ceil(N/R)` ticks. It is pure, derived and dropped each
tick; a Group cell is one inference over N labelled, never-unioned views,
each constituent submitting its own command (`controllers.rs run_group`).
The adjacency it reads is `agency_graph` (`lib.rs:3923`), exposed only on
`WorldMailbox` (`mailbox.rs:488`), never on a controller port.
- **The verse runner** (`verse/run.rs`, binary `ghostlight-verse`) advances a
world tick by tick under a token cap: open a tick document that freezes the
cover (`open_or_find`, `run.rs:1143`), run each cell through
`ControllerRunner::run_cell`, advance the clock once, checkpoint. Spend is
reserved before each call and settled after by `RecordingInferencePort`
(`verse/calls.rs:552`). It is the only world-scale scheduler today, and it is
one level deep: every faction every tick, at one resolution.
- **The Dungeon DM** (`ghostlight-dungeon/src/play.rs`, Opus) reads
`table_view`, `dispatch`es Personas, commits with authoring and actor tools,
and owns time through `advance_time`. Branch `dungeon-npc-voice` adds
`react`: one Persona-model call for the room's onlookers
(`PersonaLane::gestalt`), whose sections come back as drafts the DM commits
through each person's `__speak`. Nothing outside the DM's dispatches moves.
- **Run-ahead** (`run_ahead.rs`) starts a bounded elaboration sweep after each
closed turn (`api.rs:443`), sized by `Scale` session and permit counts
(`begin.rs:39`). Its claim order is jurisdiction order, then derivation order
(`elaboration.rs:963`): it does not know where the player is or looks.
- **The pre-rebuild design** (`docs/articles/multiresolution-gestalts.md`, tag
`parked/ghostlight-pre-rebuild`
`docs/architecture/ghostlight-multiresolution-agency.md`) had the agency
graph, a budgeted connected cover, cohesive versus arena cells, detail debt,
approval-gated fission and population baselines with member deltas. The
cover, arena cells and detail debt (as the rotation window) are ported.
The hierarchy, rates, focus and membership are not.
## Prior art that shaped this
Research notes of pass `gestalt-map` (`ghostlight-verse:research:gestalt-map.*`):
- `brom-lod-membrane`. IVE (Šerý, Poch, Šafrata, Brom 2006; Brom, Šerý, Poch,
IVA 2007): detail is an elastic membrane cut through a location tree; an
important object presses it down; LOD influence between neighbours makes a
crater, not a hole, around the player; locations expand eagerly and shrink
lazily in a garbage-collection pass; a process above the membrane runs
atomically and is partially evaluated when detail drops; one dedicated
"genius" can drive several actors at once. This is the shape of focus,
promotion, demotion and hysteresis below.
- `navarro-mesoscopic`. Navarro, Corruble, Flacher, Zucker (AAMAS 2013):
aggregate the minds, keep the bodies; partial disaggregation of only the
members something interacts with. Full macro aggregation lost emergent
micro phenomena and consistency fell. A Ghostlight Group cell is already
mesoscopic: one decision call, every member's state stays its own.
- `mrm-aggregation-failures`. The multiresolution-modelling literature's known
failures at level boundaries: chain disaggregation, transition latency,
thrashing, and mapping inconsistency between representations; MRE keeps
every representation with mapping functions (Reynolds, Natrajan, Srinivasan
1997). Ghostlight avoids the class by keeping one representation.
- `holonic-mas`. Holons (Gerber, Siekmann, Vierke 1999; Fischer, Schillo,
Siekmann 2003; Gaud et al. 2008): a group appears outward as one agent whose
head speaks for members that gave up part of their autonomy; recursive;
reorganised at run time. Ghostlight's head is an institution subject with
its own controller, and that is why the cut goes along institutions first.
- `dwarf-fortress-world-vs-site`. Dwarf Fortress runs world history coarsely
and keeps it running during play; off-site events reach the active site only
through in-world channels (a liaison, invaders who physically travel). The
Dungeon's equivalent: off-screen waves write kernel acts, and the player
learns of them only through knowledge and travel.
- `paradox-pops`. Victoria 3 aggregates people into pops keyed by profession,
culture, religion, workplace and state, and cost scales with the number of
pops, not of people; interest groups are fractions of pops. Aggregation keys
are typed attributes, not a model's judgement.
- `sunshine-hill-alibi`. Alibi generation (Sunshine-Hill and Badler, AIIDE
2010; dissertation 2011): fill in an agent's goals and history only when
inspected, consistent with what was already observed. That is what an
elaborator does when the player opens a node nobody authored.
- `ghostlight-pre-rebuild-gestalt` and `ghostlight-flat-cover-today`: the repo
facts above.
## Vocabulary
- **Node.** A vertex of the gestalt hierarchy: `World` (root), an
`Institution` node anchored at an institution subject, a `Place` node
anchored at a place entity, or a `Subject` leaf.
- **Voice.** A subject that acts in a node's turn. An open node's voices are
its children's anchors and its loose subjects; a closed institution node's
only voice is the institution itself.
- **Gestalt turn (node turn).** One wave's work for one node: its voices,
partitioned into cells by `derive_cover` when they exceed the constituent
cap, each cell one inference through the existing lanes.
- **Wave.** The set of node turns one planning pass chose, frozen with
deterministic ids before any inference.
- **Focus.** The places and nodes detail is pressed down around: the player's
place always, plus what the DM names. Distance is counted in hierarchy steps
from the focus.
- **Rate.** A period in fictional minutes per distance band. A node is due
when its most neglected voice was last attended at least one period ago.
- **Room.** The player's place and the subjects positioned in it. The one
level that is always geographic, because presence is physical.
## Invariants
- **G1 `kernel-only-writer`.** Every effect of a turn at any level reaches the
world as an ordinary submission by an exact subject (`ExerciseDecision`,
`DeclineDecision`) or a confined patch through the mailbox (elaborator, play
table). The hierarchy, waves, knobs, focus and ledgers never enter
`WorldState`, a `CommandEnvelope` or a scope digest.
- **G2 `one-representation`** (a group turn is legible at the finer level).
Ghostlight aggregates attention, never state. A coarse turn acts only through
subjects that exist, so the finer level reads exactly what it wrote. Opening
a node writes nothing and needs no disaggregation; closing one writes
nothing and discards nothing. A group turn's uncommitted prose is not canon,
as a Persona's draft is not.
- **G3 `bounded-and-reported`.** Every model call of every level reserves its
bound in a ledger before it is made and is settled and reported after, by
lane (room, wave, elaboration), node and distance. A call that could pass its
allowance is not made; the node is reported deferred, never dropped silently.
- **G4 `institutions-first`.** The hierarchy is derived from world state, and
a subject's home is decided by institutional ties before places: office
incumbency, then authority over the subject, then authority over a place
subtree containing it, then place containment, then the root.
- **G5 `one-planner`.** The Dungeon and the verse plan waves with one pure
function over (hierarchy, opportunities, knobs, focus, wave ordinal). The
drivers differ only in who sets the knobs, when a wave runs, and who owns
time.
- **G6 `no-starvation`.** Every voice of every due node is attended within its
rate period times the rotation bound of `derive_cover`; deferral is visible
in the wave report.
- **G7 `cohesion-needs-authority`.** Only an institution subject speaks for
others, through its own affordances. Every other grouping is an arena in
which each act names its exact subject (the grouped lane's per-handle rule).
- **G8 `replayable-waves`.** Hierarchy, wave and command ids are pure over
world state, knobs and the wave ordinal, so a resumed wave re-submits the
same ids and the kernel answers with the original receipts.
## Identity, lifecycle and authority
| Thing | Named by | Life over time | Who decides |
|---|---|---|---|
| Node (resolution level / group node) | `NodeId`: sha256 over a fixed namespace, the world id and the anchor (`World`, `Institution(SubjectId)`, `Place(EntityId)`, `Subject(SubjectId)`) | Derived on every read from the current world state; exists while its anchor exists and has at least one live descendant voice; never stored. A world change moves a subject to another parent on the next read, with no migration step | `derive_hierarchy` (kernel-private, beside `agency_graph`), exposed only on `WorldMailbox::hierarchy` |
| Node state open/closed | (node, wave) | Decided per wave by the planner from focus and depth; held only in the frozen wave | The planner, from the driver's knobs |
| Gestalt turn (node turn) | `(world, node, wave ordinal)`; its cells' ids from `cover.rs` with the wave ordinal in place of the tick | Frozen in the wave document before the first inference; each cell runs through `ControllerRunner::run_cell`, resumes from its controller-work row, ends committed, declined, refused or deferred | Cells decide what voices do; the kernel admits; the wave runner owns order and checkpoints and nothing else |
| Wave | Verse: the tick ordinal (clock advances). Dungeon: `(timeline, closed turn sequence)` | Opened (frozen) once, run, closed once; an open wave is finished as frozen by the next run | The driver opens and closes it; the planner chooses its content |
| Room turn | The DM's `react` call slot in the play turn, as `dispatch` today | Inside one play turn, recorded and resumed by the play turn store | The DM's judgement (`dungeon-dm-owns-the-gears`) |
| Level rate | Distance band (0 = the focus's own node, 1, 2, ..., and `rest`) mapped to a period in fictional minutes | Standing value in the knobs; changed by the DM tool or the verse run config; takes effect at the next wave | Dungeon: the DM. Verse: the operator's run config |
| DM knobs (rates, depth, budget, focus) | One `GestaltKnobs` document per Dungeon timeline; the verse's `VerseRunConfig` | Persisted per timeline, survives reload; default at Begin; each wave records the knob values it was planned under | The DM through one `tune` tool; the player only by asking the DM; never the kernel |
| Focus entry | Place or node id, with a lease in fictional minutes | Added by the DM or implied by the player's place; the player's place never expires; others expire at lease end (lazy shrink) | The DM; expiry by the planner reading `now` |
| Promotion (opening a node) | The node in a wave that plans it open | Happens when the focus comes within `depth` of it, or the DM forces it, or its detail debt makes it due; writes nothing | The planner |
| Demotion (closing a node) | The node in a wave that plans it closed | Only after the lease of the focus that opened it ends and the next wave plans it closed (shrink lazily); writes nothing | The planner |
| Spend ledger window | Verse: the run. Dungeon: the post-turn window | Reserve before each call, settle after, report by lane, node and distance | The recording port (`RecordingInferencePort` core) |
## Authority map
### Who owns the hierarchy
- **Owner.** `derive_hierarchy(&WorldState) -> Hierarchy`, a pure kernel-private
function beside `agency_graph`, reached only through `WorldMailbox::hierarchy`.
- **Inputs.** `selection` (offices, incumbents), `authority` grants over
subjects and place subtrees, `positions`, place containment,
`controller_assignments` (only subjects with a non-Human controller are
voices; the player is placed but never a voice).
- **Outputs.** A tree: `World` root; institution nodes; place nodes only where
some live subject has no institutional home; subject leaves. Each node lists
its children, its anchor voice (if any) and its loose subjects. Also the
focus path of any place: the chain of nodes that govern it.
- **Home-parent rule.** A subject's parent is the first that exists of: the
institution in which it holds an office (several: the one with the fewest
live members, then the lowest id); the institution holding an authority grant
over it; the innermost institution holding a grant over a place subtree that
contains its position; the innermost place node containing its position; the
root. An institution's own parent follows the same rule. A cycle is broken
at its lowest id, which then hangs from the root. Other ties stay visible as
context, not as second parents (question `gestalt-multi-affiliation`).
- **Derived state.** The whole hierarchy, node ids, focus paths. Nothing is
stored. An elaborator, the DM or a Persona changes the hierarchy only by
changing the world through ordinary commands (granting an office, a grant,
a move).
- **Forbidden writers.** No hierarchy document, no declared tree, no cache that
outlives one read, no model output.
- **Shared paths.** The Dungeon wave, the verse tick, the DM's view of what is
due and the elaborator's focus all read the same `hierarchy()`.
### Who schedules
- **Owner.** One pure planner, `plan_wave(world, ordinal, &Hierarchy,
&[DecisionOpportunity], &GestaltKnobs, &Focus, now) -> Wave`. It opens nodes
along each focus path up to `depth`, closes everything else, takes the due
nodes by rate, orders them nearest-focus first then most overdue, partitions
each node's voices into cells with `derive_cover` (the agency graph
restricted to those voices) and cuts the list at the knobs' turn bound.
- **Two drivers, one planner.**
- *Dungeon.* The DM owns the gears inside a turn: the room is its `react`
call. Above the room, the DM sets standing knobs and focus with `tune`;
after each closed play turn the Dungeon plans one wave and runs it, while
the player reads the narration; the DM may force a node now with
`run_world`. Time stays the DM's (`advance_time`); a wave never advances
the clock. (Question `gestalt-dungeon-trigger` asks whether the DM
should instead call every wave itself.)
- *Verse.* A tick plans a wave with no focus (or the operator's), runs it,
and advances the clock by the frozen span. The tick document freezes the
wave instead of the flat cover.
- **Derived state.** `derive_cover` is no longer the scheduler; it is the
within-node cell partition. `Resolution::{Detail, Coarse}` stays a derived
label. Due-ness is derived from kernel `last_opportunity_at`; no second
schedule store exists.
- **Forbidden writers.** No background timer, no wall clock, no code path that
runs a world wave the knobs did not plan. Run-ahead stops choosing its own
claim order (below).
### How Gestalt and Elaborator turns share the budget
- **Owner.** One ledger per window: the reserve-before-call, settle-after core
of `RecordingInferencePort`, with every call record tagged by lane
(`room`, `wave`, `elaboration`), node and distance.
- **Allowances.** The knobs split a window's token budget between the `wave`
and `elaboration` lanes. The room lane is the DM's play turn, bounded by its
round budget and the per-call output cap, and is reported but never starved
by background lanes: background lanes run after the turn closes.
- **Elaboration focus.** The elaborator's sweep takes the focus as its first
claim key: boundaries and deficits at focus places first, then the
current order. A place is at focus when it is a focus place, inside one, or
one open route from one (read either way); a boundary's place is its
destination's, or the position of the subject it names; a deficit's is its
jurisdiction root; the uncovered residual is nowhere. The partition is stable,
so an empty focus is today's order. Focus is also the outer key of fair
claims: in-focus demand before the rest, and inside each band an untried
entry before a tried one. It answers "what is the player looking at" with
structure, where waves answer it with action.
- **Demotions.** `Scale::sweep_sessions` and `sweep_permits` stop deciding
how much elaboration happens; the elaboration allowance does, and permits
stay a concurrency bound. The verse's `COVER` constant becomes a knob value.
The verse's run token cap is the wave lane's allowance.
Landed (cut `gestalt-ledger`, on Ghostlight `main` `1419b3b`): call records are
`ghostlight.verse_provider_call.v2` (lane and request id) and a run's ledger
`ghostlight.verse_run_ledger.v2` (allowances and spend by lane). A call that
could pass its lane's allowance is refused `budget_exhausted` in `reserve`,
beside the run cap, before the provider is called; the play agent has no lane
and is refused at the port. `WaveSpend::of` joins records to a frozen wave by
the command id a request id begins with, so node spend is a join and
`NodeOutcome.spent` is gone. The verse tick is `ghostlight.verse_tick.v3` and
records what the plan deferred; the tick report lists deferred nodes with why
(not due, over the node-turn bound, past the allowance). The Dungeon's run-ahead
spends in `window-<world revision>` of the timeline's `calls.cc`, under the
allowances of the timeline's knobs (below).
### Deletion line
Before the hierarchy lands nothing is deleted. In order: `react`'s mandatory
subject list becomes an override (room derived); the verse's one-line
`derive_cover` call over all opportunities is replaced by `plan_wave`; the
Dungeon's unfocused post-turn sweep is replaced by the focused, allowance-bounded
one; `Scale`'s sweep counts are deleted when the allowance lands.
## The shape in one walk
Deru stands in the Ironmarket tap-room. He insults the guild factor.
1. Room. The DM `dispatch`es the factor and `react`s the room: one call, every
onlooker in the tap-room from their own slice. The DM commits what is said.
2. The turn closes. The Dungeon plans a wave with focus = the tap-room.
The focus path is tap-room → Ironmarket Guild (it holds the market district's
grant) → City Council → Crown → World. With depth 2, the Guild and the
Council are open: the guild's officers and the watch captain act in their
own cells; the Crown is closed and acts as one voice at its slower rate
when due; the rest of the world turns as closed institution voices only when
their band's period has passed.
3. Every act goes through the kernel. The factor's grudge is a commitment and a
pressure; the guild's order to its enforcers is the guild's act, heard by its
audience.
4. The elaborator spends its allowance on boundaries under the tap-room and its
exits first.
5. Next turn, the DM's view shows what moved off-screen and what is due. When
Deru walks into the guild hall, its officers already have their own state:
nothing to disaggregate.
## How the verse runner fits
The verse runner is the unattended driver of the same planner. It keeps its
tick document, its token cap, its resume rules and its clock advance; only
the content it freezes changes, from one flat cover to one planned wave. With no
focus and a depth knob, a verse tick turns the world's institutions as closed
voices at their band rates, and `derive_cover` still bounds each node's cells.
Ruling `verse-cadence-ruled` (manual under a hard cap, then nightly) is its
trigger; the Dungeon's closed turn is the other.
Landed (cut `gestalt-wave-driver`): the tick document is
`ghostlight.verse_tick.v2`, each frozen cell carries its node and distance, and
the tick records the knobs. The operator sets them with
`ghostlight-verse run --depth N --band DIST=MINUTES` (repeatable); the default
is depth 1 and one band at the tick span, which plans the flat cover's shape.
`run_frozen_cells` in `wave.rs` runs the frozen cells for any driver; the clock
advance stays in the verse driver.
Landed (cut `dungeon-world-waves`, branch `ghostlight-verse/dungeon-world-waves`
from Ghostlight `main` `ab290dc`): after each closed play turn the Dungeon runs
`run_waves` (`waves.rs`) under the sweep lock, before run-ahead. It finishes any
wave left open, then plans one wave with `plan_wave` over the derived hierarchy
with the player's place as focus and constant knobs (bands 60, 360, 1440 and
10080 minutes, depth 2, four node turns, cover 4/6/1). The wave is frozen under
the closed turn's log `seq` in the timeline's `waves.cc`
(`ghostlight.dungeon_wave.v1`) before its first call, runs through
`run_frozen_cells` on a runner over the window port, and closes once with a
report. It spends in `window-<revision it opened at>`, so a resumed wave
reopens its own ledger and re-submits its own command ids. A voice the world
has never given an opportunity counts as attended at the clock's origin, so
nothing is due until a band's period has passed and a wave never turns a world
whose clock has not moved. The clock stays the DM's. The DM's next opening view
carries the closed waves it has not seen: acts by node, then nodes due but not
run. A wave that stops with a cell unfinished stays open and is finished at the
timeline's next closed turn. (That is the wave as `dungeon-world-waves`
landed it; the knobs, the document version and the room rule changed with
`dm-gestalt-knobs`, below.)
Landed (cut `dm-gestalt-knobs`, branch `ghostlight-verse/dm-gestalt-knobs` from
Ghostlight `main` `d3b0e20`): the knobs are one document per timeline,
`ghostlight.dungeon_gestalt_knobs.v1` in `gestalt-knobs.cc` (`knobs.rs`),
written with a Begin's defaults when a timeline opens without one: bands 60,
360, 1440 and 10080 minutes, depth 2, four node turns, cover 4/6/1, and a wave
and an elaboration allowance of 200000 tokens a window (sized to the retired
four-session sweep; no cost is measured yet). `default_knobs`,
`Scale::sweep_sessions`, `Scale::window` and their environment variables are
deleted; `Scale::sweep_permits` stays as the concurrency bound. The wave, the
run-ahead sweep and the opening view read the document, and each wave
(`ghostlight.dungeon_wave.v2`) records the knobs, allowances, DM focus and
forced nodes it planned under; the window it runs in follows the knobs as they
stand.
The DM turns them with two tools. `tune` sets bands (1 to 8 periods of 1 to
525600 minutes), depth (1 to 8), `max_node_turns` (1 to 32), the two lane
allowances (0 to 5000000 tokens), and adds or removes focus entries, each a
place or an institution by the id `table_view` prints, with a lease in
fictional minutes. A value outside its bound refuses the whole call, quoting
the value. A lease is an end minute: past it the entry is not focus, and the
next `tune` drops it. The player's own place is derived, never stored.
`run_world` names places or institutions; the next post-turn wave opens them
like focus nodes, treats them as due whatever their band and runs them ahead of
every other node, within the wave allowance (a node past it is reported
waiting); that wave takes the request whether or not it ran. The opening view
prints the knobs, the focus path by label, the DM's leases and queued nodes,
and the average tokens a node turn has cost in each band from the closed waves.
The knobs are the authority over a window's limits: a window already open at
the current revision follows a tuned allowance (`open_following`), keeps its
spend, and a lane held above a lowered allowance is exhausted, not an error.
A `run_world` target with no one to take a turn is frozen into its wave and the
next view says "nothing stirred" at it.
A wave gives no turn to a subject standing in the player's place: the room is
the DM's `react`. The DM's focus on an institution opens its node for waves;
the elaborator's claim order reads only the places.
## Cut sequence
Each cut is one `cut_spec` in the mind, `ghostlight-verse:cut_spec:cut-<cut>.r1`,
sized for one Sonnet Hands. Rejected alternatives are the ideas
`ghostlight-verse:idea:gestalt-map.*`, each with its Recorded resolution.
1. `gestalt-room`: `react` becomes the room-level Gestalt turn: the room
derived from the player's place, sections keyed by handle, non-Persona
subjects routed instead of failing the call. On `dungeon-npc-voice`.
2. `gestalt-hierarchy`: `derive_hierarchy` and `WorldMailbox::hierarchy`.
3. `gestalt-planner`: `plan_wave`, `GestaltKnobs`, `Focus`, due-ness. Depends on 2.
4. `gestalt-wave-driver`: the shared wave runner; verse ticks freeze planned
waves. Depends on 3.
5. `gestalt-ledger`: lane, node and distance on call records; lane
allowances; the Dungeon gets a ledger. Depends on 4.
6. `elaboration-focus`: the sweep's focus-first claim order; Dungeon
run-ahead spends the elaboration allowance on the player's focus. Depends on 5.
7. `dungeon-world-waves`: a wave after each closed play turn; off-screen acts
and due nodes in the DM's view. Depends on 1, 4, 5.
8. `dm-gestalt-knobs`: the DM's `tune` and `run_world` tools; knobs persisted
per timeline; focus leases. Depends on 6, 7.
9. `closed-voice-digest`: a closed institution's view carries a capped digest
of its folded members' salient state. Depends on 3.
## Questions
- `ghostlight-verse:question:gestalt-hierarchy-owner`: derived, declared or
model-proposed hierarchy. Recommended: derived.
- `ghostlight-verse:question:gestalt-multi-affiliation`: one home parent or a
voice in every institution. Recommended: one home parent.
- `ghostlight-verse:question:gestalt-dungeon-trigger`: the DM calls every wave,
or sets knobs that a post-turn step runs. Recommended: standing knobs.
- `ghostlight-verse:question:gestalt-rate-clock`: rates in fictional minutes or
in play turns. Recommended: fictional minutes.
- `ghostlight-verse:question:gestalt-population-membership`: port population
baselines and member deltas now, or individuate through elaborators.
Recommended: defer.
## Not in scope
- Population membership, baselines, member deltas and fission (the question
above holds it; ruling `gestalt-fission-auto` governs fission when it comes).
- A model-chosen cut per wave (the old six-axis demand model).
- Eve or any play-surface change beyond the DM's own view.
- Cost tuning: allowances and rates are measured in the burn
(`dungeon-credit-burn`), not designed here.

View file

@ -2,25 +2,21 @@
This is a pointer. It does not carry open work; the Eureka mind does.
## What runs
## What exists
Ghostlight Dungeon runs on Yggdrasil under Idunn at
`https://yggdrasil.gamecult.org/ghostlight/` (runtime `ghostlight-yggdrasil`,
target `ghostlight`, ref `main`, state root `/var/lib/gamecult/ghostlight-world-v2`).
`/health` names the commit it serves (`crates/ghostlight-dungeon/src/runtime.rs`).
The binary is `ghostlight-dungeon`; its inference reaches Bonsai on Raven
through a loopback tunnel, and sign-in goes through Heimdall, discovered via
Odin.
Nothing is deployed. The Dungeon (daemon, play table, Eve surface, browser host,
`vendor/eve`, Idunn recipe) is parked at the tag `parked/ghostlight-eve-surface`
and is not on main. A Thing 2 rebuild starts from that tag.
## How it deploys
What is in the tree is the kernel (`crates/ghostlight`), the persona projection
(`crates/ghostlight-persona-projection`) and the verse runner
(`crates/ghostlight-verse`). `cargo test` runs them on Linux; use the
`ygg-verify` stopgap on Yggdrasil, not the workstation, and say which host
you used.
Idunn is the only deploy path (`idunn up ghostlight`). The recipe is
`deployment/idunn/recipe.toml`; the runbook is
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. The Ghostlight daemon
cannot start without Odin: its Warming presence and process write lease go
through Odin. Preflight Odin's route health before a deploy. Do not invoke the
retired v1 actuator (`gamecult-ops/scripts/deploy-ghostlight-yggdrasil.sh`), its
wiring test, or `ghostlight-dungeon.service`.
The Idunn target `ghostlight` is braked and stopped, not retired. Its state is in
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. Do not run
`idunn up ghostlight`, the v1 actuator, or `ghostlight-dungeon.service`.
## Where open work is
@ -35,9 +31,10 @@ target and probed body facts are `notes/ghostlight-verse-target.md` and
1. `README.md`: what exists and what does not.
2. `AGENTS.md`: invariants and where things are.
3. `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture.
4. `docs/architecture/ghostlight-world-ontology.md`: the kernel's vocabulary and
3. `docs/architecture/ghostlight-world-ontology.md`: the kernel's vocabulary and
current mechanism.
4. `docs/architecture/ghostlight-dungeon-mvp.md`: the parked Dungeon's authority
architecture. History until Thing 2 revives it.
5. `docs/architecture/ghostlight-play-agent-cut.md`: the dated record of the play
agent and of the first deploy on 2026-09-23 (findings PA.f198 to PA.f216).
It is history; the mind says which findings are still open.

View file

@ -1,6 +1,8 @@
# Ghostlight Verse: Map
Campaign `ghostlight-verse`, target `ghostlight-verse:target:r2`
> Status: Dungeon, eve.rs and the bridge-test references below are parked at tag `parked/ghostlight-eve-surface`; line refs are to that tag.
Campaign `ghostlight-verse`, target `ghostlight-verse:target:r3`
(`notes/ghostlight-verse-target.md`). This page holds body facts, the model
page and rationale only. Cut specs, questions, rulings and follow-ups live in
the Eureka mind; query them there, never copy them here.
@ -9,6 +11,15 @@ Phase 1 map: Imagination, session `self-2026-10-09-morning`, 2026-10-09.
Base for every phase-1 anchor: Ghostlight `origin/main` `4fee97f`.
Times are UTC unless marked local (UTC+2).
## Cut sequence
Cuts without a `cut_spec`, withdrawn 2026-10-12 under map-only-what-runs: a spec is admitted when Self is about to dispatch the cut. The live run waits on the operator's DeepSeek key. Re-map a line by a fresh Imagination pass against the Body when the frontier reaches it.
- model-asleep: The play card says the storyteller is waking while Bonsai reloads, and refuses a turn with an asleep line when the. Waits on: play-faults (live run waits on the operator DeepSeek key).
- raven-bonsai-scripts: Raven's Bonsai scripts enter gamecult-ops; the server stays up and sleeps its model on idle, the reaper is gone, and. Waits on: nothing in the mind (not queued; Ghostlight live run waits on the operator DeepSeek key).
- deploy-main: Main deploys on Yggdrasil through Idunn, stays up, and a human plays a session end to end. Waits on: play-faults, play-surface, session-refresh, acceptance-gate, raven-bonsai-scripts, model-asleep, create-flow (blocked on the DeepSeek key and the Ghostlight live-run chain).
- v1-retire: The retired v1 Ghostlight body leaves Yggdrasil and gamecult-ops. Waits on: nothing in the mind (not queued; Ghostlight frontier is the live run).
## Body facts (probed 2026-10-09)
### Does main run on Yggdrasil?
@ -57,7 +68,7 @@ Times are UTC unless marked local (UTC+2).
### Does main build and pass?
Two jobs through `ygg-verify.sh` at `4fee97f`, with `vendor/eve` initialised:
Two jobs through `ygg-verify.sh` at `4fee97f`, with the Eve submodule initialised:
- Rust (image `eureka-verify-rust`), the recipe's own steps:
`ghostlight-persona-projection` 35 passed; `ghostlight` lib 621 passed,
@ -202,6 +213,67 @@ from 21:04 the denial forever. Mechanism:
code is flat under `crates/ghostlight/src/`. Dated cut documents and
postmortems keep their paths: they are history.
### Who refuses an operational in-flight row whose scope moved? (probed 2026-10-17, `4741d50`)
- Three paths answer the same fact (the subject still holds one opportunity on
the bound scope, at a new digest), with two errors. A probe test run on
Yggdrasil returned these, with one provider call in total:
- The scope moves during round 0 of a fresh run. Round 1's
`ensure_scope_unchanged` returns `NoOpportunity`.
- A resume passing the row's own stale opportunity returns `NoOpportunity`
(same gate).
- A resume passing the fresh opportunity returns `OpportunityMismatch`, from
the digest clause of `row_answers_caller` at lookup.
- The driver's `classify` (`verse/run.rs` 641-651) labels the first two
`OpportunityGone` and the third `ScopeMoved`. That makes the first two
mislabels: the label's doc says `OpportunityGone` means the subject holds no
opportunity. Cause: when `select_scope`'s digest clause empties the match
list, it answers `NoOpportunity` (`controllers.rs` ~1552).
- In the narrative lane, the lookup digest clause is the only gate. A driver
resume with the fresh opportunity is refused there. Fork A's kernel-refusal
re-lowering (`1ef973a`) runs only when a caller passes the stale opportunity.
- Grouped lane (probed 2026-10-17, `771a79d`, by reading; `select_one` now
returns `ScopeMoved`): `run_group` maps every `select_one` error to
`LeftBeforeSelection`, which the driver records as `OpportunityGone`. A member
whose scope moved is dropped before any constituent, inference or submission
exists, so only the label is wrong; spend is identical and nothing branches on
the reason (`grouped-record-and-carry` keys on membership in `refused`). Own
cut: `cut-grouped-scope-moved-label.r1`.
### Who refuses a resumed narrative row whose scope moved? (probed 2026-10-17, `73f26a5`)
- **Today, at lookup, by the caller's digest.** `run_narrative`'s Confirmed
and CustodyUncertain arms (`controllers.rs` 3144, 3152) call
`row_answers_caller`, the only callers it has since `in-flight-gate`
(`771a79d`). A fresh caller is refused `OpportunityMismatch`; a stale caller
passes to Fork A. Nothing in Projector, Persona or Interpreter rounds reads
the world (source read: `self.select` is called only at fresh run, round
checks of the operational lane, and the other lanes' fresh paths).
- **The kernel path is already whole.** `submit_narrative`'s `ScopeChanged`
arm calls `interrupted`, which re-lowers once. A second move reads
`interrupted_from.is_some()` and ends the turn `overtaken`, with nothing
submitted and no further inference. The progression arm (~2375) refuses to
persist a second re-lowering even if the runner tried. Pinned by
`a_second_scope_change_after_the_re_lowering_spends_nothing`.
- **Probe** (Yggdrasil, ygg-verify rust, clone at `73f26a5`, sed in the job;
script `probe1.sh` in the imagination-ag5-narrative scratchpad): both lookup
arms put on `same_decision`, and `OpportunityMismatch` moved from `ScopeMoved`
to `OpportunityGone` in `classify`. `cargo test -p ghostlight --lib`: 803
passed, 3 failed. The failures were
`a_narrative_row_in_flight_whose_scope_moved_is_refused_before_inference`
(the resumed row now called the provider and ran the test port dry),
`a_narrative_row_in_flight_in_uncertain_custody_keeps_the_digest_gate`, and
`an_error_ends_a_cell_as_the_run_must_treat_it` (the classify table). No
verse driver test reached `ScopeMoved` through `OpportunityMismatch`.
- **`OpportunityMismatch` is no longer a moved scope anywhere.** After the cut
it arises from `same_decision` (another decision), `select_scope`'s
controller-id check, and the Persona lane's forged-field refusals. The driver
cannot reach a `same_decision` mismatch, because `run_cell` derives the
command id from world, cell, subject and tick.
- **Dead code.** Both `awaits_world` methods have no production caller once
`row_answers_caller` goes. The operational one has been test-only since
`771a79d`. The only other reader is the `NeverSentStore` test fixture.
## Model page
One row per persistent kind phase 1 touches. No cell may be empty.
@ -216,6 +288,7 @@ One row per persistent kind phase 1 touches. No cell may be empty.
| v1 body (`ghostlight-dungeon.service`, `/srv/ghostlight`, v1 state) | unit name; paths | retired in fact 2026-09-23; unit still enabled | nobody today; phase 1 assigns its removal to a gamecult-ops cut, data by operator ruling |
| Bonsai lifecycle (Raven containers) | container `bonsai`; scripts under `/opt/gamecult/bonsai` | started by hand ("Start AI Chat"); restarted by the RSS watchdog; stopped by the idle reaper | gamecult-ops/Raven; Dungeon only reads the endpoint; availability policy is an operator question |
| Repository docs (README, AGENTS, live architecture pages, handoff) | path on `main` | rewritten to the live machine; pre-rebuild material leaves `main` by operator ruling | the Ghostlight repo; history in git, dated cut documents and postmortems |
| Controller-work row (`controller-work.cc`, narrative and operational checkpoints) | `CommandId` (driver: derived from world, cell, subject, tick) | persisted before each spend; advanced only by the progression rule; a narrative row re-lowers at most once (`interrupted_from`), then commits, declines or ends overtaken | which decision a row answers: `same_decision`, both lanes, the caller naming identity only. Whether its scope moved: the world (operational: `ensure_scope_unchanged` before each round; narrative: the kernel's `ScopeChanged` at submit, answered by `interrupted`). Labels: `classify` alone |
### Where phase 2's verb sets plug in
@ -264,3 +337,16 @@ verbs as the target.
Dungeon tests that drive the real client, and nothing runs them. Fixing the
gate means a runner with both Rust and Node, which is Idunn's recipe and
runner surface: a follow-up, with each phase-1 Hands run doing them by hand.
- **A narrative resume has one detector, and it is the kernel** (ruling
`narrative-resume-relowers`). The caller's opportunity names the decision
and nothing more, in both lanes, through the one `same_decision`. The lanes
differ only in when the world is asked. The operational lane asks before each
round, because it has nothing to preserve. The narrative lane asks at submit,
because its prose and receipts survive to be lowered again. The price is the
remaining rounds plus at most one Interpreter call. `OpportunityMismatch`
then stops meaning a moved scope, so `classify` labels it `OpportunityGone`,
as the grouped lane already does. Keeping it on `ScopeMoved` would leave a
second, wrong answer to "did the scope move". The grouped selection label
becomes a pure function, because `AmbiguousOpportunity` cannot be built
through a live world, which offers one opportunity per scope. Pinning the
function is what closes follow-up `grouped-left-arms-pin`.

View file

@ -1,63 +1,50 @@
# Connector And Claude SDK Sidecar Bring-Up
No live smoke exists in this tree. The ignored test this file once documented,
`runtime::tests::live_smoke_seeds_then_ticks_a_world_against_the_connector`,
ran the production tick driver and the Active elaboration sweep against a real
CodexConnector; the play agent's Cut 1 (`d69e9d4`) deleted both, and the test
with them. A command that names it now matches nothing and exits 0. No
replacement exists. The real-model gate that does exist is the Idunn recipe's
`accept-real-persona-membrane` step (`deployment/idunn/recipe.toml`).
No automated live smoke exists in this tree. The one real-model test left is the
ignored `controllers::tests::real_local_model_cognition_modes_commit_speech`
(`crates/ghostlight/src/controllers.rs`), and a person runs it by hand with
`cargo test -p ghostlight -- --ignored real_local_model_cognition_modes_commit_speech`.
It needs either a local model server (`GHOSTLIGHT_LOCAL_ENDPOINT`) or the
connector (`GHOSTLIGHT_ACCEPTANCE_CONNECTOR=<host:port>` plus the systemd
credential below), and the `GHOSTLIGHT_CONTROLLER_*_MODEL`,
`GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID` and `GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG`
variables. The release gate passes if one of three attempts commits; every
failed attempt's prose is kept.
What remains true and stays here: bringing up a real CodexConnector and a
built Claude SDK sidecar. The seed lane (`world.seed`) still runs real
inference through `ControllerRunner`, and both transports below are how a
session gets real model responses instead of a fixture inference port.
## The connector
## Substrate
Ghostlight's connector lane speaks model-connector v4 to claude-connector, which
Eureka owns and runs on Yggdrasil at `127.0.0.1:4110`. Ghostlight is one of its
callers, identified as `ghostlight`. Connector models are `claude-haiku-5-5`,
`claude-sonnet-5-5` and `claude-opus-5-5`; any other name is refused
`ModelNotAllowed`. A required tool choice on `claude-sonnet-5-5` is refused as
an invalid request, and Ghostlight sends only `Auto`.
Machine-local, outside the repo: `F:\Projects\Ghostlight-smoke\`.
The connection key is never copied, printed or put in an environment variable.
`ConnectorBinding::key_path` names a file, read once when the port opens. Under
systemd that file is the credential the unit mounts:
- `codex-home\auth.json`: a copy of `~/.codex/auth.json`. The connector spawns
the official `codex app-server` child against this home and may refresh it.
- `connector\ghostlight.key`: 64 hex characters, no trailing newline; the
shared connection secret. Both sides read the same file.
- `connector\connector.cc`: the daemon's single-caller config.
- `logs\`: connector stdout/stderr and pid.
The connector binary is `F:\Projects\CodexConnector\target\debug\codex-connector.exe`
built from the repo head with the `daemon` feature. Ghostlight's `Cargo.lock`
pins the connector library at an older revision whose daemon does not build
against its own lockfile; the head daemon speaks the same wire law.
## Bring-up
Initialize the config once (the codex executable path and SHA-256 are the
newest `codex.exe` under `%LOCALAPPDATA%\OpenAI\Codex\bin\`):
```powershell
F:\Projects\CodexConnector\target\debug\codex-connector.exe --initialize-single-caller-config F:\Projects\Ghostlight-smoke\connector\connector.cc 127.0.0.1:4103 <codex.exe> <sha256> F:\Projects\Ghostlight-smoke\codex-home F:\Projects\Ghostlight-smoke\connector\replay.cc ghostlight-smoke F:\Projects\Ghostlight-smoke\connector\ghostlight.key 1 gpt-5.6-luna,gpt-5.6-sol,gpt-5.6-terra 4 1052672 16000
```bash
sudo systemd-run --wait --pipe \
-p LoadCredential=connector-key:/etc/gamecult/claude-connector/connection-ghostlight.key \
-E GHOSTLIGHT_ACCEPTANCE_CONNECTOR=127.0.0.1:4110 ... <test binary> --ignored
```
Start the daemon detached; it prints one ready line to stderr:
The ignored `live_connector_v4_completes_plain_tool_and_schema_requests` runs the
same way (it needs only `CREDENTIALS_DIRECTORY`) and checks a plain, a tool and
an output-schema request on haiku and a plain request on sonnet.
```powershell
$R='F:\Projects\Ghostlight-smoke'; $p = Start-Process -FilePath 'F:\Projects\CodexConnector\target\debug\codex-connector.exe' -ArgumentList @('--config', "$R\connector\connector.cc") -RedirectStandardOutput "$R\logs\connector.stdout.log" -RedirectStandardError "$R\logs\connector.stderr.log" -PassThru -WindowStyle Hidden; $p.Id | Out-File "$R\logs\connector.pid"
```
Stop it with `Stop-Process -Id (Get-Content F:\Projects\Ghostlight-smoke\logs\connector.pid)`.
A session that wants the connector reads
`GHOSTLIGHT_CONTROLLER_CONNECTOR=127.0.0.1:4103` and
`GHOSTLIGHT_CONTROLLER_CREDENTIAL='F:\Projects\Ghostlight-smoke\connector\ghostlight.key'`,
the same variables the deleted harness read.
Ghostlight's port is one shot
and returns a typed fault (`InferenceFaultClass`) whose disposition says whether
the owning flow may try again.
## Claude SDK route
`crates/ghostlight/src/sdk_inference.rs`'s `SdkInferencePort` gives any lane whose configured
model is `claude`-prefixed (matching `GHOSTLIGHT_SDK_MODEL_PREFIX`, default
`claude`) a second transport: a Node sidecar on the Claude Agent SDK instead of
the CodexConnector, so a session can run on the Claude subscription with no
Codex budget.
the connector, so a session can run on the Claude subscription with no
connector budget.
**Operator prerequisites, none of which Ghostlight performs:**
@ -86,10 +73,10 @@ GHOSTLIGHT_SDK_SIDECAR='F:\Projects\Ghostlight\sidecar\claude-sdk\dist\main.js'
GHOSTLIGHT_SDK_MODEL_PREFIX=claude # optional; this is already the default
```
`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all — a
`claude`-prefixed lane model then fails at open with `UnroutableModel` rather
than silently reaching the connector. Any of the five
`GHOSTLIGHT_CONTROLLER_*_MODEL` variables can be set to a `claude`-prefixed
model (for example `claude-opus-5`) to route that lane through the sidecar;
the connector variables are only required for lanes that still route to the
connector, and an all-`claude` configuration needs neither.
`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all: a
`claude`-prefixed lane model then routes to the connector, which serves the
`claude-*-5-5` models itself. With both bound, a model the connector serves
(`claude-<tier>-5-5`) under the sidecar's prefix is refused at open
(`SidecarClaimsConnectorModel`) rather than stolen by the sidecar; a model
such as `claude-opus-5` still reaches the sidecar.

View file

@ -2,11 +2,8 @@
"name": "ghostlight",
"private": true,
"version": "0.0.0",
"description": "Ghostlight: the Rust kernel for socially situated agents, and Ghostlight Dungeon, the single-player DM-led client.",
"description": "Ghostlight: the Rust kernel for socially situated agents.",
"scripts": {
"dungeon:build": "cargo build --workspace && npm --prefix web run build",
"dungeon:test": "cargo test --workspace && npm --prefix web run build",
"dungeon:run": "cargo run -p ghostlight-dungeon",
"sdk:build": "npm --prefix sidecar/claude-sdk run build",
"sdk:test": "npm --prefix sidecar/claude-sdk test"
},

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Some files were not shown because too many files have changed in this diff Show more