# MARSYS Framework Architecture Overview

## 1. System Context
MARSYS (Multi-Agent Coordination System) is a framework for orchestrating multiple AI agents to solve complex tasks. It addresses the multi-agent coordination problem by providing a centralized execution engine that manages dynamic branching, parallelism, convergence, validation, and routing across a topology of agents.

Primary actors:
- Developers define topologies and agents.
- The system executes agent workflows, coordinating tools and responses.
- End users receive final responses (optionally via User nodes in the topology).

## 2. High-Level Architecture
```mermaid
flowchart TD
  A[Orchestra.run/execute] --> B[TopologyAnalyzer]
  B --> C[TopologyGraph]
  A --> D[ValidationProcessor]
  A --> E[BranchExecutor]
  A --> F[DynamicBranchSpawner]
  E --> G[StepExecutor]
  G --> H[BaseAgent._run]
  E --> D
  F -->|execute_branch| E
  E -->|requests new branches| F
```

The execution flow centers on the Orchestra coordinating branch execution. BranchExecutor performs per-branch logic and calls StepExecutor, which invokes the agent's pure `_run()` method. ValidationProcessor parses/validates responses, and DynamicBranchSpawner creates branches at divergence points and handles convergence.

## 3. Core Components
| Component | Location | Purpose | Criticality |
|-----------|----------|---------|-------------|
| Orchestra | `src/marsys/coordination/orchestra.py` | Orchestration facade; wires topology, validation, branching, and execution | TRUNK-CRITICAL |
| BranchExecutor | `src/marsys/coordination/execution/branch_executor.py` | Executes a single branch lifecycle and applies validation/routing | TRUNK-CRITICAL |
| DynamicBranchSpawner | `src/marsys/coordination/execution/branch_spawner.py` | Creates branches at divergence points; manages convergence | TRUNK-CRITICAL |
| ValidationProcessor | `src/marsys/coordination/validation/response_validator.py` | Central response parsing and action validation | TRUNK-CRITICAL |
| TopologyGraph | `src/marsys/coordination/topology/graph.py` | Runtime graph for routing/branching permissions | TRUNK-CRITICAL |
| StepExecutor | `src/marsys/coordination/execution/step_executor.py` | Stateless single-step agent execution and tool handling | TRUNK-STABLE |

## 4. Execution Flow
1. `Orchestra.run()` builds or accepts an `ExecutionConfig`, creates an Orchestra instance, and calls `execute()`.
2. `execute()` converts input topology into canonical `Topology`, analyzes it via `TopologyAnalyzer`, and builds a `TopologyGraph`.
3. Orchestra initializes per-run components: `ValidationProcessor`, `Router`, `BranchExecutor`, `DynamicBranchSpawner`, and rules engine.
4. `_execute_with_dynamic_branching()` creates initial branches for entry agents and starts `BranchExecutor.execute_branch()` tasks.
5. `BranchExecutor` loops over steps within a branch, calling `StepExecutor.execute_step()` for each agent step.
6. `StepExecutor` calls the agent's pure `_run()` method, handles tool execution, and returns a `StepResult`.
7. `BranchExecutor` passes the agent response to `ValidationProcessor.process_response()` to obtain structured routing decisions.
8. When an agent completes, Orchestra calls `DynamicBranchSpawner.handle_agent_completion()` to spawn new branches at divergence points or parallel invocations.
9. `DynamicBranchSpawner.check_synchronization_points()` determines when convergence criteria are met and resumes parent/continuation branches.
10. Orchestra aggregates `BranchResult` objects into an `OrchestraResult`, emits status events, and performs auto-cleanup.

## 5. Key Abstractions
- **Branch**: `ExecutionBranch` represents an independent execution context with its own `BranchTopology` and `BranchState` (`coordination/branches/types.py`).
- **Step**: A `StepResult` captures the outcome of a single agent step, including validation-derived routing fields.
- **Topology**: The canonical `Topology` defines nodes/edges; `TopologyGraph` provides runtime adjacency, divergence, and convergence analysis.
- **Agent**: `BaseAgent` (and `Agent`) implement pure `_run()` logic and tool schemas; orchestration is handled externally.
- **Model**: `BaseAPIModel`/`BaseLocalModel` provide unified model invocation via adapter patterns.

## 6. Module Boundaries
| Module | Responsible For | NOT Responsible For |
|--------|-----------------|---------------------|
| `coordination/` | Orchestration, branching, routing, validation, topology execution | Agent reasoning logic, provider API calls |
| `agents/` | Agent definitions, pure `_run()` logic, tools schema, memory policy | Parsing responses into actions, tool execution, routing |
| `environment/` | Tools and environment interfaces (bash, browser, file ops) | Orchestration, validation, topology decisions |
| `models/` | Provider adapters, model invocation, response harmonization | Routing, branching, coordination policies |

## 7. Extension Points
- **Add new agents**: Create a subclass of `BaseAgent`/`Agent` in `src/marsys/agents/`, implement `_run()`, and register via `AgentRegistry`.
- **Add response formats**: Implement a `BaseResponseFormat` and `ResponseProcessor`, then register via `register_format()` in `coordination/formats/registry.py`.
- **Add topology patterns**: Extend `PatternConfig` in `coordination/topology/patterns.py` or add converters in `coordination/topology/converters/`.
- **Add model providers**: Implement a new adapter and register it in `ProviderAdapterFactory` (`models/models.py`).
