From ee3a6f9b0be8ae554a84d788eb91ad450f419dc3 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:14:19 -0700 Subject: [PATCH 001/156] economy: add traders.tcl --- core/src/economy/traders.tcl | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 core/src/economy/traders.tcl diff --git a/core/src/economy/traders.tcl b/core/src/economy/traders.tcl new file mode 100644 index 0000000..9ed45dd --- /dev/null +++ b/core/src/economy/traders.tcl @@ -0,0 +1,31 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Traders { + variable records paused + constructor {} { set records {}; set paused {} } + + method register {trader_id specialization} { + if {[dict exists $records $trader_id]} { error "trader_exists" } + dict set records $trader_id [dict create specialization $specialization] + dict set paused $trader_id 0 + return [dict create status registered trader_id $trader_id specialization $specialization] + } + method exists {trader_id} { return [dict exists $records $trader_id] } + method pause {trader_id} { + if {![my exists $trader_id]} { error "unknown_trader" } + dict set paused $trader_id 1 + } + method resume {trader_id} { + if {![my exists $trader_id]} { error "unknown_trader" } + dict set paused $trader_id 0 + } + method is_paused {trader_id} { + expr {[dict exists $paused $trader_id] && [dict get $paused $trader_id]} + } + method count {} { return [dict size $records] } + method paused_count {} { + set n 0 + dict for {id p} $paused { if {$p} { incr n } } + return $n + } +} From 39ac5751c42fc1493a4e55742aacc35ea7075359 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:14:21 -0700 Subject: [PATCH 002/156] economy: add wallets.tcl --- core/src/economy/wallets.tcl | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core/src/economy/wallets.tcl diff --git a/core/src/economy/wallets.tcl b/core/src/economy/wallets.tcl new file mode 100644 index 0000000..340c71e --- /dev/null +++ b/core/src/economy/wallets.tcl @@ -0,0 +1,39 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Wallets { + variable wallets wallet_for_trader spend + constructor {} { set wallets {}; set wallet_for_trader {}; set spend {} } + + method bind {wallet_id trader_id daily_limit per_action_limit} { + if {[dict exists $wallets $wallet_id]} { error "wallet_already_bound" } + if {[dict exists $wallet_for_trader $trader_id]} { error "trader_already_bound" } + foreach {name value} [list daily_limit $daily_limit per_action_limit $per_action_limit] { + if {![string is double -strict $value] || $value <= 0} { error "${name}_must_be_positive" } + } + # No key material exists here. Binding/limits are implemented first; local + # key generation/signing waits for the still-open M4 storage specification. + dict set wallets $wallet_id [dict create trader_id $trader_id daily_limit $daily_limit per_action_limit $per_action_limit] + dict set wallet_for_trader $trader_id $wallet_id + dict set spend $wallet_id 0.0 + return [dict create status bound wallet_id $wallet_id trader_id $trader_id] + } + method binding_for {trader_id} { + if {![dict exists $wallet_for_trader $trader_id]} { return "" } + return [dict get $wallet_for_trader $trader_id] + } + method binding_matches {trader_id wallet_id} { + expr {[dict exists $wallet_for_trader $trader_id] && [dict get $wallet_for_trader $trader_id] eq $wallet_id && [dict exists $wallets $wallet_id] && [dict get $wallets $wallet_id trader_id] eq $trader_id} + } + method spending_check {wallet_id action} { + set w [dict get $wallets $wallet_id] + set notional [expr {double([dict get $action amount]) * double([dict get $action price])}] + if {$notional > double([dict get $w per_action_limit])} { return [dict create pass 0 reason wallet_limit] } + set used [dict get $spend $wallet_id] + if {$used + $notional > double([dict get $w daily_limit])} { return [dict create pass 0 reason wallet_daily_limit] } + return [dict create pass 1 notional $notional] + } + method record_spend {wallet_id notional} { + dict set spend $wallet_id [expr {[dict get $spend $wallet_id] + $notional}] + } + method count {} { return [dict size $wallets] } +} From 51ec96f366df9fd081188608304d0a622934dfed Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:14:58 -0700 Subject: [PATCH 003/156] economy: add sae.tcl --- core/src/economy/sae.tcl | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 core/src/economy/sae.tcl diff --git a/core/src/economy/sae.tcl b/core/src/economy/sae.tcl new file mode 100644 index 0000000..8fe59ac --- /dev/null +++ b/core/src/economy/sae.tcl @@ -0,0 +1,15 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SAEMonitor { + variable events + constructor {} { set events {} } + method log_tool {trader_id tool detail} { + lappend events [dict create trader_id $trader_id tool $tool detail $detail timestamp [clock seconds]] + } + method alert {trader_id alert_type evidence severity timestamp} { + if {![string is double -strict $severity] || $severity < 0 || $severity > 10} { error "severity_out_of_range" } + return [dict create trader_id $trader_id alert_type $alert_type evidence $evidence severity $severity timestamp $timestamp] + } + method log {} { return $events } + method count {} { return [llength $events] } +} From efdce9d41be4d0c5841ee9bfd3dc9a827a030af2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:02 -0700 Subject: [PATCH 004/156] economy: add conductor.tcl --- core/src/economy/conductor.tcl | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 core/src/economy/conductor.tcl diff --git a/core/src/economy/conductor.tcl b/core/src/economy/conductor.tcl new file mode 100644 index 0000000..2d44f96 --- /dev/null +++ b/core/src/economy/conductor.tcl @@ -0,0 +1,43 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Conductor { + variable traders decisions veto_next + constructor {traders_obj} { set traders $traders_obj; set decisions {}; set veto_next {} } + + method veto_next {trader_id reason} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + dict set veto_next $trader_id $reason + return [dict create status armed trader_id $trader_id] + } + method consume_veto {trader_id} { + if {![dict exists $veto_next $trader_id]} { return [dict create approved 1] } + set reason [dict get $veto_next $trader_id] + dict unset veto_next $trader_id + lappend decisions [dict create decision veto trader_id $trader_id reason $reason timestamp [clock seconds]] + return [dict create approved 0 reason $reason] + } + method pause {trader_id reason} { + $traders pause $trader_id + set d [dict create decision pause trader_id $trader_id reason $reason timestamp [clock seconds]] + lappend decisions $d + return $d + } + method resume {trader_id reason} { + $traders resume $trader_id + set d [dict create decision resume trader_id $trader_id reason $reason timestamp [clock seconds]] + lappend decisions $d + return $d + } + method receive_alert {alert} { + set trader_id [dict get $alert trader_id] + if {[dict get $alert severity] >= 8.0} { + $traders pause $trader_id + set d [dict create decision pause trader_id $trader_id reason "sae:[dict get $alert alert_type]" alert $alert timestamp [clock seconds]] + } else { + set d [dict create decision dismiss trader_id $trader_id reason below_pause_threshold alert $alert timestamp [clock seconds]] + } + lappend decisions $d + return $d + } + method log {} { return $decisions } +} From 12be786507033d52323dbc143f608b35213facba Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:04 -0700 Subject: [PATCH 005/156] economy: add feeds.tcl --- core/src/economy/feeds.tcl | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 core/src/economy/feeds.tcl diff --git a/core/src/economy/feeds.tcl b/core/src/economy/feeds.tcl new file mode 100644 index 0000000..7d13fb2 --- /dev/null +++ b/core/src/economy/feeds.tcl @@ -0,0 +1,22 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Feeds { + variable history_cap feeds + constructor {cap} { + if {![string is integer -strict $cap] || $cap < 1} { error "history_cap_must_be_positive" } + set history_cap $cap + set feeds {} + } + method publish {feed_type source timestamp payload confidence} { + if {![string is double -strict $confidence] || $confidence < 0 || $confidence > 10} { error "confidence_out_of_range" } + set history [expr {[dict exists $feeds $feed_type] ? [dict get $feeds $feed_type] : {}}] + if {[llength $history] >= $history_cap} { return [dict create status backpressure feed_type $feed_type buffered [llength $history]] } + lappend history [dict create feed_type $feed_type source $source timestamp $timestamp payload $payload confidence $confidence] + dict set feeds $feed_type $history + return [dict create status accepted feed_type $feed_type buffered [llength $history]] + } + method history {feed_type} { + if {![dict exists $feeds $feed_type]} { return {} } + return [dict get $feeds $feed_type] + } +} From 93b0de2924acd1a2cd8595e920ce0d6b545782fd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:06 -0700 Subject: [PATCH 006/156] economy: add hub.tcl --- core/src/economy/sims/hub.tcl | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 core/src/economy/sims/hub.tcl diff --git a/core/src/economy/sims/hub.tcl b/core/src/economy/sims/hub.tcl new file mode 100644 index 0000000..6460bcf --- /dev/null +++ b/core/src/economy/sims/hub.tcl @@ -0,0 +1,29 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SimsHub { + variable predictions + constructor {} { set predictions {} } + method publish {sim_type prediction} { + foreach required {value lower_bound upper_bound confidence correctness certainty time_horizon token_ticker recent_shift timestamp} { + if {![dict exists $prediction $required]} { error "prediction_missing_$required" } + } + foreach numeric {value lower_bound upper_bound confidence correctness certainty recent_shift timestamp} { + if {![string is double -strict [dict get $prediction $numeric]]} { error "prediction_${numeric}_not_numeric" } + } + set value [dict get $prediction value]; set lo [dict get $prediction lower_bound]; set hi [dict get $prediction upper_bound] + if {$lo > $value || $value > $hi} { error "prediction_out_of_bounds" } + foreach metric {confidence correctness certainty} { + set v [dict get $prediction $metric] + if {$v < 0 || $v > 10} { error "prediction_${metric}_out_of_range" } + } + dict set prediction sim_type $sim_type + dict set prediction running 1 + dict set predictions $sim_type $prediction + return [dict create status published sim_type $sim_type] + } + method query {sim_type} { + if {![dict exists $predictions $sim_type]} { error "prediction_unavailable" } + return [dict get $predictions $sim_type] + } + method count {} { return [dict size $predictions] } +} From ac93b7421ea0aa03ab7c2e9548e2d609e220ade3 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:23 -0700 Subject: [PATCH 007/156] economy: add marketplace.tcl --- core/src/economy/marketplace.tcl | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 core/src/economy/marketplace.tcl diff --git a/core/src/economy/marketplace.tcl b/core/src/economy/marketplace.tcl new file mode 100644 index 0000000..e8f2d1b --- /dev/null +++ b/core/src/economy/marketplace.tcl @@ -0,0 +1,49 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Marketplace { + variable traders wallets conductor sae sims executions tx_seq + constructor {traders_obj wallets_obj conductor_obj sae_obj sims_obj} { + set traders $traders_obj; set wallets $wallets_obj; set conductor $conductor_obj; set sae $sae_obj; set sims $sims_obj + set executions {}; set tx_seq 0 + } + method _reject {reason} { return [dict create status failed reason $reason] } + method _law_check {action} { + foreach required {type asset chain amount price} { + if {![dict exists $action $required]} { return [dict create pass 0 reason "missing_$required"] } + } + if {[lsearch -exact {buy sell mint provide_liquidity withdraw_liquidity claim_rewards} [dict get $action type]] < 0} { return [dict create pass 0 reason action_not_allowed] } + if {[lsearch -exact {ethereum solana arbitrum} [dict get $action chain]] < 0} { return [dict create pass 0 reason chain_not_allowed] } + set amount [dict get $action amount]; set price [dict get $action price] + if {![string is double -strict $amount] || ![string is double -strict $price] || $amount <= 0 || $price < 0} { return [dict create pass 0 reason invalid_notional] } + return [dict create pass 1] + } + method submit {trader_id wallet_id action} { + $sae log_tool $trader_id submit_action $action + if {![$traders exists $trader_id]} { return [my _reject unknown_trader] } + if {[$wallets binding_for $trader_id] eq ""} { return [my _reject missing_wallet] } + if {![$wallets binding_matches $trader_id $wallet_id]} { return [my _reject wallet_binding] } + if {[$traders is_paused $trader_id]} { return [my _reject trader_paused] } + set law [my _law_check $action] + if {![dict get $law pass]} { return [my _reject [dict get $law reason]] } + set wc [$wallets spending_check $wallet_id $action] + if {![dict get $wc pass]} { return [my _reject [dict get $wc reason]] } + set veto [$conductor consume_veto $trader_id] + if {![dict get $veto approved]} { return [my _reject [dict get $veto reason]] } + + # Simulation boundary: there is no signer, broadcaster, RPC client, or + # chain-execution method in this scaffold. Success means the proposed + # action cleared the organ's gates and was recorded in the sandbox. + incr tx_seq + set tx_id [format "simtx-%06d" $tx_seq] + $wallets record_spend $wallet_id [dict get $wc notional] + lappend executions [dict create tx_id $tx_id trader_id $trader_id wallet_id $wallet_id action $action execution simulated] + return [dict create status succeeded execution simulated tx_id $tx_id] + } + method predictions {trader_id sim_type} { + $sae log_tool $trader_id query_predictions [dict create sim_type $sim_type] + if {![$traders exists $trader_id]} { error "unknown_trader" } + if {[$traders is_paused $trader_id]} { error "trader_paused" } + return [$sims query $sim_type] + } + method execution_count {} { return [llength $executions] } +} From 1b4bd41c991357dcfb789b5b1e8875f99d437b6c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:25 -0700 Subject: [PATCH 008/156] economy: add stomach.tcl --- core/src/economy/stomach.tcl | 65 ++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 core/src/economy/stomach.tcl diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl new file mode 100644 index 0000000..235bdd0 --- /dev/null +++ b/core/src/economy/stomach.tcl @@ -0,0 +1,65 @@ +# M0 stomach/economy organ composition for sica-fondt. +# Tcl 8.6, external-dependency free. This scaffold is simulation-only: no RPC, +# signing, or private-key surface exists yet. +namespace eval ::stomach { variable version 0.1 } +set __stomach_dir [file dirname [file normalize [info script]]] +foreach __stomach_file {traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl sims/hub.tcl marketplace.tcl} { + source [file join $__stomach_dir $__stomach_file] +} +unset __stomach_file + +oo::class create ::stomach::Economy { + variable traders wallets sae conductor feeds sims market taxes + constructor {args} { + set cap 256 + if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } + foreach {k v} $args { + switch -- $k { + -history_cap { set cap $v } + default { error "unknown option $k" } + } + } + set traders [::stomach::Traders new] + set wallets [::stomach::Wallets new] + set sae [::stomach::SAEMonitor new] + set conductor [::stomach::Conductor new $traders] + set feeds [::stomach::Feeds new $cap] + set sims [::stomach::SimsHub new] + set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] + set taxes {} + } + destructor { + foreach obj [list $market $sims $feeds $conductor $sae $wallets $traders] { catch {$obj destroy} } + } + method register_trader {id specialization} { return [$traders register $id $specialization] } + method bind_wallet {wallet_id trader_id daily_limit per_action_limit} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + return [$wallets bind $wallet_id $trader_id $daily_limit $per_action_limit] + } + method submit_action {trader_id wallet_id action} { return [$market submit $trader_id $wallet_id $action] } + method conductor_veto_next {trader_id reason} { return [$conductor veto_next $trader_id $reason] } + method conductor_pause {trader_id reason} { return [$conductor pause $trader_id $reason] } + method conductor_resume {trader_id reason} { return [$conductor resume $trader_id $reason] } + method sae_alert {trader_id alert_type evidence severity timestamp} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + return [$conductor receive_alert [$sae alert $trader_id $alert_type $evidence $severity $timestamp]] + } + method feed_publish {args} { return [$feeds publish {*}$args] } + method feed_history {feed_type} { return [$feeds history $feed_type] } + method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } + method query_predictions {trader_id sim_type} { return [$market predictions $trader_id $sim_type] } + method tax_event {trader_id amount source_wallet dest_wallet} { + if {![string is double -strict $amount] || $amount < 0} { error "invalid_tax_amount" } + set receipt [dict create receipt_id [format "tax-%06d" [expr {[llength $taxes] + 1}]] status staged transferred 0 trader_id $trader_id amount $amount source_wallet $source_wallet dest_wallet $dest_wallet] + lappend taxes $receipt + return $receipt + } + method secretion {} { + return [dict create source stomach destination ada_border provenance organ_secretion live_execution 0 traders [$traders count] wallets [$wallets count] predictions [$sims count] executions [$market execution_count] paused_traders [$traders paused_count] tax_receipts [llength $taxes]] + } + method sae_log {} { return [$sae log] } + method decision_log {} { return [$conductor log] } + method execution_count {} { return [$market execution_count] } + method live_execution {} { return 0 } +} +unset __stomach_dir From 3531b432cf7bd5d59438e10b0aa5c4b0231780c7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:48 -0700 Subject: [PATCH 009/156] economy: add stomach.test --- core/src/economy/tests/stomach.test | 139 ++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 core/src/economy/tests/stomach.test diff --git a/core/src/economy/tests/stomach.test b/core/src/economy/tests/stomach.test new file mode 100644 index 0000000..4b72771 --- /dev/null +++ b/core/src/economy/tests/stomach.test @@ -0,0 +1,139 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. stomach.tcl] + +proc new_stomach {{cap 2}} { + set s [::stomach::Economy new -history_cap $cap] + $s register_trader trader-a statistical + $s register_trader trader-b microstructure + return $s +} + +test walletless-rejected-1.0 {M1 L3 rejects a trader with no wallet before execution} -body { + set s [new_stomach] + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 0.1 price 100.0]] + set out [list [dict get $result status] [dict get $result reason] [$s execution_count]] + $s destroy + set out +} -result {failed missing_wallet 0} + +test binding-rejected-1.0 {M4 one-to-one binding prevents use of another trader's wallet} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s bind_wallet wallet-b trader-b 1000.0 500.0 + set result [$s submit_action trader-a wallet-b [dict create type buy asset ETH chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $result status] [dict get $result reason]] + $s destroy + set out +} -result {failed wallet_binding} + +test valid-dry-run-1.0 {valid market action traverses M1/M4/M6 and remains simulated} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 2.0 price 100.0]] + set out [list [dict get $result status] [dict get $result execution] [dict get $result tx_id] [$s execution_count]] + $s destroy + set out +} -result {succeeded simulated simtx-000001 1} + +test law-before-veto-1.0 {M1 rejects a law violation before M6 veto is consumed} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s conductor_veto_next trader-a strategic_risk + set bad [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain forbidden-chain amount 1.0 price 10.0]] + set good [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $bad reason] [dict get $good reason] [$s execution_count]] + $s destroy + set out +} -result {chain_not_allowed strategic_risk 0} + +test every-action-logged-1.0 {M7 receives pass and fail marketplace submissions} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s submit_action trader-a wallet-a [dict create type buy asset BTC chain forbidden-chain amount 1.0 price 10.0] + $s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0] + set events [$s sae_log] + set out [list [llength $events] [dict get [lindex $events 0] tool] [dict get [lindex $events 1] tool]] + $s destroy + set out +} -result {2 submit_action submit_action} + +test severe-sae-alert-pauses-1.0 {M7 severe alert reaches M6 and mechanically pauses trader} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + set decision [$s sae_alert trader-a frequency_spike {burst of calls} 9 1700000000] + set attempt [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $decision decision] [dict get $attempt reason]] + $s destroy + set out +} -result {pause trader_paused} + +test resume-1.0 {M6 pause is reversible} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s conductor_pause trader-a manual_review + $s conductor_resume trader-a cleared + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [dict get $result status] + $s destroy + set out +} -result succeeded + +test bounded-prediction-1.0 {M3 rejects a point estimate outside its explicit bounds} -body { + set s [new_stomach] + set code [catch {$s sim_publish statistical [dict create value 11.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 7.0 certainty 7.0 time_horizon 4h token_ticker BTC recent_shift 0.0 timestamp 1700000000]} msg] + set out [list $code $msg] + $s destroy + set out +} -result {1 prediction_out_of_bounds} + +test marketplace-prediction-query-1.0 {trader reads bounded predictions through Marketplace, not sim hub directly} -body { + set s [new_stomach] + $s sim_publish statistical [dict create value 7.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 8.0 certainty 6.0 time_horizon 4h token_ticker BTC recent_shift -0.02 timestamp 1700000000] + set p [$s query_predictions trader-a statistical] + set out [list [dict get $p value] [dict get $p lower_bound] [dict get $p upper_bound]] + $s destroy + set out +} -result {7.0 5.0 10.0} + +test feed-backpressure-1.0 {M2 returns backpressure without silently dropping buffered data} -body { + set s [new_stomach 2] + set a [$s feed_publish price_tick source-a 1 {BTC 100} 9.0] + set b [$s feed_publish price_tick source-a 2 {BTC 101} 9.0] + set c [$s feed_publish price_tick source-a 3 {BTC 102} 9.0] + set h [$s feed_history price_tick] + set out [list [dict get $a status] [dict get $b status] [dict get $c status] [llength $h] [dict get [lindex $h 1] timestamp]] + $s destroy + set out +} -result {accepted accepted backpressure 2 2} + +test wallet-limit-1.0 {M4 wallet-level per-action limit independently brakes exposure} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 50.0 + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 100.0]] + set out [list [dict get $result status] [dict get $result reason]] + $s destroy + set out +} -result {failed wallet_limit} + +test tax-stub-1.0 {M0 tax hook produces a receipt but does not transfer value} -body { + set s [new_stomach] + set r [$s tax_event trader-a 12.5 wallet-a verein-wallet] + set out [list [dict get $r status] [dict get $r transferred] [dict get $r amount]] + $s destroy + set out +} -result {staged 0 12.5} + +test secretion-1.0 {M0 produces an Ada-bound organ secretion summary} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s sim_publish statistical [dict create value 7.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 8.0 certainty 6.0 time_horizon 4h token_ticker BTC recent_shift -0.02 timestamp 1700000000] + set secretion [$s secretion] + set out [list [dict get $secretion source] [dict get $secretion destination] [dict get $secretion provenance] [dict get $secretion live_execution]] + $s destroy + set out +} -result {stomach ada_border organ_secretion 0} + +cleanupTests From 5a8937840e092000e157808e594c72608f1ced2a Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:51 -0700 Subject: [PATCH 010/156] economy: add README.md --- core/src/economy/README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 core/src/economy/README.md diff --git a/core/src/economy/README.md b/core/src/economy/README.md new file mode 100644 index 0000000..3263d04 --- /dev/null +++ b/core/src/economy/README.md @@ -0,0 +1,32 @@ +# 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. + +## Implemented now + +- **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. +- **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. +- **M3 Sims hub** — bounded-prediction validation and current-state publication/query. Native M3a–M3g engines and 90:1 scheduler are not built yet. +- **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. +- **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. +- **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. +- **M7 SAE** — records Marketplace tool calls and produces alert envelopes; actual sparse-autoencoder inference/training is not implemented yet. +- **M0** — composes the above, stages tax receipts without moving value, and emits a stomach→Ada status secretion. + +There is deliberately no live transaction broadcaster. A successful action returns `execution simulated` and a deterministic `simtx-*` identifier. Live custody/execution should not appear until the unresolved M4 key-storage design is ratified. + +## Test + +```sh +tclsh core/src/economy/tests/stomach.test +``` + +Expected: `Total 13 Passed 13 ... Failed 0`. + +The repo smoke harness also runs this suite. + +## Public scaffold API + +`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `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. From d329d23dea12f9bd3ef6fb298ba88f575b913bec Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:15:53 -0700 Subject: [PATCH 011/156] economy: add AGENTS.md --- core/src/economy/AGENTS.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 core/src/economy/AGENTS.md diff --git a/core/src/economy/AGENTS.md b/core/src/economy/AGENTS.md new file mode 100644 index 0000000..5b1aa16 --- /dev/null +++ b/core/src/economy/AGENTS.md @@ -0,0 +1,22 @@ +# AGENTS.md — M0 economy/stomach organ + +Local guide for `core/src/economy`. The design source of truth is `core/docs/plans/M0-economy-organ-hub.md` plus M1–M7. + +## Hard boundaries + +- This is an **OUTER** organ. Organism-bound output is `Stomach → AdaBorder` with `OrganSecretion` provenance. Never add an inner-bus route. +- Traders never receive RPC, signing, or chain clients. All market actions enter M1 Marketplace. +- M1 deterministic law runs before M6 veto. M6 may veto a legal action; it may not legalize an illegal one. +- 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. +- 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. + +## Build/test + +Tcl 8.6, standard library only: + +```sh +tclsh core/src/economy/tests/stomach.test +``` + +Use test-first changes. Keep `stomach.tcl` as composition/facade; put component behavior in the M1–M7 module that owns it. From 14f6e23b254a52c59fa11ab5bc56e31cc56b23d4 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:16:22 -0700 Subject: [PATCH 012/156] docs: correct stomach test integration status --- core/src/economy/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index 3263d04..115b83c 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -23,8 +23,6 @@ tclsh core/src/economy/tests/stomach.test Expected: `Total 13 Passed 13 ... Failed 0`. -The repo smoke harness also runs this suite. - ## Public scaffold API `::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`. From 502e070abf1b869c3fb8acf9008fe264a5ade1ba Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:03 -0700 Subject: [PATCH 013/156] docs: mark M0 economy scaffold executable --- core/docs/plans/M0-economy-organ-hub.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/core/docs/plans/M0-economy-organ-hub.md b/core/docs/plans/M0-economy-organ-hub.md index 04cc588..b0987f2 100644 --- a/core/docs/plans/M0-economy-organ-hub.md +++ b/core/docs/plans/M0-economy-organ-hub.md @@ -12,13 +12,15 @@ organism are TBD and out of scope. Brain for permission to trade. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. A `Stomach` primitive exists in Ichor (`src/ichor/envelope.pony:20`) with -one smoke-test wire (`main.pony:29`), but no dedicated organ code. Role C4; implementation C1. +SCAFFOLD · EXECUTABLE. The existing Ichor `Stomach` primitive now has a dedicated +M0–M7 simulation scaffold under `core/src/economy/`. M0 composes the component facades and +emits Ada-bound secretion metadata; external execution and the Pony↔Tcl runtime bridge remain +separate integration work. Role C4; scaffold implementation C2. ## 3. Language & location -TBD · new location e.g. `src/economy/`. The organ is polyglot by nature: trading infrastructure -(APIs, wallets) may differ in language from simulations (numerical computing) and the conductor -(AI supervision). Pony actors provide the Ichor-facing facade. +**Tcl 8.6 scaffold** · `core/src/economy/`. M0 orchestration is Tcl and preserves the +existing polyglot plan for later component engines. Pony remains the Ichor-facing transport layer; +the runtime bridge between Ichor and this scaffold is still open. ## 4. Does / does-not - **Does:** host crypto/NFT trading via the Marketplace (M1); run always-on market prediction @@ -67,8 +69,10 @@ TBD · new location e.g. `src/economy/`. The organ is polyglot by nature: tradin 4. Implement tax stub and Verschwörern Veregeister transfer last. ## 9. Tests -Hub smoke: Marketplace reachable; Sims running and queryable; Wallet bound to Trader; Conductor -receives SAE reports; tax stub logs transfer. Ichor: outbound envelope reaches Ada stub. +Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 13 +tests cover admission ordering, 1:1 binding, simulation-only execution, monitor logging, +supervisor pause/resume, bounded predictions, feed backpressure, exposure limits, tax staging, +and Ada-bound secretion. Ichor runtime bridging remains a separate integration test. ## 10. Open items - Reward signal protocol from economy organ to organism (TBD, out of scope). From 2d7aefa1fe512d696408e80da4f0d0100f464ae5 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:14 -0700 Subject: [PATCH 014/156] docs: sync M1-marketplace.md scaffold status --- core/docs/plans/M1-marketplace.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/docs/plans/M1-marketplace.md b/core/docs/plans/M1-marketplace.md index 6dea5ba..167bd86 100644 --- a/core/docs/plans/M1-marketplace.md +++ b/core/docs/plans/M1-marketplace.md @@ -7,7 +7,9 @@ the Marketplace. Enforces a **deterministic law script** (scoped invariants — own constitution) and integrates the **Conductor's veto** (M6) before execution. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4; implementation C1. +SCAFFOLD · EXECUTABLE SIMULATION. `core/src/economy/marketplace.tcl` implements the single +action ingress, deterministic admission ordering, supervisor veto, monitor logging, and +simulation-only execution. The full law-script loader remains open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/marketplace/`. Needs to interface with blockchain APIs (RPC/REST), wallet From f73b360d592584e20d93ffbfd9bb342a13e63b75 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:17 -0700 Subject: [PATCH 015/156] docs: sync M2-data-feeds.md scaffold status --- core/docs/plans/M2-data-feeds.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/docs/plans/M2-data-feeds.md b/core/docs/plans/M2-data-feeds.md index dcde588..ac36679 100644 --- a/core/docs/plans/M2-data-feeds.md +++ b/core/docs/plans/M2-data-feeds.md @@ -7,7 +7,9 @@ produces execution data (fills, positions, P&L) that feeds back into Sims, and S predictions that inform Traders operating through the Marketplace. Data Feeds is the bridge. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. +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; +scaffold C2. ## 3. Language & location TBD · `src/economy/feeds/`. Needs async I/O for streaming data (WebSockets, SSE, RSS polling). From c5b4d2ed408af8754d77152cb95474a8f3a73943 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:19 -0700 Subject: [PATCH 016/156] docs: sync M3-sims-hub.md scaffold status --- core/docs/plans/M3-sims-hub.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/docs/plans/M3-sims-hub.md b/core/docs/plans/M3-sims-hub.md index 4e56d8c..d4b4573 100644 --- a/core/docs/plans/M3-sims-hub.md +++ b/core/docs/plans/M3-sims-hub.md @@ -12,8 +12,9 @@ The academic foundations span AMM mechanism design [1,2], MEV game theory [3,4,5 tokenomics via SDEs [6,7], and evolutionary consensus games [8–11]. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. Mathematical foundations C4 (literature -established); specific model parameters C1. +SCAFFOLD · EXECUTABLE HUB STATE. `core/src/economy/sims/hub.tcl` validates bounded +predictions and exposes current per-sim state. The continuous scheduler and M3a–M3g engines +remain open. Role C3; scaffold C2. Mathematical foundations C4; parameters C1. ## 3. Language & location **Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages From 97157444023e7e3932c0e249fa928a954eb81121 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:28 -0700 Subject: [PATCH 017/156] docs: sync M4-wallets.md scaffold status --- core/docs/plans/M4-wallets.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/docs/plans/M4-wallets.md b/core/docs/plans/M4-wallets.md index 6e1a7c8..f85b545 100644 --- a/core/docs/plans/M4-wallets.md +++ b/core/docs/plans/M4-wallets.md @@ -8,7 +8,9 @@ the Marketplace (M1). Wallets hold keys, sign transactions, and enforce wallet-l Tax is collected on trader income and routed to the Verschwörern Veregeister wallets (stub — M0). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4 (sovereign custody is a hard requirement); implementation C1. +SCAFFOLD · PARTIAL. `core/src/economy/wallets.tcl` implements permanent 1:1 binding and +independent exposure limits for the simulation scaffold. Custody/signing implementation remains +open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for From a66104e0ee5bada22b501f0aafedce499c0cea18 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:31 -0700 Subject: [PATCH 018/156] docs: sync M5-traders.md scaffold status --- core/docs/plans/M5-traders.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/docs/plans/M5-traders.md b/core/docs/plans/M5-traders.md index 12a1c53..5dea4b7 100644 --- a/core/docs/plans/M5-traders.md +++ b/core/docs/plans/M5-traders.md @@ -5,7 +5,9 @@ The economy organ's hands: **specialized AI instances** that buy, sell, and mint 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**. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. +SCAFFOLD · PARTIAL. `core/src/economy/traders.tcl` implements trader identity, +specialization labels, and mechanical pause/resume state. Trader inference remains open. +Role C3; scaffold C2. ## 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. From c0e2d46aa0ab7e9237650463c420dd766fe8183a Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:34 -0700 Subject: [PATCH 019/156] docs: sync M6-conductor.md scaffold status --- core/docs/plans/M6-conductor.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/docs/plans/M6-conductor.md b/core/docs/plans/M6-conductor.md index 3a347c9..ea2a73f 100644 --- a/core/docs/plans/M6-conductor.md +++ b/core/docs/plans/M6-conductor.md @@ -8,8 +8,9 @@ organism's Brain for trade-level decisions. It supervises; the deterministic law constrains; together they form the multi-layered braking system. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4 (supervision architecture is clear); implementation C1 (model -selection, training, authority scope). +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 +audit storage remain open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/conductor/`. The Conductor is an AI actor — likely a fine-tuned LLM with From 6967dfd1e08e2eb21f80fd206e08d4715fb053d2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:37 -0700 Subject: [PATCH 020/156] docs: sync M7-sae-monitor.md scaffold status --- core/docs/plans/M7-sae-monitor.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/docs/plans/M7-sae-monitor.md b/core/docs/plans/M7-sae-monitor.md index d9a985b..05a40e9 100644 --- a/core/docs/plans/M7-sae-monitor.md +++ b/core/docs/plans/M7-sae-monitor.md @@ -11,9 +11,10 @@ Extends the F2 (SAE monitor) pattern to the economy organ's internal domain. F2 subagents at the organism level; M7 watches traders at the stomach level. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. F2 SAE monitor provides the architectural pattern (watch the machinery, -never the homunculus — F2-L1). M7 adapts this: watch the **traders** (the machinery), never the -**Conductor** (the stomach's judgment). Role C3; implementation C1. +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. +F2 still provides the architectural pattern: watch traders, never the Conductor. Role C3; +scaffold C2. ## 3. Language & location TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader action embeddings). From 76d07a1e4c81070aed0dac8d80c019f65a2401e2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:18:47 -0700 Subject: [PATCH 021/156] docs: add stomach economy organ to docmap --- docmap.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docmap.yaml b/docmap.yaml index afc5958..3d72890 100644 --- a/docmap.yaml +++ b/docmap.yaml @@ -39,6 +39,11 @@ organs: lang: [r, octave] role: endocrine array — R Drive-Box + Octave ETR build: "src/endocrine/run_tests.sh ; src/endocrine/etr/run_etr_tests.sh" + - path: core/src/economy + agents_md: core/src/economy/AGENTS.md + lang: tcl + role: M0 stomach/economy organ scaffold — M1–M7 simulation and Ada-bound secretion + build: "tclsh core/src/economy/tests/stomach.test" - path: core agents_md: core/AGENTS.md lang: [ada, cobol] From 863cd0ead44d2fc8c7183308a0bd1d9c3972d763 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:46:09 -0700 Subject: [PATCH 022/156] toolchain: install gfortran for M3 numerical sims --- .claude/hooks/session-start.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.sh index 7aac33d..383be24 100755 --- a/.claude/hooks/session-start.sh +++ b/.claude/hooks/session-start.sh @@ -3,6 +3,7 @@ # in Claude Code on the web: # * R (Rscript) -> the Drive-Box drivers + tests (src/endocrine/*.R) # * GNU Octave -> the ETR torus + tests (src/endocrine/etr/*.m) +# * GNU Fortran -> M3d/M3e/M3g numerical sims (core/src/economy/sims/*) # # Synchronous + idempotent (safe to re-run; installs only what's missing). # Ada/Alire (mafiabot_core) is intentionally NOT installed here: it is not an apt @@ -20,6 +21,7 @@ export DEBIAN_FRONTEND=noninteractive pkgs=() command -v Rscript >/dev/null 2>&1 || pkgs+=(r-base-core) command -v octave >/dev/null 2>&1 || pkgs+=(octave) +command -v gfortran >/dev/null 2>&1 || pkgs+=(gfortran) if [ "${#pkgs[@]}" -gt 0 ]; then sudo apt-get update -qq @@ -29,3 +31,4 @@ fi # Surface versions in the session log (non-fatal). command -v Rscript >/dev/null 2>&1 && Rscript --version 2>&1 | head -1 || true command -v octave-cli >/dev/null 2>&1 && octave-cli --version 2>&1 | head -1 || true +command -v gfortran >/dev/null 2>&1 && gfortran --version 2>&1 | head -1 || true From 6ae9291e435af72f6417b18059a097bafb6ddf79 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:46:56 -0700 Subject: [PATCH 023/156] M3: add src/mev_engine.f90 --- core/src/economy/sims/mev/src/mev_engine.f90 | 60 ++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core/src/economy/sims/mev/src/mev_engine.f90 diff --git a/core/src/economy/sims/mev/src/mev_engine.f90 b/core/src/economy/sims/mev/src/mev_engine.f90 new file mode 100644 index 0000000..47e61c9 --- /dev/null +++ b/core/src/economy/sims/mev/src/mev_engine.f90 @@ -0,0 +1,60 @@ +module mev_engine + implicit none +contains + subroutine pga_all_pay(bids, opportunity_value, profits, winner) + real(8), intent(in) :: bids(:), opportunity_value + real(8), intent(out) :: profits(size(bids)) + integer, intent(out) :: winner + integer :: i + winner = maxloc(bids, dim=1) + do i=1,size(bids) + profits(i) = -bids(i) + end do + profits(winner) = opportunity_value - bids(winner) + end subroutine + + subroutine knapsack_select(values, gas, gas_limit, selected, best_value) + real(8), intent(in) :: values(:) + integer, intent(in) :: gas(:), gas_limit + integer, intent(out) :: selected(size(values)) + real(8), intent(out) :: best_value + real(8), allocatable :: dp(:,:) + integer :: n, i, w + n = size(values) + allocate(dp(0:n,0:gas_limit)); dp = 0d0 + do i=1,n + do w=0,gas_limit + dp(i,w)=dp(i-1,w) + if (gas(i)<=w) dp(i,w)=max(dp(i,w), dp(i-1,w-gas(i))+values(i)) + end do + end do + best_value=dp(n,gas_limit); selected=0; w=gas_limit + do i=n,1,-1 + if (abs(dp(i,w)-dp(i-1,w))>1d-12) then + selected(i)=1; w=w-gas(i) + end if + end do + deallocate(dp) + end subroutine + + subroutine cross_chain_profit(p_src,p_dst,slippage,gas_cost,bridge_fee,depreciation,q,inventory_profit,bridge_profit) + real(8), intent(in) :: p_src,p_dst,slippage,gas_cost,bridge_fee,depreciation,q + real(8), intent(out) :: inventory_profit,bridge_profit + real(8) :: spread + spread = p_src-p_dst + inventory_profit = (spread-slippage-gas_cost)*q + bridge_profit = (spread-bridge_fee-depreciation)*q + end subroutine + + pure real(8) function sandwich_probability(trade_fraction, slippage_tolerance, liquidity_score) result(p) + real(8), intent(in) :: trade_fraction, slippage_tolerance, liquidity_score + real(8) :: z + z = 5d0*max(0d0,trade_fraction) + 3d0*max(0d0,slippage_tolerance) - 2d0*max(0d0,liquidity_score) + p = 1d0/(1d0+exp(-z)) + end function + + pure real(8) function all_pay_social_cost(bids) result(cost) + real(8), intent(in) :: bids(:) + cost = sum(max(bids,0d0)) + end function +end module From d8624b7a573aa5bcb57a369e8d8662e5750a2787 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:46:59 -0700 Subject: [PATCH 024/156] M3: add test/test_mev.f90 --- core/src/economy/sims/mev/test/test_mev.f90 | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 core/src/economy/sims/mev/test/test_mev.f90 diff --git a/core/src/economy/sims/mev/test/test_mev.f90 b/core/src/economy/sims/mev/test/test_mev.f90 new file mode 100644 index 0000000..f232d53 --- /dev/null +++ b/core/src/economy/sims/mev/test/test_mev.f90 @@ -0,0 +1,19 @@ +program test_mev + use mev_engine + implicit none + real(8) :: bids(3), profits(3), invp, bridgep + integer :: winner + integer :: gas(3), selected(3) + real(8) :: vals(3), best + bids = [1d0, 2d0, 3d0] + call pga_all_pay(bids, 10d0, profits, winner) + if (winner /= 3) error stop 'winner' + if (abs(profits(1) + 1d0) > 1d-9) error stop 'loser pays' + if (abs(profits(3) - 7d0) > 1d-9) error stop 'winner profit' + gas = [4, 5, 9]; vals = [6d0, 7d0, 12d0] + call knapsack_select(vals, gas, 9, selected, best) + if (abs(best - 13d0) > 1d-9) error stop 'knapsack optimum' + call cross_chain_profit(105d0, 100d0, 0.5d0, 0.2d0, 0.1d0, 0.8d0, 2d0, invp, bridgep) + if (invp <= bridgep) error stop 'inventory latency advantage' + print *, 'MEV TESTS PASSED' +end program From 4335f9e72db84fc9445fb58ae15fef929e71b4bd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:04 -0700 Subject: [PATCH 025/156] M3: add src/tokenomics_engine.f90 --- .../sims/tokenomics/src/tokenomics_engine.f90 | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 new file mode 100644 index 0000000..a677a2f --- /dev/null +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -0,0 +1,53 @@ +module tokenomics_engine + implicit none +contains + pure real(8) function lending_rate(utilization, r0, slope1, slope2, uopt) result(r) + real(8), intent(in) :: utilization,r0,slope1,slope2,uopt + real(8) :: u + u=min(1d0,max(0d0,utilization)) + if (u<=uopt) then + r=r0+slope1*u + else + r=r0+slope1*uopt+slope2*(u-uopt) + end if + end function + + pure logical function stock_flow_conserved(circulating,staked,locked,burned,total,tol) result(ok) + real(8), intent(in) :: circulating,staked,locked,burned,total,tol + ok = abs((circulating+staked+locked+burned)-total) <= tol + end function + + subroutine euler_maruyama(x0, drift, sigma, dt, shocks, path) + real(8), intent(in) :: x0,drift,sigma,dt,shocks(:) + real(8), intent(out) :: path(size(shocks)+1) + integer :: i + path(1)=x0 + do i=1,size(shocks) + path(i+1)=path(i)+drift*dt+sigma*sqrt(max(dt,0d0))*shocks(i) + end do + end subroutine + + subroutine contagion_step(exposure, shock, propagated) + real(8), intent(in) :: exposure(:,:), shock(:) + real(8), intent(out) :: propagated(size(shock)) + propagated = shock + matmul(exposure, shock) + end subroutine + + subroutine yield_weights(apy, vol, risk_aversion, weights) + real(8), intent(in) :: apy(:),vol(:),risk_aversion + real(8), intent(out) :: weights(size(apy)) + real(8) :: score(size(apy)), total + score = max(0d0, apy-risk_aversion*vol*vol) + total=sum(score) + if (total<=1d-15) then + weights = 1d0/real(size(apy),8) + else + weights = score/total + end if + end subroutine + + pure real(8) function liquidation_shortfall(collateral,ltv,borrowed) result(shortfall) + real(8), intent(in) :: collateral,ltv,borrowed + shortfall=max(0d0,borrowed-collateral*ltv) + end function +end module From c820727b3c7c2a9d39f178bdaa3ba4074c84c87e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:07 -0700 Subject: [PATCH 026/156] M3: add test/test_tokenomics.f90 --- .../sims/tokenomics/test/test_tokenomics.f90 | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 core/src/economy/sims/tokenomics/test/test_tokenomics.f90 diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 new file mode 100644 index 0000000..dfb0460 --- /dev/null +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -0,0 +1,15 @@ +program test_tokenomics + use tokenomics_engine + implicit none + real(8) :: shock(3), exposure(3,3), propagated(3), w(3), apy(3), vol(3) + if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' + if (lending_rate(0.90d0,0.02d0,0.04d0,0.60d0,0.80d0) <= lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)) error stop 'kink slope' + if (.not. stock_flow_conserved(100d0,50d0,20d0,30d0,200d0,1d-9)) error stop 'conservation' + exposure = 0d0; exposure(2,1)=0.5d0; shock=[1d0,0d0,0d0] + call contagion_step(exposure, shock, propagated) + if (propagated(2) <= 0d0 .or. abs(propagated(3)) > 1d-12) error stop 'directional contagion' + apy=[0.04d0,0.08d0,0.06d0]; vol=[0.01d0,0.10d0,0.03d0] + call yield_weights(apy,vol,4d0,w) + if (abs(sum(w)-1d0)>1d-9) error stop 'weights normalize' + print *, 'TOKENOMICS TESTS PASSED' +end program From ad0a2eef67b5bf505808c7462aa710ceed42064f Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:09 -0700 Subject: [PATCH 027/156] M3: add tokenomics/fpm.toml --- core/src/economy/sims/tokenomics/fpm.toml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 core/src/economy/sims/tokenomics/fpm.toml diff --git a/core/src/economy/sims/tokenomics/fpm.toml b/core/src/economy/sims/tokenomics/fpm.toml new file mode 100644 index 0000000..19609ba --- /dev/null +++ b/core/src/economy/sims/tokenomics/fpm.toml @@ -0,0 +1,8 @@ +name = "sica-tokenomics-sim" +version = "0.1.0" +[library] +source-dir = "src" +[[test]] +name = "tokenomics" +source-dir = "test" +main = "test_tokenomics.f90" From 04e9a00b177e605dd80aa2f69cd7787b86104e15 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:11 -0700 Subject: [PATCH 028/156] M3: add src/microstructure_engine.f90 --- .../src/microstructure_engine.f90 | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 core/src/economy/sims/microstructure/src/microstructure_engine.f90 diff --git a/core/src/economy/sims/microstructure/src/microstructure_engine.f90 b/core/src/economy/sims/microstructure/src/microstructure_engine.f90 new file mode 100644 index 0000000..af077cd --- /dev/null +++ b/core/src/economy/sims/microstructure/src/microstructure_engine.f90 @@ -0,0 +1,69 @@ +module microstructure_engine + implicit none +contains + real(8) function slippage_buy(ask_prices, ask_qty, order_qty) result(slip) + real(8), intent(in) :: ask_prices(:), ask_qty(:), order_qty + real(8) :: remain, take, cost, filled, best, vwap + integer :: i + if (order_qty<=0d0) then; slip=0d0; return; end if + remain=order_qty; cost=0d0; filled=0d0; best=ask_prices(1) + do i=1,size(ask_prices) + if (remain<=0d0) exit + take=min(remain,ask_qty(i)); cost=cost+take*ask_prices(i); filled=filled+take; remain=remain-take + end do + if (filled<=0d0 .or. remain>1d-12) then + slip=huge(1d0) + else + vwap=cost/filled; slip=(vwap-best)/best + end if + end function + + pure real(8) function bid_ask_spread(best_bid,best_ask) result(s) + real(8), intent(in) :: best_bid,best_ask + s=max(0d0,best_ask-best_bid) + end function + + subroutine almgren_chriss_schedule(total_qty,n_buckets,lambda,eta,sigma,risk_aversion,schedule) + real(8), intent(in) :: total_qty,lambda,eta,sigma,risk_aversion + integer, intent(in) :: n_buckets + real(8), intent(out) :: schedule(n_buckets) + real(8) :: kappa, denom, x_prev, x_next, t_next + integer :: i + if (n_buckets<=0) return + if (total_qty<=0d0) then; schedule=0d0; return; end if + if (eta<=0d0 .or. risk_aversion<=0d0 .or. sigma<=0d0) then + schedule=1d0/real(n_buckets,8); return + end if + kappa=sqrt(max(1d-15,(risk_aversion*sigma*sigma+max(lambda,0d0))/eta)) + denom=sinh(kappa) + if (abs(denom)<1d-12) then + schedule=1d0/real(n_buckets,8); return + end if + x_prev=1d0 + do i=1,n_buckets + t_next=real(i,8)/real(n_buckets,8) + x_next=sinh(kappa*(1d0-t_next))/denom + schedule(i)=max(0d0,x_prev-x_next) + x_prev=x_next + end do + if (sum(schedule)>0d0) schedule=schedule/sum(schedule) + end subroutine + + pure real(8) function arb_gap_decay(initial_gap, elapsed, tau) result(gap) + real(8), intent(in) :: initial_gap,elapsed,tau + if (tau<=0d0) then + gap=0d0 + else + gap=initial_gap*exp(-max(0d0,elapsed)/tau) + end if + end function + + subroutine fit_linear_impact(order_flow,price_change,lambda) + real(8), intent(in) :: order_flow(:),price_change(:) + real(8), intent(out) :: lambda + real(8) :: mx,my,varx,cov + mx=sum(order_flow)/size(order_flow); my=sum(price_change)/size(price_change) + varx=sum((order_flow-mx)**2); cov=sum((order_flow-mx)*(price_change-my)) + if (varx<=1d-15) then; lambda=0d0; else; lambda=cov/varx; end if + end subroutine +end module From b0851bc320cead16450586d1ea34ba8ccbaebbb3 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:14 -0700 Subject: [PATCH 029/156] M3: add test/test_microstructure.f90 --- .../microstructure/test/test_microstructure.f90 | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 core/src/economy/sims/microstructure/test/test_microstructure.f90 diff --git a/core/src/economy/sims/microstructure/test/test_microstructure.f90 b/core/src/economy/sims/microstructure/test/test_microstructure.f90 new file mode 100644 index 0000000..7dfe173 --- /dev/null +++ b/core/src/economy/sims/microstructure/test/test_microstructure.f90 @@ -0,0 +1,15 @@ +program test_microstructure + use microstructure_engine + implicit none + real(8) :: prices(3), qty(3), s1, s2, sched(5), gap1, gap2 + prices=[100d0,101d0,103d0]; qty=[1d0,2d0,10d0] + s1=slippage_buy(prices,qty,1d0) + s2=slippage_buy(prices,qty,6d0) + if (s2 <= s1) error stop 'slippage monotonic' + call almgren_chriss_schedule(100d0,5,0.01d0,0.05d0,0.02d0,1d0,sched) + if (abs(sum(sched)-1d0)>1d-8) error stop 'schedule sums' + if (minval(sched) < 0d0) error stop 'schedule nonnegative' + gap1=arb_gap_decay(0.05d0,0d0,10d0); gap2=arb_gap_decay(0.05d0,20d0,10d0) + if (gap2 >= gap1) error stop 'arb decays' + print *, 'MICROSTRUCTURE TESTS PASSED' +end program From df2b01d5002a3f2c4004e42e3f8ea6e4f4f13146 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:16 -0700 Subject: [PATCH 030/156] M3: add microstructure/fpm.toml --- core/src/economy/sims/microstructure/fpm.toml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 core/src/economy/sims/microstructure/fpm.toml diff --git a/core/src/economy/sims/microstructure/fpm.toml b/core/src/economy/sims/microstructure/fpm.toml new file mode 100644 index 0000000..83d6469 --- /dev/null +++ b/core/src/economy/sims/microstructure/fpm.toml @@ -0,0 +1,8 @@ +name = "sica-microstructure-sim" +version = "0.1.0" +[library] +source-dir = "src" +[[test]] +name = "microstructure" +source-dir = "test" +main = "test_microstructure.f90" From 78592d4b0f3d7597aa3b90e03fa52988688e72a4 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:19 -0700 Subject: [PATCH 031/156] M3: add sims/registry.tcl --- core/src/economy/sims/registry.tcl | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core/src/economy/sims/registry.tcl diff --git a/core/src/economy/sims/registry.tcl b/core/src/economy/sims/registry.tcl new file mode 100644 index 0000000..ecc5945 --- /dev/null +++ b/core/src/economy/sims/registry.tcl @@ -0,0 +1,30 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::EngineRegistry { + variable root engines + constructor {root_dir} { + set root [file normalize $root_dir] + set engines [dict create statistical [dict create lang r runtime Rscript source statistical/engine.R test statistical/tests.R] sociological [dict create lang eclipse_prolog runtime eclipse source sociological/engine.ecl test sociological/test.ecl] amm_liquidity [dict create lang solidity runtime forge source amm/src/AMMSim.sol test amm/test/AMMSim.t.sol] mev_adversarial [dict create lang fortran runtime gfortran source mev/src/mev_engine.f90 test mev/test/test_mev.f90] tokenomics_macro [dict create lang fortran runtime gfortran source tokenomics/src/tokenomics_engine.f90 test tokenomics/test/test_tokenomics.f90] consensus_staking [dict create lang eclipse_prolog runtime eclipse source consensus/engine.ecl test consensus/test.ecl] market_microstructure [dict create lang fortran runtime gfortran source microstructure/src/microstructure_engine.f90 test microstructure/test/test_microstructure.f90]] + } + method names {} { return [dict keys $engines] } + method descriptor {name} { + if {![dict exists $engines $name]} { error "unknown_engine" } + set d [dict get $engines $name] + dict set d source [file join $root [dict get $d source]] + dict set d test [file join $root [dict get $d test]] + return $d + } + method source_present {name} { return [file exists [dict get [my descriptor $name] source]] } + method runtime_available {name} { + set cmd [dict get [my descriptor $name] runtime] + expr {[auto_execok $cmd] ne ""} + } + method status {} { + set out {} + foreach name [my names] { + set d [my descriptor $name] + dict set out $name [dict create lang [dict get $d lang] source_present [my source_present $name] runtime_available [my runtime_available $name]] + } + return $out + } +} From 56fa2c3850b89db22f0e1d505d8ed73731c5a352 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:22 -0700 Subject: [PATCH 032/156] M3: add sims/scheduler.tcl --- core/src/economy/sims/scheduler.tcl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 core/src/economy/sims/scheduler.tcl diff --git a/core/src/economy/sims/scheduler.tcl b/core/src/economy/sims/scheduler.tcl new file mode 100644 index 0000000..b92b77b --- /dev/null +++ b/core/src/economy/sims/scheduler.tcl @@ -0,0 +1,21 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::HorizonClock { + variable ratios simulated + constructor {} { + set ratios [dict create tick_hourly 90 daily 2160 weekly 15120 monthly 64800 annual 788000 five_year 3942000] + set simulated {} + dict for {h r} $ratios { dict set simulated $h 0.0 } + } + method horizons {} { return [dict keys $ratios] } + method ratio {horizon} { + if {![dict exists $ratios $horizon]} { error "unknown_horizon" } + return [dict get $ratios $horizon] + } + method advance {wall_seconds} { + if {![string is double -strict $wall_seconds] || $wall_seconds < 0} { error "invalid_wall_seconds" } + dict for {h r} $ratios { dict set simulated $h [expr {[dict get $simulated $h] + $wall_seconds*$r}] } + return $simulated + } + method state {} { return $simulated } +} From 36bfdd577230131bde7241cefd06656fb7b14f75 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:47:25 -0700 Subject: [PATCH 033/156] M3: add tests/hub_runtime.test --- core/src/economy/sims/tests/hub_runtime.test | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 core/src/economy/sims/tests/hub_runtime.test diff --git a/core/src/economy/sims/tests/hub_runtime.test b/core/src/economy/sims/tests/hub_runtime.test new file mode 100644 index 0000000..a37f4b5 --- /dev/null +++ b/core/src/economy/sims/tests/hub_runtime.test @@ -0,0 +1,46 @@ +package require tcltest 2 +namespace import ::tcltest::* +set here [file dirname [file normalize [info script]]] +source [file join $here .. registry.tcl] +source [file join $here .. scheduler.tcl] +set simsRoot [file normalize [file join $here ..]] + +test registry-seven-1.0 {all seven M3 engines are registered} -body { + set r [::stomach::EngineRegistry new $simsRoot] + set n [llength [$r names]] + $r destroy + set n +} -result 7 + +test registry-sources-1.0 {all registered engine sources are built into the tree} -body { + set r [::stomach::EngineRegistry new $simsRoot] + set present {} + foreach n [$r names] { lappend present [$r source_present $n] } + $r destroy + expr {[lsearch -exact $present 0] < 0} +} -result 1 + +test six-horizons-1.0 {scheduler contains all six concurrent horizon clocks} -body { + set c [::stomach::HorizonClock new] + set n [llength [$c horizons]] + $c destroy + set n +} -result 6 + +test minimum-speed-1.0 {no simulation horizon advances below the 90:1 base ratio} -body { + set c [::stomach::HorizonClock new] + set ok 1 + foreach h [$c horizons] { if {[$c ratio $h] < 90} { set ok 0 } } + $c destroy + set ok +} -result 1 + +test concurrent-advance-1.0 {one wall tick advances every horizon concurrently} -body { + set c [::stomach::HorizonClock new] + set st [$c advance 1.0] + set out [list [dict get $st tick_hourly] [dict get $st daily] [dict get $st five_year]] + $c destroy + set out +} -result {90.0 2160.0 3942000.0} + +cleanupTests From df7eea1b6db1102f6a56b844a4beb74ba4ad6426 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:12 -0700 Subject: [PATCH 034/156] M3: add statistical/engine.R --- core/src/economy/sims/statistical/engine.R | 91 ++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 core/src/economy/sims/statistical/engine.R diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R new file mode 100644 index 0000000..d2ba765 --- /dev/null +++ b/core/src/economy/sims/statistical/engine.R @@ -0,0 +1,91 @@ +# M3a statistical simulator kernels. Base R only; no Python bridge. +clamp <- function(x, lo, hi) pmin(hi, pmax(lo, x)) + +gbm_terminal <- function(s0, mu, sigma, dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, sigma >= 0, dt > 0, steps >= 1, paths >= 2) + set.seed(seed) + z <- matrix(rnorm(steps * paths), nrow=steps) + lr <- (mu - 0.5 * sigma^2) * dt + sigma * sqrt(dt) * z + s0 * exp(colSums(lr)) +} + +merton_terminal <- function(s0, mu, sigma, lambda, jump_mu, jump_sigma, dt, steps, paths, seed=1L) { + stopifnot(lambda >= 0, jump_sigma >= 0) + set.seed(seed) + z <- matrix(rnorm(steps * paths), nrow=steps) + n <- matrix(rpois(steps * paths, lambda * dt), nrow=steps) + jumps <- matrix(rnorm(steps * paths, jump_mu, jump_sigma), nrow=steps) * n + drift <- (mu - 0.5*sigma^2 - lambda*(exp(jump_mu + 0.5*jump_sigma^2)-1)) * dt + s0 * exp(colSums(drift + sigma*sqrt(dt)*z + jumps)) +} + +heston_terminal <- function(s0, v0, mu, kappa, theta, xi, rho, dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, v0 >= 0, kappa >= 0, theta >= 0, xi >= 0, abs(rho) <= 1) + set.seed(seed); s <- rep(s0, paths); v <- rep(v0, paths) + for (i in seq_len(steps)) { + z1 <- rnorm(paths); z2 <- rho*z1 + sqrt(max(0, 1-rho^2))*rnorm(paths) + vp <- pmax(v, 0) + s <- s * exp((mu - 0.5*vp)*dt + sqrt(vp*dt)*z1) + v <- pmax(v + kappa*(theta-vp)*dt + xi*sqrt(vp*dt)*z2, 0) + } + s +} + +garch11_fit <- function(r) { + r <- as.numeric(r); stopifnot(length(r) >= 20) + v0 <- var(r) + nll <- function(p) { + omega <- exp(p[1]); alpha <- plogis(p[2]); beta <- plogis(p[3])*(1-alpha) + h <- numeric(length(r)); h[1] <- max(v0, 1e-12) + for (i in 2:length(r)) h[i] <- max(1e-12, omega + alpha*r[i-1]^2 + beta*h[i-1]) + 0.5*sum(log(h) + r^2/h) + } + opt <- optim(c(log(max(v0*0.05,1e-12)), qlogis(0.1), qlogis(0.85/0.9)), nll) + alpha <- plogis(opt$par[2]); beta <- plogis(opt$par[3])*(1-alpha) + list(omega=exp(opt$par[1]), alpha=alpha, beta=beta) +} + +hurst_rs <- function(x) { + x <- as.numeric(x); n <- length(x); stopifnot(n >= 32) + scales <- c(4,8,16,32); scales <- scales[scales <= n/2] + rs <- sapply(scales, function(m) { + chunks <- split(x[seq_len(floor(n/m)*m)], rep(seq_len(floor(n/m)), each=m)) + vals <- sapply(chunks, function(y) { z <- cumsum(y-mean(y)); sdv <- sd(y); if (sdv==0) NA else (max(z)-min(z))/sdv }) + mean(vals, na.rm=TRUE) + }) + unname(coef(lm(log(rs) ~ log(scales)))[2]) +} + +regime_state <- function(returns) { + m <- mean(returns); s <- sd(returns) + if (!is.finite(s) || s == 0) return("neutral") + if (m > 0.25*s) "bull" else if (m < -0.25*s) "bear" else "neutral" +} + +bounded_price_prediction <- function(s0, mu, sigma, dt, steps, paths=4000L, seed=1L, horizon="24h", ticker="ASSET") { + sims <- gbm_terminal(s0, mu, sigma, dt, steps, paths, seed) + q <- as.numeric(quantile(sims, c(.025,.5,.975), names=FALSE)) + width <- (q[3]-q[1])/max(q[2],1e-12) + list(value=q[2], lower_bound=q[1], upper_bound=q[3], confidence=clamp(10-5*width,0,10), correctness=5, certainty=clamp(10-8*width,0,10), time_horizon=horizon, sim_type="statistical", token_ticker=ticker, recent_shift=0) +} + +json_number <- function(line, key, default) { + pat <- paste0('"', key, '"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)') + m <- regexec(pat, line, perl=TRUE); z <- regmatches(line,m)[[1]] + if (length(z) < 2) default else as.numeric(z[2]) +} +json_string <- function(line, key, default) { + pat <- paste0('"', key, '"[[:space:]]*:[[:space:]]*"([^"]*)"') + m <- regexec(pat, line, perl=TRUE); z <- regmatches(line,m)[[1]] + if (length(z) < 2) default else z[2] +} +emit_prediction <- function(p) { + cat(sprintf('{"value":%.10g,"lower_bound":%.10g,"upper_bound":%.10g,"confidence":%.4f,"correctness":%.4f,"certainty":%.4f,"time_horizon":"%s","sim_type":"statistical","token_ticker":"%s","recent_shift":%.10g}\n', p$value,p$lower_bound,p$upper_bound,p$confidence,p$correctness,p$certainty,p$time_horizon,p$token_ticker,p$recent_shift)) +} +main <- function() { + line <- readLines(file("stdin"), n=1, warn=FALSE) + if (!length(line)) quit(status=2) + p <- bounded_price_prediction(json_number(line,"spot",100), json_number(line,"mu",0), json_number(line,"sigma",0.2), json_number(line,"dt",1/365), as.integer(json_number(line,"steps",1)), as.integer(json_number(line,"paths",4000)), as.integer(json_number(line,"seed",1)), json_string(line,"time_horizon","24h"), json_string(line,"token_ticker","ASSET")) + emit_prediction(p) +} +if (sys.nframe() == 0) main() From d472c25c5729a14009d69b265960b0362b62540d Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:15 -0700 Subject: [PATCH 035/156] M3: add statistical/tests.R --- core/src/economy/sims/statistical/tests.R | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 core/src/economy/sims/statistical/tests.R diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R new file mode 100644 index 0000000..6b050ef --- /dev/null +++ b/core/src/economy/sims/statistical/tests.R @@ -0,0 +1,16 @@ +args <- commandArgs(trailingOnly=FALSE); f <- sub("^--file=", "", args[grep("^--file=", args)]) +source(file.path(dirname(normalizePath(f)), "engine.R")) +x <- gbm_terminal(100,0.05,0.2,1/252,252,20000,7) +expected <- 100*exp(0.05) +stopifnot(abs(mean(x)-expected)/expected < 0.02) +j <- merton_terminal(100,0.05,0.15,2,-0.08,0.15,1/252,252,10000,9) +kurtosis <- mean((j-mean(j))^4)/(var(j)^2) +stopifnot(kurtosis > 3) +h <- heston_terminal(100,0.04,0.03,2,0.04,0.3,-0.6,1/252,252,5000,3) +stopifnot(all(h > 0)) +set.seed(12) +r <- c(rnorm(100,0,.01), rnorm(100,0,.05)); fit <- garch11_fit(r) +stopifnot(fit$alpha >= 0, fit$beta >= 0, fit$alpha+fit$beta < 1) +p <- bounded_price_prediction(100,.03,.2,1/365,30,5000,4,"30d","TEST") +stopifnot(p$lower_bound <= p$value, p$value <= p$upper_bound) +cat("STATISTICAL TESTS PASSED\n") From efe1d58449d30ca2cf3b281a795c1bad5e81c245 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:17 -0700 Subject: [PATCH 036/156] M3: add sociological/engine.ecl --- core/src/economy/sims/sociological/engine.ecl | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core/src/economy/sims/sociological/engine.ecl diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl new file mode 100644 index 0000000..c7f9ddc --- /dev/null +++ b/core/src/economy/sims/sociological/engine.ecl @@ -0,0 +1,40 @@ +% M3b sociological simulator kernels for ECLiPSe Prolog 7.2. + +sum_list([], 0.0). +sum_list([X|Xs], S) :- sum_list(Xs, T), S is X + T. + +normalize([], []). +normalize(Xs, Ys) :- sum_list(Xs, S), S > 0, normalize_(Xs, S, Ys). +normalize_([], _, []). +normalize_([X|Xs], S, [Y|Ys]) :- Y is X/S, normalize_(Xs,S,Ys). + +weighted_mean([], [], 0.0). +weighted_mean([X|Xs],[P|Ps], M) :- weighted_mean(Xs,Ps,T), M is T + X*P. + +replicator_step(Shares, Payoffs, Dt, Next) :- + weighted_mean(Payoffs, Shares, Avg), + replicator_raw(Shares,Payoffs,Avg,Dt,Raw), normalize(Raw,Next). +replicator_raw([],[],_,_,[]). +replicator_raw([X|Xs],[P|Ps],Avg,Dt,[Y|Ys]) :- + Y0 is X + Dt*X*(P-Avg), (Y0 < 0 -> Y = 0 ; Y = Y0), + replicator_raw(Xs,Ps,Avg,Dt,Ys). + +hk_step(Opinions, Bound, Mu, Next) :- hk_all(Opinions,Opinions,Bound,Mu,Next). +hk_all([],_,_,_,[]). +hk_all([X|Xs],All,D,Mu,[Y|Ys]) :- neighbor_mean(All,X,D,M), Y is X + Mu*(M-X), hk_all(Xs,All,D,Mu,Ys). +neighbor_mean(All,X,D,M) :- collect_neighbors(All,X,D,Ns), sum_list(Ns,S), length(Ns,N), N > 0, M is S/N. +collect_neighbors([],_,_,[]). +collect_neighbors([Y|Ys],X,D,[Y|Ns]) :- abs(Y-X) =< D, !, collect_neighbors(Ys,X,D,Ns). +collect_neighbors([_|Ys],X,D,Ns) :- collect_neighbors(Ys,X,D,Ns). + +complex_contagion(Exposures, Degrees, Thresholds, Adoption) :- contagion_(Exposures,Degrees,Thresholds,Adoption). +contagion_([],[],[],[]). +contagion_([E|Es],[D|Ds],[T|Ts],[A|As]) :- + (D =< 0 -> Frac=0 ; Frac is E/D), + (Frac >= T -> A=1 ; A=0), contagion_(Es,Ds,Ts,As). + +pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase) :- + (VolumeRatio > 2.0, Sentiment > 0.6, PriceDelta > 0.05 -> Phase=promotion ; + VolumeRatio > 2.0, PriceDelta < -0.05 -> Phase=collapse ; + VolumeRatio > 1.5, PriceDelta >= 0 -> Phase=distribution ; + Phase=accumulation). From c5df535b43b08450ef744b23f4e468805ae57a0c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:20 -0700 Subject: [PATCH 037/156] M3: add sociological/test.ecl --- core/src/economy/sims/sociological/test.ecl | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 core/src/economy/sims/sociological/test.ecl diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl new file mode 100644 index 0000000..574180f --- /dev/null +++ b/core/src/economy/sims/sociological/test.ecl @@ -0,0 +1,8 @@ +:- [engine]. +run :- + replicator_step([0.5,0.5],[2.0,1.0],0.2,N), N=[A,B], A > B, + hk_step([0.0,0.1,0.9,1.0],0.2,1.0,H), H=[H1,H2,H3,H4], H1 < 0.2, H4 > 0.8, + complex_contagion([1,3],[4,4],[0.5,0.5],Ad), Ad=[0,1], + pump_phase(0.1,3.0,0.9,promotion), + writeln('SOCIOLOGICAL TESTS PASSED'). +:- local initialization(run). From e8a162a2be5069970b56589d0f5f9ee65c87dd09 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:22 -0700 Subject: [PATCH 038/156] M3: add consensus/engine.ecl --- core/src/economy/sims/consensus/engine.ecl | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 core/src/economy/sims/consensus/engine.ecl diff --git a/core/src/economy/sims/consensus/engine.ecl b/core/src/economy/sims/consensus/engine.ecl new file mode 100644 index 0000000..ae23dbb --- /dev/null +++ b/core/src/economy/sims/consensus/engine.ecl @@ -0,0 +1,25 @@ +% M3f consensus/staking simulator kernels for ECLiPSe Prolog 7.2. + +honesty_step(Honest, HonestPayoff, AttackPayoff, Dt, Next) :- + Avg is Honest*HonestPayoff + (1-Honest)*AttackPayoff, + N0 is Honest + Dt*Honest*(HonestPayoff-Avg), + (N0 < 0 -> Next=0 ; N0 > 1 -> Next=1 ; Next=N0). + +required_slash_probability(HonestReward, AttackGain, SlashPenalty, P) :- + SlashPenalty > 0, + P0 is (AttackGain-HonestReward)/SlashPenalty, + (P0 < 0 -> P=0 ; P0 > 1 -> P=1 ; P=P0). + +markov_step(Dist, Matrix, Next) :- transpose(Matrix, T), dot_rows(T,Dist,Next). +dot_rows([],_,[]). +dot_rows([R|Rs],D,[X|Xs]) :- dot(R,D,X), dot_rows(Rs,D,Xs). +dot([],[],0.0). +dot([A|As],[B|Bs],X) :- dot(As,Bs,T), X is T+A*B. +transpose([],[]). +transpose([[]|_],[]) :- !. +transpose(M,[R|Rs]) :- heads_tails(M,R,T), transpose(T,Rs). +heads_tails([],[],[]). +heads_tails([[H|T]|Rows],[H|Hs],[T|Ts]) :- heads_tails(Rows,Hs,Ts). + +consensus_liveness(HonestFraction, Threshold, Liveness) :- + (HonestFraction >= Threshold -> Liveness=1.0 ; HonestFraction =< 0 -> Liveness=0.0 ; Liveness is HonestFraction/Threshold). From 1f3f1e42aabdafa953a745f960be4114c55cab10 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:25 -0700 Subject: [PATCH 039/156] M3: add consensus/test.ecl --- core/src/economy/sims/consensus/test.ecl | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 core/src/economy/sims/consensus/test.ecl diff --git a/core/src/economy/sims/consensus/test.ecl b/core/src/economy/sims/consensus/test.ecl new file mode 100644 index 0000000..2771d74 --- /dev/null +++ b/core/src/economy/sims/consensus/test.ecl @@ -0,0 +1,8 @@ +:- [engine]. +run :- + honesty_step(0.5,2.0,1.0,0.2,H), H > 0.5, + required_slash_probability(2.0,5.0,10.0,P), abs(P-0.3) < 0.000001, + markov_step([1.0,0.0],[[0.9,0.1],[0.2,0.8]],N), N=[A,B], abs(A-0.9)<0.000001, abs(B-0.1)<0.000001, + consensus_liveness(0.5,0.67,L), L < 1.0, + writeln('CONSENSUS TESTS PASSED'). +:- local initialization(run). From af4dab005860573ed48c50372e742613a6a736f7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:27 -0700 Subject: [PATCH 040/156] M3: add src/AMMSim.sol --- core/src/economy/sims/amm/src/AMMSim.sol | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 core/src/economy/sims/amm/src/AMMSim.sol diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol new file mode 100644 index 0000000..a9781ea --- /dev/null +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; + +library AMMSim { + uint256 internal constant WAD = 1e18; + uint256 internal constant BPS = 10_000; + + function amountOut(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256 dy) { + require(x > 0 && y > 0 && dx > 0 && feeBps < BPS, "bad pool"); + uint256 dxEff = dx * (BPS - feeBps) / BPS; + dy = y * dxEff / (x + dxEff); + require(dy < y, "drain"); + } + + function sqrt(uint256 a) internal pure returns (uint256 z) { + if (a == 0) return 0; + z = 1 << ((log2(a) + 1) >> 1); + unchecked { + for (uint256 i=0; i<7; ++i) z = (z + a/z) >> 1; + uint256 z1 = a/z; + if (z1 < z) z = z1; + } + } + function log2(uint256 x) internal pure returns (uint256 r) { + while (x > 1) { x >>= 1; ++r; } + } + + function impermanentLossWad(uint256 ratioWad) internal pure returns (int256) { + require(ratioWad > 0, "ratio"); + uint256 rootWad = sqrt(ratioWad * WAD); + uint256 relativeWad = 2 * rootWad * WAD / (WAD + ratioWad); + return int256(relativeWad) - int256(WAD); + } + + function slippageWad(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256) { + uint256 dy = amountOut(x,y,dx,feeBps); + uint256 spotWad = y * WAD / x; + uint256 execWad = dy * WAD / dx; + return execWad >= spotWad ? 0 : (spotWad-execWad)*WAD/spotWad; + } + + function lpShouldWithdraw(uint256 feeIncomeWad, uint256 ratioWad) internal pure returns (bool) { + int256 il = impermanentLossWad(ratioWad); + uint256 loss = il < 0 ? uint256(-il) : 0; + return loss > feeIncomeWad; + } +} From 390f736989ed19cca02d02729d4de47423ed9aa2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:30 -0700 Subject: [PATCH 041/156] M3: add test/AMMSim.t.sol --- core/src/economy/sims/amm/test/AMMSim.t.sol | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 core/src/economy/sims/amm/test/AMMSim.t.sol diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol new file mode 100644 index 0000000..b2d43d6 --- /dev/null +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; +import "../src/AMMSim.sol"; +contract AMMSimTest { + function testInvariantDirection() public pure { + uint256 x=1000e18; uint256 y=1000e18; uint256 dx=10e18; + uint256 dy=AMMSim.amountOut(x,y,dx,30); + require(dy>0 && dy= x*y, "k lower by rounding"); + } + function testImpermanentLossKnownRatio() public pure { + int256 il=AMMSim.impermanentLossWad(4e18); + int256 expected=-2e17; + int256 d=il-expected; if (d<0) d=-d; + require(d < 1e10, "IL formula"); + } + function testSlippageGrowsWithSize() public pure { + uint256 a=AMMSim.slippageWad(1000e18,1000e18,1e18,30); + uint256 b=AMMSim.slippageWad(1000e18,1000e18,100e18,30); + require(b>a, "slippage"); + } + function testWithdrawalDerivedFromIL() public pure { + require(AMMSim.lpShouldWithdraw(1e16,4e18), "withdraw"); + require(!AMMSim.lpShouldWithdraw(3e17,4e18), "stay"); + } +} From 8a442c77d737c12668f7936e05516dd39416e85d Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:48:32 -0700 Subject: [PATCH 042/156] M3: add amm/foundry.toml --- core/src/economy/sims/amm/foundry.toml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 core/src/economy/sims/amm/foundry.toml diff --git a/core/src/economy/sims/amm/foundry.toml b/core/src/economy/sims/amm/foundry.toml new file mode 100644 index 0000000..3ede138 --- /dev/null +++ b/core/src/economy/sims/amm/foundry.toml @@ -0,0 +1,6 @@ +[profile.default] +src = "src" +test = "test" +solc_version = "0.8.24" +optimizer = true +optimizer_runs = 200 From 255b927694b3abfaaab145bb0c7c967b4037c7ed Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:49:29 -0700 Subject: [PATCH 043/156] M3: expose native engine registry and horizon clocks through M0 --- core/src/economy/stomach.tcl | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index 235bdd0..96625f5 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -1,15 +1,20 @@ # M0 stomach/economy organ composition for sica-fondt. -# Tcl 8.6, external-dependency free. This scaffold is simulation-only: no RPC, -# signing, or private-key surface exists yet. -namespace eval ::stomach { variable version 0.1 } +# The stomach is an OUTER organ. Market execution remains simulation-only here; +# M3's native engines are registered as subordinate simulation processes. +namespace eval ::stomach { variable version 0.2; variable root } set __stomach_dir [file dirname [file normalize [info script]]] -foreach __stomach_file {traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl sims/hub.tcl marketplace.tcl} { +set ::stomach::root $__stomach_dir +foreach __stomach_file { + traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl + sims/registry.tcl sims/scheduler.tcl sims/hub.tcl + marketplace.tcl +} { source [file join $__stomach_dir $__stomach_file] } unset __stomach_file oo::class create ::stomach::Economy { - variable traders wallets sae conductor feeds sims market taxes + variable traders wallets sae conductor feeds sims registry clock market taxes constructor {args} { set cap 256 if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } @@ -25,11 +30,15 @@ oo::class create ::stomach::Economy { set conductor [::stomach::Conductor new $traders] set feeds [::stomach::Feeds new $cap] set sims [::stomach::SimsHub new] + set registry [::stomach::EngineRegistry new [file join $::stomach::root sims]] + set clock [::stomach::HorizonClock new] set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set taxes {} } destructor { - foreach obj [list $market $sims $feeds $conductor $sae $wallets $traders] { catch {$obj destroy} } + foreach obj [list $market $clock $registry $sims $feeds $conductor $sae $wallets $traders] { + catch {$obj destroy} + } } method register_trader {id specialization} { return [$traders register $id $specialization] } method bind_wallet {wallet_id trader_id daily_limit per_action_limit} { @@ -48,6 +57,10 @@ oo::class create ::stomach::Economy { method feed_history {feed_type} { return [$feeds history $feed_type] } method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } method query_predictions {trader_id sim_type} { return [$market predictions $trader_id $sim_type] } + method sim_engines {} { return [$registry names] } + method sim_engine_status {} { return [$registry status] } + method sim_horizons {} { return [$clock horizons] } + method sim_advance {wall_seconds} { return [$clock advance $wall_seconds] } method tax_event {trader_id amount source_wallet dest_wallet} { if {![string is double -strict $amount] || $amount < 0} { error "invalid_tax_amount" } set receipt [dict create receipt_id [format "tax-%06d" [expr {[llength $taxes] + 1}]] status staged transferred 0 trader_id $trader_id amount $amount source_wallet $source_wallet dest_wallet $dest_wallet] @@ -55,7 +68,7 @@ oo::class create ::stomach::Economy { return $receipt } method secretion {} { - return [dict create source stomach destination ada_border provenance organ_secretion live_execution 0 traders [$traders count] wallets [$wallets count] predictions [$sims count] executions [$market execution_count] paused_traders [$traders paused_count] tax_receipts [llength $taxes]] + return [dict create source stomach destination ada_border provenance organ_secretion live_execution 0 traders [$traders count] wallets [$wallets count] sim_engines [llength [$registry names]] predictions [$sims count] executions [$market execution_count] paused_traders [$traders paused_count] tax_receipts [llength $taxes]] } method sae_log {} { return [$sae log] } method decision_log {} { return [$conductor log] } From f89034807ef58b7a555182588fdb3125660c2b0c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:49:36 -0700 Subject: [PATCH 044/156] test: expose seven simulator engines through stomach --- core/src/economy/tests/stomach.test | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/core/src/economy/tests/stomach.test b/core/src/economy/tests/stomach.test index 4b72771..4d4a8b1 100644 --- a/core/src/economy/tests/stomach.test +++ b/core/src/economy/tests/stomach.test @@ -136,4 +136,31 @@ test secretion-1.0 {M0 produces an Ada-bound organ secretion summary} -body { set out } -result {stomach ada_border organ_secretion 0} +test sim-engine-registry-1.0 {M0 exposes all seven built-in M3 engine identities} -body { + set s [new_stomach] + set n [llength [$s sim_engines]] + $s destroy + set n +} -result 7 + +test sim-engine-sources-1.0 {all seven registered native engine sources are present in the organ tree} -body { + set s [new_stomach] + set status [$s sim_engine_status] + set ok 1 + dict for {name state} $status { + if {![dict get $state source_present]} { set ok 0 } + } + $s destroy + set ok +} -result 1 + +test sim-six-horizons-1.0 {M0 advances all six forecast clocks and preserves 90:1 minimum speed} -body { + set s [new_stomach] + set horizons [$s sim_horizons] + set state [$s sim_advance 1.0] + set out [list [llength $horizons] [dict get $state tick_hourly] [dict get $state five_year]] + $s destroy + set out +} -result {6 90.0 3942000.0} + cleanupTests From 2e95fb0ebe5982aedd68df2aa63fafe2bd52a088 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:52:22 -0700 Subject: [PATCH 045/156] M3: make six-horizon scheduler a running Tcl clock --- core/src/economy/sims/scheduler.tcl | 33 +++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/scheduler.tcl b/core/src/economy/sims/scheduler.tcl index b92b77b..dfbebe5 100644 --- a/core/src/economy/sims/scheduler.tcl +++ b/core/src/economy/sims/scheduler.tcl @@ -1,12 +1,17 @@ namespace eval ::stomach {} oo::class create ::stomach::HorizonClock { - variable ratios simulated + variable ratios simulated is_running after_id last_ms interval_ms constructor {} { set ratios [dict create tick_hourly 90 daily 2160 weekly 15120 monthly 64800 annual 788000 five_year 3942000] set simulated {} dict for {h r} $ratios { dict set simulated $h 0.0 } + set is_running 0 + set after_id "" + set last_ms 0 + set interval_ms 1000 } + destructor { my stop } method horizons {} { return [dict keys $ratios] } method ratio {horizon} { if {![dict exists $ratios $horizon]} { error "unknown_horizon" } @@ -14,8 +19,32 @@ oo::class create ::stomach::HorizonClock { } method advance {wall_seconds} { if {![string is double -strict $wall_seconds] || $wall_seconds < 0} { error "invalid_wall_seconds" } - dict for {h r} $ratios { dict set simulated $h [expr {[dict get $simulated $h] + $wall_seconds*$r}] } + dict for {h r} $ratios { + dict set simulated $h [expr {[dict get $simulated $h] + $wall_seconds*$r}] + } return $simulated } + method start {{pulse_ms 1000}} { + if {![string is integer -strict $pulse_ms] || $pulse_ms < 1} { error "invalid_pulse_ms" } + if {$is_running} { return } + set interval_ms $pulse_ms + set is_running 1 + set last_ms [clock milliseconds] + set after_id [after $interval_ms [list [self] pulse]] + } + method pulse {} { + if {!$is_running} { return } + set now [clock milliseconds] + set elapsed [expr {double($now-$last_ms)/1000.0}] + set last_ms $now + my advance $elapsed + set after_id [after $interval_ms [list [self] pulse]] + } + method stop {} { + if {$after_id ne ""} { after cancel $after_id } + set after_id "" + set is_running 0 + } + method running {} { return $is_running } method state {} { return $simulated } } From e7b0c1d8d03ad62de4765cbdf163e0e1cbc1934a Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:52:25 -0700 Subject: [PATCH 046/156] test: verify always-running M3 horizon clock --- core/src/economy/sims/tests/hub_runtime.test | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/core/src/economy/sims/tests/hub_runtime.test b/core/src/economy/sims/tests/hub_runtime.test index a37f4b5..b7d06a9 100644 --- a/core/src/economy/sims/tests/hub_runtime.test +++ b/core/src/economy/sims/tests/hub_runtime.test @@ -43,4 +43,27 @@ test concurrent-advance-1.0 {one wall tick advances every horizon concurrently} set out } -result {90.0 2160.0 3942000.0} +test clock-start-stop-1.0 {horizon clock is a live event-loop clock, not just a counter} -body { + set c [::stomach::HorizonClock new] + set before [$c running] + $c start 10 + set during [$c running] + $c stop + set after [$c running] + $c destroy + list $before $during $after +} -result {0 1 0} + +test clock-pulse-1.0 {a running clock advances simulated time from wall time} -body { + set c [::stomach::HorizonClock new] + $c start 10 + after 30 {set ::m3_clock_done 1} + vwait ::m3_clock_done + unset ::m3_clock_done + set st [$c state] + $c stop + $c destroy + expr {[dict get $st tick_hourly] > 0} +} -result 1 + cleanupTests From 1355bf0697ebce0337eb21c82b67345f8c5ea90e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:52:37 -0700 Subject: [PATCH 047/156] M3: start horizon clock with stomach runtime --- core/src/economy/stomach.tcl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index 96625f5..d4b2082 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -32,6 +32,7 @@ oo::class create ::stomach::Economy { set sims [::stomach::SimsHub new] set registry [::stomach::EngineRegistry new [file join $::stomach::root sims]] set clock [::stomach::HorizonClock new] + $clock start set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set taxes {} } @@ -60,6 +61,7 @@ oo::class create ::stomach::Economy { method sim_engines {} { return [$registry names] } method sim_engine_status {} { return [$registry status] } method sim_horizons {} { return [$clock horizons] } + method sim_running {} { return [$clock running] } method sim_advance {wall_seconds} { return [$clock advance $wall_seconds] } method tax_event {trader_id amount source_wallet dest_wallet} { if {![string is double -strict $amount] || $amount < 0} { error "invalid_tax_amount" } From 1cc3edaa27f06cd48b0c93b1b57fe683317dcf59 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:52:52 -0700 Subject: [PATCH 048/156] test: assert M3 scheduler runs with stomach --- core/src/economy/tests/stomach.test | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/src/economy/tests/stomach.test b/core/src/economy/tests/stomach.test index 4d4a8b1..bb9387d 100644 --- a/core/src/economy/tests/stomach.test +++ b/core/src/economy/tests/stomach.test @@ -163,4 +163,11 @@ test sim-six-horizons-1.0 {M0 advances all six forecast clocks and preserves 90: set out } -result {6 90.0 3942000.0} +test sim-clock-running-1.0 {M3 horizon scheduler starts with the stomach} -body { + set s [new_stomach] + set running [$s sim_running] + $s destroy + set running +} -result 1 + cleanupTests From 7240eefc619e9c488dadd13910e6933234a32c52 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:53:08 -0700 Subject: [PATCH 049/156] test: add polyglot M3 engine driver --- core/src/economy/sims/run_tests.tcl | 78 +++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core/src/economy/sims/run_tests.tcl diff --git a/core/src/economy/sims/run_tests.tcl b/core/src/economy/sims/run_tests.tcl new file mode 100644 index 0000000..a22ab03 --- /dev/null +++ b/core/src/economy/sims/run_tests.tcl @@ -0,0 +1,78 @@ +# Polyglot M3 test driver. Missing externally hosted runtimes are reported as +# SKIP by default; pass --strict to make a missing runtime fail the run. +set here [file dirname [file normalize [info script]]] +set strict [expr {[lsearch -exact $argv --strict] >= 0}] +set failures 0 +set skipped 0 + +proc have {cmd} { expr {[auto_execok $cmd] ne ""} } +proc run_cmd {label cwd cmd} { + global failures + puts "=== $label ===" + set old [pwd] + cd $cwd + set code [catch {exec {*}$cmd 2>@1} out opts] + cd $old + if {$out ne ""} { puts $out } + if {$code} { + incr failures + puts "FAIL: $label" + return 0 + } + if {[string match "*Failed*" $out] && ![regexp {Failed[[:space:]]+0} $out]} { + incr failures + puts "FAIL: $label reported test failures" + return 0 + } + puts "PASS: $label" + return 1 +} +proc require_runtime {label cmd} { + global strict failures skipped + if {[have $cmd]} { return 1 } + if {$strict} { + incr failures + puts "FAIL: $label runtime '$cmd' missing" + } else { + incr skipped + puts "SKIP: $label runtime '$cmd' missing" + } + return 0 +} + +run_cmd "M3 hub registry + clocks" [file join $here tests] [list tclsh hub_runtime.test] + +set build /tmp/sica-m3-build +file mkdir $build +foreach spec { + {M3d-MEV mev mev_engine.f90 test_mev.f90} + {M3e-tokenomics tokenomics tokenomics_engine.f90 test_tokenomics.f90} + {M3g-microstructure microstructure microstructure_engine.f90 test_microstructure.f90} +} { + lassign $spec label dir engine test + if {[require_runtime $label gfortran]} { + set exe [file join $build $dir-test] + set src [file join $here $dir src $engine] + set tst [file join $here $dir test $test] + if {[run_cmd "$label compile" $here [list gfortran -std=f2018 -Wall -Wextra -Werror -pedantic -J $build $src $tst -o $exe]]} { + run_cmd "$label executable" $here [list $exe] + } + } +} + +if {[require_runtime M3a-statistical Rscript]} { + run_cmd M3a-statistical [file join $here statistical] [list Rscript tests.R] +} +if {[require_runtime M3b-sociological eclipse]} { + run_cmd M3b-sociological [file join $here sociological] [list eclipse -b test.ecl -e halt] +} +if {[require_runtime M3f-consensus eclipse]} { + run_cmd M3f-consensus [file join $here consensus] [list eclipse -b test.ecl -e halt] +} +if {[require_runtime M3c-AMM forge]} { + run_cmd M3c-AMM [file join $here amm] [list forge test] +} + +puts "=== M3 RESULT ===" +puts "failures=$failures skipped=$skipped strict=$strict" +exit [expr {$failures > 0 ? 1 : 0}] From 745785d1f87b3df7d713995ce572b7eb755bafe7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:53:56 -0700 Subject: [PATCH 050/156] docs: mark M3-sims-hub.md kernel implemented --- core/docs/plans/M3-sims-hub.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/core/docs/plans/M3-sims-hub.md b/core/docs/plans/M3-sims-hub.md index d4b4573..2b323fe 100644 --- a/core/docs/plans/M3-sims-hub.md +++ b/core/docs/plans/M3-sims-hub.md @@ -12,9 +12,12 @@ The academic foundations span AMM mechanism design [1,2], MEV game theory [3,4,5 tokenomics via SDEs [6,7], and evolutionary consensus games [8–11]. ## 2. Status / certainty -SCAFFOLD · EXECUTABLE HUB STATE. `core/src/economy/sims/hub.tcl` validates bounded -predictions and exposes current per-sim state. The continuous scheduler and M3a–M3g engines -remain open. Role C3; scaffold C2. Mathematical foundations C4; parameters C1. +EXECUTABLE KERNEL SET. `core/src/economy/sims/` now contains all seven native engine +trees (M3a–M3g), a seven-engine registry, and a live Tcl event-loop scheduler for all six +horizons at the specified 90:1-or-faster ratios. The hub still validates/publishes bounded +predictions. Advanced model layers called out in the individual sub-specs remain incremental +work; the simulator family is no longer absent. Role C3; kernel implementation C2. +Mathematical foundations C4; live-market parameterization C1. ## 3. Language & location **Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages From 124b5f835822411f3064000557d3b24529fb3e6f Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:53:58 -0700 Subject: [PATCH 051/156] docs: mark M3a-statistical-sims.md kernel implemented --- core/docs/plans/M3a-statistical-sims.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/docs/plans/M3a-statistical-sims.md b/core/docs/plans/M3a-statistical-sims.md index 9bd5d41..ab3e8d8 100644 --- a/core/docs/plans/M3a-statistical-sims.md +++ b/core/docs/plans/M3a-statistical-sims.md @@ -8,12 +8,12 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math **stochastic sample paths**, not behavioral agents. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Core quant methods C5 (GBM, GARCH, ARIMA — textbook). Heston stochastic -volatility C5 (closed-form characteristic function; industry standard since 1993). Rough -volatility C4 (Gatheral et al. 2018, heavily cited; crypto implementations exist). HMM regime -detection C4 (established; crypto-specific copula hybrids emerging 2023–2024). Almgren-Chriss -execution C5 (industry standard since 2001). Jump-diffusion C5 (Merton 1976). Parameterization -for crypto markets C1. +KERNEL IMPLEMENTED · R. `core/src/economy/sims/statistical/engine.R` contains GBM Monte +Carlo, Merton jump-diffusion, Heston full-truncation simulation, GARCH(1,1) QMLE, a rolling +Hurst estimator, regime classification, bounded Monte Carlo price predictions, and hand-rolled +JSON stdin/stdout. Native tests are in `tests.R`. Full HMM Viterbi, DCC/t-copula, and live +Bayesian recalibration remain incremental. Core quant methods C5; implementation C2; +live-market parameterization C1. ## 3. Language & location **R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only: From 34216127d606c387ddc84a4cf058d36538e260e6 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:01 -0700 Subject: [PATCH 052/156] docs: mark M3b-sociological-sims.md kernel implemented --- core/docs/plans/M3b-sociological-sims.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/docs/plans/M3b-sociological-sims.md b/core/docs/plans/M3b-sociological-sims.md index 228d9a3..13ef44d 100644 --- a/core/docs/plans/M3b-sociological-sims.md +++ b/core/docs/plans/M3b-sociological-sims.md @@ -10,11 +10,11 @@ pressure across **six concurrent time horizons**. Grounded in evolutionary conse MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Evolutionary game theory C4 (Cornell [8]). Hegselmann-Krause bounded -confidence C5 (established 2002). Complex contagion C4 (Centola & Macy 2007; crypto applications -C3). Bandit-replicator hybrid C3 (emerging). Mean-Field Games C4 (Lasry & Lions 2007; tensor-train -solvers C3). Crypto pump-and-dump ABM C3 (3-agent protocol validated on historical data). -Pop behavioral models C1. +KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl` +implements replicator dynamics, Hegselmann-Krause bounded-confidence updates, heterogeneous +complex-contagion thresholds, and four-phase pump/dump classification. Native tests live beside +the engine. UCB/Thompson bandit coupling and the HJB/Fokker-Planck MFG layer remain incremental. +Foundations C4/C5 as previously stated; implementation C2; calibrated pop models C1. ## 3. Language & location **ECLiPSe Prolog 7.2** · `src/economy/sims/sociological/`. Libraries: **ic** (interval From 900b7c0e532e38c4f24efe34fbabcf5775c0fa36 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:04 -0700 Subject: [PATCH 053/156] docs: mark M3d-mev-adversarial-sims.md kernel implemented --- core/docs/plans/M3d-mev-adversarial-sims.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/core/docs/plans/M3d-mev-adversarial-sims.md b/core/docs/plans/M3d-mev-adversarial-sims.md index 7f9e26a..b4f1548 100644 --- a/core/docs/plans/M3d-mev-adversarial-sims.md +++ b/core/docs/plans/M3d-mev-adversarial-sims.md @@ -13,10 +13,11 @@ dynamics (non-linear Fokker-Planck with WENO shock capturing), and DSMFG bilevel (leader policy + follower MFG equilibrium). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. PGA-as-all-pay-auction C4 (ACM [3]); knapsack formulation C4 (Cornell -[4,5]); cross-chain arbitrage C4 (ACM SIGMETRICS 2025, 5.5x growth since Dencun); DSMFG bilevel -optimization C3 (emerging — SMFRL solvers); Kolokoltsov adversarial C3 (non-linear Fokker-Planck; -WENO discretization established but crypto application novel). Parameterization C1. +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 +comparison, sandwich-risk scoring, and aggregate all-pay cost. Native tests compile cleanly +under strict gfortran flags. WENO/Kolokoltsov and DSMFG bilevel solvers remain incremental. +Core game/knapsack foundations C4; implementation C2; parameterization C1. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS** From 101cd056c9f58bcf46f9415c5cc4d129cc5550bb Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:07 -0700 Subject: [PATCH 054/156] docs: mark M3e-tokenomics-macro-sims.md kernel implemented --- core/docs/plans/M3e-tokenomics-macro-sims.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/docs/plans/M3e-tokenomics-macro-sims.md b/core/docs/plans/M3e-tokenomics-macro-sims.md index 256df1d..663fd76 100644 --- a/core/docs/plans/M3e-tokenomics-macro-sims.md +++ b/core/docs/plans/M3e-tokenomics-macro-sims.md @@ -13,10 +13,12 @@ frameworks [6], Aave/Compound kinked interest rate models (industry standard), a inter-protocol credit propagation (Matzakos et al. 2025). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. SDE state-space framework C4 (Vienna [7]); stock-flow modeling C4 -(ResearchGate [6]); kinked interest rate model C5 (Aave/Compound production standard); -DeXposure inter-protocol credit propagation C3 (emerging, 2025 — high DeFi specificity); -composable yield optimization C4 (Yearn v3, Beefy, production-validated). Specific parameters C1. +KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/tokenomics/` implements +Euler-Maruyama state evolution, stock-flow conservation checks, kinked lending curves, +directional exposure propagation, risk-adjusted yield allocation, and liquidation shortfall. +Native tests compile cleanly under strict gfortran flags. Full state estimation, calibrated VAR +impulse response, and policy-event orchestration remain incremental. Foundations C4/C5; +implementation C2; specific parameters C1. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies: From ed5c4cd642cda9ae5a63a4dd6deead84a9b13a1e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:10 -0700 Subject: [PATCH 055/156] docs: mark M3f-consensus-staking-sims.md kernel implemented --- core/docs/plans/M3f-consensus-staking-sims.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/core/docs/plans/M3f-consensus-staking-sims.md b/core/docs/plans/M3f-consensus-staking-sims.md index 1723a44..af6a387 100644 --- a/core/docs/plans/M3f-consensus-staking-sims.md +++ b/core/docs/plans/M3f-consensus-staking-sims.md @@ -8,10 +8,11 @@ financial incentives. Grounded in Cornell evolutionary consensus [8,9], ACM stak theorems [10], and Monash dynamic PBFT modeling [11]. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Evolutionary PoS game theory C4 (Cornell [8]); staking pool Nash -equilibrium proofs C4 (ACM [10]); Markov chain throughput models C4 (Monash [11]); MFG for -validator populations C4 (Lasry & Lions 2007; validator-specific application C3); -simulation parameterization C1. +KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/consensus/engine.ecl` +implements evolutionary honesty updates, validator-state Markov transitions, an explicit +incentive-compatibility slashing threshold, and liveness degradation below an honesty threshold. +Native tests live beside the engine. The large-population HJB/Fokker-Planck MFG layer remains +incremental. Foundations C4; implementation C2; protocol parameterization C1. ## 3. Language & location **ECLiPSe Prolog 7.2** · `src/economy/sims/consensus/`. Libraries: **ic** (interval From 41df6994c5e3c275497a415183bfec3c9c96bcf6 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:12 -0700 Subject: [PATCH 056/156] docs: mark M3g-market-microstructure-sims.md kernel implemented --- core/docs/plans/M3g-market-microstructure-sims.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/docs/plans/M3g-market-microstructure-sims.md b/core/docs/plans/M3g-market-microstructure-sims.md index 062d966..b3a7c98 100644 --- a/core/docs/plans/M3g-market-microstructure-sims.md +++ b/core/docs/plans/M3g-market-microstructure-sims.md @@ -10,9 +10,11 @@ models pool mechanics, M3g models the *plumbing* of how orders actually execute, concurrent time horizons** at tick-advanced, 90:1 (1s wall = 90s sim). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Order-book microstructure theory C4 (established). Almgren-Chriss -optimal execution C5 (industry standard since 2001; crypto adaptations validated 2023–2024, -Kurz CMC thesis). DEX-specific microstructure C2 (emerging). Implementation C1. +KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/microstructure/` implements +depth-consuming buy slippage, bid/ask spread, Almgren-Chriss execution schedules, exponential +cross-venue arbitrage decay, and live linear impact estimation. Native tests compile cleanly +under strict gfortran flags. Full order-event simulation and venue adapters remain incremental. +Microstructure C4; Almgren-Chriss C5; implementation C2; DEX-specific calibration C1/C2. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/microstructure/`. Build: **fpm**. Dependencies: From 46abf6f63b199178a7500a7d6d16ef64f029898f Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:22 -0700 Subject: [PATCH 057/156] docs: mark M3c AMM kernel implemented --- core/docs/plans/M3c-amm-liquidity-sims.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/docs/plans/M3c-amm-liquidity-sims.md b/core/docs/plans/M3c-amm-liquidity-sims.md index 53056cf..d635830 100644 --- a/core/docs/plans/M3c-amm-liquidity-sims.md +++ b/core/docs/plans/M3c-amm-liquidity-sims.md @@ -7,9 +7,11 @@ loss, and the non-cooperative game between liquidity providers and arbitrageurs* literature [1,2]. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Mathematical foundations C5 (constant product invariant is proven); -impermanent loss formula C5 (closed-form: $\text{IL}(r) = \frac{2\sqrt{r}}{1+r} - 1$); -simulation parameterization C1. +KERNEL IMPLEMENTED · Solidity/Foundry. `core/src/economy/sims/amm/src/AMMSim.sol` +implements fee-adjusted constant-product swaps, fixed-point impermanent loss, nonlinear +slippage, and an IL-vs-fee withdrawal decision; Foundry-native tests cover the invariants. +Concentrated liquidity, multi-pool routing, and richer LP/arbitrage populations remain +incremental. Mathematical foundations C5; implementation C2; parameterization C1. ## 3. Language & location **Solidity** + **Foundry** (forge, anvil) · `src/economy/sims/amm/`. Foundry is hosted From db568b1bc176d43f8efc850ead66ce5c43b3c4b8 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:50 -0700 Subject: [PATCH 058/156] docs: describe built-in M3 simulator family --- core/src/economy/README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index 115b83c..ee69cb9 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. -- **M3 Sims hub** — bounded-prediction validation and current-state publication/query. Native M3a–M3g engines and 90:1 scheduler are not built yet. +- **M3 Sims** — all seven native engine trees are now built in: M3a R statistical, M3b ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster; the registry exposes source/runtime status through M0. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. @@ -21,10 +21,18 @@ There is deliberately no live transaction broadcaster. A successful action retur tclsh core/src/economy/tests/stomach.test ``` -Expected: `Total 13 Passed 13 ... Failed 0`. +Expected: `Total 17 Passed 17 ... Failed 0` once the current branch is checked out. + +The simulator family also has its own polyglot driver: + +```sh +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. ## Public scaffold API -`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `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`, `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. From 3544cfef8c91ad787b70f90dd39ae6555c44ea38 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:54:52 -0700 Subject: [PATCH 059/156] docs: add M3 simulator family readme --- core/src/economy/sims/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 core/src/economy/sims/README.md diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md new file mode 100644 index 0000000..64d70a5 --- /dev/null +++ b/core/src/economy/sims/README.md @@ -0,0 +1,27 @@ +# M3 simulator family + +Seven native simulator engines live here behind the Tcl M3 hub. + +| ID | Engine | Native language | Implemented kernel | +|---|---|---|---| +| M3a | statistical | R | GBM, Merton jump diffusion, Heston, GARCH(1,1), Hurst estimate, regime state, bounded MC forecast | +| M3b | sociological | ECLiPSe Prolog | replicator dynamics, Hegselmann-Krause, complex contagion, pump/dump phase | +| M3c | AMM/liquidity | Solidity + Foundry | fee-adjusted x*y=k, impermanent loss, slippage, IL-derived withdrawal | +| M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | +| M3e | tokenomics/macro | Fortran 2018 | Euler-Maruyama, stock-flow conservation, kinked lending, directional contagion, yield weights | +| M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | +| M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit | + +`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. + +Run all locally available native tests: + +```sh +tclsh core/src/economy/sims/run_tests.tcl +``` + +Pass `--strict` when the environment is expected to contain every external runtime. + +The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design; their native test files are checked in next to their engines. + +This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. From 6ccfb800e8cb4ed0b14c74fa18296638500f0aa6 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Sun, 18 Oct 2026 22:55:27 -0700 Subject: [PATCH 060/156] docs: include native M3 engine verification in M0 --- core/docs/plans/M0-economy-organ-hub.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/docs/plans/M0-economy-organ-hub.md b/core/docs/plans/M0-economy-organ-hub.md index b0987f2..ec554a4 100644 --- a/core/docs/plans/M0-economy-organ-hub.md +++ b/core/docs/plans/M0-economy-organ-hub.md @@ -69,10 +69,13 @@ the runtime bridge between Ichor and this scaffold is still open. 4. Implement tax stub and Verschwörern Veregeister transfer last. ## 9. Tests -Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 13 +Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 17 tests cover admission ordering, 1:1 binding, simulation-only execution, monitor logging, supervisor pause/resume, bounded predictions, feed backpressure, exposure limits, tax staging, -and Ada-bound secretion. Ichor runtime bridging remains a separate integration test. +Ada-bound secretion, all seven M3 engine registrations, source presence, the six horizon clocks, +and the running scheduler. Native simulator tests are driven by +`tclsh core/src/economy/sims/run_tests.tcl`. Ichor runtime bridging remains a separate +integration test. ## 10. Open items - Reward signal protocol from economy organ to organism (TBD, out of scope). From eebcdbb4e3eb864b7b6750e4cb3a40662daf8d84 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 16:53:52 -0700 Subject: [PATCH 061/156] ci: add native R verification for M3a --- .github/workflows/m3a-statistical.yml | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/workflows/m3a-statistical.yml diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml new file mode 100644 index 0000000..28ce310 --- /dev/null +++ b/.github/workflows/m3a-statistical.yml @@ -0,0 +1,32 @@ +name: M3a Statistical CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/statistical/**" + - ".github/workflows/m3a-statistical.yml" + pull_request: + paths: + - "core/src/economy/sims/statistical/**" + - ".github/workflows/m3a-statistical.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3a: + name: R statistical engine + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up R + uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + + - name: Run M3a native tests + run: Rscript core/src/economy/sims/statistical/tests.R From 176490899f1da666e05cd34a99d2c51f9135e9ce Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 16:54:15 -0700 Subject: [PATCH 062/156] test: specify full M3a statistical engine --- core/src/economy/sims/statistical/tests.R | 128 +++++++++++++++++++++- 1 file changed, 126 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R index 6b050ef..98d83c6 100644 --- a/core/src/economy/sims/statistical/tests.R +++ b/core/src/economy/sims/statistical/tests.R @@ -1,16 +1,140 @@ -args <- commandArgs(trailingOnly=FALSE); f <- sub("^--file=", "", args[grep("^--file=", args)]) +args <- commandArgs(trailingOnly=FALSE) +f <- sub("^--file=", "", args[grep("^--file=", args)]) source(file.path(dirname(normalizePath(f)), "engine.R")) + +near <- function(x, y, tol) abs(x-y) <= tol + +# Existing stochastic kernels ------------------------------------------------- x <- gbm_terminal(100,0.05,0.2,1/252,252,20000,7) expected <- 100*exp(0.05) stopifnot(abs(mean(x)-expected)/expected < 0.02) + j <- merton_terminal(100,0.05,0.15,2,-0.08,0.15,1/252,252,10000,9) kurtosis <- mean((j-mean(j))^4)/(var(j)^2) stopifnot(kurtosis > 3) + h <- heston_terminal(100,0.04,0.03,2,0.04,0.3,-0.6,1/252,252,5000,3) stopifnot(all(h > 0)) + set.seed(12) -r <- c(rnorm(100,0,.01), rnorm(100,0,.05)); fit <- garch11_fit(r) +r <- c(rnorm(100,0,.01), rnorm(100,0,.05)) +fit <- garch11_fit(r) stopifnot(fit$alpha >= 0, fit$beta >= 0, fit$alpha+fit$beta < 1) +stopifnot(length(fit$variance) == length(r)) +stopifnot(all(fit$variance > 0)) + p <- bounded_price_prediction(100,.03,.2,1/365,30,5000,4,"30d","TEST") stopifnot(p$lower_bound <= p$value, p$value <= p$upper_bound) + +# HMM regime filter ----------------------------------------------------------- +set.seed(40) +regime_returns <- c( + rnorm(160,-0.012,0.006), + rnorm(160, 0.000,0.004), + rnorm(160, 0.012,0.006) +) +hmm <- hmm3_fit(regime_returns, max_iter=40, tol=1e-6) +path <- hmm3_viterbi(regime_returns, hmm) +stopifnot(identical(sort(names(hmm$state_mean)), c("bear","bull","neutral"))) +stopifnot(mean(path[1:140] == "bear") > 0.70) +stopifnot(mean(path[181:300] == "neutral") > 0.60) +stopifnot(mean(path[341:480] == "bull") > 0.70) +stopifnot(all(abs(rowSums(hmm$transition)-1) < 1e-8)) + +# Rough-vol / Hurst estimation ------------------------------------------------ +set.seed(41) +brownian <- cumsum(rnorm(2048)) +H <- hurst_variogram(brownian) +stopifnot(is.finite(H), H > 0.30, H < 0.70) + +rv <- exp(arima.sim(model=list(ar=-0.55), n=800, sd=0.2)) +rough <- rough_vol_state(rv) +stopifnot(rough$hurst > 0.01, rough$hurst < 0.80) +stopifnot(rough$forecast_variance > 0) + +# Cross-asset DCC and t-copula tail dependence ------------------------------- +set.seed(42) +n <- 700 +z1 <- rnorm(n) +rho <- c(rep(0.10,350),rep(0.85,350)) +z2 <- rho*z1 + sqrt(1-rho^2)*rnorm(n) +dcc <- dcc_fit(cbind(z1,z2), a=0.03, b=0.94) +stopifnot(length(dcc$correlation) == n) +stopifnot(mean(dcc$correlation[500:700]) > mean(dcc$correlation[50:250]) + 0.15) +td_lo <- t_copula_tail_dependence(0.2, 6) +td_hi <- t_copula_tail_dependence(0.8, 6) +stopifnot(td_hi > td_lo, td_lo >= 0, td_hi <= 1) + +# Bayesian calibration + AR forecast ----------------------------------------- +set.seed(43) +prior <- normal_inverse_gamma_prior(mu=0, kappa=1, alpha=2, beta=0.001) +post_pos <- bayes_return_update(prior, rnorm(300,0.01,0.02)) +post_neg <- bayes_return_update(prior, rnorm(300,-0.01,0.02)) +stopifnot(post_pos$mu > 0, post_neg$mu < 0) +stopifnot(post_pos$alpha > prior$alpha, post_pos$beta > 0) + +ar_data <- as.numeric(arima.sim(model=list(ar=0.75), n=500, sd=0.01)) +arf <- arima_forecast_base(ar_data, horizon=5) +stopifnot(length(arf$mean) == 5, length(arf$sd) == 5) +stopifnot(all(is.finite(arf$mean)), all(arf$sd >= 0)) + +# Risk measures --------------------------------------------------------------- +set.seed(44) +risk_returns <- rt(5000, df=5) * 0.02 +risk <- historical_var_es(risk_returns, alpha=0.99) +stopifnot(risk$var > 0, risk$expected_shortfall >= risk$var) + +# Jump + Heston calibration proxies ------------------------------------------ +set.seed(45) +plain <- rnorm(1000,0,0.01) +jumpy <- plain +jumpy[seq(50,1000,by=100)] <- jumpy[seq(50,1000,by=100)] - 0.10 +ji_plain <- estimate_jump_intensity(plain) +ji_jump <- estimate_jump_intensity(jumpy) +stopifnot(ji_jump$lambda > ji_plain$lambda) + +prices_proxy <- 100*exp(cumsum(rnorm(1000,0,0.01))) +hp <- fit_heston_proxy(prices_proxy, window=24) +stopifnot(hp$v0 > 0, hp$theta > 0, hp$kappa >= 0, hp$xi >= 0, abs(hp$rho) <= 1) + +# Full calibration and six concurrent horizons ------------------------------- +set.seed(46) +returns <- c( + rnorm(500,0.0004,0.012), + rnorm(400,-0.0002,0.025) +) +prices <- 100*exp(cumsum(returns)) +state <- calibrate_market(prices, dt=1/365, ticker="TEST") +stopifnot(state$spot > 0) +stopifnot(state$garch$alpha + state$garch$beta < 1) +stopifnot(state$rough$hurst > 0, state$rough$hurst < 1) +stopifnot(state$heston$theta > 0) +stopifnot(state$jump$lambda >= 0) +stopifnot(state$regime %in% c("bear","neutral","bull")) + +forecasts <- forecast_all_horizons(state, paths=2500, seed=90) +expected_horizons <- c("tick_hourly","daily","weekly","monthly","annual","five_year") +stopifnot(identical(names(forecasts), expected_horizons)) +for (name in names(forecasts)) { + q <- forecasts[[name]] + stopifnot(q$lower_bound <= q$value, q$value <= q$upper_bound) + stopifnot(q$confidence >= 0, q$confidence <= 10) + stopifnot(q$correctness >= 0, q$correctness <= 10) + stopifnot(q$certainty >= 0, q$certainty <= 10) + stopifnot(q$sim_type == "statistical") + stopifnot(q$token_ticker == "TEST") +} + +# DCC accepts calibrated GARCH residuals from a return matrix ----------------- +set.seed(47) +m <- cbind( + rnorm(450,0,0.015), + 0.6*rnorm(450,0,0.015) + 0.4*rnorm(450,0,0.015), + rnorm(450,0,0.020) +) +cross <- calibrate_cross_asset(m) +stopifnot(all(dim(cross$last_correlation) == c(3,3))) +stopifnot(max(abs(diag(cross$last_correlation)-1)) < 1e-10) +stopifnot(max(abs(cross$last_correlation-t(cross$last_correlation))) < 1e-10) + cat("STATISTICAL TESTS PASSED\n") From 33c247cc2710b700a0b2cf304e432d3e37fb0da7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 16:56:09 -0700 Subject: [PATCH 063/156] M3a: implement full statistical calibration engine --- core/src/economy/sims/statistical/engine.R | 746 +++++++++++++++++++-- 1 file changed, 702 insertions(+), 44 deletions(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index d2ba765..577423a 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -1,5 +1,27 @@ -# M3a statistical simulator kernels. Base R only; no Python bridge. +# M3a statistical & quantitative simulator. +# Base R only: no Python bridge and no runtime dependency on CRAN packages. +# The heavier CRAN stack in the design remains optional acceleration/validation. + clamp <- function(x, lo, hi) pmin(hi, pmax(lo, x)) +eps <- 1e-12 + +safe_sd <- function(x, floor=1e-8) { + s <- sd(as.numeric(x)) + if (!is.finite(s) || s < floor) floor else s +} + +normalize_prob <- function(x) { + x <- pmax(as.numeric(x), 1e-300) + x / sum(x) +} + +returns_from_prices <- function(prices) { + prices <- as.numeric(prices) + stopifnot(length(prices) >= 3, all(is.finite(prices)), all(prices > 0)) + diff(log(prices)) +} + +# --- Monte Carlo price kernels --------------------------------------------- gbm_terminal <- function(s0, mu, sigma, dt, steps, paths, seed=1L) { stopifnot(s0 > 0, sigma >= 0, dt > 0, steps >= 1, paths >= 2) @@ -9,21 +31,30 @@ gbm_terminal <- function(s0, mu, sigma, dt, steps, paths, seed=1L) { s0 * exp(colSums(lr)) } -merton_terminal <- function(s0, mu, sigma, lambda, jump_mu, jump_sigma, dt, steps, paths, seed=1L) { - stopifnot(lambda >= 0, jump_sigma >= 0) +merton_terminal <- function(s0, mu, sigma, lambda, jump_mu, jump_sigma, + dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, sigma >= 0, lambda >= 0, jump_sigma >= 0, + dt > 0, steps >= 1, paths >= 2) set.seed(seed) z <- matrix(rnorm(steps * paths), nrow=steps) n <- matrix(rpois(steps * paths, lambda * dt), nrow=steps) - jumps <- matrix(rnorm(steps * paths, jump_mu, jump_sigma), nrow=steps) * n - drift <- (mu - 0.5*sigma^2 - lambda*(exp(jump_mu + 0.5*jump_sigma^2)-1)) * dt + jump_z <- matrix(rnorm(steps * paths), nrow=steps) + jumps <- n * jump_mu + sqrt(pmax(n, 0)) * jump_sigma * jump_z + compensator <- lambda * (exp(jump_mu + 0.5 * jump_sigma^2) - 1) + drift <- (mu - 0.5*sigma^2 - compensator) * dt s0 * exp(colSums(drift + sigma*sqrt(dt)*z + jumps)) } -heston_terminal <- function(s0, v0, mu, kappa, theta, xi, rho, dt, steps, paths, seed=1L) { - stopifnot(s0 > 0, v0 >= 0, kappa >= 0, theta >= 0, xi >= 0, abs(rho) <= 1) - set.seed(seed); s <- rep(s0, paths); v <- rep(v0, paths) +heston_terminal <- function(s0, v0, mu, kappa, theta, xi, rho, + dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, v0 >= 0, kappa >= 0, theta >= 0, xi >= 0, + abs(rho) <= 1, dt > 0, steps >= 1, paths >= 2) + set.seed(seed) + s <- rep(s0, paths) + v <- rep(v0, paths) for (i in seq_len(steps)) { - z1 <- rnorm(paths); z2 <- rho*z1 + sqrt(max(0, 1-rho^2))*rnorm(paths) + z1 <- rnorm(paths) + z2 <- rho*z1 + sqrt(max(0, 1-rho^2))*rnorm(paths) vp <- pmax(v, 0) s <- s * exp((mu - 0.5*vp)*dt + sqrt(vp*dt)*z1) v <- pmax(v + kappa*(theta-vp)*dt + xi*sqrt(vp*dt)*z2, 0) @@ -31,61 +62,688 @@ heston_terminal <- function(s0, v0, mu, kappa, theta, xi, rho, dt, steps, paths, s } -garch11_fit <- function(r) { - r <- as.numeric(r); stopifnot(length(r) >= 20) - v0 <- var(r) - nll <- function(p) { - omega <- exp(p[1]); alpha <- plogis(p[2]); beta <- plogis(p[3])*(1-alpha) - h <- numeric(length(r)); h[1] <- max(v0, 1e-12) - for (i in 2:length(r)) h[i] <- max(1e-12, omega + alpha*r[i-1]^2 + beta*h[i-1]) - 0.5*sum(log(h) + r^2/h) +# --- GARCH ----------------------------------------------------------------- + +garch11_filter <- function(r, omega, alpha, beta, mean_return=mean(r)) { + r <- as.numeric(r) + e <- r - mean_return + h <- numeric(length(r)) + h[1] <- max(var(e), eps) + if (length(r) >= 2) { + for (i in 2:length(r)) { + h[i] <- max(eps, omega + alpha*e[i-1]^2 + beta*h[i-1]) + } } - opt <- optim(c(log(max(v0*0.05,1e-12)), qlogis(0.1), qlogis(0.85/0.9)), nll) - alpha <- plogis(opt$par[2]); beta <- plogis(opt$par[3])*(1-alpha) - list(omega=exp(opt$par[1]), alpha=alpha, beta=beta) + h } -hurst_rs <- function(x) { - x <- as.numeric(x); n <- length(x); stopifnot(n >= 32) - scales <- c(4,8,16,32); scales <- scales[scales <= n/2] - rs <- sapply(scales, function(m) { - chunks <- split(x[seq_len(floor(n/m)*m)], rep(seq_len(floor(n/m)), each=m)) - vals <- sapply(chunks, function(y) { z <- cumsum(y-mean(y)); sdv <- sd(y); if (sdv==0) NA else (max(z)-min(z))/sdv }) - mean(vals, na.rm=TRUE) +garch11_fit <- function(r) { + r <- as.numeric(r) + stopifnot(length(r) >= 20, all(is.finite(r))) + mean_return <- mean(r) + e <- r - mean_return + v0 <- max(var(e), 1e-10) + + unpack <- function(p) { + alpha <- 0.98 * plogis(p[2]) + beta <- (0.999 - alpha) * plogis(p[3]) + c(omega=exp(p[1]), alpha=alpha, beta=beta) + } + + nll <- function(p) { + q <- unpack(p) + h <- garch11_filter(r, q["omega"], q["alpha"], q["beta"], mean_return) + 0.5 * sum(log(2*pi) + log(h) + e^2/h) + } + + init_alpha <- 0.08 + init_beta <- 0.88 + init <- c( + log(max(v0 * (1-init_alpha-init_beta), 1e-12)), + qlogis(init_alpha/0.98), + qlogis(init_beta/(0.999-init_alpha)) + ) + opt <- tryCatch(optim(init, nll, method="BFGS", control=list(maxit=500)), + error=function(e) NULL) + if (is.null(opt) || !is.finite(opt$value)) { + q <- c(omega=max(v0*0.04,1e-12), alpha=0.08, beta=0.88) + convergence <- 1L + } else { + q <- unpack(opt$par) + convergence <- opt$convergence + } + h <- garch11_filter(r, q["omega"], q["alpha"], q["beta"], mean_return) + list( + omega=unname(q["omega"]), + alpha=unname(q["alpha"]), + beta=unname(q["beta"]), + mean=mean_return, + variance=h, + sigma=sqrt(h), + standardized=(r-mean_return)/sqrt(h), + convergence=convergence + ) +} + +garch11_forecast <- function(fit, last_return, steps=1L) { + stopifnot(steps >= 1) + out <- numeric(steps) + h <- tail(fit$variance, 1) + e2 <- (last_return-fit$mean)^2 + for (i in seq_len(steps)) { + h <- fit$omega + fit$alpha*e2 + fit$beta*h + out[i] <- max(h, eps) + e2 <- h + } + out +} + +# --- Three-state Gaussian HMM ---------------------------------------------- + +hmm_forward_backward <- function(x, initial, transition, state_mean, state_sd) { + x <- as.numeric(x) + n <- length(x) + k <- length(state_mean) + emission <- sapply(seq_len(k), function(j) { + pmax(dnorm(x, mean=state_mean[j], sd=max(state_sd[j],1e-8)), 1e-300) }) - unname(coef(lm(log(rs) ~ log(scales)))[2]) + if (k == 1) emission <- matrix(emission, ncol=1) + + forward <- matrix(0, n, k) + scale <- numeric(n) + forward[1,] <- initial * emission[1,] + scale[1] <- max(sum(forward[1,]), 1e-300) + forward[1,] <- forward[1,] / scale[1] + + if (n >= 2) { + for (t in 2:n) { + forward[t,] <- as.numeric(forward[t-1,] %*% transition) * emission[t,] + scale[t] <- max(sum(forward[t,]), 1e-300) + forward[t,] <- forward[t,] / scale[t] + } + } + + backward <- matrix(1, n, k) + if (n >= 2) { + for (t in (n-1):1) { + backward[t,] <- as.numeric( + transition %*% (emission[t+1,] * backward[t+1,]) + ) / scale[t+1] + } + } + + gamma <- forward * backward + gamma <- gamma / rowSums(gamma) + + xi_sum <- matrix(0, k, k) + if (n >= 2) { + for (t in 1:(n-1)) { + xi <- transition * outer( + forward[t,], + emission[t+1,] * backward[t+1,] + ) + den <- sum(xi) + if (den > 0) xi_sum <- xi_sum + xi/den + } + } + + list( + emission=emission, + forward=forward, + backward=backward, + posterior=gamma, + xi_sum=xi_sum, + loglik=sum(log(scale)) + ) +} + +hmm3_fit <- function(returns, max_iter=80L, tol=1e-7) { + x <- as.numeric(returns) + stopifnot(length(x) >= 60, all(is.finite(x))) + state_names <- c("bear","neutral","bull") + state_mean <- as.numeric(quantile(x, c(0.15,0.50,0.85), names=FALSE)) + base_sd <- safe_sd(x) + state_sd <- rep(base_sd, 3) + initial <- rep(1/3, 3) + transition <- matrix(0.015, 3, 3) + diag(transition) <- 0.97 + previous_ll <- -Inf + + for (iter in seq_len(max_iter)) { + fb <- hmm_forward_backward(x, initial, transition, state_mean, state_sd) + w <- colSums(fb$posterior) + initial <- normalize_prob(fb$posterior[1,]) + + transition <- fb$xi_sum + transition <- transition / pmax(rowSums(transition), 1e-300) + transition[!is.finite(transition)] <- 1/3 + transition <- t(apply(transition, 1, normalize_prob)) + + new_mean <- colSums(fb$posterior * x) / pmax(w, 1e-12) + new_sd <- numeric(3) + for (j in 1:3) { + new_sd[j] <- sqrt( + sum(fb$posterior[,j] * (x-new_mean[j])^2) / max(w[j],1e-12) + ) + } + state_mean <- new_mean + state_sd <- pmax(new_sd, base_sd*0.05, 1e-8) + + ord <- order(state_mean) + state_mean <- state_mean[ord] + state_sd <- state_sd[ord] + initial <- initial[ord] + transition <- transition[ord,ord,drop=FALSE] + + if (is.finite(previous_ll) && abs(fb$loglik-previous_ll) < tol) break + previous_ll <- fb$loglik + } + + fb <- hmm_forward_backward(x, initial, transition, state_mean, state_sd) + names(state_mean) <- state_names + names(state_sd) <- state_names + names(initial) <- state_names + dimnames(transition) <- list(state_names,state_names) + colnames(fb$posterior) <- state_names + + list( + initial=initial, + transition=transition, + state_mean=state_mean, + state_sd=state_sd, + posterior=fb$posterior, + loglik=fb$loglik + ) +} + +hmm3_viterbi <- function(returns, model) { + x <- as.numeric(returns) + names_state <- names(model$state_mean) + k <- length(names_state) + n <- length(x) + log_trans <- log(pmax(model$transition,1e-300)) + log_initial <- log(pmax(model$initial,1e-300)) + emit <- sapply(seq_len(k), function(j) { + dnorm(x, model$state_mean[j], model$state_sd[j], log=TRUE) + }) + if (k == 1) emit <- matrix(emit,ncol=1) + + delta <- matrix(-Inf,n,k) + psi <- matrix(1L,n,k) + delta[1,] <- log_initial + emit[1,] + if (n >= 2) { + for (t in 2:n) { + for (j in seq_len(k)) { + candidate <- delta[t-1,] + log_trans[,j] + psi[t,j] <- which.max(candidate) + delta[t,j] <- max(candidate) + emit[t,j] + } + } + } + path <- integer(n) + path[n] <- which.max(delta[n,]) + if (n >= 2) { + for (t in (n-1):1) path[t] <- psi[t+1,path[t+1]] + } + names_state[path] } regime_state <- function(returns) { - m <- mean(returns); s <- sd(returns) - if (!is.finite(s) || s == 0) return("neutral") - if (m > 0.25*s) "bull" else if (m < -0.25*s) "bear" else "neutral" + x <- as.numeric(returns) + if (length(x) < 60) { + m <- mean(x) + s <- safe_sd(x) + if (m > 0.25*s) "bull" else if (m < -0.25*s) "bear" else "neutral" + } else { + model <- hmm3_fit(x) + tail(hmm3_viterbi(x,model),1) + } } -bounded_price_prediction <- function(s0, mu, sigma, dt, steps, paths=4000L, seed=1L, horizon="24h", ticker="ASSET") { - sims <- gbm_terminal(s0, mu, sigma, dt, steps, paths, seed) - q <- as.numeric(quantile(sims, c(.025,.5,.975), names=FALSE)) - width <- (q[3]-q[1])/max(q[2],1e-12) - list(value=q[2], lower_bound=q[1], upper_bound=q[3], confidence=clamp(10-5*width,0,10), correctness=5, certainty=clamp(10-8*width,0,10), time_horizon=horizon, sim_type="statistical", token_ticker=ticker, recent_shift=0) +# --- Rough volatility ------------------------------------------------------- + +hurst_variogram <- function(x, max_lag=NULL) { + x <- as.numeric(x) + n <- length(x) + stopifnot(n >= 32, all(is.finite(x))) + if (is.null(max_lag)) max_lag <- min(64L, floor(n/8)) + max_lag <- max(4L, min(as.integer(max_lag), floor(n/3))) + raw_lags <- unique(as.integer(round(exp(seq(log(1),log(max_lag),length.out=12))))) + lags <- raw_lags[raw_lags >= 1 & raw_lags < n] + variogram <- sapply(lags, function(lag) { + mean((x[(lag+1):n] - x[1:(n-lag)])^2) + }) + keep <- is.finite(variogram) & variogram > 0 + if (sum(keep) < 3) return(0.5) + slope <- unname(coef(lm(log(variogram[keep]) ~ log(lags[keep])))[2]) + clamp(slope/2, 0.01, 0.99) } +hurst_rs <- function(x) { + # Kept for API compatibility; variogram estimator is more appropriate for + # the realized-variance rough-vol path used by M3a. + hurst_variogram(cumsum(as.numeric(x)-mean(x))) +} + +realized_variance <- function(returns, window=24L) { + x <- as.numeric(returns) + stopifnot(window >= 2, length(x) >= window) + idx <- window:length(x) + vapply(idx, function(i) mean(x[(i-window+1):i]^2), numeric(1)) +} + +rough_vol_state <- function(realized_variance_series) { + rv <- pmax(as.numeric(realized_variance_series), eps) + stopifnot(length(rv) >= 32) + logv <- log(rv) + H <- hurst_variogram(logv) + center <- mean(logv) + if (length(logv) > 2) { + phi <- suppressWarnings(cor(logv[-length(logv)], logv[-1])) + if (!is.finite(phi)) phi <- 0 + } else { + phi <- 0 + } + phi <- clamp(phi, -0.99, 0.99) + forecast_log <- center + phi*(tail(logv,1)-center) + list( + hurst=H, + persistence=phi, + current_variance=tail(rv,1), + forecast_variance=exp(forecast_log) + ) +} + +# --- DCC correlation + t-copula -------------------------------------------- + +dcc_fit <- function(standardized_returns, a=0.02, b=0.97) { + z <- as.matrix(standardized_returns) + stopifnot(nrow(z) >= 20, ncol(z) >= 2, a >= 0, b >= 0, a+b < 1) + z[!is.finite(z)] <- 0 + qbar <- cov(z) + qbar <- qbar + diag(eps,ncol(z)) + q <- qbar + n <- nrow(z) + p <- ncol(z) + history <- array(0, dim=c(p,p,n)) + + for (t in seq_len(n)) { + if (t >= 2) { + q <- (1-a-b)*qbar + a*tcrossprod(z[t-1,]) + b*q + } + d <- sqrt(pmax(diag(q),eps)) + r <- q / outer(d,d) + diag(r) <- 1 + history[,,t] <- r + } + + if (p == 2) { + correlation <- as.numeric(history[1,2,]) + } else { + correlation <- history + } + list( + a=a, + b=b, + qbar=cov2cor(qbar), + correlation=correlation, + last_correlation=history[,,n,drop=TRUE] + ) +} + +t_copula_tail_dependence <- function(rho, df=6) { + stopifnot(df > 0) + rho <- clamp(rho,-0.999999,0.999999) + 2 * pt(-sqrt((df+1)*(1-rho)/(1+rho)), df=df+1) +} + +calibrate_cross_asset <- function(return_matrix, a=0.02, b=0.97) { + x <- as.matrix(return_matrix) + stopifnot(nrow(x) >= 20, ncol(x) >= 2) + fits <- lapply(seq_len(ncol(x)), function(j) garch11_fit(x[,j])) + z <- do.call(cbind,lapply(fits,function(f) f$standardized)) + dcc <- dcc_fit(z,a,b) + list( + univariate=fits, + standardized=z, + dcc=dcc, + last_correlation=dcc$last_correlation + ) +} + +# --- Bayesian calibration + time series ------------------------------------ + +normal_inverse_gamma_prior <- function(mu=0, kappa=1, alpha=2, beta=1e-4) { + stopifnot(kappa > 0, alpha > 0, beta > 0) + list(mu=mu,kappa=kappa,alpha=alpha,beta=beta) +} + +bayes_return_update <- function(prior, observations) { + x <- as.numeric(observations) + stopifnot(length(x) >= 1, all(is.finite(x))) + n <- length(x) + xb <- mean(x) + ss <- sum((x-xb)^2) + kappa_n <- prior$kappa+n + mu_n <- (prior$kappa*prior$mu+n*xb)/kappa_n + alpha_n <- prior$alpha+n/2 + beta_n <- prior$beta + 0.5*ss + + prior$kappa*n*(xb-prior$mu)^2/(2*kappa_n) + list(mu=mu_n,kappa=kappa_n,alpha=alpha_n,beta=beta_n) +} + +arima_forecast_base <- function(x, horizon=1L, order=c(1L,0L,0L)) { + x <- as.numeric(x) + stopifnot(length(x) >= 20, horizon >= 1) + fit <- tryCatch( + arima(x, order=order, include.mean=TRUE, method="ML"), + error=function(e) NULL + ) + if (is.null(fit)) { + return(list( + mean=rep(mean(x),horizon), + sd=rep(safe_sd(x),horizon), + fit=NULL + )) + } + pred <- predict(fit,n.ahead=horizon) + list(mean=as.numeric(pred$pred),sd=pmax(as.numeric(pred$se),0),fit=fit) +} + +# --- Risk and parameter proxies -------------------------------------------- + +historical_var_es <- function(returns, alpha=0.99) { + x <- as.numeric(returns) + stopifnot(length(x) >= 20, alpha > 0.5, alpha < 1) + q <- unname(quantile(x,1-alpha,type=8,na.rm=TRUE)) + tail_x <- x[x <= q] + var_loss <- max(0,-q) + es <- if (length(tail_x)) max(var_loss,-mean(tail_x)) else var_loss + list(var=var_loss,expected_shortfall=es,quantile=q,alpha=alpha) +} + +estimate_jump_intensity <- function(returns, threshold=4) { + x <- as.numeric(returns) + stopifnot(length(x) >= 20, threshold > 0) + center <- median(x) + scale <- mad(x,center=center,constant=1.4826) + if (!is.finite(scale) || scale < eps) scale <- safe_sd(x) + idx <- which(abs(x-center) > threshold*scale) + jumps <- x[idx] + list( + lambda=length(idx)/length(x), + count=length(idx), + jump_mu=if (length(jumps)) mean(jumps) else 0, + jump_sigma=if (length(jumps) > 1) sd(jumps) else 0, + threshold=threshold*scale + ) +} + +fit_heston_proxy <- function(prices, window=24L) { + r <- returns_from_prices(prices) + window <- min(as.integer(window), max(4L,floor(length(r)/4))) + rv <- realized_variance(r,window) + theta <- max(mean(rv),eps) + v0 <- max(tail(rv,1),eps) + + if (length(rv) >= 3) { + phi <- suppressWarnings(cor(rv[-length(rv)],rv[-1])) + if (!is.finite(phi)) phi <- 0 + phi <- clamp(phi,-0.99,0.999) + kappa <- max(0,1-phi) + + drv <- diff(rv) + aligned_r <- tail(r,length(drv)) + rho <- suppressWarnings(cor(aligned_r,drv)) + if (!is.finite(rho)) rho <- 0 + rho <- clamp(rho,-0.999,0.999) + + base <- pmax(rv[-length(rv)],eps) + xi <- safe_sd(drv/sqrt(base)) + } else { + kappa <- 0 + rho <- 0 + xi <- 0 + } + + list(v0=v0,theta=theta,kappa=kappa,xi=max(xi,0),rho=rho) +} + +coverage_correctness <- function(standardized_returns, target=0.95) { + z <- as.numeric(standardized_returns) + z <- z[is.finite(z)] + if (!length(z)) return(5) + observed <- mean(abs(z) <= 1.959964) + clamp(10 - 25*abs(observed-target),0,10) +} + +# --- Calibration state ------------------------------------------------------ + +calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { + p <- as.numeric(prices) + stopifnot(length(p) >= 80, all(is.finite(p)), all(p > 0), dt > 0) + r <- returns_from_prices(p) + g <- garch11_fit(r) + hmm_window <- tail(r,min(length(r),900)) + hmm <- hmm3_fit(hmm_window,max_iter=60,tol=1e-6) + path <- hmm3_viterbi(hmm_window,hmm) + regime <- tail(path,1) + + rv_window <- min(24L,max(4L,floor(length(r)/10))) + rv <- realized_variance(r,rv_window) + rough <- rough_vol_state(rv) + + prior <- normal_inverse_gamma_prior(mu=0,kappa=1,alpha=2,beta=max(var(r),1e-6)) + posterior <- bayes_return_update(prior,r) + jump <- estimate_jump_intensity(r) + heston_step <- fit_heston_proxy(p,rv_window) + + # Convert per-observation estimates into per-unit-time rates used by SDEs. + mu_rate <- posterior$mu/dt + sigma_rate <- sqrt(max(tail(g$variance,1),eps)/dt) + heston <- heston_step + heston$v0 <- heston$v0/dt + heston$theta <- heston$theta/dt + heston$kappa <- heston$kappa/dt + heston$xi <- heston$xi/sqrt(dt) + jump$lambda <- jump$lambda/dt + + recent_n <- min(24L,length(p)-1) + recent_shift <- tail(p,1)/p[length(p)-recent_n]-1 + last_posterior <- tail(hmm$posterior,1) + regime_certainty <- max(last_posterior) + + list( + ticker=ticker, + spot=tail(p,1), + dt=dt, + returns=r, + mu=mu_rate, + sigma=sigma_rate, + garch=g, + hmm=hmm, + regime=regime, + regime_certainty=regime_certainty, + rough=rough, + posterior=posterior, + jump=jump, + heston=heston, + risk=historical_var_es(r,0.99), + correctness=coverage_correctness(g$standardized), + recent_shift=recent_shift, + calibrated_at=as.numeric(Sys.time()) + ) +} + +# --- Six concurrent forecast horizons -------------------------------------- + +m3a_horizon_specs <- function() { + data.frame( + name=c("tick_hourly","daily","weekly","monthly","annual","five_year"), + label=c("1h","24h","7d","30d","1y","5y"), + years=c(1/(24*365),1/365,7/365,30/365,1,5), + model=c("heston","heston","merton","merton","heston","gbm"), + stringsAsFactors=FALSE + ) +} + +bounded_from_samples <- function(samples, state, label, model) { + q <- as.numeric(quantile(samples,c(.025,.5,.975),names=FALSE,type=8)) + width <- (q[3]-q[1])/max(abs(q[2]),eps) + confidence <- clamp( + 0.55*state$correctness + + 4.5*state$regime_certainty + + 2.0*(1-clamp(width,0,1)), + 0,10 + ) + certainty <- clamp( + 5.0*state$regime_certainty + + 5.0*(1-clamp(width,0,1)), + 0,10 + ) + list( + value=q[2], + lower_bound=q[1], + upper_bound=q[3], + confidence=confidence, + correctness=clamp(state$correctness,0,10), + certainty=certainty, + time_horizon=label, + sim_type="statistical", + token_ticker=state$ticker, + recent_shift=state$recent_shift, + model=model, + regime=state$regime + ) +} + +forecast_horizon <- function(state, horizon_name, paths=4000L, seed=1L) { + specs <- m3a_horizon_specs() + row <- specs[specs$name==horizon_name,,drop=FALSE] + if (!nrow(row)) stop("unknown_horizon") + years <- row$years[1] + model <- row$model[1] + label <- row$label[1] + + steps <- max(1L,min(365L,as.integer(ceiling(years*365)))) + step_dt <- years/steps + + samples <- switch( + model, + heston=heston_terminal( + state$spot, + max(state$heston$v0,eps), + state$mu, + max(state$heston$kappa,0), + max(state$heston$theta,eps), + max(state$heston$xi,0), + state$heston$rho, + step_dt,steps,paths,seed + ), + merton=merton_terminal( + state$spot,state$mu,state$sigma, + max(state$jump$lambda,0), + state$jump$jump_mu, + max(state$jump$jump_sigma,0), + step_dt,steps,paths,seed + ), + gbm=gbm_terminal( + state$spot,state$mu,state$sigma, + step_dt,steps,paths,seed + ), + stop("unknown_model") + ) + bounded_from_samples(samples,state,label,model) +} + +forecast_all_horizons <- function(state, paths=4000L, seed=1L) { + specs <- m3a_horizon_specs() + out <- lapply(seq_len(nrow(specs)), function(i) { + forecast_horizon(state,specs$name[i],paths,seed+i-1L) + }) + names(out) <- specs$name + out +} + +bounded_price_prediction <- function(s0, mu, sigma, dt, steps, + paths=4000L, seed=1L, + horizon="24h", ticker="ASSET") { + sims <- gbm_terminal(s0,mu,sigma,dt,steps,paths,seed) + q <- as.numeric(quantile(sims,c(.025,.5,.975),names=FALSE,type=8)) + width <- (q[3]-q[1])/max(q[2],eps) + list( + value=q[2], + lower_bound=q[1], + upper_bound=q[3], + confidence=clamp(10-5*width,0,10), + correctness=5, + certainty=clamp(10-8*width,0,10), + time_horizon=horizon, + sim_type="statistical", + token_ticker=ticker, + recent_shift=0 + ) +} + +# --- Minimal hand-rolled JSON line protocol -------------------------------- + json_number <- function(line, key, default) { - pat <- paste0('"', key, '"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)') - m <- regexec(pat, line, perl=TRUE); z <- regmatches(line,m)[[1]] + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] if (length(z) < 2) default else as.numeric(z[2]) } + json_string <- function(line, key, default) { - pat <- paste0('"', key, '"[[:space:]]*:[[:space:]]*"([^"]*)"') - m <- regexec(pat, line, perl=TRUE); z <- regmatches(line,m)[[1]] + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*"([^"]*)"') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] if (length(z) < 2) default else z[2] } + +json_number_array <- function(line, key) { + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*\\[([^]]*)\\]') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] + if (length(z) < 2 || !nzchar(trimws(z[2]))) return(numeric()) + as.numeric(strsplit(z[2],",",fixed=TRUE)[[1]]) +} + emit_prediction <- function(p) { - cat(sprintf('{"value":%.10g,"lower_bound":%.10g,"upper_bound":%.10g,"confidence":%.4f,"correctness":%.4f,"certainty":%.4f,"time_horizon":"%s","sim_type":"statistical","token_ticker":"%s","recent_shift":%.10g}\n', p$value,p$lower_bound,p$upper_bound,p$confidence,p$correctness,p$certainty,p$time_horizon,p$token_ticker,p$recent_shift)) + cat(sprintf( + '{"value":%.10g,"lower_bound":%.10g,"upper_bound":%.10g,"confidence":%.4f,"correctness":%.4f,"certainty":%.4f,"time_horizon":"%s","sim_type":"statistical","token_ticker":"%s","recent_shift":%.10g}\n', + p$value,p$lower_bound,p$upper_bound,p$confidence,p$correctness, + p$certainty,p$time_horizon,p$token_ticker,p$recent_shift + )) } + main <- function() { - line <- readLines(file("stdin"), n=1, warn=FALSE) + line <- readLines(file("stdin"),n=1,warn=FALSE) if (!length(line)) quit(status=2) - p <- bounded_price_prediction(json_number(line,"spot",100), json_number(line,"mu",0), json_number(line,"sigma",0.2), json_number(line,"dt",1/365), as.integer(json_number(line,"steps",1)), as.integer(json_number(line,"paths",4000)), as.integer(json_number(line,"seed",1)), json_string(line,"time_horizon","24h"), json_string(line,"token_ticker","ASSET")) - emit_prediction(p) + + prices <- json_number_array(line,"prices") + if (length(prices) >= 80) { + dt <- json_number(line,"dt",1/365) + ticker <- json_string(line,"token_ticker","ASSET") + horizon <- json_string(line,"horizon","daily") + paths <- as.integer(json_number(line,"paths",4000)) + seed <- as.integer(json_number(line,"seed",1)) + state <- calibrate_market(prices,dt,ticker) + emit_prediction(forecast_horizon(state,horizon,paths,seed)) + } else { + p <- bounded_price_prediction( + json_number(line,"spot",100), + json_number(line,"mu",0), + json_number(line,"sigma",0.2), + json_number(line,"dt",1/365), + as.integer(json_number(line,"steps",1)), + as.integer(json_number(line,"paths",4000)), + as.integer(json_number(line,"seed",1)), + json_string(line,"time_horizon","24h"), + json_string(line,"token_ticker","ASSET") + ) + emit_prediction(p) + } } + if (sys.nframe() == 0) main() From 7e7193b02676a4eb70e032b80d88d87ca3f76307 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 16:57:15 -0700 Subject: [PATCH 064/156] M3a: harden rough-vol Hurst bounds --- core/src/economy/sims/statistical/engine.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index 577423a..1d1827c 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -316,7 +316,7 @@ hurst_variogram <- function(x, max_lag=NULL) { keep <- is.finite(variogram) & variogram > 0 if (sum(keep) < 3) return(0.5) slope <- unname(coef(lm(log(variogram[keep]) ~ log(lags[keep])))[2]) - clamp(slope/2, 0.01, 0.99) + clamp(slope/2, 0.02, 0.98) } hurst_rs <- function(x) { From 3050865a2c6cd5543b34bf686f782d69cd3aa0f7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 16:59:15 -0700 Subject: [PATCH 065/156] test: require fitted DCC and rough-vol path generation --- core/src/economy/sims/statistical/tests.R | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R index 98d83c6..dfdc748 100644 --- a/core/src/economy/sims/statistical/tests.R +++ b/core/src/economy/sims/statistical/tests.R @@ -52,6 +52,18 @@ rough <- rough_vol_state(rv) stopifnot(rough$hurst > 0.01, rough$hurst < 0.80) stopifnot(rough$forecast_variance > 0) +fgn <- fgn_davies_harte(4096, H=0.35, seed=410) +fgn_h <- hurst_variogram(cumsum(fgn)) +stopifnot(abs(fgn_h-0.35) < 0.10) +stopifnot(abs(var(fgn)-1) < 0.12) + +rough_terminal <- rough_vol_terminal( + s0=100, mu=0.03, v0=0.04, H=0.35, eta=0.25, + dt=1/365, steps=24, paths=300, seed=411 +) +stopifnot(length(rough_terminal) == 300) +stopifnot(all(is.finite(rough_terminal)), all(rough_terminal > 0)) + # Cross-asset DCC and t-copula tail dependence ------------------------------- set.seed(42) n <- 700 @@ -61,10 +73,21 @@ z2 <- rho*z1 + sqrt(1-rho^2)*rnorm(n) dcc <- dcc_fit(cbind(z1,z2), a=0.03, b=0.94) stopifnot(length(dcc$correlation) == n) stopifnot(mean(dcc$correlation[500:700]) > mean(dcc$correlation[50:250]) + 0.15) + +dcc_qml <- dcc_estimate(cbind(z1,z2)) +stopifnot(dcc_qml$a >= 0, dcc_qml$b >= 0, dcc_qml$a+dcc_qml$b < 1) +stopifnot(is.finite(dcc_qml$loglik)) +stopifnot(mean(dcc_qml$correlation[500:700]) > + mean(dcc_qml$correlation[50:250]) + 0.15) + td_lo <- t_copula_tail_dependence(0.2, 6) td_hi <- t_copula_tail_dependence(0.8, 6) stopifnot(td_hi > td_lo, td_lo >= 0, td_hi <= 1) +set.seed(420) +df_hat <- estimate_t_df(rt(6000,df=7)) +stopifnot(df_hat > 4.1, df_hat < 15) + # Bayesian calibration + AR forecast ----------------------------------------- set.seed(43) prior <- normal_inverse_gamma_prior(mu=0, kappa=1, alpha=2, beta=0.001) From 6e1206b2a24a04e6439f73ce5dee05002a565eb4 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:00:07 -0700 Subject: [PATCH 066/156] M3a: add spectral rough volatility and fitted DCC --- core/src/economy/sims/statistical/engine.R | 176 +++++++++++++++++++-- 1 file changed, 161 insertions(+), 15 deletions(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index 1d1827c..d9f7fe7 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -325,6 +325,57 @@ hurst_rs <- function(x) { hurst_variogram(cumsum(as.numeric(x)-mean(x))) } +fgn_davies_harte <- function(n, H, seed=1L) { + n <- as.integer(n) + stopifnot(n >= 2, H > 0, H < 1) + k <- 0:n + gamma <- 0.5 * ( + abs(k-1)^(2*H) - 2*abs(k)^(2*H) + abs(k+1)^(2*H) + ) + circulant <- c(gamma, rev(gamma[2:n])) + lambda <- Re(fft(circulant)) + if (min(lambda) < -1e-8) stop("davies_harte_negative_eigenvalue") + lambda <- pmax(lambda,0) + + set.seed(seed) + w <- complex(length=2*n) + w[1] <- sqrt(lambda[1]/(2*n))*rnorm(1) + w[n+1] <- sqrt(lambda[n+1]/(2*n))*rnorm(1) + if (n > 1) { + for (j in 2:n) { + z <- rnorm(2) + w[j] <- sqrt(lambda[j]/(4*n)) * (z[1] + 1i*z[2]) + mirror <- 2*n-j+2 + w[mirror] <- Conj(w[j]) + } + } + Re(fft(w))[1:n] +} + +rough_vol_terminal <- function(s0, mu, v0, H, eta, dt, steps, paths, seed=1L) { + stopifnot( + s0 > 0, v0 > 0, H > 0, H < 1, eta >= 0, + dt > 0, steps >= 1, paths >= 2 + ) + steps <- as.integer(steps) + paths <- as.integer(paths) + terminal <- numeric(paths) + for (p in seq_len(paths)) { + fgn <- fgn_davies_harte(steps,H,seed+p-1L) + set.seed(seed+100000L+p) + price_noise <- rnorm(steps) + logv <- log(v0) + logp <- log(s0) + for (i in seq_len(steps)) { + logv <- logv + eta*(dt^H)*fgn[i] + v <- max(exp(logv),eps) + logp <- logp + (mu-0.5*v)*dt + sqrt(v*dt)*price_noise[i] + } + terminal[p] <- exp(logp) + } + terminal +} + realized_variance <- function(returns, window=24L) { x <- as.numeric(returns) stopifnot(window >= 2, length(x) >= window) @@ -350,63 +401,149 @@ rough_vol_state <- function(realized_variance_series) { hurst=H, persistence=phi, current_variance=tail(rv,1), - forecast_variance=exp(forecast_log) + forecast_variance=exp(forecast_log), + vol_of_log_vol=safe_sd(diff(logv)) ) } # --- DCC correlation + t-copula -------------------------------------------- -dcc_fit <- function(standardized_returns, a=0.02, b=0.97) { +dcc_core <- function(standardized_returns, a, b) { z <- as.matrix(standardized_returns) stopifnot(nrow(z) >= 20, ncol(z) >= 2, a >= 0, b >= 0, a+b < 1) z[!is.finite(z)] <- 0 - qbar <- cov(z) - qbar <- qbar + diag(eps,ncol(z)) + qbar <- cov(z) + diag(1e-10,ncol(z)) q <- qbar n <- nrow(z) p <- ncol(z) - history <- array(0, dim=c(p,p,n)) + history <- array(0,dim=c(p,p,n)) + nll <- 0 for (t in seq_len(n)) { if (t >= 2) { q <- (1-a-b)*qbar + a*tcrossprod(z[t-1,]) + b*q } d <- sqrt(pmax(diag(q),eps)) - r <- q / outer(d,d) + r <- q/outer(d,d) diag(r) <- 1 history[,,t] <- r + + if (t >= 2) { + det_r <- determinant(r,logarithm=TRUE) + if (det_r$sign <= 0) { + nll <- Inf + } else if (is.finite(nll)) { + solved <- tryCatch(solve(r,z[t,]),error=function(e) NULL) + if (is.null(solved)) { + nll <- Inf + } else { + quad <- sum(z[t,]*solved) + nll <- nll + 0.5*(as.numeric(det_r$modulus)+quad) + } + } + } } - if (p == 2) { - correlation <- as.numeric(history[1,2,]) + list(z=z,qbar=qbar,history=history,nll=nll) +} + +dcc_fit <- function(standardized_returns, a=0.02, b=0.97) { + core <- dcc_core(standardized_returns,a,b) + p <- dim(core$history)[1] + n <- dim(core$history)[3] + correlation <- if (p == 2) { + as.numeric(core$history[1,2,]) } else { - correlation <- history + core$history } list( a=a, b=b, - qbar=cov2cor(qbar), + qbar=cov2cor(core$qbar), correlation=correlation, - last_correlation=history[,,n,drop=TRUE] + last_correlation=core$history[,,n,drop=TRUE], + loglik=-core$nll ) } +dcc_estimate <- function(standardized_returns, start=c(a=0.03,b=0.94)) { + z <- as.matrix(standardized_returns) + stopifnot(nrow(z) >= 20, ncol(z) >= 2) + a0 <- unname(start["a"]) + b0 <- unname(start["b"]) + if (!is.finite(a0) || !is.finite(b0) || a0 < 0 || b0 < 0 || a0+b0 >= 0.999) { + a0 <- 0.03 + b0 <- 0.94 + } + rest0 <- max(1-a0-b0,1e-4) + p0 <- log(c(a0/rest0,b0/rest0)) + + unpack <- function(p) { + p <- clamp(p,-30,30) + ea <- exp(p[1]) + eb <- exp(p[2]) + den <- 1+ea+eb + c(a=0.999*ea/den,b=0.999*eb/den) + } + objective <- function(p) { + q <- unpack(p) + dcc_core(z,q["a"],q["b"])$nll + } + + opt <- tryCatch( + optim(p0,objective,method="BFGS",control=list(maxit=300,reltol=1e-8)), + error=function(e) NULL + ) + if (is.null(opt) || !is.finite(opt$value)) { + q <- c(a=a0,b=b0) + convergence <- 1L + } else { + q <- unpack(opt$par) + convergence <- opt$convergence + } + fit <- dcc_fit(z,unname(q["a"]),unname(q["b"])) + fit$convergence <- convergence + fit +} + t_copula_tail_dependence <- function(rho, df=6) { stopifnot(df > 0) rho <- clamp(rho,-0.999999,0.999999) - 2 * pt(-sqrt((df+1)*(1-rho)/(1+rho)), df=df+1) + 2 * pt(-sqrt((df+1)*(1-rho)/(1+rho)),df=df+1) } -calibrate_cross_asset <- function(return_matrix, a=0.02, b=0.97) { +estimate_t_df <- function(x) { + x <- as.numeric(x) + x <- x[is.finite(x)] + stopifnot(length(x) >= 50) + centered <- x-mean(x) + m2 <- mean(centered^2) + if (m2 <= eps) return(50) + excess <- mean(centered^4)/(m2^2)-3 + if (!is.finite(excess) || excess <= 0) return(50) + clamp(4+6/excess,4.1,100) +} + +calibrate_cross_asset <- function(return_matrix, a=NULL, b=NULL) { x <- as.matrix(return_matrix) stopifnot(nrow(x) >= 20, ncol(x) >= 2) fits <- lapply(seq_len(ncol(x)), function(j) garch11_fit(x[,j])) z <- do.call(cbind,lapply(fits,function(f) f$standardized)) - dcc <- dcc_fit(z,a,b) + dcc <- if (is.null(a) || is.null(b)) dcc_estimate(z) else dcc_fit(z,a,b) + df <- estimate_t_df(as.numeric(z)) + tail_dependence <- matrix(0,ncol(z),ncol(z)) + for (i in seq_len(ncol(z))) { + for (j in seq_len(ncol(z))) { + tail_dependence[i,j] <- if (i == j) 1 else + t_copula_tail_dependence(dcc$last_correlation[i,j],df) + } + } list( univariate=fits, standardized=z, dcc=dcc, + t_df=df, + tail_dependence=tail_dependence, last_correlation=dcc$last_correlation ) } @@ -532,6 +669,7 @@ calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { rv_window <- min(24L,max(4L,floor(length(r)/10))) rv <- realized_variance(r,rv_window) rough <- rough_vol_state(rv) + rough$eta <- rough$vol_of_log_vol/(dt^rough$hurst) prior <- normal_inverse_gamma_prior(mu=0,kappa=1,alpha=2,beta=max(var(r),1e-6)) posterior <- bayes_return_update(prior,r) @@ -582,7 +720,7 @@ m3a_horizon_specs <- function() { name=c("tick_hourly","daily","weekly","monthly","annual","five_year"), label=c("1h","24h","7d","30d","1y","5y"), years=c(1/(24*365),1/365,7/365,30/365,1,5), - model=c("heston","heston","merton","merton","heston","gbm"), + model=c("rough","heston","merton","merton","heston","gbm"), stringsAsFactors=FALSE ) } @@ -630,6 +768,14 @@ forecast_horizon <- function(state, horizon_name, paths=4000L, seed=1L) { samples <- switch( model, + rough=rough_vol_terminal( + state$spot, + state$mu, + max(state$rough$current_variance/state$dt,eps), + state$rough$hurst, + max(state$rough$eta,0), + step_dt,steps,paths,seed + ), heston=heston_terminal( state$spot, max(state$heston$v0,eps), From ff2760cd4471ef5a0fe257d330fbb4343a43a0a0 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:00:56 -0700 Subject: [PATCH 067/156] test: specify M2 to M3a hub integration --- .../economy/sims/statistical/integration.test | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core/src/economy/sims/statistical/integration.test diff --git a/core/src/economy/sims/statistical/integration.test b/core/src/economy/sims/statistical/integration.test new file mode 100644 index 0000000..13145ea --- /dev/null +++ b/core/src/economy/sims/statistical/integration.test @@ -0,0 +1,39 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +test m3a-runner-available-1.0 {R-backed statistical runner is available in M3a CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s statistical_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3a-to-hub-1.0 {price ticks calibrate M3a and publish a bounded prediction into the hub} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + set base 100.0 + for {set i 0} {$i < 120} {incr i} { + set price [expr {$base * exp(0.0005*$i + 0.01*sin($i/7.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + set p [$s statistical_from_feed TEST daily 1200 77] + set q [$s query_predictions trader-a statistical] + set out [list [dict get $p sim_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $q time_horizon]] + $s destroy + set out +} -result {statistical 1 1 TEST 24h} + +test m3a-insufficient-history-1.0 {M3a refuses calibration from a too-short M2 price history} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 20} {incr i} { + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s statistical_from_feed TEST daily 500 1} msg] + $s destroy + list $code $msg +} -result {1 insufficient_price_history} + +cleanupTests From 7bf8ab47a121a108914f1a79b4c1e1963bd1b4da Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:01:03 -0700 Subject: [PATCH 068/156] ci: exercise M2 to M3a hub integration --- .github/workflows/m3a-statistical.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml index 28ce310..031900b 100644 --- a/.github/workflows/m3a-statistical.yml +++ b/.github/workflows/m3a-statistical.yml @@ -30,3 +30,6 @@ jobs: - name: Run M3a native tests run: Rscript core/src/economy/sims/statistical/tests.R + + - name: Run M2 → M3a → Hub integration + run: tclsh core/src/economy/sims/statistical/integration.test From 1ee85617f21bce84978be1f981164a62ae640f04 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:01:24 -0700 Subject: [PATCH 069/156] M3a: handle single-step rough-vol horizon --- core/src/economy/sims/statistical/engine.R | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index d9f7fe7..eaf985b 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -327,7 +327,11 @@ hurst_rs <- function(x) { fgn_davies_harte <- function(n, H, seed=1L) { n <- as.integer(n) - stopifnot(n >= 2, H > 0, H < 1) + stopifnot(n >= 1, H > 0, H < 1) + if (n == 1) { + set.seed(seed) + return(rnorm(1)) + } k <- 0:n gamma <- 0.5 * ( abs(k-1)^(2*H) - 2*abs(k)^(2*H) + abs(k+1)^(2*H) From 3405a324f571835e98b4a73df9a878f1f1a0e276 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:01:43 -0700 Subject: [PATCH 070/156] M3a: add Tcl to R statistical runner --- core/src/economy/sims/statistical/runner.tcl | 60 ++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core/src/economy/sims/statistical/runner.tcl diff --git a/core/src/economy/sims/statistical/runner.tcl b/core/src/economy/sims/statistical/runner.tcl new file mode 100644 index 0000000..79645da --- /dev/null +++ b/core/src/economy/sims/statistical/runner.tcl @@ -0,0 +1,60 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::StatisticalRunner { + variable engine runtime + + constructor {engine_path {runtime_cmd Rscript}} { + set engine [file normalize $engine_path] + set runtime $runtime_cmd + } + + method available {} { + expr {[file exists $engine] && [auto_execok $runtime] ne ""} + } + + method _number {json key} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)} $key] + if {![regexp -- $pattern $json -> value]} { error "prediction_missing_$key" } + return $value + } + + method _string {json key} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*"([^"]*)"} $key] + if {![regexp -- $pattern $json -> value]} { error "prediction_missing_$key" } + return $value + } + + method parse_prediction {json} { + set p [dict create] + foreach key {value lower_bound upper_bound confidence correctness certainty recent_shift} { + dict set p $key [my _number $json $key] + } + foreach key {time_horizon sim_type token_ticker} { + dict set p $key [my _string $json $key] + } + dict set p timestamp [clock seconds] + return $p + } + + method query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + if {![my available]} { error "r_runtime_unavailable" } + if {[llength $prices] < 80} { error "insufficient_price_history" } + if {![regexp {^[A-Za-z0-9_.:-]+$} $ticker]} { error "invalid_ticker" } + if {[lsearch -exact {tick_hourly daily weekly monthly annual five_year} $horizon] < 0} { + error "unknown_horizon" + } + if {![string is integer -strict $paths] || $paths < 100} { error "invalid_paths" } + if {![string is integer -strict $seed]} { error "invalid_seed" } + if {![string is double -strict $dt] || $dt <= 0} { error "invalid_dt" } + + set encoded {} + foreach price $prices { + if {![string is double -strict $price] || $price <= 0} { error "invalid_price" } + lappend encoded [format %.17g $price] + } + set payload [format {"prices":[%s],"dt":%.17g,"token_ticker":"%s","horizon":"%s","paths":%d,"seed":%d} [join $encoded ,] $dt $ticker $horizon $paths $seed] + + set output [exec $runtime $engine << $payload] + return [my parse_prediction $output] + } +} From b66c514cfa33e4d55352f1482c213160968b7ee9 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:01:52 -0700 Subject: [PATCH 071/156] M3a: wire M2 price history through R engine into hub --- core/src/economy/stomach.tcl | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index d4b2082..a325dc5 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -7,14 +7,14 @@ set ::stomach::root $__stomach_dir foreach __stomach_file { traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl sims/registry.tcl sims/scheduler.tcl sims/hub.tcl - marketplace.tcl + sims/statistical/runner.tcl marketplace.tcl } { source [file join $__stomach_dir $__stomach_file] } unset __stomach_file oo::class create ::stomach::Economy { - variable traders wallets sae conductor feeds sims registry clock market taxes + variable traders wallets sae conductor feeds sims registry clock statistical_runner market taxes constructor {args} { set cap 256 if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } @@ -33,11 +33,12 @@ oo::class create ::stomach::Economy { set registry [::stomach::EngineRegistry new [file join $::stomach::root sims]] set clock [::stomach::HorizonClock new] $clock start + set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]] set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set taxes {} } destructor { - foreach obj [list $market $clock $registry $sims $feeds $conductor $sae $wallets $traders] { + foreach obj [list $market $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { catch {$obj destroy} } } @@ -57,6 +58,26 @@ oo::class create ::stomach::Economy { method feed_publish {args} { return [$feeds publish {*}$args] } method feed_history {feed_type} { return [$feeds history $feed_type] } method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } + method statistical_runner_available {} { return [$statistical_runner available] } + method statistical_query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + set p [$statistical_runner query $prices $ticker $horizon $paths $seed $dt] + $sims publish statistical $p + return $p + } + method statistical_from_feed {ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + set prices {} + foreach datum [$feeds history price_tick] { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token]} { continue } + if {$token ne $ticker} { continue } + if {[catch {dict get $payload price} price]} { continue } + if {![string is double -strict $price] || $price <= 0} { continue } + lappend prices $price + } + if {[llength $prices] < 80} { error "insufficient_price_history" } + return [my statistical_query $prices $ticker $horizon $paths $seed $dt] + } method query_predictions {trader_id sim_type} { return [$market predictions $trader_id $sim_type] } method sim_engines {} { return [$registry names] } method sim_engine_status {} { return [$registry status] } From 83408afe9cdb16339cdd7045847a8286b354e883 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:02:02 -0700 Subject: [PATCH 072/156] ci: gate M3a composition changes --- .github/workflows/m3a-statistical.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml index 031900b..8978468 100644 --- a/.github/workflows/m3a-statistical.yml +++ b/.github/workflows/m3a-statistical.yml @@ -6,6 +6,9 @@ on: - feat/stomach-economic-organ paths: - "core/src/economy/sims/statistical/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" - ".github/workflows/m3a-statistical.yml" pull_request: paths: From b81036281d692787fcefb4a5b98098f9923e9ea5 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:03:04 -0700 Subject: [PATCH 073/156] ci: fail M3a integration on tcltest failures --- .github/workflows/m3a-statistical.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml index 8978468..0974e4a 100644 --- a/.github/workflows/m3a-statistical.yml +++ b/.github/workflows/m3a-statistical.yml @@ -35,4 +35,8 @@ jobs: run: Rscript core/src/economy/sims/statistical/tests.R - name: Run M2 → M3a → Hub integration - run: tclsh core/src/economy/sims/statistical/integration.test + shell: bash + run: | + set -euo pipefail + tclsh core/src/economy/sims/statistical/integration.test | tee /tmp/m3a-integration.out + grep -Eq 'Total[[:space:]]+3[[:space:]]+Passed[[:space:]]+3.*Failed[[:space:]]+0' /tmp/m3a-integration.out From fb4aaec4f00ffebebf78409502bc539c124e165b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:03:38 -0700 Subject: [PATCH 074/156] docs: sync substantial M3a statistical implementation --- core/docs/plans/M3a-statistical-sims.md | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/core/docs/plans/M3a-statistical-sims.md b/core/docs/plans/M3a-statistical-sims.md index ab3e8d8..ea1234c 100644 --- a/core/docs/plans/M3a-statistical-sims.md +++ b/core/docs/plans/M3a-statistical-sims.md @@ -8,12 +8,19 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math **stochastic sample paths**, not behavioral agents. ## 2. Status / certainty -KERNEL IMPLEMENTED · R. `core/src/economy/sims/statistical/engine.R` contains GBM Monte -Carlo, Merton jump-diffusion, Heston full-truncation simulation, GARCH(1,1) QMLE, a rolling -Hurst estimator, regime classification, bounded Monte Carlo price predictions, and hand-rolled -JSON stdin/stdout. Native tests are in `tests.R`. Full HMM Viterbi, DCC/t-copula, and live -Bayesian recalibration remain incremental. Core quant methods C5; implementation C2; -live-market parameterization C1. +SUBSTANTIAL ENGINE IMPLEMENTED · R. `core/src/economy/sims/statistical/engine.R` +now implements GBM, Merton jump-diffusion, full-truncation Heston simulation, GARCH(1,1) QMLE, +three-state Gaussian HMM training + Viterbi decoding, Davies–Harte fractional Gaussian noise, +rough-volatility paths with estimated Hurst exponent, fitted DCC dynamic correlation, t-copula +tail-dependence with degrees-of-freedom estimation, conjugate Bayesian return calibration, +base-R ARIMA forecasting, historical VaR/Expected Shortfall, jump-intensity estimation, fitted +Heston proxy parameters including rho, cross-asset calibration, and six concurrent bounded +forecast horizons. A Tcl runner provides tested `M2 price_tick → R M3a → M3 hub → Marketplace` +integration. Native R CI and the boundary integration suite are green. Remaining research-depth +work is Heston characteristic-function/option-surface calibration, richer rough-vol parameter +estimation, historical backtest calibration of the three quality scores, and live multi-source +M2 adapters beyond normalized price history. Core methods C4/C5; implementation C3; +live-market parameterization remains C1/C2. ## 3. Language & location **R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only: @@ -66,8 +73,10 @@ the Hub stdin/stdout protocol is hand-rolled. - Calibration: ingests `price_tick` and `dex_pool_state` from M2 Data Feeds. ## 6. Dependencies & stubs -- M2 Data Feeds — price history for calibration; *stub:* canned price series. -- M3 Sims hub — lifecycle management; *stub:* manual init. +- M2 Data Feeds — normalized `price_tick` history is now consumed by the Tcl→R + integration path; RSS and DEX-pool cross-source calibration remain open. +- M3 Sims hub — M3a predictions are now published into the live hub and subsequently queried by + Traders through Marketplace. ## 7. Invariants / laws - **L1 (C5):** bounds are **statistical confidence intervals** — derived from the model's From f016a639d366f341ef2f99858cf8d146282631cd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:04:02 -0700 Subject: [PATCH 075/156] docs: expand M3a simulator description --- core/src/economy/sims/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md index 64d70a5..97b55f0 100644 --- a/core/src/economy/sims/README.md +++ b/core/src/economy/sims/README.md @@ -4,7 +4,7 @@ Seven native simulator engines live here behind the Tcl M3 hub. | ID | Engine | Native language | Implemented kernel | |---|---|---|---| -| M3a | statistical | R | GBM, Merton jump diffusion, Heston, GARCH(1,1), Hurst estimate, regime state, bounded MC forecast | +| M3a | statistical | R | GBM, Merton, Heston, GARCH(1,1), Gaussian HMM/Viterbi, Davies–Harte rough vol, fitted DCC, t-copula tails, Bayesian calibration, ARIMA, VaR/ES, six-horizon forecasts | | M3b | sociological | ECLiPSe Prolog | replicator dynamics, Hegselmann-Krause, complex contagion, pump/dump phase | | M3c | AMM/liquidity | Solidity + Foundry | fee-adjusted x*y=k, impermanent loss, slippage, IL-derived withdrawal | | M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | @@ -22,6 +22,6 @@ tclsh core/src/economy/sims/run_tests.tcl Pass `--strict` when the environment is expected to contain every external runtime. -The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design; their native test files are checked in next to their engines. +The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design; their native test files are checked in next to their engines. This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. From 59f778b3d69c74d87b9ea83ec9e175962ecefea8 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 17:04:06 -0700 Subject: [PATCH 076/156] docs: expose M3a stomach integration --- core/src/economy/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index ee69cb9..ec675e4 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. -- **M3 Sims** — all seven native engine trees are now built in: M3a R statistical, M3b ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster; the registry exposes source/runtime status through M0. +- **M3 Sims** — all seven native engine trees are built in. M3a is now a substantial R engine with calibrated HMM regimes, spectral rough volatility, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting and a tested M2→R→Hub path; M3b is ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. @@ -33,6 +33,6 @@ It executes Tcl + every native suite whose runtime is installed. Use `--strict` ## Public scaffold API -`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `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`, `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. From 2d12ce4a229b38d6ab1c02a1290e4871271b49c2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:03:31 -0700 Subject: [PATCH 077/156] test: require Heston surface calibration --- core/src/economy/sims/statistical/tests.R | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R index dfdc748..ab04e12 100644 --- a/core/src/economy/sims/statistical/tests.R +++ b/core/src/economy/sims/statistical/tests.R @@ -160,4 +160,40 @@ stopifnot(all(dim(cross$last_correlation) == c(3,3))) stopifnot(max(abs(diag(cross$last_correlation)-1)) < 1e-10) stopifnot(max(abs(cross$last_correlation-t(cross$last_correlation))) < 1e-10) + +# Heston characteristic-function pricing + option-surface calibration -------- +bs <- black_scholes_call(100,100,1,0.01,0,0.20) +heston_bs <- heston_call_price( + spot=100,strike=100,maturity=1,rate=0.01,dividend=0, + kappa=2,theta=0.04,xi=0,rho=-0.5,v0=0.04 +) +stopifnot(abs(bs-heston_bs) < 1e-8) + +true_heston <- list(kappa=1.8,theta=0.04,xi=0.35,rho=-0.55,v0=0.045) +surface <- expand.grid( + strike=c(90,100,110), + maturity=c(0.25,0.75,1.25) +) +surface$price <- mapply(function(k,t) { + heston_call_price( + 100,k,t,0.01,0, + true_heston$kappa,true_heston$theta,true_heston$xi, + true_heston$rho,true_heston$v0, + integration_points=768 + ) +}, surface$strike, surface$maturity) +start_heston <- c(kappa=0.8,theta=0.08,xi=0.18,rho=-0.1,v0=0.08) +start_rmse <- heston_surface_rmse( + start_heston,surface,spot=100,rate=0.01,dividend=0, + integration_points=384 +) +hcal <- calibrate_heston_surface( + surface,spot=100,rate=0.01,dividend=0,start=start_heston, + integration_points=384,maxit=120 +) +stopifnot(is.finite(hcal$rmse), hcal$rmse < start_rmse*0.45) +stopifnot(hcal$params$theta > 0, hcal$params$xi >= 0) +stopifnot(hcal$params$rho < 0, abs(hcal$params$rho) <= 1) +stopifnot(abs(hcal$params$theta-true_heston$theta) < 0.04) + cat("STATISTICAL TESTS PASSED\n") From c350d9e80c076b1b2f111f7f110dcfcae6f7e03f Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:05:32 -0700 Subject: [PATCH 078/156] M3a: add Heston characteristic-function calibration --- core/src/economy/sims/statistical/engine.R | 199 +++++++++++++++++++++ 1 file changed, 199 insertions(+) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index eaf985b..182149c 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -591,6 +591,205 @@ arima_forecast_base <- function(x, horizon=1L, order=c(1L,0L,0L)) { list(mean=as.numeric(pred$pred),sd=pmax(as.numeric(pred$se),0),fit=fit) } +# --- Heston characteristic-function pricing -------------------------------- + +black_scholes_call <- function(spot,strike,maturity,rate=0,dividend=0,sigma) { + stopifnot( + spot > 0, strike > 0, maturity >= 0, + is.finite(rate), is.finite(dividend), sigma >= 0 + ) + if (maturity == 0) return(max(spot-strike,0)) + discounted_spot <- spot*exp(-dividend*maturity) + discounted_strike <- strike*exp(-rate*maturity) + if (sigma <= 1e-14) return(max(discounted_spot-discounted_strike,0)) + vol_t <- sigma*sqrt(maturity) + d1 <- (log(spot/strike)+(rate-dividend+0.5*sigma^2)*maturity)/vol_t + d2 <- d1-vol_t + discounted_spot*pnorm(d1)-discounted_strike*pnorm(d2) +} + +heston_characteristic <- function( + u,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0) { + stopifnot( + spot > 0, maturity >= 0, kappa >= 0, theta >= 0, + xi > 0, abs(rho) <= 1, v0 >= 0 + ) + iu <- 1i*u + drift <- log(spot)+(rate-dividend)*maturity + d <- sqrt((kappa-rho*xi*iu)^2 + xi^2*(u^2+iu)) + g <- (kappa-rho*xi*iu-d)/(kappa-rho*xi*iu+d) + exp_dt <- exp(-d*maturity) + one_minus_g <- 1-g + one_minus_gexp <- 1-g*exp_dt + + C <- iu*drift + + (kappa*theta/xi^2) * ( + (kappa-rho*xi*iu-d)*maturity - + 2*log(one_minus_gexp/one_minus_g) + ) + D <- ((kappa-rho*xi*iu-d)/xi^2) * + ((1-exp_dt)/one_minus_gexp) + exp(C + D*v0) +} + +trapz_real <- function(x,y) { + x <- as.numeric(x) + y <- as.numeric(y) + stopifnot(length(x) == length(y), length(x) >= 2) + sum(diff(x)*(head(y,-1)+tail(y,-1))*0.5) +} + +heston_call_price <- function( + spot,strike,maturity,rate=0,dividend=0, + kappa,theta,xi,rho,v0, + integration_points=1024L,integration_limit=100) { + stopifnot( + spot > 0, strike > 0, maturity >= 0, + kappa >= 0, theta >= 0, xi >= 0, abs(rho) <= 1, v0 >= 0, + integration_points >= 64, integration_limit > 0 + ) + if (maturity == 0) return(max(spot-strike,0)) + + # With no vol-of-vol, variance is deterministic under CIR mean reversion. + if (xi <= 1e-12) { + integrated_variance <- if (kappa <= 1e-12) { + v0*maturity + } else { + theta*maturity + (v0-theta)*(1-exp(-kappa*maturity))/kappa + } + sigma_eff <- sqrt(max(integrated_variance/maturity,0)) + return(black_scholes_call( + spot,strike,maturity,rate,dividend,sigma_eff + )) + } + + n <- as.integer(integration_points) + u <- seq(1e-5,integration_limit,length.out=n) + phi_u <- heston_characteristic( + u,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + phi_u_minus_i <- heston_characteristic( + u-1i,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + phi_minus_i <- heston_characteristic( + -1i,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + oscillation <- exp(-1i*u*log(strike)) + + integrand1 <- Re( + oscillation*phi_u_minus_i/(1i*u*phi_minus_i) + ) + integrand2 <- Re( + oscillation*phi_u/(1i*u) + ) + p1 <- 0.5 + trapz_real(u,integrand1)/pi + p2 <- 0.5 + trapz_real(u,integrand2)/pi + + raw <- spot*exp(-dividend*maturity)*p1 - + strike*exp(-rate*maturity)*p2 + lower <- max( + spot*exp(-dividend*maturity)-strike*exp(-rate*maturity),0 + ) + upper <- spot*exp(-dividend*maturity) + clamp(Re(raw),lower,upper) +} + +heston_params_vector <- function(params) { + q <- unlist(params[c("kappa","theta","xi","rho","v0")],use.names=TRUE) + if (length(q) != 5 || any(!is.finite(q))) stop("invalid_heston_params") + q +} + +heston_surface_rmse <- function( + params,surface,spot,rate=0,dividend=0,integration_points=512L) { + q <- heston_params_vector(params) + required <- c("strike","maturity","price") + if (!all(required %in% names(surface))) stop("invalid_option_surface") + predicted <- mapply( + function(strike,maturity) { + heston_call_price( + spot,strike,maturity,rate,dividend, + q["kappa"],q["theta"],q["xi"],q["rho"],q["v0"], + integration_points=integration_points + ) + }, + surface$strike,surface$maturity + ) + weights <- if ("weight" %in% names(surface)) { + pmax(as.numeric(surface$weight),0) + } else { + rep(1,nrow(surface)) + } + if (sum(weights) <= 0) stop("invalid_surface_weights") + sqrt(sum(weights*(predicted-surface$price)^2)/sum(weights)) +} + +calibrate_heston_surface <- function( + surface,spot,rate=0,dividend=0, + start=c(kappa=1.5,theta=0.04,xi=0.3,rho=-0.5,v0=0.04), + integration_points=512L,maxit=200L) { + start <- heston_params_vector(start) + stopifnot( + start["kappa"] > 0, start["theta"] > 0, + start["xi"] >= 0, abs(start["rho"]) < 1, start["v0"] > 0 + ) + + encode <- function(q) { + c( + log(max(q["kappa"],1e-8)), + log(max(q["theta"],1e-8)), + log(max(q["xi"],1e-8)), + atanh(clamp(q["rho"],-0.999,0.999)), + log(max(q["v0"],1e-8)) + ) + } + decode <- function(p) { + c( + kappa=exp(clamp(p[1],-12,8)), + theta=exp(clamp(p[2],-12,2)), + xi=exp(clamp(p[3],-12,3)), + rho=tanh(p[4]), + v0=exp(clamp(p[5],-12,2)) + ) + } + objective <- function(p) { + q <- decode(p) + err <- tryCatch( + heston_surface_rmse( + q,surface,spot,rate,dividend,integration_points + ), + error=function(e) Inf + ) + if (!is.finite(err)) 1e12 else err + } + + initial_rmse <- objective(encode(start)) + opt <- tryCatch( + optim( + encode(start),objective,method="Nelder-Mead", + control=list(maxit=as.integer(maxit),reltol=1e-7) + ), + error=function(e) NULL + ) + if (is.null(opt) || !is.finite(opt$value)) { + params <- start + rmse <- initial_rmse + convergence <- 1L + } else { + params <- decode(opt$par) + rmse <- objective(opt$par) + convergence <- opt$convergence + } + + list( + params=as.list(params), + rmse=rmse, + start_rmse=initial_rmse, + convergence=convergence, + observations=nrow(surface) + ) +} + # --- Risk and parameter proxies -------------------------------------------- historical_var_es <- function(returns, alpha=0.99) { From 57bab0958c8de2e83f461e18e2e457ed252348e5 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:07:02 -0700 Subject: [PATCH 079/156] test: require rough calibration and empirical M3a scoring --- core/src/economy/sims/statistical/tests.R | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R index ab04e12..147af78 100644 --- a/core/src/economy/sims/statistical/tests.R +++ b/core/src/economy/sims/statistical/tests.R @@ -196,4 +196,41 @@ stopifnot(hcal$params$theta > 0, hcal$params$xi >= 0) stopifnot(hcal$params$rho < 0, abs(hcal$params$rho) <= 1) stopifnot(abs(hcal$params$theta-true_heston$theta) < 0.04) + +# Rough-vol parameter calibration -------------------------------------------- +set.seed(480) +rough_true_h <- 0.28 +rough_true_eta <- 0.55 +rough_dt <- 1/365 +rough_noise <- fgn_davies_harte(4096,rough_true_h,481) +rough_logv <- log(0.04) + + rough_true_eta*(rough_dt^rough_true_h)*cumsum(rough_noise) +rough_fit <- fit_rough_volatility(exp(rough_logv),rough_dt) +stopifnot(abs(rough_fit$hurst-rough_true_h) < 0.08) +stopifnot(abs(rough_fit$eta-rough_true_eta)/rough_true_eta < 0.35) +stopifnot(rough_fit$r_squared > 0.80) + +# Walk-forward empirical quality scores -------------------------------------- +set.seed(482) +bt_returns <- rnorm(420,0.0004,0.012) +bt_prices <- 100*exp(cumsum(bt_returns)) +quality <- backtest_quality_scores( + bt_prices,dt=1/365,min_train=120,max_points=24 +) +stopifnot(quality$source == "walk_forward") +stopifnot(quality$observations >= 20) +stopifnot(quality$coverage >= 0, quality$coverage <= 1) +stopifnot(quality$median_relative_error >= 0) +for (metric in c("confidence","correctness","certainty")) { + stopifnot(quality[[metric]] >= 0, quality[[metric]] <= 10) +} + +quality_state <- calibrate_market( + bt_prices,dt=1/365,ticker="BACKTEST",quality_points=24 +) +stopifnot(quality_state$quality$source == "walk_forward") +stopifnot(abs(quality_state$correctness-quality_state$quality$correctness) < 1e-12) +stopifnot(abs(quality_state$confidence-quality_state$quality$confidence) < 1e-12) +stopifnot(abs(quality_state$certainty-quality_state$quality$certainty) < 1e-12) + cat("STATISTICAL TESTS PASSED\n") From 23a13e3fb35b8c8d621c138b7623581c8d6d2b40 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:08:55 -0700 Subject: [PATCH 080/156] M3a: fit rough volatility and score forecasts empirically --- core/src/economy/sims/statistical/engine.R | 146 +++++++++++++++++++-- 1 file changed, 138 insertions(+), 8 deletions(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index 182149c..69956b1 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -410,6 +410,38 @@ rough_vol_state <- function(realized_variance_series) { ) } +fit_rough_volatility <- function(realized_variance_series,dt,max_lag=NULL) { + rv <- pmax(as.numeric(realized_variance_series),eps) + stopifnot(length(rv) >= 64, dt > 0, all(is.finite(rv))) + logv <- log(rv) + n <- length(logv) + if (is.null(max_lag)) max_lag <- min(64L,floor(n/8)) + max_lag <- max(4L,min(as.integer(max_lag),floor(n/3))) + lags <- unique(as.integer(round(exp(seq(log(1),log(max_lag),length.out=14))))) + lags <- lags[lags >= 1 & lags < n] + variogram <- vapply(lags,function(lag) { + mean((logv[(lag+1):n]-logv[1:(n-lag)])^2) + },numeric(1)) + keep <- is.finite(variogram) & variogram > 0 + if (sum(keep) < 3) stop("rough_vol_insufficient_variogram") + x <- log(lags[keep]*dt) + y <- log(variogram[keep]) + fit <- lm(y ~ x) + slope <- unname(coef(fit)[2]) + intercept <- unname(coef(fit)[1]) + H <- clamp(slope/2,0.02,0.98) + eta <- sqrt(max(exp(intercept),eps)) + r2 <- summary(fit)$r.squared + if (!is.finite(r2)) r2 <- 0 + list( + hurst=H, + eta=eta, + r_squared=clamp(r2,0,1), + lags=lags[keep], + variogram=variogram[keep] + ) +} + # --- DCC correlation + t-copula -------------------------------------------- dcc_core <- function(standardized_returns, a, b) { @@ -857,9 +889,94 @@ coverage_correctness <- function(standardized_returns, target=0.95) { clamp(10 - 25*abs(observed-target),0,10) } +backtest_quality_scores <- function( + prices,dt,min_train=80L,max_points=24L,target_coverage=0.95) { + p <- as.numeric(prices) + stopifnot( + length(p) >= 40, all(is.finite(p)), all(p > 0), dt > 0, + max_points >= 5, target_coverage > 0.5, target_coverage < 1 + ) + r <- returns_from_prices(p) + min_train <- as.integer(min(min_train,length(r)-5L)) + min_train <- max(20L,min_train) + if (length(r) <= min_train) stop("insufficient_backtest_history") + + base_fit <- garch11_fit(r[seq_len(min_train)]) + perturb_start <- max(1L,as.integer(floor(min_train*0.1))) + perturbed_fit <- garch11_fit(r[perturb_start:min_train]) + + h_base <- tail(base_fit$variance,1) + h_pert <- tail(perturbed_fit$variance,1) + rows <- vector("list",length(r)-min_train) + + for (t in (min_train+1L):length(r)) { + prev_base_error <- r[t-1L]-base_fit$mean + prev_pert_error <- r[t-1L]-perturbed_fit$mean + h_base <- max( + eps, + base_fit$omega + + base_fit$alpha*prev_base_error^2 + + base_fit$beta*h_base + ) + h_pert <- max( + eps, + perturbed_fit$omega + + perturbed_fit$alpha*prev_pert_error^2 + + perturbed_fit$beta*h_pert + ) + + sigma_base <- sqrt(h_base) + sigma_pert <- sqrt(h_pert) + lo <- base_fit$mean-qnorm((1+target_coverage)/2)*sigma_base + hi <- base_fit$mean+qnorm((1+target_coverage)/2)*sigma_base + actual <- r[t] + rows[[t-min_train]] <- c( + covered=as.numeric(actual >= lo && actual <= hi), + relative_error=abs(exp(actual)-exp(base_fit$mean)), + relative_width=exp(hi)-exp(lo), + perturbation=abs(sigma_base-sigma_pert)/max(sigma_base,eps) + ) + } + + mat <- do.call(rbind,rows) + if (nrow(mat) > max_points) { + mat <- tail(mat,as.integer(max_points)) + } + coverage <- mean(mat[,"covered"]) + med_err <- median(mat[,"relative_error"]) + med_width <- median(mat[,"relative_width"]) + med_perturb <- median(mat[,"perturbation"]) + + coverage_score <- clamp( + 10 - 40*abs(coverage-target_coverage),0,10 + ) + error_score <- 10*exp(-med_err/0.03) + sharpness_score <- 10*exp(-med_width/0.20) + correctness <- clamp( + 0.55*coverage_score + 0.45*error_score,0,10 + ) + confidence <- clamp( + 0.65*coverage_score + 0.35*sharpness_score,0,10 + ) + certainty <- clamp(10*exp(-4*med_perturb),0,10) + + list( + source="walk_forward", + observations=nrow(mat), + coverage=coverage, + median_relative_error=med_err, + median_relative_width=med_width, + median_perturbation=med_perturb, + confidence=confidence, + correctness=correctness, + certainty=certainty + ) +} + # --- Calibration state ------------------------------------------------------ -calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { +calibrate_market <- function( + prices,dt=1/365,ticker="ASSET",quality_points=16L) { p <- as.numeric(prices) stopifnot(length(p) >= 80, all(is.finite(p)), all(p > 0), dt > 0) r <- returns_from_prices(p) @@ -872,7 +989,10 @@ calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { rv_window <- min(24L,max(4L,floor(length(r)/10))) rv <- realized_variance(r,rv_window) rough <- rough_vol_state(rv) - rough$eta <- rough$vol_of_log_vol/(dt^rough$hurst) + rough_fit <- fit_rough_volatility(rv,dt) + rough$hurst <- rough_fit$hurst + rough$eta <- rough_fit$eta + rough$r_squared <- rough_fit$r_squared prior <- normal_inverse_gamma_prior(mu=0,kappa=1,alpha=2,beta=max(var(r),1e-6)) posterior <- bayes_return_update(prior,r) @@ -894,6 +1014,14 @@ calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { last_posterior <- tail(hmm$posterior,1) regime_certainty <- max(last_posterior) + bt_min_train <- min( + 80L,max(20L,as.integer(floor(length(r)*0.60))) + ) + quality <- backtest_quality_scores( + p,dt,min_train=bt_min_train, + max_points=max(5L,as.integer(quality_points)) + ) + list( ticker=ticker, spot=tail(p,1), @@ -910,7 +1038,10 @@ calibrate_market <- function(prices, dt=1/365, ticker="ASSET") { jump=jump, heston=heston, risk=historical_var_es(r,0.99), - correctness=coverage_correctness(g$standardized), + quality=quality, + confidence=quality$confidence, + correctness=quality$correctness, + certainty=quality$certainty, recent_shift=recent_shift, calibrated_at=as.numeric(Sys.time()) ) @@ -932,14 +1063,13 @@ bounded_from_samples <- function(samples, state, label, model) { q <- as.numeric(quantile(samples,c(.025,.5,.975),names=FALSE,type=8)) width <- (q[3]-q[1])/max(abs(q[2]),eps) confidence <- clamp( - 0.55*state$correctness + - 4.5*state$regime_certainty + - 2.0*(1-clamp(width,0,1)), + 0.75*state$confidence + + 0.25*10*(1-clamp(width,0,1)), 0,10 ) certainty <- clamp( - 5.0*state$regime_certainty + - 5.0*(1-clamp(width,0,1)), + 0.75*state$certainty + + 0.25*10*(1-clamp(width,0,1)), 0,10 ) list( From 5830036f9b310e103d1b6046eeaf8d3a6e755f2c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:10:43 -0700 Subject: [PATCH 081/156] test: require complete M3a query contract --- core/src/economy/sims/statistical/tests.R | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R index 147af78..7e33fd8 100644 --- a/core/src/economy/sims/statistical/tests.R +++ b/core/src/economy/sims/statistical/tests.R @@ -233,4 +233,48 @@ stopifnot(abs(quality_state$correctness-quality_state$quality$correctness) < 1e- stopifnot(abs(quality_state$confidence-quality_state$quality$confidence) < 1e-12) stopifnot(abs(quality_state$certainty-quality_state$quality$certainty) < 1e-12) + +# Full M3a prediction-type contract + DEX pool calibration ------------------- +pool_prices <- c(99.8,100.1,100.0,100.2) +pool_liquidity <- c(1.0e6,2.0e6,1.5e6,0.5e6) +pool_state <- calibrate_market( + bt_prices,dt=1/365,ticker="POOL", + pool_prices=pool_prices,pool_liquidity=pool_liquidity, + quality_points=12 +) +stopifnot(pool_state$pool$observations == 4) +stopifnot(abs(pool_state$pool$spot-weighted.mean(pool_prices,pool_liquidity)) < 1e-10) +stopifnot(all(c("price_tick","dex_pool_state") %in% pool_state$calibration_sources)) + +typed <- c( + "price_forecast","volatility_surface","var_calculation", + "regime_state","rough_vol_estimate","jump_intensity" +) +for (prediction_type in typed) { + q <- statistical_prediction( + pool_state,prediction_type,horizon="daily",paths=800,seed=520 + ) + stopifnot(q$prediction_type == prediction_type) + stopifnot(is.numeric(q$value),length(q$value) == 1,is.finite(q$value)) + stopifnot(q$lower_bound <= q$value,q$value <= q$upper_bound) + stopifnot(q$confidence >= 0,q$confidence <= 10) + stopifnot(q$correctness >= 0,q$correctness <= 10) + stopifnot(q$certainty >= 0,q$certainty <= 10) +} +regime_prediction <- statistical_prediction( + pool_state,"regime_state",horizon="current",paths=800,seed=521 +) +stopifnot(regime_prediction$label %in% c("bear","neutral","bull")) +stopifnot(regime_prediction$value >= 0,regime_prediction$value <= 1) + +cross_state <- pool_state +cross_state$cross_asset <- cross +corr_prediction <- statistical_prediction( + cross_state,"correlation_matrix",horizon="current",paths=800,seed=522 +) +stopifnot(corr_prediction$prediction_type == "correlation_matrix") +stopifnot(all(dim(corr_prediction$matrix) == c(3,3))) +stopifnot(corr_prediction$lower_bound <= corr_prediction$value) +stopifnot(corr_prediction$value <= corr_prediction$upper_bound) + cat("STATISTICAL TESTS PASSED\n") From f6c5246715f5f0e34156f1f2ed447efd8f50ecfc Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:10:46 -0700 Subject: [PATCH 082/156] test: require pool and typed M3a integration --- .../economy/sims/statistical/integration.test | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/core/src/economy/sims/statistical/integration.test b/core/src/economy/sims/statistical/integration.test index 13145ea..342702b 100644 --- a/core/src/economy/sims/statistical/integration.test +++ b/core/src/economy/sims/statistical/integration.test @@ -36,4 +36,33 @@ test m3a-insufficient-history-1.0 {M3a refuses calibration from a too-short M2 p list $code $msg } -result {1 insufficient_price_history} +test m2-pool-to-m3a-1.0 {DEX pool state participates in M3a calibration} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + for {set i 0} {$i < 120} {incr i} { + set price [expr {100.0 * exp(0.0003*$i + 0.006*sin($i/9.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + foreach {ts price liq} {100 103.1 1000000 101 103.3 1500000 102 103.2 2000000} { + $s feed_publish dex_pool_state dex $ts [dict create token_ticker TEST price $price liquidity $liq] 8.5 + } + set p [$s statistical_from_feed_type TEST volatility_surface daily 700 91] + set out [list [dict get $p prediction_type] [dict get $p calibration_sources]] + $s destroy + set out +} -result {volatility_surface price_tick,dex_pool_state} + +test m3a-regime-query-1.0 {categorical regime is carried as label on a bounded numeric posterior} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + for {set i 0} {$i < 120} {incr i} { + set price [expr {100.0 * exp(-0.0008*$i + 0.003*sin($i/5.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + set p [$s statistical_from_feed_type TEST regime_state current 700 92] + set out [list [dict get $p prediction_type] [expr {[lsearch -exact {bear neutral bull} [dict get $p label]] >= 0}] [expr {[dict get $p lower_bound] <= [dict get $p value] && [dict get $p value] <= [dict get $p upper_bound]}]] + $s destroy + set out +} -result {regime_state 1 1} + cleanupTests From 18d0ca0008e5e7c1fba675d0bd67fded51cd98df Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:13:07 -0700 Subject: [PATCH 083/156] M3a: implement typed predictions and pool calibration --- core/src/economy/sims/statistical/engine.R | 268 ++++++++++++++++++++- 1 file changed, 260 insertions(+), 8 deletions(-) diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R index 69956b1..9593f99 100644 --- a/core/src/economy/sims/statistical/engine.R +++ b/core/src/economy/sims/statistical/engine.R @@ -433,8 +433,11 @@ fit_rough_volatility <- function(realized_variance_series,dt,max_lag=NULL) { eta <- sqrt(max(exp(intercept),eps)) r2 <- summary(fit)$r.squared if (!is.finite(r2)) r2 <- 0 + slope_se <- summary(fit)$coefficients["x","Std. Error"] + if (!is.finite(slope_se)) slope_se <- 0 list( hurst=H, + hurst_se=max(slope_se/2,0), eta=eta, r_squared=clamp(r2,0,1), lags=lags[keep], @@ -973,10 +976,44 @@ backtest_quality_scores <- function( ) } +pool_calibration <- function(pool_prices,pool_liquidity=NULL,reference_spot) { + px <- as.numeric(pool_prices) + if (!length(px)) { + return(list( + observations=0L,spot=NA_real_,basis=0,dispersion=0, + total_liquidity=0,agreement=1 + )) + } + keep <- is.finite(px) & px > 0 + px <- px[keep] + if (!length(px)) stop("invalid_pool_prices") + liq <- if (is.null(pool_liquidity) || !length(pool_liquidity)) { + rep(1,length(px)) + } else { + raw <- as.numeric(pool_liquidity) + if (length(raw) != length(keep)) stop("pool_liquidity_length") + raw <- raw[keep] + ifelse(is.finite(raw) & raw > 0,raw,0) + } + if (sum(liq) <= 0) liq <- rep(1,length(px)) + spot <- weighted.mean(px,liq) + dispersion <- sqrt(weighted.mean((px-spot)^2,liq))/spot + basis <- spot/reference_spot-1 + list( + observations=length(px), + spot=spot, + basis=basis, + dispersion=dispersion, + total_liquidity=sum(liq), + agreement=exp(-20*abs(basis)) + ) +} + # --- Calibration state ------------------------------------------------------ calibrate_market <- function( - prices,dt=1/365,ticker="ASSET",quality_points=16L) { + prices,dt=1/365,ticker="ASSET",quality_points=16L, + pool_prices=numeric(),pool_liquidity=numeric()) { p <- as.numeric(prices) stopifnot(length(p) >= 80, all(is.finite(p)), all(p > 0), dt > 0) r <- returns_from_prices(p) @@ -1021,6 +1058,17 @@ calibrate_market <- function( p,dt,min_train=bt_min_train, max_points=max(5L,as.integer(quality_points)) ) + pool <- pool_calibration( + pool_prices,pool_liquidity,reference_spot=tail(p,1) + ) + calibration_sources <- c( + "price_tick", + if (pool$observations > 0) "dex_pool_state" else NULL + ) + pool_certainty_factor <- 0.75 + 0.25*pool$agreement + quality$certainty <- clamp( + quality$certainty*pool_certainty_factor,0,10 + ) list( ticker=ticker, @@ -1038,6 +1086,8 @@ calibrate_market <- function( jump=jump, heston=heston, risk=historical_var_es(r,0.99), + pool=pool, + calibration_sources=calibration_sources, quality=quality, confidence=quality$confidence, correctness=quality$correctness, @@ -1164,6 +1214,173 @@ bounded_price_prediction <- function(s0, mu, sigma, dt, steps, ) } +horizon_metadata <- function(horizon) { + if (horizon == "current") { + return(list(label="current",years=0,steps=0L)) + } + specs <- m3a_horizon_specs() + row <- specs[specs$name == horizon,,drop=FALSE] + if (!nrow(row)) stop("unknown_horizon") + list( + label=row$label[1], + years=row$years[1], + steps=max(1L,min(365L,as.integer(ceiling(row$years[1]*365)))) + ) +} + +bounded_scalar_prediction <- function( + state,prediction_type,value,lower,upper,horizon, + label=NULL,matrix=NULL,detail=NULL) { + if (!is.finite(value) || !is.finite(lower) || !is.finite(upper)) { + stop("nonfinite_prediction") + } + if (lower > value || value > upper) stop("prediction_out_of_bounds") + h <- horizon_metadata(horizon) + out <- list( + value=as.numeric(value), + lower_bound=as.numeric(lower), + upper_bound=as.numeric(upper), + confidence=clamp(state$confidence,0,10), + correctness=clamp(state$correctness,0,10), + certainty=clamp(state$certainty,0,10), + time_horizon=h$label, + sim_type="statistical", + token_ticker=state$ticker, + recent_shift=state$recent_shift, + prediction_type=prediction_type, + calibration_sources=paste(state$calibration_sources,collapse=",") + ) + if (!is.null(label)) out$label <- label + if (!is.null(matrix)) out$matrix <- matrix + if (!is.null(detail)) out$detail <- detail + out +} + +heston_variance_terminal <- function( + v0,kappa,theta,xi,dt,steps,paths,seed=1L) { + stopifnot( + v0 >= 0,kappa >= 0,theta >= 0,xi >= 0, + dt > 0,steps >= 1,paths >= 2 + ) + set.seed(seed) + v <- rep(v0,paths) + for (i in seq_len(steps)) { + vp <- pmax(v,0) + v <- pmax( + v + kappa*(theta-vp)*dt + xi*sqrt(vp*dt)*rnorm(paths), + 0 + ) + } + v +} + +statistical_prediction <- function( + state,prediction_type="price_forecast", + horizon="daily",paths=4000L,seed=1L) { + allowed <- c( + "price_forecast","volatility_surface","var_calculation", + "correlation_matrix","regime_state","rough_vol_estimate", + "jump_intensity" + ) + if (!(prediction_type %in% allowed)) stop("unknown_prediction_type") + + if (prediction_type == "price_forecast") { + p <- forecast_horizon(state,horizon,paths,seed) + p$prediction_type <- prediction_type + p$calibration_sources <- paste(state$calibration_sources,collapse=",") + return(p) + } + + if (prediction_type == "volatility_surface") { + h <- horizon_metadata(horizon) + years <- max(h$years,state$dt) + steps <- max(1L,h$steps) + vars <- heston_variance_terminal( + max(state$heston$v0,eps), + max(state$heston$kappa,0), + max(state$heston$theta,eps), + max(state$heston$xi,0), + years/steps,steps,paths,seed + ) + vols <- sqrt(pmax(vars,0)) + q <- as.numeric(quantile(vols,c(.025,.5,.975),names=FALSE,type=8)) + return(bounded_scalar_prediction( + state,prediction_type,q[2],q[1],q[3],horizon, + detail=sprintf("heston_vol;rho=%.6g",state$heston$rho) + )) + } + + if (prediction_type == "var_calculation") { + h <- horizon_metadata(horizon) + scale <- sqrt(max(h$years/state$dt,1)) + r95 <- historical_var_es(state$returns,0.95) + r99 <- state$risk + return(bounded_scalar_prediction( + state,prediction_type, + r99$var*scale, + min(r95$var,r99$var)*scale, + max(r99$expected_shortfall,r99$var)*scale, + horizon, + detail="historical_var_99" + )) + } + + if (prediction_type == "regime_state") { + posterior <- tail(state$hmm$posterior,1) + p <- as.numeric(posterior[1,state$regime]) + n_eff <- max(1,nrow(state$hmm$posterior)) + se <- sqrt(max(p*(1-p)/n_eff,0)) + lo <- clamp(p-1.96*se,0,1) + hi <- clamp(p+1.96*se,0,1) + return(bounded_scalar_prediction( + state,prediction_type,p,lo,hi,horizon,label=state$regime + )) + } + + if (prediction_type == "rough_vol_estimate") { + h <- state$rough$hurst + se <- if (!is.null(state$rough$hurst_se)) state$rough$hurst_se else 0 + return(bounded_scalar_prediction( + state,prediction_type,h, + clamp(h-1.96*se,0.001,0.999), + clamp(h+1.96*se,0.001,0.999), + horizon, + detail=sprintf("eta=%.6g;r2=%.6g",state$rough$eta,state$rough$r_squared) + )) + } + + if (prediction_type == "jump_intensity") { + exposure <- length(state$returns)*state$dt + lambda <- state$jump$lambda + se <- sqrt(max(state$jump$count,1))/max(exposure,eps) + return(bounded_scalar_prediction( + state,prediction_type,lambda, + max(0,lambda-1.96*se), + lambda+1.96*se, + horizon, + detail=sprintf("jumps=%d",state$jump$count) + )) + } + + if (prediction_type == "correlation_matrix") { + if (is.null(state$cross_asset)) stop("cross_asset_unavailable") + m <- state$cross_asset$last_correlation + if (!is.matrix(m) || nrow(m) < 2) stop("cross_asset_unavailable") + vals <- m[upper.tri(m)] + value <- mean(vals) + return(bounded_scalar_prediction( + state,prediction_type,value,min(vals),max(vals),horizon, + matrix=m, + detail=paste( + apply(m,1,function(row) paste(format(row,digits=8),collapse=",")), + collapse=";" + ) + )) + } + + stop("unreachable_prediction_type") +} + # --- Minimal hand-rolled JSON line protocol -------------------------------- json_number <- function(line, key, default) { @@ -1188,12 +1405,37 @@ json_number_array <- function(line, key) { as.numeric(strsplit(z[2],",",fixed=TRUE)[[1]]) } +json_escape <- function(x) { + x <- gsub("\\\\","\\\\\\\\",as.character(x)) + gsub('"','\\\\"',x,fixed=TRUE) +} + emit_prediction <- function(p) { - cat(sprintf( - '{"value":%.10g,"lower_bound":%.10g,"upper_bound":%.10g,"confidence":%.4f,"correctness":%.4f,"certainty":%.4f,"time_horizon":"%s","sim_type":"statistical","token_ticker":"%s","recent_shift":%.10g}\n', - p$value,p$lower_bound,p$upper_bound,p$confidence,p$correctness, - p$certainty,p$time_horizon,p$token_ticker,p$recent_shift - )) + fields <- c( + sprintf('"value":%.10g',p$value), + sprintf('"lower_bound":%.10g',p$lower_bound), + sprintf('"upper_bound":%.10g',p$upper_bound), + sprintf('"confidence":%.4f',p$confidence), + sprintf('"correctness":%.4f',p$correctness), + sprintf('"certainty":%.4f',p$certainty), + sprintf('"time_horizon":"%s"',json_escape(p$time_horizon)), + '"sim_type":"statistical"', + sprintf('"token_ticker":"%s"',json_escape(p$token_ticker)), + sprintf('"recent_shift":%.10g',p$recent_shift), + sprintf('"prediction_type":"%s"',json_escape( + if (is.null(p$prediction_type)) "price_forecast" else p$prediction_type + )), + sprintf('"calibration_sources":"%s"',json_escape( + if (is.null(p$calibration_sources)) "price_tick" else p$calibration_sources + )) + ) + if (!is.null(p$label)) { + fields <- c(fields,sprintf('"label":"%s"',json_escape(p$label))) + } + if (!is.null(p$detail)) { + fields <- c(fields,sprintf('"detail":"%s"',json_escape(p$detail))) + } + cat(sprintf("{%s}\n",paste(fields,collapse=","))) } main <- function() { @@ -1205,10 +1447,18 @@ main <- function() { dt <- json_number(line,"dt",1/365) ticker <- json_string(line,"token_ticker","ASSET") horizon <- json_string(line,"horizon","daily") + prediction_type <- json_string(line,"prediction_type","price_forecast") paths <- as.integer(json_number(line,"paths",4000)) seed <- as.integer(json_number(line,"seed",1)) - state <- calibrate_market(prices,dt,ticker) - emit_prediction(forecast_horizon(state,horizon,paths,seed)) + pool_prices <- json_number_array(line,"pool_prices") + pool_liquidity <- json_number_array(line,"pool_liquidity") + state <- calibrate_market( + prices,dt,ticker, + pool_prices=pool_prices,pool_liquidity=pool_liquidity + ) + emit_prediction(statistical_prediction( + state,prediction_type,horizon,paths,seed + )) } else { p <- bounded_price_prediction( json_number(line,"spot",100), @@ -1221,6 +1471,8 @@ main <- function() { json_string(line,"time_horizon","24h"), json_string(line,"token_ticker","ASSET") ) + p$prediction_type <- "price_forecast" + p$calibration_sources <- "price_tick" emit_prediction(p) } } From 17e7cfe91ddab3a8370134d3fcb1633857f4c8a5 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:13:42 -0700 Subject: [PATCH 084/156] M3a: expose typed R runner protocol --- core/src/economy/sims/statistical/runner.tcl | 47 ++++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/core/src/economy/sims/statistical/runner.tcl b/core/src/economy/sims/statistical/runner.tcl index 79645da..60f002e 100644 --- a/core/src/economy/sims/statistical/runner.tcl +++ b/core/src/economy/sims/statistical/runner.tcl @@ -24,23 +24,44 @@ oo::class create ::stomach::StatisticalRunner { return $value } + method _optional_string {json key {default ""}} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*"([^"]*)"} $key] + if {![regexp -- $pattern $json -> value]} { return $default } + return $value + } + method parse_prediction {json} { set p [dict create] foreach key {value lower_bound upper_bound confidence correctness certainty recent_shift} { dict set p $key [my _number $json $key] } - foreach key {time_horizon sim_type token_ticker} { + foreach key {time_horizon sim_type token_ticker prediction_type calibration_sources} { dict set p $key [my _string $json $key] } + foreach key {label detail} { + set value [my _optional_string $json $key] + if {$value ne ""} { dict set p $key $value } + } dict set p timestamp [clock seconds] return $p } - method query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + method query_typed { + prices ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + {pool_prices {}} {pool_liquidity {}} + } { if {![my available]} { error "r_runtime_unavailable" } if {[llength $prices] < 80} { error "insufficient_price_history" } if {![regexp {^[A-Za-z0-9_.:-]+$} $ticker]} { error "invalid_ticker" } - if {[lsearch -exact {tick_hourly daily weekly monthly annual five_year} $horizon] < 0} { + if {[lsearch -exact { + price_forecast volatility_surface var_calculation correlation_matrix + regime_state rough_vol_estimate jump_intensity + } $prediction_type] < 0} { error "unknown_prediction_type" } + if {[lsearch -exact {current tick_hourly daily weekly monthly annual five_year} $horizon] < 0} { + error "unknown_horizon" + } + if {$prediction_type eq "price_forecast" && $horizon eq "current"} { error "unknown_horizon" } if {![string is integer -strict $paths] || $paths < 100} { error "invalid_paths" } @@ -52,9 +73,27 @@ oo::class create ::stomach::StatisticalRunner { if {![string is double -strict $price] || $price <= 0} { error "invalid_price" } lappend encoded [format %.17g $price] } - set payload [format {"prices":[%s],"dt":%.17g,"token_ticker":"%s","horizon":"%s","paths":%d,"seed":%d} [join $encoded ,] $dt $ticker $horizon $paths $seed] + set encoded_pool {} + foreach price $pool_prices { + if {![string is double -strict $price] || $price <= 0} { error "invalid_pool_price" } + lappend encoded_pool [format %.17g $price] + } + set encoded_liquidity {} + foreach liquidity $pool_liquidity { + if {![string is double -strict $liquidity] || $liquidity < 0} { error "invalid_pool_liquidity" } + lappend encoded_liquidity [format %.17g $liquidity] + } + if {[llength $encoded_pool] != [llength $encoded_liquidity] && [llength $encoded_liquidity] > 0} { + error "pool_liquidity_length" + } + + set payload [format {"prices":[%s],"pool_prices":[%s],"pool_liquidity":[%s],"dt":%.17g,"token_ticker":"%s","prediction_type":"%s","horizon":"%s","paths":%d,"seed":%d} [join $encoded ,] [join $encoded_pool ,] [join $encoded_liquidity ,] $dt $ticker $prediction_type $horizon $paths $seed] set output [exec $runtime $engine << $payload] return [my parse_prediction $output] } + + method query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my query_typed $prices $ticker price_forecast $horizon $paths $seed $dt {} {}] + } } From 3c0dfeb15d8d0703309aab0da9d21d8d0a3e8491 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:13:45 -0700 Subject: [PATCH 085/156] M3a: wire typed and DEX-pool feed queries through stomach --- core/src/economy/stomach.tcl | 40 ++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index a325dc5..6ed425c 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -59,12 +59,22 @@ oo::class create ::stomach::Economy { method feed_history {feed_type} { return [$feeds history $feed_type] } method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } method statistical_runner_available {} { return [$statistical_runner available] } - method statistical_query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { - set p [$statistical_runner query $prices $ticker $horizon $paths $seed $dt] + method statistical_query_type { + prices ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + {pool_prices {}} {pool_liquidity {}} + } { + set p [$statistical_runner query_typed $prices $ticker $prediction_type $horizon $paths $seed $dt $pool_prices $pool_liquidity] $sims publish statistical $p return $p } - method statistical_from_feed {ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + method statistical_query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my statistical_query_type $prices $ticker price_forecast $horizon $paths $seed $dt {} {}] + } + method statistical_from_feed_type { + ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + } { set prices {} foreach datum [$feeds history price_tick] { if {![dict exists $datum payload]} { continue } @@ -76,7 +86,29 @@ oo::class create ::stomach::Economy { lappend prices $price } if {[llength $prices] < 80} { error "insufficient_price_history" } - return [my statistical_query $prices $ticker $horizon $paths $seed $dt] + + set pool_prices {} + set pool_liquidity {} + foreach datum [$feeds history dex_pool_state] { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token]} { continue } + if {$token ne $ticker} { continue } + if {[catch {dict get $payload price} price]} { continue } + if {![string is double -strict $price] || $price <= 0} { continue } + set liquidity 1.0 + if {![catch {dict get $payload liquidity} raw_liquidity] && + [string is double -strict $raw_liquidity] && $raw_liquidity >= 0} { + set liquidity $raw_liquidity + } + lappend pool_prices $price + lappend pool_liquidity $liquidity + } + + return [my statistical_query_type $prices $ticker $prediction_type $horizon $paths $seed $dt $pool_prices $pool_liquidity] + } + method statistical_from_feed {ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my statistical_from_feed_type $ticker price_forecast $horizon $paths $seed $dt] } method query_predictions {trader_id sim_type} { return [$market predictions $trader_id $sim_type] } method sim_engines {} { return [$registry names] } From c4d51044218302a13911607c6ef246c4aada23c1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:13:49 -0700 Subject: [PATCH 086/156] ci: enforce complete M3a integration contract --- .github/workflows/m3a-statistical.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml index 0974e4a..a3be06f 100644 --- a/.github/workflows/m3a-statistical.yml +++ b/.github/workflows/m3a-statistical.yml @@ -13,6 +13,9 @@ on: pull_request: paths: - "core/src/economy/sims/statistical/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" - ".github/workflows/m3a-statistical.yml" workflow_dispatch: @@ -39,4 +42,4 @@ jobs: run: | set -euo pipefail tclsh core/src/economy/sims/statistical/integration.test | tee /tmp/m3a-integration.out - grep -Eq 'Total[[:space:]]+3[[:space:]]+Passed[[:space:]]+3.*Failed[[:space:]]+0' /tmp/m3a-integration.out + grep -Eq 'Total[[:space:]]+5[[:space:]]+Passed[[:space:]]+5.*Failed[[:space:]]+0' /tmp/m3a-integration.out From 6f8778756dbd700d5e437ebd04470cf77b9730dc Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:16:25 -0700 Subject: [PATCH 087/156] docs: mark M3a V1 implemented --- core/docs/plans/M3a-statistical-sims.md | 53 ++++++++++++++----------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/core/docs/plans/M3a-statistical-sims.md b/core/docs/plans/M3a-statistical-sims.md index ea1234c..14ef920 100644 --- a/core/docs/plans/M3a-statistical-sims.md +++ b/core/docs/plans/M3a-statistical-sims.md @@ -8,19 +8,18 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math **stochastic sample paths**, not behavioral agents. ## 2. Status / certainty -SUBSTANTIAL ENGINE IMPLEMENTED · R. `core/src/economy/sims/statistical/engine.R` -now implements GBM, Merton jump-diffusion, full-truncation Heston simulation, GARCH(1,1) QMLE, -three-state Gaussian HMM training + Viterbi decoding, Davies–Harte fractional Gaussian noise, -rough-volatility paths with estimated Hurst exponent, fitted DCC dynamic correlation, t-copula -tail-dependence with degrees-of-freedom estimation, conjugate Bayesian return calibration, -base-R ARIMA forecasting, historical VaR/Expected Shortfall, jump-intensity estimation, fitted -Heston proxy parameters including rho, cross-asset calibration, and six concurrent bounded -forecast horizons. A Tcl runner provides tested `M2 price_tick → R M3a → M3 hub → Marketplace` -integration. Native R CI and the boundary integration suite are green. Remaining research-depth -work is Heston characteristic-function/option-surface calibration, richer rough-vol parameter -estimation, historical backtest calibration of the three quality scores, and live multi-source -M2 adapters beyond normalized price history. Core methods C4/C5; implementation C3; -live-market parameterization remains C1/C2. +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 +simulation, GARCH(1,1) QMLE, three-state Gaussian HMM training + Viterbi decoding, +Davies–Harte fractional Gaussian noise and fitted rough volatility, fitted DCC dynamic +correlation, t-copula tail dependence with degrees-of-freedom estimation, conjugate Bayesian +return calibration, base-R ARIMA forecasting, historical VaR/Expected Shortfall, jump-intensity +estimation, Heston characteristic-function option pricing + surface calibration, empirical +walk-forward confidence/correctness/certainty scoring, and six concurrent bounded forecast +horizons. All seven declared prediction types are implemented. A Tcl runner provides tested +`M2 price_tick + dex_pool_state → R M3a → M3 hub → Marketplace` integration. Native R CI and +the boundary integration suite are green. Core methods C4/C5; implementation C3; live-market +parameterization remains data-dependent rather than hardcoded. ## 3. Language & location **R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only: @@ -73,10 +72,13 @@ the Hub stdin/stdout protocol is hand-rolled. - Calibration: ingests `price_tick` and `dex_pool_state` from M2 Data Feeds. ## 6. Dependencies & stubs -- M2 Data Feeds — normalized `price_tick` history is now consumed by the Tcl→R - integration path; RSS and DEX-pool cross-source calibration remain open. -- M3 Sims hub — M3a predictions are now published into the live hub and subsequently queried by - Traders through Marketplace. +- M2 Data Feeds — normalized `price_tick` and `dex_pool_state` histories are consumed by + the Tcl→R calibration path. Pool observations contribute liquidity-weighted reference price, + dispersion, basis, and certainty calibration. +- M3 Sims hub — typed M3a predictions are published as bounded scalar predictions. Categorical + regime state is carried as a label plus a bounded posterior probability; correlation matrices + retain the matrix as detail while the bounded scalar value is the mean off-diagonal + correlation, preserving the hub's scalar-bound invariant. ## 7. Invariants / laws - **L1 (C5):** bounds are **statistical confidence intervals** — derived from the model's @@ -114,9 +116,14 @@ synthetic regime-switching data. Copula: tail dependence captured (BTC crash → correlation spike). Jump-diffusion: fat tails reproduced. Calibration: new data shifts parameter estimates. Multi-horizon: all six horizons produce concurrent outputs. -## 10. Open items -- Heston calibration method (characteristic function inversion? particle filter?). -- Rough vol computational cost (fBM generation is O(N²) naively; FFT methods needed). -- HMM state count (3 sufficient? 4+ for crypto with "mania" regime?). -- Which copula family for tail dependence ($t$-copula? Clayton? Joe?). -- Computational budget per horizon (GPU for Monte Carlo paths?). +## 10. V1 decisions and future extensions +- **Heston calibration:** resolved with characteristic-function inversion and numerical + option-surface calibration; realized-price proxy calibration remains available when no option + surface exists. +- **Rough-vol cost:** resolved with Davies–Harte circulant embedding / FFT rather than the + O(N²) naive generator. +- **HMM states:** three states (bear / neutral / bull) are canonical for V1. A fourth "mania" + state is an optional future experiment, not a V1 dependency. +- **Tail copula:** Student-t copula is canonical for V1, with fitted degrees of freedom. +- **Compute budget:** Monte Carlo path count is explicit per query and CPU-native in V1. + GPU acceleration is an optional optimization; it is not required for correctness. From ae70c674ece98589aa2a6a1b170565fd4336a060 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:16:28 -0700 Subject: [PATCH 088/156] docs: mark M3a complete in simulator inventory --- core/src/economy/sims/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md index 97b55f0..c1bac5d 100644 --- a/core/src/economy/sims/README.md +++ b/core/src/economy/sims/README.md @@ -4,7 +4,7 @@ Seven native simulator engines live here behind the Tcl M3 hub. | ID | Engine | Native language | Implemented kernel | |---|---|---|---| -| M3a | statistical | R | GBM, Merton, Heston, GARCH(1,1), Gaussian HMM/Viterbi, Davies–Harte rough vol, fitted DCC, t-copula tails, Bayesian calibration, ARIMA, VaR/ES, six-horizon forecasts | +| 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 | | M3b | sociological | ECLiPSe Prolog | replicator dynamics, Hegselmann-Krause, complex contagion, pump/dump phase | | M3c | AMM/liquidity | Solidity + Foundry | fee-adjusted x*y=k, impermanent loss, slippage, IL-derived withdrawal | | M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | From fd34e4d1032a635583e5d6c288c85f0ba570119b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:16:31 -0700 Subject: [PATCH 089/156] docs: mark M3a V1 complete in economy overview --- core/src/economy/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index ec675e4..635017c 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. -- **M3 Sims** — all seven native engine trees are built in. M3a is now a substantial R engine with calibrated HMM regimes, spectral rough volatility, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting and a tested M2→R→Hub path; M3b is ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. +- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b is ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. From 611b213b98d75d1e786d62807a8a2f3c12b98255 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 18:16:35 -0700 Subject: [PATCH 090/156] docs: add final M3a V1 runtime contract --- core/src/economy/sims/statistical/README.md | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 core/src/economy/sims/statistical/README.md diff --git a/core/src/economy/sims/statistical/README.md b/core/src/economy/sims/statistical/README.md new file mode 100644 index 0000000..8e56090 --- /dev/null +++ b/core/src/economy/sims/statistical/README.md @@ -0,0 +1,24 @@ +# M3a — statistical simulator + +M3a V1 is the R-native quantitative simulator behind the stomach's statistical prediction type. + +Implemented models: GBM; Merton jump diffusion; Heston full-truncation SDE; Heston characteristic-function call pricing and option-surface calibration; GARCH(1,1) QMLE; three-state Gaussian HMM with Viterbi decoding; Davies–Harte fractional Gaussian noise; fitted rough-vol H and eta; fitted DCC correlation; Student-t copula tail dependence; conjugate Bayesian return calibration; ARIMA; historical VaR / Expected Shortfall; jump-intensity estimation; empirical walk-forward quality scoring. + +The seven public prediction types are `price_forecast`, `volatility_surface`, `var_calculation`, `correlation_matrix`, `regime_state`, `rough_vol_estimate`, and `jump_intensity`. Every hub publication remains numerically bounded. Regime labels and matrix detail are metadata, not exceptions to the hub bound invariant. + +Calibration consumes normalized M2 `price_tick` history and optional `dex_pool_state` observations. Pool price is liquidity weighted and cross-venue disagreement reduces certainty rather than replacing literal price-tick ground truth. + +The live boundary is: + +`M2 → StatisticalRunner (Tcl) → engine.R → SimsHub → Marketplace` + +No function in M3a signs, broadcasts, routes, or submits transactions. + +Verification: + +```sh +Rscript core/src/economy/sims/statistical/tests.R +tclsh core/src/economy/sims/statistical/integration.test +``` + +GitHub Actions enforces both the native R suite and the Tcl summary (`5 passed / 0 failed`). From e9e45ab2d9bab35bd80cdee299afdf09146c70a1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:25:36 -0700 Subject: [PATCH 091/156] test: require concentrated liquidity and split routing --- core/src/economy/sims/amm/test/AMMSim.t.sol | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol index b2d43d6..e63d051 100644 --- a/core/src/economy/sims/amm/test/AMMSim.t.sol +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -24,4 +24,35 @@ contract AMMSimTest { require(AMMSim.lpShouldWithdraw(1e16,4e18), "withdraw"); require(!AMMSim.lpShouldWithdraw(3e17,4e18), "stay"); } + function testConcentratedLiquidityAmountsAtMidPrice() public pure { + (uint256 amount0,uint256 amount1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 2e18, 3e18 + ); + require(amount0 == 100e18, "amount0"); + require(amount1 == 600e18, "amount1"); + } + + function testConcentratedLiquidityBecomesOneSidedOutsideRange() public pure { + (uint256 below0,uint256 below1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 5e17, 3e18 + ); + require(below0 == 400e18 && below1 == 0, "below"); + (uint256 above0,uint256 above1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 4e18, 3e18 + ); + require(above0 == 0 && above1 == 1200e18, "above"); + } + + function testSplitRoutingUsesBothPoolsAndImprovesOutput() public pure { + uint256 dx=100e18; + uint256 singleA=AMMSim.amountOut(1000e18,1000e18,dx,30); + uint256 singleB=AMMSim.amountOut(500e18,500e18,dx,30); + (uint256 splitA,uint256 totalOut)=AMMSim.bestSplitTwoPools( + 1000e18,1000e18,500e18,500e18,dx,30,30 + ); + require(splitA > 0 && splitA < dx, "must split"); + require(splitA > dx/2, "deeper pool gets more"); + require(totalOut > singleA && totalOut > singleB, "split improves"); + } + } From 318e2afc8da1768400fa336b6b7cc3a3e80edfcd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:25:43 -0700 Subject: [PATCH 092/156] ci: add native Foundry gate for M3c --- .github/workflows/m3c-amm.yml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 .github/workflows/m3c-amm.yml diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml new file mode 100644 index 0000000..8cc02d5 --- /dev/null +++ b/.github/workflows/m3c-amm.yml @@ -0,0 +1,33 @@ +name: M3c AMM CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/amm/**" + - ".github/workflows/m3c-amm.yml" + pull_request: + paths: + - "core/src/economy/sims/amm/**" + - ".github/workflows/m3c-amm.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3c: + name: Solidity AMM engine + runs-on: ubuntu-latest + defaults: + run: + working-directory: core/src/economy/sims/amm + steps: + - uses: actions/checkout@v4 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Run M3c native tests + run: forge test -vv From 43d375d044b194f9d8d5787e0b74368847c9dc42 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:26:33 -0700 Subject: [PATCH 093/156] M3c: add concentrated liquidity and split routing --- core/src/economy/sims/amm/src/AMMSim.sol | 139 +++++++++++++++++++++++ 1 file changed, 139 insertions(+) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index a9781ea..b26c7eb 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -44,4 +44,143 @@ library AMMSim { uint256 loss = il < 0 ? uint256(-il) : 0; return loss > feeIncomeWad; } + + + /// @notice Token amounts represented by concentrated liquidity L at a + /// current sqrt-price. All sqrt-prices are WAD-scaled. + function concentratedAmounts( + uint256 liquidity, + uint256 sqrtLowerWad, + uint256 sqrtPriceWad, + uint256 sqrtUpperWad + ) internal pure returns (uint256 amount0, uint256 amount1) { + require( + liquidity > 0 && + sqrtLowerWad > 0 && + sqrtLowerWad < sqrtUpperWad, + "bad range" + ); + + if (sqrtPriceWad <= sqrtLowerWad) { + amount0 = + liquidity * + (sqrtUpperWad - sqrtLowerWad) / + sqrtLowerWad * + WAD / + sqrtUpperWad; + return (amount0, 0); + } + + if (sqrtPriceWad >= sqrtUpperWad) { + amount1 = + liquidity * + (sqrtUpperWad - sqrtLowerWad) / + WAD; + return (0, amount1); + } + + amount0 = + liquidity * + (sqrtUpperWad - sqrtPriceWad) / + sqrtPriceWad * + WAD / + sqrtUpperWad; + amount1 = + liquidity * + (sqrtPriceWad - sqrtLowerWad) / + WAD; + } + + function _amountOutOrZero( + uint256 x, + uint256 y, + uint256 dx, + uint256 feeBps + ) private pure returns (uint256) { + if (dx == 0) return 0; + return amountOut(x, y, dx, feeBps); + } + + function _marginalOutWad( + uint256 x, + uint256 y, + uint256 dx, + uint256 feeBps + ) private pure returns (uint256) { + require(x > 0 && y > 0 && feeBps < BPS, "bad pool"); + uint256 gamma = BPS - feeBps; + uint256 dxEff = dx * gamma / BPS; + uint256 denom = x + dxEff; + + // d(amountOut)/d(raw input), WAD-scaled. Keeping the divisions late + // preserves enough precision for the router without floating point. + return y * x * gamma * WAD / BPS / denom / denom; + } + + /// @notice Split one exact-input swap across two constant-product pools. + /// The optimum is where their marginal outputs equalize; binary search is + /// deterministic because each pool's marginal output is monotone. + function bestSplitTwoPools( + uint256 xA, + uint256 yA, + uint256 xB, + uint256 yB, + uint256 dx, + uint256 feeABps, + uint256 feeBBps + ) internal pure returns (uint256 splitA, uint256 totalOut) { + require( + xA > 0 && yA > 0 && xB > 0 && yB > 0 && + dx > 0 && feeABps < BPS && feeBBps < BPS, + "bad route" + ); + + uint256 lo = 0; + uint256 hi = dx; + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + uint256 marginalA = _marginalOutWad( + xA, yA, mid, feeABps + ); + uint256 marginalB = _marginalOutWad( + xB, yB, dx - mid, feeBBps + ); + if (marginalA > marginalB) { + lo = mid + 1; + } else { + hi = mid; + } + } + + uint256 candidate = lo; + uint256 outCandidate = + _amountOutOrZero(xA, yA, candidate, feeABps) + + _amountOutOrZero(xB, yB, dx - candidate, feeBBps); + + splitA = candidate; + totalOut = outCandidate; + + if (candidate > 0) { + uint256 alt = candidate - 1; + uint256 outAlt = + _amountOutOrZero(xA, yA, alt, feeABps) + + _amountOutOrZero(xB, yB, dx - alt, feeBBps); + if (outAlt > totalOut) { + splitA = alt; + totalOut = outAlt; + } + } + + uint256 onlyA = amountOut(xA, yA, dx, feeABps); + if (onlyA > totalOut) { + splitA = dx; + totalOut = onlyA; + } + + uint256 onlyB = amountOut(xB, yB, dx, feeBBps); + if (onlyB > totalOut) { + splitA = 0; + totalOut = onlyB; + } + } } From d8215be73d216265f61c340119a9c77be8591cb5 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:27:22 -0700 Subject: [PATCH 094/156] M3c: reduce split-router stack pressure --- core/src/economy/sims/amm/src/AMMSim.sol | 120 +++++++++++++---------- 1 file changed, 70 insertions(+), 50 deletions(-) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index b26c7eb..bda7cf1 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -5,6 +5,12 @@ library AMMSim { uint256 internal constant WAD = 1e18; uint256 internal constant BPS = 10_000; + struct Pool { + uint256 x; + uint256 y; + uint256 feeBps; + } + function amountOut(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256 dy) { require(x > 0 && y > 0 && dx > 0 && feeBps < BPS, "bad pool"); uint256 dxEff = dx * (BPS - feeBps) / BPS; @@ -120,6 +126,64 @@ library AMMSim { /// @notice Split one exact-input swap across two constant-product pools. /// The optimum is where their marginal outputs equalize; binary search is /// deterministic because each pool's marginal output is monotone. + function _routeOutput( + Pool memory a, + Pool memory b, + uint256 dx, + uint256 splitA + ) private pure returns (uint256) { + return + _amountOutOrZero(a.x, a.y, splitA, a.feeBps) + + _amountOutOrZero(b.x, b.y, dx - splitA, b.feeBps); + } + + function _bestSplit( + Pool memory a, + Pool memory b, + uint256 dx + ) private pure returns (uint256 splitA, uint256 totalOut) { + uint256 lo = 0; + uint256 hi = dx; + + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + if ( + _marginalOutWad(a.x, a.y, mid, a.feeBps) > + _marginalOutWad(b.x, b.y, dx - mid, b.feeBps) + ) { + lo = mid + 1; + } else { + hi = mid; + } + } + + splitA = lo; + totalOut = _routeOutput(a, b, dx, splitA); + + if (splitA > 0) { + uint256 alt = splitA - 1; + uint256 altOut = _routeOutput(a, b, dx, alt); + if (altOut > totalOut) { + splitA = alt; + totalOut = altOut; + } + } + + uint256 onlyA = _routeOutput(a, b, dx, dx); + if (onlyA > totalOut) { + splitA = dx; + totalOut = onlyA; + } + + uint256 onlyB = _routeOutput(a, b, dx, 0); + if (onlyB > totalOut) { + splitA = 0; + totalOut = onlyB; + } + } + + /// @notice Split one exact-input swap across two constant-product pools. + /// The optimum is where their marginal outputs equalize. function bestSplitTwoPools( uint256 xA, uint256 yA, @@ -134,53 +198,9 @@ library AMMSim { dx > 0 && feeABps < BPS && feeBBps < BPS, "bad route" ); - - uint256 lo = 0; - uint256 hi = dx; - for (uint256 i = 0; i < 64 && lo < hi; ++i) { - uint256 mid = lo + (hi - lo) / 2; - uint256 marginalA = _marginalOutWad( - xA, yA, mid, feeABps - ); - uint256 marginalB = _marginalOutWad( - xB, yB, dx - mid, feeBBps - ); - if (marginalA > marginalB) { - lo = mid + 1; - } else { - hi = mid; - } - } - - uint256 candidate = lo; - uint256 outCandidate = - _amountOutOrZero(xA, yA, candidate, feeABps) + - _amountOutOrZero(xB, yB, dx - candidate, feeBBps); - - splitA = candidate; - totalOut = outCandidate; - - if (candidate > 0) { - uint256 alt = candidate - 1; - uint256 outAlt = - _amountOutOrZero(xA, yA, alt, feeABps) + - _amountOutOrZero(xB, yB, dx - alt, feeBBps); - if (outAlt > totalOut) { - splitA = alt; - totalOut = outAlt; - } - } - - uint256 onlyA = amountOut(xA, yA, dx, feeABps); - if (onlyA > totalOut) { - splitA = dx; - totalOut = onlyA; - } - - uint256 onlyB = amountOut(xB, yB, dx, feeBBps); - if (onlyB > totalOut) { - splitA = 0; - totalOut = onlyB; - } - } -} + return _bestSplit( + Pool({x: xA, y: yA, feeBps: feeABps}), + Pool({x: xB, y: yB, feeBps: feeBBps}), + dx + ); + }} From b0959f2eb731f3bfb25051e93b5d35a4a8801f58 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:28:32 -0700 Subject: [PATCH 095/156] test: require LP and arbitrage population mechanics --- core/src/economy/sims/amm/test/AMMSim.t.sol | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol index e63d051..ba5ce71 100644 --- a/core/src/economy/sims/amm/test/AMMSim.t.sol +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -55,4 +55,58 @@ contract AMMSimTest { require(totalOut > singleA && totalOut > singleB, "split improves"); } + function testActiveLpRebalanceComparesIlFeesAndCost() public pure { + require( + AMMSim.lpShouldRebalance(1e16, 5e15, 4e18), + "rebalance when IL dominates" + ); + require( + !AMMSim.lpShouldRebalance(25e16, 5e15, 4e18), + "stay when fees dominate" + ); + } + + function testJitLiquidityRequiresPositiveNetFeeShare() public pure { + uint256 income=AMMSim.jitFeeIncomeWad( + 1000e18, 30, 100e18, 1000e18 + ); + require(income == 3e17, "fee share"); + require( + AMMSim.jitShouldProvide( + 1000e18, 30, 100e18, 1000e18, 2e17 + ), + "profitable JIT" + ); + require( + !AMMSim.jitShouldProvide( + 1000e18, 30, 100e18, 1000e18, 4e17 + ), + "costly JIT" + ); + } + + function testBackrunMovesPoolTowardExternalPrice() public pure { + AMMSim.ArbitrageResult memory a=AMMSim.backrunToPrice( + 1000e18, 2000e18, 15e17, 30 + ); + require(a.amountIn > 0 && a.amountOut > 0, "arb size"); + require(a.zeroForOne, "x in"); + require(a.profitQuote > 0, "profitable"); + uint256 pre=2e18; + uint256 preError=pre > 15e17 ? pre-15e17 : 15e17-pre; + uint256 postError=a.postPriceWad > 15e17 + ? a.postPriceWad-15e17 + : 15e17-a.postPriceWad; + require(postError < preError, "price converges"); + } + + function testSandwichSimulationAccountsForBothLegs() public pure { + AMMSim.SandwichResult memory s=AMMSim.simulateSandwich( + 1000e18, 1000e18, 100e18, 10e18, 30 + ); + require(s.frontOut > 0 && s.victimOut > 0 && s.backOut > 0, "legs"); + require(s.profitToken0 > 0, "positive sandwich"); + require(s.victimOut < AMMSim.amountOut(1000e18,1000e18,100e18,30), "victim worsens"); + } + } From 24f2a210b1c198034bd7a63bd875604b363ee14a Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:29:21 -0700 Subject: [PATCH 096/156] M3c: add LP strategies and arbitrage mechanics --- core/src/economy/sims/amm/src/AMMSim.sol | 181 +++++++++++++++++++++++ 1 file changed, 181 insertions(+) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index bda7cf1..1412e3a 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -11,6 +11,21 @@ library AMMSim { uint256 feeBps; } + struct ArbitrageResult { + bool zeroForOne; + uint256 amountIn; + uint256 amountOut; + int256 profitQuote; + uint256 postPriceWad; + } + + struct SandwichResult { + uint256 frontOut; + uint256 victimOut; + uint256 backOut; + int256 profitToken0; + } + function amountOut(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256 dy) { require(x > 0 && y > 0 && dx > 0 && feeBps < BPS, "bad pool"); uint256 dxEff = dx * (BPS - feeBps) / BPS; @@ -52,6 +67,172 @@ library AMMSim { } + function lpShouldRebalance( + uint256 feeIncomeWad, + uint256 rebalanceCostWad, + uint256 ratioWad + ) internal pure returns (bool) { + int256 il = impermanentLossWad(ratioWad); + uint256 loss = il < 0 ? uint256(-il) : 0; + return loss > feeIncomeWad + rebalanceCostWad; + } + + function jitFeeIncomeWad( + uint256 volumeWad, + uint256 feeBps, + uint256 ownLiquidity, + uint256 totalLiquidity + ) internal pure returns (uint256) { + require(feeBps < BPS, "fee"); + require(totalLiquidity > 0 && ownLiquidity <= totalLiquidity, "liquidity"); + uint256 grossFees = volumeWad * feeBps / BPS; + return grossFees * ownLiquidity / totalLiquidity; + } + + function jitShouldProvide( + uint256 volumeWad, + uint256 feeBps, + uint256 ownLiquidity, + uint256 totalLiquidity, + uint256 entryExitCostWad + ) internal pure returns (bool) { + return jitFeeIncomeWad( + volumeWad, feeBps, ownLiquidity, totalLiquidity + ) > entryExitCostWad; + } + + + + function _optimalInputForMarginal( + Pool memory pool, + uint256 targetMarginalWad + ) private pure returns (uint256) { + if (_marginalOutWad( + pool.x, pool.y, 0, pool.feeBps + ) <= targetMarginalWad) { + return 0; + } + + uint256 lo = 0; + uint256 hi = pool.x; + for (uint256 i = 0; i < 8; ++i) { + if (_marginalOutWad( + pool.x, pool.y, hi, pool.feeBps + ) <= targetMarginalWad) break; + require(hi <= type(uint256).max / 2, "arb range"); + hi *= 2; + } + + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + if (_marginalOutWad( + pool.x, pool.y, mid, pool.feeBps + ) > targetMarginalWad) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } + + function _signedDifference( + uint256 positive, + uint256 negative + ) private pure returns (int256) { + require( + positive <= uint256(type(int256).max) && + negative <= uint256(type(int256).max), + "signed overflow" + ); + return int256(positive) - int256(negative); + } + + function backrunToPrice( + uint256 x, + uint256 y, + uint256 externalPriceWad, + uint256 feeBps + ) internal pure returns (ArbitrageResult memory r) { + require( + x > 0 && y > 0 && externalPriceWad > 0 && feeBps < BPS, + "bad arb" + ); + uint256 poolPriceWad = y * WAD / x; + if (poolPriceWad == externalPriceWad) { + r.postPriceWad = poolPriceWad; + return r; + } + + if (poolPriceWad > externalPriceWad) { + r.zeroForOne = true; + Pool memory pool = Pool({x: x, y: y, feeBps: feeBps}); + r.amountIn = _optimalInputForMarginal( + pool, externalPriceWad + ); + if (r.amountIn == 0) { + r.postPriceWad = poolPriceWad; + return r; + } + r.amountOut = amountOut(x, y, r.amountIn, feeBps); + uint256 newX = x + r.amountIn; + uint256 newY = y - r.amountOut; + r.postPriceWad = newY * WAD / newX; + uint256 externalCost = r.amountIn * externalPriceWad / WAD; + r.profitQuote = _signedDifference( + r.amountOut, externalCost + ); + return r; + } + + uint256 reciprocalPriceWad = WAD * WAD / externalPriceWad; + Pool memory reversePool = Pool({x: y, y: x, feeBps: feeBps}); + r.amountIn = _optimalInputForMarginal( + reversePool, reciprocalPriceWad + ); + if (r.amountIn == 0) { + r.postPriceWad = poolPriceWad; + return r; + } + r.amountOut = amountOut(y, x, r.amountIn, feeBps); + uint256 newY2 = y + r.amountIn; + uint256 newX2 = x - r.amountOut; + r.postPriceWad = newY2 * WAD / newX2; + uint256 externalValue = r.amountOut * externalPriceWad / WAD; + r.profitQuote = _signedDifference( + externalValue, r.amountIn + ); + } + + function simulateSandwich( + uint256 x, + uint256 y, + uint256 victimDx, + uint256 attackerDx, + uint256 feeBps + ) internal pure returns (SandwichResult memory r) { + require( + x > 0 && y > 0 && victimDx > 0 && + attackerDx > 0 && feeBps < BPS, + "bad sandwich" + ); + + r.frontOut = amountOut(x, y, attackerDx, feeBps); + uint256 x1 = x + attackerDx; + uint256 y1 = y - r.frontOut; + + r.victimOut = amountOut(x1, y1, victimDx, feeBps); + uint256 x2 = x1 + victimDx; + uint256 y2 = y1 - r.victimOut; + + r.backOut = amountOut( + y2, x2, r.frontOut, feeBps + ); + r.profitToken0 = _signedDifference( + r.backOut, attackerDx + ); + } + /// @notice Token amounts represented by concentrated liquidity L at a /// current sqrt-price. All sqrt-prices are WAD-scaled. function concentratedAmounts( From aac8cd6d79cf037c7db6efe95c0d15ffd8b2e42c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:30:46 -0700 Subject: [PATCH 097/156] test: require complete bounded M3c prediction contract --- core/src/economy/sims/amm/test/AMMSim.t.sol | 63 +++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol index ba5ce71..8403180 100644 --- a/core/src/economy/sims/amm/test/AMMSim.t.sol +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -109,4 +109,67 @@ contract AMMSimTest { require(s.victimOut < AMMSim.amountOut(1000e18,1000e18,100e18,30), "victim worsens"); } + function _basePoolState() private pure returns (AMMSim.PoolState memory s) { + s.x=1000e18; + s.y=1000e18; + s.feeBps=100; + s.volumeWad=5000e18; + s.tvlWad=1000e18; + s.priceRatioWad=4e18; + s.externalPriceWad=1e18; + s.volatilityWad=5e17; + s.tradeSizeWad=10e18; + s.uncertaintyBps=500; + s.horizonSeconds=7 days; + } + + function testWithdrawalThresholdIsDerivedFromIlFormula() public pure { + uint256 threshold=AMMSim.withdrawalUpperRatioWad(2e17); + uint256 d=threshold > 4e18 ? threshold-4e18 : 4e18-threshold; + require(d < 1e11, "20pct IL threshold"); + int256 il=AMMSim.impermanentLossWad(threshold); + int256 target=-2e17; + int256 e=il-target; if (e<0) e=-e; + require(e < 1e10, "threshold reproduces IL"); + } + + function testPoolReturnCombinesFeesAndImpermanentLoss() public pure { + AMMSim.PoolState memory s=_basePoolState(); + AMMSim.BoundedPrediction memory p=AMMSim.predict( + AMMSim.PredictionType.PoolReturn, s + ); + int256 expected=-15e16; + int256 d=p.value-expected; if (d<0) d=-d; + require(d < 1e12, "fees minus IL"); + require(p.lower <= p.value && p.value <= p.upper, "bounded"); + } + + function testOptimalRangeWidensWithVolatility() public pure { + AMMSim.PoolState memory low=_basePoolState(); + low.priceRatioWad=1e18; + low.volatilityWad=2e17; + AMMSim.PoolState memory high=low; + high.volatilityWad=8e17; + AMMSim.BoundedPrediction memory a=AMMSim.predict( + AMMSim.PredictionType.OptimalRange, low + ); + AMMSim.BoundedPrediction memory b=AMMSim.predict( + AMMSim.PredictionType.OptimalRange, high + ); + require(b.upper-b.lower > a.upper-a.lower, "wider at high vol"); + require(a.lower <= a.value && a.value <= a.upper, "a bounded"); + require(b.lower <= b.value && b.value <= b.upper, "b bounded"); + } + + function testAllM3cPredictionKindsAreBounded() public pure { + AMMSim.PoolState memory s=_basePoolState(); + for (uint256 i=0; i<5; ++i) { + AMMSim.BoundedPrediction memory p=AMMSim.predict( + AMMSim.PredictionType(i), s + ); + require(p.lower <= p.value, "lower"); + require(p.value <= p.upper, "upper"); + } + } + } From 3aa89ca27cab13e8193b69782250dfdac4e1f30e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:31:46 -0700 Subject: [PATCH 098/156] M3c: implement bounded prediction contract --- core/src/economy/sims/amm/src/AMMSim.sol | 229 +++++++++++++++++++++++ 1 file changed, 229 insertions(+) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index 1412e3a..806c1b4 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -26,6 +26,34 @@ library AMMSim { int256 profitToken0; } + enum PredictionType { + ImpermanentLoss, + PoolReturn, + OptimalRange, + SlippageEstimate, + LpWithdrawalThreshold + } + + struct PoolState { + uint256 x; + uint256 y; + uint256 feeBps; + uint256 volumeWad; + uint256 tvlWad; + uint256 priceRatioWad; + uint256 externalPriceWad; + uint256 volatilityWad; + uint256 tradeSizeWad; + uint256 uncertaintyBps; + uint256 horizonSeconds; + } + + struct BoundedPrediction { + int256 value; + int256 lower; + int256 upper; + } + function amountOut(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256 dy) { require(x > 0 && y > 0 && dx > 0 && feeBps < BPS, "bad pool"); uint256 dxEff = dx * (BPS - feeBps) / BPS; @@ -102,6 +130,207 @@ library AMMSim { } + function feeYieldWad( + uint256 volumeWad, + uint256 feeBps, + uint256 tvlWad + ) internal pure returns (uint256) { + require(tvlWad > 0 && feeBps < BPS, "yield"); + uint256 fees = volumeWad * feeBps / BPS; + return fees * WAD / tvlWad; + } + + function withdrawalUpperRatioWad( + uint256 feeIncomeWad + ) internal pure returns (uint256) { + require(feeIncomeWad < WAD, "fee income"); + if (feeIncomeWad == 0) return WAD; + + uint256 retained = WAD - feeIncomeWad; + uint256 discriminant = + WAD * WAD - retained * retained; + uint256 root = sqrt(discriminant); + uint256 sqrtRatioWad = + (WAD + root) * WAD / retained; + return sqrtRatioWad * sqrtRatioWad / WAD; + } + + function _int(uint256 x) private pure returns (int256) { + require(x <= uint256(type(int256).max), "int overflow"); + return int256(x); + } + + function _min3( + int256 a, int256 b, int256 c0 + ) private pure returns (int256) { + int256 m = a < b ? a : b; + return m < c0 ? m : c0; + } + + function _max3( + int256 a, int256 b, int256 c0 + ) private pure returns (int256) { + int256 m = a > b ? a : b; + return m > c0 ? m : c0; + } + + function _scaledByUncertainty( + uint256 value, + uint256 uncertaintyBps, + bool upper + ) private pure returns (uint256) { + require(uncertaintyBps < BPS, "uncertainty"); + uint256 factor = upper + ? BPS + uncertaintyBps + : BPS - uncertaintyBps; + return value * factor / BPS; + } + + function _ilPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 loRatio = _scaledByUncertainty( + s.priceRatioWad, s.uncertaintyBps, false + ); + uint256 hiRatio = _scaledByUncertainty( + s.priceRatioWad, s.uncertaintyBps, true + ); + int256 a = impermanentLossWad(loRatio); + int256 b = impermanentLossWad(s.priceRatioWad); + int256 c0 = impermanentLossWad(hiRatio); + p.value = b; + p.lower = _min3(a, b, c0); + p.upper = _max3(a, b, c0); + if (loRatio <= WAD && hiRatio >= WAD) { + p.upper = 0; + } + } + + function _poolReturnPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + BoundedPrediction memory il = _ilPrediction(s); + uint256 lowVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, false + ); + uint256 highVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, true + ); + int256 fee = _int( + feeYieldWad(s.volumeWad, s.feeBps, s.tvlWad) + ); + int256 lowFee = _int( + feeYieldWad(lowVolume, s.feeBps, s.tvlWad) + ); + int256 highFee = _int( + feeYieldWad(highVolume, s.feeBps, s.tvlWad) + ); + p.value = fee + il.value; + p.lower = lowFee + il.lower; + p.upper = highFee + il.upper; + } + + function _optimalRangePrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + require( + s.externalPriceWad > 0 && s.horizonSeconds > 0, + "range" + ); + uint256 yearSeconds = 365 days; + uint256 fractionWad = + s.horizonSeconds * WAD / yearSeconds; + uint256 sqrtTimeWad = sqrt(fractionWad * WAD); + uint256 widthWad = + 2 * s.volatilityWad * sqrtTimeWad / WAD; + if (widthWad > 9e17) widthWad = 9e17; + + p.value = _int(s.externalPriceWad); + p.lower = _int( + s.externalPriceWad * (WAD - widthWad) / WAD + ); + p.upper = _int( + s.externalPriceWad * (WAD + widthWad) / WAD + ); + } + + function _slippagePrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 lowTrade = _scaledByUncertainty( + s.tradeSizeWad, s.uncertaintyBps, false + ); + uint256 highTrade = _scaledByUncertainty( + s.tradeSizeWad, s.uncertaintyBps, true + ); + p.value = _int( + slippageWad(s.x, s.y, s.tradeSizeWad, s.feeBps) + ); + p.lower = _int( + slippageWad(s.x, s.y, lowTrade, s.feeBps) + ); + p.upper = _int( + slippageWad(s.x, s.y, highTrade, s.feeBps) + ); + } + + function _thresholdPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 lowVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, false + ); + uint256 highVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, true + ); + uint256 fee = feeYieldWad( + s.volumeWad, s.feeBps, s.tvlWad + ); + uint256 lowFee = feeYieldWad( + lowVolume, s.feeBps, s.tvlWad + ); + uint256 highFee = feeYieldWad( + highVolume, s.feeBps, s.tvlWad + ); + if (fee >= WAD) fee = WAD - 1; + if (lowFee >= WAD) lowFee = WAD - 1; + if (highFee >= WAD) highFee = WAD - 1; + + p.value = _int(withdrawalUpperRatioWad(fee)); + p.lower = _int(withdrawalUpperRatioWad(lowFee)); + p.upper = _int(withdrawalUpperRatioWad(highFee)); + } + + function predict( + PredictionType predictionType, + PoolState memory s + ) internal pure returns (BoundedPrediction memory) { + require( + s.x > 0 && s.y > 0 && + s.tvlWad > 0 && + s.priceRatioWad > 0 && + s.tradeSizeWad > 0 && + s.feeBps < BPS && + s.uncertaintyBps < BPS, + "bad state" + ); + + if (predictionType == PredictionType.ImpermanentLoss) { + return _ilPrediction(s); + } + if (predictionType == PredictionType.PoolReturn) { + return _poolReturnPrediction(s); + } + if (predictionType == PredictionType.OptimalRange) { + return _optimalRangePrediction(s); + } + if (predictionType == PredictionType.SlippageEstimate) { + return _slippagePrediction(s); + } + return _thresholdPrediction(s); + } + + function _optimalInputForMarginal( Pool memory pool, From 94964cb966f15e24f819aab37e4fb05e4408a282 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:32:20 -0700 Subject: [PATCH 099/156] test: isolate M3c volatility range fixtures --- core/src/economy/sims/amm/test/AMMSim.t.sol | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol index 8403180..b9b9cde 100644 --- a/core/src/economy/sims/amm/test/AMMSim.t.sol +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -148,7 +148,8 @@ contract AMMSimTest { AMMSim.PoolState memory low=_basePoolState(); low.priceRatioWad=1e18; low.volatilityWad=2e17; - AMMSim.PoolState memory high=low; + AMMSim.PoolState memory high=_basePoolState(); + high.priceRatioWad=1e18; high.volatilityWad=8e17; AMMSim.BoundedPrediction memory a=AMMSim.predict( AMMSim.PredictionType.OptimalRange, low From a54205a39c9a94fa8e91d0fbfec309cd77ac4ae2 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:34:26 -0700 Subject: [PATCH 100/156] test: specify M2 to M3c hub integration --- core/src/economy/sims/amm/integration.test | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core/src/economy/sims/amm/integration.test diff --git a/core/src/economy/sims/amm/integration.test b/core/src/economy/sims/amm/integration.test new file mode 100644 index 0000000..6b11e30 --- /dev/null +++ b/core/src/economy/sims/amm/integration.test @@ -0,0 +1,54 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +proc seed_m3c {s ticker} { + for {set i 0} {$i < 24} {incr i} { + set price [expr {100.0 * exp(0.0008*$i + 0.01*sin($i/4.0))}] + $s feed_publish price_tick synthetic [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.2 + set r0 [expr {1000.0 + 2.0*$i}] + set r1 [expr {$r0 * $price / 100.0}] + $s feed_publish dex_pool_state dex [expr {$i*3600}] [dict create token_ticker $ticker reserve0 $r0 reserve1 $r1 fee_bps 30 volume 5000.0 tvl 2000.0 trade_size 10.0] 8.8 + } +} + +test m3c-runner-available-1.0 {Foundry-backed AMM runner is available in M3c CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s amm_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3c-to-hub-1.0 {pool and price feeds produce bounded pool return in M3 hub} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-amm amm_liquidity + seed_m3c $s TEST + set p [$s amm_from_feed TEST pool_return weekly] + set q [$s query_predictions trader-amm amm_liquidity] + set out [list [dict get $p sim_type] [dict get $p prediction_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $p time_horizon]] + $s destroy + set out +} -result {amm_liquidity pool_return 1 1 TEST 7d} + +test m3c-optimal-range-1.0 {volatility range is exposed as a bounded M3c prediction} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3c $s RANGE + set p [$s amm_from_feed RANGE optimal_range monthly] + set out [list [dict get $p prediction_type] [expr {[dict get $p lower_bound] < [dict get $p value]}] [expr {[dict get $p value] < [dict get $p upper_bound]}] [dict get $p calibration_sources]] + $s destroy + set out +} -result {optimal_range 1 1 price_tick,dex_pool_state} + +test m3c-insufficient-pool-history-1.0 {M3c refuses a query without pool state} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 24} {incr i} { + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s amm_from_feed TEST pool_return weekly} msg] + $s destroy + list $code $msg +} -result {1 insufficient_pool_history} + +cleanupTests From f2d9de4dc286f3c707093ddfa4d1bc39be892444 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:34:35 -0700 Subject: [PATCH 101/156] ci: exercise M2 to M3c hub integration --- .github/workflows/m3c-amm.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml index 8cc02d5..77571c6 100644 --- a/.github/workflows/m3c-amm.yml +++ b/.github/workflows/m3c-amm.yml @@ -31,3 +31,10 @@ jobs: - name: Run M3c native tests run: forge test -vv + + - name: Run M2 → M3c → Hub integration + shell: bash + run: | + set -euo pipefail + tclsh integration.test | tee /tmp/m3c-integration.out + grep -Eq 'Total[[:space:]]+4[[:space:]]+Passed[[:space:]]+4.*Failed[[:space:]]+0' /tmp/m3c-integration.out From 7f3e6abab424db18d64cdde79ba44a7ef5d56338 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:35:43 -0700 Subject: [PATCH 102/156] M3c: add read-only EVM query bridge --- core/src/economy/sims/amm/src/AMMQuery.sol | 51 ++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core/src/economy/sims/amm/src/AMMQuery.sol diff --git a/core/src/economy/sims/amm/src/AMMQuery.sol b/core/src/economy/sims/amm/src/AMMQuery.sol new file mode 100644 index 0000000..15499d8 --- /dev/null +++ b/core/src/economy/sims/amm/src/AMMQuery.sol @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; + +import "./AMMSim.sol"; + +/// @notice Read-only ABI bridge for M3c. This contract contains no storage, +/// transfer, approval, swap execution, or privileged method. It exists so the +/// Tcl coordinator can evaluate the Solidity-native simulator with eth_call. +contract AMMQuery { + function _query( + uint8 predictionType, + uint256[11] calldata raw + ) private pure returns (AMMSim.BoundedPrediction memory p) { + require(predictionType < 5, "prediction type"); + AMMSim.PoolState memory s = AMMSim.PoolState({ + x: raw[0], + y: raw[1], + feeBps: raw[2], + volumeWad: raw[3], + tvlWad: raw[4], + priceRatioWad: raw[5], + externalPriceWad: raw[6], + volatilityWad: raw[7], + tradeSizeWad: raw[8], + uncertaintyBps: raw[9], + horizonSeconds: raw[10] + }); + return AMMSim.predict(AMMSim.PredictionType(predictionType), s); + } + + function queryValue( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).value; + } + + function queryLower( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).lower; + } + + function queryUpper( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).upper; + } +} From fac04d8ad765a8cfd5fa447db22a78361fba19b1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:37:03 -0700 Subject: [PATCH 103/156] M3c: add Foundry-backed Tcl runner --- core/src/economy/sims/amm/runner.tcl | 239 +++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 core/src/economy/sims/amm/runner.tcl diff --git a/core/src/economy/sims/amm/runner.tcl b/core/src/economy/sims/amm/runner.tcl new file mode 100644 index 0000000..5dd092b --- /dev/null +++ b/core/src/economy/sims/amm/runner.tcl @@ -0,0 +1,239 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::AMMRunner { + variable runtime rpc address + + constructor {} { + set runtime cast + set rpc [expr {[info exists ::env(AMM_RPC_URL)] ? $::env(AMM_RPC_URL) : ""}] + set address [expr {[info exists ::env(AMM_QUERY_ADDRESS)] ? $::env(AMM_QUERY_ADDRESS) : ""}] + } + + method available {} { + expr { + [auto_execok $runtime] ne "" && + $rpc ne "" && + [regexp {^0x[0-9A-Fa-f]{40}$} $address] + } + } + + method _prediction_index {prediction_type} { + set names { + impermanent_loss + pool_return + optimal_range + slippage_estimate + lp_withdrawal_threshold + } + set i [lsearch -exact $names $prediction_type] + if {$i < 0} { error "unknown_prediction_type" } + return $i + } + + method _horizon {horizon} { + switch -- $horizon { + tick_hourly { return [list 3600 1h] } + daily { return [list 86400 24h] } + weekly { return [list 604800 7d] } + monthly { return [list 2592000 30d] } + annual { return [list 31536000 1y] } + five_year { return [list 157680000 5y] } + default { error "unknown_horizon" } + } + } + + method _decimal_wad {value} { + set s [string trim $value] + if {[regexp {^([+-]?)([0-9]+)(?:\.([0-9]*))?$} $s -> sign whole frac]} { + if {$frac eq ""} { set frac "" } + set frac [string range "${frac}000000000000000000" 0 17] + set n [expr {$whole * 1000000000000000000 + $frac}] + if {$sign eq "-"} { set n [expr {-$n}] } + return $n + } + if {![string is double -strict $s]} { error "invalid_decimal" } + return [format %.0f [expr {double($s) * 1.0e18}]] + } + + method _wad_double {value} { + expr {double($value) / 1.0e18} + } + + method _scalar {function_name prediction_index raw} { + if {![my available]} { error "amm_runtime_unavailable" } + if {[llength $raw] != 11} { error "invalid_amm_state" } + set arr "\[[join $raw ,]\]" + set sig "${function_name}(uint8,uint256\[11\])(int256)" + set output [exec $runtime call --rpc-url $rpc $address $sig $prediction_index $arr] + set output [string trim $output] + if {![regexp {^-?[0-9]+} $output value]} { + error "invalid_amm_output" + } + return $value + } + + method _raw_prediction {prediction_type raw} { + set kind [my _prediction_index $prediction_type] + set value [my _scalar queryValue $kind $raw] + set lower [my _scalar queryLower $kind $raw] + set upper [my _scalar queryUpper $kind $raw] + if {$lower > $value || $value > $upper} { error "amm_prediction_out_of_bounds" } + return [dict create value_wad $value lower_wad $lower upper_wad $upper] + } + + method _filter_prices {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $payload price} price] || ![string is double -strict $price] || $price <= 0} { continue } + lappend out [dict create price $price timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _filter_pools {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $payload reserve0} r0] || + [catch {dict get $payload reserve1} r1] || + ![string is double -strict $r0] || + ![string is double -strict $r1] || + $r0 <= 0 || $r1 <= 0} { continue } + lappend out $datum + } + return $out + } + + method _volatility {prices} { + if {[llength $prices] < 3} { return 0.2 } + set returns {} + set spacings {} + for {set i 1} {$i < [llength $prices]} {incr i} { + set a [lindex $prices [expr {$i-1}]] + set b [lindex $prices $i] + set pa [dict get $a price] + set pb [dict get $b price] + if {$pa > 0 && $pb > 0} { + lappend returns [expr {log(double($pb)/double($pa))}] + } + set ta [dict get $a timestamp] + set tb [dict get $b timestamp] + if {[string is double -strict $ta] && [string is double -strict $tb] && $tb > $ta} { + lappend spacings [expr {double($tb)-double($ta)}] + } + } + if {[llength $returns] < 2} { return 0.2 } + set sum 0.0 + foreach x $returns { set sum [expr {$sum+$x}] } + set mean [expr {$sum/double([llength $returns])}] + set ss 0.0 + foreach x $returns { set ss [expr {$ss+($x-$mean)*($x-$mean)}] } + set sd [expr {sqrt($ss/double([llength $returns]-1))}] + set dt 86400.0 + if {[llength $spacings]} { + set total 0.0 + foreach x $spacings { set total [expr {$total+$x}] } + set dt [expr {$total/double([llength $spacings])}] + } + if {$dt <= 0} { set dt 86400.0 } + set annualized [expr {$sd*sqrt(31536000.0/$dt)}] + if {$annualized < 0.0001} { set annualized 0.0001 } + if {$annualized > 5.0} { set annualized 5.0 } + return $annualized + } + + method _uncertainty_bps {price_conf pool_conf} { + set c [expr {(double($price_conf)+double($pool_conf))/2.0}] + if {$c < 0} { set c 0 } + if {$c > 10} { set c 10 } + set bps [expr {round(100.0 + (10.0-$c)*200.0)}] + if {$bps < 50} { set bps 50 } + if {$bps > 2500} { set bps 2500 } + return $bps + } + + method _state_from_pool {pool price_ratio external_price volatility uncertainty_bps horizon_seconds} { + set payload [dict get $pool payload] + set x [my _decimal_wad [dict get $payload reserve0]] + set y [my _decimal_wad [dict get $payload reserve1]] + set fee 30 + if {[dict exists $payload fee_bps]} { set fee [dict get $payload fee_bps] } + if {![string is integer -strict $fee] || $fee < 0 || $fee >= 10000} { error "invalid_pool_fee" } + + set volume 0.0 + if {[dict exists $payload volume]} { set volume [dict get $payload volume] } + set tvl [expr {double([dict get $payload reserve0]) + double([dict get $payload reserve1])}] + if {[dict exists $payload tvl]} { set tvl [dict get $payload tvl] } + if {![string is double -strict $tvl] || $tvl <= 0} { error "invalid_pool_tvl" } + + set trade [expr {double([dict get $payload reserve0]) * 0.01}] + if {[dict exists $payload trade_size]} { set trade [dict get $payload trade_size] } + if {![string is double -strict $trade] || $trade <= 0} { error "invalid_trade_size" } + + return [list $x $y $fee [my _decimal_wad $volume] [my _decimal_wad $tvl] [my _decimal_wad $price_ratio] [my _decimal_wad $external_price] [my _decimal_wad $volatility] [my _decimal_wad $trade] $uncertainty_bps $horizon_seconds] + } + + method _correctness {pools price_ratio external_price volatility uncertainty_bps horizon_seconds} { + set n [llength $pools] + if {$n < 2} { return 5.0 } + set start [expr {max(0,$n-4)}] + set hits 0 + set total 0 + for {set i $start} {$i < $n-1} {incr i} { + set prev [my _state_from_pool [lindex $pools $i] $price_ratio $external_price $volatility $uncertainty_bps $horizon_seconds] + set next [my _state_from_pool [lindex $pools [expr {$i+1}]] $price_ratio $external_price $volatility $uncertainty_bps $horizon_seconds] + set pred [my _raw_prediction slippage_estimate $prev] + set actualKind [my _prediction_index slippage_estimate] + set actual [my _scalar queryValue $actualKind $next] + if {$actual >= [dict get $pred lower_wad] && $actual <= [dict get $pred upper_wad]} { + incr hits + } + incr total + } + if {$total == 0} { return 5.0 } + return [expr {10.0*double($hits)/double($total)}] + } + + method query_history {ticker prediction_type horizon price_history pool_history} { + if {![my available]} { error "amm_runtime_unavailable" } + set prices [my _filter_prices $price_history $ticker] + set pools [my _filter_pools $pool_history $ticker] + if {![llength $pools]} { error "insufficient_pool_history" } + if {[llength $prices] < 2} { error "insufficient_price_history" } + + lassign [my _horizon $horizon] horizon_seconds horizon_label + set first [lindex $prices 0] + set last [lindex $prices end] + set first_price [dict get $first price] + set last_price [dict get $last price] + set price_ratio [expr {double($last_price)/double($first_price)}] + set volatility [my _volatility $prices] + set pool_conf [dict get [lindex $pools end] confidence] + set price_conf [dict get $last confidence] + set uncertainty_bps [my _uncertainty_bps $price_conf $pool_conf] + + set raw [my _state_from_pool [lindex $pools end] $price_ratio $last_price $volatility $uncertainty_bps $horizon_seconds] + set native [my _raw_prediction $prediction_type $raw] + set value [my _wad_double [dict get $native value_wad]] + set lower [my _wad_double [dict get $native lower_wad]] + set upper [my _wad_double [dict get $native upper_wad]] + + set confidence [expr {(double($price_conf)+double($pool_conf))/2.0}] + if {$confidence < 0} { set confidence 0 } + if {$confidence > 10} { set confidence 10 } + set correctness [my _correctness $pools $price_ratio $last_price $volatility $uncertainty_bps $horizon_seconds] + set denom [expr {max(abs($value),1.0e-9)}] + set relative_width [expr {abs($upper-$lower)/$denom}] + set certainty [expr {$confidence/(1.0+min($relative_width,5.0))}] + if {$certainty < 0} { set certainty 0 } + if {$certainty > 10} { set certainty 10 } + + set recent_shift [expr {double($last_price)/double($first_price)-1.0}] + return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type amm_liquidity token_ticker $ticker recent_shift $recent_shift prediction_type $prediction_type calibration_sources price_tick,dex_pool_state timestamp [clock seconds]] + } +} From a6c978bf958e5af88a8920eb8f722fecd0e7f73b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:37:17 -0700 Subject: [PATCH 104/156] M3c: wire AMM runner into stomach --- core/src/economy/stomach.tcl | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index 6ed425c..6e02811 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -7,14 +7,14 @@ set ::stomach::root $__stomach_dir foreach __stomach_file { traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl sims/registry.tcl sims/scheduler.tcl sims/hub.tcl - sims/statistical/runner.tcl marketplace.tcl + sims/statistical/runner.tcl sims/amm/runner.tcl marketplace.tcl } { source [file join $__stomach_dir $__stomach_file] } unset __stomach_file oo::class create ::stomach::Economy { - variable traders wallets sae conductor feeds sims registry clock statistical_runner market taxes + variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner market taxes constructor {args} { set cap 256 if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } @@ -34,11 +34,12 @@ oo::class create ::stomach::Economy { set clock [::stomach::HorizonClock new] $clock start set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]] + set amm_runner [::stomach::AMMRunner new] set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set taxes {} } destructor { - foreach obj [list $market $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { + foreach obj [list $market $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { catch {$obj destroy} } } @@ -59,6 +60,12 @@ oo::class create ::stomach::Economy { method feed_history {feed_type} { return [$feeds history $feed_type] } method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } method statistical_runner_available {} { return [$statistical_runner available] } + method amm_runner_available {} { return [$amm_runner available] } + method amm_from_feed {ticker prediction_type horizon} { + set p [$amm_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history dex_pool_state]] + $sims publish amm_liquidity $p + return $p + } method statistical_query_type { prices ticker prediction_type horizon {paths 4000} {seed 1} {dt 0.0027397260273972603} From fecb4b858c38988b545fa629a1456e6701dfd2c8 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:37:34 -0700 Subject: [PATCH 105/156] ci: deploy ephemeral M3c EVM bridge --- .github/workflows/m3c-amm.yml | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml index 77571c6..38ba666 100644 --- a/.github/workflows/m3c-amm.yml +++ b/.github/workflows/m3c-amm.yml @@ -6,6 +6,9 @@ on: - feat/stomach-economic-organ paths: - "core/src/economy/sims/amm/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" - ".github/workflows/m3c-amm.yml" pull_request: paths: @@ -32,6 +35,37 @@ jobs: - name: Run M3c native tests run: forge test -vv + - name: Start local EVM and deploy read-only M3c bridge + shell: bash + run: | + set -euo pipefail + anvil --silent --port 8545 > /tmp/m3c-anvil.log 2>&1 & + echo $! > /tmp/m3c-anvil.pid + ready=0 + for i in $(seq 1 30); do + if cast block-number --rpc-url http://127.0.0.1:8545 >/dev/null 2>&1; then + ready=1 + break + fi + sleep 0.2 + done + test "$ready" = 1 + + wallet="$(cast wallet new)" + key="$(printf '%s\n' "$wallet" | awk '/Private key:/ {print $3}')" + addr="$(printf '%s\n' "$wallet" | awk '/Address:/ {print $2}')" + test -n "$key" + test -n "$addr" + + cast rpc anvil_setBalance "$addr" 0x3635C9ADC5DEA00000 --rpc-url http://127.0.0.1:8545 >/dev/null + + deploy="$(forge create src/AMMQuery.sol:AMMQuery --rpc-url http://127.0.0.1:8545 --private-key "$key" --broadcast)" + query_addr="$(printf '%s\n' "$deploy" | awk '/Deployed to:/ {print $3}')" + [[ "$query_addr" =~ ^0x[0-9A-Fa-f]{40}$ ]] + + echo "AMM_RPC_URL=http://127.0.0.1:8545" >> "$GITHUB_ENV" + echo "AMM_QUERY_ADDRESS=$query_addr" >> "$GITHUB_ENV" + - name: Run M2 → M3c → Hub integration shell: bash run: | From 8bbb8c170058a2f2db21a9cf008acccdf380b56c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:38:14 -0700 Subject: [PATCH 106/156] ci: capture ephemeral Foundry wallet output --- .github/workflows/m3c-amm.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml index 38ba666..d7d7111 100644 --- a/.github/workflows/m3c-amm.yml +++ b/.github/workflows/m3c-amm.yml @@ -51,7 +51,7 @@ jobs: done test "$ready" = 1 - wallet="$(cast wallet new)" + wallet="$(cast wallet new 2>&1)" key="$(printf '%s\n' "$wallet" | awk '/Private key:/ {print $3}')" addr="$(printf '%s\n' "$wallet" | awk '/Address:/ {print $2}')" test -n "$key" From 985deec8d7b58f14d8d4c21321ab58cbb48ccc20 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:38:57 -0700 Subject: [PATCH 107/156] M3c: fix runner environment detection --- core/src/economy/sims/amm/runner.tcl | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/core/src/economy/sims/amm/runner.tcl b/core/src/economy/sims/amm/runner.tcl index 5dd092b..8e814b7 100644 --- a/core/src/economy/sims/amm/runner.tcl +++ b/core/src/economy/sims/amm/runner.tcl @@ -5,16 +5,20 @@ oo::class create ::stomach::AMMRunner { constructor {} { set runtime cast - set rpc [expr {[info exists ::env(AMM_RPC_URL)] ? $::env(AMM_RPC_URL) : ""}] - set address [expr {[info exists ::env(AMM_QUERY_ADDRESS)] ? $::env(AMM_QUERY_ADDRESS) : ""}] + set rpc "" + set address "" + if {[info exists ::env(AMM_RPC_URL)]} { + set rpc $::env(AMM_RPC_URL) + } + if {[info exists ::env(AMM_QUERY_ADDRESS)]} { + set address $::env(AMM_QUERY_ADDRESS) + } } method available {} { - expr { - [auto_execok $runtime] ne "" && - $rpc ne "" && - [regexp {^0x[0-9A-Fa-f]{40}$} $address] - } + if {[auto_execok $runtime] eq ""} { return 0 } + if {$rpc eq "" || $address eq ""} { return 0 } + return [regexp {^0x[0-9A-Fa-f]{40}$} $address] } method _prediction_index {prediction_type} { From aa79c3ab687d531c253d4d153c1d6dc5e8667146 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:39:40 -0700 Subject: [PATCH 108/156] M3c: canonicalize decimal WAD parsing --- core/src/economy/sims/amm/runner.tcl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/src/economy/sims/amm/runner.tcl b/core/src/economy/sims/amm/runner.tcl index 8e814b7..c1e98c4 100644 --- a/core/src/economy/sims/amm/runner.tcl +++ b/core/src/economy/sims/amm/runner.tcl @@ -51,7 +51,11 @@ oo::class create ::stomach::AMMRunner { if {[regexp {^([+-]?)([0-9]+)(?:\.([0-9]*))?$} $s -> sign whole frac]} { if {$frac eq ""} { set frac "" } set frac [string range "${frac}000000000000000000" 0 17] - set n [expr {$whole * 1000000000000000000 + $frac}] + set whole_dec [string trimleft $whole 0] + set frac_dec [string trimleft $frac 0] + if {$whole_dec eq ""} { set whole_dec 0 } + if {$frac_dec eq ""} { set frac_dec 0 } + set n [expr {$whole_dec * 1000000000000000000 + $frac_dec}] if {$sign eq "-"} { set n [expr {-$n}] } return $n } From b2d1d382f341e9feca95a382a04a6aa3021a10e0 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:41:44 -0700 Subject: [PATCH 109/156] ci: gate M3c composition changes on pull requests --- .github/workflows/m3c-amm.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml index d7d7111..e99e4d5 100644 --- a/.github/workflows/m3c-amm.yml +++ b/.github/workflows/m3c-amm.yml @@ -13,6 +13,9 @@ on: pull_request: paths: - "core/src/economy/sims/amm/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" - ".github/workflows/m3c-amm.yml" workflow_dispatch: From 999a1fb1e07da5ff394e8dc50345b3a9582bc942 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:42:04 -0700 Subject: [PATCH 110/156] docs: mark M3c V1 implemented --- core/docs/plans/M3c-amm-liquidity-sims.md | 42 ++++++++++++++++------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/core/docs/plans/M3c-amm-liquidity-sims.md b/core/docs/plans/M3c-amm-liquidity-sims.md index d635830..4091cf7 100644 --- a/core/docs/plans/M3c-amm-liquidity-sims.md +++ b/core/docs/plans/M3c-amm-liquidity-sims.md @@ -7,11 +7,16 @@ loss, and the non-cooperative game between liquidity providers and arbitrageurs* literature [1,2]. ## 2. Status / certainty -KERNEL IMPLEMENTED · Solidity/Foundry. `core/src/economy/sims/amm/src/AMMSim.sol` -implements fee-adjusted constant-product swaps, fixed-point impermanent loss, nonlinear -slippage, and an IL-vs-fee withdrawal decision; Foundry-native tests cover the invariants. -Concentrated liquidity, multi-pool routing, and richer LP/arbitrage populations remain -incremental. Mathematical foundations C5; implementation C2; parameterization C1. +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 +slippage, IL-derived withdrawal thresholds, active LP rebalance, just-in-time liquidity economics, +deterministic backrun and sandwich populations, concentrated-liquidity position/range accounting, +two-pool optimal split routing, and all five bounded M3c prediction types. `AMMQuery.sol` is a +read-only EVM ABI bridge; `runner.tcl` calibrates from M2 `price_tick` + `dex_pool_state`, +evaluates the Solidity engine via `eth_call`, and publishes the result into the M3 hub for +Marketplace consumption. Dedicated Foundry CI verifies both native math and the M2→M3c→Hub +boundary on an ephemeral local Anvil instance. Mathematical foundations C5; implementation C3; +live-market parameterization remains data-dependent. ## 3. Language & location **Solidity** + **Foundry** (forge, anvil) · `src/economy/sims/amm/`. Foundry is hosted @@ -49,9 +54,15 @@ execute, eliminating precision-mismatch bugs between sim and production contract `lp_withdrawal_threshold`. - Calibration: ingests `dex_pool_state` and `price_tick` from M2. -## 6. Dependencies & stubs -- M2 Data Feeds — pool state and price data; *stub:* canned pool snapshots. -- M3 Sims hub — lifecycle management; *stub:* manual init. +## 6. Dependencies & runtime boundary +- M2 Data Feeds — normalized `dex_pool_state` supplies reserves, fee tier, volume, TVL and + representative trade size; `price_tick` supplies external price, realized movement and + volatility calibration. +- M3 Sims hub — every M3c result is converted to the common bounded-prediction schema and + published as `amm_liquidity`; Traders read it through Marketplace. +- Foundry — hosted separately by design. CI uses a fresh local Anvil chain and deploys only the + stateless/read-only `AMMQuery` bridge. M3c has no live-chain signer, broadcaster, approval, + transfer, or swap-execution surface. ## 7. Invariants / laws - **L1 (C5):** the **constant product invariant** $x \cdot y = k$ (adjusted for fees $\gamma$) @@ -74,7 +85,14 @@ Invariant: every swap satisfies $(x + \gamma \Delta x)(y - \Delta y) = k$. IL fo closed-form for known price ratios. Slippage: large swaps produce greater slippage than small. LP threshold: LP withdraws when IL exceeds fee income. Bounds: all outputs bounded. -## 10. Open items -- Concentrated liquidity (>>>Uniswap v3 style<<<) — extends the base model significantly. -- Multi-pool routing (split swaps across pools). >>>yes<<< -- Which specific pools to simulate (>>>ETH<<>and other popular chains<< NOT STABLE/USDC/USDT etc. +## 10. V1 decisions and future extensions +- **Concentrated liquidity:** V1 implements the canonical liquidity-to-token amount equations, + one-sided out-of-range positions, and volatility/horizon-derived optimal ranges. Full + Uniswap-v3-style initialized-tick crossing and fee-growth accounting are a future fidelity + extension, not required by the V1 prediction contract. +- **Multi-pool routing:** V1 implements deterministic optimal exact-input splitting across two + pools by marginal-output equalization. N-way routing is a future scaling extension. +- **Pool universe:** the engine is chain- and pair-agnostic. M2 chooses the concrete pools; + the simulator does not hardcode ETH/USDC, stablecoins, or any particular chain. +- **Execution boundary:** arbitrage and sandwich functions are simulation constructs only. + No native M3c API can submit a real swap. From bd948ab4e9d43cea66247267ff2e2c6b2ef5b8b7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:42:17 -0700 Subject: [PATCH 111/156] docs: expand M3c simulator inventory --- core/src/economy/sims/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md index c1bac5d..a39126e 100644 --- a/core/src/economy/sims/README.md +++ b/core/src/economy/sims/README.md @@ -6,7 +6,7 @@ Seven native simulator engines live here behind the Tcl M3 hub. |---|---|---|---| | 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 | | M3b | sociological | ECLiPSe Prolog | replicator dynamics, Hegselmann-Krause, complex contagion, pump/dump phase | -| M3c | AMM/liquidity | Solidity + Foundry | fee-adjusted x*y=k, impermanent loss, slippage, IL-derived withdrawal | +| 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 | | M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | | M3e | tokenomics/macro | Fortran 2018 | Euler-Maruyama, stock-flow conservation, kinked lending, directional contagion, yield weights | | M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | @@ -22,6 +22,6 @@ tclsh core/src/economy/sims/run_tests.tcl Pass `--strict` when the environment is expected to contain every external runtime. -The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design; their native test files are checked in next to their engines. +The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; ECLiPSe native test files remain checked in next to their engines. This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. From 3746b097e3745a464f929afbc7c845fcd3d14b20 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:42:21 -0700 Subject: [PATCH 112/156] docs: expose M3c V1 through economy overview --- core/src/economy/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index 635017c..53fa2b7 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. -- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b is ECLiPSe sociological, M3c Solidity AMM, M3d Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. +- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b is ECLiPSe sociological; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. @@ -33,6 +33,6 @@ It executes Tcl + every native suite whose runtime is installed. Use `--strict` ## 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`, `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`, `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. From 9def3dae5e0213168a34cb94c2e6f54fcdcb572c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:42:33 -0700 Subject: [PATCH 113/156] docs: add M3c V1 runtime contract --- core/src/economy/sims/amm/README.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 core/src/economy/sims/amm/README.md diff --git a/core/src/economy/sims/amm/README.md b/core/src/economy/sims/amm/README.md new file mode 100644 index 0000000..4e6f46b --- /dev/null +++ b/core/src/economy/sims/amm/README.md @@ -0,0 +1,27 @@ +# M3c — AMM & liquidity simulator + +M3c V1 is the Solidity-native AMM simulator behind the stomach's `amm_liquidity` prediction type. + +Implemented mechanics: fee-adjusted constant-product swaps; exact fixed-point impermanent loss; nonlinear slippage; IL-derived withdrawal thresholds; active LP rebalance; just-in-time liquidity fee economics; deterministic backrun and sandwich simulation; concentrated-liquidity position amounts and volatility/horizon range forecasts; deterministic exact-input splitting across two pools. + +The five public prediction types are `impermanent_loss`, `pool_return`, `optimal_range`, `slippage_estimate`, and `lp_withdrawal_threshold`. Every publication remains a numeric `BoundedPrediction` with explicit lower/value/upper bounds. + +Calibration consumes normalized M2 `dex_pool_state` and `price_tick` histories. Source confidence sets the uncertainty width; recent literal pool-state history supplies a retrospective correctness score. + +The live simulation boundary is: + +`M2 → AMMRunner (Tcl) → AMMQuery (read-only eth_call) → AMMSim → SimsHub → Marketplace` + +`AMMQuery.sol` is stateless and exposes only pure query methods. It has no transfer, approval, swap, signer, broadcaster, or privileged function. CI deploys it only to a fresh ephemeral local Anvil instance. + +V1 concentrated liquidity covers position/range accounting, not full initialized-tick traversal. V1 multi-pool routing optimizes across two pools; N-way routing is a scaling extension. + +Verification: + +```sh +cd core/src/economy/sims/amm +forge test -vv +tclsh integration.test +``` + +The dedicated M3c workflow enforces both the native Foundry suite and the Tcl M2→M3c→Hub summary. From f71d61e7e7de8c50ccb3b3011def6db3f999fd35 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:46:23 -0700 Subject: [PATCH 114/156] tooling: install ECLiPSe CLP for M3b and M3f --- .claude/hooks/install-toolchains.sh | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 .claude/hooks/install-toolchains.sh diff --git a/.claude/hooks/install-toolchains.sh b/.claude/hooks/install-toolchains.sh new file mode 100644 index 0000000..e5d2903 --- /dev/null +++ b/.claude/hooks/install-toolchains.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# SessionStart non-apt toolchains for sica-fondt. +# +# ECLiPSe CLP is required by M3b/M3f and is not distributed as a reliable +# Ubuntu apt package. Install the official x86_64 Linux binary distribution +# idempotently. Foundry remains separately hosted by design (M3c). +set -euo pipefail + +if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ] && [ "${SICA_INSTALL_TOOLCHAINS:-}" != "true" ]; then + exit 0 +fi + +ECLIPSE_VERSION="7.2_13" +ECLIPSE_ARCH="x86_64_linux" +ECLIPSE_ROOT="/opt/eclipse-clp-${ECLIPSE_VERSION}" +ECLIPSE_BASE="https://eclipseclp.org/Distribution/Builds/${ECLIPSE_VERSION}/${ECLIPSE_ARCH}" + +if ! command -v eclipse >/dev/null 2>&1; then + tmp="$(mktemp -d)" + trap 'rm -rf "$tmp"' EXIT + + curl --fail --location --silent --show-error "${ECLIPSE_BASE}/eclipse_basic.tgz" --output "${tmp}/eclipse_basic.tgz" + + sudo mkdir -p "${ECLIPSE_ROOT}" + sudo tar -xzf "${tmp}/eclipse_basic.tgz" -C "${ECLIPSE_ROOT}" + + sudo tee /usr/local/bin/eclipse >/dev/null < Date: Mon, 19 Oct 2026 19:47:13 -0700 Subject: [PATCH 115/156] test: require M3b archetypes and bandit replicator --- core/src/economy/sims/sociological/test.ecl | 70 ++++++++++++++++++--- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 574180f..231f076 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -1,8 +1,64 @@ :- [engine]. -run :- - replicator_step([0.5,0.5],[2.0,1.0],0.2,N), N=[A,B], A > B, - hk_step([0.0,0.1,0.9,1.0],0.2,1.0,H), H=[H1,H2,H3,H4], H1 < 0.2, H4 > 0.8, - complex_contagion([1,3],[4,4],[0.5,0.5],Ad), Ad=[0,1], - pump_phase(0.1,3.0,0.9,promotion), - writeln('SOCIOLOGICAL TESTS PASSED'). -:- local initialization(run). + +approx(A, B, Eps) :- Diff is abs(A-B), Diff =< Eps. + +must(Name, Goal) :- + ( call(Goal) -> + true + ; + printf(error, "FAILED: %w%n", [Name]), + fail + ). + +run_tests :- + must(replicator_normalizes, + (replicator_step([0.5,0.5],[1.0,2.0],0.2,N), + N=[A,B], approx(A+B,1.0,1.0e-9), B > 0.5)), + + must(hk_clusters_local_neighbors, + (hk_step([0.0,0.1,0.9,1.0],0.2,1.0,H), + H=[H1,H2,H3,H4], + approx(H1,0.05,1.0e-9), + approx(H2,0.05,1.0e-9), + approx(H3,0.95,1.0e-9), + approx(H4,0.95,1.0e-9))), + + must(complex_contagion_needs_threshold, + (complex_contagion([1,3],[4,4],[0.5,0.5],Ad), + Ad=[0,1])), + + must(pump_phase_promotion, + pump_phase(0.10,2.5,0.8,promotion)), + + must(archetype_catalog_v1, + archetype_catalog([ + retail_herd, + contrarian_whale, + mev_searcher, + passive_lp, + manipulator + ])), + + must(ucb_rewards_exploration, + (ucb_score(0.2,10,100,0.7,S1), + ucb_score(0.8,10,100,0.7,S2), + S2 > S1)), + + must(bandit_replicator_adapts, + (bandit_replicator_step( + [0.5,0.5], + [2.0,9.0], + [10,10], + 20, + 0.6, + 0.25, + Next, + Scores + ), + Next=[N1,N2], + Scores=[U1,U2], + U2 > U1, + N2 > N1, + approx(N1+N2,1.0,1.0e-9))), + + writeln("SOCIOLOGICAL TESTS PASSED"). From b2211d69a7178bdbba332a96f330774b001b9e7e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:47:26 -0700 Subject: [PATCH 116/156] ci: add native ECLiPSe gate for M3b --- .github/workflows/m3b-sociological.yml | 41 ++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 .github/workflows/m3b-sociological.yml diff --git a/.github/workflows/m3b-sociological.yml b/.github/workflows/m3b-sociological.yml new file mode 100644 index 0000000..87f661a --- /dev/null +++ b/.github/workflows/m3b-sociological.yml @@ -0,0 +1,41 @@ +name: M3b Sociological CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/sociological/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".claude/hooks/install-toolchains.sh" + - ".github/workflows/m3b-sociological.yml" + pull_request: + paths: + - "core/src/economy/sims/sociological/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".claude/hooks/install-toolchains.sh" + - ".github/workflows/m3b-sociological.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3b: + name: ECLiPSe sociological engine + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install ECLiPSe CLP + env: + SICA_INSTALL_TOOLCHAINS: "true" + run: bash .claude/hooks/install-toolchains.sh + + - name: Run M3b native tests + working-directory: core/src/economy/sims/sociological + run: eclipse -b test.ecl -e run_tests From cecd152b95a0d04680f9a419732d1a6cf9ef5152 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:48:05 -0700 Subject: [PATCH 117/156] test: evaluate M3b numeric assertions explicitly --- core/src/economy/sims/sociological/test.ecl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 231f076..315708b 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -13,7 +13,7 @@ must(Name, Goal) :- run_tests :- must(replicator_normalizes, (replicator_step([0.5,0.5],[1.0,2.0],0.2,N), - N=[A,B], approx(A+B,1.0,1.0e-9), B > 0.5)), + N=[A,B], Sum is A+B, approx(Sum,1.0,1.0e-9), B > 0.5)), must(hk_clusters_local_neighbors, (hk_step([0.0,0.1,0.9,1.0],0.2,1.0,H), @@ -59,6 +59,7 @@ run_tests :- Scores=[U1,U2], U2 > U1, N2 > N1, - approx(N1+N2,1.0,1.0e-9))), + SumN is N1+N2, + approx(SumN,1.0,1.0e-9))), writeln("SOCIOLOGICAL TESTS PASSED"). From 6ad5686b0b89e88f1087b98c921f9bd9d18224fb Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:48:43 -0700 Subject: [PATCH 118/156] M3b: add archetypes and UCB replicator --- core/src/economy/sims/sociological/engine.ecl | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index c7f9ddc..c081f1e 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -38,3 +38,48 @@ pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase) :- VolumeRatio > 2.0, PriceDelta < -0.05 -> Phase=collapse ; VolumeRatio > 1.5, PriceDelta >= 0 -> Phase=distribution ; Phase=accumulation). + + +% V1 behavioral archetypes. These are abstract population roles, never literal +% identities or profiles of real market participants. +archetype_catalog([ + retail_herd, + contrarian_whale, + mev_searcher, + passive_lp, + manipulator +]). + +ucb_score(_, Count, _, _, 1.0e9) :- + Count =< 0, !. +ucb_score(Mean, Count, Total, Explore, Score) :- + Count > 0, + ( Total =< 1 -> + Bonus = 0.0 + ; + Bonus is Explore * sqrt(log(Total) / Count) + ), + Score is Mean + Bonus. + +ucb_scores([], [], _, _, []). +ucb_scores([Reward|Rewards], [Count|Counts], Total, Explore, [Score|Scores]) :- + ( Count =< 0 -> + Mean = 0.0 + ; + Mean is Reward / Count + ), + ucb_score(Mean, Count, Total, Explore, Score), + ucb_scores(Rewards, Counts, Total, Explore, Scores). + +bandit_replicator_step( + Shares, + RewardSums, + Counts, + Total, + Explore, + Dt, + Next, + Scores +) :- + ucb_scores(RewardSums, Counts, Total, Explore, Scores), + replicator_step(Shares, Scores, Dt, Next). From f5c82447eb9640f16d9d399b81b27c7542c3cd61 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:49:20 -0700 Subject: [PATCH 119/156] M3b: use ECLiPSe natural log in UCB --- core/src/economy/sims/sociological/engine.ecl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index c081f1e..4d67e34 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -57,7 +57,7 @@ ucb_score(Mean, Count, Total, Explore, Score) :- ( Total =< 1 -> Bonus = 0.0 ; - Bonus is Explore * sqrt(log(Total) / Count) + Bonus is Explore * sqrt(ln(Total) / Count) ), Score is Mean + Bonus. From 1415f0f9d3f5bd642e40cd65475687693785fbbf Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:49:59 -0700 Subject: [PATCH 120/156] test: require M3b mean-field equilibrium --- core/src/economy/sims/sociological/test.ecl | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 315708b..27b44cd 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -62,4 +62,31 @@ run_tests :- SumN is N1+N2, approx(SumN,1.0,1.0e-9))), + + must(mfg_population_guard, + (not(mfg_valid_population(99)), + mfg_valid_population(100), + mfg_valid_population(1000))), + + must(mfg_equilibrium_normalized_and_stable, + (mfg_equilibrium( + 250, + [0.10,0.20,0.40,0.20,0.10], + 0.12, + 0.08, + 0.35, + 80, + Density, + Value, + Stability, + Residual + ), + Density=[D1,D2,D3,D4,D5], + SumD is D1+D2+D3+D4+D5, + approx(SumD,1.0,1.0e-6), + D1 >= 0.0, D2 >= 0.0, D3 >= 0.0, D4 >= 0.0, D5 >= 0.0, + length(Value,5), + Stability >= 0.0, Stability =< 1.0, + Residual >= 0.0, Residual < 0.25)), + writeln("SOCIOLOGICAL TESTS PASSED"). From 8301382d9357c96f80577a7839e2c630235fe119 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:50:59 -0700 Subject: [PATCH 121/156] M3b: add coupled HJB Fokker-Planck solver --- core/src/economy/sims/sociological/engine.ecl | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index 4d67e34..33ee0f0 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -83,3 +83,135 @@ bandit_replicator_step( ) :- ucb_scores(RewardSums, Counts, Total, Explore, Scores), replicator_step(Shares, Scores, Dt, Next). + + +% --- Large-population mean-field game -------------------------------------- + +mfg_valid_population(N) :- integer(N), N >= 100. + +zeros_like([], []). +zeros_like([_|Xs], [0.0|Zs]) :- zeros_like(Xs, Zs). + +nth0_value([X|_], 0, X) :- !. +nth0_value([_|Xs], I, X) :- + I > 0, + I1 is I - 1, + nth0_value(Xs, I1, X). + +reflected_neighbor(List, I, N, X) :- + ( I < 0 -> + nth0_value(List, 0, X) + ; I >= N -> + Last is N - 1, + nth0_value(List, Last, X) + ; + nth0_value(List, I, X) + ). + +hjb_residual_at(M, U, I, N, Diffusion, Coupling, Residual) :- + nth0_value(U, I, Ui), + nth0_value(M, I, Mi), + IL is I - 1, + IR is I + 1, + reflected_neighbor(U, IL, N, UL), + reflected_neighbor(U, IR, N, UR), + Grad is (UR - UL) / 2.0, + Lap is UL - 2.0*Ui + UR, + Residual is Ui + 0.5*Grad*Grad - Coupling*Mi - Diffusion*Lap. + +hjb_residuals(M, U, Diffusion, Coupling, Residuals) :- + length(U, N), + hjb_residuals_(0, N, M, U, Diffusion, Coupling, Residuals). +hjb_residuals_(I, N, _, _, _, _, []) :- I >= N, !. +hjb_residuals_(I, N, M, U, Diffusion, Coupling, [R|Rs]) :- + hjb_residual_at(M, U, I, N, Diffusion, Coupling, R), + I1 is I + 1, + hjb_residuals_(I1, N, M, U, Diffusion, Coupling, Rs). + +newton_value_update([], [], _, _, []). +newton_value_update([U|Us], [R|Rs], Diffusion, Damping, [V|Vs]) :- + Denom is 1.0 + 2.0*Diffusion, + V is U - Damping*R/Denom, + newton_value_update(Us, Rs, Diffusion, Damping, Vs). + +hjb_newton_step(M, U, Diffusion, Coupling, Damping, Next, Residuals) :- + hjb_residuals(M, U, Diffusion, Coupling, Residuals), + newton_value_update(U, Residuals, Diffusion, Damping, Next). + +boltzmann_weights([], _, []). +boltzmann_weights([U|Us], Temperature, [W|Ws]) :- + W is exp(-U / Temperature), + boltzmann_weights(Us, Temperature, Ws). + +fp_stationary_density(U, Diffusion, Density) :- + ( Diffusion < 1.0e-6 -> Temp = 1.0e-6 ; Temp = Diffusion ), + boltzmann_weights(U, Temp, Raw), + normalize(Raw, Density). + +blend_density([], [], _, []). +blend_density([M|Ms], [T|Ts], Damping, [N|Ns]) :- + N0 is (1.0-Damping)*M + Damping*T, + ( N0 < 0.0 -> N = 0.0 ; N = N0 ), + blend_density(Ms, Ts, Damping, Ns). + +density_relax(M, Target, Damping, Next) :- + blend_density(M, Target, Damping, Raw), + normalize(Raw, Next). + +abs_list([], []). +abs_list([X|Xs], [A|As]) :- A is abs(X), abs_list(Xs, As). + +max_list([X|Xs], Max) :- max_list_(Xs, X, Max). +max_list_([], Max, Max). +max_list_([X|Xs], Acc, Max) :- + ( X > Acc -> Acc1 = X ; Acc1 = Acc ), + max_list_(Xs, Acc1, Max). + +list_l1([], [], 0.0). +list_l1([A|As], [B|Bs], D) :- + list_l1(As, Bs, Tail), + D is abs(A-B) + Tail. + +mfg_residual(M, U, Diffusion, Coupling, Residual) :- + hjb_residuals(M, U, Diffusion, Coupling, H), + abs_list(H, AbsH), + max_list(AbsH, HMax), + fp_stationary_density(U, Diffusion, Target), + list_l1(M, Target, FpResidual), + Residual is max(HMax, FpResidual). + +mfg_iter(0, M, U, Diffusion, Coupling, _, M, U, Residual) :- !, + mfg_residual(M, U, Diffusion, Coupling, Residual). +mfg_iter(K, M, U, Diffusion, Coupling, Damping, Density, Value, Residual) :- + K > 0, + hjb_newton_step(M, U, Diffusion, Coupling, Damping, U1, _), + fp_stationary_density(U1, Diffusion, Target), + density_relax(M, Target, Damping, M1), + K1 is K - 1, + mfg_iter(K1, M1, U1, Diffusion, Coupling, Damping, + Density, Value, Residual). + +mfg_equilibrium( + Population, + InitialDensity, + Diffusion, + Coupling, + Damping, + Iterations, + Density, + Value, + Stability, + Residual +) :- + mfg_valid_population(Population), + Diffusion > 0.0, + Coupling >= 0.0, + Damping > 0.0, + Damping =< 1.0, + integer(Iterations), + Iterations > 0, + normalize(InitialDensity, M0), + zeros_like(M0, U0), + mfg_iter(Iterations, M0, U0, Diffusion, Coupling, Damping, + Density, Value, Residual), + Stability is 1.0 / (1.0 + 10.0*Residual). From 4923ee2524963fbd7e61fddfa3106c55a136f69b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:51:30 -0700 Subject: [PATCH 122/156] test: enforce multi-exposure contagion law --- core/src/economy/sims/sociological/test.ecl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 27b44cd..8ed1d9e 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -27,6 +27,10 @@ run_tests :- (complex_contagion([1,3],[4,4],[0.5,0.5],Ad), Ad=[0,1])), + must(complex_contagion_requires_multiple_exposures, + (complex_contagion([1,2,3],[1,2,4],[0.1,0.5,0.75],Multi), + Multi=[0,1,1])), + must(pump_phase_promotion, pump_phase(0.10,2.5,0.8,promotion)), From 43adcadaa02cb5be4997f19670fce344baeb5e62 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:52:00 -0700 Subject: [PATCH 123/156] M3b: require multiple exposures for contagion --- core/src/economy/sims/sociological/engine.ecl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index 33ee0f0..4e7df81 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -31,7 +31,8 @@ complex_contagion(Exposures, Degrees, Thresholds, Adoption) :- contagion_(Exposu contagion_([],[],[],[]). contagion_([E|Es],[D|Ds],[T|Ts],[A|As]) :- (D =< 0 -> Frac=0 ; Frac is E/D), - (Frac >= T -> A=1 ; A=0), contagion_(Es,Ds,Ts,As). + (E >= 2, Frac >= T -> A=1 ; A=0), + contagion_(Es,Ds,Ts,As). pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase) :- (VolumeRatio > 2.0, Sentiment > 0.6, PriceDelta > 0.05 -> Phase=promotion ; From 95c44dc2c87ab24356053169cd0a09f37c7bc7dd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:52:32 -0700 Subject: [PATCH 124/156] test: require dynamic pump dump populations --- core/src/economy/sims/sociological/test.ecl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 8ed1d9e..1b44b8e 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -93,4 +93,23 @@ run_tests :- Stability >= 0.0, Stability =< 1.0, Residual >= 0.0, Residual < 0.25)), + + must(pump_abm_promotion_selects_manipulators, + (pump_abm_step( + [0.80,0.10,0.10], + 0.10,3.0,0.85,0.25, + Promotion,promotion + ), + Promotion=[_,_,PromoMP], + PromoMP > 0.10)), + + must(pump_abm_collapse_selects_against_manipulators, + (pump_abm_step( + [0.70,0.15,0.15], + -0.12,3.2,0.20,0.25, + Collapse,collapse + ), + Collapse=[_,_,CollapseMP], + CollapseMP < 0.15)), + writeln("SOCIOLOGICAL TESTS PASSED"). From e9338de45b261eea2e27e93f90c4e96fe757ca62 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:53:12 -0700 Subject: [PATCH 125/156] M3b: add bounded-rational pump dump ABM --- core/src/economy/sims/sociological/engine.ecl | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index 4e7df81..768ac68 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -216,3 +216,42 @@ mfg_equilibrium( mfg_iter(Iterations, M0, U0, Diffusion, Coupling, Damping, Density, Value, Residual), Stability is 1.0 / (1.0 + 10.0*Residual). + + +% --- Pump/dump three-population ABM ---------------------------------------- + +pump_phase_payoffs(accumulation, [1.00,1.10,1.30]). +pump_phase_payoffs(promotion, [1.15,1.35,2.00]). +pump_phase_payoffs(distribution, [0.85,1.20,1.45]). +pump_phase_payoffs(collapse, [0.70,1.40,0.20]). + +satisficing_payoff(Payoff, Aspiration, Limit, Effective) :- + Gap is Payoff - Aspiration, + ( Gap > Limit -> + Bounded = Limit + ; Gap < -Limit -> + Bounded is -Limit + ; + Bounded = Gap + ), + Effective is Aspiration + Bounded. + +satisficing_payoffs([], _, _, []). +satisficing_payoffs([P|Ps], Aspiration, Limit, [E|Es]) :- + satisficing_payoff(P, Aspiration, Limit, E), + satisficing_payoffs(Ps, Aspiration, Limit, Es). + +pump_abm_step( + Shares, + PriceDelta, + VolumeRatio, + Sentiment, + Dt, + Next, + Phase +) :- + Shares = [_,_,_], + pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase), + pump_phase_payoffs(Phase, RawPayoffs), + satisficing_payoffs(RawPayoffs, 1.0, 0.75, Payoffs), + replicator_step(Shares, Payoffs, Dt, Next). From e9a748eb2f05228bfd6f1bf5a5419920af5b0c5b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:53:58 -0700 Subject: [PATCH 126/156] test: require complete bounded M3b prediction contract --- core/src/economy/sims/sociological/test.ecl | 60 +++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 1b44b8e..99ad07c 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -10,6 +10,25 @@ must(Name, Goal) :- fail ). +prediction_types([ + sentiment_index, + herd_threshold, + strategy_distribution, + cascade_probability, + coordination_stability, + opinion_cluster_count, + pump_dump_phase, + mfg_equilibrium_stability, + narrative_regime +]). + +check_prediction_types([], _, _). +check_prediction_types([Type|Types], State, Horizon) :- + sociological_prediction(Type,State,Horizon,V,L,U,_), + number(V), number(L), number(U), + L =< V, V =< U, + check_prediction_types(Types,State,Horizon). + run_tests :- must(replicator_normalizes, (replicator_step([0.5,0.5],[1.0,2.0],0.2,N), @@ -112,4 +131,45 @@ run_tests :- Collapse=[_,_,CollapseMP], CollapseMP < 0.15)), + + must(adaptive_hk_tightens_under_uncertainty, + (adaptive_confidence_bound(0.35,0.20,0.10,Loose), + adaptive_confidence_bound(0.35,0.90,0.50,Tight), + Tight < Loose, + Tight > 0.01)), + + must(opinion_cluster_count_detects_groups, + (opinion_cluster_count([0.10,0.12,0.50,0.52,0.90],0.08,Clusters), + Clusters =:= 3)), + + must(all_m3b_prediction_types_bounded, + (State=state( + 0.70, + 0.20, + 0.08, + 0.60, + 0.65, + [0.40,0.20,0.15,0.15,0.10], + [0.70,0.15,0.15], + 0.80, + [0.10,0.12,0.50,0.52,0.90] + ), + prediction_types(Types), + check_prediction_types(Types,State,weekly))), + + must(categorical_predictions_keep_labels, + (State2=state( + 0.85,0.15,0.10,0.50,0.75, + [0.45,0.15,0.10,0.10,0.20], + [0.70,0.10,0.20], + 0.75, + [0.70,0.72,0.75,0.80] + ), + sociological_prediction(pump_dump_phase,State2,daily,PV,PL,PU,PLabel), + PL =< PV, PV =< PU, + PLabel = promotion, + sociological_prediction(narrative_regime,State2,monthly,NV,NL,NU,NLabel), + NL =< NV, NV =< NU, + NLabel = bullish)), + writeln("SOCIOLOGICAL TESTS PASSED"). From f2f899c07b38057e4e97cc3783c60b682facc1b6 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:54:58 -0700 Subject: [PATCH 127/156] M3b: implement bounded sociological predictions --- core/src/economy/sims/sociological/engine.ecl | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index 768ac68..ba638bd 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -255,3 +255,182 @@ pump_abm_step( pump_phase_payoffs(Phase, RawPayoffs), satisficing_payoffs(RawPayoffs, 1.0, 0.75, Payoffs), replicator_step(Shares, Payoffs, Dt, Next). + + +% --- Adaptive confidence, clusters, and bounded prediction contract -------- + +clamp_value(X, Lo, Hi, Y) :- + ( X < Lo -> Y = Lo + ; X > Hi -> Y = Hi + ; Y = X + ). + +adaptive_confidence_bound(Base, Volatility, Dispersion, Bound) :- + Base > 0.0, + Penalty is 0.35*Volatility + 0.45*Dispersion, + Raw is Base * (1.0 - Penalty), + clamp_value(Raw, 0.01, Base, Bound). + +opinion_cluster_count([], _, 0) :- !. +opinion_cluster_count(Opinions, Bound, Count) :- + Bound >= 0.0, + sort(Opinions, Sorted), + Sorted = [First|Rest], + cluster_count_sorted(Rest, First, Bound, 1, Count). + +cluster_count_sorted([], _, _, Count, Count). +cluster_count_sorted([X|Xs], Previous, Bound, Acc, Count) :- + Gap is X - Previous, + ( Gap > Bound -> Acc1 is Acc + 1 ; Acc1 = Acc ), + cluster_count_sorted(Xs, X, Bound, Acc1, Count). + +sentiment_label(Sentiment, bullish) :- Sentiment > 0.25, !. +sentiment_label(Sentiment, bearish) :- Sentiment < -0.25, !. +sentiment_label(_, neutral). + +narrative_label(Sentiment, PriceShift, bearish) :- + (Sentiment < -0.25 ; PriceShift < -0.05), !. +narrative_label(Sentiment, PriceShift, bullish) :- + Sentiment > 0.25, PriceShift >= 0.0, !. +narrative_label(_, _, neutral). + +dominant_strategy(Shares, Label, Share) :- + archetype_catalog(Labels), + Shares = [S|Ss], + Labels = [L|Ls], + dominant_strategy_(Ss, Ls, L, S, Label, Share). + +dominant_strategy_([], [], Label, Share, Label, Share). +dominant_strategy_([S|Ss], [L|Ls], BestL, BestS, Label, Share) :- + ( S > BestS -> + NextL = L, NextS = S + ; + NextL = BestL, NextS = BestS + ), + dominant_strategy_(Ss, Ls, NextL, NextS, Label, Share). + +bounded_unit(Value0, Width0, Value, Lower, Upper) :- + clamp_value(Value0, 0.0, 1.0, Value), + (Width0 < 0.0 -> Width = 0.0 ; Width = Width0), + L0 is Value - Width, + U0 is Value + Width, + clamp_value(L0, 0.0, 1.0, Lower), + clamp_value(U0, 0.0, 1.0, Upper). + +bounded_ten(Value0, Width0, Value, Lower, Upper) :- + clamp_value(Value0, 0.0, 10.0, Value), + (Width0 < 0.0 -> Width = 0.0 ; Width = Width0), + L0 is Value - Width, + U0 is Value + Width, + clamp_value(L0, 0.0, 10.0, Lower), + clamp_value(U0, 0.0, 10.0, Upper). + +phase_code(accumulation, 0.25). +phase_code(promotion, 0.50). +phase_code(distribution, 0.75). +phase_code(collapse, 1.00). + +regime_code(bearish, 0.0). +regime_code(neutral, 0.5). +regime_code(bullish, 1.0). + +sociological_prediction( + sentiment_index, + state(Sentiment,Dispersion,_,_,_,_,_,_,_), + _, + Value,Lower,Upper,Label +) :- !, + Raw is (Sentiment + 1.0) * 5.0, + Width is 0.5 + 4.0*Dispersion, + bounded_ten(Raw, Width, Value, Lower, Upper), + sentiment_label(Sentiment, Label). + +sociological_prediction( + herd_threshold, + state(_,Dispersion,_,Volatility,_,_,_,_,_), + _, + Value,Lower,Upper,herd_activation +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Value), + Width is 0.10 + 0.20*Dispersion, + bounded_unit(Value, Width, Value, Lower, Upper). + +sociological_prediction( + strategy_distribution, + state(_,Dispersion,_,_,_,Shares,_,_,_), + _, + Value,Lower,Upper,Label +) :- !, + dominant_strategy(Shares, Label, Dominant), + Width is 0.05 + 0.20*Dispersion, + bounded_unit(Dominant, Width, Value, Lower, Upper). + +sociological_prediction( + cascade_probability, + state(_,Dispersion,_,Volatility,ExposureRate,_,_,_,_), + _, + Value,Lower,Upper,complex_contagion +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Threshold), + E2 is ExposureRate*ExposureRate, + T2 is Threshold*Threshold, + ( E2 + T2 =< 0.0 -> Raw = 0.0 ; Raw is E2/(E2+T2) ), + Width is 0.05 + 0.25*Dispersion, + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + coordination_stability, + state(_,Dispersion,_,Volatility,_,_,_,MfgStability,_), + _, + Value,Lower,Upper,coordination +) :- !, + Raw is MfgStability * (1.0-Dispersion) * (1.0-0.25*Volatility), + Width is 0.05 + 0.20*Dispersion, + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + opinion_cluster_count, + state(_,Dispersion,_,Volatility,_,_,_,_,Opinions), + _, + Value,Lower,Upper,clusters +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Bound), + opinion_cluster_count(Opinions, Bound, Count), + length(Opinions, N), + Value is float(Count), + L0 is max(1, Count-1), + U0 is min(N, Count+1), + Lower is float(L0), + Upper is float(U0). + +sociological_prediction( + pump_dump_phase, + state(Sentiment,Dispersion,PriceShift,_,ExposureRate,_,_,_,_), + _, + Value,Lower,Upper,Phase +) :- !, + VolumeRatio is 1.0 + 2.0*ExposureRate, + pump_phase(PriceShift, VolumeRatio, Sentiment, Phase), + phase_code(Phase, Raw), + Width is 0.05 + 0.15*Dispersion, + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + mfg_equilibrium_stability, + state(_,Dispersion,_,_,_,_,_,MfgStability,_), + _, + Value,Lower,Upper,mfg +) :- !, + Width is 0.05 + 0.20*Dispersion, + bounded_unit(MfgStability, Width, Value, Lower, Upper). + +sociological_prediction( + narrative_regime, + state(Sentiment,Dispersion,PriceShift,_,_,_,_,_,_), + _, + Value,Lower,Upper,Label +) :- !, + narrative_label(Sentiment, PriceShift, Label), + regime_code(Label, Raw), + Width is 0.05 + 0.20*Dispersion, + bounded_unit(Raw, Width, Value, Lower, Upper). From 7008f4484c7a5a5f60303a27a19e2667c49fbaf1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:55:44 -0700 Subject: [PATCH 128/156] test: require M3b horizon-sensitive bounds --- core/src/economy/sims/sociological/test.ecl | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl index 99ad07c..b42541d 100644 --- a/core/src/economy/sims/sociological/test.ecl +++ b/core/src/economy/sims/sociological/test.ecl @@ -172,4 +172,20 @@ run_tests :- NL =< NV, NV =< NU, NLabel = bullish)), + + must(multi_horizon_uncertainty_widens, + (HState=state( + 0.40,0.15,0.03,0.45,0.50, + [0.45,0.20,0.15,0.15,0.05], + [0.80,0.10,0.10], + 0.85, + [0.35,0.40,0.45,0.50] + ), + sociological_prediction(sentiment_index,HState,hourly,HV,HL,HU,_), + sociological_prediction(sentiment_index,HState,five_year,FV,FL,FU,_), + approx(HV,FV,1.0e-9), + HWidth is HU-HL, + FWidth is FU-FL, + FWidth > HWidth)), + writeln("SOCIOLOGICAL TESTS PASSED"). From 6bcd98194ab44e88a30663a2a49f5bb0eb311626 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:56:35 -0700 Subject: [PATCH 129/156] M3b: scale prediction bounds by horizon --- core/src/economy/sims/sociological/engine.ecl | 64 +++++++++++++------ 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl index ba638bd..e697d8e 100644 --- a/core/src/economy/sims/sociological/engine.ecl +++ b/core/src/economy/sims/sociological/engine.ecl @@ -325,6 +325,19 @@ bounded_ten(Value0, Width0, Value, Lower, Upper) :- clamp_value(L0, 0.0, 10.0, Lower), clamp_value(U0, 0.0, 10.0, Upper). +horizon_scale(current, 0.50). +horizon_scale(hourly, 0.65). +horizon_scale(tick_hourly, 0.65). +horizon_scale(daily, 0.80). +horizon_scale(weekly, 1.00). +horizon_scale(monthly, 1.20). +horizon_scale(annual, 1.50). +horizon_scale(five_year, 1.80). + +horizon_width(Horizon, BaseWidth, Width) :- + horizon_scale(Horizon, Scale), + Width is BaseWidth * Scale. + phase_code(accumulation, 0.25). phase_code(promotion, 0.50). phase_code(distribution, 0.75). @@ -337,100 +350,109 @@ regime_code(bullish, 1.0). sociological_prediction( sentiment_index, state(Sentiment,Dispersion,_,_,_,_,_,_,_), - _, + Horizon, Value,Lower,Upper,Label ) :- !, Raw is (Sentiment + 1.0) * 5.0, - Width is 0.5 + 4.0*Dispersion, + BaseWidth is 0.5 + 4.0*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_ten(Raw, Width, Value, Lower, Upper), sentiment_label(Sentiment, Label). sociological_prediction( herd_threshold, state(_,Dispersion,_,Volatility,_,_,_,_,_), - _, + Horizon, Value,Lower,Upper,herd_activation ) :- !, adaptive_confidence_bound(0.35, Volatility, Dispersion, Value), - Width is 0.10 + 0.20*Dispersion, + BaseWidth is 0.10 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Value, Width, Value, Lower, Upper). sociological_prediction( strategy_distribution, state(_,Dispersion,_,_,_,Shares,_,_,_), - _, + Horizon, Value,Lower,Upper,Label ) :- !, dominant_strategy(Shares, Label, Dominant), - Width is 0.05 + 0.20*Dispersion, + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Dominant, Width, Value, Lower, Upper). sociological_prediction( cascade_probability, state(_,Dispersion,_,Volatility,ExposureRate,_,_,_,_), - _, + Horizon, Value,Lower,Upper,complex_contagion ) :- !, adaptive_confidence_bound(0.35, Volatility, Dispersion, Threshold), E2 is ExposureRate*ExposureRate, T2 is Threshold*Threshold, ( E2 + T2 =< 0.0 -> Raw = 0.0 ; Raw is E2/(E2+T2) ), - Width is 0.05 + 0.25*Dispersion, + BaseWidth is 0.05 + 0.25*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Raw, Width, Value, Lower, Upper). sociological_prediction( coordination_stability, state(_,Dispersion,_,Volatility,_,_,_,MfgStability,_), - _, + Horizon, Value,Lower,Upper,coordination ) :- !, Raw is MfgStability * (1.0-Dispersion) * (1.0-0.25*Volatility), - Width is 0.05 + 0.20*Dispersion, + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Raw, Width, Value, Lower, Upper). sociological_prediction( opinion_cluster_count, state(_,Dispersion,_,Volatility,_,_,_,_,Opinions), - _, + Horizon, Value,Lower,Upper,clusters ) :- !, adaptive_confidence_bound(0.35, Volatility, Dispersion, Bound), opinion_cluster_count(Opinions, Bound, Count), length(Opinions, N), Value is float(Count), - L0 is max(1, Count-1), - U0 is min(N, Count+1), - Lower is float(L0), - Upper is float(U0). + horizon_scale(Horizon, Scale), + L0 is max(1.0, Value-Scale), + U0 is min(float(N), Value+Scale), + Lower = L0, + Upper = U0. sociological_prediction( pump_dump_phase, state(Sentiment,Dispersion,PriceShift,_,ExposureRate,_,_,_,_), - _, + Horizon, Value,Lower,Upper,Phase ) :- !, VolumeRatio is 1.0 + 2.0*ExposureRate, pump_phase(PriceShift, VolumeRatio, Sentiment, Phase), phase_code(Phase, Raw), - Width is 0.05 + 0.15*Dispersion, + BaseWidth is 0.05 + 0.15*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Raw, Width, Value, Lower, Upper). sociological_prediction( mfg_equilibrium_stability, state(_,Dispersion,_,_,_,_,_,MfgStability,_), - _, + Horizon, Value,Lower,Upper,mfg ) :- !, - Width is 0.05 + 0.20*Dispersion, + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(MfgStability, Width, Value, Lower, Upper). sociological_prediction( narrative_regime, state(Sentiment,Dispersion,PriceShift,_,_,_,_,_,_), - _, + Horizon, Value,Lower,Upper,Label ) :- !, narrative_label(Sentiment, PriceShift, Label), regime_code(Label, Raw), - Width is 0.05 + 0.20*Dispersion, + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), bounded_unit(Raw, Width, Value, Lower, Upper). From 0cc5a468e2f440cc1f1b4cf058e8bb84d1570116 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:57:14 -0700 Subject: [PATCH 130/156] test: specify M2 to M3b hub integration --- .../sims/sociological/integration.test | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core/src/economy/sims/sociological/integration.test diff --git a/core/src/economy/sims/sociological/integration.test b/core/src/economy/sims/sociological/integration.test new file mode 100644 index 0000000..9fa4b56 --- /dev/null +++ b/core/src/economy/sims/sociological/integration.test @@ -0,0 +1,60 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +proc seed_m3b {s ticker} { + for {set i 0} {$i < 30} {incr i} { + set price [expr {100.0 * exp(0.0030*$i + 0.004*sin($i/4.0))}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.4 + } + + set sources {reddit social blog reddit social blog reddit social blog reddit social blog} + set i 0 + foreach source_type $sources { + set sentiment [expr {0.68 + 0.04*sin($i)}] + set engagement [expr {0.78 + 0.05*cos($i)}] + $s feed_publish rss_news $source_type [expr {$i*7200}] [dict create token_ticker $ticker source_type $source_type sentiment $sentiment engagement $engagement] 8.0 + incr i + } +} + +test m3b-runner-available-1.0 {ECLiPSe-backed sociological runner is available in M3b CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s sociological_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3b-to-hub-1.0 {social aggregate and price feeds publish a bounded sentiment state} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-social sociological + seed_m3b $s TEST + set p [$s sociological_from_feed TEST sentiment_index daily] + set q [$s query_predictions trader-social sociological] + set out [list [dict get $p sim_type] [dict get $p prediction_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $p time_horizon] [dict get $p calibration_sources]] + $s destroy + set out +} -result {sociological sentiment_index 1 1 TEST 24h rss_news,price_tick} + +test m3b-pump-phase-label-1.0 {aggregate promotion signature carries categorical phase label} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b $s PUMP + set p [$s sociological_from_feed PUMP pump_dump_phase daily] + set out [list [dict get $p prediction_type] [dict get $p label] [expr {[dict get $p lower_bound] <= [dict get $p value] && [dict get $p value] <= [dict get $p upper_bound]}]] + $s destroy + set out +} -result {pump_dump_phase promotion 1} + +test m3b-insufficient-social-history-1.0 {M3b refuses calibration without aggregate social evidence} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 20} {incr i} { + $s feed_publish price_tick exchange $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s sociological_from_feed TEST sentiment_index daily} msg] + $s destroy + list $code $msg +} -result {1 insufficient_social_history} + +cleanupTests From 2b18bdc580d87054ea1fd9545ba7746f70ca46b9 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 19:57:25 -0700 Subject: [PATCH 131/156] ci: exercise M2 to M3b hub integration --- .github/workflows/m3b-sociological.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/m3b-sociological.yml b/.github/workflows/m3b-sociological.yml index 87f661a..fd6c189 100644 --- a/.github/workflows/m3b-sociological.yml +++ b/.github/workflows/m3b-sociological.yml @@ -39,3 +39,10 @@ jobs: - name: Run M3b native tests working-directory: core/src/economy/sims/sociological run: eclipse -b test.ecl -e run_tests + + - name: Run M2 → M3b → Hub integration + shell: bash + run: | + set -euo pipefail + tclsh core/src/economy/sims/sociological/integration.test | tee /tmp/m3b-integration.out + grep -Eq 'Total[[:space:]]+4[[:space:]]+Passed[[:space:]]+4.*Failed[[:space:]]+0' /tmp/m3b-integration.out From c2547c33a029c5348bbf9bd9b208c21b8c8146f1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:34:48 -0700 Subject: [PATCH 132/156] M3c: implement LP, JIT, backrun and sandwich mechanics --- core/src/economy/sims/amm/src/AMMSim.sol | 211 +++++++++++++++++++++++ 1 file changed, 211 insertions(+) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index 806c1b4..799b3c9 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -11,6 +11,21 @@ library AMMSim { uint256 feeBps; } + struct ArbitrageResult { + bool zeroForOne; + uint256 amountIn; + uint256 amountOut; + uint256 profitQuote; + uint256 postPriceWad; + } + + struct SandwichResult { + uint256 frontOut; + uint256 victimOut; + uint256 backOut; + uint256 profitToken0; + } + struct ArbitrageResult { bool zeroForOne; uint256 amountIn; @@ -95,6 +110,45 @@ library AMMSim { } + function lpShouldRebalance( + uint256 feeIncomeWad, + uint256 rebalanceCostWad, + uint256 ratioWad + ) internal pure returns (bool) { + int256 il = impermanentLossWad(ratioWad); + uint256 loss = il < 0 ? uint256(-il) : 0; + return loss > feeIncomeWad + rebalanceCostWad; + } + + function jitFeeIncomeWad( + uint256 tradeAmount, + uint256 feeBps, + uint256 jitLiquidity, + uint256 totalLiquidity + ) internal pure returns (uint256) { + require(feeBps < BPS, "bad fee"); + require(totalLiquidity > 0, "no liquidity"); + require(jitLiquidity <= totalLiquidity, "jit share"); + uint256 totalFee = tradeAmount * feeBps / BPS; + return totalFee * jitLiquidity / totalLiquidity; + } + + function jitShouldProvide( + uint256 tradeAmount, + uint256 feeBps, + uint256 jitLiquidity, + uint256 totalLiquidity, + uint256 placementCost + ) internal pure returns (bool) { + return jitFeeIncomeWad( + tradeAmount, + feeBps, + jitLiquidity, + totalLiquidity + ) > placementCost; + } + + function lpShouldRebalance( uint256 feeIncomeWad, uint256 rebalanceCostWad, @@ -462,6 +516,163 @@ library AMMSim { ); } + function _spotPriceWad(uint256 x, uint256 y) + private pure returns (uint256) + { + require(x > 0 && y > 0, "bad reserves"); + return y * WAD / x; + } + + function _arbCandidate( + uint256 x, + uint256 y, + uint256 amountIn, + uint256 externalPriceWad, + uint256 feeBps, + bool zeroForOne + ) private pure returns (ArbitrageResult memory r) { + r.zeroForOne = zeroForOne; + r.amountIn = amountIn; + + if (amountIn == 0) { + r.postPriceWad = _spotPriceWad(x, y); + return r; + } + + if (zeroForOne) { + r.amountOut = amountOut(x, y, amountIn, feeBps); + uint256 postX = x + amountIn; + uint256 postY = y - r.amountOut; + r.postPriceWad = _spotPriceWad(postX, postY); + uint256 externalCost = amountIn * externalPriceWad / WAD; + if (r.amountOut > externalCost) { + r.profitQuote = r.amountOut - externalCost; + } + } else { + r.amountOut = amountOut(y, x, amountIn, feeBps); + uint256 postY = y + amountIn; + uint256 postX = x - r.amountOut; + r.postPriceWad = _spotPriceWad(postX, postY); + uint256 externalValue = r.amountOut * externalPriceWad / WAD; + if (externalValue > amountIn) { + r.profitQuote = externalValue - amountIn; + } + } + } + + function _priceError(uint256 a, uint256 b) + private pure returns (uint256) + { + return a > b ? a - b : b - a; + } + + function backrunToPrice( + uint256 x, + uint256 y, + uint256 externalPriceWad, + uint256 feeBps + ) internal pure returns (ArbitrageResult memory best) { + require( + x > 0 && y > 0 && + externalPriceWad > 0 && + feeBps < BPS, + "bad arb" + ); + + uint256 current = _spotPriceWad(x, y); + if (current == externalPriceWad) { + best.postPriceWad = current; + return best; + } + + bool zeroForOne = current > externalPriceWad; + uint256 base = zeroForOne ? x : y; + uint256 lo = 0; + uint256 hi = base; + + // Expand until the post-trade price crosses the reference price. + for (uint256 i = 0; i < 24; ++i) { + ArbitrageResult memory probe = _arbCandidate( + x, y, hi, externalPriceWad, feeBps, zeroForOne + ); + bool crossed = zeroForOne + ? probe.postPriceWad <= externalPriceWad + : probe.postPriceWad >= externalPriceWad; + if (crossed) break; + require(hi <= type(uint256).max / 2, "arb overflow"); + hi *= 2; + } + + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + ArbitrageResult memory probe = _arbCandidate( + x, y, mid, externalPriceWad, feeBps, zeroForOne + ); + if (zeroForOne) { + if (probe.postPriceWad > externalPriceWad) { + lo = mid + 1; + } else { + hi = mid; + } + } else { + if (probe.postPriceWad < externalPriceWad) { + lo = mid + 1; + } else { + hi = mid; + } + } + } + + best = _arbCandidate( + x, y, lo, externalPriceWad, feeBps, zeroForOne + ); + if (lo > 0) { + ArbitrageResult memory alt = _arbCandidate( + x, y, lo - 1, externalPriceWad, feeBps, zeroForOne + ); + if ( + _priceError(alt.postPriceWad, externalPriceWad) < + _priceError(best.postPriceWad, externalPriceWad) + ) { + best = alt; + } + } + } + + function simulateSandwich( + uint256 x, + uint256 y, + uint256 victimDx, + uint256 attackerFrontDx, + uint256 feeBps + ) internal pure returns (SandwichResult memory s) { + require( + x > 0 && y > 0 && + victimDx > 0 && attackerFrontDx > 0 && + feeBps < BPS, + "bad sandwich" + ); + + s.frontOut = amountOut( + x, y, attackerFrontDx, feeBps + ); + x += attackerFrontDx; + y -= s.frontOut; + + s.victimOut = amountOut( + x, y, victimDx, feeBps + ); + x += victimDx; + y -= s.victimOut; + + s.backOut = amountOut( + y, x, s.frontOut, feeBps + ); + if (s.backOut > attackerFrontDx) { + s.profitToken0 = s.backOut - attackerFrontDx; + } + } + /// @notice Token amounts represented by concentrated liquidity L at a /// current sqrt-price. All sqrt-prices are WAD-scaled. function concentratedAmounts( From 01668db973ff32af7200c9e144fdf625efe871be Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:35:54 -0700 Subject: [PATCH 133/156] M3c: reconcile duplicate resumed adversarial implementation --- core/src/economy/sims/amm/src/AMMSim.sol | 211 ----------------------- 1 file changed, 211 deletions(-) diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol index 799b3c9..806c1b4 100644 --- a/core/src/economy/sims/amm/src/AMMSim.sol +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -11,21 +11,6 @@ library AMMSim { uint256 feeBps; } - struct ArbitrageResult { - bool zeroForOne; - uint256 amountIn; - uint256 amountOut; - uint256 profitQuote; - uint256 postPriceWad; - } - - struct SandwichResult { - uint256 frontOut; - uint256 victimOut; - uint256 backOut; - uint256 profitToken0; - } - struct ArbitrageResult { bool zeroForOne; uint256 amountIn; @@ -110,45 +95,6 @@ library AMMSim { } - function lpShouldRebalance( - uint256 feeIncomeWad, - uint256 rebalanceCostWad, - uint256 ratioWad - ) internal pure returns (bool) { - int256 il = impermanentLossWad(ratioWad); - uint256 loss = il < 0 ? uint256(-il) : 0; - return loss > feeIncomeWad + rebalanceCostWad; - } - - function jitFeeIncomeWad( - uint256 tradeAmount, - uint256 feeBps, - uint256 jitLiquidity, - uint256 totalLiquidity - ) internal pure returns (uint256) { - require(feeBps < BPS, "bad fee"); - require(totalLiquidity > 0, "no liquidity"); - require(jitLiquidity <= totalLiquidity, "jit share"); - uint256 totalFee = tradeAmount * feeBps / BPS; - return totalFee * jitLiquidity / totalLiquidity; - } - - function jitShouldProvide( - uint256 tradeAmount, - uint256 feeBps, - uint256 jitLiquidity, - uint256 totalLiquidity, - uint256 placementCost - ) internal pure returns (bool) { - return jitFeeIncomeWad( - tradeAmount, - feeBps, - jitLiquidity, - totalLiquidity - ) > placementCost; - } - - function lpShouldRebalance( uint256 feeIncomeWad, uint256 rebalanceCostWad, @@ -516,163 +462,6 @@ library AMMSim { ); } - function _spotPriceWad(uint256 x, uint256 y) - private pure returns (uint256) - { - require(x > 0 && y > 0, "bad reserves"); - return y * WAD / x; - } - - function _arbCandidate( - uint256 x, - uint256 y, - uint256 amountIn, - uint256 externalPriceWad, - uint256 feeBps, - bool zeroForOne - ) private pure returns (ArbitrageResult memory r) { - r.zeroForOne = zeroForOne; - r.amountIn = amountIn; - - if (amountIn == 0) { - r.postPriceWad = _spotPriceWad(x, y); - return r; - } - - if (zeroForOne) { - r.amountOut = amountOut(x, y, amountIn, feeBps); - uint256 postX = x + amountIn; - uint256 postY = y - r.amountOut; - r.postPriceWad = _spotPriceWad(postX, postY); - uint256 externalCost = amountIn * externalPriceWad / WAD; - if (r.amountOut > externalCost) { - r.profitQuote = r.amountOut - externalCost; - } - } else { - r.amountOut = amountOut(y, x, amountIn, feeBps); - uint256 postY = y + amountIn; - uint256 postX = x - r.amountOut; - r.postPriceWad = _spotPriceWad(postX, postY); - uint256 externalValue = r.amountOut * externalPriceWad / WAD; - if (externalValue > amountIn) { - r.profitQuote = externalValue - amountIn; - } - } - } - - function _priceError(uint256 a, uint256 b) - private pure returns (uint256) - { - return a > b ? a - b : b - a; - } - - function backrunToPrice( - uint256 x, - uint256 y, - uint256 externalPriceWad, - uint256 feeBps - ) internal pure returns (ArbitrageResult memory best) { - require( - x > 0 && y > 0 && - externalPriceWad > 0 && - feeBps < BPS, - "bad arb" - ); - - uint256 current = _spotPriceWad(x, y); - if (current == externalPriceWad) { - best.postPriceWad = current; - return best; - } - - bool zeroForOne = current > externalPriceWad; - uint256 base = zeroForOne ? x : y; - uint256 lo = 0; - uint256 hi = base; - - // Expand until the post-trade price crosses the reference price. - for (uint256 i = 0; i < 24; ++i) { - ArbitrageResult memory probe = _arbCandidate( - x, y, hi, externalPriceWad, feeBps, zeroForOne - ); - bool crossed = zeroForOne - ? probe.postPriceWad <= externalPriceWad - : probe.postPriceWad >= externalPriceWad; - if (crossed) break; - require(hi <= type(uint256).max / 2, "arb overflow"); - hi *= 2; - } - - for (uint256 i = 0; i < 64 && lo < hi; ++i) { - uint256 mid = lo + (hi - lo) / 2; - ArbitrageResult memory probe = _arbCandidate( - x, y, mid, externalPriceWad, feeBps, zeroForOne - ); - if (zeroForOne) { - if (probe.postPriceWad > externalPriceWad) { - lo = mid + 1; - } else { - hi = mid; - } - } else { - if (probe.postPriceWad < externalPriceWad) { - lo = mid + 1; - } else { - hi = mid; - } - } - } - - best = _arbCandidate( - x, y, lo, externalPriceWad, feeBps, zeroForOne - ); - if (lo > 0) { - ArbitrageResult memory alt = _arbCandidate( - x, y, lo - 1, externalPriceWad, feeBps, zeroForOne - ); - if ( - _priceError(alt.postPriceWad, externalPriceWad) < - _priceError(best.postPriceWad, externalPriceWad) - ) { - best = alt; - } - } - } - - function simulateSandwich( - uint256 x, - uint256 y, - uint256 victimDx, - uint256 attackerFrontDx, - uint256 feeBps - ) internal pure returns (SandwichResult memory s) { - require( - x > 0 && y > 0 && - victimDx > 0 && attackerFrontDx > 0 && - feeBps < BPS, - "bad sandwich" - ); - - s.frontOut = amountOut( - x, y, attackerFrontDx, feeBps - ); - x += attackerFrontDx; - y -= s.frontOut; - - s.victimOut = amountOut( - x, y, victimDx, feeBps - ); - x += victimDx; - y -= s.victimOut; - - s.backOut = amountOut( - y, x, s.frontOut, feeBps - ); - if (s.backOut > attackerFrontDx) { - s.profitToken0 = s.backOut - attackerFrontDx; - } - } - /// @notice Token amounts represented by concentrated liquidity L at a /// current sqrt-price. All sqrt-prices are WAD-scaled. function concentratedAmounts( From d3b7762e41f871f79733f6908f249577981f492c Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:38:37 -0700 Subject: [PATCH 134/156] M3b: add ECLiPSe sociological runner --- core/src/economy/sims/sociological/runner.tcl | 261 ++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 core/src/economy/sims/sociological/runner.tcl diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl new file mode 100644 index 0000000..c195008 --- /dev/null +++ b/core/src/economy/sims/sociological/runner.tcl @@ -0,0 +1,261 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SociologicalRunner { + variable engine runtime + + constructor {engine_path {runtime_cmd eclipse}} { + set engine [file normalize $engine_path] + set runtime $runtime_cmd + } + + method available {} { + expr {[file exists $engine] && [auto_execok $runtime] ne ""} + } + + method _clamp {x lo hi} { + if {$x < $lo} { return $lo } + if {$x > $hi} { return $hi } + return $x + } + + method _fmt {x} { + if {![string is double -strict $x]} { error "invalid_numeric_state" } + format %.17g [expr {double($x)}] + } + + method _list_fmt {xs} { + set out {} + foreach x $xs { lappend out [my _fmt $x] } + return "[[join $out ,]]" + } + + method _prediction_type {name} { + set allowed { + sentiment_index herd_threshold strategy_distribution + cascade_probability coordination_stability opinion_cluster_count + pump_dump_phase mfg_equilibrium_stability narrative_regime + } + if {[lsearch -exact $allowed $name] < 0} { error "unknown_prediction_type" } + return $name + } + + method _horizon {name} { + switch -- $name { + current { return [list current current] } + tick_hourly - + hourly { return [list hourly 1h] } + daily { return [list daily 24h] } + weekly { return [list weekly 7d] } + monthly { return [list monthly 30d] } + annual { return [list annual 1y] } + five_year { return [list five_year 5y] } + default { error "unknown_horizon" } + } + } + + method _filter_prices {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set p [dict get $datum payload] + if {[catch {dict get $p token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $p price} price] || + ![string is double -strict $price] || $price <= 0} { continue } + lappend out [dict create price [expr {double($price)}] timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _filter_social {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set p [dict get $datum payload] + if {[catch {dict get $p token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $p sentiment} sentiment] || + ![string is double -strict $sentiment]} { continue } + set engagement 0.5 + if {[dict exists $p engagement] && + [string is double -strict [dict get $p engagement]]} { + set engagement [dict get $p engagement] + } + set source_type unknown + if {[dict exists $p source_type]} { set source_type [dict get $p source_type] } + lappend out [dict create sentiment [my _clamp [expr {double($sentiment)}] -1.0 1.0] engagement [my _clamp [expr {double($engagement)}] 0.0 1.0] source_type $source_type timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _weighted_social {social} { + set sumw 0.0 + set sums 0.0 + set sume 0.0 + foreach d $social { + set c [my _clamp [expr {double([dict get $d confidence])}] 0.0 10.0] + set e [dict get $d engagement] + set w [expr {max(0.05,$e) * max(0.1,$c/10.0)}] + set s [dict get $d sentiment] + set sumw [expr {$sumw+$w}] + set sums [expr {$sums+$w*$s}] + set sume [expr {$sume+$w*$e}] + } + if {$sumw <= 0} { error "invalid_social_weights" } + set mean [expr {$sums/$sumw}] + set exposure [expr {$sume/$sumw}] + set var 0.0 + foreach d $social { + set c [my _clamp [expr {double([dict get $d confidence])}] 0.0 10.0] + set e [dict get $d engagement] + set w [expr {max(0.05,$e) * max(0.1,$c/10.0)}] + set delta [expr {[dict get $d sentiment]-$mean}] + set var [expr {$var+$w*$delta*$delta}] + } + set dispersion [expr {sqrt($var/$sumw)}] + return [list [my _clamp $mean -1.0 1.0] [my _clamp $dispersion 0.0 1.0] [my _clamp $exposure 0.0 1.0]] + } + + method _price_stats {prices} { + set first [dict get [lindex $prices 0] price] + set last [dict get [lindex $prices end] price] + set shift [expr {$last/$first-1.0}] + set returns {} + set spacings {} + for {set i 1} {$i < [llength $prices]} {incr i} { + set a [lindex $prices [expr {$i-1}]] + set b [lindex $prices $i] + set pa [dict get $a price] + set pb [dict get $b price] + lappend returns [expr {log($pb/$pa)}] + set ta [dict get $a timestamp] + set tb [dict get $b timestamp] + if {[string is double -strict $ta] && + [string is double -strict $tb] && $tb > $ta} { + lappend spacings [expr {double($tb)-double($ta)}] + } + } + set vol 0.0 + if {[llength $returns] >= 2} { + set total 0.0 + foreach x $returns { set total [expr {$total+$x}] } + set mean [expr {$total/double([llength $returns])}] + set ss 0.0 + foreach x $returns { set ss [expr {$ss+($x-$mean)*($x-$mean)}] } + set sd [expr {sqrt($ss/double([llength $returns]-1))}] + set dt 86400.0 + if {[llength $spacings]} { + set sumdt 0.0 + foreach x $spacings { set sumdt [expr {$sumdt+$x}] } + set dt [expr {$sumdt/double([llength $spacings])}] + } + if {$dt <= 0} { set dt 86400.0 } + set vol [expr {$sd*sqrt(31536000.0/$dt)}] + } + return [list [my _clamp $shift -1.0 1.0] [my _clamp $vol 0.0001 1.0]] + } + + method _normalize {weights} { + set total 0.0 + foreach w $weights { set total [expr {$total+max(0.0,$w)}] } + if {$total <= 0} { error "invalid_population_weights" } + set out {} + foreach w $weights { lappend out [expr {max(0.0,$w)/$total}] } + return $out + } + + method _shares {sentiment volatility exposure} { + set a [expr {abs($sentiment)}] + set pos [expr {max(0.0,$sentiment)}] + return [my _normalize [list [expr {0.20+0.30*$a+0.15*$exposure}] [expr {0.15+0.25*(1.0-$a)}] [expr {0.10+0.25*$volatility}] [expr {0.25+0.25*(1.0-$volatility)}] [expr {0.05+0.25*$pos*$exposure}]]] + } + + method _pump_shares {sentiment exposure} { + set manip [expr {0.10+0.25*max(0.0,$sentiment)*$exposure}] + set analyst [expr {0.15+0.10*$exposure}] + set normal [expr {max(0.10,1.0-$analyst-$manip)}] + return [my _normalize [list $normal $analyst $manip]] + } + + method _mean_confidence {items} { + if {![llength $items]} { return 0.0 } + set total 0.0 + foreach d $items { set total [expr {$total+double([dict get $d confidence])}] } + my _clamp [expr {$total/double([llength $items])}] 0.0 10.0 + } + + method _mfg_stability {shares} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set density [my _list_fmt $shares] + set goal [format { + mfg_equilibrium(500,%s,0.12,0.08,0.35,60,_,_,S,_), + printf("MFG %%w%%n",[S]) + } $density] + set output [exec $runtime -b $engine -e $goal] + if {![regexp {MFG[[:space:]]+([-+0-9.eE]+)} $output -> value] || + ![string is double -strict $value]} { + error "invalid_mfg_output" + } + return [my _clamp [expr {double($value)}] 0.0 1.0] + } + + method _prediction {prediction_type state horizon_atom} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set type [my _prediction_type $prediction_type] + set goal [format { + sociological_prediction(%s,%s,%s,V,L,U,Label), + printf("RESULT %%w %%w %%w %%w%%n",[V,L,U,Label]) + } $type $state $horizon_atom] + set output [exec $runtime -b $engine -e $goal] + if {![regexp {RESULT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([^[:space:]]+)} $output -> value lower upper label]} { + error "invalid_sociological_output" + } + foreach x [list $value $lower $upper] { + if {![string is double -strict $x]} { error "invalid_sociological_output" } + } + return [dict create value [expr {double($value)}] lower [expr {double($lower)}] upper [expr {double($upper)}] label $label] + } + + method query_history {ticker prediction_type horizon price_history social_history} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set prices [my _filter_prices $price_history $ticker] + set social [my _filter_social $social_history $ticker] + if {[llength $social] < 3} { error "insufficient_social_history" } + if {[llength $prices] < 3} { error "insufficient_price_history" } + + lassign [my _horizon $horizon] horizon_atom horizon_label + lassign [my _weighted_social $social] sentiment dispersion exposure + lassign [my _price_stats $prices] price_shift volatility + set shares [my _shares $sentiment $volatility $exposure] + set pump_shares [my _pump_shares $sentiment $exposure] + set stability [my _mfg_stability $shares] + + set opinions {} + foreach d $social { + lappend opinions [my _clamp [expr {([dict get $d sentiment]+1.0)/2.0}] 0.0 1.0] + } + set state [format {state(%s,%s,%s,%s,%s,%s,%s,%s,%s)} [my _fmt $sentiment] [my _fmt $dispersion] [my _fmt $price_shift] [my _fmt $volatility] [my _fmt $exposure] [my _list_fmt $shares] [my _list_fmt $pump_shares] [my _fmt $stability] [my _list_fmt $opinions]] + + set native [my _prediction $prediction_type $state $horizon_atom] + set value [dict get $native value] + set lower [dict get $native lower] + set upper [dict get $native upper] + if {$lower > $value || $value > $upper} { + error "sociological_prediction_out_of_bounds" + } + + set social_conf [my _mean_confidence $social] + set price_conf [my _mean_confidence $prices] + set confidence [my _clamp [expr {0.65*$social_conf+0.35*$price_conf}] 0.0 10.0] + set width [expr {abs($upper-$lower)}] + set scale [expr {max(abs($value),1.0)}] + set certainty [my _clamp [expr {$confidence/(1.0+$width/$scale)}] 0.0 10.0] + + # V1 boundary correctness is evidence coverage rather than a trained + # classifier score: reward agreement of independent social sources. + array set source_seen {} + foreach d $social { set source_seen([dict get $d source_type]) 1 } + set source_count [array size source_seen] + set correctness [my _clamp [expr {4.0+1.5*min($source_count,4)}] 0.0 10.0] + + return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type sociological token_ticker $ticker recent_shift $price_shift prediction_type $prediction_type label [dict get $native label] calibration_sources rss_news,price_tick timestamp [clock seconds]] + } +} From 9945824f4a1da487505e8499cb0db292ad8e94db Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:38:47 -0700 Subject: [PATCH 135/156] M3b: wire sociological runner through stomach --- core/src/economy/stomach.tcl | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl index 6e02811..41d1962 100644 --- a/core/src/economy/stomach.tcl +++ b/core/src/economy/stomach.tcl @@ -7,14 +7,15 @@ set ::stomach::root $__stomach_dir foreach __stomach_file { traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl sims/registry.tcl sims/scheduler.tcl sims/hub.tcl - sims/statistical/runner.tcl sims/amm/runner.tcl marketplace.tcl + sims/statistical/runner.tcl sims/amm/runner.tcl + sims/sociological/runner.tcl marketplace.tcl } { source [file join $__stomach_dir $__stomach_file] } unset __stomach_file oo::class create ::stomach::Economy { - variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner market taxes + variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner sociological_runner market taxes constructor {args} { set cap 256 if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } @@ -35,11 +36,12 @@ oo::class create ::stomach::Economy { $clock start set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]] set amm_runner [::stomach::AMMRunner new] + set sociological_runner [::stomach::SociologicalRunner new [file join $::stomach::root sims sociological engine.ecl]] set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] set taxes {} } destructor { - foreach obj [list $market $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { + foreach obj [list $market $sociological_runner $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { catch {$obj destroy} } } @@ -61,6 +63,12 @@ oo::class create ::stomach::Economy { method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } method statistical_runner_available {} { return [$statistical_runner available] } method amm_runner_available {} { return [$amm_runner available] } + method sociological_runner_available {} { return [$sociological_runner available] } + method sociological_from_feed {ticker prediction_type horizon} { + set p [$sociological_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history rss_news]] + $sims publish sociological $p + return $p + } method amm_from_feed {ticker prediction_type horizon} { set p [$amm_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history dex_pool_state]] $sims publish amm_liquidity $p From c9ad85e7846ae01ae5a774b21a89f3dfc459b655 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:39:33 -0700 Subject: [PATCH 136/156] M3b: fix Prolog list serialization --- core/src/economy/sims/sociological/runner.tcl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl index c195008..e4e6f84 100644 --- a/core/src/economy/sims/sociological/runner.tcl +++ b/core/src/economy/sims/sociological/runner.tcl @@ -26,7 +26,7 @@ oo::class create ::stomach::SociologicalRunner { method _list_fmt {xs} { set out {} foreach x $xs { lappend out [my _fmt $x] } - return "[[join $out ,]]" + return [format {[%s]} [join $out ,]] } method _prediction_type {name} { From 95c385ad19b5fb376795f12e655a2fd0fa66637e Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:40:31 -0700 Subject: [PATCH 137/156] test: require live M3b bandit population evolution --- .../economy/sims/sociological/integration.test | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/src/economy/sims/sociological/integration.test b/core/src/economy/sims/sociological/integration.test index 9fa4b56..922dc73 100644 --- a/core/src/economy/sims/sociological/integration.test +++ b/core/src/economy/sims/sociological/integration.test @@ -57,4 +57,21 @@ test m3b-insufficient-social-history-1.0 {M3b refuses calibration without aggreg list $code $msg } -result {1 insufficient_social_history} +test m3b-bandit-population-evolves-1.0 {live population state evolves through bandit-replicator learning} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b $s EVOLVE + set first [$s sociological_from_feed EVOLVE strategy_distribution daily] + + for {set i 30} {$i < 42} {incr i} { + set price [expr {110.0 * exp(0.008*($i-30))}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker EVOLVE price $price] 9.5 + $s feed_publish rss_news social [expr {$i*3600}] [dict create token_ticker EVOLVE source_type social sentiment 0.95 engagement 0.98] 9.2 + } + + set second [$s sociological_from_feed EVOLVE strategy_distribution daily] + set out [list [dict get $first population_model] [dict get $first population_epoch] [dict get $second population_epoch] [expr {[dict get $first population_shares] ne [dict get $second population_shares]}]] + $s destroy + set out +} -result {bandit_replicator 1 2 1} + cleanupTests From 696ef1dc12b1f735e6e86839bf6b6eee89d594a0 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:41:19 -0700 Subject: [PATCH 138/156] M3b: evolve live populations with native bandit replicator --- core/src/economy/sims/sociological/runner.tcl | 52 +++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl index e4e6f84..1b92241 100644 --- a/core/src/economy/sims/sociological/runner.tcl +++ b/core/src/economy/sims/sociological/runner.tcl @@ -1,11 +1,13 @@ namespace eval ::stomach {} oo::class create ::stomach::SociologicalRunner { - variable engine runtime + variable engine runtime populations epochs constructor {engine_path {runtime_cmd eclipse}} { set engine [file normalize $engine_path] set runtime $runtime_cmd + set populations {} + set epochs {} } method available {} { @@ -182,6 +184,49 @@ oo::class create ::stomach::SociologicalRunner { my _clamp [expr {$total/double([llength $items])}] 0.0 10.0 } + method _bandit_update { + ticker initial_shares sentiment price_shift volatility exposure evidence_count + } { + if {![my available]} { error "eclipse_runtime_unavailable" } + + if {[dict exists $populations $ticker]} { + set shares [dict get $populations $ticker] + } else { + set shares $initial_shares + } + + set n [expr {max(1,int($evidence_count))}] + set positive [expr {max(0.0,$sentiment)}] + set aligned [expr {max(0.0,$sentiment*$price_shift)}] + set payoffs [list [expr {0.75+1.20*$aligned+0.35*$exposure}] [expr {0.80+0.60*abs($sentiment-$price_shift)}] [expr {0.70+1.40*$volatility}] [expr {1.15-0.65*$volatility}] [expr {0.45+1.60*$positive*$exposure+0.80*max(0.0,$price_shift)}]] + set reward_sums {} + foreach payoff $payoffs { + lappend reward_sums [expr {$payoff*$n}] + } + set counts [lrepeat 5 $n] + set total [expr {5*$n}] + + set goal [format { + bandit_replicator_step(%s,%s,%s,%d,0.6,0.25,[A,B,C,D,E],_), + printf("BANDIT %%w %%w %%w %%w %%w%%n",[A,B,C,D,E]) + } [my _list_fmt $shares] [my _list_fmt $reward_sums] [my _list_fmt $counts] $total] + set output [exec $runtime -b $engine -e $goal] + if {![regexp { + BANDIT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+) + } $output -> a b cc d e]} { + error "invalid_bandit_output" + } + set next [my _normalize [list [expr {double($a)}] [expr {double($b)}] [expr {double($cc)}] [expr {double($d)}] [expr {double($e)}]]] + dict set populations $ticker $next + + set epoch 1 + if {[dict exists $epochs $ticker]} { + set epoch [expr {[dict get $epochs $ticker]+1}] + } + dict set epochs $ticker $epoch + return [list $next $epoch] + } + method _mfg_stability {shares} { if {![my available]} { error "eclipse_runtime_unavailable" } set density [my _list_fmt $shares] @@ -224,7 +269,8 @@ oo::class create ::stomach::SociologicalRunner { lassign [my _horizon $horizon] horizon_atom horizon_label lassign [my _weighted_social $social] sentiment dispersion exposure lassign [my _price_stats $prices] price_shift volatility - set shares [my _shares $sentiment $volatility $exposure] + set initial_shares [my _shares $sentiment $volatility $exposure] + lassign [my _bandit_update $ticker $initial_shares $sentiment $price_shift $volatility $exposure [llength $social]] shares population_epoch set pump_shares [my _pump_shares $sentiment $exposure] set stability [my _mfg_stability $shares] @@ -256,6 +302,6 @@ oo::class create ::stomach::SociologicalRunner { set source_count [array size source_seen] set correctness [my _clamp [expr {4.0+1.5*min($source_count,4)}] 0.0 10.0] - return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type sociological token_ticker $ticker recent_shift $price_shift prediction_type $prediction_type label [dict get $native label] calibration_sources rss_news,price_tick timestamp [clock seconds]] + return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type sociological token_ticker $ticker recent_shift $price_shift prediction_type $prediction_type label [dict get $native label] calibration_sources rss_news,price_tick population_model bandit_replicator population_epoch $population_epoch population_shares [join $shares ,] timestamp [clock seconds]] } } From bf3c12506536bdb2dd7af9706a29dc3cc75dc9b8 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:41:26 -0700 Subject: [PATCH 139/156] ci: enforce M3b population evolution boundary --- .github/workflows/m3b-sociological.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/m3b-sociological.yml b/.github/workflows/m3b-sociological.yml index fd6c189..2d8688e 100644 --- a/.github/workflows/m3b-sociological.yml +++ b/.github/workflows/m3b-sociological.yml @@ -45,4 +45,4 @@ jobs: run: | set -euo pipefail tclsh core/src/economy/sims/sociological/integration.test | tee /tmp/m3b-integration.out - grep -Eq 'Total[[:space:]]+4[[:space:]]+Passed[[:space:]]+4.*Failed[[:space:]]+0' /tmp/m3b-integration.out + grep -Eq 'Total[[:space:]]+5[[:space:]]+Passed[[:space:]]+5.*Failed[[:space:]]+0' /tmp/m3b-integration.out From aa5a11abdf83502ba87d5b004601cd683dc02cd0 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:42:01 -0700 Subject: [PATCH 140/156] M3b: parse native bandit output without literal indentation --- core/src/economy/sims/sociological/runner.tcl | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl index 1b92241..e685576 100644 --- a/core/src/economy/sims/sociological/runner.tcl +++ b/core/src/economy/sims/sociological/runner.tcl @@ -211,9 +211,7 @@ oo::class create ::stomach::SociologicalRunner { printf("BANDIT %%w %%w %%w %%w %%w%%n",[A,B,C,D,E]) } [my _list_fmt $shares] [my _list_fmt $reward_sums] [my _list_fmt $counts] $total] set output [exec $runtime -b $engine -e $goal] - if {![regexp { - BANDIT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+) - } $output -> a b cc d e]} { + if {![regexp {BANDIT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)} $output -> a b cc d e]} { error "invalid_bandit_output" } set next [my _normalize [list [expr {double($a)}] [expr {double($b)}] [expr {double($cc)}] [expr {double($d)}] [expr {double($e)}]]] From 2e366c458cbd3999ee715d5e97e8e4b6126200a1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:42:52 -0700 Subject: [PATCH 141/156] test: require empirical M3b walk-forward correctness --- .../sims/sociological/integration.test | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/core/src/economy/sims/sociological/integration.test b/core/src/economy/sims/sociological/integration.test index 922dc73..5b96a7e 100644 --- a/core/src/economy/sims/sociological/integration.test +++ b/core/src/economy/sims/sociological/integration.test @@ -74,4 +74,29 @@ test m3b-bandit-population-evolves-1.0 {live population state evolves through ba set out } -result {bandit_replicator 1 2 1} +proc seed_m3b_accuracy {s ticker direction} { + for {set i 0} {$i < 16} {incr i} { + set sign [expr {$direction eq "up" ? 1.0 : -1.0}] + set price [expr {100.0 * exp($sign*0.008*$i)}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.5 + } + set sources {reddit social blog reddit social blog reddit social blog} + set i 0 + foreach source_type $sources { + $s feed_publish rss_news $source_type [expr {($i+1)*3600-60}] [dict create token_ticker $ticker source_type $source_type sentiment 0.90 engagement 0.85] 9.0 + incr i + } +} + +test m3b-correctness-walk-forward-1.0 {correctness measures whether social direction predicts subsequent price movement} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b_accuracy $s GOOD up + seed_m3b_accuracy $s BAD down + set good [$s sociological_from_feed GOOD sentiment_index daily] + set bad [$s sociological_from_feed BAD sentiment_index daily] + set out [list [expr {[dict get $good correctness] > 8.0}] [expr {[dict get $bad correctness] < 2.0}] [expr {[dict get $good correctness] > [dict get $bad correctness] + 6.0}]] + $s destroy + set out +} -result {1 1 1} + cleanupTests From bf32cc3fb1af7211b6a36c6dbfe4e10bce2e6233 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:43:42 -0700 Subject: [PATCH 142/156] M3b: score sociological predictions by walk-forward accuracy --- core/src/economy/sims/sociological/runner.tcl | 51 ++++++++++++++++--- 1 file changed, 45 insertions(+), 6 deletions(-) diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl index e685576..9eccf7a 100644 --- a/core/src/economy/sims/sociological/runner.tcl +++ b/core/src/economy/sims/sociological/runner.tcl @@ -184,6 +184,48 @@ oo::class create ::stomach::SociologicalRunner { my _clamp [expr {$total/double([llength $items])}] 0.0 10.0 } + method _walk_forward_correctness {prices social} { + set correct 0.0 + set total_weight 0.0 + foreach event $social { + set sentiment [dict get $event sentiment] + if {abs($sentiment) < 0.10} { continue } + set ts [dict get $event timestamp] + if {![string is double -strict $ts]} { continue } + + set before "" + set after "" + foreach point $prices { + set pts [dict get $point timestamp] + if {![string is double -strict $pts]} { continue } + if {$pts <= $ts} { + set before $point + continue + } + set after $point + break + } + if {$before eq "" || $after eq ""} { continue } + + set p0 [dict get $before price] + set p1 [dict get $after price] + set move [expr {$p1/$p0-1.0}] + if {abs($move) < 0.0005} { continue } + + set predicted [expr {$sentiment > 0 ? 1 : -1}] + set actual [expr {$move > 0 ? 1 : -1}] + set engagement [dict get $event engagement] + set confidence [my _clamp [expr {double([dict get $event confidence])}] 0.0 10.0] + set weight [expr {max(0.05,$engagement)*max(0.1,$confidence/10.0)}] + set total_weight [expr {$total_weight+$weight}] + if {$predicted == $actual} { + set correct [expr {$correct+$weight}] + } + } + if {$total_weight <= 0.0} { return 5.0 } + return [my _clamp [expr {10.0*$correct/$total_weight}] 0.0 10.0] + } + method _bandit_update { ticker initial_shares sentiment price_shift volatility exposure evidence_count } { @@ -293,12 +335,9 @@ oo::class create ::stomach::SociologicalRunner { set scale [expr {max(abs($value),1.0)}] set certainty [my _clamp [expr {$confidence/(1.0+$width/$scale)}] 0.0 10.0] - # V1 boundary correctness is evidence coverage rather than a trained - # classifier score: reward agreement of independent social sources. - array set source_seen {} - foreach d $social { set source_seen([dict get $d source_type]) 1 } - set source_count [array size source_seen] - set correctness [my _clamp [expr {4.0+1.5*min($source_count,4)}] 0.0 10.0] + # Empirical correctness: does signed aggregate social evidence predict + # the next observed price move in walk-forward order? + set correctness [my _walk_forward_correctness $prices $social] return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type sociological token_ticker $ticker recent_shift $price_shift prediction_type $prediction_type label [dict get $native label] calibration_sources rss_news,price_tick population_model bandit_replicator population_epoch $population_epoch population_shares [join $shares ,] timestamp [clock seconds]] } From 155e9ccea37cdbae1c0eb36a2eae326cdd6186ea Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:43:52 -0700 Subject: [PATCH 143/156] ci: enforce empirical M3b correctness boundary --- .github/workflows/m3b-sociological.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/m3b-sociological.yml b/.github/workflows/m3b-sociological.yml index 2d8688e..3c1f3bc 100644 --- a/.github/workflows/m3b-sociological.yml +++ b/.github/workflows/m3b-sociological.yml @@ -45,4 +45,4 @@ jobs: run: | set -euo pipefail tclsh core/src/economy/sims/sociological/integration.test | tee /tmp/m3b-integration.out - grep -Eq 'Total[[:space:]]+5[[:space:]]+Passed[[:space:]]+5.*Failed[[:space:]]+0' /tmp/m3b-integration.out + grep -Eq 'Total[[:space:]]+6[[:space:]]+Passed[[:space:]]+6.*Failed[[:space:]]+0' /tmp/m3b-integration.out From 5fcae16a0542903160488e4ab2e313d0ff4cc2da Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:44:56 -0700 Subject: [PATCH 144/156] docs: mark M3b V1 implemented --- core/docs/plans/M3b-sociological-sims.md | 51 +++++++++++++++++------- 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/core/docs/plans/M3b-sociological-sims.md b/core/docs/plans/M3b-sociological-sims.md index 13ef44d..5618a40 100644 --- a/core/docs/plans/M3b-sociological-sims.md +++ b/core/docs/plans/M3b-sociological-sims.md @@ -10,11 +10,17 @@ pressure across **six concurrent time horizons**. Grounded in evolutionary conse MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs. ## 2. Status / certainty -KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl` -implements replicator dynamics, Hegselmann-Krause bounded-confidence updates, heterogeneous -complex-contagion thresholds, and four-phase pump/dump classification. Native tests live beside -the engine. UCB/Thompson bandit coupling and the HJB/Fokker-Planck MFG layer remain incremental. -Foundations C4/C5 as previously stated; implementation C2; calibrated pop models C1. +IMPLEMENTED · M3b V1 · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl` +implements five abstract behavioral archetypes, replicator dynamics, Hegselmann–Krause bounded +confidence, heterogeneous complex contagion with a multiple-exposure requirement, UCB +bandit-replicator learning, a large-population HJB/Fokker–Planck mean-field equilibrium solver +with damped Newton updates, bounded-rationality pump/dump population dynamics, adaptive +confidence bounds, opinion clustering, and all nine bounded prediction types. The Tcl runner +calibrates from M2 `rss_news` + `price_tick`, preserves per-ticker population state across +queries, advances that state through the native bandit-replicator kernel, evaluates native MFG +stability, and scores correctness by walk-forward social→price agreement. Dedicated CI verifies +both the ECLiPSe kernel and M2→M3b→Hub boundary. Foundations C4/C5; implementation C3; +population parameterization remains evidence-driven rather than hardcoded to literal persons. ## 3. Language & location **ECLiPSe Prolog 7.2** · `src/economy/sims/sociological/`. Libraries: **ic** (interval @@ -77,9 +83,14 @@ mutation, PDE solvers for MFG (HJB + Fokker-Planck), and bandit algorithms (UCB/ `pump_dump_phase`, `mfg_equilibrium_stability`, `narrative_regime`. - Calibration: ingests `rss_news` (sentiment signal) and `price_tick` (realized behavior) from M2. -## 6. Dependencies & stubs -- M2 Data Feeds — sentiment and price data for calibration; *stub:* canned sentiment series. -- M3 Sims hub — lifecycle management; *stub:* manual init. +## 6. Dependencies & runtime boundary +- M2 Data Feeds — normalized `rss_news` carries aggregate source type, sentiment, engagement + and confidence; `price_tick` supplies realized behavioral response. +- M3 Sims hub — every M3b result is published as the common bounded-prediction schema and read + by Traders through Marketplace. Categorical phase/regime results retain a label beside their + bounded numeric code. +- ECLiPSe CLP — installed by the repo toolchain hook and exercised directly by dedicated CI. + M3b has no individual-profile ingestion and no trading/execution surface. ## 7. Invariants / laws - **L1 (C5):** pops are **archetypal individuals, not literal living persons** — no attempt to model or track real @@ -116,10 +127,20 @@ produces adapting populations. MFG: equilibrium converges for large N; matches d small N. Pump-dump: 4-phase cycle detected on synthetic manipulation data. Bounds: all outputs include upper/lower. -## 10. Open items -- Pop archetype catalog (which behavioral types? how many?). -- Network topology for sentiment contagion (small-world? scale-free?). -- Calibration from real market data — how to infer pop distribution from observable price action. >>>We actually use blogs, reddit, and social networks to infer pops<<< -- MFG tensor-train rank $r$ (>>>accuracy<<< vs. compute tradeoff). -- Hegselmann-Krause confidence bound $d$ — fixed or >>>adaptive<< Date: Mon, 19 Oct 2026 20:44:59 -0700 Subject: [PATCH 145/156] docs: mark M3b complete in simulator inventory --- core/src/economy/sims/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md index a39126e..d80eaef 100644 --- a/core/src/economy/sims/README.md +++ b/core/src/economy/sims/README.md @@ -5,7 +5,7 @@ Seven native simulator engines live here behind the Tcl M3 hub. | ID | Engine | Native language | Implemented kernel | |---|---|---|---| | 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 | -| M3b | sociological | ECLiPSe Prolog | replicator dynamics, Hegselmann-Krause, complex contagion, pump/dump phase | +| 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 | | 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 | | M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | | M3e | tokenomics/macro | Fortran 2018 | Euler-Maruyama, stock-flow conservation, kinked lending, directional contagion, yield weights | @@ -22,6 +22,6 @@ tclsh core/src/economy/sims/run_tests.tcl Pass `--strict` when the environment is expected to contain every external runtime. -The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; ECLiPSe native test files remain checked in next to their engines. +The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; M3b has a dedicated ECLiPSe workflow covering the native sociological suite plus persistent M2→M3b→Hub population evolution and walk-forward correctness. This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. From 39fb1dba01e859dbcaa6490da0329028681bce0b Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:45:03 -0700 Subject: [PATCH 146/156] docs: expose completed M3b in economy overview --- core/src/economy/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/economy/README.md b/core/src/economy/README.md index 53fa2b7..d621483 100644 --- a/core/src/economy/README.md +++ b/core/src/economy/README.md @@ -6,7 +6,7 @@ Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organis - **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. - **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. -- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b is ECLiPSe sociological; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. +- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b V1 is complete with persistent five-archetype populations, native bandit-replicator learning, adaptive bounded-confidence/contagion dynamics, HJB/FP MFG stability, pump/dump ABM behavior, nine bounded prediction types, M2 social+price calibration and empirical walk-forward scoring; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. - **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. - **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. - **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. @@ -33,6 +33,6 @@ It executes Tcl + every native suite whose runtime is installed. Use `--strict` ## 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`, `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`, `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. From 0ec8a850fe63a477aeb5d82f3dc05592d32576b7 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:45:07 -0700 Subject: [PATCH 147/156] docs: add M3b V1 runtime contract --- core/src/economy/sims/sociological/README.md | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 core/src/economy/sims/sociological/README.md diff --git a/core/src/economy/sims/sociological/README.md b/core/src/economy/sims/sociological/README.md new file mode 100644 index 0000000..6b6dbd3 --- /dev/null +++ b/core/src/economy/sims/sociological/README.md @@ -0,0 +1,26 @@ +# M3b — sociological simulator + +M3b V1 is the ECLiPSe-Prolog population simulator behind the stomach's `sociological` prediction type. + +V1 contains five abstract archetypes: retail herd, contrarian whale, MEV searcher, passive LP, and manipulator. It implements replicator dynamics, UCB bandit-replicator adaptation, adaptive Hegselmann–Krause bounded confidence, heterogeneous complex contagion, a one-dimensional HJB/Fokker–Planck mean-field equilibrium with damped Newton iteration, bounded-rationality pump/dump dynamics, opinion clustering, and nine public prediction types. + +The live boundary is: + +`M2 rss_news + price_tick → SociologicalRunner (Tcl) → ECLiPSe → SimsHub → Marketplace` + +Population state persists per ticker. Each query advances that state through ECLiPSe's native bandit-replicator relation before the requested prediction is evaluated. MFG stability is also computed by ECLiPSe, not reimplemented in Tcl. + +`correctness` is empirical: confidence/engagement-weighted social direction is compared walk-forward against the next realized price move. It is therefore usable as evidence for later cross-sim gating rather than as a source-count heuristic. + +The nine prediction types are `sentiment_index`, `herd_threshold`, `strategy_distribution`, `cascade_probability`, `coordination_stability`, `opinion_cluster_count`, `pump_dump_phase`, `mfg_equilibrium_stability`, and `narrative_regime`. + +No pop represents a literal person. M3b has no trading, signing, broadcasting, or transaction surface. + +Verification: + +```sh +eclipse -b core/src/economy/sims/sociological/test.ecl -e run_tests +tclsh core/src/economy/sims/sociological/integration.test +``` + +Dedicated CI enforces the native ECLiPSe suite and `6 passed / 0 failed` at the M2→M3b→Hub boundary. From d61b372912838e8c8bc1aaf2ab3199ce661caf99 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:46:07 -0700 Subject: [PATCH 148/156] test: require M3e stock-flow state and halving policy --- .../sims/tokenomics/test/test_tokenomics.f90 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 index dfb0460..c8e4e78 100644 --- a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -2,6 +2,8 @@ program test_tokenomics use tokenomics_engine implicit none real(8) :: shock(3), exposure(3,3), propagated(3), w(3), apy(3), vol(3) + type(token_state) :: state0, state1 + real(8) :: e_before, e_half, e_quarter if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' if (lending_rate(0.90d0,0.02d0,0.04d0,0.60d0,0.80d0) <= lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)) error stop 'kink slope' if (.not. stock_flow_conserved(100d0,50d0,20d0,30d0,200d0,1d-9)) error stop 'conservation' @@ -11,5 +13,21 @@ program test_tokenomics apy=[0.04d0,0.08d0,0.06d0]; vol=[0.01d0,0.10d0,0.03d0] call yield_weights(apy,vol,4d0,w) if (abs(sum(w)-1d0)>1d-9) error stop 'weights normalize' + + state0 = token_state(600d0,250d0,100d0,50d0,1000d0) + call token_state_step(state0,20d0,5d0,10d0,-4d0,state1) + if (abs(state1%total_minted-1020d0)>1d-9) error stop 'minted supply' + if (abs(state1%burned-55d0)>1d-9) error stop 'burn accounting' + if (abs(state1%staked-260d0)>1d-9) error stop 'stake flow' + if (abs(state1%locked-96d0)>1d-9) error stop 'unlock flow' + if (.not. stock_flow_conserved(state1%circulating,state1%staked,state1%locked, & + state1%burned,state1%total_minted,1d-9)) error stop 'state conservation' + + e_before = halving_emission_rate(20d0,99d0,100d0) + e_half = halving_emission_rate(20d0,100d0,100d0) + e_quarter = halving_emission_rate(20d0,200d0,100d0) + if (abs(e_before-20d0)>1d-12) error stop 'pre-halving emission' + if (abs(e_half-10d0)>1d-12) error stop 'first halving' + if (abs(e_quarter-5d0)>1d-12) error stop 'second halving' print *, 'TOKENOMICS TESTS PASSED' end program From 2e6598475fc71efa8b1eafc4a12fae9296626126 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:46:16 -0700 Subject: [PATCH 149/156] ci: add strict Fortran gate for M3e --- .github/workflows/m3e-tokenomics.yml | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/m3e-tokenomics.yml diff --git a/.github/workflows/m3e-tokenomics.yml b/.github/workflows/m3e-tokenomics.yml new file mode 100644 index 0000000..d0796ee --- /dev/null +++ b/.github/workflows/m3e-tokenomics.yml @@ -0,0 +1,35 @@ +name: M3e Tokenomics CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/tokenomics/**" + - ".github/workflows/m3e-tokenomics.yml" + pull_request: + paths: + - "core/src/economy/sims/tokenomics/**" + - ".github/workflows/m3e-tokenomics.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3e: + name: Fortran tokenomics engine + runs-on: ubuntu-latest + defaults: + run: + working-directory: core/src/economy/sims/tokenomics + steps: + - uses: actions/checkout@v4 + + - name: Compile M3e native tests + run: | + mkdir -p /tmp/sica-m3e + gfortran -std=f2018 -Wall -Wextra -Werror -pedantic -J /tmp/sica-m3e src/tokenomics_engine.f90 test/test_tokenomics.f90 -o /tmp/sica-m3e/test_tokenomics + + - name: Run M3e native tests + run: /tmp/sica-m3e/test_tokenomics From 20f5e6b0dda9e1068ab1e72fb6aef5b253475764 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:46:57 -0700 Subject: [PATCH 150/156] M3e: add conserved token state and halving drift --- .../sims/tokenomics/src/tokenomics_engine.f90 | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 index a677a2f..fb5cf8b 100644 --- a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -1,6 +1,68 @@ module tokenomics_engine implicit none + + type :: token_state + real(8) :: circulating + real(8) :: staked + real(8) :: locked + real(8) :: burned + real(8) :: total_minted + end type token_state + contains + + subroutine token_state_step(state, emission, burn, stake_delta, lock_delta, next_state) + type(token_state), intent(in) :: state + real(8), intent(in) :: emission, burn, stake_delta, lock_delta + type(token_state), intent(out) :: next_state + real(8) :: available + + if (emission < 0d0 .or. burn < 0d0) error stop 'negative policy flow' + + next_state = state + next_state%total_minted = state%total_minted + emission + next_state%circulating = state%circulating + emission + + available = next_state%circulating + if (burn > available) error stop 'burn exceeds circulating' + next_state%circulating = next_state%circulating - burn + next_state%burned = state%burned + burn + + if (stake_delta >= 0d0) then + if (stake_delta > next_state%circulating) error stop 'stake exceeds circulating' + next_state%circulating = next_state%circulating - stake_delta + next_state%staked = state%staked + stake_delta + else + if (-stake_delta > state%staked) error stop 'unstake exceeds staked' + next_state%staked = state%staked + stake_delta + next_state%circulating = next_state%circulating - stake_delta + end if + + if (lock_delta >= 0d0) then + if (lock_delta > next_state%circulating) error stop 'lock exceeds circulating' + next_state%circulating = next_state%circulating - lock_delta + next_state%locked = state%locked + lock_delta + else + if (-lock_delta > state%locked) error stop 'unlock exceeds locked' + next_state%locked = state%locked + lock_delta + next_state%circulating = next_state%circulating - lock_delta + end if + end subroutine token_state_step + + pure real(8) function halving_emission_rate(base_rate, time, interval) result(rate) + real(8), intent(in) :: base_rate, time, interval + integer :: halvings + if (base_rate <= 0d0) then + rate = 0d0 + return + end if + if (interval <= 0d0) then + rate = base_rate + return + end if + halvings = int(floor(max(0d0,time) / interval)) + rate = base_rate * 0.5d0**halvings + end function halving_emission_rate pure real(8) function lending_rate(utilization, r0, slope1, slope2, uopt) result(r) real(8), intent(in) :: utilization,r0,slope1,slope2,uopt real(8) :: u From bebd33cb9a93dc6b09ffc53c42116d06fa7d0ebd Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:47:43 -0700 Subject: [PATCH 151/156] test: require M3e liquidation cascades and VAR impulses --- .../sims/tokenomics/test/test_tokenomics.f90 | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 index c8e4e78..19ac85c 100644 --- a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -2,6 +2,8 @@ program test_tokenomics use tokenomics_engine implicit none real(8) :: shock(3), exposure(3,3), propagated(3), w(3), apy(3), vol(3) + real(8) :: collateral(4), borrowed(4), ltv(4), cascade_exposure(4,4), losses(4) + real(8) :: var_a(3,3), impulse(3,4) type(token_state) :: state0, state1 real(8) :: e_before, e_half, e_quarter if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' @@ -29,5 +31,28 @@ program test_tokenomics if (abs(e_before-20d0)>1d-12) error stop 'pre-halving emission' if (abs(e_half-10d0)>1d-12) error stop 'first halving' if (abs(e_quarter-5d0)>1d-12) error stop 'second halving' + + + collateral = [100d0,100d0,100d0,100d0] + borrowed = [90d0,50d0,20d0,20d0] + ltv = [0.80d0,0.80d0,0.80d0,0.80d0] + cascade_exposure = 0d0 + cascade_exposure(2,1) = 0.50d0 + cascade_exposure(3,2) = 0.50d0 + call liquidation_cascade(collateral,borrowed,ltv,cascade_exposure,3,losses) + if (abs(losses(1)-10d0)>1d-9) error stop 'initial liquidation' + if (losses(2) <= 0d0) error stop 'first contagion hop' + if (losses(3) <= 0d0) error stop 'second contagion hop' + if (abs(losses(4)) > 1d-12) error stop 'isolated protocol' + + var_a = 0d0 + var_a(2,1) = 0.40d0 + var_a(3,2) = 0.50d0 + call var_impulse_response(var_a,[1d0,0d0,0d0],3,impulse) + if (abs(impulse(1,1)-1d0)>1d-12) error stop 'impulse origin' + if (abs(impulse(2,2)-0.40d0)>1d-12) error stop 'var first hop' + if (abs(impulse(3,3)-0.20d0)>1d-12) error stop 'var second hop' + if (abs(impulse(1,4))+abs(impulse(2,4))+abs(impulse(3,4)) > 1d-12) & + error stop 'impulse decay' print *, 'TOKENOMICS TESTS PASSED' end program From 734b994f7d95f96d4ded76ba2a04c1cf0a099fbc Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:48:18 -0700 Subject: [PATCH 152/156] M3e: add liquidation cascade and VAR impulse kernels --- .../sims/tokenomics/src/tokenomics_engine.f90 | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 index fb5cf8b..7e17100 100644 --- a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -95,6 +95,45 @@ contains propagated = shock + matmul(exposure, shock) end subroutine + subroutine liquidation_cascade(collateral, borrowed, ltv, exposure, iterations, losses) + real(8), intent(in) :: collateral(:), borrowed(:), ltv(:), exposure(:,:) + integer, intent(in) :: iterations + real(8), intent(out) :: losses(size(collateral)) + real(8) :: initial(size(collateral)), next_losses(size(collateral)) + integer :: step, n + + n = size(collateral) + if (size(borrowed) /= n .or. size(ltv) /= n) error stop 'cascade vector shape' + if (size(exposure,1) /= n .or. size(exposure,2) /= n) error stop 'cascade matrix shape' + if (iterations < 0) error stop 'negative cascade iterations' + if (any(collateral < 0d0) .or. any(borrowed < 0d0)) error stop 'negative balance' + if (any(ltv < 0d0) .or. any(ltv > 1d0)) error stop 'invalid ltv' + if (any(exposure < 0d0)) error stop 'negative exposure' + + initial = max(0d0, borrowed - collateral*ltv) + losses = initial + do step=1,iterations + next_losses = initial + matmul(exposure, losses) + losses = max(0d0, next_losses) + end do + end subroutine liquidation_cascade + + subroutine var_impulse_response(a, shock, steps, response) + real(8), intent(in) :: a(:,:), shock(:) + integer, intent(in) :: steps + real(8), intent(out) :: response(size(shock),steps+1) + integer :: t, n + + n = size(shock) + if (size(a,1) /= n .or. size(a,2) /= n) error stop 'var matrix shape' + if (steps < 0) error stop 'negative impulse steps' + + response(:,1) = shock + do t=1,steps + response(:,t+1) = matmul(a, response(:,t)) + end do + end subroutine var_impulse_response + subroutine yield_weights(apy, vol, risk_aversion, weights) real(8), intent(in) :: apy(:),vol(:),risk_aversion real(8), intent(out) :: weights(size(apy)) From 2c15eabb007b9f7a72af3cde95c49a4980628965 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:49:04 -0700 Subject: [PATCH 153/156] test: require exact M3e yield optimizer KKT conditions --- .../economy/sims/tokenomics/test/test_tokenomics.f90 | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 index 19ac85c..dd6ac83 100644 --- a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -4,6 +4,7 @@ program test_tokenomics real(8) :: shock(3), exposure(3,3), propagated(3), w(3), apy(3), vol(3) real(8) :: collateral(4), borrowed(4), ltv(4), cascade_exposure(4,4), losses(4) real(8) :: var_a(3,3), impulse(3,4) + real(8) :: opt_apy(3), opt_vol(3), opt_w(3), marginal(3) type(token_state) :: state0, state1 real(8) :: e_before, e_half, e_quarter if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' @@ -54,5 +55,14 @@ program test_tokenomics if (abs(impulse(3,3)-0.20d0)>1d-12) error stop 'var second hop' if (abs(impulse(1,4))+abs(impulse(2,4))+abs(impulse(3,4)) > 1d-12) & error stop 'impulse decay' + + + opt_apy = [0.06d0,0.08d0,0.07d0] + opt_vol = [0.10d0,0.12d0,0.08d0] + call yield_weights(opt_apy,opt_vol,2d0,opt_w) + if (abs(sum(opt_w)-1d0)>1d-10) error stop 'optimal weights normalize' + if (minval(opt_w) <= 0d0) error stop 'expected active set' + marginal = opt_apy - 4d0*opt_vol*opt_vol*opt_w + if (maxval(marginal)-minval(marginal) > 1d-8) error stop 'yield KKT stationarity' print *, 'TOKENOMICS TESTS PASSED' end program From 014beb8a5724beb49cd85f56bc01514e346d2180 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:49:42 -0700 Subject: [PATCH 154/156] M3e: solve constrained quadratic yield allocation --- .../sims/tokenomics/src/tokenomics_engine.f90 | 58 ++++++++++++++++--- 1 file changed, 51 insertions(+), 7 deletions(-) diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 index 7e17100..9f05f8e 100644 --- a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -135,15 +135,59 @@ contains end subroutine var_impulse_response subroutine yield_weights(apy, vol, risk_aversion, weights) - real(8), intent(in) :: apy(:),vol(:),risk_aversion + real(8), intent(in) :: apy(:), vol(:), risk_aversion real(8), intent(out) :: weights(size(apy)) - real(8) :: score(size(apy)), total - score = max(0d0, apy-risk_aversion*vol*vol) - total=sum(score) - if (total<=1d-15) then - weights = 1d0/real(size(apy),8) + real(8) :: denom(size(apy)), mu, inv_sum, return_sum + logical :: active(size(apy)), changed + integer :: i, iter, n, best + + n = size(apy) + if (size(vol) /= n .or. n < 1) error stop 'yield vector shape' + if (risk_aversion < 0d0 .or. any(vol < 0d0)) error stop 'invalid yield risk' + + weights = 0d0 + if (risk_aversion <= 1d-15) then + best = maxloc(apy, dim=1) + weights(best) = 1d0 + return + end if + + denom = 2d0*risk_aversion*max(vol*vol,1d-12) + active = .true. + + do iter=1,n + inv_sum = 0d0 + return_sum = 0d0 + do i=1,n + if (active(i)) then + inv_sum = inv_sum + 1d0/denom(i) + return_sum = return_sum + apy(i)/denom(i) + end if + end do + if (inv_sum <= 0d0) exit + + mu = (return_sum-1d0)/inv_sum + changed = .false. + weights = 0d0 + do i=1,n + if (active(i)) then + weights(i) = (apy(i)-mu)/denom(i) + if (weights(i) <= 0d0) then + active(i) = .false. + weights(i) = 0d0 + changed = .true. + end if + end if + end do + if (.not. changed) exit + end do + + if (sum(weights) <= 1d-15) then + best = maxloc(apy, dim=1) + weights = 0d0 + weights(best) = 1d0 else - weights = score/total + weights = weights/sum(weights) end if end subroutine From 2ebdef48c3359c2355f6c3d33f823ab8a436022a Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:50:19 -0700 Subject: [PATCH 155/156] test: require M3e state-estimation convergence --- .../sims/tokenomics/test/test_tokenomics.f90 | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 index dd6ac83..a533671 100644 --- a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -5,6 +5,8 @@ program test_tokenomics real(8) :: collateral(4), borrowed(4), ltv(4), cascade_exposure(4,4), losses(4) real(8) :: var_a(3,3), impulse(3,4) real(8) :: opt_apy(3), opt_vol(3), opt_w(3), marginal(3) + real(8) :: est_mean, est_var, next_mean, next_var + integer :: est_i type(token_state) :: state0, state1 real(8) :: e_before, e_half, e_quarter if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' @@ -64,5 +66,16 @@ program test_tokenomics if (minval(opt_w) <= 0d0) error stop 'expected active set' marginal = opt_apy - 4d0*opt_vol*opt_vol*opt_w if (maxval(marginal)-minval(marginal) > 1d-8) error stop 'yield KKT stationarity' + + + est_mean = 0d0 + est_var = 100d0 + do est_i=1,20 + call kalman_scalar_update(est_mean,est_var,100d0,4d0,1d0,next_mean,next_var) + est_mean = next_mean + est_var = next_var + end do + if (abs(est_mean-100d0)>0.5d0) error stop 'state estimate convergence' + if (est_var >= 4d0) error stop 'state estimate uncertainty' print *, 'TOKENOMICS TESTS PASSED' end program From 846417af58852c67b13219cbb863c17acaf974c1 Mon Sep 17 00:00:00 2001 From: gravermistakes Date: Mon, 19 Oct 2026 20:50:49 -0700 Subject: [PATCH 156/156] M3e: add Kalman state-estimation update --- .../sims/tokenomics/src/tokenomics_engine.f90 | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 index 9f05f8e..da22baf 100644 --- a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -89,6 +89,21 @@ contains end do end subroutine + subroutine kalman_scalar_update(prior_mean, prior_var, observation, observation_var, & + process_var, posterior_mean, posterior_var) + real(8), intent(in) :: prior_mean, prior_var, observation, observation_var, process_var + real(8), intent(out) :: posterior_mean, posterior_var + real(8) :: predicted_var, gain + + if (prior_var < 0d0 .or. observation_var <= 0d0 .or. process_var < 0d0) & + error stop 'invalid kalman variance' + + predicted_var = prior_var + process_var + gain = predicted_var / (predicted_var + observation_var) + posterior_mean = prior_mean + gain*(observation-prior_mean) + posterior_var = max(0d0,(1d0-gain)*predicted_var) + end subroutine kalman_scalar_update + subroutine contagion_step(exposure, shock, propagated) real(8), intent(in) :: exposure(:,:), shock(:) real(8), intent(out) :: propagated(size(shock))