From a5bf35e2614ac5c46ff786cd85e3461e830f3248 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 11 Sep 2026 18:29:05 +0200 Subject: [PATCH] Scaffold Njordr: engine and shell, the state document, the fixture The engine crate carries the spec's nouns as typed state (dimensions, materials, sources, lots, recipes, facilities, discovery, knowledge, shipments, markets, carrier and producer policies), validate_catalog as the generation plan's first gate, and the pipeline fixture as a test-only constructor proven to be a well-formed state document. The shell is a binary that refuses to run until there is something to drive. Spec, map, and doctrine included. Co-Authored-By: Claude Fable 5.1 --- .gitignore | 3 + AGENTS.md | 49 +++ CLAUDE.md | 3 + Cargo.lock | 142 +++++++ Cargo.toml | 17 + LICENSE | 21 + README.md | 19 + crates/njordr-engine/Cargo.toml | 16 + crates/njordr-engine/src/lib.rs | 670 ++++++++++++++++++++++++++++++++ crates/njordr/Cargo.toml | 14 + crates/njordr/src/main.rs | 11 + docs/architecture/njordr.md | 514 ++++++++++++++++++++++++ state/map.yaml | 52 +++ 13 files changed, 1531 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 crates/njordr-engine/Cargo.toml create mode 100644 crates/njordr-engine/src/lib.rs create mode 100644 crates/njordr/Cargo.toml create mode 100644 crates/njordr/src/main.rs create mode 100644 docs/architecture/njordr.md create mode 100644 state/map.yaml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b59c51 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +**/*.rs.bk +Cargo.lock.orig diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5b513bf --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,49 @@ +# Njörðr Instructions + +Njörðr is the GameCult economy daemon: one economy organ serving Aetheria +and Delvehold, owning the economy whole. The specification is +`docs/architecture/njordr.md` and it is the authority for what this +repository builds; when code and spec disagree, say so and fix the one that +is wrong, never route around it. + +## Shape + +- `crates/njordr-engine`: the pure, deterministic step function over a state + document and a stream of exogenous events. No I/O, no environment, no + ports, no clock of its own, no knowledge of the shell. Every input reaches + it as one typed event it cannot attribute. This crate is embedded in the + Aetheria client over a C ABI, so nothing may enter it that cannot be + compiled there. +- `crates/njordr`: the shell. Lifecycle, the CultCache store per world, + CultMesh discovery and the Eve composition graph, the Ghostlight consumer + port, the game-host command port. It feeds the engine and persists what it + returns. It holds no opinion about a price. + +## Rules the spec makes non-negotiable + +- Prices, product properties, rarity, and quality are derived, never stored. +- Lots are conserved; provenance is permanent and acyclic. +- A property is a vector over authored dimensions, never a scalar quality. +- A recipe names roles, never materials; a role is filled by any lot that + meets it. +- The engine owns no trader and no maker; it executes authored policy. +- Fixtures before engine: a capability lands with the fixture that proves + it, and the catalog is validated by replay, not by reading. + +## Canonical state + +- `state/map.yaml` is the human-readable project map and carries the next + action. +- Evidence and scratch surfaces follow when there is enough of a body to + need them; do not create them ceremonially. + +## Session bootstrap + +1. Read `state/map.yaml` and `docs/architecture/njordr.md`. +2. Run `cargo test` and read the result line. +3. Restate the next action from the map before editing. + +Build and prove on the host the artifact runs on: the daemon on Linux +through the deploy path's builder, the engine's embedding on the Unity +target. A Windows compile is where the shell is, not where the artifact +runs. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..640c1a1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +Repository doctrine for this project lives in AGENTS.md, shared with Codex. + +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..3e9105b --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,142 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "njordr" +version = "0.1.0" +dependencies = [ + "anyhow", + "njordr-engine", +] + +[[package]] +name = "njordr-engine" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..056eafc --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[workspace] +members = [ + "crates/njordr-engine", + "crates/njordr", +] +resolver = "2" + +[workspace.package] +edition = "2024" +license = "MIT" +version = "0.1.0" + +[workspace.dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a6ddc3f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Meta Vens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e4ca67b --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# Njörðr + +The GameCult economy daemon. One economy for Aetheria and Delvehold, in +which every item is the product of a supply chain, materials fill roles at +different trade-offs, prices are a pure function of committed state, and the +economy both produces from player choices and reacts to them. + +Njörðr is two things. The engine (`crates/njordr-engine`) is a pure, +deterministic step function over a state document and a stream of typed +events; it does no I/O and is embedded in the Aetheria client for +single-player. The shell (`crates/njordr`) is the daemon around it: store, +discovery, ports, lifecycle. + +The specification is [`docs/architecture/njordr.md`](docs/architecture/njordr.md). +The map and next action are in [`state/map.yaml`](state/map.yaml). + +```bash +cargo test +``` diff --git a/crates/njordr-engine/Cargo.toml b/crates/njordr-engine/Cargo.toml new file mode 100644 index 0000000..f4047cb --- /dev/null +++ b/crates/njordr-engine/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "njordr-engine" +description = "The pure, deterministic economy engine: ledgers, recipes, quotes, policies, replay. No I/O." +edition.workspace = true +license.workspace = true +version.workspace = true + +[lib] +crate-type = ["rlib"] + +[dependencies] +serde.workspace = true +thiserror.workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/crates/njordr-engine/src/lib.rs b/crates/njordr-engine/src/lib.rs new file mode 100644 index 0000000..cc0ea19 --- /dev/null +++ b/crates/njordr-engine/src/lib.rs @@ -0,0 +1,670 @@ +//! Njörðr's engine: the state document and, in later cuts, the pure step +//! function over it. This crate performs no I/O, reads no environment, holds +//! no port, and knows nothing of the shell that feeds it. Everything here is +//! data the spec names (`docs/architecture/njordr.md`); everything derived +//! (a price, a product's properties, a rarity) is computed and never stored. +//! +//! This cut carries the seven nouns and the policies as typed state, plus the +//! one validation the generation plan needs before any step function exists: +//! a catalog whose references all resolve. The step function, the ledgers' +//! conservation, the quote function, and replay are the next cuts, and each +//! arrives with its fixture. + +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Authored names. Ids minted by the engine are sequence numbers so replay +/// mints the same ids; authored ids are strings the world chose. +macro_rules! authored_id { + ($name:ident) => { + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub String); + }; +} +macro_rules! minted_id { + ($name:ident) => { + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub u64); + }; +} + +authored_id!(DimensionId); +authored_id!(MaterialId); +authored_id!(ClassId); +authored_id!(RecipeId); +authored_id!(PlaceId); +authored_id!(RouteId); +authored_id!(HolderId); +authored_id!(MarketId); +authored_id!(SourceId); +minted_id!(LotId); +minted_id!(RunId); +minted_id!(ShipmentId); + +/// A conserved count. Unsigned, checked, unitless: the unit is the material's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Quantity(pub u64); + +/// Simulation time, in the world's own ticks. Deterministic by construction: +/// the engine never reads a clock; it is told the time with each event. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Time(pub u64); + +/// A dimension is a property axis or an operating condition, with a unit tag. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Dimension { + Property { unit: String }, + Condition { unit: String }, +} + +/// A property value is a scalar or a curve over one condition dimension. +/// Points are ordered by condition; evaluation is piecewise linear and clamps +/// to the end values, the shape Aetheria's heat performance curve already has. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "value", rename_all = "snake_case")] +pub enum PropertyValue { + Scalar { at: f64 }, + Curve { over: DimensionId, points: Vec<(f64, f64)> }, +} + +pub type Properties = BTreeMap; + +/// A class of stuff with authored properties. A produced material's +/// properties are derived from its lot and are never stored here. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Material { + pub class: ClassId, + pub properties: Properties, +} + +/// Where a lot begins: a deposit with a remaining quantity and a yield rate. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Source { + pub place: PlaceId, + pub material: MaterialId, + pub remaining: Quantity, + pub yield_per_tick: Quantity, +} + +/// How a lot came to be. Permanent; a seizure is in it forever. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "origin", rename_all = "snake_case")] +pub enum Provenance { + Extracted { source: SourceId, at: Time }, + Produced { run: RunId, inputs: Vec, at: Time }, + Seized { shipment: ShipmentId, by: HolderId, at: Time }, +} + +/// A quantity of one material at one place with one provenance. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Lot { + pub material: MaterialId, + pub quantity: Quantity, + pub place: PlaceId, + pub holder: Holder, + pub provenance: Provenance, +} + +/// Who holds a lot. A shipment holds its lots in transit. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "held_by", rename_all = "snake_case")] +pub enum Holder { + Subject { id: HolderId }, + Shipment { id: ShipmentId }, + Market { id: MarketId }, +} + +/// A bound on one dimension, optionally required across an envelope of one +/// condition dimension (so a curve-valued property must clear the bound at +/// every point of the envelope, not merely somewhere). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Requirement { + pub dimension: DimensionId, + pub min: Option, + pub max: Option, + pub envelope: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Envelope { + pub condition: DimensionId, + pub from: f64, + pub to: f64, +} + +/// A functional slot in a recipe, filled by any lot meeting its requirements. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Role { + pub name: String, + pub quantity: Quantity, + pub requirements: Vec, +} + +/// How one output dimension reads the lot filling a role. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Derivation { + pub output: DimensionId, + pub from_role: String, + pub from_dimension: DimensionId, +} + +/// A transformation stated as roles. `process` is the facility's requirements. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Recipe { + pub roles: Vec, + pub process: Vec, + pub output_class: ClassId, + pub output_quantity: Quantity, + pub derivations: Vec, + pub ticks: u64, +} + +/// A facility is a lot with process properties; this row binds the two. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Facility { + pub lot: LotId, + pub place: PlaceId, + pub owner: HolderId, +} + +/// One step of the tech tree: knowing `from` and running `research` may +/// unlock `unlocks`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct DiscoveryEdge { + pub from: Vec, + pub research: RecipeId, + pub unlocks: RecipeId, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Route { + pub from: PlaceId, + pub to: PlaceId, + pub cost_ticks: u64, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case")] +pub enum ShipmentStatus { + InTransit, + Arrived { at: Time }, + Lost { at: Time, to: HolderId }, +} + +/// A lot in motion. In transit, the shipment holds its lots. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Shipment { + pub lots: Vec, + pub carrier: HolderId, + pub route: RouteId, + pub departed: Time, + pub speed_ticks_per_cost: u64, + pub status: ShipmentStatus, +} + +/// A consumption rate and a reserve target for one class at one market. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct DemandRow { + pub class: ClassId, + pub consumed_per_tick: Quantity, + pub reserve_target: Quantity, +} + +/// What a market does with a lot by its provenance. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "admission", rename_all = "snake_case")] +pub enum Admission { + /// Refuse a seizure at any depth. + Strict, + /// Look `depth` levels into provenance; refuse a seizure found there. + Lax { depth: u32 }, + /// Accept anything; discount seized lots by `seized_discount` in [0, 1]. + Permissive { seized_discount: f64 }, +} + +/// A place-bound market: a reserve per class under a logarithmic market +/// scoring rule with liquidity `b`, authored demand rows, and an admission +/// policy. Prices are never stored; they are the quote function over this. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Market { + pub place: PlaceId, + pub liquidity_b: f64, + pub reserves: BTreeMap, + pub demand: Vec, + pub admission: Admission, +} + +/// A carrier's data: known routes, capacity, classes, margin, and a risk term +/// per route that rises with seizures and decays with time. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CarrierPolicy { + pub home: MarketId, + pub routes: BTreeSet, + pub capacity: Quantity, + pub classes: BTreeSet, + pub min_margin: f64, + pub risk: BTreeMap, + pub risk_decay_per_tick: f64, +} + +/// A producer's data: a facility, the recipes it may run, and a margin. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ProducerPolicy { + pub facility: LotId, + pub recipes: BTreeSet, + pub min_margin: f64, +} + +/// The engine's whole state at one revision. Everything the spec names as +/// owned is here; nothing derived is. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +pub struct EngineState { + pub revision: u64, + pub now: Time, + pub dimensions: BTreeMap, + pub materials: BTreeMap, + pub sources: BTreeMap, + pub places: BTreeSet, + pub routes: BTreeMap, + pub recipes: BTreeMap, + pub discovery: Vec, + pub known: BTreeMap>, + pub lots: BTreeMap, + pub facilities: BTreeMap, + pub shipments: BTreeMap, + pub markets: BTreeMap, + pub carriers: BTreeMap, + pub producers: BTreeMap, + pub next_lot: u64, + pub next_run: u64, + pub next_shipment: u64, +} + +impl Default for Time { + fn default() -> Self { + Time(0) + } +} + +/// A catalog reference that does not resolve. The generation plan refuses a +/// catalog on the first of these; the step function assumes none exist. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CatalogError { + #[error("{site} names dimension `{dimension}`, which is not declared")] + UnknownDimension { site: String, dimension: String }, + #[error("{site} uses `{dimension}` as a condition, but it is a property")] + NotACondition { site: String, dimension: String }, + #[error("{site} names material `{material}`, which is not declared")] + UnknownMaterial { site: String, material: String }, + #[error("{site} names place `{place}`, which is not declared")] + UnknownPlace { site: String, place: String }, + #[error("{site} names route `{route}`, which is not declared")] + UnknownRoute { site: String, route: String }, + #[error("{site} names recipe `{recipe}`, which is not declared")] + UnknownRecipe { site: String, recipe: String }, + #[error("recipe `{recipe}` derives from role `{role}`, which it does not declare")] + UnknownRole { recipe: String, role: String }, + #[error("{site} names market `{market}`, which is not declared")] + UnknownMarket { site: String, market: String }, + #[error("{site} names lot {lot}, which does not exist")] + UnknownLot { site: String, lot: u64 }, +} + +impl EngineState { + /// Every authored reference resolves, and every curve and envelope runs + /// over a condition. This is the first gate of the generation plan and + /// the precondition of every later function; nothing here reads a + /// quantity or a price. + pub fn validate_catalog(&self) -> Result<(), CatalogError> { + let dim = |site: String, id: &DimensionId| -> Result<&Dimension, CatalogError> { + self.dimensions.get(id).ok_or_else(|| CatalogError::UnknownDimension { + site, + dimension: id.0.clone(), + }) + }; + let condition = |site: String, id: &DimensionId| -> Result<(), CatalogError> { + match dim(site.clone(), id)? { + Dimension::Condition { .. } => Ok(()), + Dimension::Property { .. } => Err(CatalogError::NotACondition { + site, + dimension: id.0.clone(), + }), + } + }; + let requirement = |site: String, requirement: &Requirement| -> Result<(), CatalogError> { + dim(site.clone(), &requirement.dimension)?; + if let Some(envelope) = &requirement.envelope { + condition(site, &envelope.condition)?; + } + Ok(()) + }; + let place = |site: String, id: &PlaceId| -> Result<(), CatalogError> { + if self.places.contains(id) { + Ok(()) + } else { + Err(CatalogError::UnknownPlace { + site, + place: id.0.clone(), + }) + } + }; + let recipe_ref = |site: String, id: &RecipeId| -> Result<(), CatalogError> { + if self.recipes.contains_key(id) { + Ok(()) + } else { + Err(CatalogError::UnknownRecipe { + site, + recipe: id.0.clone(), + }) + } + }; + let lot_ref = |site: String, id: LotId| -> Result<(), CatalogError> { + if self.lots.contains_key(&id) { + Ok(()) + } else { + Err(CatalogError::UnknownLot { site, lot: id.0 }) + } + }; + + for (id, material) in &self.materials { + for (dimension, value) in &material.properties { + let site = format!("material `{}`", id.0); + dim(site.clone(), dimension)?; + if let PropertyValue::Curve { over, .. } = value { + condition(site, over)?; + } + } + } + for (id, source) in &self.sources { + let site = format!("source `{}`", id.0); + place(site.clone(), &source.place)?; + if !self.materials.contains_key(&source.material) { + return Err(CatalogError::UnknownMaterial { + site, + material: source.material.0.clone(), + }); + } + } + for (id, route) in &self.routes { + let site = format!("route `{}`", id.0); + place(site.clone(), &route.from)?; + place(site, &route.to)?; + } + for (id, recipe) in &self.recipes { + let site = format!("recipe `{}`", id.0); + for role in &recipe.roles { + for r in &role.requirements { + requirement(format!("{site} role `{}`", role.name), r)?; + } + } + for r in &recipe.process { + requirement(format!("{site} process"), r)?; + } + for derivation in &recipe.derivations { + dim(site.clone(), &derivation.output)?; + dim(site.clone(), &derivation.from_dimension)?; + if !recipe.roles.iter().any(|role| role.name == derivation.from_role) { + return Err(CatalogError::UnknownRole { + recipe: id.0.clone(), + role: derivation.from_role.clone(), + }); + } + } + } + for (index, edge) in self.discovery.iter().enumerate() { + let site = format!("discovery edge {index}"); + for from in &edge.from { + recipe_ref(site.clone(), from)?; + } + recipe_ref(site.clone(), &edge.research)?; + recipe_ref(site, &edge.unlocks)?; + } + for (holder, recipes) in &self.known { + for recipe in recipes { + recipe_ref(format!("holder `{}` knowledge", holder.0), recipe)?; + } + } + for (id, lot) in &self.lots { + let site = format!("lot {}", id.0); + place(site.clone(), &lot.place)?; + if !self.materials.contains_key(&lot.material) { + return Err(CatalogError::UnknownMaterial { + site, + material: lot.material.0.clone(), + }); + } + } + for (lot, facility) in &self.facilities { + let site = format!("facility on lot {}", lot.0); + lot_ref(site.clone(), *lot)?; + place(site, &facility.place)?; + } + for (id, shipment) in &self.shipments { + let site = format!("shipment {}", id.0); + if !self.routes.contains_key(&shipment.route) { + return Err(CatalogError::UnknownRoute { + site, + route: shipment.route.0.clone(), + }); + } + for lot in &shipment.lots { + lot_ref(site.clone(), *lot)?; + } + } + for (id, market) in &self.markets { + place(format!("market `{}`", id.0), &market.place)?; + } + for (holder, carrier) in &self.carriers { + let site = format!("carrier `{}`", holder.0); + if !self.markets.contains_key(&carrier.home) { + return Err(CatalogError::UnknownMarket { + site, + market: carrier.home.0.clone(), + }); + } + for route in carrier.routes.iter().chain(carrier.risk.keys()) { + if !self.routes.contains_key(route) { + return Err(CatalogError::UnknownRoute { + site, + route: route.0.clone(), + }); + } + } + } + for (holder, producer) in &self.producers { + let site = format!("producer `{}`", holder.0); + lot_ref(site.clone(), producer.facility)?; + for recipe in &producer.recipes { + recipe_ref(site.clone(), recipe)?; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(s: &str) -> DimensionId { + DimensionId(s.into()) + } + + /// The spec's pipeline fixture, as far as this cut can state it: copper, + /// aluminium, and gold conductors; a vapour-chamber part whose capacity is + /// a curve over temperature; a thruster recipe with a spreader role and a + /// hot variant; two markets on one route with a strict and a permissive + /// admission. Later cuts run it; this one proves it is a well-formed + /// state document. + pub(crate) fn fixture() -> EngineState { + let mut state = EngineState::default(); + for (name, kind) in [ + ("thermal_conductivity", Dimension::Property { unit: "W/m·K".into() }), + ("heat_transfer_capacity", Dimension::Property { unit: "W".into() }), + ("density", Dimension::Property { unit: "kg/m³".into() }), + ("precision", Dimension::Property { unit: "ratio".into() }), + ("cooling", Dimension::Property { unit: "W".into() }), + ("temperature", Dimension::Condition { unit: "K".into() }), + ] { + state.dimensions.insert(d(name), kind); + } + let metal = |k: f64, rho: f64| Material { + class: ClassId("conductor".into()), + properties: BTreeMap::from([ + (d("thermal_conductivity"), PropertyValue::Scalar { at: k }), + (d("heat_transfer_capacity"), PropertyValue::Scalar { at: k }), + (d("density"), PropertyValue::Scalar { at: rho }), + ]), + }; + state.materials.insert(MaterialId("copper".into()), metal(400.0, 8960.0)); + state.materials.insert(MaterialId("aluminium".into()), metal(237.0, 2700.0)); + state.materials.insert(MaterialId("gold".into()), metal(315.0, 19300.0)); + state.materials.insert( + MaterialId("vapour_chamber".into()), + Material { + class: ClassId("spreader_part".into()), + properties: BTreeMap::from([ + ( + d("heat_transfer_capacity"), + PropertyValue::Curve { + over: d("temperature"), + points: vec![(250.0, 0.0), (300.0, 900.0), (400.0, 900.0), (450.0, 0.0)], + }, + ), + (d("density"), PropertyValue::Scalar { at: 1200.0 }), + ]), + }, + ); + state.materials.insert( + MaterialId("lathe".into()), + Material { + class: ClassId("facility".into()), + properties: BTreeMap::from([(d("precision"), PropertyValue::Scalar { at: 0.9 })]), + }, + ); + for place in ["sere_steps", "high_gate"] { + state.places.insert(PlaceId(place.into())); + } + state.routes.insert( + RouteId("sere_run".into()), + Route { from: PlaceId("sere_steps".into()), to: PlaceId("high_gate".into()), cost_ticks: 10 }, + ); + state.sources.insert( + SourceId("copper_vein".into()), + Source { + place: PlaceId("high_gate".into()), + material: MaterialId("copper".into()), + remaining: Quantity(10_000), + yield_per_tick: Quantity(5), + }, + ); + let spreader = |lo: f64, hi: f64| Role { + name: "spreader".into(), + quantity: Quantity(1), + requirements: vec![ + Requirement { + dimension: d("heat_transfer_capacity"), + min: Some(100.0), + max: None, + envelope: Some(Envelope { condition: d("temperature"), from: lo, to: hi }), + }, + Requirement { dimension: d("density"), min: None, max: Some(3000.0), envelope: None }, + ], + }; + let thruster = |lo: f64, hi: f64| Recipe { + roles: vec![spreader(lo, hi)], + process: vec![Requirement { dimension: d("precision"), min: Some(0.8), max: None, envelope: None }], + output_class: ClassId("thruster".into()), + output_quantity: Quantity(1), + derivations: vec![Derivation { + output: d("cooling"), + from_role: "spreader".into(), + from_dimension: d("heat_transfer_capacity"), + }], + ticks: 4, + }; + state.recipes.insert(RecipeId("thruster_cool".into()), thruster(300.0, 400.0)); + state.recipes.insert(RecipeId("thruster_hot".into()), thruster(300.0, 500.0)); + state.markets.insert( + MarketId("steps_market".into()), + Market { + place: PlaceId("sere_steps".into()), + liquidity_b: 100.0, + reserves: BTreeMap::from([(ClassId("conductor".into()), Quantity(200))]), + demand: vec![DemandRow { + class: ClassId("thruster".into()), + consumed_per_tick: Quantity(1), + reserve_target: Quantity(20), + }], + admission: Admission::Strict, + }, + ); + state.markets.insert( + MarketId("gate_black".into()), + Market { + place: PlaceId("high_gate".into()), + liquidity_b: 40.0, + reserves: BTreeMap::new(), + demand: Vec::new(), + admission: Admission::Permissive { seized_discount: 0.4 }, + }, + ); + state.carriers.insert( + HolderId("kestrel".into()), + CarrierPolicy { + home: MarketId("steps_market".into()), + routes: BTreeSet::from([RouteId("sere_run".into())]), + capacity: Quantity(50), + classes: BTreeSet::from([ClassId("conductor".into())]), + min_margin: 0.1, + risk: BTreeMap::new(), + risk_decay_per_tick: 0.01, + }, + ); + state + } + + #[test] + fn the_fixture_is_a_well_formed_state_document() { + let state = fixture(); + assert_eq!(state.validate_catalog(), Ok(())); + let encoded = serde_json::to_string(&state).unwrap(); + let decoded: EngineState = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, state); + } + + #[test] + fn a_curve_over_a_property_and_a_dangling_reference_are_refused() { + let mut state = fixture(); + state + .materials + .get_mut(&MaterialId("vapour_chamber".into())) + .unwrap() + .properties + .insert( + d("heat_transfer_capacity"), + PropertyValue::Curve { over: d("density"), points: vec![(0.0, 1.0)] }, + ); + assert!(matches!( + state.validate_catalog(), + Err(CatalogError::NotACondition { .. }) + )); + + let mut state = fixture(); + state.recipes.get_mut(&RecipeId("thruster_hot".into())).unwrap().derivations[0].from_role = + "housing".into(); + assert_eq!( + state.validate_catalog(), + Err(CatalogError::UnknownRole { recipe: "thruster_hot".into(), role: "housing".into() }) + ); + + let mut state = fixture(); + state.carriers.get_mut(&HolderId("kestrel".into())).unwrap().routes.insert(RouteId("ghost_run".into())); + assert!(matches!(state.validate_catalog(), Err(CatalogError::UnknownRoute { .. }))); + } +} diff --git a/crates/njordr/Cargo.toml b/crates/njordr/Cargo.toml new file mode 100644 index 0000000..6f9ca82 --- /dev/null +++ b/crates/njordr/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "njordr" +description = "The shell: lifecycle, CultCache store, CultMesh, the Ghostlight and game-host ports. It feeds the engine events and persists what it returns." +edition.workspace = true +license.workspace = true +version.workspace = true + +[[bin]] +name = "njordr" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +njordr-engine = { path = "../njordr-engine" } diff --git a/crates/njordr/src/main.rs b/crates/njordr/src/main.rs new file mode 100644 index 0000000..d397fd7 --- /dev/null +++ b/crates/njordr/src/main.rs @@ -0,0 +1,11 @@ +//! The shell. This cut has no store, no ports, and no world, and says so +//! rather than pretending: a daemon earns its process when the engine has a +//! step function to drive and a store to persist. Until then the binary +//! exists so the engine/shell split is a workspace fact, not a plan. + +fn main() -> anyhow::Result<()> { + anyhow::bail!( + "njordr {}: no world configured; the engine has a state document and no step function yet (see docs/architecture/njordr.md)", + env!("CARGO_PKG_VERSION") + ) +} diff --git a/docs/architecture/njordr.md b/docs/architecture/njordr.md new file mode 100644 index 0000000..8b0d4c9 --- /dev/null +++ b/docs/architecture/njordr.md @@ -0,0 +1,514 @@ +# Njörðr, the GameCult economy daemon + +Status: specification, 2026-09-11. Nothing is built. The daemon is Njörðr, +repository `GameCult/Njordr` (ASCII spelling for the repo; the name keeps its +letters in prose); no repository exists yet. + +## Objective + +One economy organ serving Aetheria and Delvehold, in which every item is the +product of a supply chain, materials are interchangeable within a role at +different trade-offs, prices are a pure function of committed state, and the +economy both produces from player choices and reacts to them. Consequences +authored in Ghostlight (a closed route, a defaulted promise, a witnessed +collapse) reach players as prices; player choices (what was crafted from +what, where it was sold) reach Ghostlight's people as facts and pressures. + +## What the two games already hold + +Aetheria's shared model (`Assets/Scripts/ServerShared/ItemData.cs`, +`ItemInstance.cs`, `ItemManager.cs`) carries a scalar `Quality` on every +crafted instance, a `Price` integer on the item datum, and stats evaluated as +`lerp(min, max, quality^exponent)`. The legacy model kept the better idea and +lost it to a breach: a crafted instance remembered every ingredient instance, +and a stat named the ingredient whose quality it read +(`Aetheria-legacy/Assets/Scripts/Item.cs` line 385). Delvehold's design +(`Game Design/HOLD/Production and Logistics.md`) already states the target +rule: "Every transformation records recipe or method, consumed and produced +lots, operator or automation, facility, time, quality-relevant conditions, +and provenance," and "players specialize sites, trade, commission, use +institutional services, or accept less efficient substitutes." The daemon is +the single owner of that rule for both games. + +Ghostlight keeps a unitless conserved ledger and no prices, by construction +(`Quantity` has no unit "because a unit is where prices enter"). That stance +does not change. The daemon is where units, properties, and prices live, and +it reaches Ghostlight only through the consumer contract +(Ghostlight `docs/architecture/ghostlight-world-consumer-api.md`) as one more consumer that owns market +mirrors. + +## The model + +Seven nouns. Everything else is derived. + +**Dimension.** A named property axis with a unit tag, authored per world: +`thermal_conductivity (W/m·K)`, `density (kg/m³)`, `tensile_strength`, +`corrosion_resistance`, and in other worlds `aether_conductance`, +`mana_capacity`, `hex_resistance`. Some dimensions are **operating +conditions** rather than properties: `temperature`, `pressure`, `aether +density`. A property value is either a scalar or a curve over one condition +dimension, so a vapour chamber's `heat_transfer_capacity` is a curve over +`temperature` that falls to nothing outside its working band, while a copper +block's is a flat line. Curves are the same piecewise shape Aetheria's +shared model already uses for heat performance. The daemon is genre-neutral +because a dimension is data. A world declares its dimensions once; nothing +in the daemon names one. + +**Material.** A class of stuff with a property vector over the world's +dimensions and a base extraction or synthesis source. Copper, aluminium, gold +are three materials sharing most dimensions with different values. A +material may itself be the product of a recipe (an alloy, a refined ore, a +grown culture), in which case its property vector is derived from its lot, +not authored. + +**Lot.** A quantity of one material at one place with one provenance: +extracted at a site, or produced by one recipe run from named input lots. A +lot's property vector is its material's for an authored material, or the +recipe's output function applied to its inputs for a produced one. Lots are +conserved: a recipe run consumes input lots and produces output lots, a +transfer moves a lot between holders and places, and nothing else creates or +destroys quantity except an extraction with a source and a consumption with a +sink. Provenance is the DAG of lot ids through recipe runs, acyclic by +construction because a run's outputs are minted after its inputs are +consumed. This is the legacy "remembers every ingredient," made durable and +queryable rather than carried on the instance. + +**Recipe.** A transformation stated as roles, not ingredients. Each role names +a functional requirement over dimensions, a quantity, and how the output's +properties read the lot filling the role. A role is filled by any lot, raw +or produced: `spreader: heat_transfer_capacity ≥ 100 over the recipe's +temperature envelope, density ≤ 3000` is filled by a block of copper, by a +produced vapour-chamber part, or by whatever the world's physics offers, +and the recipe never names which. A requirement over a curve-valued property +states the envelope it must hold across, so a vapour chamber that fails hot +fills a cool recipe and not a hot one. A recipe also names a **process** +role: the facility, tool, and practice that run it, which carry their own +dimensions (`precision`, `throughput`, `contamination`) and are filled by +the workshop's actual station and operator. Substitution is therefore not a +special case and needs no optional roles or alternate recipes: any lot +meeting the role's requirement fills it, the output's derived properties +carry the difference (a thruster's cooling curve is its spreader's capacity +curve through the recipe's output function), and the market prices it. + +**Product.** A produced lot with a property vector, a product class, and its +provenance. There is no scalar quality on the product. Game stats read the +product's properties by dimension the way the legacy stat read a named +ingredient's quality: a thruster's output reads its conductor's +`thermal_conductivity`, its housing's `density`, and its process's +`precision`. Rarity tiers, star ratings, and "quality" are projections a game +computes for display from the vector, never inputs. A scalar quality on the +instance is what the breach left; it does not come back. + +**Source.** Where a lot begins: a deposit at a place, of one material, with +a remaining quantity and a yield rate. Extraction moves quantity from the +source's remaining into a new lot, so a deposit is inside the same +conservation and depletion is a ledger row reaching zero, never a script. An +extraction policy is a producer policy with no input roles: a facility at a +source, the class it yields, and a margin. In Aetheria a worked source is +materialized like a shipment, by place instead of by route: the host asks +what sources are being worked in a zone and by whom, instantiates the +miners, drones, and the field bound to the source id and revision, and the +player may mine the same deposit against the concern working it, seize its +unsold lots, or sell into the same market. For Ghostlight-owned holders an +extraction arrives as an admit with Njörðr's receipt as evidence, the one +way Ghostlight's ledger gains quantity, and a depleted deposit is a witnessed +event over the place. + +**Shipment.** A lot in motion: one or more lots, a carrier subject, a route, +a departure revision, and an arrival derived from the route's cost and the +carrier's speed. While a shipment is in transit its lots are held by the +shipment, not by the sender or the receiver, so a seized cargo is a custody +change on the shipment and nothing else has to be repaired. A shipment is +how economic activity becomes concrete: a price gap across a route is not +closed by an arithmetic transfer but by a carrier deciding to move a lot, +and that carrier, its cargo, and its position along the route are world +facts a player can meet. The daemon owns the shipment ledger; it owns no +carrier's decision to sail. + +Two consequences of the model that the games asked for: + +- An exceptional item is a product of a well-managed supply chain by + construction. Its properties are its inputs' properties through the + recipe's output function, and its provenance names every choice that made + it so. +- "Functionally interchangeable with different trade-offs" is the recipe's + role requirement plus the market's price. The daemon never ranks materials; + the dimensions and the prices do. + +## Discovery, the tech tree, and retooling + +A recipe exists in the catalog from seeding; a holder runs only the recipes +it **knows**, and knowing is a per-subject row that changes through +discovery. Discovery is a producer policy whose output is a recipe-known row +rather than a lot: a facility with research dimensions consumes lots and +time and unlocks the next process along a **discovery DAG** the world +authors. The tech tree is that DAG plus the per-holder knowledge state; +there is no separate tech-tree mechanism. Online, a discovery is also a +fact witnessed in Ghostlight, so a process can be sold, leaked, or stolen +like any other knowledge. A discovered process that improves a material is +just a recipe producing a variant whose properties clear a role the old +material could not (a structural ceramic), and every recipe with that role +gains a substitute the moment someone can make it. + +A **facility** is a lot like any other, with process dimensions. A recipe +requires a facility meeting its process requirements, and **retooling** is +a recipe that consumes the old facility, lots, and time and produces the new +one. A producer policy compares margins with the retool included, so a +design that is better but too different does not reach market because +nobody's margin clears the rebuild, and it reaches market the day a player +or a pressured subject eats that cost. Nothing is authored to say so. + +## Generating the catalog + +The catalog will not materialize and will not be hand-authored at the scale +two worlds need. The plan: + +1. Hand-author the physics: the world's dimensions, its materials with their + property tables, and its product classes with the roles they need. Tens, + then hundreds. Human-owned and lore-grounded. +2. Generate recipes, processes, and discovery edges with a seed lane, not a + script: Ghostlight's elaboration lane already authors typed structure + through tools with validation, gap recording, and refusal continuation + against a stated shortfall. The same lane, pointed at Njörðr's catalog + with recipe, process, and discovery-edge tools, is given the shortfall + "every product class producible from seeded sources through recipes + known at seed" and proposes until the engine's closure check clears. +3. Validate by running, not reading: replay the seeded world for a fixed + span with no players and refuse a catalog where a class has no producer, + a source feeds nothing, a quote runs away, or a discovery unlocks a + recipe nothing can fill. The seeding run's output is the catalog plus + the replay that proves it closes. +4. Ground in lore per repository doctrine: Aetheria's recipes come from what + AetheriaLore says its factions and species make, Delvehold's from the + Greathold canon, and a gap the generator finds is pushed back into the + lore vault as an elaboration, the way Ghostlight already does for scenes. + +## Markets and prices + +A **market** is a place-bound institution with a liquidity reserve per +material class and a demand profile. In Ghostlight terms a market is an +externally controlled mirror subject the daemon owns: Ghostlight's people may +stand in it, transact toward it, witness facts in it, and never mutate it. +Several markets exist per world, one configured mirror each. + +A **price** is a pure function of committed daemon state at a revision: the +market's reserve of the class, its demand profile, the route cost to the +nearest markets holding the class, and a liquidity parameter. Use the +standard mechanism rather than a bespoke one: a per-market, per-class +automated market maker (a logarithmic scoring rule or constant-function +curve, chosen at build for its bounded loss) quoting against the reserve, +with tatonnement between markets carried by shipments, not by the daemon: a +price gap across a route is an opportunity for a Ghostlight subject or a +player to move a lot, the move is a shipment, and its arrival is what closes +the gap. The daemon owns no trader and never moves a lot on its own. + +**Demand** is a rate, not a wish. A demand row on a market is a consumption +rate per class per unit of simulation time plus a reserve target, and +consumption is a real lot sink, so a market that is oversupplied has its +reserve drawn down at the rate its people use the class and its price finds +a floor there rather than at zero. Rows enter three ways and are typed the +same way: a Delvehold Hold's ratified policy (mandates, reserves, rationing); +a Ghostlight population's needs as pressure and dependency deltas through +the outbound batch; a player's or a workshop's standing orders. None is +privileged. **Intermediate demand is derived, never authored**: a producer +policy (below) that would run a recipe at current quotes contributes its +input needs as demand rows on the markets it buys from, so a crash in a +product's price stops its producers, withdraws their demand for inputs, +lowers the inputs' quotes, and cheapens everything else made from them. That +propagation through the recipe graph, in both directions, is how a player +who floods one class moves the prices of classes they never touched. + +**Admission** is a market policy over provenance. Every lot's provenance is +permanent and a seizure is in it forever, so a market may refuse, accept, or +discount a lot by what its provenance contains and how deep it looks. A +legitimate market refuses a seizure at any depth; a black market accepts it +at a discount; a lax market looks one level deep, so a re-smelted seized +ingot passes there and nowhere stricter. A black market is therefore an +ordinary market with a permissive admission policy at its own place, and a +diverted shipment is still in play: its lots re-enter supply wherever they +are admitted, and the shortage they caused at their destination is answered +by whoever the destination's quote draws. + +**Cornering** is possible and expensive by construction. Buying a reserve out +walks the quote up the scoring rule's curve, and the maker's loss is bounded, +so a market cannot be bankrupted by a corner. What answers a corner is +supply: price gaps pull shipments, and producers make more. A market that no +carrier's routes reach and no producer serves is a shortage nobody answers, +which is why seeding carries the rule below. + +**Quotes.** A proposed trade is quoted against a named revision and honoured +only against that revision; a stale quote is refused, never repriced +silently. This is the same idempotency and staleness rule the Ghostlight +consumer contract uses, and it is what makes a price replayable: replaying +the committed lot and demand events reproduces every price ever quoted. + +## The two directions + +**Ghostlight to prices.** The outbound consumer batch (next on Ghostlight's +map) is designed as this daemon's signal surface: custody deltas by holder, +resource, and place; pressure and dependency deltas by subject; route open, +close, and cost changes; witnessed events by place subtree. The daemon lowers +custody deltas onto its lots for Ghostlight-owned holders, pressure and +dependency deltas onto demand profiles, route changes onto its route-cost +table, and events onto shocks. A collapsed grate above a basin town is a +route closure and a witnessed event; its price consequence is derived, not +authored. + +**Prices to Ghostlight.** The daemon writes back through consumer patches: a +price at a market is a fact witnessed at the market place, landing as +knowledge on everyone standing there and reaching a Persona as prose; a +shortage is a pressure on the holders who depend on the class; a realized +trade is a custody change on the Ghostlight subject, with the daemon's +receipt as evidence. A Ghostlight person's intent to buy exits as an +attributed proposal, the daemon quotes and executes it against its revision, +and the realized custody returns through the receipt. One tick of latency +between wanting and holding is the design, and the Projector renders a +pending intent as "asked, not yet answered". + +**Players to prices.** A game host submits lot events as typed CultMesh +commands with receipts: extract, run recipe, transfer, consume, sell, buy. +The daemon validates against the recipe catalog and the lot ledger, commits +atomically, and the market maker's next quote reflects the new reserve. A +player who floods a market with aluminium spreaders lowers their price and +raises copper's relative standing; a workshop that buys every lot of a scarce +conductor raises its price in every market a route reaches. + +## Two consumer profiles + +The model is one; the granularity at which a game consumes it is not. + +**Delvehold, the boundary profile.** All player agency occurs inside the +Greathold, which is a strict boundary. Njörðr owns the interior economy as +much as the exterior: a Hold's workshops, facilities, inventories, and +orders are its lots, recipes, and markets, and a Hold's ratified policy +reaches it as demand rows and carrier policies. What the boundary bounds is +Ghostlight's reach, not Njörðr's: the outside world reaches players as +arrivals, prices, and news at the boundary subject, batched per tick; a +shipment outside the Greathold is abstract until it arrives, and no player +can meet it on the road. The integration note +(Ghostlight `docs/architecture/delvehold-forced-ontology-integration.md`) describes the Ghostlight side +of this shape; its "Delvehold owns its own quantitative economy" sentence is +superseded by this document. + +**Aetheria, the interspersed profile.** Player actors are spread through the +whole world and get to meddle with all of it. Nothing economic may stay +abstract where a player is: a shipment on a route a player is flying is a +ship with a hold full of lots, and piracy is the canonical case. This needs +three things the boundary profile does not: + +- Materialization. The Aetheria host asks Njörðr for the shipments whose + derived position lies inside a zone a player occupies, and instantiates + each as an entity whose cargo is the shipment's lots by id. The entity is + a rendering of the shipment, bound to its id and revision; it is not a + second truth about where the cargo is. When no player is present the + shipment progresses abstractly by route cost and time, and the two + descriptions must agree at the boundary: a materialized ship's position is + the derived one at the moment of materialization, and its arrival is + whichever comes first, the derived arrival or the host's committed docking. +- Interception. A seizure is a command from the host carrying the shipment + id, the revision it was materialized against, the seizing holder, and the + combat receipt as evidence. Njörðr moves the lots from the shipment to the + seizer, marks the shipment lost, and refuses the command if the shipment's + revision moved (it arrived, or was already taken) exactly as a stale quote + is refused. The same command shape serves a legitimate boarding, a + customs seizure, a salvage, and a wreck. +- Cadence. The interspersed profile emits and consumes events per zone as + they happen, not per world tick. A seizure reaches Ghostlight at once as a + custody change on the carrier's owner, a witnessed event over the route's + places, and a pressure on whoever was owed the cargo; the destination + market's next quote reflects the lot that will not arrive. Consequence is + expressed as price, as news, and as a promise now in default, and all + three are derived from the one committed seizure. + +Both profiles use the one lot ledger, the one shipment ledger, and the one +quote function. The difference is which events a host subscribes to and at +what grain, which is subscription configuration, not a second model. + +## Authority map + +- Owner: Njörðr owns dimensions, materials, sources, lots, recipes, + facilities, per-holder recipe knowledge, the discovery DAG, products, + shipments, markets, demand rows, and prices for every world it serves. One + process, one CultCache store per world, one revision counter per world. +- Inputs: authored catalogs (dimensions, materials, recipes, facilities) per + world; lot and trade commands from game hosts; the Ghostlight outbound + batch; policy demand documents from Delvehold's civic organs. +- Outputs: price and reserve projections per market as CultMesh state + lowered to Eve; quotes and receipts; consumer patches to Ghostlight; + provenance and property queries for any lot. +- Derived state: every price, every product property vector, every rarity + projection, every "quality". None is stored as truth; all are recomputed + from lots, recipes, demand, and routes at a revision. +- Forbidden writers: a game host writes no price and moves no lot except by + a command with a receipt; a materialized entity is never the position of + record; Ghostlight writes no lot; + the daemon writes no Ghostlight component except through a consumer patch + the kernel validates; no client, projection, cache, or Eve surface commits + anything; no material carries a scalar quality; no recipe names a material + where a role will do. +- Shared paths: player trades, Ghostlight-subject trades, institutional + procurement, and replay all pass through the one lot ledger and the one + quote function. There is no second price path for NPCs. +- Deletion line: Aetheria's `ItemData.Price`, `CraftedItemInstance.Quality`, + and `ItemManager.GetPrice` become projections read from the daemon or are + cut; the commented-out `Ingredients` and `Blueprint` fields are not + restored, because provenance lives on the lot. + +## Engine and shell + +Njörðr is two things, and the split is load-bearing. The **engine** is a +pure, deterministic step function over a state document, a stream of typed +events, and a clock: it owns the lot and shipment ledgers, the recipe and +property derivation, the quote function, carrier policy execution, and +replay, and it performs no I/O, reads no environment, and holds no port. The +**shell** is the daemon: CultMesh discovery, the Eve composition graph, the +Ghostlight consumer port, the game host command port, the CultCache store, +and lifecycle. The shell feeds the engine events and persists what it +returns. Nothing in the engine knows whether a shell exists. + +Two consequences: + +- Every input reaches the engine as an **exogenous event** of one typed + shape, whatever its origin: a Ghostlight outbound batch lowered by the + shell, a game host's lot command, a Delvehold policy document, or an + authored script. The engine cannot tell where an event came from, and that + is the invariant that makes the single-player mode below the same machine + rather than a second one. +- Nobody decides inside the engine. Carriers execute **carrier policies** + and producers execute **producer policies**, and both are data. A carrier + policy is a home market, a set of known routes, a capacity, the classes it + carries, a minimum margin after route cost, and a risk term per route that + rises with seizures on it and decays with time; each step the carrier + sails the best known route above its margin. A producer policy is a + facility, the recipes it can run, and a margin; each step it runs the + recipe whose output quote clears its input quotes plus margin, and its + planned inputs are the derived demand above. Online, a Ghostlight subject + amends its own policy through a consumer command, and its name, route, + and grudge stay Ghostlight's. Offline, the seeded policies run unchanged. + The engine owns no trader and no maker in either mode; it owns the + executor of authored policy. Seeding rule: every market is on at least one + carrier's route set or is marked unserved, and unserved is a fact + Ghostlight receives, because a shortage nobody can answer is a story, not a + bug. + +## Modes + +**Online.** The shell runs as a daemon beside Ghostlight and the game hosts. +Ghostlight's outbound batch is lowered to exogenous events; prices and +seizures return through consumer patches; both games' hosts submit lot +commands with receipts. This is the multiplayer body. + +**Seeded single-player, Aetheria.** The full machine runs once to make a +world: Ghostlight and Njörðr together seed the initial state, and a separate +branching-narrative pass, not yet begun, authors what the story needs to +happen. The handover artifact is exactly two documents plus the engine: + +1. the engine's state document at the seed revision, as CultCache; and +2. an **exogenous event script**: authored demand rows, shocks, route + changes, and carrier policy amendments keyed to simulation time, produced + by the seeding run and the narrative pass. + +The client then runs the engine locally with a deterministic clock and a +seeded `CultMath.Random`, replays the script as time passes, and applies +the player's own lot commands into the same stream. "Precalculated narrative +price movements" are therefore precalculated **events**, never precalculated +prices. A script that pinned prices would make the player's choices inert +against the story; a script of shocks and demand keeps every price a pure +function of committed state, so the player who floods a market during a +scripted shortage moves the outcome, and the story's pressure still lands. +Save and load are engine checkpoints; a checkpoint plus the script replays +to the same state. + +The engine must therefore be embeddable in the Aetheria client. Rust with a +C ABI as a Unity native plugin is the default under Odin-class doctrine; a +second implementation of the engine in C# is refused, because two +implementations of a deterministic step function are two truths the moment +one is patched. + +## Why a daemon + +An organ earns a process only when independent lifecycle, privilege, +resource, or failure isolation protects a named invariant. The invariants +here are lot conservation and price determinism across two game hosts that +start, stop, and fail independently of each other and of Ghostlight's world +ticks. A price computed inside either game host would fork the ledger the +moment the other host wrote; a price computed inside Ghostlight would put +units into a kernel built to have none. The daemon is the one place both +hosts and Ghostlight can agree a lot moved. + +## Substrate + +CultCache `.cc` state, one store per world; CultNet typed documents for +commands, receipts, and projections; CultMesh for discovery and the Eve +composition graph (price boards, reserve gauges, provenance views, TUI +tables). Rust, matching Odin-class doctrine: the engine as pure crates (the +ledgers, the market maker, property derivation, carrier policy execution, +replay) with no I/O and a C ABI for embedding, and the daemon as a thin +lifecycle shell around them. Clocks, transports, the Ghostlight port, and the +game host port are traits on the shell so a partial pipeline smoke can price +a market from a fixture ledger without the whole daemon, and the engine can +be driven from a script with no shell at all. + +## Verification + +Unit: lot conservation under every command; provenance acyclic; a recipe +refuses a material that fails its role; output properties are a pure +function of input properties and process; the quote function is +deterministic and its loss is bounded; a stale quote is refused; the same +state, script, and seed replay to the same state on two machines; an event +lowered from a Ghostlight batch and the same event read from a script +produce identical state. + +Pipeline: a fixture world with copper, aluminium, and gold conductors, a +vapour-chamber part recipe whose capacity is a curve over temperature, one +thruster recipe with a spreader role fillable by the copper block or the +part, two markets on one route; the hot variant of the thruster recipe +refuses the vapour chamber and the cool one accepts it; flooding one market moves both prices in the direction the route cost +predicts; closing the route decouples them. A shipment between the two +markets, seized mid-route against its revision, lands its lots on the seizer, +is refused a second time, and leaves the destination's next quote higher +than it would have been on arrival; the seized lots are refused by the strict +market and admitted by the black market at a discount, and the destination's +shortage resolves through the carrier whose margin the gap now clears. A +producer flooding the spreader class walks its quote down the curve to the +consumption floor, withdraws the producer's conductor demand, and lowers the +conductor quote at the market it bought from; buying the gold reserve out +walks its quote up, and the far market's shipment answers it. + +End to end: a Ghostlight world with a market mirror; a witnessed route +closure in Ghostlight arrives as a shock and moves a price; the price arrives +in Ghostlight as a fact witnessed at the market; a person's buy intent exits, +is executed, and returns as custody with a receipt; replay of the daemon's +journal reproduces every quote. + +## Decisions + +Taken 2026-09-11: the daemon is Njörðr; properties are dimensions, never a +scalar quality, because one axis cannot express a trade-off within a recipe; +process roles are dimensions like materials; Njörðr owns the economy whole, +Delvehold's interior included, so Greathold recipes, facilities, capacity, +inventories, orders, and prices are Njörðr lots, recipes, markets, and +quotes, and Delvehold's civic organs author policy as demand rows and +carrier policies rather than running a second ledger; the Unity embedding is +the Rust engine as a native plugin over a C ABI; the market maker is the +logarithmic market scoring rule, one liquidity parameter per market and +class, chosen for its bounded loss. + +Delvehold has no existing economy surface to cut against: its world host +names a commons market id and nothing else. The shape is therefore +constrained only by the invariants above and by the verification fixtures +below, which is why those fixtures are written before the engine is. + +Still the operator's: + +1. Resolved by the engine split, and widened to producers: a shipment sails because a carrier policy + fires, and the policy is data. Online, a Ghostlight carrier subject owns + and amends its policy, so a pirate's victim has a name, a route, and a + grudge; offline, the seeded policies run. What remains the operator's is + the policy vocabulary's first cut: which thresholds and preferences the + seeding run may author. +2. The policy vocabulary's first cut: recommend the route-bounded, + gap-seeking carrier and the margin-driven producer described under + "Engine and shell", with the risk term decaying in time and the margin + per subject rather than global, so a desperate carrier sails what a + cautious one refuses. diff --git a/state/map.yaml b/state/map.yaml new file mode 100644 index 0000000..9b92d84 --- /dev/null +++ b/state/map.yaml @@ -0,0 +1,52 @@ +mission: > + One economy organ for Aetheria and Delvehold. Every item is the product of + a supply chain; materials fill roles at different trade-offs; prices are a + pure function of committed state; the economy produces from player + choices and reacts to them. The specification is + docs/architecture/njordr.md and is the authority. + +live_architecture: + engine: > + crates/njordr-engine. The state document (dimensions, materials, + sources, lots, recipes, facilities, discovery edges, per-holder recipe + knowledge, shipments, markets, carrier and producer policies) as typed, + serde-round-tripping data, and validate_catalog, the first gate of the + generation plan: every authored reference resolves and every curve and + envelope runs over a condition. No step function yet. + shell: > + crates/njordr. A binary that refuses to run because there is no store + and no step function to drive. It exists so the engine/shell split is a + workspace fact. + fixture: > + The spec's pipeline fixture is a test-only constructor in the engine + crate: copper, aluminium, gold conductors; a vapour-chamber part with a + capacity curve over temperature; thruster recipes with a spreader role + in cool and hot variants; a strict market and a permissive one on one + route; one carrier. Later cuts run it; this cut proves it is a + well-formed state document. + +hard_boundaries: + - Prices, product properties, rarity, and quality are derived, never stored. + - Lots are conserved; provenance is permanent and acyclic. + - The engine performs no I/O and cannot attribute an event to its origin. + - The engine owns no trader and no maker; it executes authored policy. + - A recipe names roles, never materials. + - Fixtures before engine; a catalog is validated by replay. + +current_status: + scaffolded: 2026-09-11 + next_action: > + The first engine capability with its fixture, in this order: (1) property + evaluation and role filling: PropertyValue evaluated at a condition, + Requirement checked over an envelope, so the fixture's cool thruster + accepts the vapour chamber and the hot one refuses it; (2) the lot + ledger: extract, run recipe, transfer, consume, with conservation and + provenance pinned, and the produced lot's properties derived by the + recipe's derivations; (3) the quote function: a logarithmic market + scoring rule per market and class over reserves and demand rows, pure + and deterministic, with stale quotes refused; (4) shipments and seizure + against a revision, with admission over provenance; (5) carrier and + producer policies as the step function, with derived intermediate demand; + (6) replay equality on two machines. Then the C ABI for the Unity + embedding, then the shell's store and ports, then the Ghostlight consumer + binding when Ghostlight's outbound batch exists.