Merge pull request #16 from SHOGGOTH-SECTOR/claude/economy-organ-analysis-spec-y4d2sh

Economy organ spec review: data flow, toolchains, corrections
This commit is contained in:
2026-07-17 18:55:33 -07:00
committed by GitHub
11 changed files with 204 additions and 188 deletions
+79 -36
View File
@@ -1,21 +1,18 @@
#!/bin/bash #!/bin/bash
set -euo pipefail
# SessionStart hook — install the polyglot build toolchains for this repo. # SessionStart hook — install the polyglot build toolchains for this repo.
# #
# Claude Code on the web runs in an ephemeral container: anything installed # Claude Code on the web runs in an ephemeral container: anything installed
# outside the cached project tree vanishes on restart. This hook reinstalls the # outside the cached project tree vanishes on restart. This hook reinstalls the
# toolchains the project depends on at the start of every session: # toolchains the project depends on at the start of every session.
# * GNAT + gprbuild + GnuCOBOL (apt: gnat gprbuild gnucobol)
# * Pony (ponyc) via ponyup
# * Alire (alr) 2.1.1 (prebuilt release zip)
# #
# Design rules: # Design rules:
# * IDEMPOTENT — each tool is skipped if it is already on PATH (command -v). # * IDEMPOTENT — each tool is skipped if it is already on PATH (command -v).
# * NON-FATAL — a failed download/install must NOT break the session. We never # * HARD FAIL — if an install fails, the session cannot build. Stop.
# run `set -e`; every step is guarded and the script always exits 0.
# * Warnings (not errors) are logged so failures are visible in the session log.
log() { echo "[install-toolchains] $*"; } log() { echo "[install-toolchains] $*"; }
warn() { echo "[install-toolchains] WARNING: $*" >&2; } die() { echo "[install-toolchains] FATAL: $*" >&2; exit 1; }
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
@@ -26,9 +23,7 @@ if command -v gnatmake >/dev/null 2>&1 && command -v cobc >/dev/null 2>&1; then
log "GNAT/gprbuild/GnuCOBOL already present; skipping apt install." log "GNAT/gprbuild/GnuCOBOL already present; skipping apt install."
else else
log "Installing gnat gprbuild gnucobol via apt-get ..." log "Installing gnat gprbuild gnucobol via apt-get ..."
if ! sudo apt-get install -y gnat gprbuild gnucobol; then sudo apt-get install -y gnat gprbuild gnucobol || die "apt-get install of gnat/gprbuild/gnucobol failed."
warn "apt-get install of gnat/gprbuild/gnucobol failed; continuing."
fi
fi fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -38,13 +33,8 @@ if command -v ponyc >/dev/null 2>&1; then
log "ponyc already present; skipping ponyup install." log "ponyc already present; skipping ponyup install."
else else
log "Installing ponyc via ponyup ..." log "Installing ponyc via ponyup ..."
if sh -c "$(curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/ponylang/ponyup/latest-release/ponyup-init.sh)"; then sh -c "$(curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/ponylang/ponyup/latest-release/ponyup-init.sh)" || die "ponyup-init.sh failed."
if ! /root/.local/share/ponyup/bin/ponyup update ponyc release; then /root/.local/share/ponyup/bin/ponyup update ponyc release || die "ponyup update ponyc release failed."
warn "ponyup update ponyc release failed; continuing."
fi
else
warn "ponyup-init.sh download/run failed; continuing."
fi
fi fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -54,28 +44,81 @@ if command -v alr >/dev/null 2>&1; then
log "alr already present; skipping Alire install." log "alr already present; skipping Alire install."
else else
log "Installing Alire (alr) 2.1.1 ..." log "Installing Alire (alr) 2.1.1 ..."
if curl -sSL -o /tmp/alr.zip https://github.com/alire-project/alire/releases/download/v2.1.1/alr-2.1.1-bin-x86_64-linux.zip; then curl -sSL -o /tmp/alr.zip https://github.com/alire-project/alire/releases/download/v2.1.1/alr-2.1.1-bin-x86_64-linux.zip || die "Alire download failed."
if ( cd /tmp && unzip -o -q alr.zip && sudo cp bin/alr /usr/local/bin/alr && chmod +x /usr/local/bin/alr ); then ( cd /tmp && unzip -o -q alr.zip && sudo cp bin/alr /usr/local/bin/alr && chmod +x /usr/local/bin/alr ) || die "Alire unzip/copy failed."
log "alr installed to /usr/local/bin/alr" log "alr installed to /usr/local/bin/alr"
else
warn "Alire unzip/copy failed; continuing."
fi
else
warn "Alire download failed; continuing."
fi
fi fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Ensure ponyc is on PATH for future shells. # Fortran 2018 (gfortran) + OpenBLAS (economy organ: M3d, M3e)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
PONY_PATH_LINE='export PATH=/root/.local/share/ponyup/bin:$PATH' if command -v gfortran >/dev/null 2>&1; then
if [ -f "$HOME/.bashrc" ] && grep -qF "$PONY_PATH_LINE" "$HOME/.bashrc"; then log "gfortran already present; skipping."
log "ponyup PATH line already in ~/.bashrc; skipping."
else else
log "Appending ponyup PATH line to ~/.bashrc" log "Installing gfortran libopenblas-dev via apt-get ..."
echo "$PONY_PATH_LINE" >> "$HOME/.bashrc" || warn "Could not append to ~/.bashrc; continuing." sudo apt-get install -y gfortran libopenblas-dev || die "apt-get install of gfortran/libopenblas-dev failed."
fi
# ---------------------------------------------------------------------------
# fpm — Fortran Package Manager (economy organ: M3d, M3e)
# ---------------------------------------------------------------------------
if command -v fpm >/dev/null 2>&1; then
log "fpm already present; skipping."
else
log "Installing fpm ..."
FPM_URL="https://github.com/fortran-lang/fpm/releases/download/v0.10.1/fpm-0.10.1-linux-x86_64"
curl -sSL -o /tmp/fpm "$FPM_URL" || die "fpm download failed."
sudo cp /tmp/fpm /usr/local/bin/fpm && sudo chmod +x /usr/local/bin/fpm || die "fpm install failed."
log "fpm installed to /usr/local/bin/fpm"
fi
# ---------------------------------------------------------------------------
# Tcl (economy organ: M3 sim hub)
# ---------------------------------------------------------------------------
if command -v tclsh >/dev/null 2>&1; then
log "tclsh already present; skipping."
else
log "Installing tcl via apt-get ..."
sudo apt-get install -y tcl || die "apt-get install of tcl failed."
fi
# ---------------------------------------------------------------------------
# ECLiPSe Prolog (economy organ: M3b, M3f)
# ---------------------------------------------------------------------------
if command -v eclipse >/dev/null 2>&1 || [ -x /opt/eclipseclp/bin/x86_64_linux/eclipse ]; then
log "ECLiPSe Prolog already present; skipping."
else
log "Installing ECLiPSe Prolog ..."
ECLIPSE_URL="https://eclipseclp.org/Distribution/Current/7.1_13/x86_64_linux/eclipse_basic.tgz"
curl -sSL -o /tmp/eclipse_basic.tgz "$ECLIPSE_URL" || die "ECLiPSe download failed."
sudo mkdir -p /opt/eclipseclp || die "Could not create /opt/eclipseclp."
sudo tar -xzf /tmp/eclipse_basic.tgz -C /opt/eclipseclp || die "ECLiPSe extraction failed."
log "ECLiPSe installed to /opt/eclipseclp"
fi
# --------------------------------------------------------------------------- ---------------------------------------------------------------------------
# Solidity / Foundry (economy organ: M3c)
# ---------------------------------------------------------------------------
# if command -v forge >/dev/null 2>&1; then
# log "forge (Foundry) already present; skipping."
# else
# log "Installing Foundry (forge, anvil) ..."
# curl -sSL https://foundry.paradigm.xyz | bash || die "Foundry install script failed."
# "$HOME/.foundry/bin/foundryup" || die "foundryup failed."
# log "Foundry installed"
# fi
# ---------------------------------------------------------------------------
# PATH for tools not in standard locations.
# ---------------------------------------------------------------------------
EXTRA_PATHS='/root/.local/share/ponyup/bin:/opt/eclipseclp/bin/x86_64_linux'
FOUNDRY_PATH="$HOME/.foundry/bin"
FULL_PATH_LINE="export PATH=$EXTRA_PATHS:$FOUNDRY_PATH:\$PATH"
if [ -f "$HOME/.bashrc" ] && grep -qF "eclipseclp" "$HOME/.bashrc"; then
log "Toolchain PATH lines already in ~/.bashrc; skipping."
else
log "Appending toolchain PATH lines to ~/.bashrc"
echo "$FULL_PATH_LINE" >> "$HOME/.bashrc" || die "Could not append to ~/.bashrc."
fi fi
log "Done." log "Done."
# Never fail the session, regardless of what happened above.
exit 0
+4
View File
@@ -27,6 +27,10 @@ signing (M4), and the Conductor (M6). Deterministic law script must be auditable
Diagnostic reasons (law violation, veto, missing wallet) are internal — routed to Conductor Diagnostic reasons (law violation, veto, missing wallet) are internal — routed to Conductor
(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
predictions through the Marketplace. Predictions are published continuously by the sim hub
(M3) via M2 Data Feeds. The Marketplace holds the latest predictions from each sim type.
Traders see individual sim results (not aggregated) and decide how to weight them.
- `law_check(action: MarketAction) -> { pass | violation(rule_id, reason) }` — deterministic, - `law_check(action: MarketAction) -> { pass | violation(rule_id, reason) }` — deterministic,
pure function. The law script is loaded at startup and **immutable at runtime** (mirrors S3 / pure function. The law script is loaded at startup and **immutable at runtime** (mirrors S3 /
the COBOL vault pattern). the COBOL vault pattern).
+32 -20
View File
@@ -3,9 +3,10 @@
## 1. Component ## 1. Component
The economy organ's prediction engine: **always-running simulations** ("Sims") populated by The economy organ's prediction engine: **always-running simulations** ("Sims") populated by
autonomous simulation agents ("Pops") that model market dynamics across multiple mathematical autonomous simulation agents ("Pops") that model market dynamics across multiple mathematical
domains and time scales. Sims are **queryable at any time** by Traders (M5) — they produce domains and time scales. Sims produce raw simulation data; the hub transforms it into
**predictions with explicit upper and lower bounds** on every output value. This is the hub spec; **predictions with explicit upper and lower bounds** and publishes them continuously to the
individual sim types have dedicated sub-specs (M3a–M3g). Marketplace via M2 Data Feeds. Traders query predictions from the Marketplace (M1), not from the
hub directly. This is the hub spec; individual sim types have dedicated sub-specs (M3a–M3g).
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].
@@ -22,12 +23,13 @@ stdin/stdout JSON — **Fortran** (M3d, M3e), **Prolog** (M3b, M3f), **R** (M3a)
sub-processes it orchestrates. sub-processes it orchestrates.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** tick-advance continuously at **90:1** (1 wall-second = 90 simulated seconds) - **Does:** tick-advance continuously at **90:1** (90 simulated seconds = 1 wall-second)
across **six concurrent time horizons** — tick/hourly, daily, weekly, monthly, annual, and across **six concurrent time horizons** — tick/hourly, daily, weekly, monthly, annual, and
5-year forecast windows; every tick advances every sim; maintain populations of Pops whose 5-year forecast windows; every tick advances every sim; maintain populations of Pops whose
behaviors emerge from the sim's mathematical model; ingest live data from Data Feeds (M2) behaviors emerge from the sim's mathematical model; ingest live data from Data Feeds (M2)
for calibration; respond to Trader queries with bounded predictions; produce outputs with for calibration; transform raw sim data into bounded predictions and publish them continuously
**explicit upper/lower bounds** on every prediction value. to the Marketplace via M2; produce outputs with **explicit upper/lower bounds** on every
prediction value.
| Horizon | Window | Tick step | Effective ratio | Wall time for window | | Horizon | Window | Tick step | Effective ratio | Wall time for window |
|---------|--------|-----------|-----------------|---------------------| |---------|--------|-----------|-----------------|---------------------|
| Tick–hourly | Next 1–60 min | 1s | 90:1 | ~40s | | Tick–hourly | Next 1–60 min | 1s | 90:1 | ~40s |
@@ -37,27 +39,35 @@ sub-processes it orchestrates.
| Annual | Next 365d | ~2.5 hr | ~788,000:1 | ~40s | | Annual | Next 365d | ~2.5 hr | ~788,000:1 | ~40s |
| 5-year | Next 1825d | 12 hr | ~3,942,000:1 | ~40s | | 5-year | Next 1825d | 12 hr | ~3,942,000:1 | ~40s |
- **Does-not:** trade (Traders/Marketplace do); make decisions for traders (it informs, they - **Does-not:** trade (Traders/Marketplace do); make decisions for traders (it informs, they
decide); enforce laws (Marketplace does); supervise behavior (Conductor/SAE do); skip ticks; decide); enforce laws (Marketplace does); supervise behavior (Conductor/SAE do); receive
run slower than 90:1. trader queries (traders query the Marketplace); skip ticks; run slower than 90:1.
## 5. Interface contract ## 5. Interface contract
- `query(sim_type: SimType, query: PredictionQuery) -> BoundedPrediction`. - `publish(sim_type: SimType, prediction: BoundedPrediction)` — the hub continuously transforms
raw sim data into predictions and publishes them to the Marketplace via M2 Data Feeds. This is
a constant stream, not on-demand. Traders query predictions from the Marketplace (M1), not from
the sim hub.
`SimType` ∈ { `statistical`, `sociological`, `amm_liquidity`, `mev_adversarial`, `SimType` ∈ { `statistical`, `sociological`, `amm_liquidity`, `mev_adversarial`,
`tokenomics_macro`, `consensus_staking`, `market_microstructure` } (M3a–M3g). `tokenomics_macro`, `consensus_staking`, `market_microstructure` } (M3a–M3g).
- `BoundedPrediction { value, lower_bound, upper_bound, confidence, time_horizon, sim_type, timestamp }`. - `BoundedPrediction { value, lower_bound, upper_bound, confidence, correctness, certainty,
time_horizon, sim_type, timestamp }`.
Every output is bounded — no point estimates without uncertainty ranges. Every output is bounded — no point estimates without uncertainty ranges.
`confidence` ∈ [0.00, 10.00] — printed as `7.62/10.00`. Gain rates print as Three quality metrics, each ∈ [0.00, 10.00]:
`lower - value - upper / 10.00` (e.g. `2.31 - 4.44 - 7.11 / 10.00 gain over next 30 days`); **confidence** — how sure the model is of this prediction;
**correctness** — how accurate the model has been historically;
**certainty** — how stable the estimate is across perturbations.
Gain rates print as `lower - value - upper / 10.00`
(e.g. `2.31 - 4.44 - 7.11 / 10.00 gain over next 30 days`);
the denominator aids legibility — gain is not capped at 10.00. the denominator aids legibility — gain is not capped at 10.00.
Example: `{ value: 7.2, lower_bound: 5.8, upper_bound: 8.9, confidence: 7.30, Example: `{ value: 7.2, lower_bound: 5.8, upper_bound: 8.9, confidence: 7.30,
time_horizon: "4h", sim_type: "amm_liquidity" }`. correctness: 8.10, certainty: 6.50, time_horizon: "4h", sim_type: "amm_liquidity" }`.
- `status(sim_type?) -> { running, pop_count, last_calibration, data_freshness }` — health check. - `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 - `calibrate(sim_type, feed_data: [NormalizedDatum])` — Data Feeds (M2) pushes live data for
model recalibration. model recalibration.
## 6. Dependencies & stubs ## 6. Dependencies & stubs
- M2 Data Feeds — calibration data source; *stub:* canned market data. - M2 Data Feeds — calibration data source; *stub:* canned market data.
- M5 Traders — query consumers; *stub:* canned queries. - M1 Marketplace — prediction consumer (via M2); *stub:* print predictions.
- M3a–M3g sub-specs — individual sim implementations; *stub:* each returns fixed predictions. - M3a–M3g sub-specs — individual sim implementations; *stub:* each returns fixed predictions.
## 7. Invariants / laws ## 7. Invariants / laws
@@ -70,24 +80,26 @@ sub-processes it orchestrates.
steps and update less frequently. Each horizon completes its forecast window in **~40s wall steps and update less frequently. Each horizon completes its forecast window in **~40s wall
time**. Each horizon runs **in parallel** — they are concurrent, not sequential. No horizon time**. Each horizon runs **in parallel** — they are concurrent, not sequential. No horizon
runs slower than 90:1. runs slower than 90:1.
- **L4 (C4):** sims are **read-only from traders' perspective** — a query never mutates sim - **L4 (C4):** sims are **read-only from traders' perspective** — traders consume predictions
state. Calibration happens only from Data Feeds (M2). from the Marketplace; they cannot mutate sim state. Calibration happens only from Data Feeds
(M2).
- **L5 (C4):** each sim type is **independent** — failure in one sim does not cascade to others. - **L5 (C4):** each sim type is **independent** — failure in one sim does not cascade to others.
Degraded sims report their status; traders handle missing predictions. Degraded sims report their status; traders handle missing predictions.
- **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 steps
1. Define `BoundedPrediction` shape and query protocol. 1. Define `BoundedPrediction` shape (value, bounds, confidence/correctness/certainty).
2. Build the sim runner (lifecycle management for always-on sims). 2. Build the sim runner (lifecycle management for always-on sims).
3. Wire M2 Data Feeds → calibration pipeline. 3. Wire M2 Data Feeds → calibration pipeline.
4. Implement sub-specs M3a–M3g as they land. 4. Implement sub-specs M3a–M3g as they land.
5. Wire trader query interface. 5. Wire continuous prediction publishing → M2 → Marketplace.
## 9. Tests ## 9. Tests
Always-on: sim running after init without external trigger. Bounded output: every prediction has Always-on: sim running after init without external trigger. Bounded output: every prediction has
lower ≤ value ≤ upper. Query: trader receives prediction without mutating sim. Independence: lower ≤ value ≤ upper. Three metrics: confidence, correctness, certainty all present in every
one sim's failure doesn't affect others. Calibration: new data updates model state. output. Publishing: predictions flow continuously to Marketplace via M2. Independence: one sim's
failure doesn't affect others. Calibration: new data updates model state.
## 10. Open items ## 10. Open items
- Pop lifecycle (birth/death/mutation within sims, or fixed populations?). - Pop lifecycle (birth/death/mutation within sims, or fixed populations?).
+1 -1
View File
@@ -81,7 +81,7 @@ strategy mutation, PDE solvers for MFG (HJB + Fokker-Planck), and bandit algorit
- M3 Sims hub — lifecycle management; *stub:* manual init. - M3 Sims hub — lifecycle management; *stub:* manual init.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** pops are **archetypal individuals, not literao living persons** — no attempt to model or track real - **L1 (C5):** pops are **archetypal individuals, not literal living persons** — no attempt to model or track real
market participants. The sim models emergent behavior from abstracted populations. market participants. The sim models emergent behavior from abstracted populations.
- **L2 (C5):** strategies **evolve** — the population distribution shifts over time via - **L2 (C5):** strategies **evolve** — the population distribution shifts over time via
replicator dynamics. No fixed strategy ratios. replicator dynamics. No fixed strategy ratios.
+3 -1
View File
@@ -19,7 +19,9 @@ optimization C3 (emerging — SMFRL solvers); Kolokoltsov adversarial C3 (non-li
WENO discretization established but crypto application novel). Parameterization C1. WENO discretization established but crypto application novel). Parameterization C1.
## 3. Language & location ## 3. Language & location
FORTRAN [WHICH IMPLEMENTATIOBS?] · `src/economy/sims/mev/`. **Fortran** — dense numerical loops for PDE solvers (WENO **Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS**
(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
shock-capturing), knapsack combinatorics, and continuous-time auction modeling at the throughput shock-capturing), knapsack combinatorics, and continuous-time auction modeling at the throughput
MEV extraction demands; no GC pauses during hot-path simulation. MEV extraction demands; no GC pauses during hot-path simulation.
+6 -4
View File
@@ -19,10 +19,12 @@ DeXposure inter-protocol credit propagation C3 (emerging, 2025 — high DeFi spe
composable yield optimization C4 (Yearn v3, Beefy, production-validated). Specific parameters C1. composable yield optimization C4 (Yearn v3, Beefy, production-validated). Specific parameters C1.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/sims/tokenomics/`. **Fortran** — SDE solvers (Euler-Maruyama, Milstein), **Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies:
state-space estimation, and VAR impulse responses are dense matrix-heavy loops where Fortran's **OpenBLAS** (LAPACK/BLAS via native Fortran interfaces). Hand-rolled: Box-Muller RNG, SDE
array intrinsics and zero-overhead numerics dominate; same language as M3d avoids a toolchain solvers, JSON I/O against fixed schemas. SDE solvers (Euler-Maruyama, Milstein), state-space
split across the heaviest numerical sims. estimation, and VAR impulse responses are dense matrix-heavy loops where Fortran's array
intrinsics and zero-overhead numerics dominate; same language as M3d avoids a toolchain split
across the heaviest numerical sims.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** simulate token state dynamics via the SDE framework: - **Does:** simulate token state dynamics via the SDE framework:
+23 -28
View File
@@ -2,8 +2,9 @@
## 1. Component ## 1. Component
The economy organ's vault: **sovereign, local-hosted, our-custody-only cryptocurrency wallets**. The economy organ's vault: **sovereign, local-hosted, our-custody-only cryptocurrency wallets**.
Each wallet binds to exactly one Trader (M5) — a trader without a wallet cannot access the Each wallet binds to exactly one Trader (M5) — strictly 1:1 both directions. A single wallet
Marketplace (M1). Wallets hold keys, sign transactions, and enforce wallet-level spending limits. handles multiple chains internally (EVM, Solana, etc.). A trader without a wallet cannot access
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).
## 2. Status / certainty ## 2. Status / certainty
@@ -11,8 +12,7 @@ DESIGN-FIRST · ABSENT. Role C4 (sovereign custody is a hard requirement); imple
## 3. Language & location ## 3. Language & location
TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for
Solana, etc.), HD derivation, and transaction signing. Rust or Go for crypto primitives; Python Solana, etc.)
with web3 libs for prototyping.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** generate and store private keys locally (never transmitted); sign transactions on - **Does:** generate and store private keys locally (never transmitted); sign transactions on
@@ -24,15 +24,11 @@ with web3 libs for prototyping.
custody to any third party — ever. custody to any third party — ever.
## 5. Interface contract ## 5. Interface contract
- `create_wallet(chain: Chain, trader_id) -> wallet_id` — generates keys, binds to trader.
- `sign(wallet_id, tx: UnsignedTransaction) -> SignedTransaction` — signs with the wallet's key. - `sign(wallet_id, tx: UnsignedTransaction) -> SignedTransaction` — signs with the wallet's key.
Only the bound trader (via Marketplace) can request signing. Only the bound trader can request signing.
- `balance(wallet_id) -> { chain, assets: [{ token, amount }] }`. - `balance(wallet_id) -> { chain, assets: [{ token, amount }] }`.
- `spending_check(wallet_id, amount) -> { allowed:bool, remaining_daily:num }`. - `spending_check(wallet_id)`.
- `tax_collect(wallet_id, income_amount) -> { tax_amount, receipt }` — computes and stages tax. - taxes are out of scope
- `transfer_tax_stub(source_wallet, dest_wallet, amount) -> receipt` — **STUB** for future
Verschwörern Veregeister internal transfer. Logs only; does not execute.
- `Chain` ∈ { `evm`, `solana`, `bitcoin`, … } — extensible.
## 6. Dependencies & stubs ## 6. Dependencies & stubs
- M5 Traders — 1:1 binding; *stub:* canned trader ID. - M5 Traders — 1:1 binding; *stub:* canned trader ID.
@@ -42,33 +38,32 @@ with web3 libs for prototyping.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** **sovereign custody only** — private keys are generated locally, stored locally, - **L1 (C5):** **sovereign custody only** — private keys are generated locally, stored locally,
and **never leave the wallet**. No custodial service, no exchange deposit, no MPC with external and **never leave the wallet**. No custodial service, no exchange deposit, no trust with external
parties. Our keys, our coins. 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 routing** — a wallet will not sign a transaction - **L3 (C4):** **signing requires Marketplace confirmation** — a wallet will not sign a transaction
that didn't come through the Marketplace harness (M1-L1). No direct signing API for traders. that didn't receive direct authorization from Marketpakce (M1-L1). No direct signing API for 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 controls 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):** **tax collection is automatic** — realized income triggers tax staging. The trader
cannot opt out. cannot opt out. OUT OF SCOPE
## 8. Build steps ## 8. Build steps
1. Implement key generation and secure local storage (encrypted keystore). 1. Implement key generation and secure storage.
2. Implement transaction signing for one chain (start with EVM/secp256k1). 2. Implement transaction signing for one chain.
3. Implement trader binding and Marketplace-only signing enforcement. 3. Implement trader binding and Marketplace-only signing enforcement.
4. Implement spending limits (daily cap, per-tx cap). 4. Implement algorithmic limits.
5. Implement tax calculation and staging stub.
## 9. Tests ## 9. Tests
Custody: private key never appears in any API response or log. Binding: wrong trader cannot Custody: private key never appears in any response, messages, or log.
sign. Marketplace-only: direct sign request (not via Marketplace) rejected. Spending limit: Binding: wrong trader cannot sign.
over-limit transaction rejected. Tax: income event triggers correct tax amount. Multi-chain: Trade limits: over-limit transaction rejects; risk :: reward ratio below-limit rejects.
EVM and one other chain produce valid signatures. Tax: out of scope.
Multi-chain: every chain produces valid signatures.
## 10. Open items ## 10. Open items
- Key storage format (encrypted JSON keystore? OS keyring? HSM for production?). - Key storage format.
- Which chains to support initially. - Which chains to support initially. (all of them)
- Spending limit configuration (hardcoded? per-trader? adjustable by Conductor?). - Spending limit configuration (correction: This is algorithmic and hardcoded.)
- Tax rate and calculation method.
- Key rotation / backup strategy. - Key rotation / backup strategy.
+28 -52
View File
@@ -1,78 +1,54 @@
# M5 — Traders (AI actors) # M5 — Traders (AI actors)
## 1. Component ## 1. Component
The economy organ's hands: **specialized AI actors** 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 Sims 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**.
(M3) for predictions, and has all tool calls monitored by the SAE (M7). Multiple traders may
operate concurrently with **different specializations** (DeFi yield, NFT minting, arbitrage,
long-term holding, etc.).
## 2. Status / certainty ## 2. Status / certainty
DESIGN-FIRST · ABSENT. Role C3; implementation C1. DESIGN-FIRST · ABSENT. Role C3; implementation C1.
## 3. Language & location ## 3. Language & location
TBD · `src/economy/traders/`. Each trader is an AI actor — likely LLM-based (small models for 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.
speed) or hybrid (LLM for strategy + deterministic execution logic). The harness managing
multiple traders may be Pony actors or a Python async framework.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** query Sims (M3) for market predictions (bounded, multi-domain); consume Data Feeds - **Does:** read sim predictions from the Marketplace (M1) (bounded, multi-domain, per-sim-type);
(M2) for real-time market state; formulate trade decisions based on predictions + data + formulate trade decisions based on predictions + market state + specialization; submit
specialization; submit `MarketAction` requests to the Marketplace (M1) via bound wallet (M4); `MarketAction` requests to the Marketplace (M1) only bound wallet (M4); operate with **scoped
operate with **scoped autonomy** — trades within law/budget constraints don't need Brain or autonomy** — trades within law/budget constraints don't need Brain or Conductor approval; manage lower level bot goals.
Conductor approval.
- **Does-not:** execute on-chain directly (Marketplace does); hold keys (Wallet does); supervise - **Does-not:** execute on-chain directly (Marketplace does); hold keys (Wallet does); supervise
other traders (Conductor does); modify the law script (immutable — M1-L2); bypass the other traders (Conductor does); modify the law script (immutable — M1-L2); bypass the
Marketplace (M1-L1). Marketplace (M1-L1) - this must be due to literal lack of surface.
## 5. Interface contract ## 5. Interface contract
- `init_trader(specialization, wallet_id, config) -> trader_id`.
`specialization` ∈ { `defi_yield`, `nft_minter`, `arbitrageur`, `trend_follower`, - [somehow this was a literal mess]
`market_maker`, … } — extensible.
- `decide(market_state, predictions: [BoundedPrediction]) -> MarketAction?` — the trader's core
loop. May return no action (waiting is a valid decision).
- `tool_call(tool_name, args) -> result` — every tool call is intercepted and logged to SAE (M7)
before execution. Includes Marketplace submissions, Sim queries, and Data Feed reads.
- `pause() / resume()` — Conductor (M6) can pause a trader pending investigation.
- `status() -> { active | paused | investigating, wallet_id, specialization, position_summary }`.
## 6. Dependencies & stubs ## 6. Dependencies & stubs
- M1 Marketplace — action submission; *stub:* mock marketplace that logs actions. - M1 Marketplace — trade verification; *stub:* none, must make marketplace first.
- M2 Data Feeds — market data; *stub:* canned data. - M1 Marketplace — predictions (from sims via M2) and action submission; *stub:* see above
- M3 Sims — predictions; *stub:* fixed predictions. - M4 Wallet — bound 1:1; *stub:* see above
- M4 Wallet — bound 1:1; *stub:* mock wallet. - M6 Conductor — supervision; *stub:* ... need i state
- M6 Conductor — supervision; *stub:* no supervision. - M7 SAE — Out of scope
- M7 SAE — monitors all tool calls; *stub:* print calls.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** **all market actions 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 `MarketAction` → Marketplace (M1). Enforced by architecture any chain or protocol except via Marketplace (M1). Enforced by architecture (no direct RPC access), not just policy.
(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.
- **L2 (C5):** **all tool calls are monitored** — every tool invocation (Marketplace, Sims, - **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.
Feeds, internal) is logged to SAE (M7). No unmonitored trader action. - **L5 (C3):** trader specialization constrains strategy but not the interface — all traders use the same vocabulary regardless of specialization.
- **L3 (C4):** **wallet binding is irrevocable within a session** — a trader's wallet cannot be
reassigned to another trader at runtime.
- **L4 (C4):** **Conductor can pause** — a paused trader cannot submit actions, query sims, or
read feeds until resumed by the Conductor (M6).
- **L5 (C3):** trader specialization constrains strategy but not the interface — all traders use
the same `MarketAction` vocabulary regardless of specialization.
## 8. Build steps ## 8. Build steps
1. Define the trader agent architecture (LLM-based? hybrid? rule-based for v1?). 1. Make the real build order.
2. Implement the `decide` loop (observe market state + predictions → action).
3. Wire tool-call interception → M7 SAE.
4. Wire Marketplace submission → M1.
5. Implement pause/resume for Conductor control.
6. Build at least two specializations to test multi-trader dynamics.
## 9. Tests ## 9. Tests
Marketplace-only: trader cannot call chain RPC directly. Monitoring: every tool call appears in Marketplace-only: trader cannot call chain RPC directly.
SAE log. Wallet binding: trader uses only its bound wallet. Pause: paused trader cannot submit Wallet binding: trader uses only its bound wallet.
actions. Specialization: different specializations produce different action patterns on identical Pause: paused trader does not change state.
market state. Specialization: different specializations produce different action patterns on identical market state.
## 10. Open items ## 10. Open items
- Trader agent architecture (which LLM? how much deterministic logic vs. model inference?). - Trader architecture
- Number of concurrent traders and resource allocation per trader. - Number of concurrent traders and resource allocation per trader.
- Specialization catalog (which types, and how do they differ in strategy?). - Specialization catalog (which types, and how do they differ in strategy?).
- Inter-trader coordination (do traders see each other's positions? shared state? isolated?). - Inter-trader coordination (necessary for high end maneuvers including rugpulls)
+2 -1
View File
@@ -57,7 +57,8 @@ inference wrapper sits alongside the Marketplace.
fields, same signatures. The Conductor processes them the same way the Brain would. fields, same signatures. The Conductor processes them the same way the Brain would.
## 8. Build steps ## 8. Build steps
1. Define the Conductor's decision model (rule-based for v1? fine-tuned LLM for v2?). 1. Define the Conductor's LLM decision model (specialist-trained; rules are enforced by the
Marketplace law script and wallet spending limits — the Conductor applies judgment).
2. Wire SAE alert intake (M7 → M6). 2. Wire SAE alert intake (M7 → M6).
3. Wire Marketplace veto check (M1 → M6 → approve/veto). 3. Wire Marketplace veto check (M1 → M6 → approve/veto).
4. Implement trader pause/investigate/resume flow. 4. Implement trader pause/investigate/resume flow.
+13 -45
View File
@@ -20,64 +20,32 @@ TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader a
Shares the architectural pattern with F2 but is a separate instance scoped to the economy organ. Shares the architectural pattern with F2 but is a separate instance scoped to the economy organ.
## 4. Does / does-not ## 4. Does / does-not
- **Does:** intercept and log **every trader tool call** (Marketplace, Sims, Feeds, internal); - **Does:** intercept and log **every trader action at the Marketplace level** — the Marketplace
embed trader action sequences; run SAE anomaly detection over action embeddings; flag suspicious is the only interface traders can act through, so monitoring it captures everything; embed trader
patterns (unusual trading frequency, outsized positions, coordinated behavior across traders, action sequences; run SAE anomaly detection over action embeddings; flag suspicious patterns
repeated failed actions, unusual Sim query patterns); report alerts to the Conductor (M6) with (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).
evidence; format alerts **identically to Brain messages** (same structure, same signatures). - **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.
- **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.
## 5. Interface contract ## 5. Interface contract
- `log_tool_call(trader_id, tool_name, args, result, timestamp)` — called on every trader tool
invocation. Synchronous interception (the call is logged before execution proceeds).
- `alert(trader_id, alert_type, evidence, severity) -> SAEAlert`.
`alert_type` ∈ { `unusual_frequency`, `outsized_position`, `coordinated_behavior`,
`repeated_failures`, `anomalous_queries`, `pattern_deviation` }.
`severity` ∈ { `low`, `medium`, `high`, `critical` }.
- `SAEAlert` structure is **identical to Brain message structure** — same fields, same
signature scheme. The Conductor (M6) processes SAE alerts and Brain messages through the
same intake (M6-L5).
- `status() -> { active, traders_monitored, alerts_pending, model_freshness }`.
## 6. Dependencies & stubs ## 6. Dependencies & stubs
- M5 Traders — tool call source; *stub:* canned tool call log. -
- M6 Conductor — alert consumer; *stub:* print alerts.
- F2 SAE monitor (organism-level) — architectural pattern; no runtime dependency.
## 7. Invariants / laws ## 7. Invariants / laws
- **L1 (C5):** the SAE watches **traders, never the Conductor** — the Conductor is the - **L1 (C5):** the SAE watches everyone in the orgab.
stomach's judgment; the SAE monitors the machinery. Echoes F2-L1 (watch the machinery, never - **L2 (C5):** **every tool call is logged** — no trader action escapes monitoring. This is enforced architecturally (tool call interception), not by policy.
the homunculus). - **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).
- **L2 (C5):** **every tool call is logged** — no trader action escapes monitoring. This is - **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.
enforced architecturally (tool call interception), not by policy. - **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).
- **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.
- **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).
## 8. Build steps ## 8. Build steps
1. Implement tool-call interception in the trader harness (M5). 1. Implement action interception at the Marketplace level (M1).
2. Define the action embedding scheme (how tool calls are vectorized). 2. Define the action embedding scheme (how tool calls are vectorized).
3. Train the SAE on normal trader behavior (bootstrapped from simulated trading). 3. Train the SAE on normal trader behavior (bootstrapped from simulated trading).
4. Implement anomaly scoring and alert threshold. 4. Implement anomaly scoring and alert threshold.
5. Wire alerts to Conductor (M6) in Brain-compatible message format. 5. Wire alerts to Conductor (M6) in Brain-compatible message format.
## 9. Tests ## 9. Tests
Interception: every tool call produces a log entry. Anomaly: known-suspicious patterns (e.g.
100x normal frequency) trigger alert. Normal: baseline behavior does not trigger alert.
No enforcement: SAE cannot pause or block a trader (only Conductor can). Alert format: SAE
alert parses as valid Brain message. Conductor-blind: no Conductor action appears in SAE logs.
## 10. Open items ## 10. Open items
- SAE architecture (how many features? reconstruction vs. classification?).
- Training data bootstrapping (simulated trading or historical data?).
- Alert threshold tuning (too sensitive = alert fatigue; too lax = missed anomalies).
- Whether M7 should also monitor Marketplace execution outcomes (fills, slippage) in addition
to tool calls.
- Relationship to F2: shared model? shared training pipeline? or fully independent?
+13
View File
@@ -0,0 +1,13 @@
name = "mev-sims"
version = "0.1.0"
license = "proprietary"
[build]
auto-executables = false
auto-tests = true
link = ["openblas"]
[fortran]
implicit-typing = false
implicit-external = false
source-form = "free"