# Clay-Borg Architecture Blueprint Reference architecture for the Clay-Borg framework. This document describes the stable structural decisions: layers, component planes, capability ports, data flows, and repository layout. For motivation and product intent see [`../INTENT.md`](../INTENT.md); for the full originating exploration see [`../history/260730-InitialExploration.md`](../history/260730-InitialExploration.md). Status: **draft** — this blueprint is normative for new work but still malleable (Clay). Changes go through a decision record in `decisions/`. --- ## 1. Layered architecture ```mermaid flowchart TB TR["TargetRevenue Control Plane phases • workload • revenue • licensing • trust"] AF["Agentic Development Forge specifications • work packets • generators tests • scenarios • benchmarks • evidence"] GP["Game Packages GROUND • fixture games • future products"] TT["Tabletop Framework cards • decks • tokens • zones • hands seats • hidden information • manipulation"] GR["Game Runtime commands • validation • rules • events phases • simultaneous actions • replay"] WS["World and Simulation entities • components • transforms • time scheduling • spatial queries • snapshots"] PORTS["Canonical Capability Ports render • physics • network • assets UI • audio • persistence • scripting"] LIBS["Assimilated Libraries wgpu • Rapier • Bevy ECS • Wasmtime Quinn • egui • Serde • tracing"] PLATFORM["Platform Substrate native • browser/WASM • server • CI"] TR --> AF AF --> GP GP --> TT TT --> GR GR --> WS WS --> PORTS PORTS --> LIBS LIBS --> PLATFORM AF -.tests and measures.-> GR AF -.tests and measures.-> WS AF -.tests and measures.-> PORTS TR -.governs releases.-> GP TR -.governs releases.-> PORTS ``` ### The four state kinds Every subsystem must respect the separation between: | State kind | Definition | Owner | |---|---|---| | **Authoritative semantic state** | What is legally happening in the game | Game runtime | | **World state** | Where representations currently are | World layer | | **Physical state** | How objects are moving | Physics port | | **Presentation state** | What a particular player is allowed to see | Projection layer | A game must remain playable in a headless process with no rendering and no rigid-body simulation. The 3D tabletop is a projection and interaction surface, never the definition of the game. --- ## 2. Clay Canon The stable conceptual foundation shared by engines, games, tools, and agents. | Component | Responsibility | |---|---| | Capability model | Names and describes each engine capability and its implementations | | Canonical identifiers | Stable IDs for entities, players, assets, games, commands, events, sessions, packages | | Schema system | Machine-readable definitions for game packages, assets, scenarios, engine configuration | | Contract system | Interfaces and invariants every implementation must satisfy | | Versioning model | Compatibility rules for APIs, schemas, save games, event logs | | Capability registry | What exists, where it lives, maturity, dependencies, evidence, release phase | | Assimilation manifests | Why a library was adopted, what boundary contains it, how it can be replaced | ### Assimilation manifest (required per external dependency) ```toml capability = "physics.rigid-body.3d" implementation = "rapier3d" boundary_crate = "cb-physics-rapier" canonical_interface = "cb-physics-api" determinism = "authoritative-server" replaceability = "high" exposed_upstream_types = false required_tests = [ "physics-conformance", "snapshot-restore", "card-stack-stability", "drag-release-behavior", ] required_benchmarks = [ "1000-resting-cards", "deck-shuffle-and-deal", "multi-object-picking", ] ``` **Hard rule: no external library type leaks across a canonical interface.** A card must not contain a `RapierRigidBodyHandle`, a `wgpu::Texture`, or an engine-specific entity id. --- ## 3. Runtime substrate The lowest layer Clay-Borg owns itself: - Platform abstraction, application lifecycle - Time and fixed simulation ticks - Task scheduling and job execution - Memory and resource ownership conventions - Deterministic random-number streams - Configuration and feature flags - Diagnostics and structured tracing (`tracing`) - Capability discovery - Error taxonomy - Shutdown, recovery, headless execution ### Port/implementation pattern Every important capability ships a **null**, a **reference**, and (when financed) an **optimized** implementation: ```text cb-time-api ├── cb-time-realtime └── cb-time-controlled cb-render-api ├── cb-render-null └── cb-render-wgpu cb-network-api ├── cb-network-loopback └── cb-network-quic cb-physics-api ├── cb-physics-null ├── cb-physics-reference └── cb-physics-rapier ``` Null and reference implementations keep tests fast, expose semantic assumptions, and let agents work without a GPU or a multiplayer environment. --- ## 4. Simulation kernel Small and largely independent of game-specific concepts. ### Entity and component model - **ECS** (`bevy_ecs`, assimilated standalone — not full Bevy) for world composition, spatial representation, runtime scheduling. - **Explicit typed aggregates** for game rules and authoritative state. Canonical game state is never reduced to arbitrary ECS components. ### Mutation pipeline Every meaningful state change follows: ```text Intent → Command → Validation → Domain Events → State Reducer → New Authoritative State → World/Presentation Projection ``` This yields replay, undo/branching, multiplayer sync, bot/agent access, auditing, save-game migration, rule debugging, and scenario testing. ### Snapshots and event logs - Periodic full snapshots; append-only event streams - Stable event serialization (Serde behind versioned Clay-Borg schemas) - State hashes, replay seeds, branching from earlier state - Snapshot migration; expected-vs-actual state comparison - **Every failed test produces a replay bundle an agent can execute locally.** --- ## 5. Physics subsystem Physics is a **service of the world, not a source of game truth**. Rapier is the optimized implementation; the server owns authoritative physical outcomes while clients interpolate and predict interaction feedback. Do not depend on independently simulated client physics remaining identical across platforms. Tabletop physics scope (initial, deliberately narrow): pick up / move / flip / place a card, stack and unstack, move relation markers, snap tokens to tracks, animate reveal and resolution, prevent accidental scattering. Dice, complex joints, bags, arbitrary models, and unrestricted throwing come later. --- ## 6. World-building layer Binds semantic objects to spatial representations. | Concept | Meaning | |---|---| | World | An independently simulated environment | | Scene | A loadable arrangement of objects | | Object | A spatially represented entity | | Prototype | Reusable object definition | | Instance | Runtime occurrence of a prototype | | Transform | Position, orientation, scale | | Zone | A spatial area with semantic meaning | | Surface | Table, board, tray, or similar placement area | | Seat | A participant position and viewpoint | | View | Player-specific projection of world state | | Binding | Connection between domain state and world objects | The world system supports multiple simultaneous projections: authoritative server world, player-visible worlds, spectator, debug, replay, and agent-observation worlds. This is what makes hidden hands and simultaneous decisions tractable. --- ## 7. Tabletop domain framework Canonical tabletop object set (no game reinvents these): ```text Table Board Card Deck Stack Token Counter Marker Die Bag Zone Hand Seat PlayerPointer Note Rulebook ScoreTrack SequenceTrack Timer ``` Each object carries: physical representation, semantic identity, ownership, visibility policy, interaction permissions, allowed operations, snap behavior, serialization, behavior hooks, presentation variants. ### Game-operation modes | Mode | Rule | |---|---| | **Sandbox** | Players manipulate objects freely; physics is primary, rules are social | | **Governed** | Only legal commands alter authoritative state; objects merely visualize | | **Hybrid** | Physical gestures *propose* commands; zones, ownership, and rules decide acceptance | GROUND uses **hybrid mode**: dragging a card toward another player only becomes an attack or support action when the rules engine validates target, relationship capacity, timing, and card availability. --- ## 8. Game runtime and packages A game package describes five things separately: 1. **Content** — cards, tokens, text, symbols, assets 2. **Setup** — session initialization 3. **Rules** — legal commands and their effects 4. **Flow** — phases, simultaneous windows, end conditions 5. **Presentation bindings** — how semantic state appears on the table ```text games/ground/ ├── GAME.toml ├── INTENT.md ├── rules/ # ground.wit, phases.yaml, actions.yaml, resolution.yaml ├── content/ # cards.yaml, tokens.yaml, symbols.yaml ├── scenes/ # table.scene.yaml, tutorial.scene.yaml ├── assets/ ├── scenarios/ ├── bots/ ├── tests/ └── migrations/ ``` ### Extension boundary Early GROUND rules live in native Rust crates. The stable extension boundary is later expressed through **WebAssembly Interface Types** loaded via **Wasmtime**. A game component receives explicit capabilities from the host (read public state, propose commands, spawn canonical objects) — never direct filesystem, network, clock, or GPU access. ### Simultaneous action primitive ```text Open decision window → privately choose action and target → commit → wait for all players or timeout → reveal → order or group interactions → resolve → emit consequences ``` Networked play uses commit/reveal semantics so early submissions cannot be inspected and exploited. The interaction-group resolver (mutual attacks, support opposing an attack, capacity conflicts, simultaneous end conditions) is expected to become one of the first genuinely reusable Clay-Borg capabilities. --- ## 9. Rendering, input, and creation tools Rust-first stack: - `winit` — windows and platform input - `wgpu` — GPU rendering (Vulkan / Metal / D3D / browser) - `egui` — engine tools, inspectors, early editors - Custom scene renderer for the game table - **glTF** as the primary imported 3D format, wrapped in Clay-Borg asset metadata and provenance Creator environment (grows over milestones): scene hierarchy, object inspector, prototype browser, card-sheet importer, deck builder, zone and snap-point editors, rule-state inspector, event timeline, player-view switcher, hidden-information debugger, physics debugger, scenario recorder, replay controls, package validator. --- ## 10. Networking and sessions Authoritative session host: ```text Client gesture → proposed command → session server validation → authoritative events → state update → player-specific projection → client animation ``` Capabilities: session discovery, auth and seat assignment, lobby/readiness, command submission, commit/reveal windows, event-stream replication, snapshot transfer, reconnection, state-hash verification, spectators, player-specific redaction, host migration (later). Transport: **Quinn** (QUIC) for native; browser transport is a separate adapter (WebTransport or WebSockets). The canonical protocol is defined independently of any transport: ```text cb-session-protocol ├── CommandEnvelope ├── EventEnvelope ├── SnapshotEnvelope ├── CommitmentEnvelope ├── AssetRequest └── CapabilityNegotiation ``` --- ## 11. Agentic inner loop Agentic coding is a first-class product surface. Optimize for small capability boundaries, executable specifications, controlled work areas, and replayable failures. ### Work packet (every agent task) ```yaml task_id: CB-PHYS-0042 capability: tabletop.card-stacking intent: Keep card stacks stable after drag release. allowed_crates: - cb-physics-api - cb-physics-rapier - cb-tabletop-physics forbidden_changes: - canonical game event schema invariants: - semantic card order must not depend on collider order scenarios: - scenarios/card-stack-20.yaml benchmarks: - benches/card-stack-stability.yaml acceptance: - all conformance tests pass - no state divergence over 10,000 ticks - benchmark regression below 3% ``` ### CLI surface (`cb`) ```bash cb inspect capability tabletop.card cb task prepare CB-PHYS-0042 cb generate contracts cb check --affected cb test --affected # supports --format json cb sim ground scenarios/mutual-attack.yaml cb play ground --players 4 cb replay artifacts/failure.cbreplay cb compare physics-reference physics-rapier cb bench --affected cb evidence build CB-PHYS-0042 cb release assess CB-PHYS-0042 ``` ### Quality gates Formatting/linting, dependency-policy check, unit tests, capability conformance tests, property tests, golden scenario tests, replay determinism, snapshot migration, performance and memory budgets, rendering comparison where relevant, security/sandbox tests, documentation and schema consistency. Tooling: `cargo-nextest` (isolated parallel tests), Criterion (regression-sensitive benchmarks), `sccache` (compile reuse), `tracing` (structured diagnostics). --- ## 12. TargetRevenue integration TargetRevenue governs **versioned capability improvements**, not the monorepo as one indivisible target. ```toml improvement_id = "CB-GROUND-001" capability = "game.ground.simultaneous-resolution" classification = "10x" estimated_days = 4 daily_rate = 1000 target_revenue = 40000 phase = "commercial-recovery" release_when_target_reached = "MIT" trust_record = "required" ``` Components: improvement registry, workload ledger, cost model, revenue attribution, dependency graph, phase license generator, revenue meter, release gate, evidence bundle, trust service. Economic rule: > Optimized assimilations may be financed as independent improvements, while > the canonical interface remains stable and reusable. --- ## 13. Repository structure ```text clay-borg/ ├── INTENT.md ├── SCOPE.md ├── ARCHITECTURE.md # or specs/ArchitectureBlueprint.md (this file) ├── Cargo.toml ├── rust-toolchain.toml │ ├── canon/ # entities, events, capabilities, schemas, terminology ├── crates/ │ ├── cb-kernel/ cb-ids/ cb-time/ cb-rng/ cb-events/ │ ├── cb-snapshot/ cb-capability/ │ ├── cb-world/ cb-world-api/ cb-ecs-bevy/ │ ├── cb-physics-api/ cb-physics-null/ cb-physics-reference/ cb-physics-rapier/ │ ├── cb-render-api/ cb-render-null/ cb-render-wgpu/ │ ├── cb-tabletop/ cb-tabletop-physics/ cb-tabletop-view/ │ ├── cb-game-runtime/ cb-game-protocol/ cb-game-wasm/ │ ├── cb-session/ cb-network-api/ cb-network-loopback/ cb-network-quic/ │ └── cb-assets/ cb-ui/ cb-editor/ cb-observe/ cb-evidence/ │ ├── games/ # ground/, fixture-cards/ ├── tools/ # cb-cli/, cb-agent/, cb-import/, cb-pack/ ├── scenarios/ ├── conformance/ ├── benchmarks/ ├── replays/ ├── examples/ ├── decisions/ ├── assimilation/ # assimilation manifests └── target-revenue/ ``` Stay a monorepo during architectural formation. Extract a repository only when a capability has a stable contract, an independent lifecycle, and a genuine external consumer. --- ## 14. Milestones | # | Milestone | Proves | |---|---|---| | 0 | Headless GROUND | Authoritative rules, commit/reveal, DARVO, replay — no rendering, no physics | | 1 | Inspectable 2D table | Presentation bindings without 3D complexity | | 2 | Physical 3D tabletop | wgpu + Rapier projection of semantic events | | 3 | Networked sessions | Authoritative host, private projections, reconnection | | 4 | Game creation framework | Editors, importers, Wasm game components | | 5 | Second fixture game | Generality — abstractions promoted to Canon only after a second concrete use | --- ## 15. Governing design decisions 1. Build GROUND first, not a general engine first. 2. Keep rules independent from rendering and physics. 3. Use commands and events as the authoritative mutation mechanism. 4. Provide null, reference, and optimized implementations of important capabilities. 5. Never leak assimilated-library types into canonical interfaces. 6. Use server-authoritative physics and deterministic semantic rules. 7. Treat player visibility as a projection, not a UI afterthought. 8. Make every defect reproducible as a scenario and replay. 9. Give coding agents bounded work packets and stable commands. 10. Attach TargetRevenue phases to versioned improvements and evidence bundles.