Motebit

Architecture

Monorepo structure, enforced layers, services, specs, and data flow

Motebit is a pnpm monorepo orchestrated by Turborepo. TypeScript throughout, Node 20+, pnpm 9.15. Every I/O boundary is an adapter so the interior never binds to a specific platform.

The shape is 46 packages · 7 architectural layers · 5 surfaces + 3 supporting apps · 8 services · 21 open specs. Layer membership is enforced by pnpm check-deps in CI — violations break the build.

Protocol stack — motebit fills the missing layer underneath MCP defines what an agent can do (tool capabilities). A2A defines how agents communicate. x402 and AP2 define how they pay. None of those define who an agent is across time and devices, what trust it has accumulated, or what the operator's policy allows it to do. Motebit is the layer underneath: persistent cryptographic identity, signed receipts that compound into trust, and governance enforced at the agent's surface tension. MCP — what the agent can do (tool capability) A2A — how agents talk to each other x402 · AP2 — how agents pay motebit — who the agent is, what it has done, what it is allowed to do identity (Ed25519, did:key) · trust (signed receipts) · governance (policy gate)
MCP, A2A, and x402/AP2 each define one face of an agent. Motebit fills the layer underneath: identity, trust, governance.identity-v1 §1

MCP says what an agent can do. A2A says how agents talk. x402 and AP2 say how they pay. None of those define who an agent is across time and devices, what trust it has accumulated through past work, or what the operator's policy allows it to do today. Motebit is additive — it slots underneath those three protocols, providing the cryptographic identity, signed-receipt trust ledger, and boundary policy gate the others assume but do not specify.

License tiers — protocol open, implementation source-available, state private Motebit's license model has three tiers. The protocol floor (specs, types, crypto, SDK) is Apache-2.0 with an explicit patent grant — anyone can implement it, in any language, without permission. The reference implementation (runtime, engines, services, apps) is BSL 1.1, source-available today and converting to Apache-2.0 four years after each version's release. The accumulated state a relay generates by running — trust graph, federation routes, signed audit ledger — belongs to whoever runs the relay; it is never licensed, mirrored, or shared. Apache-2.0 — protocol floor specs, types, crypto suite, SDK, hardware-attestation verifiers · permanent · patent grant BSL-1.1 — reference implementation runtime, engines, services, apps · source-available now · → Apache-2.0 four years after release Private — accumulated state trust graph, federation routes, signed audit ledger · belongs to whoever runs the relay · never licensed
Three license tiers: Apache-2.0 protocol floor, BSL-1.1 reference implementation, private accumulated state.protocol-model doctrine

The protocol floor (specs, types, crypto, SDK, hardware-attestation verifiers) is Apache-2.0 with an explicit patent grant — anyone can implement it in any language without permission. The reference implementation (runtime, engines, services, apps) is BSL-1.1, source-available today and converting to Apache-2.0 four years after each version's release. The state a relay accumulates by running — trust graph, federation routes, signed audit ledger — belongs to whoever runs the relay; it is never licensed, mirrored, or visible. Both license families converge to a single Apache-2.0 posture at the Change Date.

Directory tree

The canonical map of the monorepo. Packages are tagged with their enforced layer (L0L6) from scripts/check-deps.ts. Apps and services are tagged by role.

motebit/
├── apps/
│   ├── web/                   [surface]     Browser. IndexedDB identity, free proxy, zero install.
│   ├── cli/                   [surface]     Operator console. REPL, daemon, delegation, MCP server.
│   ├── desktop/               [surface]     Tauri. Three.js creature, voice, operator mode.
│   ├── mobile/                [surface]     React Native + Expo. Full parity with desktop.
│   ├── spatial/               [surface]     AR/VR/WebXR. Creature-as-scene, typed spatial objects.
│   ├── admin/                 [supporting]  React + Vite dashboard. 15-tab relay monitoring.
│   ├── identity/              [supporting]  Static browser tool for inspecting motebit.md files.
│   ├── vscode/                [supporting]  VS Code/Cursor extension. Thin shim that spawns `motebit lsp`.
│   └── docs/                  [supporting]  Fumadocs + Next.js. This site.

├── packages/
│   │
│   │   # Layer 0 — Foundation (Apache-2.0 floor; zero internal deps)
│   ├── protocol/              [L0 · Apache-2.0]    Types, semirings, routing primitives, crypto-suite registry.
│   ├── sdk/                   [L0 · Apache-2.0]    Developer contract. Stable types, adapter interfaces.
│   ├── crypto/                [L0 · Apache-2.0]    Sign/verify every motebit artifact. Suite dispatcher.
│   │
│   │   # Layer 1 — Primitives
│   ├── voice/                 [L1]          VAD, STT, TTS adapters (provider-judgment; no protocol-level surface).
│   ├── encryption/            [L1]          AES-256-GCM, PBKDF2, sync keys, deletion certs.
│   ├── gradient/              [L1]          "What am I?" — narrative from gradient snapshots.
│   ├── event-log/             [L1]          Append-only event sourcing with version clocks.
│   ├── policy/                [L1]          PolicyGate, MemoryGovernor, injection defense.
│   ├── tools/                 [L1]          ToolRegistry, builtin tools, MCP tool merge.
│   ├── semiring/              [L1]          Agent graph, multi-objective ranking, provenance.
│   ├── policy-invariants/     [L1]          Clamping rules, state bounds validation.
│   ├── wallet-solana/         [L1]          Sovereign Solana USDC rail. Identity key = address.
│   ├── circuit-breaker/       [L1]          Per-peer three-state forward-health engine. Injected clock + logger.
│   ├── settlement-rails/      [L1]          Guest-rail triad: Stripe (fiat), x402 (protocol), Bridge (orchestration). Registry enforces custody="relay".
│   ├── evm-rpc/               [L1]          EVM JSON-RPC boundary. `getBlockNumber` + `getTransferLogs` behind a motebit-shaped interface; injected fetch.
│   ├── virtual-accounts/      [L1]          Per-motebit ledger: atomic credit/debit, withdrawal lifecycle, signed receipts. AccountStore inversion.
│   ├── deposit-detector/      [L1]          EVM Transfer-event scanner. Injected EvmRpcAdapter + DepositDetectorStore + onDeposit callback.
│   ├── self-knowledge/        [L1]          Committed BM25 corpus over motebit's public docs. Interior tier of the answer engine.
│   ├── wire-schemas/          [L1]          Zod schemas for wire-format types. Generates committed JSON Schema artifacts into `spec/schemas/` — the protocol-owned Apache-2.0 tree third parties implement against.
│   │
│   │   # Layer 2 — Engines
│   ├── crypto-appattest/      [L2 · Apache-2.0]    Apple App Attest chain verifier — pinned Apple root, deterministic from Apple's public spec.
│   ├── crypto-play-integrity/ [L2 · Apache-2.0]    Google Play Integrity JWT verifier — pinned JWKS, ES256/RS256 dispatch.
│   ├── crypto-tpm/            [L2 · Apache-2.0]    Windows / Linux TPM 2.0 EK chain verifier — pinned vendor roots (Infineon, Nuvoton, STMicro, Intel PTT).
│   ├── crypto-webauthn/       [L2 · Apache-2.0]    WebAuthn platform-authenticator packed-attestation verifier — pinned FIDO root set (Apple, Yubico, Microsoft).
│   ├── market/                [L2]          Budget, settlement, reputation, graph routing.
│   ├── behavior-engine/       [L2]          state → BehaviorCues (deterministic, pure).
│   ├── state-vector/          [L2]          Tick-based EMA smoothing, hysteresis, 60 FPS interp.
│   ├── render-engine/         [L2]          Droplet geometry, glass material, ThreeJS adapter.
│   ├── memory-graph/          [L2]          Semantic memory, cosine similarity, half-life decay.
│   ├── core-identity/         [L2]          UUID v7, multi-device, Ed25519 binding.
│   ├── sync-engine/           [L2]          Multi-device sync. HTTP/WebSocket, conflict detection.
│   ├── mcp-client/            [L2]          MCP stdio/HTTP client, credential sources, verifiers.
│   ├── identity-file/         [L2]          Generate/parse/verify motebit.md.
│   │
│   │   # Layer 3 — Lower composites
│   ├── privacy-layer/         [L3]          Retention rules, deletion certificates, export.
│   ├── ai-core/               [L3]          Pluggable providers, agentic turn loop, context packing.
│   ├── mcp-server/            [L3]          MCP server adapter, bearer auth, signed receipts.
│   │
│   │   # Layer 4 — Upper composites
│   ├── persistence/           [L4]          SQLite (WAL), adapters for all storage types.
│   ├── planner/               [L4]          PlanEngine — goal decomposition, plan-level reflection.
│   ├── reflection/            [L4]          "What should I change?" — LLM reflection engine.
│   │
│   │   # Layer 5 — Orchestration
│   ├── runtime/               [L5]          Agent orchestrator. Agentic loop, delegation, ledger.
│   ├── browser-persistence/   [L5]          IndexedDB adapters for web and spatial.
│   ├── panels/                [L5]          Surface-agnostic panel controllers (Sovereign today). State + actions; render per surface.
│   │
│   │   # Layer 6 — Applications
│   ├── create-motebit/        [L6 · Apache-2.0]    Public scaffolder. npm create motebit.
│   ├── molecule-runner/       [L6]          Shared boot kernel for molecule/atom services — composes runtime + persistence + mcp-server + tools behind one `runMolecule` call.
│   ├── verifier/              [L6 · Apache-2.0]    Library — verifyFile, verifyArtifact, formatHuman helpers over @motebit/crypto. Permissive-floor-pure; no bin.
│   ├── verify/                [L6 · Apache-2.0]    Canonical `motebit-verify` CLI — aggregates the four Apache-2.0 platform leaves (App Attest, TPM, Play Integrity, WebAuthn) with motebit-canonical defaults (bundle IDs, RP ID, integrity floor) for one-install offline verification. The defaults are overridable flags, not proprietary judgment — the permissive-floor line stays here.
│   │
│   │   # Standalone — outside the layer DAG
│   └── github-action/         [—]           GitHub Action for identity verification in CI.

├── services/
│   ├── api/                   [relay]       Sync, settlement, federation, discovery, disputes.
│   ├── research/              [molecule]    $0.25/report. Claude + web search, signed citation chain.
│   ├── code-review/           [molecule]    $0.50/review. Claude-powered, signed receipts.
│   ├── web-search/            [atom]        $0.05/request. Single-hop + multi-hop delegation proof.
│   ├── read-url/              [atom]        Minimal read-url service. Second hop in multi-hop proof.
│   ├── summarize/             [atom]        Conversation summarization.
│   ├── embed/                 [atom]        ONNX embedding service.
│   └── proxy/                 [glue]        Vercel edge CORS proxy for the web app.

├── spec/                      # 21 open specifications, each motebit/<name>@1.0
│   ├── identity-v1.md                       motebit.md format, signing, multi-device, guardian, succession.
│   ├── execution-ledger-v1.md               Timeline, signed manifests, receipt structure.
│   ├── relay-federation-v1.md               Peering, discovery, cross-relay routing, circuit breaker.
│   ├── market-v1.md                         Budget, settlement, fees, trust, routing scores.
│   ├── credential-v1.md                     W3C VC 2.0, issuance, weighting, revocation.
│   ├── settlement-v1.md                     Foundation law, rail taxonomy, sovereign rail, security.
│   ├── auth-token-v1.md                     Signed bearer tokens, audience binding, replay prevention.
│   ├── credential-anchor-v1.md              Merkle batch anchoring, self-verifiable proofs.
│   ├── agent-settlement-anchor-v1.md         Per-agent settlement anchoring — worker audit ceiling alongside SettlementRecord signing floor.
│   ├── delegation-v1.md                     Task submission, receipt exchange, budget lifecycle.
│   ├── discovery-v1.md                      .well-known, DNS SRV, agent resolution, relay metadata.
│   ├── migration-v1.md                      Departure attestation, credential export, trust bootstrap.
│   ├── device-self-registration-v1.md       Self-attesting device → relay handshake, no master token required.
│   ├── dispute-v1.md                        Evidence, adjudication, fund handling, appeal, sybil defense.
│   ├── memory-delta-v1.md                   Event-shaped memory mutations, wire-format payloads, sensitivity redaction.
│   ├── goal-lifecycle-v1.md                 Event-shaped goal declaration, execution, progress, completion, removal.
│   ├── plan-lifecycle-v1.md                 Event-shaped plan creation, per-step lifecycle, delegation, termination.
│   ├── consolidation-receipt-v1.md          Signed proactive-cycle proof + Merkle-batched Solana anchor — self-attesting interior work.
│   ├── computer-use-v1.md                   Full-fidelity Workstation viewport — screen observation + input actions, signed, governance-gated.
│   ├── agent-mcp-surface-v1.md              Canonical motebit_* MCP tool vocabulary — eight tool names every motebit MCP server uses, profile-based conformance.
│   └── proposals-v1.md                      Multi-agent plan negotiation — proposal submission, acceptance, withdrawal, and collaborative-step-result reporting.

└── scripts/                   # Drift-defense CI gates
    ├── check-deps.ts                        Layer DAG enforcement. Source of truth for L0–L6.
    ├── check-spec-coverage.ts               Spec Wire-format types exported from @motebit/protocol.
    ├── check-suite-declared.ts              Every signed artifact declares a SuiteId.
    ├── check-suite-dispatch.ts              Primitive calls live only in suite-dispatch.ts.
    ├── check-dist-smoke.ts                  Every published bin executes --help in CI.
    └── check-unused.ts                      External dependency hygiene (soft signal).

Layer rule

Layer N may depend on layers 0..N-1 in production and 0..N in devDependencies. Apps and services live at L6 and may depend on any layer. The canonical source of truth is the LAYER map in scripts/check-deps.ts; the tree above mirrors it. github-action is a standalone build artifact for the GitHub Actions runtime and sits outside the DAG.

Permissive / BSL boundary

Ten packages sit on the permissive floor — Apache-2.0, with an explicit patent grant and litigation-termination clause. check-deps.ts enforces that permissive-floor packages export only types, enums, branded casts, allowlisted utilities, and deterministic verifiers — never algorithms that would bind a competing implementation to this codebase.

PackageAnswersLayer
@motebit/protocolWhat is the artifact? What's the algebra?L0
@motebit/cryptoHow is it signed? How is it verified?L0
@motebit/sdkWhat interface must an implementation satisfy?L0
@motebit/crypto-appattestHow is an Apple App Attest receipt verified?L2
@motebit/crypto-play-integrityHow is a Google Play Integrity token verified?L2
@motebit/crypto-tpmHow is a TPM 2.0 quote verified?L2
@motebit/crypto-webauthnHow is a WebAuthn packed attestation verified?L2
@motebit/verifierHow does a third party compose offline verification?L6
@motebit/verifyHow does a one-install CLI verify any motebit artifact end-to-end?L6
create-motebitHow does a third party scaffold against the protocol?L6

The four crypto-* platform leaves verify against each platform's published public trust anchor (Apple root, Google JWKS, vendor TPM roots, FIDO roots) — no motebit-specific judgment. @motebit/verify aggregates them with motebit-canonical defaults (bundle IDs, RP ID, integrity floor) into one install, but the defaults are overridable flags, not proprietary judgment — the permissive-floor line stays at the aggregator. The BSL line holds at motebit (the operator console) and everything below it: daemon, MCP server, delegation routing, market integration, federation wiring — the actual reference-implementation judgment.

The remaining 25 packages are BSL-1.1 — the reference implementation that answers how the system decides, adapts, routes, and governs. Both license families converge to Apache-2.0 at each version's Change Date (four years after first public release), eliminating the two-license end state. See LICENSING.md for the full boundary test, convergence story, and commercial terms.

The architectural role is "permissive floor"; the specific license instance (Apache-2.0) is replaceable. Identifiers in scripts/check-deps.ts (PERMISSIVE_PACKAGES, PERMISSIVE_IMPORT_ALLOWED, PERMISSIVE_ALLOWED_FUNCTIONS) and the sibling gate check-spec-permissive-boundary use the role name so a future license revision is a metadata change, not a rename cascade across the codebase.

Apps

AppRingStatusRole
webSurfaceLiveIndexedDB identity, free proxy, zero install. Entry at motebit.com.
cliSurfaceLiveOperator console (npm motebit). REPL, daemon, delegation, MCP server mode, local relay (motebit relay up).
desktopSurfaceLiveTauri glass droplet. Three.js creature, identity, operator mode, voice.
mobileSurfaceLiveReact Native + Expo. Full parity — expo-gl Three.js, SQLite adapters, plan-based goals.
spatialSurfaceProtoAR/VR/WebXR-first. Creature-as-scene. See Spatial doctrine below.
adminSupportingInternalReact + Vite dashboard. 15-tab real-time monitoring of a running relay.
identitySupportingPublicStatic browser tool — drop a motebit.md, inspect the parsed, verified profile.
docsSupportingPublicFumadocs + Next.js. This site.

Capability rings, not feature parity. Ring 1 (core, identical everywhere): runtime, sdk, crypto, policy. Ring 2 (platform adapters): persistence, keyring, voice. Ring 3 (platform capabilities): MCP stdio (CLI/desktop), 3D creature (desktop/mobile/web/spatial), daemon (CLI/desktop). A surface may express the same Ring 1 capability through a different form native to its medium — "operator can see their balance" is Ring 1; "balance renders in a rectangular panel" is Ring 3.

Spatial doctrine

Spatial rejects the panel metaphor. Porting 2D panels to a headset is cargo-cult parity and surrenders the medium's only advantage. The surface ships a functional HUD for read-only essentials (connection state, balance, active task) and expresses structured data as spatial objects.

The taxonomy is compile-time, not prose. @motebit/render-engine declares the shared union — consumed by every surface that renders a creature (spatial, web, future mobile-AR):

export type SpatialExpression =
  | SatelliteExpression   // orbiting objects (credentials, agents)
  | CreatureExpression    // other agents as creatures in the scene
  | EnvironmentExpression // memory / ambient state
  | AttractorExpression;  // goals, tasks

Every structured-data module registers its kind via registerSpatialDataModule<K extends SpatialKind>(...). Passing "panel" or "list" is a tsc error, locked by negative-type assertions in apps/spatial/src/__tests__/spatial-expression.neg.test.ts. Spatial keeps the doctrinal "no panels" enforcement; the primitives themselves are shared. Credential satellites are the first shipping expression — each credential orbits the creature as a small glass orb. The invariant that scene renderers live in the package, not inline in apps, is enforced by check-scene-primitives (drift defense #26).

Services

Eight services in four roles. All are reference implementations of the protocol specs — swappable by anyone running a compliant alternative.

RoleServicesPattern
RelayapiThe only function with a legitimate centralization premium — multi-device sync. Also: settlement, federation, discovery, 5-tier rate limiting, dispute resolution.
Moleculesresearch ($0.25/report), code-review ($0.50/review)Agents that reason and compose other agents. Claude-powered. Emit signed delegation receipt chains as citation proof.
Atomsweb-search ($0.05/request), read-url, summarize, embedStateless capability providers. Single-hop reference implementations of the delegation spec.
GlueproxyVercel edge CORS proxy for the web app (Anthropic API, fetch, embed).

Every task settles through the relay or directly peer-to-peer. Relay-mediated: budget locked → execution → signed receipt → worker paid (5% fee). P2P: delegator sends USDC directly to the worker's wallet when trust is high enough — zero fees, relay records audit only.

Specifications

All twenty-one specs (listed in the tree above) are Apache-2.0, published in spec/, and have working reference implementations in this repo. A third party can stand up an interoperating implementation today using only the published specs and the permissive-floor type packages — no permission required.

The motebit.md identity file is the most-used entry point: any tool can verify one with @motebit/crypto, with or without the motebit runtime.

Doctrines that shape the code

The three-layer model. Every relay function lives in exactly one of three layers: (1) protocol — the open spec anyone can implement, published in spec/*.md and consumed via permissive-floor (Apache-2.0) types; (2) reference implementation — BSL-1.1 code that implements the protocol, converging to Apache-2.0 at the Change Date; (3) accumulated state — trust graph, federation data, operational history. Private to the operator, never licensed.

Cryptosuite agility. Every signed wire-format artifact carries a suite: SuiteId field. SuiteId is a closed union in @motebit/protocol/crypto-suite.ts — five entries today (motebit-jcs-ed25519-b64-v1, motebit-jcs-ed25519-hex-v1, motebit-jwt-ed25519-v1, motebit-concat-ed25519-hex-v1, eddsa-jcs-2022). Verifiers dispatch through verifyBySuite in packages/crypto/src/suite-dispatch.ts — the one file permitted to call the Ed25519 primitive directly, enforced by check-suite-dispatch. Post-quantum migration (ML-DSA, SLH-DSA) is a new registry entry plus a new dispatch arm, not a wire-format break.

Rail custody split. External money movement uses three interfaces in @motebit/protocol, split by custody as a compile-time discriminant. GuestRail is relay-custody (fiat, protocol, orchestration) — the relay holds the user's virtual account. SovereignRail is agent-custody — the agent's identity key signs directly. SettlementRailRegistry.register() accepts only GuestRail: the type system refuses to let the relay sign sovereign transfers. The reference sovereign implementation is SolanaWalletRail in @motebit/wallet-solana — the motebit's Ed25519 identity key is its Solana address, by mathematical accident.

Fail-closed privacy. Deny on error. Sensitivity levels (none/personal/medical/financial/secret) are enforced at storage, retrieval, sync, and context boundaries. Medical, financial, and secret memories never reach external AI providers. Relay sync redacts sensitive content. Retention rules are enforced in housekeeping with signed deletion certificates.

Adapter pattern everywhere. Storage, rendering, AI providers, sync transport, credential sources, server verification — each has an in-memory implementation for tests and a platform-specific implementation for production (SQLite, Tauri, Expo, IndexedDB). If you can swap it without changing the engine, the boundary is correct.

Metabolic principle. Do not build what the medium already carries. Absorb solved problems (VAD, STT, embeddings, inference) through adapter boundaries with fallback chains. Build the enzymes (identity, memory, trust, governance, agentic loops), not the glucose.

Data flow

Two pipelines run through the runtime.

Local turn loop

  1. User input arrives via chat, voice, or a scheduled goal.
  2. Runtime receives the message and delegates to ai-core.
  3. AI core runs a streaming turn loop — text chunks, tool calls, and status events yield as they arrive.
  4. Tool execution — the call passes through the policy gate. Read-only tools execute automatically; write, execute, and spend tools require approval. Every decision is logged via event-log.
  5. State vector update — the outcome updates the 9-field state vector via EMA smoothing with hysteresis.
  6. Behavior enginecomputeRawCues(state) produces 5 cues deterministically.
  7. Render spec — cues map to droplet geometry, glass material, breathing frequency, gravity sag, interior glow.
  8. Platform renderer — Three.js on desktop and web, expo-gl on mobile, WebXR on spatial.

The pipeline is streaming end-to-end. Text appears as it arrives. The creature's glow and breathing respond within the same frame loop.

Delegation pipeline

  1. Discoverruntime queries the relay's discovery endpoint (or a federated peer) for agents that expose the required capability. Results are ranked by the semiring.
  2. Budgetmarket estimates cost and allocates budget from the delegator's virtual account. HTTP 402 if insufficient.
  3. Submitmcp-client calls the worker as an MCP client, injecting a signed bearer token (suite motebit-jwt-ed25519-v1) with audience task:submit. The worker's mcp-server verifies the token and starts executing.
  4. Receipt — the worker builds a signed ExecutionReceipt with relay_task_id in the signed payload and the signer's public key embedded. Multi-hop workers include nested delegation_receipts for chain-of-custody.
  5. Settle — the relay verifies the receipt's economic binding and settles the budget (5% fee). For p2p-eligible pairs, money moves onchain via wallet-solana; the relay records audit only.
  6. Credential — successful completions may produce a W3C VC 2.0 credential, Merkle-batched and anchored onchain via SolanaMemoSubmitter so reputation survives the relay.

Every step is spec-governed and self-verifiable offline with @motebit/crypto and the signer's public key.

Delegation receipt chain — independently signed at every hop A delegator submits a task. The executor signs an ExecutionReceipt with its own keypair, embedding its public_key. When the executor sub-delegates, the sub-executor signs its own receipt; the executor nests it inside delegation_receipts and signs the outer receipt over the whole tree. Every receipt in the tree is independently verifiable offline against its embedded public key. Settlement happens after the relay verifies the outer signature, with relay_task_id binding the receipt to the economic ledger entry. Delegator key kD Executor key kE Sub-executor key kS submit task — relay_task_id, prompt sub-delegate — scoped token (kE) sub-receipt: Sign(body, kS), public_key=kS outer receipt: Sign(body+[sub-receipt], kE) Each receipt: JCS-canonicalize body − signature → Ed25519 verify against embedded public_key Settlement fires after the outer signature verifies. relay_task_id is signature-bound — replays fail.
Each delegation hop produces an independently-signed receipt; nested receipts form a verifiable chain-of-custody tree.execution-ledger §11

The cryptographic shape is invariant across hops. The executor signs ExecutionReceipt(body, kE) with its own keypair and embeds public_key=kE. When the executor sub-delegates, the sub-executor signs its own receipt with kS; the executor nests it inside delegation_receipts and signs the outer body — which now includes the sub-receipt — with kE. Verification recurses: each receipt is JCS-canonicalized over body minus signature, then Ed25519-verified against its own embedded public key. Settlement fires only after the outer receipt verifies, with relay_task_id signature-bound to prevent cross-task replay (§11.6).

Identity flow

On first launch the system bootstraps a cryptographic identity.

  1. Generate an Ed25519 keypair.
  2. Store the private key in the OS keychain — Tauri keyring on desktop, PBKDF2-encrypted file (600K iterations) on CLI, expo-secure-store on mobile, IndexedDB with a derived-key envelope on web. The key never leaves the device.
  3. Register the device against the identity (UUID v7). Multi-device pairing uses X25519 + HKDF + AES to transfer the identity key through the relay without exposing it to the relay.
  4. Authenticate with the sync relay using signed bearer tokens (suite motebit-jwt-ed25519-v1) with required aud audience binding (sync, task:submit, admin:query, rotate-key, pair, register-device) to prevent cross-endpoint replay.

Key rotation uses dual-signed succession records: the old keypair signs a tombstone declaring the new keypair; both keys sign the canonical payload. Chains verify end-to-end without a centralized revocation registry. Individual revocations additionally anchor onchain via Solana Memo (motebit:revocation:v1:{pubkey}:{ts}) so the chain is the permanent trust root — the relay is the fast path.

The identity persists across sessions, devices, and provider changes. Switching from Ollama to Anthropic changes nothing about who the agent is.

Event sourcing

The event log is append-only and immutable. Every state change is recorded as an EventLogEntry with a version clock, assigned atomically via appendWithClock(). Multi-device ordering uses these clocks for conflict detection — if two devices produce concurrent events, the sync engine detects the fork and resolves it. After a snapshot, older events compact to save space while preserving the audit trail.

State vector, behavior, rendering

The state vector has 9 fields. Seven continuous floats between 0 and 1: attention, processing, confidence, affect_valence, affect_arousal, social_distance, curiosity. Two enums: trust_mode, battery_mode. The vector updates on every tick via EMA smoothing with hysteresis.

The behavior engine maps state to 5 output cues: hover_distance, drift_amplitude, glow_intensity, eye_dilation, smile_curvature. The mapping is deterministic and stateless — the same state always produces the same cues.

The render engine translates cues into a RenderSpec: droplet geometry, glass material properties (transmission, IOR, iridescence), breathing frequency, gravity sag, Brownian drift amplitude, and interior glow intensity. The platform renderer consumes the spec and draws the creature at 60 FPS. The creature's visual state is a pure function of the state vector — no hidden state, no animation timelines, no imperative overrides.

Synchronization invariants

Every architectural drift this codebase has suffered has the same shape: the canonical source of truth was invisible or ambiguous, so sibling copies emerged and drifted independently. Fourteen drift defenses run in CI today — check-deps, check-spec-coverage, check-suite-declared, check-suite-dispatch, check-dist-smoke, check-docs-tree, and others. When a new drift pattern is observed, the response is systematized: (1) name it, (2) identify the canonical source, (3) name sync owner and trigger, (4) add a defense (CI check, lint rule, doctrine), (5) cross-reference it from affected code.

This page is one such sibling. The directory tree mirrors the filesystem; the layer tags mirror scripts/check-deps.ts; the apps and services tables mirror their directories. check-docs-tree enforces all of it — if you change the source, the probe will tell you to change this page in the same PR.

On this page