clay-borg/history/260730-InitialExploration.md
tegwick 705496a677 Add INTENT.md and archive initial exploration notes
Distills the architectural exploration into a top-level intent doc
per the repo's own proposed structure.
2026-07-30 23:55:43 +02:00

30 KiB
Raw Blame History

The Idea

I want to set up the inner loop of development for a rebuild and assimilate nearly everything from scratch substrate- , physics- , world-, game- building development engine that is highly modular but efficiently integrated, set up from highly optimized libraries and tuned for agentic coding driven by the target revenue business framework called the clay-borg. What are the components needed to establish this in order to implement a tabletop simulator inspired framework that can create and run a virtual representation of the GROUND boardgame concept?

Clay-Borg: the architectural idea

Clay-Borg should not be another monolithic game engine. It should be a capability-assimilating development engine with three distinct properties:

  1. Clay: its canonical models, contracts, rules, and tools remain malleable.
  2. Borg: mature, optimized libraries are assimilated behind controlled interfaces rather than copied or exposed directly.
  3. Product-driven evolution: abstractions are extracted from working games, beginning with GROUND — A Game of Bonds and Rivalry: DARVO Edition, rather than invented in isolation.

The central rule should be:

Own the semantics; assimilate the implementation.

Clay-Borg owns what an entity, object, command, event, card, zone, relationship, game, simulation, asset, plugin, and capability mean. External libraries provide optimized implementations of rendering, physics, networking, serialization, and similar functions.

1. Overall architecture

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 important separation is between:

  • Authoritative semantic state: what is legally happening in the game.
  • World state: where representations currently are.
  • Physical state: how objects are moving.
  • Presentation state: what a particular player is allowed to see.

GROUND must remain playable in a headless process with no rendering and no rigid-body simulation. The 3D tabletop is a projection and interaction surface for the game, not the definition of the game.


2. The required component planes

A. Clay Canon

This is 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 and packages
Schema system Machine-readable definitions for game packages, assets, scenarios and engine configuration
Contract system Interfaces and invariants that every implementation must satisfy
Versioning model Compatibility rules for APIs, schemas, save games and event logs
Capability registry What exists, where it lives, maturity, dependencies, evidence and release phase
Assimilation manifests Why a library was adopted, what boundary contains it, how it can be replaced

Every assimilated dependency should have a manifest similar to:

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"
]

No external library type should leak across a canonical Clay-Borg interface. A GROUND card must not contain a RapierRigidBodyHandle, wgpu::Texture, or engine-specific entity identifier.


B. Runtime substrate

This is the lowest layer Clay-Borg itself should own.

It needs:

  • 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
  • Capability discovery
  • Error taxonomy
  • Shutdown and recovery
  • Headless execution

The substrate should have several implementations where useful:

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

The null and reference implementations are important. They make tests fast, expose semantic assumptions, and allow agents to work without needing a GPU or a full multiplayer environment.


C. Simulation kernel

The simulation kernel should be small and largely independent of game-specific concepts.

Its core elements are:

Entity and component model

An ECS is appropriate for the physical and world layers, but the canonical game state should not be reduced to arbitrary ECS components. Use:

  • ECS for world composition, spatial representation and runtime scheduling.
  • Explicit typed aggregates for game rules and authoritative state.

bevy_ecs is available as a standalone crate and is intended to provide a parallel, cache-friendly ECS without requiring the complete Bevy engine. That makes it a good candidate for assimilation rather than adopting all of Bevy. (Docs.rs)

Commands, events and reducers

Every meaningful state change should follow:

Intent
  → Command
  → Validation
  → Domain Events
  → State Reducer
  → New Authoritative State
  → World/Presentation Projection

This provides:

  • Replay
  • Undo and branching
  • Multiplayer synchronization
  • Bot and agent access
  • Auditing
  • Save-game migration
  • Rule debugging
  • Scenario testing

Snapshots and event logs

The kernel needs:

  • Periodic full snapshots
  • Append-only event streams
  • Stable event serialization
  • State hashes
  • Replay seeds
  • Branching from an earlier state
  • Snapshot migration
  • Comparison of expected and actual state

A failed test should produce a replay bundle that an agent can execute locally.


D. Physics subsystem

Physics should be a service of the world, not a source of game truth.

For a tabletop framework it needs:

  • Rigid bodies
  • Static and dynamic colliders
  • Ray casting and object picking
  • Drag constraints
  • Card and token stacking
  • Joints and hinges
  • Sleeping and wake-up rules
  • Controlled throwing and rolling
  • Surface friction
  • Snap points and snap zones
  • Collision layers
  • Physics snapshots
  • Server-authoritative synchronization

Rapier provides optimized 2D and 3D physics and snapshot-oriented facilities. Its documentation distinguishes local determinism from configurations intended for stronger cross-platform determinism, so Clay-Borg should not depend on independently simulated client physics remaining identical. The server should own authoritative physical outcomes while clients interpolate and predict interaction feedback. (rapier.rs)

For GROUND, the initial physics scope is deliberately narrow:

  • Pick up and move a card
  • Flip a card
  • Place a card in a legal zone
  • Stack and unstack cards
  • Move relation markers
  • Snap tokens to relationship tracks
  • Animate reveal and resolution
  • Prevent accidental scattering of the game state

Dice, complex joints, bags, arbitrary custom models and unrestricted throwing can follow later.


E. World-building layer

The world layer binds semantic objects to spatial representations.

It should contain:

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 and 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 should support multiple simultaneous projections:

  • Authoritative server world
  • Player-visible world
  • Spectator world
  • Debug world
  • Replay world
  • Agent-observation world

This is particularly important for hidden hands and simultaneous decisions.


F. Tabletop domain framework

Do not require each game to reinvent cards, decks, hands, seats, tokens and zones.

The initial canonical tabletop object set should include:

Table
Board
Card
Deck
Stack
Token
Counter
Marker
Die
Bag
Zone
Hand
Seat
PlayerPointer
Note
Rulebook
ScoreTrack
SequenceTrack
Timer

Each tabletop object requires:

  • Physical representation
  • Semantic identity
  • Ownership
  • Visibility policy
  • Interaction permissions
  • Allowed operations
  • Snap behavior
  • Serialization
  • Object behavior hooks
  • Presentation variants

Tabletop Simulators API uses both global scripts and scripts attached to individual physical objects. Clay-Borg can preserve the useful distinction while replacing unrestricted object scripting with explicit capabilities, typed events and sandboxed components. (api.tabletopsimulator.com)

The engine should support three game-operation modes:

Sandbox mode

Players can manipulate objects freely. Physics is primary and rules are social.

Governed mode

Only legal commands can alter authoritative state. Physical objects merely visualize commands.

Hybrid mode

Physical gestures propose commands. Zones, ownership and rules decide whether they are accepted.

GROUND should use hybrid mode. A player drags a card toward another player, but the move only becomes an attack or support action when the rules engine validates the target, relationship capacity, timing and card availability.

Tabletop Club is a useful open-source reference for a modifiable, physics-based 3D tabletop environment, but Clay-Borg should assimilate patterns rather than adopt its Godot architecture wholesale. (GitHub)


3. The game-runtime framework

A game package should describe five things separately:

  1. Content: cards, tokens, text, symbols and assets.
  2. Setup: how a session is initialized.
  3. Rules: legal commands and their effects.
  4. Flow: phases, simultaneous windows and end conditions.
  5. Presentation bindings: how semantic state appears on the table.

A package could look like:

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/

Native and sandboxed game modules

During early development, GROUND rules can be implemented as native Rust crates. The stable game extension boundary should later be expressed through WebAssembly Interface Types and loaded through Wasmtime.

Wasmtime provides an embedding API for WebAssembly components, while WIT defines typed interfaces between hosts and components. This is suitable for isolating game packages and allowing the host to expose only approved capabilities such as reading public state, proposing commands or spawning canonical tabletop objects. (docs.wasmtime.dev)

A game component should not receive direct filesystem, networking, clock or GPU access. It receives explicit capabilities from the host.


4. The GROUND authoritative model

GROUND is an excellent first vertical slice because it requires relatively modest physics but sophisticated social state, simultaneous decisions and constrained sequences.

A preliminary authoritative state might be:

struct GroundGameState {
    game_id: GameId,
    round: RoundNumber,
    phase: GroundPhase,
    players: Vec<PlayerState>,
    relationships: RelationshipGraph,
    committed_actions: Vec<CommittedAction>,
    revealed_actions: Vec<RevealedAction>,
    darvo_sequences: Vec<DarvoSequence>,
    ground_practices: Vec<GroundPractice>,
    resolution_queue: Vec<PendingResolution>,
    score: ScoreState,
    rng: DeterministicRngState,
}

Required GROUND-specific components

Player and seat

  • Two to six players
  • Hand and private information
  • Available actions
  • Relationship capacity
  • Current obligations and sequences

Relationship graph

The relationship model should be a typed graph rather than loose card placement:

Player A ──bond──── Player B
Player A ──rivalry─ Player C
Player B ──support─ Player C

The graph contains:

  • Relationship type
  • Strength
  • Direction
  • Capacity cost
  • Provenance
  • Duration
  • Pending change
  • Attached DARVO or GROUND state

Simultaneous action system

GROUND needs a first-class simultaneous-play primitive:

Open decision window
→ privately choose action and target
→ commit
→ wait for all players or timeout
→ reveal
→ order or group interactions
→ resolve
→ emit consequences

For network play, use commit/reveal semantics so that early submissions cannot be inspected and exploited.

DARVO sequence machine

DARVO should not be modeled as three unrelated cards. It is a binding state machine:

stateDiagram-v2
    [*] --> Deny: DARVO triggered
    Deny --> Attack: next obligation
    Attack --> Reverse: next obligation
    Reverse --> Completed
    Deny --> Interrupted: explicit rule effect
    Attack --> Interrupted: explicit rule effect
    Reverse --> Interrupted: explicit rule effect

The sequence component needs:

  • Initiator
  • Target
  • Triggering interaction
  • Current step
  • Mandatory next step
  • Allowed targets
  • Consequence on compliance
  • Consequence on interruption
  • Visibility
  • Historical events

GROUND practice

GROUND is the sole constructive practice in the base game and should therefore be represented as more than a generic positive card. It needs:

  • Eligibility conditions
  • Cost or opportunity cost
  • Relationship target
  • Immediate effect
  • Sequence-interruption effect
  • Bond restoration or rivalry reduction
  • Presentation and teaching text

Resolution engine

The resolver should handle interaction groups, not merely execute cards in submission order:

Attacks against the same player
Mutual attacks
Mutual support
Support opposing an attack
GROUND affecting a DARVO sequence
Relationship-capacity conflicts
Simultaneous end conditions

That resolver is likely to become one of the first genuinely reusable Clay-Borg capabilities.


5. Rendering, input and creation tools

A Rust-first rendering stack is a sensible starting point:

  • winit for windows and platform input
  • wgpu for GPU rendering
  • egui for engine tools, inspectors and early editors
  • A custom scene renderer for the actual game table

wgpu targets Vulkan, Metal, Direct3D and browser graphics APIs through one Rust-facing abstraction; winit provides cross-platform window and input-event handling. egui can run natively and on the web and can be integrated wherever textured triangles can be rendered. (GitHub)

The creator environment needs:

  • Scene hierarchy
  • Object inspector
  • Prototype browser
  • Card-sheet importer
  • Deck builder
  • Zone editor
  • Snap-point editor
  • Relationship-layout editor
  • Rule-state inspector
  • Event timeline
  • Player-view switcher
  • Hidden-information debugger
  • Physics debugger
  • Scenario recorder
  • Replay controls
  • Package validator

Use glTF as the primary imported 3D scene/model format because it is an open, extensible format designed for efficient runtime delivery of 3D assets. Clay-Borg should retain its own asset metadata and provenance around imported glTF content. (The Khronos Group)


6. Networking and session architecture

Use an authoritative session host.

Client gesture
→ proposed command
→ session server validation
→ authoritative events
→ state update
→ player-specific projection
→ client animation

The networking layer needs:

  • Session discovery
  • Authentication and seat assignment
  • Lobby and readiness
  • Command submission
  • Commit/reveal windows
  • Event-stream replication
  • Snapshot transfer
  • Reconnection
  • State-hash verification
  • Spectator support
  • Player-specific redaction
  • Host migration as a later capability

Quinn is a pure-Rust asynchronous QUIC implementation and is suitable for a native transport adapter. Browser transport should remain a separate adapter, potentially using WebTransport or WebSockets without affecting the game protocol. (Docs.rs)

The canonical protocol should be defined independently from Quinn:

cb-session-protocol
├── CommandEnvelope
├── EventEnvelope
├── SnapshotEnvelope
├── CommitmentEnvelope
├── AssetRequest
└── CapabilityNegotiation

7. The agentic inner loop

Agentic coding should be a first-class product surface of Clay-Borg, not an external convenience.

Recent repository-level Rust-agent research identifies repo-wide comprehension and reproducible issue setup as significant difficulties. Clay-Borg should therefore optimize for small capability boundaries, executable specifications, controlled work areas and replayable failures. (arXiv)

The work packet

Every agent task should produce a self-contained work packet:

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%

The local command surface

One CLI should make the entire loop legible to humans and agents:

cb inspect capability tabletop.card
cb task prepare CB-PHYS-0042
cb generate contracts
cb check --affected
cb test --affected
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

All commands should support structured output:

cb test --affected --format json

Inner-loop sequence

flowchart LR
    I["Intent or defect"] --> W["Generate work packet"]
    W --> C["Agent changes bounded capability"]
    C --> S["Static checks"]
    S --> T["Unit and contract tests"]
    T --> H["Headless scenarios"]
    H --> R["Deterministic replay"]
    R --> B["Benchmarks"]
    B --> V["Visual inspection"]
    V --> E["Evidence bundle"]
    E --> M["Merge and revenue milestone"]
    M --> I

Required quality gates

  • Formatting and linting
  • Dependency-policy check
  • Unit tests
  • Capability conformance tests
  • Property tests
  • Golden scenario tests
  • Replay determinism
  • Snapshot migration
  • Performance budgets
  • Memory budgets
  • Rendering comparison where relevant
  • Security and sandbox tests
  • Documentation and schema consistency

cargo-nextest offers isolated and parallel Rust test execution, Criterion supports regression-sensitive statistical benchmarking, and sccache can reuse compiler outputs locally or through shared storage. These fit the fast inner-loop requirement. (Nexte)

Structured runtime diagnostics should use tracing, while canonical state serialization can be built around Serde behind Clay-Borgs own versioned schemas. (GitHub)


8. TargetRevenue integration

TargetRevenue should govern versioned capability improvements, not turn the whole monorepo into one indivisible revenue target.

Each improvement unit needs:

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"

Required business-control components

Component Purpose
Improvement registry Defines the bounded improvement being financed
Workload ledger Records estimated and actual implementation effort
Cost model Converts work and improvement class into TargetRevenue
Revenue attribution Assigns commercial receipts to improvement targets
Dependency graph Prevents incompatible licensing and release transitions
Phase license generator Produces the applicable release terms
Revenue meter Tracks progress toward the TargetRevenue
Release gate Changes the designated versions licensing when conditions are met
Evidence bundle Connects delivered capability to tests, benchmarks and source
Trust service Publishes authoritative milestones, metrics and transitions

The central Trustservice can initially publish:

Capability
Version
Improvement classification
Source commit
Build provenance
Test evidence
Benchmark evidence
Current license phase
TargetRevenue
Recognized revenue
Remaining target
Release transition

Later federation becomes possible because the data model and evidence artifacts are already portable.

A useful economic rule is:

Optimized assimilations may be financed as independent improvements, while the canonical interface remains stable and reusable.

For example, the initial reference card-stacking implementation could be available early, while a much faster and more stable implementation becomes a separately financed 10x improvement.


9. Proposed repository structure

clay-borg/
├── INTENT.md
├── SCOPE.md
├── ARCHITECTURE.md
├── 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/
└── target-revenue/

Keep this as a monorepo during architectural formation. Extract repositories only when a capability has a stable contract, an independent lifecycle and a genuine external consumer.


10. Recommended implementation order

Milestone 0 — Headless GROUND

Deliver:

  • Complete authoritative GROUND state
  • Two-to-six-player setup
  • Simultaneous commit/reveal
  • Relationship limits
  • Attack and support
  • Binding DARVO sequence
  • GROUND practice
  • End conditions
  • CLI player
  • Replay and scenario tests
  • Simple bots

No rendering and no physics.

Milestone 1 — Inspectable 2D table

Deliver:

  • Card and token representations
  • Hands and player views
  • Relationship graph visualization
  • DARVO sequence track
  • Drag-to-propose interactions
  • Debug inspector
  • Local hot-seat play

This proves presentation bindings without introducing 3D complexity.

Milestone 2 — Physical 3D tabletop

Deliver:

  • wgpu renderer
  • Rapier-backed tabletop physics
  • Camera and pointer controls
  • Cards, decks, tokens and snap zones
  • Controlled card manipulation
  • Animation from semantic events
  • Asset importer

Milestone 3 — Networked sessions

Deliver:

  • Authoritative host
  • Private player projections
  • Commit/reveal protocol
  • Reconnection
  • Snapshot transfer
  • Replay verification
  • Spectator mode

Milestone 4 — Game creation framework

Deliver:

  • Object prototypes
  • Scene editor
  • Card/deck importer
  • Zone editor
  • Package validation
  • Wasm game components
  • Mod capability permissions

Milestone 5 — Prove generality

Implement one deliberately different fixture game. Only then promote duplicated GROUND abstractions into the stable Clay Canon.

This gives Clay-Borg a useful abstraction rule:

No concept becomes canonical merely because it looks general. It becomes canonical after surviving a second concrete use.


11. The most important 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.

The first meaningful Clay-Borg product is therefore not “a new physics engine.” It is:

A headless, replayable and agent-readable GROUND rules engine that can be projected onto an increasingly physical virtual tabletop while every new capability remains replaceable, measurable and financeable through TargetRevenue.