# Orchestrator Implementation Plan — Improved

**Datum:** 21. 10. 2026  
**Stav:** Návrh k implementaci  
**Závisí na:** `.kilo/plans/CyberBrain26cil-031026-v2.md`, `src/cyberbrain26/orchestration/ptah_bridge.py`, `src/cyberbrain26/agents/orchestrator.py`, `src/cyberbrain26/model_layer/`

---

## Executive Summary

The CyberBrain26 codebase **already has a sophisticated orchestration system** (`PtahBridge` + agents + model layer + security plane). This plan **extends** it with:

1. **Subagent pattern with context isolation** (LangGraph-style)
2. **Pattern selection logic** (subagent/handoff/router/pipeline per task)
3. **Kilo integration** (Kilo as main orchestrator, PtahBridge as execution backend)
4. **Structured subagent output** with evidence refs
5. **Token budgets & context compaction**
6. **AWS Cedar 3-layer delegation security** (L1 Agent→Tool, L2 Agent→Agent, L3 Originating User)
7. **FreeAuto UX** for Kilo ("CyberBrain26 FreeAuto" mode)

---

## Existing Infrastructure (Do Not Duplicate)

| Component | Location | Capability |
|-----------|----------|------------|
| `PtahBridge` | `orchestration/ptah_bridge.py` | Roadmap/step execution, deps, retry, persistence |
| `BaseAgent` + 6 agents | `agents/orchestrator.py` | Fail-closed auth, AgentResult, bus communication |
| `ModelRouter` | `model_layer/router.py` | 6 strategies, circuit breaker, fallback, free-only |
| `RoleAssignmentStore` | `model_layer/role_assignment.py` | Main/backup models per role |
| `ModelIntelligence` | `model_layer/model_intelligence.py` | Discovery, validation, scoring pipeline |
| `PolicyEngine` + `PermissionGateway` | `security_plane/` | Policy evaluation, audit |
| `ApprovalManager` | `security_plane/approval.py` | Human approval with timeout |
| `AuthorizedExecutionService` | `execution_plane/` | Sandbox execution with re-verification |

---

## Gap Analysis (What's Missing)

| Requirement | Current State | Gap |
|-------------|---------------|-----|
| Subagent pattern (context isolation) | Roadmap steps share context | **Missing** - need isolated subagent contexts |
| Pattern selection | Fixed roadmap DAG | **Missing** - subagent/handoff/router/pipeline |
| LangGraph integration | Not used | **Missing** - preferred per architecture |
| Kilo as main orchestrator | PtahBridge is orchestrator | **Missing** - Kilo plugin/provider bridge |
| Structured subagent output | AgentResult (basic) | **Missing** - evidence refs, summaries, confidence |
| Token budgets per subagent | None | **Missing** |
| Context compaction | None | **Missing** |
| Delegation depth limits | None | **Missing** (need max 5 hops per Cedar) |
| Cheap router model vs specialist | Single router for all | **Missing** - separate router model |
| Human-in-loop handoffs | No interrupts | **Missing** |
| FreeAuto Kilo UX | Not integrated | **Missing** |

---

## Research-Backed Decisions (Q1–Q10)

| Q | Decision | Research Basis |
|---|----------|----------------|
| **Q1** Primary goal | Coordinate Planner/Supervisor/subagents per security chain | CyberBrain26 security chain + LangChain multi-agent patterns |
| **Q2** Default pattern | **Subagent** as default, switch to handoff/router/pipeline per task | LangChain: subagents for parallel domains; router for classification; handoff for multi-turn; pipeline for linear deps |
| **Q3** Delegation | Least privilege, audit trail, Cedar 3-layer | AWS Cedar blog (Jul 2026): L1 trust_score≥3, L2 depth≤5, L3 admin+MFA |
| **Q4** Critical approval | Independent Evaluator/Reviewer (no self-approval) | AGENTS.md Multi-Agent Rule + LangChain handoff contracts |
| **Q5** Long runs | Checkpoints + retry/backoff + circuit breaker | LangGraph checkpointing + HTN-Orchestrate rebuild + Microsoft AF |
| **Q6** Router model | Cheap model (gpt-4o-mini/gemini-flash/llama-3.2-1b) for routing; quality models for specialists | Uno-Orchestra, LangChain blog: router ≠ specialist |
| **Q7** Subagent output | Structured summary + evidence refs + artifacts (max 2k tokens) | Claude Code Guide: "output = summary"; SourceShift: typed output with provenance |
| **Q8** No self-eval | Separate Implementor/Reviewer/Evaluator roles | AGENTS.md Multi-Agent Rule + Principal-Agent problem research |
| **Q9** Swappable orchestrator | Interface→Adapter→Provider (LangGraphAdapter first) | Extension Layer rule + Architectural Rule |
| **Q10** Priority | Security, auditability, human oversight | Security-First + Human Oversight principles |

---

## Implementation Plan

### Phase 1: Core Subagent Types & Interface (Week 1)

**Goal:** Define the subagent abstraction that works with existing PtahBridge.

**Files to create:**
```
src/cyberbrain26/orchestration/
├── subagent/
│   ├── __init__.py
│   ├── types.py              # SubagentSpec, SubagentOutput, ContextMode, DelegationCaps
│   ├── interface.py          # SubagentProtocol (invoke, get_state, checkpoint)
│   ├── context.py            # Context isolation, token budget, compaction
│   └── registry.py           # SubagentRegistry (role → factory)
```

**Key types:**
```python
@dataclass
class SubagentSpec:
    role: str                          # planner, coder, evaluator, etc.
    pattern: PatternType               # SUBAGENT, HANDOFF, ROUTER, PIPELINE
    tools_whitelist: list[str]
    context_mode: ContextMode          # ISOLATED, FORK, SHARED
    token_budget: int                  # hard limit
    timeout_seconds: int
    trust_level: TrustLevel
    delegation_caps: DelegationCaps    # max_depth, max_children
    model_assignment: ModelAssignment  # from RoleAssignmentStore

@dataclass
class SubagentOutput:
    summary: str                       # ≤ 2000 tokens
    evidence_refs: list[EvidenceRef]   # provenance
    artifacts: list[ArtifactRef]
    confidence: float                  # 0.0–1.0
    requires_human_review: bool
    obstacles: list[str]               # workarounds discovered
```

**Integration:** `PtahBridge.execute_step()` → if step.role has SubagentSpec → delegate to `SubagentRunner` instead of direct agent call.

---

### Phase 2: LangGraph Adapter (Week 1–2)

**Goal:** Implement `LangGraphSubagentRunner` implementing `SubagentProtocol`.

**Files:**
```
src/cyberbrain26/orchestration/subagent/
├── langgraph_runner.py      # LangGraph implementation
├── patterns/
│   ├── __init__.py
│   ├── subagent.py          # Supervisor → parallel Send() tools
│   ├── handoff.py           # interrupt() / resume() for human-in-loop
│   ├── router.py            # Cheap model classification → dispatch
│   └── pipeline.py          # Sequential StateGraph edges
```

**Key implementation details:**
- **Subagent pattern:** Main agent wraps subagents as `@tool` functions (per LangChain migration guide)
- **Context isolation:** Each subagent gets fresh `StateGraph` with own checkpointer
- **Token budget:** Enforced in node callbacks via `BudgetEnforcer`
- **Compaction:** Turn-boundary hook triggers `ContextCompactor` at 90% threshold
- **Structured output:** Subagent tool returns `SubagentOutput` (not raw messages)

---

### Phase 3: Pattern Selection Engine (Week 2)

**File:** `src/cyberbrain26/orchestration/pattern_selector.py`

```python
class PatternSelector:
    """Select orchestration pattern based on task analysis."""
    
    def select(self, task: TaskSpec) -> PatternType:
        # Router pattern: simple classification → single specialist
        if task.is_classification and not task.needs_parallel:
            return PatternType.ROUTER
        
        # Handoff pattern: multi-turn with user, dynamic specialist
        if task.requires_human_interaction and task.specialist_emerges_dynamically:
            return PatternType.HANDOFF
        
        # Pipeline pattern: linear dependencies, deterministic stages
        if task.has_linear_dependencies and not task.needs_parallel:
            return PatternType.PIPELINE
        
        # Default: Subagent pattern (parallel domains, context isolation)
        return PatternType.SUBAGENT
```

**Integration:** `PtahBridge.create_roadmap()` → analyze steps → assign `PatternType` per step group → instantiate appropriate runner.

---

### Phase 4: Cedar 3-Layer Delegation Security (Week 2–3)

**Files:**
```
src/cyberbrain26/orchestration/security/
├── __init__.py
├── cedar_engine.py          # Lightweight Cedar evaluator (or py-cedar binding)
├── delegation_gate.py       # Three-layer check
├── delegation_token.py      # HMAC-signed delegation context
└── trust_levels.py          # TrustLevel enum (1-5), lifecycle stages
```

**Three-layer check (per AWS Cedar blog Jul 2026):**

```python
class DelegationGate:
    async def check(self, delegation: DelegationRequest) -> PolicyDecision:
        # L1: Agent → Tool
        if not self._check_layer1(delegation.agent, delegation.tool):
            return DENY("L1: insufficient trust_score/namespace/lifecycle")
        
        # L2: Agent → Agent delegation
        if not self._check_layer2(delegation.from_agent, delegation.to_agent, 
                                   delegation.requested_caps, delegation.delegation_depth):
            return DENY("L2: depth>5 or caps not subset")
        
        # L3: Originating User authorization
        if delegation.is_high_risk:
            if not self._check_layer3(delegation.originating_user, delegation.delegation_depth):
                return DENY("L3: requires admin+MFA, depth≤2")
        
        return PERMIT
```

**Delegation token (HMAC-signed, per AWS sample):**
```python
@dataclass
class DelegationToken:
    originating_user: UserContext
    delegation_chain: list[DelegationHop]  # each with chain_hash
    granted_caps: set[Capability]
    expires_at: float
    chain_hash: str  # SHA-256 of previous hop
    
    def verify_integrity(self) -> bool:
        # Verify HMAC chain from origin to current hop
        ...
```

**Integration:** `SubagentRunner.invoke()` → `DelegationGate.check()` before spawning subagent.

---

### Phase 5: Token Budgets & Context Compaction (Week 3)

**Files:**
```
src/cyberbrain26/orchestration/subagent/
├── budget.py                # BudgetEnforcer, TokenCounter
├── compaction.py            # ContextCompactor (rolling summary, head/tail truncate)
└── lifecycle.py             # Spawn limits (max_depth=3, max_children=5)
```

**Budget enforcement:**
```python
class BudgetEnforcer:
    def check_and_reserve(self, spec: SubagentSpec, estimated: int) -> Reservation:
        if estimated > spec.token_budget:
            raise BudgetExceeded(f"estimated {estimated} > budget {spec.token_budget}")
        return Reservation(spec.token_budget - estimated)
    
    def record_usage(self, reservation: Reservation, actual: int) -> None:
        if actual > reservation.granted:
            # Log overrun but don't fail (soft limit)
            logger.warning("Token overrun: %d > %d", actual, reservation.granted)
```

**Compaction (per SourceShift blog):**
```python
class ContextCompactor:
    def compact(self, messages: list[Message], threshold: float = 0.9) -> list[Message]:
        if self._token_count(messages) < threshold * MAX_CONTEXT:
            return messages
        
        # Level 1: Rolling summary (keep last N turns verbatim)
        # Level 2: LLM condensation (if model available)
        # Level 3: Head/tail truncate (60/40 split with omission marker)
        ...
```

**Spawn limits (per comis.ai):**
- `max_spawn_depth = 3` (parent → child → grandchild)
- `max_children_per_agent = 5`
- Pipeline nodes bypass children limit but respect depth limit

---

### Phase 6: Kilo Integration — "CyberBrain26 FreeAuto" (Week 3–4)

**Goal:** Kilo as main orchestrator; CyberBrain26 as backend provider.

**Files:**
```
src/cyberbrain26/kilo_integration/
├── __init__.py
├── freeauto_provider.py     # Kilo dynamic model provider
├── orchestrator_bridge.py   # Kilo task → PtahBridge roadmap
├── subagent_definitions.py  # .kilo/agents/ custom subagents
└── egress_sanitizer.py      # Anonymization before model calls
```

**FreeAuto Provider (per architecture):**
```python
class CyberBrain26FreeAutoProvider:
    """Kilo provider that routes to role-specific models via ModelRouter."""
    
    async def complete(self, messages, role: str, **kwargs):
        assignment = RoleAssignmentStore.get(role)
        model_ref = assignment.select_for_role(role)
        route = ModelRouter.route(model_id=model_ref.model_id, free_only=True)
        return await ProviderRegistry.call(route.provider, route.model_id, messages)
```

**Kilo subagent definitions (`.kilo/agents/`):**
```yaml
# .kilo/agents/cyberbrain26-planner.yaml
name: cyberbrain26-planner
role: planner
tools: [read, write, glob, task]
model: cyberbrain26-freeauto:planner
```

**Orchestrator Bridge:**
```python
class KiloOrchestratorBridge:
    """Translate Kilo task → PtahBridge roadmap → subagent execution."""
    
    async def execute_kilo_task(self, kilo_task: KiloTask) -> KiloResult:
        # 1. PlannerAgent creates TaskDAG with SubagentSpecs
        roadmap = await self.planner.create_roadmap(kilo_task.goal)
        
        # 2. PatternSelector assigns PatternType per step group
        roadmap = self.pattern_selector.annotate(roadmap)
        
        # 3. Execute via PtahBridge (with subagent runners)
        result = await self.ptah_bridge.execute_roadmap(roadmap.id)
        
        # 4. Aggregate SubagentOutputs → KiloResult
        return self._aggregate_results(result)
```

---

### Phase 7: Testing & Validation (Week 4)

**Test matrix:**

| Test | Coverage |
|------|----------|
| `test_subagent_isolation.py` | Context isolation, token budget, structured output |
| `test_pattern_selection.py` | Router/handoff/pipeline/subagent selection logic |
| `test_cedar_delegation.py` | L1/L2/L3 allow/deny, HMAC chain verification |
| `test_compaction.py` | Rolling summary, LLM condensation, head/tail fallback |
| `test_spawn_limits.py` | Depth=3, children=5 enforcement |
| `test_kilo_freeauto.py` | Role-specific routing, free-only, fallback |
| `test_e2e_minimal_flow.py` | F2: goal → plan → approve → delegate → tool → verify → audit |
| `test_recovery.py` | Crash mid-subagent → checkpoint resume → idempotency |

**Gates:**
- **Gate 1:** All unit tests pass, mypy/ruff clean
- **Gate 2:** E2E minimal flow reproduces with audit log
- **Gate 3:** Security Reviewer agent validates: delegation gates, least privilege, no silent fallback

---

## Open Decisions (Need Owner Input)

| # | Decision | Options | Recommendation |
|---|----------|---------|----------------|
| 1 | Cedar implementation | `py-cedar` (Rust binding) vs pure Python lightweight | **Lightweight Python** for F1–F3; `py-cedar` in F6 |
| 2 | Checkpoint storage | SQLite (current) vs Redis | **SQLite** for F1–F3; Redis adapter in F6 |
| 3 | Human approval UI | Kilo CLI prompt / VSCodium notification / Telegram | **CLI + VSCodium** for F1/F2; Telegram in mobile rev (R1) |
| 4 | Router model default | Fixed ID (`gpt-4o-mini`) vs dynamic from FreeAuto catalog | **Dynamic from FreeAuto** (role: `router`) |
| 5 | Max concurrent subagents | CPU formula vs fixed config | **`min(8, cpu_count * 2)`** with task override |

---

## Migration Path (Non-Breaking)

1. **Phase 1–2:** Add subagent types alongside existing `RoadmapStep`; `PtahBridge` routes to subagent runner when `SubagentSpec` present
2. **Phase 3:** PatternSelector annotates existing roadmaps; no API change
3. **Phase 4:** DelegationGate wraps existing `PermissionGateway`; additive
4. **Phase 5:** BudgetEnforcer hooks into `AuthorizedExecutionService`; opt-in via `SubagentSpec.token_budget`
5. **Phase 6:** Kilo provider registers as `cyberbrain26-freeauto`; opt-in via Kilo config
6. **Phase 7:** Tests validate both old (roadmap) and new (subagent) paths

---

## Risk Mitigation

| Risk | Mitigation |
|------|------------|
| LangGraph API changes | Adapter pattern, contract tests, pin version |
| Context overflow | Hard 90% limit, 3-level compaction, degraded mode |
| Delegation recursion | Hard depth=3, children=5 limits in spawn primitive |
| Cost runaway | Per-task hard budget, circuit breaker, free_only pause |
| Security bypass | Fail-closed default, integration test per layer |
| Checkpoint corruption | SHA-256 integrity, WAL mode, pre-migration backup |
| Model provider outage | 2–3 backups per role, graceful degradation |

---

## Next Step

Owner approval on **5 open decisions** → proceed to **Phase 1 implementation** (Core Subagent Types & Interface).