Skip to content

Core API

The core module provides the fundamental building blocks of SWARM.

ProxyComputer

Converts observable signals to soft probabilistic labels.

swarm.core.proxy.ProxyComputer

Computes v_hat proxy scores from downstream observables.

v_hat is a weighted combination of normalized signals, resulting in a score in [-1, +1]. This is then converted to p via calibrated sigmoid.

Source code in swarm/core/proxy.py
class ProxyComputer:
    """
    Computes v_hat proxy scores from downstream observables.

    v_hat is a weighted combination of normalized signals, resulting
    in a score in [-1, +1]. This is then converted to p via calibrated sigmoid.
    """

    def __init__(
        self,
        weights: Optional[ProxyWeights] = None,
        sigmoid_k: float = 2.0,
        rework_decay: float = 0.3,
        rejection_decay: float = 0.4,
        misuse_decay: float = 0.5,
    ):
        """
        Initialize proxy computer.

        Args:
            weights: Weights for combining signals (default: ProxyWeights())
            sigmoid_k: Calibration sharpness for p computation
            rework_decay: Decay factor per rework cycle
            rejection_decay: Decay factor per verifier rejection
            misuse_decay: Decay factor per tool misuse flag
        """
        self.weights = (weights or ProxyWeights()).normalize()
        self.sigmoid_k = sigmoid_k
        self.rework_decay = rework_decay
        self.rejection_decay = rejection_decay
        self.misuse_decay = misuse_decay

    def _normalize_progress(self, delta: float) -> float:
        """Normalize progress delta to [-1, +1]."""
        return max(-1.0, min(1.0, delta))

    def _compute_rework_signal(self, count: int) -> float:
        """
        Convert rework count to signal in [-1, +1].

        More rework cycles = more negative signal.
        Uses exponential decay: signal = 1 - 2 * (1 - decay^count)
        """
        if count == 0:
            return 1.0  # No rework = positive signal

        # Exponential decay towards -1
        decay_factor = self.rework_decay ** count
        return 2.0 * decay_factor - 1.0

    def _compute_rejection_signal(self, count: int) -> float:
        """
        Convert verifier rejection count to signal in [-1, +1].

        More rejections = more negative signal.
        """
        if count == 0:
            return 1.0

        decay_factor = self.rejection_decay ** count
        return 2.0 * decay_factor - 1.0

    def _compute_misuse_signal(self, count: int) -> float:
        """
        Convert tool misuse flag count to signal in [-1, +1].

        Tool misuse is weighted heavily negative.
        """
        if count == 0:
            return 1.0

        decay_factor = self.misuse_decay ** count
        return 2.0 * decay_factor - 1.0

    def _normalize_engagement(self, delta: float) -> float:
        """Normalize engagement delta to [-1, +1]."""
        return max(-1.0, min(1.0, delta))

    def compute_v_hat(self, observables: ProxyObservables) -> float:
        """
        Compute v_hat from downstream observables.

        Args:
            observables: Raw observable signals

        Returns:
            v_hat: Proxy score in [-1, +1]
        """
        # Compute individual signals
        progress_signal = self._normalize_progress(observables.task_progress_delta)
        rework_signal = self._compute_rework_signal(observables.rework_count)
        rejection_signal = self._compute_rejection_signal(observables.verifier_rejections)
        misuse_signal = self._compute_misuse_signal(observables.tool_misuse_flags)
        engagement_signal = self._normalize_engagement(
            observables.counterparty_engagement_delta
        )

        # Combine rejection and misuse into a single "verifier" signal
        verifier_signal = (rejection_signal + misuse_signal) / 2.0

        # Weighted combination
        v_hat = (
            self.weights.task_progress * progress_signal +
            self.weights.rework_penalty * rework_signal +
            self.weights.verifier_penalty * verifier_signal +
            self.weights.engagement_signal * engagement_signal
        )

        # Clamp to [-1, +1]
        return max(-1.0, min(1.0, v_hat))

    def compute_p(self, v_hat: float) -> float:
        """
        Convert v_hat to probability p via calibrated sigmoid.

        Args:
            v_hat: Proxy score in [-1, +1]

        Returns:
            p: P(v = +1) in [0, 1]
        """
        return calibrated_sigmoid(v_hat, self.sigmoid_k)

    def compute_labels(self, observables: ProxyObservables) -> tuple[float, float]:
        """
        Compute both v_hat and p from observables.

        Args:
            observables: Raw observable signals

        Returns:
            (v_hat, p): Proxy score and probability
        """
        v_hat = self.compute_v_hat(observables)
        p = self.compute_p(v_hat)
        return v_hat, p

compute_labels(observables)

Compute both v_hat and p from observables.

Parameters:

Name Type Description Default
observables ProxyObservables

Raw observable signals

required

Returns:

Type Description
(v_hat, p)

Proxy score and probability

Source code in swarm/core/proxy.py
def compute_labels(self, observables: ProxyObservables) -> tuple[float, float]:
    """
    Compute both v_hat and p from observables.

    Args:
        observables: Raw observable signals

    Returns:
        (v_hat, p): Proxy score and probability
    """
    v_hat = self.compute_v_hat(observables)
    p = self.compute_p(v_hat)
    return v_hat, p

Usage

from swarm.core.proxy import ProxyComputer, ProxyObservables

proxy = ProxyComputer()

obs = ProxyObservables(
    task_progress_delta=0.7,
    rework_count=1,
    verifier_rejections=0,
    counterparty_engagement_delta=0.4,
)

v_hat, p = proxy.compute_labels(obs)

ProxyObservables

Field Type Range Description
task_progress_delta float [-1, 1] Progress on task
rework_count int [0, ∞) Number of rework cycles
verifier_rejections int [0, ∞) Safety rejections
counterparty_engagement_delta float [-1, 1] Engagement change

ProxyWeights

Default weights for combining signals:

Signal Weight
task_progress 0.4
rework_penalty 0.2
verifier_penalty 0.2
engagement 0.2

SoftPayoffEngine

Computes payoffs using soft probabilistic labels.

swarm.core.payoff.SoftPayoffEngine

Computes payoffs using soft (probabilistic) labels.

Payoff equations

π_a = θ * S_soft - τ - c_a - ρ_a * E_soft + w_rep * r_a π_b = (1-θ) * S_soft + τ - c_b - ρ_b * E_soft + w_rep * r_b

Where

S_soft = p * s_plus - (1-p) * s_minus (expected surplus) E_soft = (1-p) * h (expected harm)

Source code in swarm/core/payoff.py
class SoftPayoffEngine:
    """
    Computes payoffs using soft (probabilistic) labels.

    Payoff equations:
        π_a = θ * S_soft - τ - c_a - ρ_a * E_soft + w_rep * r_a
        π_b = (1-θ) * S_soft + τ - c_b - ρ_b * E_soft + w_rep * r_b

    Where:
        S_soft = p * s_plus - (1-p) * s_minus  (expected surplus)
        E_soft = (1-p) * h                      (expected harm)
    """

    def __init__(self, config: Optional[PayoffConfig] = None):
        """
        Initialize payoff engine.

        Args:
            config: Payoff configuration (default: PayoffConfig())
        """
        self.config = config or PayoffConfig()
        self.config.validate()

    def expected_surplus(self, p: float) -> float:
        """
        Compute expected surplus: p * s_plus - (1-p) * s_minus

        This is the expected value created/destroyed by the interaction.

        Args:
            p: P(v = +1) probability of beneficial outcome

        Returns:
            Expected surplus (can be negative)
        """
        return p * self.config.s_plus - (1 - p) * self.config.s_minus

    def expected_harm(self, p: float) -> float:
        """
        Compute expected harm externality: (1-p) * h

        This is the expected harm to the ecosystem from a bad outcome.

        Args:
            p: P(v = +1)

        Returns:
            Expected harm (always non-negative)
        """
        return (1 - p) * self.config.h

    def payoff_initiator(self, interaction: SoftInteraction) -> float:
        """
        Compute initiator's payoff.

        π_a = θ * S_soft - τ - c_a - ρ_a * E_soft + w_rep * r_a

        Args:
            interaction: The soft interaction

        Returns:
            Initiator's payoff
        """
        S_soft = self.expected_surplus(interaction.p)
        E_soft = self.expected_harm(interaction.p)

        return (
            self.config.theta * S_soft
            - interaction.tau
            - interaction.c_a
            - self.config.rho_a * E_soft
            + self.config.w_rep * interaction.r_a
        )

    def payoff_counterparty(self, interaction: SoftInteraction) -> float:
        """
        Compute counterparty's payoff.

        π_b = (1-θ) * S_soft + τ - c_b - ρ_b * E_soft + w_rep * r_b

        Args:
            interaction: The soft interaction

        Returns:
            Counterparty's payoff
        """
        S_soft = self.expected_surplus(interaction.p)
        E_soft = self.expected_harm(interaction.p)

        return (
            (1 - self.config.theta) * S_soft
            + interaction.tau
            - interaction.c_b
            - self.config.rho_b * E_soft
            + self.config.w_rep * interaction.r_b
        )

    def payoff_breakdown_initiator(
        self, interaction: SoftInteraction
    ) -> PayoffBreakdown:
        """
        Compute detailed payoff breakdown for initiator.

        Args:
            interaction: The soft interaction

        Returns:
            PayoffBreakdown with all components
        """
        S_soft = self.expected_surplus(interaction.p)
        E_soft = self.expected_harm(interaction.p)

        surplus_share = self.config.theta * S_soft
        externality_cost = self.config.rho_a * E_soft
        reputation_bonus = self.config.w_rep * interaction.r_a

        total = (
            surplus_share
            - interaction.tau
            - interaction.c_a
            - externality_cost
            + reputation_bonus
        )

        return PayoffBreakdown(
            expected_surplus=S_soft,
            expected_harm=E_soft,
            surplus_share=surplus_share,
            transfer=-interaction.tau,  # Negative because initiator pays
            governance_cost=interaction.c_a,
            externality_cost=externality_cost,
            reputation_bonus=reputation_bonus,
            total=total,
        )

    def payoff_breakdown_counterparty(
        self, interaction: SoftInteraction
    ) -> PayoffBreakdown:
        """
        Compute detailed payoff breakdown for counterparty.

        Args:
            interaction: The soft interaction

        Returns:
            PayoffBreakdown with all components
        """
        S_soft = self.expected_surplus(interaction.p)
        E_soft = self.expected_harm(interaction.p)

        surplus_share = (1 - self.config.theta) * S_soft
        externality_cost = self.config.rho_b * E_soft
        reputation_bonus = self.config.w_rep * interaction.r_b

        total = (
            surplus_share
            + interaction.tau
            - interaction.c_b
            - externality_cost
            + reputation_bonus
        )

        return PayoffBreakdown(
            expected_surplus=S_soft,
            expected_harm=E_soft,
            surplus_share=surplus_share,
            transfer=interaction.tau,  # Positive because counterparty receives
            governance_cost=interaction.c_b,
            externality_cost=externality_cost,
            reputation_bonus=reputation_bonus,
            total=total,
        )

    def total_welfare(self, interaction: SoftInteraction) -> float:
        """
        Compute total welfare (sum of payoffs minus externality).

        W = π_a + π_b + E_soft (externality not internalized)

        With full internalization (ρ_a + ρ_b = 1), this equals S_soft.

        Args:
            interaction: The soft interaction

        Returns:
            Total welfare
        """
        return (
            self.payoff_initiator(interaction)
            + self.payoff_counterparty(interaction)
        )

    def social_surplus(self, interaction: SoftInteraction) -> float:
        """
        Compute social surplus including externality.

        Social surplus = S_soft - E_soft
                      = p * s_plus - (1-p) * s_minus - (1-p) * h
                      = p * s_plus - (1-p) * (s_minus + h)

        Args:
            interaction: The soft interaction

        Returns:
            Social surplus
        """
        S_soft = self.expected_surplus(interaction.p)
        E_soft = self.expected_harm(interaction.p)
        return S_soft - E_soft

    def break_even_p(self) -> float:
        """
        Compute the probability threshold where expected surplus = 0.

        p * s_plus = (1-p) * s_minus
        p = s_minus / (s_plus + s_minus)

        Returns:
            Break-even probability
        """
        return self.config.s_minus / (self.config.s_plus + self.config.s_minus)

    def social_break_even_p(self) -> float:
        """
        Compute probability where social surplus = 0.

        p * s_plus = (1-p) * (s_minus + h)
        p = (s_minus + h) / (s_plus + s_minus + h)

        Returns:
            Social break-even probability
        """
        numerator = self.config.s_minus + self.config.h
        denominator = self.config.s_plus + self.config.s_minus + self.config.h
        return numerator / denominator

payoff_initiator(interaction)

Compute initiator's payoff.

π_a = θ * S_soft - τ - c_a - ρ_a * E_soft + w_rep * r_a

Parameters:

Name Type Description Default
interaction SoftInteraction

The soft interaction

required

Returns:

Type Description
float

Initiator's payoff

Source code in swarm/core/payoff.py
def payoff_initiator(self, interaction: SoftInteraction) -> float:
    """
    Compute initiator's payoff.

    π_a = θ * S_soft - τ - c_a - ρ_a * E_soft + w_rep * r_a

    Args:
        interaction: The soft interaction

    Returns:
        Initiator's payoff
    """
    S_soft = self.expected_surplus(interaction.p)
    E_soft = self.expected_harm(interaction.p)

    return (
        self.config.theta * S_soft
        - interaction.tau
        - interaction.c_a
        - self.config.rho_a * E_soft
        + self.config.w_rep * interaction.r_a
    )

payoff_counterparty(interaction)

Compute counterparty's payoff.

π_b = (1-θ) * S_soft + τ - c_b - ρ_b * E_soft + w_rep * r_b

Parameters:

Name Type Description Default
interaction SoftInteraction

The soft interaction

required

Returns:

Type Description
float

Counterparty's payoff

Source code in swarm/core/payoff.py
def payoff_counterparty(self, interaction: SoftInteraction) -> float:
    """
    Compute counterparty's payoff.

    π_b = (1-θ) * S_soft + τ - c_b - ρ_b * E_soft + w_rep * r_b

    Args:
        interaction: The soft interaction

    Returns:
        Counterparty's payoff
    """
    S_soft = self.expected_surplus(interaction.p)
    E_soft = self.expected_harm(interaction.p)

    return (
        (1 - self.config.theta) * S_soft
        + interaction.tau
        - interaction.c_b
        - self.config.rho_b * E_soft
        + self.config.w_rep * interaction.r_b
    )

Usage

from swarm.core.payoff import SoftPayoffEngine, PayoffConfig
from swarm.models.interaction import SoftInteraction

config = PayoffConfig(
    s_plus=1.0,
    s_minus=0.5,
    h=0.3,
    theta=0.5,
)

engine = SoftPayoffEngine(config)

interaction = SoftInteraction(
    initiator="a",
    counterparty="b",
    accepted=True,
    v_hat=0.5,
    p=0.8,
)

payoff_a = engine.payoff_initiator(interaction)
payoff_b = engine.payoff_counterparty(interaction)

PayoffConfig

Parameter Default Description
s_plus 1.0 Surplus if beneficial
s_minus 0.5 Loss if harmful
h 0.3 External harm
theta 0.5 Initiator's share
tau 0.0 Transfer
w_rep 0.1 Reputation weight
rho_a 0.1 Initiator externality internalization
rho_b 0.1 Counterparty externality internalization

Orchestrator

Runs multi-agent simulations.

swarm.core.orchestrator.Orchestrator

Orchestrates the multi-agent simulation.

Responsibilities: - Schedule agent turns - Inject observations - Execute actions - Enforce rate limits - Compute payoffs - Emit events

Delegates domain-specific work to handler objects: - MarketplaceHandler: bounty/bid/escrow/dispute lifecycle - BoundaryHandler: external-world and leakage enforcement - ObservableGenerator: signal generation from interactions

Computation engines (payoff, proxy, metrics) can be injected via constructor for testability and extensibility.

Source code in swarm/core/orchestrator.py
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
class Orchestrator:
    """
    Orchestrates the multi-agent simulation.

    Responsibilities:
    - Schedule agent turns
    - Inject observations
    - Execute actions
    - Enforce rate limits
    - Compute payoffs
    - Emit events

    Delegates domain-specific work to handler objects:
    - MarketplaceHandler: bounty/bid/escrow/dispute lifecycle
    - BoundaryHandler: external-world and leakage enforcement
    - ObservableGenerator: signal generation from interactions

    Computation engines (payoff, proxy, metrics) can be injected
    via constructor for testability and extensibility.
    """

    def __init__(
        self,
        config: Optional[OrchestratorConfig] = None,
        state: Optional[EnvState] = None,
        # --- dependency injection for computation engines ---
        payoff_engine: Optional[SoftPayoffEngine] = None,
        proxy_computer: Optional[ProxyComputer] = None,
        metrics_calculator: Optional[SoftMetrics] = None,
        observable_generator: Optional[ObservableGenerator] = None,
        governance_engine: Optional[GovernanceEngine] = None,
    ):
        """
        Initialize orchestrator.

        Args:
            config: Orchestrator configuration
            state: Initial environment state (optional)
            payoff_engine: Custom payoff engine (default: built from config)
            proxy_computer: Custom proxy computer (default: ProxyComputer())
            metrics_calculator: Custom metrics calculator (default: SoftMetrics)
            observable_generator: Custom observable generator (default:
                DefaultObservableGenerator)
            governance_engine: Custom governance engine (default: built from
                config.governance_config if provided)
        """
        self.config = config or OrchestratorConfig()
        if not 0.0 <= self.config.observation_noise_probability <= 1.0:
            raise ValueError("observation_noise_probability must be in [0, 1]")
        if self.config.observation_noise_std < 0.0:
            raise ValueError("observation_noise_std must be >= 0")

        # Set random seed
        if self.config.seed is not None:
            random.seed(self.config.seed)
        self._rng = random.Random(self.config.seed)

        # Environment components
        self.state = state or EnvState(steps_per_epoch=self.config.steps_per_epoch)
        self.feed = Feed()
        self.task_pool = TaskPool()

        # Composite task support
        if self.config.enable_composite_tasks:
            self.composite_task_pool: Optional[CompositeTaskPool] = CompositeTaskPool()
            self.capability_analyzer: Optional[CapabilityAnalyzer] = CapabilityAnalyzer(
                seed=self.config.seed
            )
        else:
            self.composite_task_pool = None
            self.capability_analyzer = None

        # Network topology (initialized when agents are registered)
        if self.config.network_config is not None:
            self.network: Optional[AgentNetwork] = AgentNetwork(
                config=self.config.network_config,
                seed=self.config.seed,
            )
        else:
            self.network = None

        # Agents
        self._agents: Dict[str, BaseAgent] = {}

        # Computation engines (injectable)
        self.payoff_engine = payoff_engine or SoftPayoffEngine(self.config.payoff_config)
        self.proxy_computer = proxy_computer or ProxyComputer()
        self.metrics_calculator = metrics_calculator or SoftMetrics(self.payoff_engine)
        self._observable_generator: ObservableGenerator = (
            observable_generator or DefaultObservableGenerator()
        )

        # Governance engine (injectable)
        if governance_engine is not None:
            self.governance_engine: Optional[GovernanceEngine] = governance_engine
        elif self.config.governance_config is not None:
            self.governance_engine = GovernanceEngine(
                self.config.governance_config,
                seed=self.config.seed,
            )
        else:
            self.governance_engine = None

        # Marketplace handler
        if self.config.marketplace_config is not None:
            marketplace = Marketplace(self.config.marketplace_config)
            self.marketplace: Optional[Marketplace] = marketplace
            self._marketplace_handler: Optional[MarketplaceHandler] = MarketplaceHandler(
                marketplace=marketplace,
                task_pool=self.task_pool,
                emit_event=self._emit_event,
            )
        else:
            self.marketplace = None
            self._marketplace_handler = None

        # Boundary handler
        if self.config.enable_boundaries:
            external_world = ExternalWorld().create_default_world()
            flow_tracker = FlowTracker(
                sensitivity_threshold=self.config.boundary_sensitivity_threshold
            )
            policy_engine = PolicyEngine().create_default_policies()
            leakage_detector = LeakageDetector()

            self.external_world: Optional[ExternalWorld] = external_world
            self.flow_tracker: Optional[FlowTracker] = flow_tracker
            self.policy_engine: Optional[PolicyEngine] = policy_engine
            self.leakage_detector: Optional[LeakageDetector] = leakage_detector

            self._boundary_handler: Optional[BoundaryHandler] = BoundaryHandler(
                external_world=external_world,
                flow_tracker=flow_tracker,
                policy_engine=policy_engine,
                leakage_detector=leakage_detector,
                emit_event=self._emit_event,
                seed=self.config.seed,
            )
        else:
            self.external_world = None
            self.flow_tracker = None
            self.policy_engine = None
            self.leakage_detector = None
            self._boundary_handler = None

        # Event logging
        if self.config.log_path:
            self.event_log: Optional[EventLog] = EventLog(self.config.log_path)
        else:
            self.event_log = None

        # Epoch metrics history
        self._epoch_metrics: List[EpochMetrics] = []

        # Callbacks
        self._on_epoch_end: List[Callable[[EpochMetrics], None]] = []
        self._on_interaction_complete: List[Callable[[SoftInteraction, float, float], None]] = []

    def register_agent(self, agent: BaseAgent) -> AgentState:
        """
        Register an agent with the simulation.

        Args:
            agent: Agent to register

        Returns:
            The agent's state
        """
        if agent.agent_id in self._agents:
            raise ValueError(f"Agent {agent.agent_id} already registered")

        self._agents[agent.agent_id] = agent

        # Create agent state in environment
        state = self.state.add_agent(
            agent_id=agent.agent_id,
            agent_type=agent.agent_type,
        )

        # Log event
        self._emit_event(Event(
            event_type=EventType.AGENT_CREATED,
            agent_id=agent.agent_id,
            payload={
                "agent_type": agent.agent_type.value,
                "roles": [r.value for r in agent.roles],
            },
            epoch=self.state.current_epoch,
            step=self.state.current_step,
        ))

        return state

    def _initialize_network(self) -> None:
        """Initialize network topology with registered agents."""
        agent_ids = list(self._agents.keys())
        if self.network is not None:
            self.network.initialize(agent_ids)
        # Set agent IDs for collusion detection
        if self.governance_engine is not None:
            self.governance_engine.set_collusion_agent_ids(agent_ids)

    def run(self) -> List[EpochMetrics]:
        """
        Run the full simulation.

        Returns:
            List of metrics for each epoch
        """
        # Initialize network with registered agents
        self._initialize_network()

        # Log simulation start
        self._emit_event(Event(
            event_type=EventType.SIMULATION_STARTED,
            payload={
                "n_epochs": self.config.n_epochs,
                "steps_per_epoch": self.config.steps_per_epoch,
                "n_agents": len(self._agents),
                "seed": self.config.seed,
                "scenario_id": self.config.scenario_id,
                "replay_k": self.config.replay_k,
            },
        ))

        # Main loop
        for _epoch in range(self.config.n_epochs):
            epoch_metrics = self._run_epoch()
            self._epoch_metrics.append(epoch_metrics)

            # Callbacks
            for callback in self._on_epoch_end:
                callback(epoch_metrics)

        # Log simulation end
        self._emit_event(Event(
            event_type=EventType.SIMULATION_ENDED,
            payload={
                "total_epochs": self.config.n_epochs,
                "final_metrics": self._epoch_metrics[-1].__dict__ if self._epoch_metrics else {},
            },
        ))

        return self._epoch_metrics

    def _run_epoch(self) -> EpochMetrics:
        """Run a single epoch."""
        epoch_start = self.state.current_epoch

        self._update_adaptive_governance()

        # Apply epoch-start governance (reputation decay, unfreezes)
        if self.governance_engine:
            gov_effect = self.governance_engine.apply_epoch_start(
                self.state, self.state.current_epoch
            )
            self._apply_governance_effect(gov_effect)

        for _step in range(self.config.steps_per_epoch):
            if self.state.is_paused:
                break

            self._run_step()
            self.state.advance_step()

        # Marketplace epoch maintenance
        if self._marketplace_handler is not None:
            self._marketplace_handler.on_epoch_end(self.state)

        # Apply network edge decay
        if self.network is not None:
            pruned = self.network.decay_edges()
            if pruned > 0:
                self._emit_event(Event(
                    event_type=EventType.EPOCH_COMPLETED,
                    payload={"network_edges_pruned": pruned},
                    epoch=epoch_start,
                ))

        # Compute epoch metrics
        metrics = self._compute_epoch_metrics()

        # Log epoch completion
        self._emit_event(Event(
            event_type=EventType.EPOCH_COMPLETED,
            payload=metrics.__dict__,
            epoch=epoch_start,
        ))

        # Advance to next epoch
        self.state.advance_epoch()

        return metrics

    def _run_step(self) -> None:
        """Run a single step within an epoch."""
        if (
            self.governance_engine
            and self.governance_engine.config.adaptive_use_behavioral_features
        ):
            self._update_adaptive_governance(include_behavioral=True)

        # Step-level governance hooks (e.g., decomposition checkpoints)
        if self.governance_engine:
            step_effect = self.governance_engine.apply_step(
                self.state, self.state.current_step
            )
            self._apply_governance_effect(step_effect)

        # Get agent schedule for this step
        agent_order = self._get_agent_schedule()

        actions_this_step = 0

        for agent_id in agent_order:
            if actions_this_step >= self.config.max_actions_per_step:
                break

            if not self.state.can_agent_act(agent_id):
                continue

            # Check governance admission control (staking)
            if self.governance_engine and not self.governance_engine.can_agent_act(agent_id, self.state):
                continue

            agent = self._agents[agent_id]

            # Build observation for agent
            observation = self._build_observation(agent_id)

            # Get agent action
            action = self._select_action(agent, observation)

            # Execute action
            success = self._execute_action(action)

            if success:
                actions_this_step += 1

        # Resolve pending interactions
        self._resolve_pending_interactions()

    def _select_action(self, agent: BaseAgent, observation: Observation) -> Action:
        """Select an action, optionally using governance ensembling."""
        if (
            self.governance_engine is None
            or not self.governance_engine.config.self_ensemble_enabled
            or self.governance_engine.config.self_ensemble_samples <= 1
        ):
            return agent.act(observation)

        samples = self.governance_engine.config.self_ensemble_samples
        candidate_actions = [agent.act(observation) for _ in range(samples)]
        selected = self._majority_action(candidate_actions)
        selected.metadata["ensemble_samples"] = samples
        return selected

    async def _select_action_async(self, agent: BaseAgent, observation: Observation) -> Action:
        """Async action selection with optional governance ensembling."""
        if (
            self.governance_engine is None
            or not self.governance_engine.config.self_ensemble_enabled
            or self.governance_engine.config.self_ensemble_samples <= 1
        ):
            if self._is_llm_agent(agent):
                return await agent.act_async(observation)  # type: ignore[attr-defined]
            return agent.act(observation)

        samples = self.governance_engine.config.self_ensemble_samples
        candidate_actions: List[Action] = []
        for _ in range(samples):
            if self._is_llm_agent(agent):
                candidate_actions.append(await agent.act_async(observation))  # type: ignore[attr-defined]
            else:
                candidate_actions.append(agent.act(observation))

        selected = self._majority_action(candidate_actions)
        selected.metadata["ensemble_samples"] = samples
        return selected

    def _majority_action(self, actions: List[Action]) -> Action:
        """Choose majority action signature with deterministic tie-break."""
        if not actions:
            return Action(action_type=ActionType.NOOP)

        counts: Dict[Tuple, int] = {}
        first_index: Dict[Tuple, int] = {}
        for idx, action in enumerate(actions):
            key = self._action_signature(action)
            counts[key] = counts.get(key, 0) + 1
            if key not in first_index:
                first_index[key] = idx

        best_key = max(
            counts.keys(),
            key=lambda key: (counts[key], -first_index[key]),
        )
        for action in actions:
            if self._action_signature(action) == best_key:
                return action
        return actions[0]

    @staticmethod
    def _action_signature(action: Action) -> Tuple:
        """Stable signature for grouping semantically equivalent actions."""
        return (
            action.action_type.value,
            action.target_id,
            action.counterparty_id,
            action.interaction_type.value,
            action.vote_direction,
            action.content,
        )

    def _get_agent_schedule(self) -> List[str]:
        """Get the order of agents for this step."""
        agent_ids = list(self._agents.keys())

        if self.config.schedule_mode == "random":
            self._rng.shuffle(agent_ids)
        elif self.config.schedule_mode == "priority":
            # Sort by reputation (higher reputation goes first)
            agent_ids.sort(
                key=lambda aid: (agent_st.reputation if (agent_st := self.state.get_agent(aid)) else 0),
                reverse=True,
            )
        # else: round_robin (default order)

        return agent_ids

    def _build_observation(self, agent_id: str) -> Observation:
        """Build observation for an agent."""
        agent_state = self.state.get_agent(agent_id)
        rate_limit = self.state.get_rate_limit_state(agent_id)

        # Get visible posts
        visible_posts = [
            p.to_dict() for p in self.feed.get_ranked_posts(limit=20)
        ]

        # Get pending proposals for this agent
        pending_proposals = [
            {
                "proposal_id": p.proposal_id,
                "initiator_id": p.initiator_id,
                "interaction_type": p.interaction_type,
                "content": p.content,
                "offered_transfer": p.metadata.get("offered_transfer", 0),
            }
            for p in self.state.get_proposals_for_agent(agent_id)
        ]

        # Get available tasks
        available_tasks = [
            t.to_dict() for t in self.task_pool.get_claimable_tasks(
                agent_reputation=agent_state.reputation if agent_state else 0,
                current_epoch=self.state.current_epoch,
            )
        ]

        # Get agent's active tasks
        active_tasks = [
            t.to_dict() for t in self.task_pool.get_tasks_for_agent(agent_id)
            if t.status in (TaskStatus.CLAIMED, TaskStatus.IN_PROGRESS)
        ]

        # Get visible agents (filtered by network if enabled)
        active_agents = self.state.get_active_agents()

        if self.network is not None:
            # Only show network neighbors
            neighbor_ids = set(self.network.neighbors(agent_id))
            active_agents = [s for s in active_agents if s.agent_id in neighbor_ids]

        visible_agents = [
            {
                "agent_id": s.agent_id,
                "agent_type": s.agent_type.value,
                "reputation": s.reputation,
                "resources": s.resources,
                "edge_weight": self.network.edge_weight(agent_id, s.agent_id) if self.network else 1.0,
            }
            for s in active_agents
            if s.agent_id != agent_id
        ]

        visible_agents = [self._apply_observation_noise(record) for record in visible_agents]

        # Build marketplace observation via handler
        available_bounties: List[Dict] = []
        active_bids: List[Dict] = []
        active_escrows: List[Dict] = []
        pending_bid_decisions: List[Dict] = []

        if self._marketplace_handler is not None:
            mkt_obs = self._marketplace_handler.build_observation_fields(
                agent_id, self.state,
            )
            available_bounties = mkt_obs["available_bounties"]
            active_bids = mkt_obs["active_bids"]
            active_escrows = mkt_obs["active_escrows"]
            pending_bid_decisions = mkt_obs["pending_bid_decisions"]

        return Observation(
            agent_state=agent_state or AgentState(),
            current_epoch=self.state.current_epoch,
            current_step=self.state.current_step,
            can_post=rate_limit.can_post(self.state.rate_limits) if self.config.enable_rate_limits else True,
            can_interact=rate_limit.can_interact(self.state.rate_limits) if self.config.enable_rate_limits else True,
            can_vote=rate_limit.can_vote(self.state.rate_limits) if self.config.enable_rate_limits else True,
            can_claim_task=rate_limit.can_claim_task(self.state.rate_limits) if self.config.enable_rate_limits else True,
            visible_posts=visible_posts,
            pending_proposals=pending_proposals,
            available_tasks=available_tasks,
            active_tasks=active_tasks,
            visible_agents=visible_agents,
            available_bounties=available_bounties,
            active_bids=active_bids,
            active_escrows=active_escrows,
            pending_bid_decisions=pending_bid_decisions,
            ecosystem_metrics=self._apply_observation_noise(
                self.state.get_epoch_metrics_snapshot()
            ),
        )

    def _apply_observation_noise(self, record: Dict[str, Any]) -> Dict[str, Any]:
        """
        Apply configurable gaussian noise to numeric observation fields.

        Noise is only applied when enabled and never to boolean fields.
        """
        if (
            self.config.observation_noise_probability <= 0
            or self.config.observation_noise_std <= 0
        ):
            return record

        noisy: Dict[str, Any] = {}
        for key, value in record.items():
            if isinstance(value, bool):
                noisy[key] = value
                continue
            if isinstance(value, (int, float)):
                if self._rng.random() < self.config.observation_noise_probability:
                    noisy[key] = float(value) + self._rng.gauss(
                        0.0, self.config.observation_noise_std
                    )
                else:
                    noisy[key] = value
                continue
            noisy[key] = value
        return noisy

    def _execute_action(self, action: Action) -> bool:
        """
        Execute an agent action.

        Returns:
            True if action was successful
        """
        agent_id = action.agent_id
        rate_limit = self.state.get_rate_limit_state(agent_id)

        if action.action_type == ActionType.NOOP:
            return True

        elif action.action_type == ActionType.POST:
            if not rate_limit.can_post(self.state.rate_limits):
                return False

            try:
                self.feed.create_post(
                    author_id=agent_id,
                    content=action.content[:self.config.max_content_length],
                )
                rate_limit.record_post()
                return True
            except ValueError:
                return False

        elif action.action_type == ActionType.REPLY:
            if not rate_limit.can_post(self.state.rate_limits):
                return False

            try:
                self.feed.create_post(
                    author_id=agent_id,
                    content=action.content[:self.config.max_content_length],
                    parent_id=action.target_id,
                )
                rate_limit.record_post()
                return True
            except ValueError:
                return False

        elif action.action_type == ActionType.VOTE:
            if not rate_limit.can_vote(self.state.rate_limits):
                return False

            vote_type = VoteType.UPVOTE if action.vote_direction > 0 else VoteType.DOWNVOTE
            vote = self.feed.vote(action.target_id, agent_id, vote_type)
            if vote:
                rate_limit.record_vote()
                return True
            return False

        elif action.action_type == ActionType.PROPOSE_INTERACTION:
            if not rate_limit.can_interact(self.state.rate_limits):
                return False

            # Validate network constraint
            if self.network is not None:
                if not self.network.has_edge(agent_id, action.counterparty_id):
                    # Cannot interact with non-neighbors
                    return False

            proposal = InteractionProposal(
                initiator_id=agent_id,
                counterparty_id=action.counterparty_id,
                interaction_type=action.interaction_type.value,
                content=action.content,
                metadata=action.metadata,
            )
            self.state.add_proposal(proposal)
            rate_limit.record_interaction()

            # Log proposal event
            self._emit_event(interaction_proposed_event(
                interaction_id=proposal.proposal_id,
                initiator_id=agent_id,
                counterparty_id=action.counterparty_id,
                interaction_type=action.interaction_type.value,
                v_hat=0.0,  # Computed later
                p=0.5,
                epoch=self.state.current_epoch,
                step=self.state.current_step,
            ))

            return True

        elif action.action_type == ActionType.ACCEPT_INTERACTION:
            accept_proposal: Optional[InteractionProposal] = self.state.remove_proposal(action.target_id)
            if accept_proposal:
                self._complete_interaction(accept_proposal, accepted=True)
                return True
            return False

        elif action.action_type == ActionType.REJECT_INTERACTION:
            proposal_rej: Optional[InteractionProposal] = self.state.remove_proposal(action.target_id)
            if proposal_rej:
                self._complete_interaction(proposal_rej, accepted=False)
                return True
            return False

        elif action.action_type == ActionType.CLAIM_TASK:
            agent_state = self.state.get_agent(agent_id)
            if not agent_state:
                return False

            success = self.task_pool.claim_task(
                task_id=action.target_id,
                agent_id=agent_id,
                agent_reputation=agent_state.reputation,
            )
            if success:
                rate_limit.record_task_claim()
            return success

        elif action.action_type == ActionType.SUBMIT_OUTPUT:
            task = self.task_pool.get_task(action.target_id)
            if task and task.claimed_by == agent_id:
                task.submit_output(agent_id, action.content)
                return True
            return False

        # Marketplace actions — delegate to handler
        elif action.action_type == ActionType.POST_BOUNTY:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_post_bounty(
                action, self.state,
                enable_rate_limits=self.config.enable_rate_limits,
            )

        elif action.action_type == ActionType.PLACE_BID:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_place_bid(
                action, self.state,
                enable_rate_limits=self.config.enable_rate_limits,
            )

        elif action.action_type == ActionType.ACCEPT_BID:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_accept_bid(action, self.state)

        elif action.action_type == ActionType.REJECT_BID:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_reject_bid(action, self.state)

        elif action.action_type == ActionType.WITHDRAW_BID:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_withdraw_bid(action)

        elif action.action_type == ActionType.FILE_DISPUTE:
            if self._marketplace_handler is None:
                return False
            return self._marketplace_handler.handle_file_dispute(action, self.state)

        return False

    def _resolve_pending_interactions(self) -> None:
        """Resolve any remaining pending interactions."""
        # Get all pending proposals
        proposals = list(self.state.pending_proposals.values())

        for proposal in proposals:
            counterparty_id = proposal.counterparty_id

            # Check if counterparty agent exists and can act
            if counterparty_id not in self._agents:
                continue

            if not self.state.can_agent_act(counterparty_id):
                continue

            counterparty = self._agents[counterparty_id]
            observation = self._build_observation(counterparty_id)

            # Ask counterparty agent to decide
            from swarm.agents.base import InteractionProposal as AgentProposal

            agent_proposal = AgentProposal(
                proposal_id=proposal.proposal_id,
                initiator_id=proposal.initiator_id,
                counterparty_id=proposal.counterparty_id,
                interaction_type=InteractionType(proposal.interaction_type),
                content=proposal.content,
                offered_transfer=proposal.metadata.get("offered_transfer", 0),
            )

            accept = counterparty.accept_interaction(agent_proposal, observation)

            # Remove and complete
            self.state.remove_proposal(proposal.proposal_id)
            self._complete_interaction(proposal, accepted=accept)

    def _complete_interaction(
        self,
        proposal: InteractionProposal,
        accepted: bool,
    ) -> None:
        """Complete an interaction and compute payoffs."""
        # Generate observables via the injectable generator
        observables = self._observable_generator.generate(
            proposal, accepted, self.state,
        )

        # Compute v_hat and p
        v_hat, p = self.proxy_computer.compute_labels(observables)

        # Create SoftInteraction
        interaction = SoftInteraction(
            interaction_id=proposal.proposal_id,
            initiator=proposal.initiator_id,
            counterparty=proposal.counterparty_id,
            interaction_type=InteractionType(proposal.interaction_type),
            accepted=accepted,
            task_progress_delta=observables.task_progress_delta,
            rework_count=observables.rework_count,
            verifier_rejections=observables.verifier_rejections,
            tool_misuse_flags=observables.tool_misuse_flags,
            counterparty_engagement_delta=observables.counterparty_engagement_delta,
            v_hat=v_hat,
            p=p,
            tau=proposal.metadata.get("offered_transfer", 0),
        )

        # Apply governance costs to interaction
        if self.governance_engine:
            gov_effect = self.governance_engine.apply_interaction(interaction, self.state)
            interaction.c_a += gov_effect.cost_a
            interaction.c_b += gov_effect.cost_b
            self._apply_governance_effect(gov_effect)

            # Log governance event
            if gov_effect.cost_a > 0 or gov_effect.cost_b > 0:
                self._emit_event(Event(
                    event_type=EventType.GOVERNANCE_COST_APPLIED,
                    interaction_id=proposal.proposal_id,
                    initiator_id=proposal.initiator_id,
                    counterparty_id=proposal.counterparty_id,
                    payload={
                        "cost_a": gov_effect.cost_a,
                        "cost_b": gov_effect.cost_b,
                        "levers": [e.lever_name for e in gov_effect.lever_effects],
                    },
                    epoch=self.state.current_epoch,
                    step=self.state.current_step,
                ))

        # Compute payoffs
        payoff_init = self.payoff_engine.payoff_initiator(interaction)
        payoff_counter = self.payoff_engine.payoff_counterparty(interaction)

        # Update agent states
        if accepted:
            initiator_state = self.state.get_agent(proposal.initiator_id)
            counterparty_state = self.state.get_agent(proposal.counterparty_id)

            if initiator_state:
                initiator_state.record_initiated(accepted=True, p=p)
                initiator_state.total_payoff += payoff_init
                # Reputation delta accounts for governance costs so that
                # tax, audit penalties, etc. feed back through the
                # reputation → observables → p loop to affect toxicity.
                rep_delta = (p - 0.5) - interaction.c_a
                self._update_reputation(proposal.initiator_id, rep_delta)

            if counterparty_state:
                counterparty_state.record_received(accepted=True, p=p)
                counterparty_state.total_payoff += payoff_counter

        # Update agent memory
        if proposal.initiator_id in self._agents:
            self._agents[proposal.initiator_id].update_from_outcome(interaction, payoff_init)
        if proposal.counterparty_id in self._agents:
            self._agents[proposal.counterparty_id].update_from_outcome(interaction, payoff_counter)

        # Record interaction
        self.state.record_interaction(interaction)

        # Log events
        self._emit_event(interaction_completed_event(
            interaction_id=proposal.proposal_id,
            accepted=accepted,
            payoff_initiator=payoff_init,
            payoff_counterparty=payoff_counter,
            epoch=self.state.current_epoch,
            step=self.state.current_step,
        ))

        self._emit_event(payoff_computed_event(
            interaction_id=proposal.proposal_id,
            initiator_id=proposal.initiator_id,
            counterparty_id=proposal.counterparty_id,
            payoff_initiator=payoff_init,
            payoff_counterparty=payoff_counter,
            components={
                "p": p,
                "v_hat": v_hat,
                "tau": interaction.tau,
                "accepted": accepted,
            },
            epoch=self.state.current_epoch,
            step=self.state.current_step,
        ))

        # Strengthen network edge after interaction
        if self.network is not None and accepted:
            self.network.strengthen_edge(proposal.initiator_id, proposal.counterparty_id)

        # Callbacks
        for callback in self._on_interaction_complete:
            callback(interaction, payoff_init, payoff_counter)

    def _generate_observables(
        self,
        proposal: InteractionProposal,
        accepted: bool,
    ) -> ProxyObservables:
        """Generate observable signals for an interaction.

        Delegates to the injected ObservableGenerator.  Kept for
        backwards compatibility with subclasses that override this.
        """
        return self._observable_generator.generate(proposal, accepted, self.state)

    def _update_reputation(self, agent_id: str, delta: float) -> None:
        """Update agent reputation."""
        agent_state = self.state.get_agent(agent_id)
        if not agent_state:
            return

        old_rep = agent_state.reputation
        agent_state.update_reputation(delta)

        self._emit_event(reputation_updated_event(
            agent_id=agent_id,
            old_reputation=old_rep,
            new_reputation=agent_state.reputation,
            delta=delta,
            reason="interaction_outcome",
            epoch=self.state.current_epoch,
            step=self.state.current_step,
        ))

    # =========================================================================
    # Marketplace Delegation (preserves public interface)
    # =========================================================================

    def settle_marketplace_task(
        self,
        task_id: str,
        success: bool,
        quality_score: float = 1.0,
    ) -> Optional[Dict]:
        """
        Settle a marketplace bounty/escrow after task completion.

        Delegates to MarketplaceHandler.
        """
        if self._marketplace_handler is None:
            return None
        return self._marketplace_handler.settle_task(
            task_id=task_id,
            success=success,
            state=self.state,
            governance_engine=self.governance_engine,
            quality_score=quality_score,
        )

    def _apply_governance_effect(self, effect: GovernanceEffect) -> None:
        """Apply governance effects to state (freeze/unfreeze, reputation, resources)."""
        # Freeze agents
        for agent_id in effect.agents_to_freeze:
            self.state.freeze_agent(agent_id)

        # Unfreeze agents
        for agent_id in effect.agents_to_unfreeze:
            self.state.unfreeze_agent(agent_id)

        # Apply reputation deltas
        for agent_id, delta in effect.reputation_deltas.items():
            agent_state = self.state.get_agent(agent_id)
            if agent_state:
                old_rep = agent_state.reputation
                agent_state.update_reputation(delta)
                self._emit_event(reputation_updated_event(
                    agent_id=agent_id,
                    old_reputation=old_rep,
                    new_reputation=agent_state.reputation,
                    delta=delta,
                    reason="governance",
                    epoch=self.state.current_epoch,
                    step=self.state.current_step,
                ))

        # Apply resource deltas
        for agent_id, delta in effect.resource_deltas.items():
            agent_state = self.state.get_agent(agent_id)
            if agent_state:
                agent_state.update_resources(delta)

    def _compute_epoch_metrics(self) -> EpochMetrics:
        """Compute metrics for the current epoch."""
        interactions = self.state.completed_interactions

        # Get network metrics if available (even with no interactions)
        network_metrics = None
        if self.network is not None:
            network_metrics = self.network.get_metrics()

        # Get capability metrics if available
        capability_metrics = None
        if self.capability_analyzer is not None:
            capability_metrics = self.capability_analyzer.compute_metrics()

        if not interactions:
            return EpochMetrics(
                epoch=self.state.current_epoch,
                network_metrics=network_metrics,
                capability_metrics=capability_metrics,
            )

        accepted = [i for i in interactions if i.accepted]

        # Use soft metrics calculator
        toxicity = self.metrics_calculator.toxicity_rate(interactions)
        quality_gap = self.metrics_calculator.quality_gap(interactions)
        welfare = self.metrics_calculator.welfare_metrics(interactions)

        return EpochMetrics(
            epoch=self.state.current_epoch,
            total_interactions=len(interactions),
            accepted_interactions=len(accepted),
            total_posts=len(self.feed._posts),
            total_votes=len(self.feed._votes),
            toxicity_rate=toxicity,
            quality_gap=quality_gap,
            avg_payoff=welfare.get("avg_initiator_payoff", 0),
            total_welfare=welfare.get("total_welfare", 0),
            network_metrics=network_metrics,
            capability_metrics=capability_metrics,
        )

    def _emit_event(self, event: Event) -> None:
        """Emit an event to the log."""
        if event.seed is None:
            event.seed = self.config.seed
        if event.scenario_id is None:
            event.scenario_id = self.config.scenario_id
        if event.replay_k is None:
            event.replay_k = self.config.replay_k

        if self.event_log is not None and self.config.log_events:
            self.event_log.append(event)

    def pause(self) -> None:
        """Pause the simulation."""
        self.state.pause()

    def resume(self) -> None:
        """Resume the simulation."""
        self.state.resume()

    def get_agent(self, agent_id: str) -> Optional[BaseAgent]:
        """Get an agent by ID."""
        return self._agents.get(agent_id)

    def get_all_agents(self) -> List[BaseAgent]:
        """Get all registered agents."""
        return list(self._agents.values())

    def get_metrics_history(self) -> List[EpochMetrics]:
        """Get all epoch metrics."""
        return self._epoch_metrics

    def get_collusion_report(self):
        """Get the latest collusion detection report."""
        if self.governance_engine is None:
            return None
        return self.governance_engine.get_collusion_report()

    # =========================================================================
    # Composite Task Support
    # =========================================================================

    def add_composite_task(self, task: CompositeTask) -> bool:
        """
        Add a composite task to the pool.

        Args:
            task: The composite task to add

        Returns:
            True if added successfully
        """
        if self.composite_task_pool is None:
            return False
        self.composite_task_pool.add_task(task)
        return True

    def get_composite_task(self, task_id: str) -> Optional[CompositeTask]:
        """Get a composite task by ID."""
        if self.composite_task_pool is None:
            return None
        return self.composite_task_pool.get_task(task_id)

    def get_open_composite_tasks(self) -> List[CompositeTask]:
        """Get all open composite tasks."""
        if self.composite_task_pool is None:
            return []
        return self.composite_task_pool.get_open_tasks()

    def register_agent_capabilities(
        self,
        agent_id: str,
        capabilities: set,
    ) -> bool:
        """
        Register an agent's capabilities for composite task matching.

        Args:
            agent_id: The agent's ID
            capabilities: Set of CapabilityType values

        Returns:
            True if registered successfully
        """
        if self.capability_analyzer is None:
            return False
        self.capability_analyzer.register_agent(agent_id, capabilities)
        return True

    def get_capability_metrics(self) -> Optional[EmergentCapabilityMetrics]:
        """Get current emergent capability metrics."""
        if self.capability_analyzer is None:
            return None
        return self.capability_analyzer.compute_metrics()

    def get_composite_task_stats(self) -> Dict:
        """Get statistics about composite tasks."""
        if self.composite_task_pool is None:
            return {}
        return self.composite_task_pool.get_stats()

    def on_epoch_end(self, callback: Callable[[EpochMetrics], None]) -> None:
        """Register a callback for epoch end."""
        self._on_epoch_end.append(callback)

    def on_interaction_complete(
        self,
        callback: Callable[[SoftInteraction, float, float], None],
    ) -> None:
        """Register a callback for interaction completion."""
        self._on_interaction_complete.append(callback)

    # =========================================================================
    # Async Support for LLM Agents
    # =========================================================================

    def _is_llm_agent(self, agent: BaseAgent) -> bool:
        """Check if an agent is an LLM agent with async support."""
        return hasattr(agent, 'act_async') and hasattr(agent, 'accept_interaction_async')

    async def run_async(self) -> List[EpochMetrics]:
        """
        Run the full simulation asynchronously.

        This method enables concurrent LLM API calls for better performance
        when using LLM-backed agents.

        Returns:
            List of metrics for each epoch
        """
        # Initialize network with registered agents
        self._initialize_network()

        # Log simulation start
        self._emit_event(Event(
            event_type=EventType.SIMULATION_STARTED,
            payload={
                "n_epochs": self.config.n_epochs,
                "steps_per_epoch": self.config.steps_per_epoch,
                "n_agents": len(self._agents),
                "seed": self.config.seed,
                "async": True,
            },
        ))

        # Main loop
        for _epoch in range(self.config.n_epochs):
            epoch_metrics = await self._run_epoch_async()
            self._epoch_metrics.append(epoch_metrics)

            # Callbacks
            for callback in self._on_epoch_end:
                callback(epoch_metrics)

        # Log simulation end
        self._emit_event(Event(
            event_type=EventType.SIMULATION_ENDED,
            payload={
                "total_epochs": self.config.n_epochs,
                "final_metrics": self._epoch_metrics[-1].__dict__ if self._epoch_metrics else {},
            },
        ))

        return self._epoch_metrics

    async def _run_epoch_async(self) -> EpochMetrics:
        """Run a single epoch asynchronously."""
        epoch_start = self.state.current_epoch

        self._update_adaptive_governance()

        # Apply epoch-start governance (reputation decay, unfreezes)
        if self.governance_engine:
            gov_effect = self.governance_engine.apply_epoch_start(
                self.state, self.state.current_epoch
            )
            self._apply_governance_effect(gov_effect)

        for _step in range(self.config.steps_per_epoch):
            if self.state.is_paused:
                break

            await self._run_step_async()
            self.state.advance_step()

        # Apply network edge decay
        if self.network is not None:
            pruned = self.network.decay_edges()
            if pruned > 0:
                self._emit_event(Event(
                    event_type=EventType.EPOCH_COMPLETED,
                    payload={"network_edges_pruned": pruned},
                    epoch=epoch_start,
                ))

        # Compute epoch metrics
        metrics = self._compute_epoch_metrics()

        # Log epoch completion
        self._emit_event(Event(
            event_type=EventType.EPOCH_COMPLETED,
            payload=metrics.__dict__,
            epoch=epoch_start,
        ))

        # Advance to next epoch
        self.state.advance_epoch()

        return metrics

    async def _run_step_async(self) -> None:
        """Run a single step asynchronously with concurrent LLM calls."""
        if (
            self.governance_engine
            and self.governance_engine.config.adaptive_use_behavioral_features
        ):
            self._update_adaptive_governance(include_behavioral=True)

        # Step-level governance hooks (e.g., decomposition checkpoints)
        if self.governance_engine:
            step_effect = self.governance_engine.apply_step(
                self.state, self.state.current_step
            )
            self._apply_governance_effect(step_effect)

        # Get agent schedule for this step
        agent_order = self._get_agent_schedule()

        actions_this_step = 0

        # Collect agents that can act this step
        agents_to_act = []
        for agent_id in agent_order:
            if actions_this_step >= self.config.max_actions_per_step:
                break

            if not self.state.can_agent_act(agent_id):
                continue

            # Check governance admission control (staking)
            if self.governance_engine and not self.governance_engine.can_agent_act(agent_id, self.state):
                continue

            agents_to_act.append(agent_id)
            actions_this_step += 1

        # Get actions concurrently for LLM agents
        async def get_agent_action(agent_id: str) -> Tuple[str, Action]:
            agent = self._agents[agent_id]
            observation = self._build_observation(agent_id)
            action = await self._select_action_async(agent, observation)
            return agent_id, action

        # Execute all agent actions concurrently
        tasks = [get_agent_action(agent_id) for agent_id in agents_to_act]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        # Process results
        for result in results:
            if isinstance(result, Exception):
                # Log error but continue
                continue

            agent_id, action = result  # type: ignore[misc]
            self._execute_action(action)

        # Resolve pending interactions asynchronously
        await self._resolve_pending_interactions_async()

    async def _resolve_pending_interactions_async(self) -> None:
        """Resolve pending interactions with async support for LLM agents."""
        # Get all pending proposals
        proposals = list(self.state.pending_proposals.values())

        async def resolve_proposal(proposal: InteractionProposal) -> Optional[bool]:
            counterparty_id = proposal.counterparty_id

            # Check if counterparty agent exists and can act
            if counterparty_id not in self._agents:
                return None

            if not self.state.can_agent_act(counterparty_id):
                return None

            counterparty = self._agents[counterparty_id]
            observation = self._build_observation(counterparty_id)

            # Create agent proposal object
            from swarm.agents.base import InteractionProposal as AgentProposal

            agent_proposal = AgentProposal(
                proposal_id=proposal.proposal_id,
                initiator_id=proposal.initiator_id,
                counterparty_id=proposal.counterparty_id,
                interaction_type=InteractionType(proposal.interaction_type),
                content=proposal.content,
                offered_transfer=proposal.metadata.get("offered_transfer", 0),
            )

            # Get decision (async for LLM agents)
            if self._is_llm_agent(counterparty):
                accept = await counterparty.accept_interaction_async(agent_proposal, observation)  # type: ignore[attr-defined]
            else:
                accept = counterparty.accept_interaction(agent_proposal, observation)

            return bool(accept)

        # Resolve all proposals concurrently
        tasks = [resolve_proposal(p) for p in proposals]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        # Process results
        for proposal, result in zip(proposals, results, strict=False):
            if isinstance(result, Exception) or result is None:
                continue

            accept = bool(result)
            # Remove and complete
            self.state.remove_proposal(proposal.proposal_id)
            self._complete_interaction(proposal, accepted=accept)

    def _update_adaptive_governance(self, include_behavioral: bool = False) -> None:
        """Update adaptive governance mode from current episode/epoch features."""
        if self.governance_engine is None:
            return
        if not self.governance_engine.config.adaptive_governance_enabled:
            return

        agents = self.get_all_agents()
        adversarial_count = sum(
            1 for agent in agents
            if agent.agent_type in (AgentType.ADVERSARIAL, AgentType.DECEPTIVE)
        )
        structural = extract_structural_features(
            horizon_length=self.config.steps_per_epoch,
            agent_count=len(agents),
            action_space_size=len(ActionType),
            adversarial_fraction=(
                adversarial_count / len(agents) if agents else 0.0
            ),
        )
        features = structural

        if include_behavioral:
            behavioral = extract_behavioral_features(self.state.completed_interactions)
            features = combine_feature_dicts(structural, behavioral)

        self.governance_engine.update_adaptive_mode(features)

    def get_llm_usage_stats(self) -> Dict[str, Dict[str, Any]]:
        """
        Get LLM usage statistics for all LLM agents.

        Returns:
            Dictionary mapping agent_id to usage stats
        """
        stats = {}
        for agent_id, agent in self._agents.items():
            if hasattr(agent, 'get_usage_stats'):
                stats[agent_id] = agent.get_usage_stats()
        return stats

    def get_network_metrics(self) -> Optional[Dict[str, float]]:
        """
        Get current network topology metrics.

        Returns:
            Dictionary of network metrics, or None if no network
        """
        if self.network is None:
            return None
        return self.network.get_metrics()

    def get_network(self) -> Optional[AgentNetwork]:
        """Get the network object for direct manipulation."""
        return self.network

    # =========================================================================
    # Red-Team Support
    # =========================================================================

    def get_adaptive_adversary_reports(self) -> Dict[str, Dict]:
        """
        Get strategy reports from all adaptive adversaries.

        Returns:
            Dictionary mapping agent_id to strategy report
        """
        reports = {}
        for agent_id, agent in self._agents.items():
            if hasattr(agent, 'get_strategy_report'):
                reports[agent_id] = agent.get_strategy_report()
        return reports

    def notify_adversary_detection(
        self,
        agent_id: str,
        penalty: float = 0.0,
        detected: bool = True,
    ) -> None:
        """
        Notify an adaptive adversary of detection/penalty.

        This allows adversaries to learn from governance feedback.

        Args:
            agent_id: The agent that was detected
            penalty: Penalty amount applied
            detected: Whether the agent was detected
        """
        agent = self._agents.get(agent_id)
        if agent is not None and hasattr(agent, 'update_adversary_outcome'):
            # Get recent payoff for this agent
            recent_payoff = 0.0
            if self.state.completed_interactions:
                agent_interactions = [
                    i for i in self.state.completed_interactions
                    if i.initiator == agent_id or i.counterparty == agent_id
                ]
                if agent_interactions:
                    last = agent_interactions[-1]
                    if last.initiator == agent_id:
                        recent_payoff = last.payoff_initiator or 0.0  # type: ignore[attr-defined]
                    else:
                        recent_payoff = last.payoff_counterparty or 0.0  # type: ignore[attr-defined]

            agent.update_adversary_outcome(
                payoff=recent_payoff,
                penalty=penalty,
                detected=detected,
            )

    def get_evasion_metrics(self) -> Dict:
        """
        Get evasion metrics for adversarial agents.

        Returns:
            Dictionary with evasion statistics
        """
        metrics: Dict[str, Any] = {
            "total_adversaries": 0,
            "adaptive_adversaries": 0,
            "avg_detection_rate": 0.0,
            "avg_heat_level": 0.0,
            "strategies_used": {},
            "by_agent": {},
        }

        detection_rates = []
        heat_levels = []

        for agent_id, agent in self._agents.items():
            agent_state = self.state.get_agent(agent_id)
            if agent_state and agent_state.agent_type == AgentType.ADVERSARIAL:
                metrics["total_adversaries"] += 1

                if hasattr(agent, 'get_strategy_report'):
                    metrics["adaptive_adversaries"] += 1
                    report = agent.get_strategy_report()
                    metrics["by_agent"][agent_id] = report

                    # Aggregate strategy usage
                    for strategy, stats in report.get("strategy_stats", {}).items():
                        if strategy not in metrics["strategies_used"]:
                            metrics["strategies_used"][strategy] = {
                                "total_attempts": 0,
                                "total_detections": 0,
                            }
                        attempts = stats.get("attempts", 0)
                        detection_rate = stats.get("detection_rate", 0)
                        metrics["strategies_used"][strategy]["total_attempts"] += attempts
                        metrics["strategies_used"][strategy]["total_detections"] += int(
                            attempts * detection_rate
                        )

                    heat_levels.append(report.get("heat_level", 0))

                    # Calculate detection rate from strategy stats
                    total_attempts = sum(
                        s.get("attempts", 0) for s in report.get("strategy_stats", {}).values()
                    )
                    total_detected = sum(
                        s.get("attempts", 0) * s.get("detection_rate", 0)
                        for s in report.get("strategy_stats", {}).values()
                    )
                    if total_attempts > 0:
                        detection_rates.append(total_detected / total_attempts)

        if detection_rates:
            metrics["avg_detection_rate"] = sum(detection_rates) / len(detection_rates)
        if heat_levels:
            metrics["avg_heat_level"] = sum(heat_levels) / len(heat_levels)

        return metrics

    # =========================================================================
    # Boundary Delegation (preserves public interface)
    # =========================================================================

    def request_external_interaction(
        self,
        agent_id: str,
        entity_id: str,
        action: str,
        payload: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """
        Request an interaction with an external entity.

        Delegates to BoundaryHandler.
        """
        if self._boundary_handler is None:
            return {"success": False, "error": "Boundaries not enabled"}
        return self._boundary_handler.request_external_interaction(
            agent_id=agent_id,
            entity_id=entity_id,
            action=action,
            payload=payload,
        )

    def get_external_entities(
        self,
        entity_type: Optional[str] = None,
        min_trust: float = 0.0,
    ) -> List[Dict[str, Any]]:
        """Get available external entities. Delegates to BoundaryHandler."""
        if self._boundary_handler is None:
            return []
        return self._boundary_handler.get_external_entities(
            entity_type=entity_type,
            min_trust=min_trust,
        )

    def add_external_entity(self, entity: ExternalEntity) -> None:
        """Add an external entity to the world. Delegates to BoundaryHandler."""
        if self._boundary_handler is not None:
            self._boundary_handler.add_external_entity(entity)

    def get_boundary_metrics(self) -> Dict[str, Any]:
        """Get comprehensive boundary metrics. Delegates to BoundaryHandler."""
        if self._boundary_handler is None:
            return {"boundaries_enabled": False}
        return self._boundary_handler.get_metrics()

    def get_agent_boundary_activity(self, agent_id: str) -> Dict[str, Any]:
        """Get boundary activity for a specific agent. Delegates to BoundaryHandler."""
        if self._boundary_handler is None:
            return {"agent_id": agent_id}
        return self._boundary_handler.get_agent_activity(agent_id)

    def get_leakage_report(self) -> Optional[LeakageReport]:
        """Get the full leakage detection report. Delegates to BoundaryHandler."""
        if self._boundary_handler is None:
            return None
        return self._boundary_handler.get_leakage_report()

register_agent(agent)

Register an agent with the simulation.

Parameters:

Name Type Description Default
agent BaseAgent

Agent to register

required

Returns:

Type Description
AgentState

The agent's state

Source code in swarm/core/orchestrator.py
def register_agent(self, agent: BaseAgent) -> AgentState:
    """
    Register an agent with the simulation.

    Args:
        agent: Agent to register

    Returns:
        The agent's state
    """
    if agent.agent_id in self._agents:
        raise ValueError(f"Agent {agent.agent_id} already registered")

    self._agents[agent.agent_id] = agent

    # Create agent state in environment
    state = self.state.add_agent(
        agent_id=agent.agent_id,
        agent_type=agent.agent_type,
    )

    # Log event
    self._emit_event(Event(
        event_type=EventType.AGENT_CREATED,
        agent_id=agent.agent_id,
        payload={
            "agent_type": agent.agent_type.value,
            "roles": [r.value for r in agent.roles],
        },
        epoch=self.state.current_epoch,
        step=self.state.current_step,
    ))

    return state

run()

Run the full simulation.

Returns:

Type Description
List[EpochMetrics]

List of metrics for each epoch

Source code in swarm/core/orchestrator.py
def run(self) -> List[EpochMetrics]:
    """
    Run the full simulation.

    Returns:
        List of metrics for each epoch
    """
    # Initialize network with registered agents
    self._initialize_network()

    # Log simulation start
    self._emit_event(Event(
        event_type=EventType.SIMULATION_STARTED,
        payload={
            "n_epochs": self.config.n_epochs,
            "steps_per_epoch": self.config.steps_per_epoch,
            "n_agents": len(self._agents),
            "seed": self.config.seed,
            "scenario_id": self.config.scenario_id,
            "replay_k": self.config.replay_k,
        },
    ))

    # Main loop
    for _epoch in range(self.config.n_epochs):
        epoch_metrics = self._run_epoch()
        self._epoch_metrics.append(epoch_metrics)

        # Callbacks
        for callback in self._on_epoch_end:
            callback(epoch_metrics)

    # Log simulation end
    self._emit_event(Event(
        event_type=EventType.SIMULATION_ENDED,
        payload={
            "total_epochs": self.config.n_epochs,
            "final_metrics": self._epoch_metrics[-1].__dict__ if self._epoch_metrics else {},
        },
    ))

    return self._epoch_metrics

Usage

from swarm.core.orchestrator import Orchestrator, OrchestratorConfig

config = OrchestratorConfig(
    n_epochs=10,
    steps_per_epoch=10,
    seed=42,
)

orchestrator = Orchestrator(config=config)
orchestrator.register_agent(agent1)
orchestrator.register_agent(agent2)

metrics = orchestrator.run()

OrchestratorConfig

Parameter Default Description
n_epochs 10 Number of epochs
steps_per_epoch 10 Steps per epoch
seed None Random seed
async_mode False Async agent execution
governance None Governance configuration
payoff None Payoff configuration

Sigmoid Functions

swarm.core.sigmoid

Calibrated sigmoid utilities for soft label computation.

calibrated_sigmoid(v_hat, k=2.0)

Compute calibrated sigmoid: P(v = +1) = 1 / (1 + exp(-k * v_hat))

Parameters:

Name Type Description Default
v_hat float

Raw proxy score in [-1, +1]

required
k float

Calibration sharpness parameter (default 2.0) - k = 0: Always returns 0.5 - k < 2: Soft/uncertain labels - k = 2: Moderate calibration - k > 2: Sharp/confident labels

2.0

Returns:

Name Type Description
p float

Probability in [0, 1]

Source code in swarm/core/sigmoid.py
def calibrated_sigmoid(v_hat: float, k: float = 2.0) -> float:
    """
    Compute calibrated sigmoid: P(v = +1) = 1 / (1 + exp(-k * v_hat))

    Args:
        v_hat: Raw proxy score in [-1, +1]
        k: Calibration sharpness parameter (default 2.0)
            - k = 0: Always returns 0.5
            - k < 2: Soft/uncertain labels
            - k = 2: Moderate calibration
            - k > 2: Sharp/confident labels

    Returns:
        p: Probability in [0, 1]
    """
    # Clamp v_hat to avoid numerical issues
    v_hat = max(-10.0, min(10.0, v_hat))

    # Compute sigmoid
    exp_term = math.exp(-k * v_hat)
    return 1.0 / (1.0 + exp_term)

inverse_sigmoid(p, k=2.0)

Compute inverse sigmoid: v_hat = -ln((1-p)/p) / k

Parameters:

Name Type Description Default
p float

Probability in (0, 1)

required
k float

Calibration sharpness parameter

2.0

Returns:

Name Type Description
v_hat float

Raw proxy score

Raises:

Type Description
ValueError

If p is not in (0, 1)

Source code in swarm/core/sigmoid.py
def inverse_sigmoid(p: float, k: float = 2.0) -> float:
    """
    Compute inverse sigmoid: v_hat = -ln((1-p)/p) / k

    Args:
        p: Probability in (0, 1)
        k: Calibration sharpness parameter

    Returns:
        v_hat: Raw proxy score

    Raises:
        ValueError: If p is not in (0, 1)
    """
    if p <= 0.0 or p >= 1.0:
        raise ValueError(f"p must be in (0, 1), got {p}")

    if k == 0:
        raise ValueError("k cannot be zero for inverse sigmoid")

    return -math.log((1.0 - p) / p) / k

Usage

from swarm.core.sigmoid import calibrated_sigmoid, inverse_sigmoid

# v_hat to probability
p = calibrated_sigmoid(v_hat=0.5, k=3.0)

# probability to v_hat
v_hat = inverse_sigmoid(p=0.8, k=3.0)