# Group Topologies

TnsAI.Coordination provides 8 group topologies for structuring multi-agent collaboration. Each topology has a dedicated builder and follows the lifecycle: create -> start -> execute -> stop.

**Pick the topology from the task, not from an org chart.** See
[Topology selection](topology-selection.md) before `Team.builder()` —
`team`, `hierarchy`, and `pipeline` are the wrong default for novel
problem solving.

## Team

A Team is the most common topology. It groups agents by role (lead, member, expert, reviewer) and executes tasks using a configurable formation (parallel, sequential, hierarchical, etc.). Think of it like organizing a project team where each person has a defined responsibility.

### TeamRole

Each agent in a team is assigned a role that determines its authority level and whether it actively participates in task execution.

| Role | Authority | Participates | Description |
|---|---|---|---|
| `LEAD` | Yes | Yes | Coordinates and delegates, final decision authority |
| `CO_LEAD` | Yes | Yes | Assists lead, takes over if lead unavailable |
| `MEMBER` | No | Yes | Executes assigned tasks |
| `EXPERT` | No | Yes | Subject matter expert, consulted for specialized knowledge |
| `REVIEWER` | No | Yes | Validates output, quality control |
| `OBSERVER` | No | No | Monitors but does not participate |
| `FACILITATOR` | Yes | Yes | Coordinates discussions (used in DEBATE formation) |

### TeamFormation

The formation controls how the team executes its work. For example, `PARALLEL` runs all members at once for speed, while `SEQUENTIAL` passes context from one member to the next like a relay.

| Formation | Description | Requires Lead | Ordered |
|---|---|---|---|
| `PARALLEL` | All members work simultaneously | No | No |
| `SEQUENTIAL` | Members work in sequence, passing context | No | Yes |
| `HIERARCHICAL` | Lead coordinates and delegates | Yes | No |
| `ADAPTIVE` | Adapts based on task complexity | No | No |
| `DEBATE` | Members discuss and debate to consensus | No | No |
| `ROUND_ROBIN` | Members take turns adding perspective | No | Yes |

### Builder

Use the fluent builder to create a team by specifying its name, mission, formation, and members with their roles.

```java
Team team = Team.builder()
    .name("Analysis Team")
    .mission("Analyze customer data and produce insights")
    .timeout(Duration.ofMinutes(30))
    .formation(TeamFormation.PARALLEL)
    .lead(coordinatorAgent)
    .member(analystAgent, TeamRole.EXPERT)
    .member(writerAgent, TeamRole.MEMBER)
    .member(reviewerAgent, TeamRole.REVIEWER)
    .autoStart(true)
    .build();
```

When `HIERARCHICAL` formation is used and no `LEAD` is explicitly set, the first member is auto-promoted.

## Pipeline

A Pipeline processes data through a series of stages in strict order, where each stage's output becomes the next stage's input. This is ideal for ETL (extract-transform-load) workflows or any process with a fixed sequence of steps. Includes per-stage metrics tracking.

```java
PipelineOrganization pipeline = PipelineOrganization.builder()
    .name("ETL Pipeline")
    .addStage("extract", extractorAgent)
    .addStage("transform", transformerAgent)
    .addStage("validate", validatorAgent)
    .addStage("load", loaderAgent)
    .autoStart(true)
    .build();
```

### Stage Record

A stage represents one step in the pipeline, linking a name to an agent. Each stage is a `record Stage(String name, String agentId, int index, UnaryOperator<String> transformFunction)`. The optional `transformFunction` preprocesses input before the agent sees it.

### PipelineMetrics

The pipeline automatically tracks how long each stage takes, how often it runs, and how often it fails. This helps you identify bottlenecks in your processing chain.

```java
PipelineMetrics metrics = pipeline.getMetrics();

// Per-stage stats
Optional<Duration> avgDuration = metrics.getAverageDuration("transform");
int executions = metrics.getExecutionCount("transform");
int failures = metrics.getFailureCount("transform");

// Bottleneck detection
Optional<String> bottleneck = metrics.getBottleneck(); // stage with highest avg duration

// Full summary
Map<String, String> summary = metrics.getSummary();
// {"extract": "executions=10, failures=0, avgMs=250", ...}
```

## HubSpoke

In a HubSpoke topology, one central "hub" agent distributes tasks to multiple "spoke" agents that do the actual work. This is useful when you have a coordinator that needs to fan out work to a pool of workers. The hub distributes tasks to spoke agents using configurable load balancing.

```java
HubSpoke hs = HubSpoke.builder()
    .name("Task Distributor")
    .hub(coordinatorAgent)
    .spoke(worker1)
    .spoke(worker2)
    .spoke(worker3)
    .loadBalancing(LoadBalancer.Strategy.LEAST_LOADED)
    .autoStart(true)
    .build();
```

### LoadBalancer Strategies

The load balancer decides which spoke agent gets the next task. Choose the strategy that best fits your workload pattern.

| Strategy | Description |
|---|---|
| `ROUND_ROBIN` | Cycles through spokes in order |
| `LEAST_LOADED` | Picks spoke with fewest active tasks |
| `RANDOM` | Random spoke selection |

The `LoadBalancer` tracks active task counts per agent via `recordTaskAssigned()` and `recordTaskCompleted()`.

## Hierarchy

A Hierarchy models a tree-structured organization chart where tasks flow downward through delegation and issues flow upward through escalation. This is useful for modeling management structures or any scenario where agents have parent-child reporting relationships.

```java
Hierarchy hierarchy = Hierarchy.builder()
    .name("Engineering Org")
    .root(ctoAgent)
    .member(ctoAgent, teamLead1)
    .member(ctoAgent, teamLead2)
    .member(teamLead1, dev1)
    .member(teamLead1, dev2)
    .member(teamLead2, dev3)
    .autoStart(true)
    .build();
```

### DelegationChain

The `DelegationChain` records the history of who delegated what to whom, and who escalated issues back up the chain. This provides an audit trail for task flow through delegation and escalation events.

```java
DelegationChain chain = hierarchy.getDelegationChain();
chain.record("cto", "team-lead-1", "Review PR #42", DelegationChain.Type.DELEGATION);
chain.record("dev-1", "team-lead-1", "Need architecture review", DelegationChain.Type.ESCALATION);

List<DelegationChain.Entry> entries = chain.getEntries();
// Each entry: fromAgentId, toAgentId, task, type, timestamp
```

## Swarm

A Swarm is a decentralized topology inspired by biological swarm intelligence (like ant colonies or bird flocks). Instead of a central coordinator, agents communicate indirectly through "pheromones" and local neighbor interactions to solve problems collectively.

```java
Swarm swarm = Swarm.builder()
    .name("Explorer Swarm")
    .behavior(SwarmBehavior.EXPLORATION)
    .intelligence(SwarmIntelligence.antColony(0.5, 0.3))
    .neighborDetection(NeighborDetection.random())
    .neighborRadius(5)
    .pheromoneDecay(0.15)
    .add(agent1, agent2, agent3, agent4, agent5)
    .build();
```

### SwarmBehavior

The behavior determines how swarm agents interact with each other and their environment. Different behaviors suit different problem types.

| Behavior | Uses Pheromones | Requires Neighbors | Best For |
|---|---|---|---|
| `EXPLORATION` | Yes | No | Information gathering, search |
| `FORAGING` | Yes | Yes | Resource collection, optimization |
| `FLOCKING` | No | Yes | Coordinated movement |
| `AGGREGATION` | Yes | Yes | Consensus building, clustering |
| `TASK_ALLOCATION` | No | No | Division of labor |
| `DIFFUSION` | No | Yes | Distributed computation |
| `QUORUM_SENSING` | No | Yes | Collective decision making |

### SwarmIntelligence

The swarm intelligence algorithm determines how individual agent results are combined into a collective answer. TnsAI provides several built-in algorithms:

```java
SwarmIntelligence.voting()              // Simple voting, first complete solution wins
SwarmIntelligence.consensus()           // Weighted averaging (max 10 iterations)
SwarmIntelligence.bestSelection()       // Best-of-N based on quality scores
SwarmIntelligence.antColony(0.5, 0.3)   // ACO with pheromoneWeight and explorationRate
SwarmIntelligence.iterativeRefinement() // Each agent improves on previous (max 5 iterations)
```

### PheromoneType

Pheromones are signals that agents leave behind to communicate indirectly with other agents. Different pheromone types convey different meanings.

| Type | Default Intensity | Purpose |
|---|---|---|
| `ATTRACTION` | 1.0 | Marks interesting locations |
| `REPULSION` | 0.8 | Marks areas to avoid |
| `TRAIL` | 0.9 | Path markers for ACO |
| `COMPLETION` | 0.5 | Prevents redundant work |
| `RECRUITMENT` | 1.2 | Calls for help |
| `WARNING` | 0.7 | Signals potential issues |
| `QUALITY` | 1.0 | Indicates solution quality |
| `CUSTOM` | 1.0 | User-defined |

## Coalition

A Coalition is a temporary alliance of agents formed around a specific goal. Unlike a permanent team, a coalition forms dynamically, executes a task, distributes rewards based on each member's contribution, and then dissolves. This is useful when different tasks need different combinations of agents.

```java
Coalition coalition = Coalition.builder()
    .goal("Complete market analysis")
    .formation(CoalitionFormation.CAPABILITY_BASED)
    .rewardDistribution(RewardDistribution.SHAPLEY)
    .coalitionValue(100.0)
    .minMembers(2)
    .maxMembers(5)
    .add(agent1, agent2, agent3)
    .autoNegotiate(true)
    .build();
```

### CoalitionFormation

The formation strategy determines how agents are selected to join the coalition. Some strategies let agents volunteer, while others pick agents based on capabilities or reputation.

| Formation | Selection-Based | Description |
|---|---|---|
| `VOLUNTARY` | No | Agents choose to participate |
| `CAPABILITY_BASED` | Yes | Selected by matching capabilities |
| `REPUTATION_BASED` | Yes | Selected by past performance |
| `AUCTION` | No | Agents bid for participation |
| `RANDOM` | No | Random selection from pool |
| `INVITATION` | Yes | Coordinator invites specific agents |
| `MERIT_BASED` | Yes | Combined capability + reputation score |

### RewardDistribution

After the coalition completes its goal, rewards are distributed among members. The strategy determines how fairly (or competitively) the total reward is split.

| Strategy | Description |
|---|---|
| `EQUAL` | Same share for all members |
| `PROPORTIONAL` | Based on contribution ratio |
| `SHAPLEY` | Fair division based on marginal contribution to all sub-coalitions |
| `NUCLEOLUS` | Minimizes maximum dissatisfaction (10% floor + 90% proportional) |
| `PERFORMANCE_BASED` | Based on task performance quality |
| `SENIORITY_BASED` | Higher share for earlier joiners |
| `WINNER_TAKE_ALL` | Best performer gets 70%, rest share 30% |

```java
Map<String, Double> contributions = Map.of("agent-1", 40.0, "agent-2", 35.0, "agent-3", 25.0);
Map<String, Double> rewards = RewardDistribution.SHAPLEY.calculate(100.0, contributions);
```

## Matrix

A Matrix topology models a dual-reporting structure where each agent can belong to multiple groups simultaneously. For example, a developer agent might belong to both the "Engineering" dimension (reporting to an engineering lead) and the "Product-A" dimension (reporting to a product lead). This mirrors how real-world matrix organizations work.

```java
MatrixOrganization matrix = MatrixOrganization.builder()
    .name("Product Org")
    .member(dev1)
    .member(dev2)
    .member(engLead)
    .member(productLead)
    .assign(dev1, "Engineering", engLead)
    .assign(dev1, "Product-A", productLead)
    .assign(dev2, "Engineering", engLead)
    .assign(dev2, "Product-B", productLead)
    .autoStart(true)
    .build();
```

Agents can be assigned to a dimension with or without a lead: `.assign(agent, "QA")` omits the lead parameter.

## NetworkMesh

A NetworkMesh is a peer-to-peer topology where agents connect directly to each other without a central coordinator. The mesh shape (full, partial, ring, or star) determines which agents can communicate directly.

```java
NetworkMesh mesh = NetworkMesh.builder()
    .name("Agent Network")
    .topology(Topology.FULL_MESH)
    .add(agent1, agent2, agent3, agent4)
    .autoStart(true)
    .build();
```

### Topology

The topology shape determines the connection pattern between agents in the mesh.

| Topology | Description |
|---|---|
| `FULL_MESH` | Every agent connected to every other |
| `PARTIAL_MESH` | Selective peer connections |
| `RING` | Circular chain |
| `STAR` | One central agent connected to all others |

After `build()`, `initializeTopology()` is called automatically to wire up connections based on the chosen topology.
