Merge pull request #20 from SHOGGOTH-SECTOR/feat/stomach-economic-organ

Tighten economy specs and synchronize runtime documentation
This commit is contained in:
2026-11-01 21:02:16 -08:00
committed by GitHub
24 changed files with 1002 additions and 396 deletions
+9 -4
View File
@@ -10,8 +10,8 @@ External (world: user / network)
▼ outer bus — ICHOR (Pony) ▼ outer bus — ICHOR (Pony)
┌─────────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────────┐
│ OUTER ORGANS │ │ OUTER ORGANS │
│ • stomach / economy organ (small-model operated; │ │ • stomach / economy organ (Tcl/polyglot outer organ; │
│ digests external input → context) │ │ M3 native sims + deterministic brakes) │
│ • microagents │ │ • microagents │
│ • SAE (sparse autoencoder) │ │ • SAE (sparse autoencoder) │
│ • MoRAG = GoDAGRAG │ │ • MoRAG = GoDAGRAG │
@@ -59,6 +59,9 @@ not shared modules.
| tool-schema store (mini-rag reads this) — *COBOL store #2* | COBOL | decided | | tool-schema store (mini-rag reads this) — *COBOL store #2* | COBOL | decided |
| COBOL invariant laws / E1 (the law vault, separate) | COBOL | given | | COBOL invariant laws / E1 (the law vault, separate) | COBOL | given |
| drive-box (A1) | R | existing | | drive-box (A1) | R | existing |
| stomach/economy orchestration (M0–M7) | Tcl 8.6 | executable scaffold |
| M3a / M3b / M3c / M3e native sim bridges | R / ECLiPSe / Solidity / Fortran | V1 wired |
| M3d / M3f / M3g native sim kernels | Fortran / ECLiPSe / Fortran | kernels; bridge open |
| MoRAG / GoDAGRAG (outer) | Haskell or Crystal | open | | MoRAG / GoDAGRAG (outer) | Haskell or Crystal | open |
| Hermes | OpenHermes agent (external model) | given | | Hermes | OpenHermes agent (external model) | given |
@@ -85,5 +88,7 @@ blocking in a protected action), **tasks = workers** that call into the organs
- **MoRAG / GoDAGRAG language** (Haskell vs Crystal vs other). - **MoRAG / GoDAGRAG language** (Haskell vs Crystal vs other).
- Each outer organ's hand-off shape to Ada. - Each outer organ's hand-off shape to Ada.
- ~~The stomach/economy organ's exact placement + which small model runs it.~~ - ~~The stomach/economy organ's exact placement + which small model runs it.~~
**→ placed:** M-series (M0–M7) in `docs/plans/`. Outer organ on Ichor; data feeds via M2 (Data Feeds). **→ placed:** M-series (M0–M7) in `docs/plans/`. Outer-organ contract targets Ichor; internal
See M0 (hub), M6 (Conductor — orchestration, provenance chain, S1/S2 compliance). orchestration lives in `core/src/economy/`. M3a/M3b/M3c/M3e are runtime-wired; M3d/M3f/M3g
are native kernels. The actual Pony↔Tcl economy/Ichor runtime bridge is still open.
See M0 (hub) and M6 (supervision).
+76 -29
View File
@@ -11,37 +11,75 @@ organism are TBD and out of scope.
**scoped autonomy** and **multiple layers of failsafe braking** — it does not ask the organism's **scoped autonomy** and **multiple layers of failsafe braking** — it does not ask the organism's
Brain for permission to trade. Brain for permission to trade.
## 1A. Operational doctrine
- **Purpose:** maximize durable profit locally. At organism scale, realized surplus is metabolic
capacity - especially additional compute budget - rather than the Brain's terminal objective.
- **Authority:** scoped autonomy. Routine economic decisions remain inside the stomach. The Brain
may set broad trade prohibitions, risk posture, budget envelopes, and exceptionally veto an
individual action; ordinary supervision belongs to M6. M1 law and M4 hard ceilings remain
non-overridable at action time.
- **Evidence:** M0 may consume M2 observations, M3 predictions/calibration, M5 outcomes, M6
interventions, and M7 anomaly evidence, always retaining their provenance.
- **Permitted decisions:** compose the economy organ, route directives to the owning component,
maintain shared economic memory, expose metabolic summaries, and coordinate component lifecycle.
- **Prohibited decisions:** M0 does not bypass M1/M4/M6/M7, does not create a Brain→execution
shortcut, and does not silently convert derived belief into raw evidence.
- **Memory:** durable records accumulate source reliability, regime behavior, Sim bias, Trader
calibration, repeated anomaly patterns, protocol precursors, and intervention outcomes.
Repetition changes trust; source observations are linked, never rewritten.
- **Performance:** durable profit, capital survival, regime adaptation, improving allocation,
retained optionality, competent Traders, and surplus sufficient to further organism compute.
- **Failure:** ruin, repeated uncorrected miscalibration, loss of scoped autonomy, or profitable
behavior achieved by bypassing constitutional/braking/border constraints.
- **Completion criterion:** M0 is complete when all owned component contracts are runtime-wired,
economic memory persists and replays, Brain directives enter only through the organism boundary,
metabolic surplus is measurable, and no local execution path bypasses M1/M4/M6/M7.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · EXECUTABLE. The existing Ichor `Stomach` primitive now has a dedicated EXECUTABLE OUTER-ORGAN SCAFFOLD. `core/src/economy/` composes M1–M7, exposes normalized
M0–M7 simulation scaffold under `core/src/economy/`. M0 composes the component facades and feed/history surfaces, runs the M3 horizon clock, wires M3a/M3b/M3c/M3e through native runtimes,
emits Ada-bound secretion metadata; external execution and the Pony↔Tcl runtime bridge remain stages tax receipts without moving value, and emits Ada-bound secretion metadata. M3d/M3f/M3g
separate integration work. Role C4; scaffold implementation C2. remain native kernels without equivalent Tcl query bridges. Live custody, signing/broadcasting,
AI Trader inference, Conductor inference, SAE inference, and the Pony↔Tcl Ichor bridge remain
open. Role C4; scaffold/runtime implementation C3.
## 3. Language & location ## 3. Language & location
**Tcl 8.6 scaffold** · `core/src/economy/`. M0 orchestration is Tcl and preserves the **Tcl 8.6 orchestration** · `core/src/economy/`, with native M3 engines in R, ECLiPSe Prolog,
existing polyglot plan for later component engines. Pony remains the Ichor-facing transport layer; Solidity/Foundry, and Fortran 2018. Pony remains the Ichor-facing outer transport layer; the
the runtime bridge between Ichor and this scaffold is still open. runtime bridge between the Tcl economy facade and Ichor is still open.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** host crypto/NFT trading via the Marketplace (M1); run always-on market prediction - **Implemented now:** compose M1–M7; accept normalized M2 data; expose bounded M3 predictions
Sims (M3) fed by live Data Feeds (M2); manage sovereign-custody Wallets (M4); supervise through Marketplace; enforce deterministic Marketplace admission, wallet binding/limits,
Traders (M5) via a Conductor (M6); guard against anomalies via SAE monitor (M7); collect taxes Conductor pause/veto state, SAE call logging/alerts, and simulation-only execution; stage tax
on trader income and stub transfer to Verschwörern Veregeister wallets; maintain a **ledger of receipts; emit an Ada-bound `organ_secretion` summary.
economy-related memories and patterns** (trade history, learned market patterns, calibration - **Native M3 integration now:** M3a statistical, M3b sociological, M3c AMM/liquidity, and M3e
state). tokenomics/macro have tested M2→native-runtime→Hub paths. M3d/M3f/M3g are registered native
- **Does-not:** consult the organism's Brain for trade decisions (scoped autonomy); route around kernels but are not yet facade-queryable.
Ada for organism-bound messages (S1); store **organism** memories (E*) — economy-specific - **Does not currently:** hold private keys; sign or broadcast transactions; move tax value;
memories stay local; act as the organism's conscience (that's Eth-Int / A6). autonomously run AI Trader/Conductor/SAE inference; continuously invoke every native sim from
the scheduler; bypass Ada; or join the inner brain bus.
- **Target architecture:** scoped economic autonomy remains the design goal, but future live-money
behavior must still pass M1 law, M4 brakes, M6 supervision, M7 observation, and D1 at the
organism boundary.
## 5. Interface contract ## 5. Interface contract
- **Ichor interface (outbound):** `Envelope(Stomach, AdaBorder, OrganSecretion, payload)` — market - **Ichor interface (outbound):** `Envelope(Stomach, AdaBorder, OrganSecretion, payload)` — market
state summaries, prediction digests, and tax receipts cross Ada to reach the inner brain. state summaries, prediction digests, and tax receipts cross Ada to reach the inner brain.
- **Ichor interface (inbound):** organism directives arrive via Ichor (e.g. risk posture changes, - **Ichor interface (inbound):** organism directives arrive via Ichor. Target directive shape:
budget adjustments from A2 energy). `RiskDirective { directive_id, scope, prohibited_trade_types, uncertainty_ceiling?,
- **Internal wiring:** Marketplace (M1) ↔ Data Feeds (M2) ↔ Sims (M3). Wallets (M4) bind to budget_delta?, effective_at, expires_at?, rationale, provenance }`. Exceptional individual
Traders (M5). Conductor (M6) supervises Traders (M5). SAE (M7) acts as an independent action vetoes use the same path and name the exact `action_id`; there is no Brain→execution
antivirus / guarddog / alarm bell — monitors via Ichor-routed messages and alerts M6. shortcut.
All trader actions route through Marketplace. - **Internal wiring:** Marketplace (M1) owns the action and prediction-read boundary. M2 stores
normalized histories consumed by M3 native bridges. Wallets (M4) currently provide identity
binding and exposure brakes only. Conductor (M6) owns veto/pause state. SAE (M7) records
Marketplace-level tool calls and constructs alerts for M6. All Trader actions route through
Marketplace.
- **Economic memory contract (target):**
`EconomicMemoryRecord { subject_type, subject_id, regime, metric, value, recurrence,
observation_refs, first_seen, last_seen, provenance }`. M0 owns persistence/lookup semantics;
producers remain M2/M3/M5/M6/M7. Derived memory never rewrites source observations.
- **Tax stub:** `transfer_tax(amount, source_wallet, dest_wallet) -> receipt` — automation hook - **Tax stub:** `transfer_tax(amount, source_wallet, dest_wallet) -> receipt` — automation hook
for Verschwörern Veregeister internal wallet-to-wallet transfer. **Out of scope** — stub only. for Verschwörern Veregeister internal wallet-to-wallet transfer. **Out of scope** — stub only.
@@ -63,10 +101,15 @@ the runtime bridge between Ichor and this scaffold is still open.
SAE surveillance (M7), and wallet-level limits (M4) each independently constrain risk. SAE surveillance (M7), and wallet-level limits (M4) each independently constrain risk.
## 8. Build steps ## 8. Build steps
1. Build sub-components (M1–M7) individually — each with defined success criteria and ablative tests. 1. **Done:** executable M1–M7 Tcl scaffold and contract tests.
2. Extend the existing `Stomach` primitive in Ichor to carry the hub facade. 2. **Done:** M3 registry/scheduler plus native runtime bridges for M3a/M3b/M3c/M3e.
3. Define internal wiring topology and connect tested sub-components. 3. **Done:** simulation-only tax receipt staging.
4. Implement tax stub and Verschwörern Veregeister transfer last. 4. **Next:** define and persist the M0 economic-memory record/lookup contract.
5. **Next:** define inbound `RiskDirective` handling and prove broad/individual Brain vetoes enter
through M6/M1 without bypassing M4.
6. **Open:** runtime bridge between the economy facade and Pony/Ichor.
7. **Open:** M3d/M3f/M3g query bridges and scheduler-driven automatic refresh.
8. **Open by design:** live custody/signing/broadcast, Trader/Conductor inference, SAE inference.
## 9. Tests ## 9. Tests
Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 17 Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 17
@@ -78,6 +121,10 @@ and the running scheduler. Native simulator tests are driven by
integration test. integration test.
## 10. Open items ## 10. Open items
- Reward signal protocol from economy organ to organism (TBD, out of scope). - Define the outbound metabolic signal: realized surplus, available capital, compute-budget
- Internal communication bus (reuse Ichor internally? separate actor topology?). contribution, drawdown, and confidence in those quantities.
- Language choices per sub-component. - Persistent economic-memory store and replay semantics.
- Brain `RiskDirective` ingress and exceptional action-veto routing.
- Pony↔Tcl process/FFI boundary for the outer-organ facade.
- Automatic M3 engine scheduling/refresh and failure isolation.
- Ratified M4 custody design before any signer or broadcaster exists.
+5
View File
@@ -1,5 +1,10 @@
# M1 Marketplace — Deterministic Law Script Format Decision Document # M1 Marketplace — Deterministic Law Script Format Decision Document
> **Status:** design decision, not current runtime. The fixed-combinator S-expression format is
> the selected target constitution. Current `core/src/economy/marketplace.tcl` still uses a
> hardcoded deterministic action/chain/notional gate; parser, signatures, proof traces, and
> startup-loaded immutable law blobs remain implementation work.
## Executive Summary ## Executive Summary
The M1 Marketplace's law script is a **constitution**: deterministic, auditable, non-Turing, loaded at startup, immutable at runtime (L2). This document compares three candidate formats for expressing M1's scoped invariants (L1–L5), position limits, drawdown stops, action allowlists, wallet-binding requirements, and chain allowlists. We recommend **S-expressions with a fixed combinator set** for its optimal balance of expressiveness, auditability, non-Turing guarantees, and failure-mode isolation. The M1 Marketplace's law script is a **constitution**: deterministic, auditable, non-Turing, loaded at startup, immutable at runtime (L2). This document compares three candidate formats for expressing M1's scoped invariants (L1–L5), position limits, drawdown stops, action allowlists, wallet-binding requirements, and chain allowlists. We recommend **S-expressions with a fixed combinator set** for its optimal balance of expressiveness, auditability, non-Turing guarantees, and failure-mode isolation.
+77 -46
View File
@@ -6,23 +6,47 @@ must route**. No trader may buy, sell, mint, or interact with any on-chain proto
the Marketplace. Enforces a **deterministic law script** (scoped invariants — the marketplace's the Marketplace. Enforces a **deterministic law script** (scoped invariants — the marketplace's
own constitution) and integrates the **Conductor's veto** (M6) before execution. own constitution) and integrates the **Conductor's veto** (M6) before execution.
## 1A. Operational doctrine
- **Purpose:** serve as the economy constitution and single execution harness. M1 makes prohibited
actions unavailable; it does not decide which lawful action is economically wise.
- **Authority:** deterministic law may reject any action in scope. M5, M6, and Brain restrictions
may narrow the lawful set but may never legalize an M1 violation.
- **Evidence:** action payload, Trader identity, M4 binding/limit state, current law version, and
M6 veto/restriction state. Economic opportunity evidence belongs upstream.
- **Permitted decisions:** validate, admit/reject, produce replayable law decisions, order M4/M6
gates, execute only through an authorized adapter, and log every attempt to M7.
- **Prohibited decisions:** choose strategy, predict markets, override M4, infer Trader intent, or
mutate constitutional law during an action.
- **Memory:** retain law version, proof/violation trace, action identity, gate outcomes, and final
execution result for replay/audit.
- **Performance:** deterministic reproducibility, complete logging, zero bypasses, and parity
between simulated and eventual live admission semantics.
- **Failure:** the same inputs produce different law results; a prohibited action executes; a
lawful action bypasses a required gate; or strategy/risk judgment leaks into constitutional law.
- **Completion criterion:** live M1 requires the signed immutable law evaluator, replayable
`LawDecision`, M4-authorized signer path, M6 restriction ordering, M7 logging, and
simulation/live parity tests. RPC connectivity alone is not completion.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · EXECUTABLE SIMULATION. `core/src/economy/marketplace.tcl` implements the single SCAFFOLD · EXECUTABLE SIMULATION. `core/src/economy/marketplace.tcl` implements the single
action ingress, deterministic admission ordering, supervisor veto, monitor logging, and action ingress, deterministic admission ordering, supervisor veto, monitor logging, and
simulation-only execution. The full law-script loader remains open. Role C4; scaffold C2. simulation-only execution. The full law-script loader remains open. Role C4; scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/marketplace/`. Needs to interface with blockchain APIs (RPC/REST), wallet **Tcl 8.6** · `core/src/economy/marketplace.tcl`. The implemented surface is deterministic,
signing (M4), and the Conductor (M6). Deterministic law script must be auditable and non-Turing simulation-only, and has no RPC, signer, key, approval, or broadcaster. A future live execution
(no unbounded loops — it's a constitution, not a program). adapter may be added only after M4 custody is ratified and must remain downstream of the same
auditable admission ordering.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** receive trade requests from Traders (M5); validate against the deterministic law - **Does now:** receive `MarketAction` requests; record every submission for M7; reject paused
script (scoped invariants); check Conductor veto (M6); verify trader-wallet binding (no wallet Traders; require exact M4 Trader↔wallet binding; apply deterministic action/chain/notional law;
= no access); execute approved actions on-chain via the bound wallet's API; record all actions apply M4 exposure limits independently; consult M6 veto only after deterministic law passes;
for SAE (M7) monitoring; collect tax on realized income → Verschwörern Veregeister stub (M0). return a deterministic simulated `simtx-*` receipt for admitted actions; expose the latest M3
- **Does-not:** decide *what* to trade (Traders decide); predict markets (Sims do); hold keys prediction for a Trader.
(Wallets do); supervise behavior (Conductor + SAE do). - **Does not now:** contact a chain, sign, broadcast, hold keys, move assets, or collect real tax.
- **Does not conceptually:** decide what to trade; predict markets; supervise Traders; or let M6
legalize an action rejected by deterministic law.
## 5. Interface contract ## 5. Interface contract
- `submit_action(trader_id, action: MarketAction, wallet_id) -> { succeeded | failed }`. - `submit_action(trader_id, action: MarketAction, wallet_id) -> { succeeded | failed }`.
@@ -30,32 +54,38 @@ signing (M4), and the Conductor (M6). Deterministic law script must be auditable
(M6) for upstream output. Immune system is a separate organ (out of scope here). (M6) for upstream output. Immune system is a separate organ (out of scope here).
`MarketAction` ∈ { `buy`, `sell`, `mint`, `provide_liquidity`, `withdraw_liquidity`, `claim_rewards`, … }. `MarketAction` ∈ { `buy`, `sell`, `mint`, `provide_liquidity`, `withdraw_liquidity`, `claim_rewards`, … }.
- `query_predictions(sim_type: SimType) -> [BoundedPrediction]` — traders read per-sim-type - `query_predictions(sim_type: SimType) -> [BoundedPrediction]` — traders read per-sim-type
predictions through the Marketplace. Predictions are published continuously by the sim hub predictions through the Marketplace. The hub stores the latest published result per sim type.
(M3) via M2 Data Feeds. The Marketplace holds the latest predictions from each sim type. M3a/M3b/M3c/M3e currently publish when their calibrated facade query runs; a scheduler-driven
Traders see individual sim results (not aggregated) and decide how to weight them. continuous refresh loop is still open. Traders see individual sim results and decide how to
- `law_check(action: MarketAction) -> { pass | violation(rule_id, reason) }` — deterministic, weight them.
pure function. The law script is loaded at startup and **immutable at runtime** (mirrors S3 / - Implemented deterministic gate: required fields, action allowlist, chain allowlist, and numeric
the COBOL vault pattern). notional validation. The full startup-loaded S-expression constitution is **designed but not
- `veto_check(action: MarketAction, trader_id) -> { approved | vetoed(reason) }` — calls M6 implemented**; see `M1-law-script-design.md`.
Conductor. - Target law result:
- `execute(action: MarketAction, wallet_id) -> { tx_hash | error }` — on-chain execution via `LawDecision { action_id, law_version, pass, violation_id?, proof_trace, evaluated_at }`.
wallet API. This record must be stable enough for replay and audit; M6 veto state is deliberately outside
- `tax_event(trader_id, income_amount) -> receipt` — triggers tax collection. the law proof.
- Implemented M4 brake: exact Trader↔wallet binding plus exposure checks.
- Implemented M6 gate: one-shot veto is consumed only after deterministic law and wallet checks.
- Implemented execution result: `{ status succeeded execution simulated tx_id simtx-* }`.
- Implemented M7 observation: every submission is logged before admission checks.
- Tax staging exists on M0 as `tax_event`; Marketplace does not currently calculate realized
income or move value.
## 6. Dependencies & stubs ## 6. Dependencies & runtime state
- M4 Wallets — signing + execution; *stub:* "if finished, would sign and broadcast tx [details]". - M4 Wallets — implemented binding + exposure brakes; no signer/custody.
- M5 Traders — action source; *stub:* "if finished, would submit [action] for [asset] at [price]". - M5 Traders — registry/state exists; AI action generation is open.
- M6 Conductor — veto authority; *stub:* "if finished, would evaluate [action] against risk policy; approving". - M6 Conductor — implemented deterministic veto/pause surface; AI judgment is open.
- M7 SAE — action log consumer; *stub:* "if finished, would analyze [action] for behavioral anomalies". - M7 SAE — implemented logging + caller-created alert envelopes; SAE inference is open.
- Blockchain RPCs — on-chain execution; *stub:* "if finished, would execute [action] on [chain], returning tx_hash". - M3 Sims — latest prediction reads are implemented through Marketplace.
- Blockchain RPC/signing/broadcast — deliberately absent.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** **all market actions route through the Marketplace** — no direct on-chain - **L1 (C5):** **all market actions route through the Marketplace** — no direct on-chain
execution by any trader. This is the economy organ's S1. execution by any trader. This is the economy organ's S1.
- **L2 (C5):** the **deterministic law script is immutable at runtime** — loaded at startup, - **L2 (C5 target):** the future startup-loaded deterministic law script is immutable at runtime
never modified by traders, conductor, or sims. Changes require a restart with a new script and dual-signed. **Current implementation note:** V1 uses hardcoded deterministic allowlists and
version **and a pair of signatures from the operator and the Homunculus**. Mirrors the COBOL field/notional validation; the signed fixed-combinator evaluator is still open.
vault (S3).
- **L3 (C4):** **no wallet, no access** — a trader without a bound wallet cannot submit actions. - **L3 (C4):** **no wallet, no access** — a trader without a bound wallet cannot submit actions.
The Marketplace enforces this before any other check. The Marketplace enforces this before any other check.
- **L4 (C4):** **veto is checked after law, before execution** — law violations are rejected - **L4 (C4):** **veto is checked after law, before execution** — law violations are rejected
@@ -63,23 +93,24 @@ signing (M4), and the Conductor (M6). Deterministic law script must be auditable
- **L5 (C4):** **every action is logged** — SAE (M7) receives a record of every submitted - **L5 (C4):** **every action is logged** — SAE (M7) receives a record of every submitted
action (including rejected ones) for behavioral analysis. action (including rejected ones) for behavioral analysis.
## 8. Build steps ## 8. Build status
1. Define `MarketAction` types and the law script format. 1. **Done:** `MarketAction` validation and deterministic hardcoded gate.
2. Implement the law checker (deterministic, pure, non-Turing). 2. **Done:** M4 binding/exposure brake before execution.
3. Wire veto check to M6 Conductor. 3. **Done:** M6 veto ordering after deterministic law.
4. Wire execution to M4 Wallet API. 4. **Done:** M7 logging for pass/fail submissions.
5. Wire action logging to M7 SAE. 5. **Done:** simulation-only execution receipts.
6. Implement tax collection on realized income. 6. **Next:** implement `LawDecision` with versioned proof/violation traces.
7. **Next:** implement the signed fixed-combinator S-expression constitution against those traces.
8. **Open by design:** signer/RPC/broadcast execution and realized-income tax calculation.
## 9. Tests ## 9. Tests
Law enforcement: known violations rejected; valid actions pass. Veto: conductor veto blocks The M0 contract suite verifies walletless rejection, wrong-wallet rejection, deterministic law
execution. Wallet binding: walletless trader rejected. Logging: every action (pass + fail) logged. rejection, law-before-veto ordering, valid simulation-only execution, per-action/session brakes,
Tax: income event triggers tax stub. Immutability: law script cannot be modified at runtime. pass/fail M7 logging, pause/resume, and staged tax receipts. There is no live-chain execution test
because no live-chain execution surface exists.
## 10. Open items ## 10. Open items
- The law script language/format (DSL? declarative rules? S-expressions?). - Implement the already-decided fixed-combinator S-expression evaluator and signature checks.
- Which blockchain protocols/RPCs to support initially. - Ratify M4 custody before choosing or exposing any chain execution adapter.
- Position limits, drawdown stops, and other risk parameters — live in the law script or in the - Position/drawdown rules that belong in deterministic law versus M6 judgment.
Conductor's judgment? - Realized-income accounting and tax calculation/transfer policy.
- Tax rate / calculation method (fixed %, tiered, per-asset?).
- Non-Turing law script design — to discuss (format, expressiveness, bounds).
+79 -40
View File
@@ -6,67 +6,106 @@ flowing into both the Marketplace (M1) and the Sims (M3). Sits between them —
produces execution data (fills, positions, P&L) that feeds back into Sims, and Sims produce produces execution data (fills, positions, P&L) that feeds back into Sims, and Sims produce
predictions that inform Traders operating through the Marketplace. Data Feeds is the bridge. predictions that inform Traders operating through the Marketplace. Data Feeds is the bridge.
## 1A. Operational doctrine
- **Purpose:** preserve observations and provenance for downstream economic reasoning.
- **Authority:** M2 has no authority to decide what is true. It may validate representation and
transport semantics, not adjudicate conflicting claims.
- **Evidence:** external observations and internal feedback, each with source identity, observed
time, received time, confidence/reliability metadata, and provenance.
- **Permitted decisions:** normalize schema/units, assign stable observation identity, buffer,
replay, apply explicit backpressure, and expose conflicting observations side by side.
- **Prohibited decisions:** silently merge contradiction, overwrite history with derived belief,
editorialize payload meaning, or drop observations without explicit loss semantics.
- **Memory:** raw observations remain immutable/addressable. Regime-conditioned source reliability
is stored separately as derived economic memory linked back to observation IDs.
- **Performance:** provenance completeness, replay fidelity, explicit loss/backpressure behavior,
deduplication correctness, and downstream reproducibility.
- **Failure:** silent drop, silent contradiction collapse, provenance loss, duplicate replay as
new evidence, or a derived source assessment masquerading as an observation.
- **Completion criterion:** each adapter preserves provenance, survives reconnect/replay without
duplication, exposes backpressure/loss explicitly, and can reproduce the normalized history
consumed by downstream Sims.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · EXECUTABLE. `core/src/economy/feeds.tcl` implements normalized in-session history SCAFFOLD · EXECUTABLE. `core/src/economy/feeds.tcl` implements normalized in-session history
and explicit backpressure without silent drop. External stream adapters remain open. Role C3; and explicit backpressure without silent drop. External stream adapters remain open. Role C3;
scaffold C2. scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/feeds/`. Needs async I/O for streaming data (WebSockets, SSE, RSS polling). **Tcl 8.6 core buffer** · `core/src/economy/feeds.tcl`. V1 provides normalized in-session
Pony actors are a natural fit (async, backpressure-aware). history and explicit capacity backpressure. External WebSocket/SSE/RSS/RPC adapters, subscriptions,
and persistent storage remain separate ingress work.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** ingest live market data from external sources (RSS, price APIs, DEX subgraphs, - **Does now:** accept already-normalized `NormalizedDatum` records; validate confidence;
on-chain event logs); normalize heterogeneous data into a common internal format; distribute retain ordered per-feed in-session history up to a configured capacity; return explicit
to Sims (M3) for prediction and to Traders (M5) for decision-making; ingest Marketplace (M1) `backpressure` instead of silently evicting or dropping data; expose history to native M3
execution data (fills, portfolio state) and feed it back into Sims for calibration; maintain bridges. Current calibrated consumers use `price_tick`, `rss_news`, `dex_pool_state`, and
time-series history within session (ring buffer). `on_chain_event`.
- **Does-not:** predict (Sims do); trade (Marketplace does); filter or editorialize data — it - **Does not now:** open external streams, poll APIs, persist history, maintain subscriptions,
delivers raw, normalized feeds. Interpretation is the consumer's job. transform heterogeneous provider payloads, or synthesize execution fills.
- **Does not conceptually:** predict or trade; interpretation belongs to consumers.
## 5. Interface contract ## 5. Interface contract
- `subscribe(feed_type: FeedType, consumer_id) -> subscription_handle`. - Implemented: `publish(feed_type, source, timestamp, payload, confidence)`.
`FeedType` ∈ { `price_tick`, `rss_news`, `on_chain_event`, `dex_pool_state`, `execution_fill`, - Implemented: `history(feed_type) -> [NormalizedDatum]`.
`portfolio_state` }. - Planned, not implemented: source adapters, subscriptions, time-range queries, persistence, and
- `publish(feed_type, data_point: NormalizedDatum)` — internal; sources push into the pipeline. provider-specific normalization.
- `query_history(feed_type, time_range) -> [NormalizedDatum]` — sims and traders can pull - `FeedType` remains open-ended; the economy currently exercises `price_tick`, `rss_news`,
historical data within the session window. `on_chain_event`, and `dex_pool_state`, with `execution_fill` / `portfolio_state`
- `NormalizedDatum { feed_type, source, timestamp, payload, confidence }` — common shape. reserved for later execution feedback.
`confidence` ∈ [0.0, 10.0] — data source reliability per position produced (exchange-reported - `NormalizedDatum { feed_type, source, timestamp, payload, confidence }` — current common shape.
price = high; RSS sentiment = lower). Sims produce even finer-grained confidence. `confidence` is source-supplied/ingress reliability metadata, not M2's declaration of truth.
- Target provenance revision:
`Observation { observation_id, feed_type, source_id, observed_at, received_at, payload,
source_confidence, provenance, supersedes? }`.
Contradictory observations get different IDs and remain simultaneously addressable.
- Target derived assessment:
`SourceAssessment { source_id, regime, metric, value, recurrence, observation_refs,
evaluated_at }`. Assessments live in economic memory and may influence consumers, but never
mutate or replace the underlying `Observation`.
## 6. Dependencies & stubs ## 6. Dependencies & runtime state
- External data sources (price APIs, RSS, RPC nodes) — *stub:* canned market data replay. - External data adapters — open; callers/tests currently provide normalized data directly.
- M1 Marketplace — execution data source (fills, positions); *stub:* canned fills. - M1 Marketplace execution feedback — open; live fills/portfolio state do not exist yet.
- M3 Sims — primary consumer; *stub:* print data points. - M3a/M3b/M3c/M3e — active history consumers through their Tcl runners.
- M5 Traders — secondary consumer; *stub:* print data points. - M3d/M3f/M3g — native kernels exist; no feed-query bridge yet.
- M5 Traders — no direct feed-reader facade is currently exposed.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C4):** data feeds are **raw and unnormalized in meaning** — the pipeline normalizes - **L1 (C4):** data feeds are **raw and unnormalized in meaning** — the pipeline normalizes
*format* (schema, timestamps, units) but never interprets, filters, or editorialize content. *format* (schema, timestamps, units) but never interprets, filters, or editorialize content.
- **L2 (C4):** **bidirectional flow** — external data flows in (market → sims/traders), and - **L2 (C4 target):** **bidirectional flow** — external observations and internal execution
internal execution data flows back (marketplace → sims). Both directions use the same feedback use the same normalized datum shape. **Current implementation:** normalized ingress
`NormalizedDatum` shape. to history is live; execution-fill/portfolio feedback is reserved because execution is
simulation-only and no feedback adapter exists yet.
- **L3 (C3):** **backpressure, not drop** — if a consumer is slow, buffer up to a cap, then - **L3 (C3):** **backpressure, not drop** — if a consumer is slow, buffer up to a cap, then
apply backpressure to the source. Never silently drop data points. apply backpressure to the source. Never silently drop data points.
- **L4 (C3):** every datum carries a **source and timestamp** — consumers can always trace - **L4 (C3):** every datum carries a **source and timestamp** — consumers can always trace
where data came from and when. where data came from and when.
## 8. Build steps ## 8. Build status
1. Define `NormalizedDatum` and `FeedType` shapes. 1. **Done:** normalized datum storage shape.
2. Implement the pub/sub pipeline (subscribe, publish, distribute). 2. **Done:** per-feed ordered in-session history.
3. Wire external source adapters (start with one price API + one RSS feed). 3. **Done:** explicit capacity backpressure with no silent eviction.
4. Wire M1 execution data feedback loop. 4. **Done:** M3a/M3b/M3c/M3e calibrated history consumers.
5. Implement session-scoped time-series history (ring buffer). 5. **Next:** assign stable observation IDs and explicit provenance fields.
6. **Next:** define contradiction/replay semantics: duplicates collapse by identity; conflicting
observations coexist.
7. **Next:** persist regime-conditioned `SourceAssessment` records separately from observations.
8. **Open:** external source adapters and provider normalization.
9. **Open:** subscriptions/fan-out, time-range queries, persistence, and execution feedback.
## 9. Tests ## 9. Tests
Normalization: heterogeneous inputs produce uniform `NormalizedDatum` output. Pub/sub: subscriber The M0 suite verifies accepted publishes, capacity backpressure, preserved buffered history, and
receives published data. History: query returns correct time range. Backpressure: slow consumer source/timestamp/confidence retention. Dedicated M3 integration suites prove real consumers for
does not cause data loss. Bidirectional: marketplace fills reach sims via the feed. `price_tick`, `rss_news`, `dex_pool_state`, and `on_chain_event`. Subscription, provider
normalization, persistence, and execution-feedback tests do not exist because those surfaces are
not implemented.
## 10. Open items ## 10. Open items
- Which price APIs / RSS sources to support initially (CoinGecko? DeFiLlama? specific DEX - External source/adaptor set and credentials/rate-limit handling.
subgraphs?). - Per-feed capacity and persistence policy beyond the current configured in-session cap.
- History buffer size / eviction policy. - Subscription/fan-out semantics if push delivery is added.
- Whether feeds need authentication / rate limiting management. - Freshness/latency contracts per consumer.
- Latency requirements (how fresh must data be for each consumer type?). - Execution-fill / portfolio-state feedback once a real execution layer exists.
+115 -73
View File
@@ -11,73 +11,103 @@ hub directly. This is the hub spec; individual sim types have dedicated sub-spec
The academic foundations span AMM mechanism design [1,2], MEV game theory [3,4,5], macro The academic foundations span AMM mechanism design [1,2], MEV game theory [3,4,5], macro
tokenomics via SDEs [6,7], and evolutionary consensus games [8–11]. tokenomics via SDEs [6,7], and evolutionary consensus games [8–11].
## 1A. Operational doctrine
- **Purpose:** provide complementary mathematical senses over different scopes of the same market
environment. Sims are not contestants for one canonical oracle.
- **Authority:** M3 may model, calibrate, forecast, and report uncertainty. It may not trade,
enforce policy, select a winning Sim, or compel a Trader action.
- **Evidence:** normalized M2 observations plus Sim-specific calibration state, always with enough
target/horizon/conditioning/regime metadata to interpret a result.
- **Permitted decisions:** run native models, publish bounded predictions, declare degraded state,
score realized predictions, and retain per-Sim calibration history.
- **Prohibited decisions:** vote/average heterogeneous Sims into truth by default, hide scope,
compare correctness across incompatible targets, or reinterpret another Sim's result.
- **Memory:** repeated bias, out-of-bound realizations, regime-specific strength, and calibration
loss persist into M0 economic memory. A single miss is evidence; repetition changes trust.
- **Performance:** longitudinal calibration loss against realization and declared uncertainty,
conditioned on `target × horizon × conditioning × regime`.
- **Failure:** unscoped correctness, hidden degraded state, stale prediction presented as current,
or forced reconciliation that destroys the distinct information carried by different scopes.
- **Completion criterion:** a native Sim is runtime-complete only when calibration input, native
execution, `PredictionScope`, bounded publication, realization capture, longitudinal scoring,
degraded-state handling, persistence, and replayable tests all exist.
## 2. Status / certainty ## 2. Status / certainty
EXECUTABLE KERNEL SET. `core/src/economy/sims/` now contains all seven native engine MIXED · EXECUTABLE HUB + FOUR V1 RUNTIME BRIDGES + THREE NATIVE KERNELS.
trees (M3a–M3g), a seven-engine registry, and a live Tcl event-loop scheduler for all six `core/src/economy/sims/` contains all seven native engine trees, a seven-engine registry, the
horizons at the specified 90:1-or-faster ratios. The hub still validates/publishes bounded bounded-prediction hub, and a live Tcl event-loop clock for all six horizons. M3a, M3b, M3c,
predictions. Advanced model layers called out in the individual sub-specs remain incremental and M3e are wired end-to-end from normalized M2 history through their native runtimes into the
work; the simulator family is no longer absent. Role C3; kernel implementation C2. M3 hub and Marketplace. M3d, M3f, and M3g are tested native kernels but do not yet have equivalent
Mathematical foundations C4; live-market parameterization C1. Tcl process/query bridges. The scheduler currently advances horizon clocks; it does **not** spawn
all seven engines or republish every prediction automatically. Role C3; hub/runtime implementation
C3; live-market parameterization remains data-dependent.
## 3. Language & location ## 3. Language & location
**Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages **Tcl 8.6** · `core/src/economy/sims/`. The hub is syntax-agnostic, but V1 does not force one
lifecycle, tick-advancement, and query routing for sub-sims in their native runtimes via wire protocol on every native engine. Current bridges are deliberately native:
stdin/stdout JSON — **Fortran** (M3d, M3e, M3g), **Prolog** (M3b, M3f), **R** (M3a), - **M3a / R:** Tcl invokes the R engine and publishes typed bounded results.
**Solidity** (M3c). Tcl imposes no type system or paradigm on the - **M3b / ECLiPSe Prolog:** Tcl submits native ECLiPSe goals and parses bounded results.
sub-processes it orchestrates. - **M3c / Solidity:** Tcl uses a read-only ABI against an ephemeral/local EVM query contract in CI.
- **M3e / Fortran:** Tcl writes normalized numeric history to `tokenomics_query` over stdin and
parses its single bounded result line.
- **M3d / Fortran, M3f / ECLiPSe, M3g / Fortran:** native kernels exist; runtime bridges remain open.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** tick-advance continuously at **90:1** (90 simulated seconds = 1 wall-second) - **Implemented now:** maintain the canonical seven-engine registry; run the six-horizon wall→sim
across **six concurrent time horizons** — tick/hourly, daily, weekly, monthly, annual, and clock at 90:1 or faster; validate every published prediction against the common bounded schema;
5-year forecast windows; every tick advances every sim; maintain populations of Pops whose retain the latest prediction per sim type; expose those predictions to Traders only through
behaviors emerge from the sim's mathematical model; ingest live data from Data Feeds (M2) Marketplace; calibrate and query M3a/M3b/M3c/M3e from M2 histories using native runtimes.
for calibration; transform raw sim data into bounded predictions and publish them continuously - **Target runtime behavior:** continuously refresh native simulations on their own cadences and
to the Marketplace via M2; produce outputs with **explicit upper/lower bounds** on every publish fresh bounded predictions without a Trader query triggering computation. The horizon
prediction value. clock needed for that loop exists, but the automatic per-engine dispatch/refresh loop is not yet
| Horizon | Window | Tick step | Effective ratio | Wall time for window | implemented.
|---------|--------|-----------|-----------------|---------------------| - **Does-not:** trade; make Trader decisions; enforce Marketplace law; supervise Trader behavior;
| Tick–hourly | Next 1–60 min | 1s | 90:1 | ~40s | bypass M1, M4, M6, M7, or D1; treat registered source presence as proof that a native engine is
| Daily | Next 24h | 24s | 2,160:1 | ~40s | runtime-wired.
| Weekly | Next 7d | ~3 min | 15,120:1 | ~40s |
| Monthly | Next 30d | 12 min | 64,800:1 | ~40s | | Horizon | Window | Clock ratio |
| Annual | Next 365d | ~2.5 hr | ~788,000:1 | ~40s | |---------|--------|-------------|
| 5-year | Next 1825d | 12 hr | ~3,942,000:1 | ~40s | | Tick–hourly | Next 1–60 min | 90:1 |
- **Does-not:** trade (Traders/Marketplace do); make decisions for traders (it informs, they | Daily | Next 24h | 2,160:1 |
decide); enforce laws (Marketplace does); supervise behavior (Conductor/SAE do); receive | Weekly | Next 7d | 15,120:1 |
trader queries (traders query the Marketplace); skip ticks; run slower than 90:1. | Monthly | Next 30d | 64,800:1 |
| Annual | Next 365d | ~788,000:1 |
| 5-year | Next 1825d | ~3,942,000:1 |
## 5. Interface contract ## 5. Interface contract
- `publish(sim_type: SimType, prediction: BoundedPrediction)` — the hub continuously transforms - `publish(sim_type, BoundedPrediction)` validates and stores the latest bounded result for one
raw sim data into predictions and publishes them to the Marketplace via M2 Data Feeds. This is of `statistical`, `sociological`, `amm_liquidity`, `mev_adversarial`,
a constant stream, not on-demand. Traders query predictions from the Marketplace (M1), not from `tokenomics_macro`, `consensus_staking`, or `market_microstructure`.
the sim hub. - Current V1 minimum:
`SimType` ∈ { `statistical`, `sociological`, `amm_liquidity`, `mev_adversarial`, `BoundedPrediction { value, lower_bound, upper_bound, confidence, correctness, certainty,
`tokenomics_macro`, `consensus_staking`, `market_microstructure` } (M3a–M3g). time_horizon, sim_type, timestamp, token_ticker, recent_shift, ...metadata }`.
- `BoundedPrediction { value, lower_bound, upper_bound, confidence, correctness, certainty, Every numeric result obeys `lower_bound ≤ value ≤ upper_bound`; quality metrics are in
time_horizon, sim_type, timestamp, token_ticker, recent_shift }`. `[0,10]`.
Every output is bounded — no point estimates without uncertainty ranges. - **Required next schema revision for meaningful correctness:**
Three quality metrics, each ∈ [0.00, 10.00]: `PredictionScope { target, prediction_type, horizon, conditioning, regime, calibration_window }`
**confidence** — how sure the model is of this prediction; travels with every result. A `correctness` value without that scope metadata is insufficient
**correctness** — how accurate the model has been historically (scored against literal for durable cross-time comparison.
market values from M2); - Native engines may preserve extra metadata such as M3b population state, M3c range/routing
**certainty** — how stable the estimate is across perturbations. detail, or M3e yield-allocation weights.
**token_ticker** — which asset this prediction concerns (e.g. `"ETH"`, `"BTC"`). - `Marketplace.predictions(trader_id, sim_type)` is the Trader-facing read path. Traders never
**recent_shift** — literal observed market movement (ground truth from M2, not sim output). receive the raw hub object or native runtime handle.
Same M2 source feeds calibration and `correctness` scoring. - Current calibrated facade methods on `::stomach::Economy`:
Gain rates print as `lower - value - upper / 10.00` `statistical_from_feed_type`, `sociological_from_feed`, `amm_from_feed`, and
(e.g. `2.31 - 4.44 - 7.11 / 10.00 gain over next 30 days`); `tokenomics_from_feed`.
the denominator aids legibility — gain is not capped at 10.00. - Registry presence and horizon-clock state are operational metadata; neither implies automatic
Example: `{ value: 7.2, lower_bound: 5.8, upper_bound: 8.9, confidence: 7.30, native execution.
correctness: 8.10, certainty: 6.50, time_horizon: "4h", sim_type: "amm_liquidity",
token_ticker: "ETH", recent_shift: -0.023 }`.
- `status(sim_type?) -> { running, pop_count, last_calibration, data_freshness }` — health check.
- `calibrate(sim_type, feed_data: [NormalizedDatum])` — Data Feeds (M2) pushes live data for
model recalibration.
## 6. Dependencies & stubs ## 6. Dependencies & runtime state
- M2 Data Feeds — calibration data source; *stub:* canned market data. - **M2 Data Feeds:** implemented in-memory normalized history + explicit backpressure. External
- M1 Marketplace — prediction consumer (via M2); *stub:* print predictions. WebSocket/RSS/on-chain adapters remain open.
- M3a–M3g sub-specs — individual sim implementations; *stub:* each returns fixed predictions. - **M1 Marketplace:** implemented prediction-consumer facade; holds no native sim handles.
- **M3a:** V1 native R bridge wired and CI-verified.
- **M3b:** V1 native ECLiPSe bridge wired and CI-verified.
- **M3c:** V1 native Solidity/read-only EVM bridge wired and CI-verified.
- **M3d:** strict-Fortran kernel/tests present; Tcl query bridge open.
- **M3e:** V1 native Fortran query bridge wired and CI-verified.
- **M3f:** ECLiPSe kernel/tests present; Tcl query bridge open.
- **M3g:** strict-Fortran kernel/tests present; Tcl query bridge open.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** sims are **always running** — they are not invoked on demand. Traders query - **L1 (C5):** sims are **always running** — they are not invoked on demand. Traders query
@@ -97,21 +127,33 @@ sub-processes it orchestrates.
- **L6 (C3):** Pops are **simulation constructs, not AI actors** — they follow mathematical - **L6 (C3):** Pops are **simulation constructs, not AI actors** — they follow mathematical
rules within the sim. Traders (M5) are the AI actors. rules within the sim. Traders (M5) are the AI actors.
## 8. Build steps ## 8. Build status
1. Define `BoundedPrediction` shape (value, bounds, confidence/correctness/certainty). 1. **Done:** common `BoundedPrediction` validation and latest-result storage.
2. Build the sim runner (lifecycle management for always-on sims). 2. **Done:** seven-engine registry and six-horizon live scheduler.
3. Wire M2 Data Feeds → calibration pipeline. 3. **Done for M3a/M3b/M3c/M3e:** M2 history → native calibration/query → M3 publish.
4. Implement sub-specs M3a–M3g as they land. 4. **Kernel done, bridge open for M3d/M3f/M3g:** add the same process/query boundary.
5. Wire continuous prediction publishing → M2 → Marketplace. 5. **Next:** add common `PredictionScope` metadata and realization linkage so correctness is
explicitly target/horizon/regime scoped.
6. **Next:** persist per-Sim longitudinal calibration-loss summaries into M0 economic memory.
7. **Open:** scheduler-driven automatic refresh/publish loop independent of Trader queries.
8. **Open:** persistent calibration/history storage beyond the in-session M2 buffers.
## 9. Tests ## 9. Tests
Always-on: sim running after init without external trigger. Bounded output: every prediction has - `tclsh core/src/economy/sims/tests/hub_runtime.test` verifies the registry and six-horizon clock.
lower ≤ value ≤ upper. Three metrics: confidence, correctness, certainty all present in every - `tclsh core/src/economy/tests/stomach.test` verifies bounded publication and Marketplace reads
output. Publishing: predictions flow continuously to Marketplace via M2. Independence: one sim's inside the M0 facade.
failure doesn't affect others. Calibration: new data updates model state. - Dedicated CI verifies the native + M2→native→Hub boundaries for M3a, M3b, M3c, and M3e.
- M3d and M3g compile/test under strict Fortran flags; M3f has native ECLiPSe tests.
- A future automatic-refresh test must prove predictions update without a Trader-triggered query;
that claim is intentionally not made by the current suite.
## 10. Open items ## 10. Open items
- Pop lifecycle (birth/death/mutation within sims, or fixed populations?). - Native runtime/query bridges for M3d, M3f, and M3g.
- Cross-sim aggregation (do traders query individual sims, or is there a meta-prediction layer?). - Common `PredictionScope` + realization-reference schema.
- Calibration frequency per sim type. - Regime-conditioned longitudinal calibration-loss persistence.
- Computational budget per sim (how much CPU/GPU each can consume). - Scheduler-driven automatic engine refresh and bounded republishing.
- Per-Sim calibration cadence and failure/degraded-state policy.
- No default cross-Sim voting/averaging layer; any future synthesis must preserve source scopes
and remain a Trader/M6 interpretation aid rather than declaring a winner.
- Persistent history/calibration state beyond the in-session M2 buffer.
- Explicit CPU/GPU budgets and admission/backpressure for expensive native queries.
+15 -1
View File
@@ -7,6 +7,20 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math
(tick/hourly → daily → weekly → monthly → annual → 5-year). Pops in this sim represent (tick/hourly → daily → weekly → monthly → annual → 5-year). Pops in this sim represent
**stochastic sample paths**, not behavioral agents. **stochastic sample paths**, not behavioral agents.
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **price, volatility, tail risk, correlation, regime, roughness, and jump behavior**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
IMPLEMENTED · M3a V1 · R. `core/src/economy/sims/statistical/engine.R` now IMPLEMENTED · M3a V1 · R. `core/src/economy/sims/statistical/engine.R` now
implements the complete V1 statistical stack: GBM, Merton jump-diffusion, full-truncation Heston implements the complete V1 statistical stack: GBM, Merton jump-diffusion, full-truncation Heston
@@ -22,7 +36,7 @@ the boundary integration suite are green. Core methods C4/C5; implementation C3;
parameterization remains data-dependent rather than hardcoded. parameterization remains data-dependent rather than hardcoded.
## 3. Language & location ## 3. Language & location
**R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only: **R 4.x** (apt `r-base-core`) · `core/src/economy/sims/statistical/`. Vital CRAN packages only:
`HiddenMarkov` (Viterbi filter, forward-backward, Baum-Welch), `rugarch` (univariate GARCH `HiddenMarkov` (Viterbi filter, forward-backward, Baum-Welch), `rugarch` (univariate GARCH
volatility — GJR/EGARCH families, ML fitting), `rmgarch` (DCC-GARCH cross-asset correlation). volatility — GJR/EGARCH families, ML fitting), `rmgarch` (DCC-GARCH cross-asset correlation).
Everything else is hand-rolled with base R primitives (`optim`, `fft`, `arima`, matrix ops): Everything else is hand-rolled with base R primitives (`optim`, `fft`, `arima`, matrix ops):
+15 -1
View File
@@ -9,6 +9,20 @@ pressure across **six concurrent time horizons**. Grounded in evolutionary conse
[8,9], Hegselmann-Krause opinion dynamics (2002), complex contagion theory (Centola & Macy 2007), [8,9], Hegselmann-Krause opinion dynamics (2002), complex contagion theory (Centola & Macy 2007),
MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs. MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs.
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **sentiment, strategy population, cascade, coordination, opinion structure, manipulation phase, and narrative regime**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
IMPLEMENTED · M3b V1 · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl` IMPLEMENTED · M3b V1 · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl`
implements five abstract behavioral archetypes, replicator dynamics, Hegselmann–Krause bounded implements five abstract behavioral archetypes, replicator dynamics, Hegselmann–Krause bounded
@@ -23,7 +37,7 @@ both the ECLiPSe kernel and M2→M3b→Hub boundary. Foundations C4/C5; implemen
population parameterization remains evidence-driven rather than hardcoded to literal persons. population parameterization remains evidence-driven rather than hardcoded to literal persons.
## 3. Language & location ## 3. Language & location
**ECLiPSe Prolog 7.2** · `src/economy/sims/sociological/`. Libraries: **ic** (interval **ECLiPSe Prolog 7.2** · `core/src/economy/sims/sociological/`. Libraries: **ic** (interval
constraints — bounds propagation for BoundedPrediction ranges), **eplex** (LP/MIP via COIN-OR constraints — bounds propagation for BoundedPrediction ranges), **eplex** (LP/MIP via COIN-OR
CLP/CBC — Nash equilibrium computation). Game-theoretic equilibria, replicator dynamics, and CLP/CBC — Nash equilibrium computation). Game-theoretic equilibria, replicator dynamics, and
strategy evolution are naturally expressed as logical relations over population states; Nash strategy evolution are naturally expressed as logical relations over population states; Nash
+15 -1
View File
@@ -6,6 +6,20 @@ loss, and the non-cooperative game between liquidity providers and arbitrageurs*
**LP positions and arbitrage bots** operating on the $x \cdot y = k$ curve. Grounded in the DEX/AMM **LP positions and arbitrage bots** operating on the $x \cdot y = k$ curve. Grounded in the DEX/AMM
literature [1,2]. literature [1,2].
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **impermanent loss, pool return, liquidity range, slippage, and LP withdrawal economics**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
IMPLEMENTED · M3c V1 · Solidity/Foundry. `core/src/economy/sims/amm/src/AMMSim.sol` IMPLEMENTED · M3c V1 · Solidity/Foundry. `core/src/economy/sims/amm/src/AMMSim.sol`
implements fee-adjusted constant-product swaps, exact fixed-point impermanent loss, nonlinear implements fee-adjusted constant-product swaps, exact fixed-point impermanent loss, nonlinear
@@ -19,7 +33,7 @@ boundary on an ephemeral local Anvil instance. Mathematical foundations C5; impl
live-market parameterization remains data-dependent. live-market parameterization remains data-dependent.
## 3. Language & location ## 3. Language & location
**Solidity** + **Foundry** (forge, anvil) · `src/economy/sims/amm/`. Foundry is hosted **Solidity** + **Foundry** (forge, anvil) · `core/src/economy/sims/amm/`. Foundry is hosted
separately from the session container — not a session-start install. M3c's output enters the separately from the session container — not a session-start install. M3c's output enters the
system through Hub like every other sim, same `BoundedPrediction` schema, same M2 path. system through Hub like every other sim, same `BoundedPrediction` schema, same M2 path.
On-chain-equivalent fixed-point arithmetic reproduces the exact invariant calculations DEXs On-chain-equivalent fixed-point arithmetic reproduces the exact invariant calculations DEXs
+15 -1
View File
@@ -12,6 +12,20 @@ Grounded in ACM MEV game theory [3], knapsack auction literature [4,5], Kolokolt
dynamics (non-linear Fokker-Planck with WENO shock capturing), and DSMFG bilevel optimization dynamics (non-linear Fokker-Planck with WENO shock capturing), and DSMFG bilevel optimization
(leader policy + follower MFG equilibrium). (leader policy + follower MFG equilibrium).
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **auction pressure, extraction opportunity, block-space competition, sandwich/front-run risk, and adversarial cost**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/mev/` implements the all-pay KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/mev/` implements the all-pay
PGA payoff model, exact 0/1 block-building knapsack selection, dual-path cross-chain profit PGA payoff model, exact 0/1 block-building knapsack selection, dual-path cross-chain profit
@@ -20,7 +34,7 @@ under strict gfortran flags. WENO/Kolokoltsov and DSMFG bilevel solvers remain i
Core game/knapsack foundations C4; implementation C2; parameterization C1. Core game/knapsack foundations C4; implementation C2; parameterization C1.
## 3. Language & location ## 3. Language & location
**Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS** **Fortran 2018** (gfortran) · `core/src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS**
(LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Box-Muller RNG, WENO stencils, SDE (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Box-Muller RNG, WENO stencils, SDE
solvers, knapsack, JSON I/O against fixed schemas. Dense numerical loops for PDE solvers (WENO solvers, knapsack, JSON I/O against fixed schemas. Dense numerical loops for PDE solvers (WENO
shock-capturing), knapsack combinatorics, and continuous-time auction modeling at the throughput shock-capturing), knapsack combinatorics, and continuous-time auction modeling at the throughput
+47 -18
View File
@@ -12,6 +12,20 @@ Grounded in Vienna complex-systems token modeling [7], ResearchGate engineering
frameworks [6], Aave/Compound kinked interest rate models (industry standard), and DeXposure frameworks [6], Aave/Compound kinked interest rate models (industry standard), and DeXposure
inter-protocol credit propagation (Matzakos et al. 2025). inter-protocol credit propagation (Matzakos et al. 2025).
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **supply, inflation, staking, velocity, policy discontinuity, treasury runway, lending utilization, liquidation, contagion, and yield allocation**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
IMPLEMENTED · M3e V1 · Fortran 2018. `core/src/economy/sims/tokenomics/` IMPLEMENTED · M3e V1 · Fortran 2018. `core/src/economy/sims/tokenomics/`
implements conserved aggregate token state, Euler–Maruyama stochastic evolution, scalar Kalman implements conserved aggregate token state, Euler–Maruyama stochastic evolution, scalar Kalman
@@ -25,7 +39,7 @@ verifies the numerical kernel and the M2→Fortran→Hub boundary. Foundations C
C3; live-token parameterization remains data-driven. C3; live-token parameterization remains data-driven.
## 3. Language & location ## 3. Language & location
**Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies: **Fortran 2018** (gfortran) · `core/src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies:
**OpenBLAS** (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Box-Muller RNG, SDE **OpenBLAS** (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Box-Muller RNG, SDE
solvers, JSON I/O against fixed schemas. SDE solvers (Euler-Maruyama, Milstein), state-space solvers, JSON I/O against fixed schemas. SDE solvers (Euler-Maruyama, Milstein), state-space
estimation, and VAR impulse responses are dense matrix-heavy loops where Fortran's array estimation, and VAR impulse responses are dense matrix-heavy loops where Fortran's array
@@ -105,24 +119,39 @@ across the heaviest numerical sims.
- **L5 (C4):** DeXposure contagion is **directional** — protocol A's exposure to protocol B - **L5 (C4):** DeXposure contagion is **directional** — protocol A's exposure to protocol B
is not symmetric. The exposure matrix $E_{ij}$ is not assumed symmetric. is not symmetric. The exposure matrix $E_{ij}$ is not assumed symmetric.
## 8. Build steps ## 8. Build status
1. Implement Euler-Maruyama SDE solver for a simple token model (supply + staking). 1. **Done:** Euler–Maruyama SDE solver and moment-law characterization.
2. Define the state vector $X_t$ and drift/diffusion functions for a reference token. 2. **Done:** conserved aggregate token state with circulating/staked/locked/burned/minted stocks.
3. Add stock-flow accounting (verify conservation). 3. **Done:** discrete halving/emission and burn policy flows.
4. Implement kinked lending rate model (Aave-style) with liquidation cascade simulation. 4. **Done:** kinked lending curve plus iterative liquidation cascade simulation.
5. Implement DeXposure credit propagation network with VAR impulse responses. 5. **Done:** directional exposure propagation and VAR impulse-response kernels.
6. Implement composable yield optimizer (risk-adjusted return maximization). 6. **Done:** exact constrained quadratic yield optimizer with active-set/KKT solution.
7. Wire M2 on-chain data → state estimation / calibration. 7. **Done:** M2 `on_chain_event` → native Kalman state estimation/calibration.
8. Add monetary policy events (halving, burn) as drift discontinuities. 8. **Done:** ten bounded prediction types → Tcl runner → M3 hub → Marketplace.
9. **Future fidelity:** explicit multi-protocol graph ingestion, multi-token correlated state, and
protocol-specific lending curves.
## 9. Tests ## 9. Verification
SDE: sample paths have correct mean (matches drift) and variance (matches diffusion). Stock-flow: Dedicated `M3e Tokenomics CI` compiles both native binaries with
conservation holds across all time steps. Halving: supply growth rate drops at halving event. `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`.
Lending: rate curve exhibits kink at $U_{\text{opt}}$; liquidation cascades triggered when
collateral ratio breached. DeXposure: shock to protocol A propagates to protocol B through shared Native tests cover:
collateral; isolated protocols unaffected. Yield: optimizer rebalances toward highest risk-adjusted - Euler–Maruyama mean and variance laws.
APY. Calibration: state estimate converges to observed data. Bounds: SDE confidence bands cover - stock-flow conservation and token-state transitions.
realized paths on backtest. Speed: sim tick-advances at 90:1. - halving discontinuities.
- kinked lending behavior.
- multi-hop liquidation contagion with isolated-protocol control.
- directional VAR impulse propagation.
- yield-allocation normalization and KKT stationarity.
- Kalman convergence and uncertainty reduction.
The Tcl boundary suite covers runner availability, M2 `on_chain_event` → Fortran → M3
publication, all ten prediction types satisfying hub bounds/quality ranges, and explicit failure
on insufficient history. The current final-head contract is `4 passed / 0 failed`.
Backtest coverage calibration of forecast intervals against long external histories remains a
future empirical-validation task; V1 verifies structural bounds rather than claiming calibrated
frequentist coverage.
## 10. V1 decisions and future extensions ## 10. V1 decisions and future extensions
- **Token universe:** V1 is token-agnostic. M2 chooses the ticker and supplies its policy/state - **Token universe:** V1 is token-agnostic. M2 chooses the ticker and supplies its policy/state
+15 -1
View File
@@ -7,6 +7,20 @@ and Byzantine fault tolerance** using evolutionary games and Markov chains. Pops
financial incentives. Grounded in Cornell evolutionary consensus [8,9], ACM staking pool risk financial incentives. Grounded in Cornell evolutionary consensus [8,9], ACM staking pool risk
theorems [10], and Monash dynamic PBFT modeling [11]. theorems [10], and Monash dynamic PBFT modeling [11].
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **validator honesty, staking incentives, slashing risk, validator-state transitions, coordination, and liveness**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/consensus/engine.ecl` KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/consensus/engine.ecl`
implements evolutionary honesty updates, validator-state Markov transitions, an explicit implements evolutionary honesty updates, validator-state Markov transitions, an explicit
@@ -15,7 +29,7 @@ Native tests live beside the engine. The large-population HJB/Fokker-Planck MFG
incremental. Foundations C4; implementation C2; protocol parameterization C1. incremental. Foundations C4; implementation C2; protocol parameterization C1.
## 3. Language & location ## 3. Language & location
**ECLiPSe Prolog 7.2** · `src/economy/sims/consensus/`. Libraries: **ic** (interval **ECLiPSe Prolog 7.2** · `core/src/economy/sims/consensus/`. Libraries: **ic** (interval
constraints), **eplex** (LP/MIP via COIN-OR CLP/CBC — Nash equilibrium via linear programming). constraints), **eplex** (LP/MIP via COIN-OR CLP/CBC — Nash equilibrium via linear programming).
Markov chain transition rules, Nash equilibrium search, and replicator dynamics are Markov chain transition rules, Nash equilibrium search, and replicator dynamics are
constraint-satisfaction problems over validator populations; Prolog's backtracking search finds constraint-satisfaction problems over validator populations; Prolog's backtracking search finds
@@ -9,6 +9,20 @@ Operates at the highest temporal resolution — where M3a provides statistical f
models pool mechanics, M3g models the *plumbing* of how orders actually execute, across **six models pool mechanics, M3g models the *plumbing* of how orders actually execute, across **six
concurrent time horizons** at tick-advanced, 90:1 (1s wall = 90s sim). concurrent time horizons** at tick-advanced, 90:1 (1s wall = 90s sim).
## 1A. Measurement contract
This Sim inherits the M3 common epistemic contract. Its scope is **depth, spread, slippage, order impact, execution schedule, cross-venue arbitrage decay, and market regime**.
- Every prediction must identify `target`, `prediction_type`, `horizon`, relevant
`conditioning`, and `regime` before its `correctness` score is meaningful.
- `confidence` describes evidential/model support; `certainty` describes stability under
perturbation/model uncertainty; `correctness` is empirical accuracy after realization. These
are not synonyms.
- Correctness is compared longitudinally only within compatible scopes. It is not a universal
leaderboard against other M3 domains.
- Every prediction family must eventually link to a realization and accumulate
regime-conditioned calibration loss. Repeated bias or repeated out-of-bound realizations feed
M0 durable economic memory.
- This Sim does not need to agree with another Sim. Cross-domain interpretation belongs to M5/M6.
## 2. Status / certainty ## 2. Status / certainty
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/microstructure/` implements KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/microstructure/` implements
depth-consuming buy slippage, bid/ask spread, Almgren-Chriss execution schedules, exponential depth-consuming buy slippage, bid/ask spread, Almgren-Chriss execution schedules, exponential
@@ -17,7 +31,7 @@ under strict gfortran flags. Full order-event simulation and venue adapters rema
Microstructure C4; Almgren-Chriss C5; implementation C2; DEX-specific calibration C1/C2. Microstructure C4; Almgren-Chriss C5; implementation C2; DEX-specific calibration C1/C2.
## 3. Language & location ## 3. Language & location
**Fortran 2018** (gfortran) · `src/economy/sims/microstructure/`. Build: **fpm**. Dependencies: **Fortran 2018** (gfortran) · `core/src/economy/sims/microstructure/`. Build: **fpm**. Dependencies:
**OpenBLAS** (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Riccati ODE solver, **OpenBLAS** (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Riccati ODE solver,
order-book state arrays, JSON I/O against fixed schemas. Almgren-Chriss optimal execution is a order-book state arrays, JSON I/O against fixed schemas. Almgren-Chriss optimal execution is a
dense ODE (Riccati equations) — Fortran's home turf; LAPACK is native, array intrinsics map dense ODE (Riccati equations) — Fortran's home turf; LAPACK is native, array intrinsics map
+72 -40
View File
@@ -7,65 +7,97 @@ handles multiple chains internally (EVM, Solana, etc.). A trader without a walle
the Marketplace (M1). Wallets hold keys, sign transactions, and enforce wallet-level trade limits. the Marketplace (M1). Wallets hold keys, sign transactions, and enforce wallet-level trade limits.
Tax is collected on trader income and routed to the Verschwörern Veregeister wallets (stub — M0). Tax is collected on trader income and routed to the Verschwörern Veregeister wallets (stub — M0).
## 1A. Operational doctrine
- **Purpose:** provide the final capability boundary around assigned capital: protect the organism
from a Trader, the Trader from itself, one Trader's funding from another, and the capital base
from catastrophic loss.
- **Authority:** M4 hard ceilings are absolute at action time. Trader, M6, and Brain authority may
further restrict activity but may not override an active M4 ceiling for one action.
- **Evidence:** Trader↔wallet binding, active limit version, proposed action/notional, cumulative
spend/exposure, and eventual chain/custody state.
- **Permitted decisions:** bind identity, calculate exposure, admit/reject against hard ceilings,
record spend, and eventually sign only Marketplace-authorized transactions.
- **Prohibited decisions:** choose strategy, infer opportunity, lend one Trader another Trader's
capital, accept a per-action override, or delegate custody to a third party.
- **Memory:** persist limit versions, binding history, capital-at-risk, spend history, signer
attribution, and any future custody/recovery event.
- **Performance:** zero ceiling bypasses, exact attribution of every admitted spend, isolation
between Trader capital stores, and recoverable/auditable custody state.
- **Failure:** any action exceeds the active ceiling, a wallet is reassigned without an explicit
versioned transition, another component can override a brake, or key custody escapes the
sovereign boundary.
- **Completion criterion:** custody is complete only when binding, versioned hard ceilings, local
key custody, signer authorization, recovery/rotation, transaction attribution, and persistence
are all tested. A working signature primitive alone is insufficient.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · PARTIAL. `core/src/economy/wallets.tcl` implements permanent 1:1 binding and SCAFFOLD · PARTIAL. `core/src/economy/wallets.tcl` implements permanent 1:1 binding and
independent exposure limits for the simulation scaffold. Custody/signing implementation remains independent exposure limits for the simulation scaffold. Custody/signing implementation remains
open. Role C4; scaffold C2. open. Role C4; scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for **Tcl 8.6 brake/binding scaffold** · `core/src/economy/wallets.tcl`. V1 contains no key
Solana, etc.) material or cryptography. A future custody implementation will require ratified storage/rotation
semantics before any secp256k1/ed25519 signer is introduced.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** generate and store private keys locally (never transmitted); sign transactions on - **Does now:** enforce permanent 1:1 Trader↔wallet identity binding; reject cross-Trader wallet
behalf of the bound trader; enforce per-wallet spending limits (daily, per-transaction); use; enforce per-action and cumulative session exposure limits; record simulated admitted
track wallet balance and transaction history; collect tax on realized income and stage for notional for brake accounting.
transfer to Verschwörern Veregeister wallets; bind 1:1 to a Trader (M5). - **Does not now:** generate, store, import, derive, rotate, or expose private keys; sign
- **Does-not:** decide what to trade (Trader decides); route to chain (Marketplace does); transactions; query balances; broadcast; maintain chain transaction history; or transfer tax.
hold keys for the organism's other wallets (Verschwörern Veregeister are separate); delegate - **Target invariant:** if live custody is later implemented, it remains sovereign/local and
custody to any third party — ever. cannot delegate custody to a third party.
## 5. Interface contract ## 5. Interface contract
- `sign(wallet_id, tx: UnsignedTransaction) -> SignedTransaction` — signs with the wallet's key. Implemented Tcl surface:
Only the bound trader can request signing. - `bind(wallet_id, trader_id, daily_limit, per_action_limit)`.
- `balance(wallet_id) -> { chain, assets: [{ token, amount }] }`. - `binding_for(trader_id)` and `binding_matches(trader_id, wallet_id)`.
- `spending_check(wallet_id)`. - `spending_check(wallet_id, action)` — independent exposure brake.
- taxes are out of scope - `record_spend(wallet_id, notional)` — simulation accounting only.
- `count()`.
- Target hard-limit record:
`WalletLimitVersion { wallet_id, trader_id, version, per_action_limit, cumulative_limit,
effective_at, supersedes?, provenance }`.
Every admitted action must name the exact active limit version. No API accepts a per-action
override.
## 6. Dependencies & stubs Future custody surface such as `sign`, `balance`, key generation/import, and transaction
- M5 Traders — 1:1 binding; *stub:* canned trader ID. history is intentionally **not implemented** and must not be inferred from the component name.
- M1 Marketplace — signing requests come through marketplace only; *stub:* direct sign call.
- Blockchain nodes — balance queries and tx broadcast; *stub:* simulated chain state. ## 6. Dependencies & runtime state
- Verschwörern Veregeister wallets — tax destination; *stub:* log transfer. - M5 Traders — implemented identity registry for 1:1 binding.
- M1 Marketplace — implemented caller of binding/exposure checks.
- Blockchain nodes / signing libraries — absent.
- Tax destination wallets — no transfer surface; M0 only stages receipt metadata.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** **sovereign custody only** — private keys are generated locally, stored locally, - **L1 (C5 target):** **sovereign custody only** if custody is implemented. V1 contains no keys at
and **never leave the wallet**. No custodial service, no exchange deposit, no trust with external all, which is stronger than accidentally introducing an unratified custody path.
parties. Our keys, our coins.
- **L2 (C5):** **1:1 trader binding** — each wallet is bound to exactly one trader. A trader - **L2 (C5):** **1:1 trader binding** — each wallet is bound to exactly one trader. A trader
cannot use another trader's wallet. The Marketplace enforces this. cannot use another trader's wallet. The Marketplace enforces this.
- **L3 (C4):** **signing requires Marketplace confirmation** — a wallet will not sign a transaction - **L3 (C4 target):** future signing requires Marketplace confirmation. V1 has no signing API for
that didn't receive direct authorization from Marketpakce (M1-L1). No direct signing API for traders. Marketplace or Traders.
- **L4 (C4):** **spending limits are wallet-level** — independent of Conductor or Marketplace - **L4 (C4):** **spending limits are wallet-level** — independent of Conductor or Marketplace
limits. Defense in depth: even if other rules fail, the wallet itself caps exposure. limits. Defense in depth: even if other rules fail, the wallet itself caps exposure.
- **L5 (C4):** **tax collection is automatic** — realized income triggers tax staging. The trader - **L5 (C4 target/out of scope):** realized-income tax policy may trigger staging/transfer later.
cannot opt out. OUT OF SCOPE V1 only exposes an M0 receipt-staging hook; M4 performs no tax action.
## 8. Build steps ## 8. Build status
1. Implement key generation and secure storage. 1. **Done:** permanent 1:1 Trader↔wallet binding.
2. Implement transaction signing for one chain. 2. **Done:** per-action and cumulative session exposure brakes.
3. Implement trader binding and Marketplace-only signing enforcement. 3. **Done:** Marketplace-only use of the implemented wallet scaffold.
4. Implement algorithmic limits. 4. **Next:** version hard limits and attach the active limit version to every admitted spend.
5. **Next:** persist capital-at-risk / spend history per Trader wallet for longitudinal analysis.
6. **Open by design:** key generation/storage, signing, balances, chain adapters, rotation/backup.
## 9. Tests ## 9. Tests
Custody: private key never appears in any response, messages, or log. Current tests verify walletless rejection, wrong-Trader binding rejection, independent per-action
Binding: wrong trader cannot sign. and cumulative exposure limits, and simulated spend accounting. There are intentionally no
Trade limits: over-limit transaction rejects; risk :: reward ratio below-limit rejects. signature/multi-chain custody tests because no key/signing implementation exists.
Tax: out of scope.
Multi-chain: every chain produces valid signatures.
## 10. Open items ## 10. Open items
- Key storage format. - Ratified key storage, backup, recovery, and rotation design.
- Which chains to support initially. (all of them) - Chain/signature support only after custody is ratified.
- Spending limit configuration (correction: This is algorithmic and hardcoded.) - Persistent time-window semantics for the currently session-cumulative exposure limit.
- Key rotation / backup strategy. - Balance/transaction-history model if live custody is introduced.
+78 -25
View File
@@ -4,53 +4,106 @@
The economy organ's hands: **specialized AI instances** that buy, sell, and mint cryptocurrency and The economy organ's hands: **specialized AI instances** that buy, sell, and mint cryptocurrency and
NFTs. Each trader is bound to a Wallet (M4), operates through the Marketplace (M1), queries Market to receive predictions (M3), and are monitored by the SAE (M7) via Marketplace. Multiple traders operate concurrently with **different heuristics and specializations**. NFTs. Each trader is bound to a Wallet (M4), operates through the Marketplace (M1), queries Market to receive predictions (M3), and are monitored by the SAE (M7) via Marketplace. Multiple traders operate concurrently with **different heuristics and specializations**.
## 1A. Operational doctrine
- **Purpose:** act as persistent, genuinely agentic economic entities that profitably deploy
independently assigned capital through specialized judgment and learning.
- **Authority:** a Trader chooses forecasts, evidence weighting, strategy, abstention, position
sizing, and lawful actions inside M1 law, M4 hard ceilings, and the active M6 uncertainty regime.
- **Evidence:** Marketplace-accessible M3 predictions, allowed market state, the Trader's own
decision/outcome memory, assigned capital state, and current M6 regime/restrictions.
- **Permitted decisions:** form predictions, declare uncertainty, disagree with other Traders,
choose/decline lawful actions, allocate only its own capital, and update its own learned strategy.
- **Prohibited decisions:** use another Trader's funding, bypass Marketplace, access raw chain
execution, override M4/M6, or treat another Trader's disagreement as something requiring
consensus.
- **Memory:** persist forecasts, declared uncertainty, decision basis, realized outcome, recurring
failure modes, regime-specific competence, and intervention history.
- **Performance:** P&L is the local objective; longitudinal loss relative to the Trader's own
prediction and declared uncertainty is the primary diagnostic. Expected losses and confident
surprise losses are not equivalent.
- **Failure:** persistent surprise loss, worsening calibration without adaptation, unauthorized
capital use, or profitable behavior dependent on bypassing constitutional/supervisory limits.
- **Completion criterion:** a Trader runtime is complete when it can form a prediction, declare
uncertainty, choose a lawful action, use only assigned capital, persist the decision basis,
receive realization, update memory, and expose rolling P&L plus regime-conditioned calibration
loss.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · PARTIAL. `core/src/economy/traders.tcl` implements trader identity, SCAFFOLD · PARTIAL. `core/src/economy/traders.tcl` implements trader identity,
specialization labels, and mechanical pause/resume state. Trader inference remains open. specialization labels, and mechanical pause/resume state. Trader inference remains open.
Role C3; scaffold C2. Role C3; scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/traders/`. Traders are AI agents.All use the same `MarketAction` interface through the Marketplace regardless of implementation. Traders are the agentic entities, the determininistic bots are subservient to them. **Tcl 8.6 identity/state scaffold** · `core/src/economy/traders.tcl`. The implemented object is
not an AI inference runtime: it registers Trader identity/specialization and maintains mechanical
pause state. Future Trader cognition may be implemented separately, but every implementation must
still use the same Marketplace-only `MarketAction` surface. Deterministic helper bots remain
subservient to Traders rather than becoming independent market actors.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** read sim predictions from the Marketplace (M1) (bounded, multi-domain, per-sim-type); - **Does now:** register unique Trader IDs with specialization labels; expose existence/count;
formulate trade decisions based on predictions + market state + specialization; submit enter and leave mechanical pause state under M6 control.
`MarketAction` requests to the Marketplace (M1) only bound wallet (M4); operate with **scoped - **Future Trader runtime:** read bounded predictions through Marketplace, formulate actions from
autonomy** — trades within law/budget constraints don't need Brain or Conductor approval; manage lower level bot goals. specialization + market state, and submit `MarketAction` through M1 using its bound M4 wallet.
- **Does-not:** execute on-chain directly (Marketplace does); hold keys (Wallet does); supervise - **Does not:** execute on-chain directly; hold keys; supervise other Traders; modify Marketplace
other traders (Conductor does); modify the law script (immutable — M1-L2); bypass the law; bypass Marketplace; or currently perform AI inference.
Marketplace (M1-L1) - this must be due to literal lack of surface.
## 5. Interface contract ## 5. Interface contract
Implemented Tcl registry/state surface:
- `register(trader_id, specialization)`.
- `exists(trader_id)`.
- `pause(trader_id)`, `resume(trader_id)`, `is_paused(trader_id)`.
- `count()`, `paused_count()`.
- [somehow this was a literal mess] The future AI Trader layer must produce Marketplace `MarketAction` requests and consume
Marketplace predictions; no native model/inference interface is implemented in V1.
Target decision/outcome records:
- `TraderDecision { decision_id, trader_id, regime, forecast_refs, declared_uncertainty,
action, capital_at_risk, rationale_digest, created_at }`.
- `TraderOutcome { decision_id, realization_refs, realized_pnl, calibration_loss,
realized_at }`.
`calibration_loss` is the longitudinal diagnostic: it measures realized outcome against the
Trader's own prediction and declared uncertainty within the active regime. P&L remains the local
objective; calibration loss explains whether wins/losses were expected or surprising.
## 6. Dependencies & stubs ## 6. Dependencies & stubs
- M1 Marketplace — trade verification; *stub:* none, must make marketplace first. - M1 Marketplace — implemented action/prediction boundary.
- M1 Marketplace — predictions (from sims via M2) and action submission; *stub:* see above - M4 Wallets — implemented 1:1 binding + exposure brakes; custody/signing absent.
- M4 Wallet — bound 1:1; *stub:* see above - M6 Conductor — implemented mechanical pause/veto supervision; specialist inference absent.
- M6 Conductor — supervision; *stub:* ... need i state - M7 SAE — implemented Marketplace-level logging/alert envelopes; SAE inference absent.
- M7 SAE — Out of scope - AI Trader inference runtime — open.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** **all trades go through the Marketplace** — a trader cannot interact with - **L1 (C5):** **all trades go through the Marketplace** — a trader cannot interact with
any chain or protocol except via Marketplace (M1). Enforced by architecture (no direct RPC access), not just policy. any chain or protocol except via Marketplace (M1). Enforced by architecture (no direct RPC access), not just policy.
- **L3 (C4):** **wallet binding is permanent** — a trader's wallet cannot be reassigned to another trader at any time. - **L3 (C4):** **wallet binding is permanent** — a trader's wallet cannot be reassigned to another trader at any time.
- **L4 (C4):** **Conductor can pause** — a paused trader cannot submit actions, query sims, or read feeds until resumed by the Conductor (M6). This is mechanical. - **L4 (C4):** **Conductor can pause** — a paused Trader cannot submit Marketplace actions or
query Marketplace predictions until resumed by M6. M2 does not currently expose a direct
Trader feed-read facade.
- **L5 (C3):** trader specialization constrains strategy but not the interface — all traders use the same vocabulary regardless of specialization. - **L5 (C3):** trader specialization constrains strategy but not the interface — all traders use the same vocabulary regardless of specialization.
## 8. Build steps ## 8. Build status
1. Make the real build order. 1. **Done:** unique Trader registry + specialization labels.
2. **Done:** mechanical pause/resume state owned by M6.
3. **Done:** M1 rejects paused Traders and M1 prediction reads reject paused Traders.
4. **Done:** M4 enforces permanent wallet binding independently.
5. **Next:** define/persist `TraderDecision` and `TraderOutcome` records.
6. **Next:** compute regime-conditioned calibration-loss rate and P&L rate over rolling windows.
7. **Next:** expose M6 uncertainty-regime admission to the Trader before M1 submission.
8. **Open:** AI inference/action-generation runtime and specialization-specific decision logic.
9. **Open:** any lower-level deterministic helper-bot framework subordinate to Traders.
## 9. Tests ## 9. Tests
Marketplace-only: trader cannot call chain RPC directly. Current tests verify identity existence, wallet binding through M1, pause blocking action
Wallet binding: trader uses only its bound wallet. submission, resume restoring submission, and Marketplace-only prediction access. There is no test
Pause: paused trader does not change state. for specialization-dependent action patterns because Trader inference is not implemented.
Specialization: different specializations produce different action patterns on identical market state.
## 10. Open items ## 10. Open items
- Trader architecture - Trader inference architecture and model/runtime choice.
- Number of concurrent traders and resource allocation per trader. - Number of concurrent Traders and resource allocation.
- Specialization catalog (which types, and how do they differ in strategy?). - Specialization catalog and training/conditioning semantics.
- Inter-trader coordination (necessary for high end maneuvers including rugpulls) - Safe coordination semantics between Traders, if any; no direct execution bypass may emerge
from coordination.
- Helper-bot interfaces that remain deterministic and subordinate to the owning Trader.
+77 -42
View File
@@ -7,25 +7,48 @@ SAE (M7) and acts on them. The Conductor is the stomach's own judgment — it do
organism's Brain for trade-level decisions. It supervises; the deterministic law script (M1) organism's Brain for trade-level decisions. It supervises; the deterministic law script (M1)
constrains; together they form the multi-layered braking system. constrains; together they form the multi-layered braking system.
## 1A. Operational doctrine
- **Purpose:** provide the stomach's big-picture intelligence: risk officer, immune response,
executive judgment, and portfolio/system situational awareness above local Trader views.
- **Authority:** M6 may set uncertainty regimes, narrow lawful behavior, veto, pause, restrict,
resume, and interpret organism directives. It may never legalize an M1 violation or override an
M4 hard ceiling.
- **Evidence:** M7 signals, M3 scoped predictions, Trader decision/outcome history, portfolio-wide
exposure, capital concentration, active uncertainty regime, and Brain/M0 directives.
- **Permitted decisions:** establish broad uncertainty boundaries, resolve system-level
implications across complementary Sims/Traders, impose/release restrictions, and route broad
or exceptional Brain vetoes into local enforcement.
- **Prohibited decisions:** trade, own a wallet, rewrite M1 law, override M4, force Sims to agree,
or create a direct Brain→execution path.
- **Memory:** persist decisions, evidence refs, regime versions, intervention outcomes, false
positives/negatives, repeated systemic precursors, and reversal history.
- **Performance:** prevented ruin, calibrated restriction quality, intervention outcome quality,
false-positive/false-negative rates, and preservation of profitable autonomy - not veto count.
- **Failure:** missing a repeated systemic precursor, chronically suppressing profitable lawful
behavior without evidence, allowing out-of-regime uncertainty, or permitting higher authority
to bypass M1/M4.
- **Completion criterion:** supervisory AI is complete only when uncertainty-regime policy,
portfolio-wide state, intervention reasoning, reversible restrictions, outcome feedback,
persistent memory, and Brain-directive handling are explicit and testable.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · EXECUTABLE SUPERVISION. `core/src/economy/conductor.tcl` implements veto ordering, SCAFFOLD · EXECUTABLE SUPERVISION. `core/src/economy/conductor.tcl` implements veto ordering,
pause/resume, alert intake, and an in-memory decision log. Specialist inference and persistent pause/resume, alert intake, and an in-memory decision log. Specialist inference and persistent
audit storage remain open. Role C4; scaffold C2. audit storage remain open. Role C4; scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/conductor/`. The Conductor is an AI actor — likely a fine-tuned LLM with **Tcl 8.6 supervision scaffold** · `core/src/economy/conductor.tcl`. V1 is deterministic state
specialist training in market risk, trader behavior analysis, and anomaly response. The and audit behavior only: veto-next, pause/resume, SAE alert intake, and decision logging.
inference wrapper sits alongside the Marketplace. Specialist-trained inference is a future layer, not part of the current executable surface.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** receive SAE (M7) anomaly reports on trader behavior; **pause** a flagged trader's - **Does now:** stage a one-shot veto reason per Trader; mechanically pause/resume Traders;
actions to investigate; **veto** a Marketplace action if investigation reveals risk; **resume** receive M7 alert envelopes; automatically pause on configured severe alerts; append decisions
a cleared trader; review Marketplace actions pre-execution when the law check passes (M1-L4: to an in-memory log; expose veto state to M1 only after deterministic Marketplace law passes.
veto is checked after law, before execution); maintain an audit log of all veto/pause/resume - **Does not now:** perform AI investigation, infer market risk, persist its audit log, or call a
decisions. specialist model.
- **Does-not:** trade (Traders do); execute on-chain (Marketplace does); modify the law script - **Does not conceptually:** trade, legalize an M1-rejected action, detect anomalies directly,
(immutable — M1-L2); detect anomalies directly (SAE does — the Conductor *responds* to SAE modify Marketplace law, or consult the organism's Brain for trade-level decisions.
reports, it doesn't watch raw data); consult the organism's Brain.
## 5. Interface contract ## 5. Interface contract
- `veto_check(action: MarketAction, trader_id) -> { approved | vetoed(reason) }` — called by - `veto_check(action: MarketAction, trader_id) -> { approved | vetoed(reason) }` — called by
@@ -33,16 +56,24 @@ inference wrapper sits alongside the Marketplace.
- `receive_alert(alert: SAEAlert) -> { pause(trader_id) | dismiss | escalate }`. - `receive_alert(alert: SAEAlert) -> { pause(trader_id) | dismiss | escalate }`.
`SAEAlert { trader_id, alert_type, evidence, severity, timestamp }`. `SAEAlert { trader_id, alert_type, evidence, severity, timestamp }`.
- `investigate(trader_id) -> { clear(resume) | veto_pending_actions | restrict(new_limits) }`. - `investigate(trader_id) -> { clear(resume) | veto_pending_actions | restrict(new_limits) }`.
- `decision_log() -> [ConductorDecision]` — full audit trail of all veto/pause/resume/dismiss. - `decision_log() -> [ConductorDecision]` — current in-memory audit trail.
- **SAE/Brain message format compatibility:** the Conductor's incoming alert format is - Target `UncertaintyRegime { regime_id, scope, action_types, assets?, max_uncertainty,
**identical in structure and signature** to Brain messages — SAE reports to the Conductor in max_capital_at_risk?, effective_at, expires_at?, provenance }`.
the same shape it would report to the Brain. This means the Conductor can be swapped for Brain - Target `RiskDirective { directive_id, source, scope, prohibited_trade_types,
oversight without protocol changes (though the stomach normally operates autonomously). uncertainty_ceiling?, budget_delta?, action_id?, effective_at, expires_at?, rationale,
provenance }`. Brain-origin directives enter through the organism boundary; M6 translates
them into restrictions without creating a direct execution path.
- Target `ConductorDecision { decision_id, action_id?, trader_id?, regime_id, decision,
evidence_refs, rationale_digest, reversible, created_at, outcome_ref? }`.
- SAE/Brain semantic compatibility is a target protocol property; cryptographic signature
equivalence is not claimed by V1.
## 6. Dependencies & stubs ## 6. Dependencies & runtime state
- M7 SAE — anomaly reports; *stub:* no alerts (all clear). - M7 SAE — implemented typed alert envelopes; autonomous SAE detection remains open.
- M1 Marketplace — veto check integration; *stub:* always-approve. - M1 Marketplace — implemented one-shot veto consumption after law + wallet checks.
- M5 Traders — pause/resume control; *stub:* print pause/resume. - M5 Traders — implemented pause/resume state target.
- Specialist Conductor inference runtime — open.
- Persistent audit store — open; V1 log is in-memory.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** the Conductor **can veto, but cannot trade** — it has no wallet, no Marketplace - **L1 (C5):** the Conductor **can veto, but cannot trade** — it has no wallet, no Marketplace
@@ -52,30 +83,34 @@ inference wrapper sits alongside the Marketplace.
are rejected before reaching the Conductor — M1-L4). are rejected before reaching the Conductor — M1-L4).
- **L3 (C4):** **pause is reversible** — a paused trader can always be resumed after - **L3 (C4):** **pause is reversible** — a paused trader can always be resumed after
investigation. Pause is a breaker, not a sentence (echoes A2-L3). investigation. Pause is a breaker, not a sentence (echoes A2-L3).
- **L4 (C4):** every Conductor decision is **logged** — vetoes, pauses, resumes, dismissals. - **L4 (C4):** every V1 Conductor decision is appended to the current in-memory log. Persistent,
The audit log is append-only (echoes M1-L2 / S3). tamper-evident audit storage is a future requirement and is not implied by the current list.
- **L5 (C4):** SAE alert format and Brain message format are **structurally identical** — same - **L5 (C4 target):** SAE and Brain oversight should converge on a compatible alert/message
fields, same signatures. The Conductor processes them the same way the Brain would. contract. V1 implements the SAE alert fields used by M6; cryptographic Brain-signature
equivalence is not implemented or verified here.
## 8. Build steps ## 8. Build status
1. Define the Conductor's LLM decision model (specialist-trained; rules are enforced by the 1. **Done:** M7 alert intake and severity-based pause/dismiss behavior.
Marketplace law script and wallet spending limits — the Conductor applies judgment). 2. **Done:** M1 one-shot veto integration after deterministic law.
2. Wire SAE alert intake (M7 → M6). 3. **Done:** Trader pause/resume control.
3. Wire Marketplace veto check (M1 → M6 → approve/veto). 4. **Done:** in-memory decision log for veto/pause/resume/dismiss.
4. Implement trader pause/investigate/resume flow. 5. **Next:** implement/version `UncertaintyRegime` and mechanically reject out-of-regime
5. Implement append-only decision log. Trader actions before execution.
6. **Next:** implement Brain/M0 `RiskDirective` intake for broad prohibitions and exceptional
individual vetoes.
7. **Next:** link every restriction/veto to evidence and later outcome for intervention scoring.
8. **Open:** specialist Conductor inference/investigation.
9. **Open:** persistent/tamper-evident audit storage and escalation protocol.
## 9. Tests ## 9. Tests
Veto: flagged action is vetoed; unflagged action approved. Pause: paused trader cannot submit Current tests verify veto, law-before-veto ordering, severe-alert pause, low-severity dismissal
actions. Resume: cleared trader resumes normal operation. No trading: Conductor cannot submit path, pause blocking M1 actions/prediction reads, resume, and decision logging. There is no
`MarketAction`. Law supremacy: Conductor cannot override a law violation (never reaches specialist-inference or Brain-signature compatibility test because those layers do not exist.
Conductor). Audit: every decision appears in the log. Alert format: SAE alert parses identically
to Brain message structure.
## 10. Open items ## 10. Open items
- Conductor AI model selection and training data (what does "specialist training" look like?). - Formal uncertainty-regime vocabulary and default boundaries by action/asset/regime.
- Veto criteria beyond SAE alerts (does the Conductor have independent judgment, or only - Brain/M0 directive translation and expiry/revocation semantics.
responds to SAE reports?). - Specialist Conductor model/runtime and training/evaluation protocol.
- Escalation path — if the Conductor is uncertain, does it escalate to the organism's Brain? - Judgment inputs beyond explicit M7 alerts.
Or is the stomach fully autonomous? (Current design: fully autonomous.) - Persistent audit and intervention-outcome memory.
- Multiple Conductors for redundancy? - Redundancy/multiple-Conductor design, if needed.
+79 -19
View File
@@ -10,6 +10,29 @@ processes them through the same pathway.
Extends the F2 (SAE monitor) pattern to the economy organ's internal domain. F2 watches Extends the F2 (SAE monitor) pattern to the economy organ's internal domain. F2 watches
subagents at the organism level; M7 watches traders at the stomach level. subagents at the organism level; M7 watches traders at the stomach level.
## 1A. Operational doctrine
- **Purpose:** produce inspectable evidence about unusual, dangerous, compromised, deceptive, or
strategy-incoherent Trader behavior and feed repeated patterns into durable economic memory.
- **Authority:** M7 has detection/reporting authority only. It cannot block, pause, veto, change
limits, declare guilt, or modify Trader behavior.
- **Evidence:** instrumented Trader activity, expected-behavior baselines, regime context, prior
signals, recurrence counts, M6 interpretations, and later realized outcomes.
- **Permitted decisions:** detect deviation, classify signal type, estimate severity/confidence,
count recurrence, assemble evidence references, and emit a signal/alert to M6.
- **Prohibited decisions:** collapse anomaly into guilt, treat rarity as danger automatically,
enforce restrictions, duplicate M1 law, or hide legitimate adaptation because it is unusual.
- **Memory:** recurrence, repeated prediction failures, repeated strategy incoherence, recurring
source/behavior couplings, M6 interpretations, and realized outcomes persist as economic memory.
- **Performance:** measured detection quality by signal class, evidence usefulness, recurrence
sensitivity, false-positive/false-negative rates, and whether legitimate anomalies remain
distinguishable from compromise/danger.
- **Failure:** uninstrumented Trader surfaces, one undifferentiated anomaly score, repeated false
accusations without correction, missed recurrent precursors, or any direct enforcement action.
- **Completion criterion:** trained M7 is complete when observations are instrumented,
features/embeddings are attributable, recurrence is represented, signal classes are separable,
evidence is inspectable, M6/outcome feedback updates memory, and longitudinal error rates are
measured.
## 2. Status / certainty ## 2. Status / certainty
SCAFFOLD · PARTIAL. `core/src/economy/sae.tcl` records Marketplace-level trader calls and SCAFFOLD · PARTIAL. `core/src/economy/sae.tcl` records Marketplace-level trader calls and
constructs alert envelopes consumed by M6. Sparse-autoencoder inference/training remains open. constructs alert envelopes consumed by M6. Sparse-autoencoder inference/training remains open.
@@ -17,36 +40,73 @@ F2 still provides the architectural pattern: watch traders, never the Conductor.
scaffold C2. scaffold C2.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader action embeddings). **Tcl 8.6 observation scaffold** · `core/src/economy/sae.tcl`. V1 records Marketplace tool-call
Shares the architectural pattern with F2 but is a separate instance scoped to the economy organ. events and constructs typed alert envelopes for M6. Sparse-autoencoder embeddings, inference,
training, learned anomaly thresholds, and model persistence remain future work.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** intercept and log **every trader action at the Marketplace level** — the Marketplace - **Does now:** record every Marketplace submission at the single action ingress; preserve Trader,
is the only interface traders can act through, so monitoring it captures everything; embed trader tool, payload/result metadata in the monitor log; construct `SAEAlert` envelopes with Trader,
action sequences; run SAE anomaly detection over action embeddings; flag suspicious patterns alert type, evidence, severity, and timestamp for M6.
(unusual trading frequency, outsized positions, repeated failed actions); report alerts to the Conductor (M6) with evidence; format alerts **identically to Brain messages** (same structure, same signatures). - **Does not now:** embed actions, run a sparse autoencoder, learn anomaly thresholds, or infer
- **Does-not:** block actions directly (Conductor decides); watch the Conductor (the stomach's "homunculus" — echoes F2-L1); correct trader behavior (detection only — F2-L2: no closed elimination loop); trade or access wallets. suspiciousness autonomously.
- **Does not conceptually:** block actions directly, watch the Conductor, correct Trader behavior,
trade, or access wallets. Enforcement remains M6/M1/M4.
## 5. Interface contract ## 5. Interface contract
Implemented Tcl surface:
- `record_tool_call(trader_id, tool, payload, result, timestamp)` — append observation.
- `alert(trader_id, alert_type, evidence, severity, timestamp) -> SAEAlert`.
- `log()` — current in-memory observations.
Target evidence contract:
`AnomalySignal { signal_id, trader_id, signal_type, severity, confidence, recurrence_count,
expected_behavior_ref?, observed_behavior_ref, evidence_refs, regime, first_seen, last_seen }`,
where `signal_type` distinguishes at minimum `deviation`, `danger`, `suspected_compromise`,
`suspected_deception`, `strategy_incoherence`, and `recurrence`.
## 6. Dependencies & stubs Future SAE inference may consume the same observation log, but V1 alerts are explicitly created
- by callers/tests rather than autonomously inferred by a trained sparse autoencoder. M7 signal
records feed M0 durable economic memory; they never directly enforce.
## 6. Dependencies & runtime state
- M1 Marketplace — implemented observation point for action submissions and prediction queries.
- M6 Conductor — implemented alert consumer.
- Trader-action embedding model / trained SAE — absent.
- Persistent observation store — absent; V1 log is in-memory.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** the SAE watches everyone in the orgab. - **L1 (C5 scope):** M7 watches Trader activity at the stomach's Marketplace boundary; it does
- **L2 (C5):** **every tool call is logged** — no trader action escapes monitoring. This is enforced architecturally (tool call interception), not by policy. not watch the Conductor or unrelated organism processes.
- **L2 (C5 within current surface):** every Marketplace submission and Marketplace prediction
query is logged. Future Trader tools must either route through an instrumented boundary or add
equivalent M7 observation before this can truthfully extend to "every tool call."
- **L3 (C4):** **detection only, no enforcement** — the SAE reports to the Conductor; it never blocks, pauses, or modifies trader actions itself. Echoes F2-L2 (no closed elimination loop). - **L3 (C4):** **detection only, no enforcement** — the SAE reports to the Conductor; it never blocks, pauses, or modifies trader actions itself. Echoes F2-L2 (no closed elimination loop).
- **L4 (C4):** **alert format = Brain message format** — structurally identical, same signatures. This is not coincidental; it ensures the Conductor can be supervised by the Brain using the same protocol if the organism ever needs to override stomach autonomy. - **L4 (C4 target):** M7 alert structure should remain compatible with any future Brain oversight
- **L5 (C3):** the SAE model is **trained on normal trader behavior** — anomalies are deviations from the learned normal, not violations of predefined rules (those are the law script's job in M1). protocol. V1 implements the shared semantic fields, not cryptographic signature equivalence.
- **L5 (C3 target):** a future SAE model should learn normal Trader behavior and detect deviations
rather than duplicate M1 law. No trained SAE exists in V1.
## 8. Build steps ## 8. Build status
1. Implement action interception at the Marketplace level (M1). 1. **Done:** Marketplace-level action/prediction-query logging.
2. Define the action embedding scheme (how tool calls are vectorized). 2. **Done:** typed `SAEAlert` envelope with bounded severity.
3. Train the SAE on normal trader behavior (bootstrapped from simulated trading). 3. **Done:** alert delivery path into M6.
4. Implement anomaly scoring and alert threshold. 4. **Next:** implement typed `AnomalySignal` records and recurrence counters.
5. Wire alerts to Conductor (M6) in Brain-compatible message format. 5. **Next:** link M6 interpretation/outcomes back to signals so false positives, false negatives,
and legitimate anomalous adaptations can be measured.
6. **Next:** persist repeated signal patterns into M0 economic memory.
7. **Open:** action embedding scheme.
8. **Open:** SAE training/inference, learned anomaly scoring, and thresholds.
9. **Open:** persistent observation/model state.
## 9. Tests ## 9. Tests
Current M0 tests verify pass/fail Marketplace submissions are logged, severe caller-created alerts
reach M6 and pause the target Trader, and severity is bounded. There is no learned-anomaly test
because no SAE inference exists.
## 10. Open items ## 10. Open items
- Action-sequence embedding representation.
- SAE architecture/training data and evaluation protocol.
- Learned anomaly threshold calibration.
- Persistent observation/model storage.
- Instrumentation contract for any future Trader tools outside the current Marketplace methods.
+71 -24
View File
@@ -6,11 +6,50 @@ design docs (`../gen03_state_of_architecture.md`, `../gen03_body.md`, `../gen03_
`../../src/endocrine/etr/etr_invariants.md`. `../../src/endocrine/etr/etr_invariants.md`.
## How to read a spec ## How to read a spec
Every `NN-<organ>.md` has the same 10 sections: The historical files use the same 10-section skeleton:
1. **Component** · 2. **Status/certainty** · 3. **Language & location** · 4. **Does / does-not** · 1. **Component** · 2. **Status/certainty** · 3. **Language & location** · 4. **Does / does-not** ·
5. **Interface contract** (language-agnostic data shapes — integrate against *this*) · 5. **Interface contract** · 6. **Dependencies/runtime state** · 7. **Invariants/laws** ·
6. **Dependencies & stubs** · 7. **Invariants/laws** (certainty-tagged) · 8. **Build steps** 8. **Build status** · 9. **Tests/verification** · 10. **Open items**.
(invariants-first: laws → tests → fit) · 9. **Tests** (standalone command) · 10. **Open items**.
Active specs may also carry **§1A Operational doctrine / Measurement contract**. This is not
ornament: it states why the component exists and supplies the authority/performance semantics that
the later interface and tests must implement.
## Tight-spec standard
When an existing spec is cleaned or a new one is written, make the following explicit rather than
leaving them implicit in prose:
1. **Purpose** — what outcome the component exists to produce.
2. **Authority** — what it may decide, what may constrain it, and what it can never override.
3. **Evidence** — what information it may consume and what provenance/uncertainty must survive.
4. **Permitted decisions** — concrete state transitions or outputs it owns.
5. **Prohibited decisions** — surfaces it must literally not possess.
6. **Memory** — what repeated evidence becomes durable knowledge, with source observations linked
rather than rewritten.
7. **Performance** — the longitudinal metric by which competence is judged.
8. **Failure condition** — what counts as architectural failure even if a local metric looks good.
9. **Completion test** — the observable evidence required before the spec may claim implementation.
Build steps should be ordered as **contract → invariant → failing test → implementation →
realization/outcome feedback → persistence**, not as a list of aspirational features.
## Economy doctrine
The M-series uses these additional commitments:
- M0's local terminal objective is durable profit; at organism scale surplus is metabolic capacity,
especially compute budget.
- M1 is constitutional law, not strategy.
- M2 preserves evidence/provenance/contradiction and does not decide truth.
- M3 Sims are complementary scopes, not competing oracles; correctness is scope/horizon/regime
conditioned.
- M4 hard ceilings are non-overridable per action.
- M5 Traders are independent agentic economic entities with independently assigned capital.
- Trader competence is diagnosed longitudinally by realized outcome versus its own prediction and
declared uncertainty; P&L remains the local objective.
- M6 owns the big picture: portfolio/system risk, uncertainty regimes, ordinary veto/pause, and
translation of broad/exceptional Brain restrictions into local enforcement.
- M7 reports evidence and recurrence; anomaly is not guilt. M6 interprets.
- Repetition matters everywhere: source reliability, Sim bias, Trader calibration, anomaly
recurrence, and intervention outcomes become durable M0 economic memory.
## Conventions ## Conventions
- **Certainty tags** (from arch doc): C5 ratified · C4 drafted · C3 partial · C2 explored · C1 stub. - **Certainty tags** (from arch doc): C5 ratified · C4 drafted · C3 partial · C2 explored · C1 stub.
@@ -49,21 +88,21 @@ Every `NN-<organ>.md` has the same 10 sections:
| G1 | Stress-loop contract | Cross-cut | C1/C2 | — | _wave 2_ | | G1 | Stress-loop contract | Cross-cut | C1/C2 | — | _wave 2_ |
| G2 | Governance | Cross-cut | DESIGN-FIRST (C2) | TBD | _wave 2_ | | G2 | Governance | Cross-cut | DESIGN-FIRST (C2) | TBD | _wave 2_ |
| G3 | Defense model | Cross-cut | emergent | — | _wave 2_ | | G3 | Defense model | Cross-cut | emergent | — | _wave 2_ |
| M0 | Economy organ hub (stomach) | Economy | DESIGN-FIRST | TBD | [M0](M0-economy-organ-hub.md) | | M0 | Economy organ hub (stomach) | Economy | EXECUTABLE SCAFFOLD | Tcl 8.6 | [M0](M0-economy-organ-hub.md) |
| M1 | Marketplace (multi-trader harness) | Economy | DESIGN-FIRST | TBD | [M1](M1-marketplace.md) | | M1 | Marketplace (multi-trader harness) | Economy | EXECUTABLE SIMULATION | Tcl 8.6 | [M1](M1-marketplace.md) |
| M2 | Data feeds (market data pipeline) | Economy | DESIGN-FIRST | TBD | [M2](M2-data-feeds.md) | | M2 | Data feeds (market data pipeline) | Economy | EXECUTABLE BUFFER/FEED CORE | Tcl 8.6 | [M2](M2-data-feeds.md) |
| M3 | Sims hub (market prediction) | Economy | DESIGN-FIRST | TBD | [M3](M3-sims-hub.md) | | M3 | Sims hub (market prediction) | Economy | MIXED: 4 V1 BRIDGES + 3 NATIVE KERNELS | Tcl + native runtimes | [M3](M3-sims-hub.md) |
| M3a | Statistical & quantitative sims | Economy/Sims | DESIGN-FIRST | TBD | [M3a](M3a-statistical-sims.md) | | M3a | Statistical & quantitative sims | Economy/Sims | V1 IMPLEMENTED + WIRED | R | [M3a](M3a-statistical-sims.md) |
| M3b | Sociological & population sims | Economy/Sims | DESIGN-FIRST | TBD | [M3b](M3b-sociological-sims.md) | | M3b | Sociological & population sims | Economy/Sims | V1 IMPLEMENTED + WIRED | ECLiPSe Prolog | [M3b](M3b-sociological-sims.md) |
| M3c | AMM & liquidity pool sims | Economy/Sims | DESIGN-FIRST | TBD | [M3c](M3c-amm-liquidity-sims.md) | | M3c | AMM & liquidity pool sims | Economy/Sims | V1 IMPLEMENTED + WIRED | Solidity / Foundry | [M3c](M3c-amm-liquidity-sims.md) |
| M3d | MEV & adversarial extraction sims | Economy/Sims | DESIGN-FIRST | TBD | [M3d](M3d-mev-adversarial-sims.md) | | M3d | MEV & adversarial extraction sims | Economy/Sims | NATIVE KERNEL | Fortran 2018 | [M3d](M3d-mev-adversarial-sims.md) |
| M3e | Tokenomics & macro-state sims | Economy/Sims | DESIGN-FIRST | TBD | [M3e](M3e-tokenomics-macro-sims.md) | | M3e | Tokenomics & macro-state sims | Economy/Sims | V1 IMPLEMENTED + WIRED | Fortran 2018 | [M3e](M3e-tokenomics-macro-sims.md) |
| M3f | Consensus & staking game sims | Economy/Sims | DESIGN-FIRST | TBD | [M3f](M3f-consensus-staking-sims.md) | | M3f | Consensus & staking game sims | Economy/Sims | NATIVE KERNEL | ECLiPSe Prolog | [M3f](M3f-consensus-staking-sims.md) |
| M3g | Market microstructure sims | Economy/Sims | DESIGN-FIRST | TBD | [M3g](M3g-market-microstructure-sims.md) | | M3g | Market microstructure sims | Economy/Sims | NATIVE KERNEL | Fortran 2018 | [M3g](M3g-market-microstructure-sims.md) |
| M4 | Wallets (sovereign custody) | Economy | DESIGN-FIRST | TBD | [M4](M4-wallets.md) | | M4 | Wallets (sovereign custody) | Economy | PARTIAL: BINDING + LIMITS ONLY | Tcl 8.6 | [M4](M4-wallets.md) |
| M5 | Traders (AI actors) | Economy | DESIGN-FIRST | TBD | [M5](M5-traders.md) | | M5 | Traders (AI actors) | Economy | PARTIAL: REGISTRY + PAUSE STATE | Tcl 8.6 | [M5](M5-traders.md) |
| M6 | Conductor (supervisory AI) | Economy | DESIGN-FIRST | TBD | [M6](M6-conductor.md) | | M6 | Conductor (supervisory AI) | Economy | EXECUTABLE SUPERVISION SCAFFOLD | Tcl 8.6 | [M6](M6-conductor.md) |
| M7 | SAE monitor (trader surveillance) | Economy | DESIGN-FIRST | TBD | [M7](M7-sae-monitor.md) | | M7 | SAE monitor (trader surveillance) | Economy | PARTIAL: LOGGING + ALERT ENVELOPES | Tcl 8.6 | [M7](M7-sae-monitor.md) |
## Integration DAG (who feeds whom) ## Integration DAG (who feeds whom)
``` ```
@@ -78,14 +117,22 @@ Hermes ──> [C1] ──> Inference cycle [C3] ──┬─ pulls Drive-Box sn
SAE [F2] watches Subagents [F3]; stress-loop [G1]: F2 → A7 (EthInt) → stress endomotiv (A4) → A8 drift + full reshuffle (B2) SAE [F2] watches Subagents [F3]; stress-loop [G1]: F2 → A7 (EthInt) → stress endomotiv (A4) → A8 drift + full reshuffle (B2)
Storage: INVARIANT [E1] / VARIANT [E2] / RAG+cross-store [E3] sit behind D1. Medium [D2] = the perfusion bus (unnamed). Storage: INVARIANT [E1] / VARIANT [E2] / RAG+cross-store [E3] sit behind D1. Medium [D2] = the perfusion bus (unnamed).
Economy (stomach — independent, scoped autonomy): Economy (stomach — independent, scoped autonomy):
Marketplace [M1] ← Traders [M5] (bound to Wallets [M4]) submit actions; law script + Conductor [M6] veto gate execution. Local objective: durable profit → organism metabolic/compute surplus.
Data Feeds [M2] ↔ Sims [M3: M3a stat, M3b socio, M3c AMM, M3d MEV, M3e tokenomics, M3f consensus, M3g microstructure]. Marketplace [M1] ← Traders [M5] (independent assigned capital; Wallets [M4]) submit actions;
SAE [M7] monitors all Trader tool calls → alerts Conductor [M6]. Tax → Verschwörern Veregeister wallets (stub). constitutional law + absolute wallet ceilings + Conductor [M6] uncertainty/veto boundaries gate execution.
Stomach [M0] ↔ organism via Ichor; reward signals TBD. Data Feeds [M2] → Sims [M3]. Runtime bridges are live for M3a stat, M3b socio, M3c AMM,
and M3e tokenomics; M3d MEV, M3f consensus, and M3g microstructure are native kernels
registered in the hub but not yet process-bridged into automatic query/publish paths.
SAE [M7] records Marketplace-level Trader calls → alert envelopes → Conductor [M6].
Tax is staged only; no wallet transfer occurs.
Stomach [M0] has an Ada-bound secretion contract; the Pony↔Tcl runtime bridge to Ichor is open.
``` ```
## Build waves ## Build waves
- **Wave 0** — this README + **C1** (priority). - **Wave 0** — this README + **C1** (priority).
- **Wave 1 (buildable-now)** — A1–A8, B1–B3, C2–C4, D1, D3. - **Wave 1 (buildable-now)** — A1–A8, B1–B3, C2–C4, D1, D3.
- **Wave 2 (design-first)** — D2, E1–E3, F1–F3, G1–G3, M0–M7 (+ M3a–M3g sim sub-specs). - **Wave 2 (design-first)** — D2, E1–E3, F1–F3, G1–G3.
- **Economy track (active implementation)** — M0–M7 plus M3a–M3g. M3a/M3b/M3c/M3e have V1
native runtime bridges; M3d/M3f/M3g remain native kernel implementations; M4/M5/M7 remain
partial by design because custody, agent inference, and SAE inference are not implemented.
Each spec is independent; review as they land. Each spec is independent; review as they land.
+15 -2
View File
@@ -10,13 +10,26 @@ Local guide for `core/src/economy`. The design source of truth is `core/docs/pla
- M4 wallet brakes are independent of M1/M6. Keep 1:1 trader↔wallet binding literal. - M4 wallet brakes are independent of M1/M6. Keep 1:1 trader↔wallet binding literal.
- M7 observes and reports. Enforcement belongs to M6/M1/M4, not the monitor. - M7 observes and reports. Enforcement belongs to M6/M1/M4, not the monitor.
- Live key custody and chain broadcast are intentionally absent until the M4 key-storage specification is ratified. Do not smuggle them in as convenience helpers. - Live key custody and chain broadcast are intentionally absent until the M4 key-storage specification is ratified. Do not smuggle them in as convenience helpers.
- Registry/source presence is **not** runtime wiring. M3a/M3b/M3c/M3e have tested native query
bridges; M3d/M3f/M3g do not yet.
- The M3 horizon clock is live, but it does not yet dispatch/refresh all native engines
automatically. Do not document or code-review it as continuous native execution until that loop
exists and has an explicit test.
- M5 identity state is not Trader inference, M6 veto state is not Conductor inference, and M7
logging is not SAE inference. Keep those boundaries literal.
## Build/test ## Build/test
Tcl 8.6, standard library only: Tcl 8.6 orchestration, plus native simulator runtimes:
```sh ```sh
tclsh core/src/economy/tests/stomach.test tclsh core/src/economy/tests/stomach.test
tclsh core/src/economy/sims/tests/hub_runtime.test
tclsh core/src/economy/sims/run_tests.tcl
``` ```
Use test-first changes. Keep `stomach.tcl` as composition/facade; put component behavior in the M1–M7 module that owns it. Dedicated CI owns the end-to-end native boundary for M3a, M3b, M3c, and M3e. Fortran kernels are
compiled under `-std=f2018 -Wall -Wextra -Werror -pedantic`.
Use test-first changes for behavior. Keep `stomach.tcl` as composition/facade; put component
behavior in the M1–M7 module or M3 native runner that owns it.
+55 -5
View File
@@ -1,6 +1,56 @@
Brief overview # Economy organ — concise orientation
3 small models act as traders The stomach is an outer, scoped-autonomous economic organ.
they connect to a shared ada hub, each with a unique ID that correlates to a wallet. The ada hub verifies with the wallet that a transaction is legal, and then uses interop Fortran to sign the transaction, which then is sent to the market, which checks an additional legality set.
Traders also consult the Marketplace directly for information that is compiled from: Live feeds; KOL; Simulations; Live ticker feeds; and other sources TBD. Its local terminal objective is **durable profit**. At organism scale that surplus is metabolic
THE MARKETPLACE then performs the trade to market. capacity: capital that can further the organism, especially its compute budget.
## Authority
- Traders (M5) make local economic decisions using independently assigned capital.
- Marketplace (M1) is constitutional law and the single action harness. It does not choose strategy.
- Wallets (M4) impose non-overridable hard capital ceilings. V1 has no private keys or signer.
- Conductor (M6) owns the big picture: portfolio/system risk, uncertainty regimes, ordinary
veto/pause/restriction, and translation of broad or exceptional Brain directives.
- SAE monitor (M7) produces anomaly evidence and recurrence signals. It does not enforce.
- Brain may broadly prohibit trade types or risk posture and may exceptionally veto an individual
action, but it does not bypass M1/M4/M6.
## Evidence and prediction
M2 preserves observations, provenance, timestamps, source confidence, and contradiction. It does
not decide what is true.
M3 Sims are complementary scopes, not competing oracles. M3a statistical, M3b sociological,
M3c AMM/liquidity, and M3e tokenomics/macro have tested native runtime bridges today.
M3d MEV/adversarial, M3f consensus/staking, and M3g microstructure have native kernels but still
need equivalent Tcl query bridges.
Correctness is always scoped to target, horizon, conditioning, and regime. Repeated prediction
error becomes durable economic memory rather than being flattened into a universal Sim ranking.
## Trader performance
P&L is the Trader's local objective. The primary diagnostic is longitudinal realized loss relative
to that Trader's own prediction and declared uncertainty. A correctly anticipated loss is not the
same failure as a confident surprise loss.
Traders do not need consensus with one another; their funding stores are independent. Conductor
intervenes when local behavior creates organ-level risk or violates the active uncertainty regime.
## Memory
The stomach must persist repeated evidence about source reliability, Sim bias, Trader calibration,
regime behavior, protocol precursors, anomaly recurrence, and intervention outcomes. Derived
assessments link back to source observations; they never rewrite raw evidence.
## Current execution boundary
Current successful Marketplace execution is simulation-only and returns `simtx-*` receipts.
There is no live key custody, signing, RPC broadcast, or real tax transfer in V1.
Target live path remains:
`Trader → Marketplace law → M4 hard brake → M6 restriction/veto → authorized signer/broadcaster`
Every future live implementation must preserve that ordering.
+30 -4
View File
@@ -1,6 +1,8 @@
# Economy organ — M0 stomach # Economy organ — M0 stomach
Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organism-facing product is an Ada-bound `organ_secretion`; it never joins the inner bus. Executable M0–M7 economy scaffold. The stomach is an OUTER organ: its organism-facing contract is
an Ada-bound `organ_secretion`; it never joins the inner bus. Native simulation runtime is
currently end-to-end for M3a/M3b/M3c/M3e and kernel-only for M3d/M3f/M3g.
## Implemented now ## Implemented now
@@ -23,16 +25,40 @@ tclsh core/src/economy/tests/stomach.test
Expected: `Total 17 Passed 17 ... Failed 0` once the current branch is checked out. Expected: `Total 17 Passed 17 ... Failed 0` once the current branch is checked out.
The simulator family also has its own polyglot driver: The simulator family also has its own polyglot native-test driver. This verifies locally
available native kernels; it does not imply that every engine has a Tcl query bridge:
```sh ```sh
tclsh core/src/economy/sims/run_tests.tcl tclsh core/src/economy/sims/run_tests.tcl
``` ```
It executes Tcl + every native suite whose runtime is installed. Use `--strict` to make missing R/ECLiPSe/Foundry runtimes a failure rather than an explicit skip. It executes hub/runtime tests plus every native suite whose runtime is installed. Use `--strict`
to make missing external runtimes a failure rather than an explicit skip. Dedicated GitHub
Actions workflows additionally verify the M2→native→Hub integration boundaries for M3a, M3b,
M3c, and M3e. M3d/M3f/M3g still need equivalent facade/query bridges.
## Public scaffold API ## Public scaffold API
`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `statistical_runner_available`, `statistical_query`, `statistical_from_feed`, `amm_runner_available`, `amm_from_feed`, `sociological_runner_available`, `sociological_from_feed`, `tokenomics_runner_available`, `tokenomics_from_feed`, `sim_engines`, `sim_engine_status`, `sim_horizons`, `sim_running`, `sim_advance`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`. `::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `statistical_runner_available`, `statistical_query`, `statistical_from_feed`, `amm_runner_available`, `amm_from_feed`, `sociological_runner_available`, `sociological_from_feed`, `tokenomics_runner_available`, `tokenomics_from_feed`, `sim_engines`, `sim_engine_status`, `sim_horizons`, `sim_running`, `sim_advance`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`.
`secretion` returns the envelope-compatible metadata `source stomach`, `destination ada_border`, `provenance organ_secretion`. The runtime Pony↔Tcl bridge is still an integration task; no code may shortcut D1 while that bridge is built. `secretion` returns envelope-compatible metadata `source stomach`, `destination ada_border`,
`provenance organ_secretion`. This is a contract/staging surface today: the Pony↔Tcl runtime
bridge is still an integration task. No code may shortcut D1 while that bridge is built.
## Runtime truth table
| Surface | Current state |
|---|---|
| M3a statistical | V1 native R bridge, M2 calibrated, Hub published |
| M3b sociological | V1 native ECLiPSe bridge, persistent populations, Hub published |
| M3c AMM/liquidity | V1 read-only Solidity bridge, M2 calibrated, Hub published |
| M3d MEV/adversarial | native Fortran kernel/tests; facade bridge open |
| M3e tokenomics/macro | V1 native Fortran query bridge, Kalman calibrated, Hub published |
| M3f consensus/staking | native ECLiPSe kernel/tests; facade bridge open |
| M3g microstructure | native Fortran kernel/tests; facade bridge open |
| M4 custody/signing | absent; binding + exposure brakes only |
| M5 Trader inference | absent; identity/specialization/pause state only |
| M6 Conductor inference | absent; deterministic veto/pause/alert handling only |
| M7 SAE inference | absent; Marketplace logging + alert envelopes only |
| live chain broadcast | deliberately absent |
| Pony↔Tcl Ichor bridge | open |
+16 -11
View File
@@ -1,18 +1,23 @@
# M3 simulator family # M3 simulator family
Seven native simulator engines live here behind the Tcl M3 hub. Seven native simulator engines live here behind the Tcl M3 hub. **Native source presence is not
the same thing as runtime integration.** The current state is:
| ID | Engine | Native language | Implemented kernel | | ID | Engine | Native language | Native implementation | Tcl/M3 runtime bridge |
|---|---|---|---| |---|---|---|---|---|
| M3a | statistical | R | V1 complete: GBM/Merton/Heston, CF option calibration, GARCH, HMM/Viterbi, fitted rough vol, DCC+t-copula, Bayesian+ARIMA, VaR/ES, empirical scoring, 7 typed predictions, price+DEX-pool calibration | | M3a | statistical | R | V1 complete: GBM/Merton/Heston, CF calibration, GARCH, HMM/Viterbi, rough vol, DCC+t-copula, Bayesian+ARIMA, VaR/ES, 7 predictions | **wired + CI verified** |
| M3b | sociological | ECLiPSe Prolog | V1 complete: 5 archetypes, replicator + UCB learning, adaptive HK, complex contagion, HJB/FP MFG, pump/dump ABM, 9 bounded predictions, persistent populations, empirical scoring | | M3b | sociological | ECLiPSe Prolog | V1 complete: 5 archetypes, UCB/replicator, adaptive HK, contagion, HJB/FP MFG, pump/dump, 9 predictions | **wired + CI verified** |
| M3c | AMM/liquidity | Solidity + Foundry | V1 complete: x*y=k, IL/slippage, concentrated positions, LP/JIT strategies, backrun/sandwich pops, two-pool routing, 5 bounded predictions, price+pool calibration | | M3c | AMM/liquidity | Solidity + Foundry | V1 complete: x*y=k, concentrated positions, LP/JIT, backrun/sandwich, 2-pool routing, 5 predictions | **wired + CI verified** |
| M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | | M3d | MEV/adversarial | Fortran 2018 | PGA, block knapsack, cross-chain paths, sandwich scoring | **open** |
| M3e | tokenomics/macro | Fortran 2018 | V1 complete: conserved token state, Euler-Maruyama, Kalman calibration, halving/burn policy, kinked lending, liquidation cascades, directional VAR contagion, exact yield optimizer, 10 bounded predictions | | M3e | tokenomics/macro | Fortran 2018 | V1 complete: conserved state, SDE, Kalman, policy, lending/cascade, VAR contagion, exact yield optimizer, 10 predictions | **wired + CI verified** |
| M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | | M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | **open** |
| M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit | | M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit | **open** |
`registry.tcl` is the canonical engine inventory. `scheduler.tcl` is the live six-horizon wall→sim clock. It starts at 90 simulated seconds per wall second for tick/hourly and accelerates the longer horizons according to the M3 spec. `registry.tcl` is the canonical engine inventory. `scheduler.tcl` is the live six-horizon
wall→sim clock. It starts at 90 simulated seconds per wall second for tick/hourly and accelerates
longer horizons according to the M3 spec. The clock does **not yet dispatch every native engine**:
M3a/M3b/M3c/M3e execute when their calibrated facade query is called; scheduler-driven automatic
refresh is still an M3 hub task.
Run all locally available native tests: Run all locally available native tests:
+7 -4
View File
@@ -24,8 +24,10 @@ the `Barrier` first (**L2**); every envelope carries **provenance** (**L3**).
- `broker.pony` — the outer `Broker` (register + route; forces Ada-bound traffic - `broker.pony` — the outer `Broker` (register + route; forces Ada-bound traffic
through the barrier). through the barrier).
- `organ.pony` — `OrganReceiver` interface + a `StubOrgan` for tests. - `organ.pony` — `OrganReceiver` interface + a `StubOrgan` for tests.
- `main.pony` — smoke wiring: stomach digests → inbound to Ada (admitted); raw - `main.pony` — **transport smoke stub**, not the executable economy runtime: stomach-shaped
external → Ada (rejected); outer organ→organ (direct). test traffic → Ada (admitted); raw external → Ada (rejected); outer organ→organ (direct).
The real M0 Tcl/polyglot economy facade lives under `core/src/economy/` and is not yet bridged
into this Pony process.
- `ichor_ada_shim.c` — **STUB** C/Fortran seam to the Ada border (not yet wired). - `ichor_ada_shim.c` — **STUB** C/Fortran seam to the Ada border (not yet wired).
## Build / run ## Build / run
@@ -40,5 +42,6 @@ is ephemeral; toolchain is per-session, reinstalled by the SessionStart hook).
## Status ## Status
Provisional **outer-bus** scaffold — compiles and runs. The `Barrier` is a Provisional **outer-bus** scaffold — compiles and runs. The `Barrier` is a
**stand-in**, not the real safety screen; the real screen is Ada `Trust_Guard` **stand-in**, not the real safety screen; the real screen is Ada `Trust_Guard`
+ the E1 invariant laws, reached over the seam (transport TBD — IPC vs in-proc + the E1 invariant laws. Two runtime seams remain explicit: Pony↔Ada for the real D1 screen, and
is an open decision). Nothing here reaches the inner brain directly. Pony↔Tcl for the executable M0 economy facade. IPC vs in-process/FFI transport is still open.
Nothing here reaches the inner brain directly.
+3 -3
View File
@@ -41,9 +41,9 @@ organs:
build: "src/endocrine/run_tests.sh ; src/endocrine/etr/run_etr_tests.sh" build: "src/endocrine/run_tests.sh ; src/endocrine/etr/run_etr_tests.sh"
- path: core/src/economy - path: core/src/economy
agents_md: core/src/economy/AGENTS.md agents_md: core/src/economy/AGENTS.md
lang: tcl lang: [tcl, r, eclipse_prolog, solidity, fortran]
role: M0 stomach/economy organ scaffold — M1–M7 simulation and Ada-bound secretion role: M0 stomach/economy outer-organ scaffold — M1–M7; M3a/b/c/e runtime-wired; M3d/f/g native kernels; Ada-bound secretion contract
build: "tclsh core/src/economy/tests/stomach.test" build: "tclsh core/src/economy/tests/stomach.test ; tclsh core/src/economy/sims/tests/hub_runtime.test ; tclsh core/src/economy/sims/run_tests.tcl"
- path: core - path: core
agents_md: core/AGENTS.md agents_md: core/AGENTS.md
lang: [ada, cobol] lang: [ada, cobol]