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 (must be > 0 and <= 100)
            rework_decay: Decay factor per rework cycle (must be in (0, 1))
            rejection_decay: Decay factor per verifier rejection (must be in (0, 1))
            misuse_decay: Decay factor per tool misuse flag (must be in (0, 1))

        Raises:
            ValueError: If any parameter is out of valid range
        """
        # Validate sigmoid_k
        if sigmoid_k <= 0:
            raise ValueError(f"sigmoid_k must be positive, got {sigmoid_k}")
        if sigmoid_k > 100:
            raise ValueError(
                f"sigmoid_k is extremely large ({sigmoid_k}), which may indicate a bug. "
                "Values above 100 are rejected."
            )

        # Validate decay parameters
        for param_name, param_value in [
            ("rework_decay", rework_decay),
            ("rejection_decay", rejection_decay),
            ("misuse_decay", misuse_decay),
        ]:
            if param_value <= 0:
                raise ValueError(
                    f"{param_name} must be positive, got {param_value}. "
                    "Decay values <= 0 would cause incorrect signal computation."
                )
            if param_value >= 1:
                raise ValueError(
                    f"{param_name} must be less than 1, got {param_value}. "
                    "Decay values >= 1 would cause signals to increase with penalties."
                )
            if param_value < 0.01:
                raise ValueError(
                    f"{param_name} is extremely small ({param_value}), which may indicate a bug. "
                    "Values below 0.01 cause signals to decay too rapidly."
                )

        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] and warn if clamping occurs
        original_v_hat = v_hat
        v_hat = max(-1.0, min(1.0, v_hat))
        if v_hat != original_v_hat:
            logger.warning(
                "v_hat clamped from %.4f to %.4f in compute_v_hat. "
                "This may indicate incorrect weight normalization or signal computation. "
                "Observables: progress=%.2f, rework=%d, rejections=%d, misuse=%d, engagement=%.2f",
                original_v_hat,
                v_hat,
                observables.task_progress_delta,
                observables.rework_count,
                observables.verifier_rejections,
                observables.tool_misuse_flags,
                observables.counterparty_engagement_delta,
            )

        return v_hat

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

        Uses the fast-path sigmoid since sigmoid_k is validated at __init__
        time and v_hat arrives here already clamped by compute_v_hat().

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

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

    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 Default Weight Role
task_progress 0.4 Primary outcome signal — directly measured progress
rework_penalty 0.2 Quality penalty — indirect signal from rework cycles
verifier_penalty 0.2 Safety penalty — indirect signal from verifier rejections and tool misuse
engagement_signal 0.2 Social signal — counterparty engagement response

Task progress receives double weight because it is the only direct outcome measure; the three indirect signals share the remaining weight equally. All weights are normalized to sum to 1.0. See Weight Rationale for full discussion.

Custom weights can be passed to ProxyComputer:

from swarm.core.proxy import ProxyComputer, ProxyWeights

# Safety-focused weighting
proxy = ProxyComputer(
    weights=ProxyWeights(
        task_progress=0.2,
        rework_penalty=0.3,
        verifier_penalty=0.3,
        engagement_signal=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 = PayoffConfig() if config is None else config
        # Pydantic auto-validates

    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)

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

    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)

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

    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 payoffs_both(self, interaction: SoftInteraction) -> tuple[float, float]:
        """
        Compute both initiator and counterparty payoffs in a single call.

        Avoids redundant expected_surplus / expected_harm computation
        compared to calling payoff_initiator + payoff_counterparty separately.

        Args:
            interaction: The soft interaction

        Returns:
            (pi_a, pi_b): Initiator and counterparty payoffs
        """
        p = interaction.p
        S_soft = p * self.config.s_plus - (1 - p) * self.config.s_minus
        E_soft = (1 - p) * self.config.h

        pi_a = (
            self.config.theta * S_soft
            - interaction.tau
            - interaction.c_a
            - self.config.rho_a * E_soft
            + self.config.w_rep * interaction.r_a
        )
        pi_b = (
            (1 - self.config.theta) * S_soft
            + interaction.tau
            - interaction.c_b
            - self.config.rho_b * E_soft
            + self.config.w_rep * interaction.r_b
        )
        return pi_a, pi_b

    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
        """
        denominator = self.config.s_plus + self.config.s_minus
        if denominator == 0:
            return 0.5
        return self.config.s_minus / denominator

    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
        if denominator == 0:
            return 0.5
        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)

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

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)

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

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.

The orchestrator is a thin coordination layer. It owns the main simulation loop (epoch → step → agent-turn) and delegates all domain logic to composed components:

  • Handlers (via HandlerRegistry): action dispatch
  • Middleware (via MiddlewarePipeline): lifecycle hooks
  • AgentScheduler: turn order and eligibility
  • InteractionFinalizer: payoff / reputation / state updates
  • ObservationBuilder: per-agent observation assembly
Source code in swarm/core/orchestrator.py
 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
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
class Orchestrator:
    """Orchestrates the multi-agent simulation.

    The orchestrator is a thin coordination layer.  It owns the main
    simulation loop (epoch → step → agent-turn) and delegates all
    domain logic to composed components:

    - **Handlers** (via ``HandlerRegistry``): action dispatch
    - **Middleware** (via ``MiddlewarePipeline``): lifecycle hooks
    - **AgentScheduler**: turn order and eligibility
    - **InteractionFinalizer**: payoff / reputation / state updates
    - **ObservationBuilder**: per-agent observation assembly
    """

    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,
    ):
        self.config = OrchestratorConfig() if config is None else config
        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")

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

        # ---------------------------------------------------------------
        # Core state
        # ---------------------------------------------------------------
        self.state = state or EnvState(steps_per_epoch=self.config.steps_per_epoch)
        self.feed = Feed()
        self.task_pool = TaskPool()
        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(rng=self._rng)
        )

        # ---------------------------------------------------------------
        # Governance engine
        # ---------------------------------------------------------------
        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

        # ---------------------------------------------------------------
        # Network
        # ---------------------------------------------------------------
        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

        # ---------------------------------------------------------------
        # Composite tasks
        # ---------------------------------------------------------------
        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

        # ---------------------------------------------------------------
        # Perturbation engine
        # ---------------------------------------------------------------
        if self.config.perturbation_config is not None:
            self._perturbation_engine: Optional[PerturbationEngine] = (
                PerturbationEngine(
                    config=self.config.perturbation_config,
                    state=self.state,
                    network=self.network,
                    governance_engine=self.governance_engine,
                )
            )
        else:
            self._perturbation_engine = None

        # ---------------------------------------------------------------
        # Event bus & logging
        # ---------------------------------------------------------------
        self._event_bus = EventBus()
        self._event_bus.set_enrichment(
            seed=self.config.seed,
            scenario_id=self.config.scenario_id,
            replay_k=self.config.replay_k,
        )

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

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

        # ---------------------------------------------------------------
        # Graph memory (cross-run trust priors)
        # ---------------------------------------------------------------
        if self.config.graph_memory_path is not None:
            self._graph_memory: Optional[GraphMemoryStore] = GraphMemoryStore(
                self.config.graph_memory_path
            )
        else:
            self._graph_memory = None

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

        # ---------------------------------------------------------------
        # Adaptive governance controller
        # ---------------------------------------------------------------
        self._adaptive_controller = None
        if (
            self.governance_engine
            and self.config.governance_config
            and self.config.governance_config.adaptive_controller_enabled
        ):
            from swarm.governance.adaptive_controller import (
                AdaptiveGovernanceController,
            )

            self._adaptive_controller = AdaptiveGovernanceController(
                governance_engine=self.governance_engine,
                event_bus=self._event_bus,
                config=self.config.governance_config,
                seed=self.config.seed,
            )
            self._on_epoch_end.append(self._adaptive_controller.on_epoch_end)

        # ---------------------------------------------------------------
        # Interaction finalizer (extracted component)
        # ---------------------------------------------------------------
        self._finalizer = InteractionFinalizer(
            state=self.state,
            payoff_engine=self.payoff_engine,
            proxy_computer=self.proxy_computer,
            observable_generator=self._observable_generator,
            governance_engine=self.governance_engine,
            network=self.network,
            agents=self._agents,
            on_interaction_complete=self._on_interaction_complete,
            event_bus=self._event_bus,
        )

        # ---------------------------------------------------------------
        # Handlers (via factory)
        # ---------------------------------------------------------------
        self._handlers: HandlerSet = build_handlers(
            self.config,
            event_bus=self._event_bus,
            feed=self.feed,
            task_pool=self.task_pool,
            finalizer=self._finalizer,
            network=self.network,
            governance_engine=self.governance_engine,
            rng=self._rng,
        )
        self._handler_registry = self._handlers.registry

        # Expose named handler refs for public API compatibility
        self.marketplace = self._handlers.marketplace
        self._marketplace_handler = self._handlers.marketplace_handler
        self._moltipedia_handler = self._handlers.moltipedia_handler
        self._moltbook_handler = self._handlers.moltbook_handler
        self._memory_handler = self._handlers.memory_handler
        self._scholar_handler = self._handlers.scholar_handler
        self._kernel_handler = self._handlers.kernel_handler
        self._rivals_handler = self._handlers.rivals_handler
        self._awm_handler = self._handlers.awm_handler
        self._evo_game_handler = self._handlers.evo_game_handler
        self._tierra_handler = self._handlers.tierra_handler
        self._boundary_handler = self._handlers.boundary_handler
        self._feed_handler = self._handlers.feed_handler
        self._core_interaction_handler = self._handlers.core_interaction_handler
        self._task_handler = self._handlers.task_handler
        self._coding_handler = self._handlers.coding_handler

        # Boundary sub-components for public API
        self.external_world = self._handlers.external_world
        self.flow_tracker = self._handlers.flow_tracker
        self.policy_engine = self._handlers.policy_engine
        self.leakage_detector = self._handlers.leakage_detector

        # ---------------------------------------------------------------
        # Contract market
        # ---------------------------------------------------------------
        if self.config.contracts_config is not None:
            from swarm.scenarios.loader import build_contract_market

            self.contract_market: Optional[Any] = build_contract_market(
                self.config.contracts_config,
                seed=self.config.seed,
            )
        else:
            self.contract_market = None
        self._last_contract_metrics: Optional[Any] = None

        # ---------------------------------------------------------------
        # Letta lifecycle
        # ---------------------------------------------------------------
        if self.config.letta_config is not None:
            from swarm.bridges.letta.lifecycle import LettaLifecycleManager

            self._letta_lifecycle: Optional[Any] = LettaLifecycleManager(
                self.config.letta_config,
            )
        else:
            self._letta_lifecycle = None

        # ---------------------------------------------------------------
        # Spawn tree
        # ---------------------------------------------------------------
        if self.config.spawn_config is not None and self.config.spawn_config.enabled:
            self._spawn_tree: Optional[SpawnTree] = SpawnTree(self.config.spawn_config)
            self._spawn_counter: int = 0
        else:
            self._spawn_tree = None
            self._spawn_counter = 0

        # ---------------------------------------------------------------
        # Observation builder
        # ---------------------------------------------------------------
        self._obs_builder = ObservationBuilder(
            config=self.config,
            state=self.state,
            feed=self.feed,
            task_pool=self.task_pool,
            network=self.network,
            handler_registry=self._handler_registry,
            rng=self._rng,
            spawn_tree=self._spawn_tree,
        )

        # ---------------------------------------------------------------
        # Red-team inspector
        # ---------------------------------------------------------------
        self._redteam = RedTeamInspector(self._agents, self.state)

        # ---------------------------------------------------------------
        # Agent scheduler
        # ---------------------------------------------------------------
        self._scheduler = AgentScheduler(
            schedule_mode=self.config.schedule_mode,
            max_actions_per_step=self.config.max_actions_per_step,
            rng=self._rng,
        )

        # ---------------------------------------------------------------
        # Middleware pipeline (lifecycle hooks for cross-cutting concerns)
        # ---------------------------------------------------------------
        self._pipeline = MiddlewarePipeline()
        self._build_pipeline()

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

        # ---------------------------------------------------------------
        # External agent support
        # ---------------------------------------------------------------
        self._external_action_queue: Optional[Any] = None
        self._external_observations: Dict[str, Dict[str, Any]] = {}

    # ===================================================================
    # Pipeline construction
    # ===================================================================

    def _build_pipeline(self) -> None:
        """Assemble the middleware pipeline in execution order.

        Order matters: governance must run before handler lifecycle hooks
        (which may read governance state), and contract signing must happen
        before handler epoch-start hooks.
        """
        # 1. Governance (adaptive updates + epoch/step effects)
        if self.governance_engine is not None:
            self._gov_mw: Optional[GovernanceMiddleware] = GovernanceMiddleware(
                self.governance_engine,
                self._adaptive_controller,
            )
            self._pipeline.add(self._gov_mw)
        else:
            self._gov_mw = None

        # 2. Letta governance block update
        if self._letta_lifecycle is not None:
            self._letta_mw: Optional[LettaMiddleware] = LettaMiddleware(
                self._letta_lifecycle
            )
            self._pipeline.add(self._letta_mw)
        else:
            self._letta_mw = None

        # 3. Contract market signing
        if self.contract_market is not None:
            self._contract_mw: Optional[ContractMiddleware] = ContractMiddleware(
                self.contract_market, self._event_bus
            )
            self._pipeline.add(self._contract_mw)
        else:
            self._contract_mw = None

        # 4. Perturbation engine triggers
        if self._perturbation_engine is not None:
            self._perturb_mw: Optional[PerturbationMiddleware] = PerturbationMiddleware(
                self._perturbation_engine
            )
            self._pipeline.add(self._perturb_mw)
        else:
            self._perturb_mw = None

        # 5. Handler lifecycle hooks (on_epoch_start/end, on_step)
        self._pipeline.add(HandlerLifecycleMiddleware(self._handler_registry))

        # 6. Network edge decay at epoch end
        if self.network is not None:
            self._pipeline.add(NetworkDecayMiddleware(self.network, self._event_bus))

        # 7. Agent memory decay at epoch end
        self._pipeline.add(MemoryDecayMiddleware())

        # 8. WorkRegimeAgent policy adaptation at epoch end
        self._pipeline.add(WorkRegimeAdaptMiddleware())

    def _make_context(self) -> MiddlewareContext:
        """Build a ``MiddlewareContext`` from current orchestrator state."""
        return MiddlewareContext(
            state=self.state,
            config=self.config,
            agents=self._agents,
            event_bus=self._event_bus,
            network=self.network,
            governance_engine=self.governance_engine,
            metrics_calculator=self.metrics_calculator,
            payoff_engine=self.payoff_engine,
            handler_registry=self._handler_registry,
            finalizer=self._finalizer,
        )

    # ===================================================================
    # Agent registration
    # ===================================================================

    def register_agent(self, agent: BaseAgent) -> AgentState:
        """Register an agent with the simulation."""
        if agent.agent_id in self._agents:
            raise ValueError(f"Agent {agent.agent_id} already registered")

        self._agents[agent.agent_id] = agent

        state = self.state.add_agent(
            agent_id=agent.agent_id,
            name=getattr(agent, "name", agent.agent_id),
            agent_type=agent.agent_type,
        )

        if self._spawn_tree is not None:
            self._spawn_tree.register_root(agent.agent_id)

        self._emit_event(
            Event(
                event_type=EventType.AGENT_CREATED,
                agent_id=agent.agent_id,
                payload={
                    "agent_type": agent.agent_type.value,
                    "name": getattr(agent, "name", agent.agent_id),
                    "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)
        if self.governance_engine is not None:
            self.governance_engine.set_collusion_agent_ids(agent_ids)
        if self._letta_lifecycle is not None:
            self._letta_lifecycle.start()
            for agent in self._agents.values():
                if hasattr(agent, "_lazy_init") and hasattr(agent, "_letta_config"):
                    agent._lazy_init(self._letta_lifecycle)

    # ===================================================================
    # Main simulation loop
    # ===================================================================

    def run(self) -> List[EpochMetrics]:
        """Run the full simulation."""
        # ---------------------------------------------------------------
        # Load prior memory from prior run(s) if graph_memory is enabled
        # ---------------------------------------------------------------
        if self._graph_memory is not None:
            prior_snapshots = self._graph_memory.load_all()
            for agent in self._agents.values():
                if agent.agent_id in prior_snapshots:
                    snapshot = prior_snapshots[agent.agent_id]
                    agent.load_prior_memory(snapshot)
                    logger.info(
                        f"Loaded prior memory for {agent.agent_id} from snapshot "
                        f"(trust priors from run={snapshot.run_id}, epoch={snapshot.epoch})"
                    )

        self._initialize_network()

        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,
                },
            )
        )

        for _epoch in range(self.config.n_epochs):
            epoch_metrics = self._run_epoch()
            self._epoch_metrics.append(epoch_metrics)
            for callback in self._on_epoch_end:
                callback(epoch_metrics)

        if self._letta_lifecycle is not None:
            self._letta_lifecycle.shutdown()

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

        # ---------------------------------------------------------------
        # Save memory snapshots at run end if graph_memory is enabled
        # ---------------------------------------------------------------
        if self._graph_memory is not None:
            run_id = self.config.scenario_id or "unknown"
            final_epoch = self.config.n_epochs - 1
            self._graph_memory.save_all(list(self._agents.values()), run_id, final_epoch)
            logger.info(
                f"Saved memory snapshots for {len(self._agents)} agents "
                f"(run={run_id}, epoch={final_epoch})"
            )

        return self._epoch_metrics

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

        # --- Epoch pre-hooks ---
        self._pipeline.on_epoch_start(ctx)

        # --- Steps ---
        for _step in range(self.config.steps_per_epoch):
            if self.state.is_paused:
                break
            self._run_step(ctx)
            self.state.advance_step()

        # --- Epoch post-hooks ---
        self._pipeline.on_epoch_end(ctx)

        # Update contract metrics ref
        if self._contract_mw is not None:
            self._last_contract_metrics = self._contract_mw.last_metrics

        metrics = self._compute_epoch_metrics()

        self._emit_event(
            Event(
                event_type=EventType.EPOCH_COMPLETED,
                payload=metrics.to_dict(),
                epoch=epoch_start,
            )
        )

        self.state.advance_epoch()
        return metrics

    def _run_step(self, ctx: Optional[MiddlewareContext] = None) -> None:
        """Run a single step within an epoch."""
        if ctx is None:
            ctx = self._make_context()
        self._pipeline.on_step_start(ctx)

        dropped = (
            self._perturbation_engine.get_dropped_agents()
            if self._perturbation_engine is not None
            else set()
        )

        eligible = self._scheduler.get_eligible(
            self._agents,
            self.state,
            governance_engine=self.governance_engine,
            dropped_agents=dropped,
        )

        for agent_id in eligible:
            agent = self._agents[agent_id]
            observation = self._obs_builder.build(agent_id)
            action = self._select_action(agent, observation)
            self._execute_action(action)

        self._resolve_pending_interactions()

    # ===================================================================
    # Action selection
    # ===================================================================

    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, no-any-return]
            return agent.act(observation)  # type: ignore[no-any-return]

        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,
        )

    # ===================================================================
    # Action execution pipeline
    # ===================================================================

    def _execute_action(self, action: Action) -> bool:
        """Execute an agent action via handler registry."""
        # --- Core actions (orchestrator-owned) ---
        core_result = self._handle_core_action(action)
        if core_result is not None:
            return core_result

        # --- Handler-dispatched actions ---
        if not isinstance(action.action_type, ActionType):
            return False

        handler = self._handler_registry.get_handler(action.action_type)
        if handler is None:
            return False

        try:
            result = handler.handle_action(action, self.state)
        except (RuntimeError, ValueError, TypeError, AttributeError):
            logger.debug(
                "Handler %s.handle_action failed",
                type(handler).__name__,
                exc_info=True,
            )
            return False

        if not result.success:
            return False

        if result.observables is None:
            return True

        # Standard proxy computation + interaction finalization
        v_hat, p = self.proxy_computer.compute_labels(result.observables)

        interaction_type = InteractionType.COLLABORATION
        if hasattr(result, "interaction_type") and isinstance(
            getattr(result, "interaction_type", None), InteractionType
        ):
            interaction_type = result.interaction_type

        tau = 0.0
        if hasattr(result, "tau") and result.tau != 0.0:
            tau = result.tau
        elif hasattr(result, "points") and result.points != 0.0:
            tau = -result.points

        ground_truth_val = getattr(result, "ground_truth", None)
        if ground_truth_val is None and hasattr(result, "submission"):
            submission = result.submission
            if submission is not None:
                ground_truth_val = -1 if submission.is_cheat else 1

        interaction = SoftInteraction(
            initiator=result.initiator_id,
            counterparty=result.counterparty_id,
            interaction_type=interaction_type,
            accepted=result.accepted,
            task_progress_delta=result.observables.task_progress_delta,
            rework_count=result.observables.rework_count,
            verifier_rejections=result.observables.verifier_rejections,
            tool_misuse_flags=result.observables.tool_misuse_flags,
            counterparty_engagement_delta=result.observables.counterparty_engagement_delta,
            v_hat=v_hat,
            p=p,
            tau=tau,
            metadata=result.metadata or {},
            **({"ground_truth": ground_truth_val} if ground_truth_val is not None else {}),
        )

        if self.contract_market is not None:
            interaction = self.contract_market.route_interaction(interaction)

        gov_effect, _, _ = self._finalize_interaction(interaction)

        try:
            handler.post_finalize(result, interaction, gov_effect, self.state)
        except (RuntimeError, ValueError, TypeError, AttributeError):
            logger.debug(
                "Handler %s.post_finalize failed",
                type(handler).__name__,
                exc_info=True,
            )

        return True

    def _handle_core_action(self, action: Action) -> Optional[bool]:
        """Handle NOOP and SPAWN_SUBAGENT — the only orchestrator-owned actions."""
        if action.action_type == ActionType.NOOP:
            return True
        if action.action_type == ActionType.SPAWN_SUBAGENT:
            return self._handle_spawn_subagent(action)
        return None

    # ===================================================================
    # Spawn
    # ===================================================================

    def _handle_spawn_subagent(self, action: Action) -> bool:
        """Handle a SPAWN_SUBAGENT action."""
        if self._spawn_tree is None:
            return False

        parent_id = action.agent_id
        parent_state = self.state.get_agent(parent_id)
        if parent_state is None:
            return False

        global_step = (
            self.state.current_epoch * self.config.steps_per_epoch
            + self.state.current_step
        )

        can, reason = self._spawn_tree.can_spawn(
            parent_id, global_step, parent_state.resources
        )
        if not can:
            self._emit_event(
                Event(
                    event_type=EventType.SPAWN_REJECTED,
                    agent_id=parent_id,
                    payload={"reason": reason},
                    epoch=self.state.current_epoch,
                    step=self.state.current_step,
                )
            )
            return False

        spawn_cfg = self._spawn_tree.config
        parent_state.update_resources(-spawn_cfg.spawn_cost)

        child_type_key = action.metadata.get("child_type")
        if not child_type_key:
            child_type_key = parent_state.agent_type.value
        child_config = action.metadata.get("child_config", {})

        from swarm.scenarios.loader import AGENT_TYPES

        agent_class = AGENT_TYPES.get(child_type_key)
        if agent_class is None:
            self._emit_event(
                Event(
                    event_type=EventType.SPAWN_REJECTED,
                    agent_id=parent_id,
                    payload={"reason": f"unknown_agent_type:{child_type_key}"},
                    epoch=self.state.current_epoch,
                    step=self.state.current_step,
                )
            )
            return False

        self._spawn_counter += 1
        child_id = f"{parent_id}_child{self._spawn_counter}"
        child_rng = random.Random((self.config.seed or 0) + self._spawn_counter)

        # Tierra-specific: mutate genome and split resources
        is_tierra = child_type_key == "tierra"
        child_initial_resources = spawn_cfg.initial_child_resources
        tierra_genome = None

        if is_tierra and action.metadata.get("genome"):
            from swarm.agents.tierra_agent import TierraGenome

            parent_genome = TierraGenome.from_dict(action.metadata["genome"])
            mutation_std = 0.05
            if self._tierra_handler is not None:
                mutation_std = self._tierra_handler.config.mutation_std
            tierra_genome = parent_genome.mutate(child_rng, mutation_std)

            share_frac = parent_genome.resource_share_fraction
            child_initial_resources = parent_state.resources * share_frac
            parent_state.update_resources(-child_initial_resources)

            child_agent = agent_class(  # type: ignore[call-arg]
                agent_id=child_id,
                name=child_id,
                config=child_config if child_config else None,
                rng=child_rng,
                genome=tierra_genome,
            )
            child_agent.generation = action.metadata.get("generation", 0)  # type: ignore[attr-defined]

            if self._tierra_handler is not None:
                self._tierra_handler.register_genome(child_id, tierra_genome.to_dict())
                self._tierra_handler._births += 1
        else:
            child_agent = agent_class(  # type: ignore[call-arg]
                agent_id=child_id,
                name=child_id,
                config=child_config if child_config else None,
                rng=child_rng,
            )

        self._agents[child_id] = child_agent

        inherited_rep = parent_state.reputation * spawn_cfg.reputation_inheritance_factor
        child_state = self.state.add_agent(
            agent_id=child_id,
            name=child_id,
            agent_type=child_agent.agent_type,
            initial_reputation=inherited_rep,
            initial_resources=child_initial_resources,
        )
        child_state.parent_id = parent_id

        self._spawn_tree.register_spawn(
            parent_id=parent_id,
            child_id=child_id,
            epoch=self.state.current_epoch,
            step=self.state.current_step,
            global_step=global_step,
        )

        if self.network is not None:
            self.network.add_node(child_id)
            self.network.add_edge(parent_id, child_id)

        self._emit_event(
            Event(
                event_type=EventType.AGENT_SPAWNED,
                agent_id=child_id,
                payload={
                    "parent_id": parent_id,
                    "child_type": child_type_key,
                    "depth": self._spawn_tree.get_depth(child_id),
                    "inherited_reputation": inherited_rep,
                    "initial_resources": spawn_cfg.initial_child_resources,
                    "spawn_cost": spawn_cfg.spawn_cost,
                },
                epoch=self.state.current_epoch,
                step=self.state.current_step,
            )
        )

        return True

    # ===================================================================
    # Interaction resolution
    # ===================================================================

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

        for proposal in proposals:
            counterparty_id = proposal.counterparty_id

            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._obs_builder.build(counterparty_id)

            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)

            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."""
        if self.contract_market is not None:
            observables = self._observable_generator.generate(
                proposal, accepted, self.state
            )
            v_hat, p = self.proxy_computer.compute_labels(observables)
            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),
                metadata=proposal.metadata,
            )
            interaction = self.contract_market.route_interaction(interaction)
            self._finalizer.finalize_interaction(interaction)
        else:
            self._finalizer.complete_interaction(proposal, accepted)

    def _finalize_interaction(
        self,
        interaction: SoftInteraction,
    ) -> Tuple[GovernanceEffect, float, float]:
        """Apply governance, compute payoffs, update state, and emit events."""
        return self._finalizer.finalize_interaction(interaction)

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

    # ===================================================================
    # Metrics
    # ===================================================================

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

        network_metrics = None
        if self.network is not None:
            network_metrics = self.network.get_metrics()

        capability_metrics = None
        if self.capability_analyzer is not None:
            capability_metrics = self.capability_analyzer.compute_metrics()

        security_report = None
        if self.governance_engine is not None:
            security_report = self.governance_engine.get_security_report()

        collusion_report = None
        if self.governance_engine is not None:
            collusion_report = self.governance_engine.get_collusion_report()

        spawn_metrics_dict = None
        if self._spawn_tree is not None:
            spawn_metrics_dict = {
                "total_spawned": self._spawn_tree.total_spawned,
                "max_depth": self._spawn_tree.max_tree_depth(),
                "depth_distribution": self._spawn_tree.depth_distribution(),
                "tree_sizes": self._spawn_tree.tree_size_distribution(),
            }

        contract_metrics_dict = None
        if self._last_contract_metrics is not None:
            contract_metrics_dict = self._last_contract_metrics.to_dict()

        if not interactions:
            return EpochMetrics(
                epoch=self.state.current_epoch,
                network_metrics=network_metrics,
                capability_metrics=capability_metrics,
                spawn_metrics=spawn_metrics_dict,
                security_report=security_report,
                collusion_report=collusion_report,
                contract_metrics=contract_metrics_dict,
            )

        accepted = [i for i in interactions if i.accepted]
        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,
            spawn_metrics=spawn_metrics_dict,
            security_report=security_report,
            collusion_report=collusion_report,
            contract_metrics=contract_metrics_dict,
        )

    # ===================================================================
    # Events
    # ===================================================================

    def _emit_event(self, event: Event) -> None:
        """Emit an event via the event bus."""
        self._event_bus.emit(event)

    def subscribe_events(self, callback: Callable[[Event], None]) -> None:
        """Register an external subscriber for all simulation events."""
        self._event_bus.subscribe(callback)

    # ===================================================================
    # Public API (preserved for backwards compatibility)
    # ===================================================================

    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()

    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."""
        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."""
        self._finalizer.apply_governance_effect(effect)

    def _update_reputation(self, agent_id: str, delta: float) -> None:
        """Update agent reputation."""
        self._finalizer._update_reputation(agent_id, delta)

    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)

    def get_network_metrics(self) -> Optional[Dict[str, float]]:
        """Get current network topology metrics."""
        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

    def get_spawn_tree(self) -> Optional[SpawnTree]:
        """Get the spawn tree for inspection."""
        return self._spawn_tree

    @property
    def adaptive_controller(self):
        """Get the adaptive governance controller."""
        return self._adaptive_controller

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

    def add_composite_task(self, task: CompositeTask) -> bool:
        """Add a composite task to the pool."""
        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."""
        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()

    # ===================================================================
    # 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."""
        self._initialize_network()

        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,
                },
            )
        )

        for _epoch in range(self.config.n_epochs):
            epoch_metrics = await self._run_epoch_async()
            self._epoch_metrics.append(epoch_metrics)
            for callback in self._on_epoch_end:
                callback(epoch_metrics)

        self._emit_event(
            Event(
                event_type=EventType.SIMULATION_ENDED,
                payload={
                    "total_epochs": self.config.n_epochs,
                    "final_metrics": self._epoch_metrics[-1].to_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
        ctx = self._make_context()

        self._pipeline.on_epoch_start(ctx)

        for _step in range(self.config.steps_per_epoch):
            if self.state.is_paused:
                break
            await self._run_step_async(ctx)
            self.state.advance_step()

        self._pipeline.on_epoch_end(ctx)

        if self._contract_mw is not None:
            self._last_contract_metrics = self._contract_mw.last_metrics

        metrics = self._compute_epoch_metrics()

        self._emit_event(
            Event(
                event_type=EventType.EPOCH_COMPLETED,
                payload=metrics.to_dict(),
                epoch=epoch_start,
            )
        )

        self.state.advance_epoch()
        return metrics

    async def _run_step_async(self, ctx: MiddlewareContext) -> None:
        """Run a single step asynchronously with concurrent LLM calls."""
        self._pipeline.on_step_start(ctx)

        if self._external_action_queue is not None:
            self._external_action_queue.reset_step()

        dropped = (
            self._perturbation_engine.get_dropped_agents()
            if self._perturbation_engine is not None
            else set()
        )

        agents_to_act = self._scheduler.get_eligible(
            self._agents,
            self.state,
            governance_engine=self.governance_engine,
            dropped_agents=dropped,
        )

        async def get_agent_action(agent_id: str) -> Tuple[str, Action]:
            agent = self._agents[agent_id]
            observation = self._obs_builder.build(agent_id)

            if agent.is_external and self._external_action_queue is not None:
                import dataclasses as _dc
                self._external_observations[agent_id] = _dc.asdict(observation)

                raw_action = await self._external_action_queue.wait_for_action(
                    agent_id
                )
                if raw_action is None:
                    return agent_id, Action(
                        agent_id=agent_id, action_type=ActionType.NOOP
                    )
                return agent_id, self._parse_external_action(agent_id, raw_action)

            action = await self._select_action_async(agent, observation)
            return agent_id, action

        tasks = [get_agent_action(agent_id) for agent_id in agents_to_act]
        results = await asyncio.gather(*tasks, return_exceptions=True)

        for result in results:
            if isinstance(result, Exception):
                continue
            agent_id, action = result  # type: ignore[misc]
            self._execute_action(action)

        await self._resolve_pending_interactions_async()

    # ===================================================================
    # External agent support
    # ===================================================================

    def set_external_action_queue(self, queue: Any) -> None:
        """Attach an external action queue for API-driven agents."""
        self._external_action_queue = queue

    def get_external_observations(self) -> Dict[str, Dict[str, Any]]:
        """Return the current external observation store."""
        return self._external_observations

    _API_ACTION_MAP: Dict[str, str] = {
        "accept": "accept_interaction",
        "reject": "reject_interaction",
        "propose": "propose_interaction",
        "counter": "propose_interaction",
    }

    def _parse_external_action(self, agent_id: str, raw: Dict) -> Action:
        """Convert a raw dict from the action queue into an ``Action``."""
        action_type_str = raw.get("action_type", "noop")
        action_type_str = self._API_ACTION_MAP.get(action_type_str, action_type_str)
        try:
            action_type = ActionType(action_type_str)
        except ValueError:
            action_type = ActionType.NOOP

        def _safe_str(val: Any, max_len: int = 256) -> str:
            if val is None:
                return ""
            if not isinstance(val, (str, int, float, bool)):
                return ""
            s = str(val)
            return s[:max_len]

        metadata = raw.get("metadata", {})
        if not isinstance(metadata, dict):
            metadata = {}

        return Action(
            agent_id=agent_id,
            action_type=action_type,
            target_id=_safe_str(raw.get("target_id")),
            counterparty_id=_safe_str(raw.get("counterparty_id")),
            content=_safe_str(raw.get("content"), max_len=4096),
            metadata=metadata,
        )

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

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

            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._obs_builder.build(counterparty_id)

            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),
            )

            if self._is_llm_agent(counterparty):
                accept = await counterparty.accept_interaction_async(
                    agent_proposal, observation
                )
            else:
                accept = counterparty.accept_interaction(agent_proposal, observation)

            return bool(accept)

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

        for proposal, result in zip(proposals, results, strict=False):
            if isinstance(result, Exception) or result is None:
                continue
            accept = bool(result)
            self.state.remove_proposal(proposal.proposal_id)
            self._complete_interaction(proposal, accepted=accept)

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

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

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

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

    # ===================================================================
    # Boundary Delegation
    # ===================================================================

    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."""
        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."""
        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."""
        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."""
        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."""
        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."""
        if self._boundary_handler is None:
            return None
        return self._boundary_handler.get_leakage_report()

    # ===================================================================
    # LLM Usage
    # ===================================================================

    def get_llm_usage_stats(self) -> Dict[str, Dict[str, Any]]:
        """Get LLM usage statistics for all LLM agents."""
        stats = {}
        for agent_id, agent in self._agents.items():
            if hasattr(agent, "get_usage_stats"):
                stats[agent_id] = agent.get_usage_stats()
        return stats

    # ===================================================================
    # Legacy compatibility shims
    # ===================================================================

    def _build_observation(self, agent_id: str) -> Observation:
        """Build observation for an agent."""
        return self._obs_builder.build(agent_id)

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

    def _get_eligible_agents(self) -> List[str]:
        """Return agents eligible to act this step."""
        dropped = (
            self._perturbation_engine.get_dropped_agents()
            if self._perturbation_engine is not None
            else set()
        )
        return self._scheduler.get_eligible(
            self._agents,
            self.state,
            governance_engine=self.governance_engine,
            dropped_agents=dropped,
        )

    def _get_agent_schedule(self) -> List[str]:
        """Get the order of agents for this step."""
        return self._scheduler._get_order(self._agents, self.state)

    def _update_adaptive_governance(self, include_behavioral: bool = False) -> None:
        """Update adaptive governance mode."""
        if self._gov_mw is not None:
            ctx = self._make_context()
            self._gov_mw._update_adaptive(ctx, include_behavioral=include_behavioral)

    def _apply_agent_memory_decay(self, epoch: int) -> None:
        """Apply memory decay to all agents."""
        for agent in self._agents.values():
            if hasattr(agent, "apply_memory_decay"):
                agent.apply_memory_decay(epoch)

    def _epoch_pre_hooks(self) -> None:
        """Shared epoch-start logic."""
        ctx = self._make_context()
        self._pipeline.on_epoch_start(ctx)

    def _epoch_post_hooks(self, epoch_start: int) -> EpochMetrics:
        """Shared epoch-end logic."""
        ctx = self._make_context()
        self._pipeline.on_epoch_end(ctx)

        if self._contract_mw is not None:
            self._last_contract_metrics = self._contract_mw.last_metrics

        metrics = self._compute_epoch_metrics()

        self._emit_event(
            Event(
                event_type=EventType.EPOCH_COMPLETED,
                payload=metrics.to_dict(),
                epoch=epoch_start,
            )
        )

        self.state.advance_epoch()
        return metrics

    def _step_preamble(self) -> None:
        """Shared step-start logic."""
        ctx = self._make_context()
        self._pipeline.on_step_start(ctx)

register_agent(agent)

Register an agent with the simulation.

Source code in swarm/core/orchestrator.py
def register_agent(self, agent: BaseAgent) -> AgentState:
    """Register an agent with the simulation."""
    if agent.agent_id in self._agents:
        raise ValueError(f"Agent {agent.agent_id} already registered")

    self._agents[agent.agent_id] = agent

    state = self.state.add_agent(
        agent_id=agent.agent_id,
        name=getattr(agent, "name", agent.agent_id),
        agent_type=agent.agent_type,
    )

    if self._spawn_tree is not None:
        self._spawn_tree.register_root(agent.agent_id)

    self._emit_event(
        Event(
            event_type=EventType.AGENT_CREATED,
            agent_id=agent.agent_id,
            payload={
                "agent_type": agent.agent_type.value,
                "name": getattr(agent, "name", agent.agent_id),
                "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.

Source code in swarm/core/orchestrator.py
def run(self) -> List[EpochMetrics]:
    """Run the full simulation."""
    # ---------------------------------------------------------------
    # Load prior memory from prior run(s) if graph_memory is enabled
    # ---------------------------------------------------------------
    if self._graph_memory is not None:
        prior_snapshots = self._graph_memory.load_all()
        for agent in self._agents.values():
            if agent.agent_id in prior_snapshots:
                snapshot = prior_snapshots[agent.agent_id]
                agent.load_prior_memory(snapshot)
                logger.info(
                    f"Loaded prior memory for {agent.agent_id} from snapshot "
                    f"(trust priors from run={snapshot.run_id}, epoch={snapshot.epoch})"
                )

    self._initialize_network()

    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,
            },
        )
    )

    for _epoch in range(self.config.n_epochs):
        epoch_metrics = self._run_epoch()
        self._epoch_metrics.append(epoch_metrics)
        for callback in self._on_epoch_end:
            callback(epoch_metrics)

    if self._letta_lifecycle is not None:
        self._letta_lifecycle.shutdown()

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

    # ---------------------------------------------------------------
    # Save memory snapshots at run end if graph_memory is enabled
    # ---------------------------------------------------------------
    if self._graph_memory is not None:
        run_id = self.config.scenario_id or "unknown"
        final_epoch = self.config.n_epochs - 1
        self._graph_memory.save_all(list(self._agents.values()), run_id, final_epoch)
        logger.info(
            f"Saved memory snapshots for {len(self._agents)} agents "
            f"(run={run_id}, epoch={final_epoch})"
        )

    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]

Raises:

Type Description
ValueError

If k <= 0 or k > 100 (extremely large values indicate potential bugs)

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]

    Raises:
        ValueError: If k <= 0 or k > 100 (extremely large values indicate potential bugs)
    """
    # Validate k parameter
    if k <= 0:
        raise ValueError(f"sigmoid_k must be positive, got {k}")
    if k > 100:
        raise ValueError(
            f"sigmoid_k is extremely large ({k}), which may indicate a bug. "
            "Values above 100 are rejected."
        )

    # Warn if v_hat is out of expected range [-1, +1]
    if v_hat < -1.0 or v_hat > 1.0:
        logger.warning(
            "v_hat out of expected range [-1, +1]: %.4f. "
            "Value will be clamped before sigmoid computation. "
            "This may indicate upstream bugs in proxy computation.",
            v_hat,
        )

    # Clamp v_hat to avoid numerical issues and warn if clamping occurs
    original_v_hat = v_hat
    v_hat = max(-10.0, min(10.0, v_hat))
    if v_hat != original_v_hat:
        logger.warning(
            "v_hat clamped from %.4f to %.4f in calibrated_sigmoid. "
            "This may indicate an upstream bug in proxy computation.",
            original_v_hat,
            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)

See also