Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

42.7 KB
Raw Blame
"""
ai.autonomous_planner - LLM-Powered Attack Chain Orchestration

Reads all campaign context (artifacts, credentials, findings, failed modules,
network topology) and sends to an LLM API to dynamically plan the next attack
steps. Returns a structured ExecutionPlan that can be fed directly into
engine.run_plan().

This module connects all existing ARES building blocks:
  GoalEngine     → goal definition and backward chaining
  AttackGraph    → shortest path analysis
  KnowledgeBase  → success rates per technique
  ArtifactStore  → discovered hosts, users, hashes
  CredentialVault → available credentials with privilege scores
  ModuleChain    → execution of the AI-generated plan

LLM operates in SUGGEST mode (not autonomous executor) - every plan
requires operator review before execution unless auto_approve=True.

MITRE: T1591 (Gather Victim Org Info - context aggregation)
OPSEC: LOCAL (LLM API call only, no direct target network contact)

Supported LLM backends:
  - claude    (Anthropic Claude - default)
  - openai    (OpenAI GPT-4)
  - local     (Ollama local LLM)

Note: LLM API key must be set in environment:
  ANTHROPIC_API_KEY  - for Claude
  OPENAI_API_KEY     - for OpenAI GPT
"""
from __future__ import annotations

import abc
import asyncio
import json
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any

from ares.core.campaign import Severity
from ares.core.logger import audit, get_logger
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, ModuleResult, OpsecLevel
from ares.modules.params import AIPlannerParams
from ares.sdk import (
    CircuitBreaker,
    EvidenceRecord,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

if TYPE_CHECKING:
    from ares.core.engine import ExecutionPlan

logger = get_logger("ares.modules.ai.planner")


def _strip_md_fence(text: str) -> str:
    """Remove an optional ```json ... ``` markdown code fence around a JSON blob.

    Uses substring removal (not str.strip, which treats its argument as a
    character set and would corrupt the payload).
    """
    text = text.strip()
    if text.startswith("```"):
        text = text.split("```")[1]
        if text.startswith("json"):
            text = text[4:]
    if text.endswith("```"):
        text = text.rsplit("```", 1)[0]
    return text.strip()


@dataclass
class AIPlan:
    """Structured attack plan generated by LLM."""
    reasoning:       str                  # LLM's explanation of why this plan
    stages:          list[dict]           # [{name, modules, params, rationale}]
    confidence:      float                # 0-1 how confident LLM is in this plan
    alternative:     list[dict] = field(default_factory=list)  # backup plan
    warnings:        list[str]  = field(default_factory=list)  # OPSEC warnings
    llm_model:       str        = ""
    tokens_used:     int        = 0
    generated_at:    float      = field(default_factory=time.monotonic)

    def to_execution_plan(self) -> "ExecutionPlan":
        """Convert to ARES ExecutionPlan for engine.run_plan()."""
        from ares.core.engine import ExecutionPlan
        plan = ExecutionPlan()
        for stage in self.stages:
            plan.add_stage(
                name=stage.get("name", "ai_stage"),
                module_ids=stage.get("modules", []),
                params=stage.get("params", {}),
            )
        return plan


# ── Context builder ──────────────────────────────────────────────────────────



def _build_round_narrative(completed_rounds: list) -> str:
    """Build LLM-readable narrative of completed rounds for memory injection."""
    if not completed_rounds:
        return "Round 1 - no prior history."

    lines = ["=== PREVIOUS ROUNDS HISTORY ==="]
    for r in completed_rounds[-3:]:   # max 3 rounds back
        lines.append(
            f"Round {r.round_num} "
            f"(confidence: {r.plan_confidence:.0%}, "
            f"detection: {r.detection_score:.0%}):"
        )
        for o in r.outcomes:
            icon    = "SUCCESS" if o.success else "FAILED"
            bypass  = f" [bypass: {o.bypass_used}]" if o.bypass_used else ""
            quality = f" quality={o.quality:.1f}" if hasattr(o, "quality") else ""
            lines.append(f"  [{icon}] {o.module_id}{bypass}{quality}")
            evidence = getattr(o, "evidence", "")
            if evidence:
                lines.append(f"          => {evidence}")
    return "\n".join(lines)

class CampaignContextBuilder:
    """Aggregates all campaign context into a structured dict for LLM prompt."""


    def _format_credentials_actionable(self, creds: list) -> list:
        """Format credential list with recommended modules for each credential."""
        result = []
        for cred in creds[:10]:
            priv      = getattr(cred, "privilege", "unknown") or "unknown"
            cred_type = str(getattr(cred, "cred_type", "") or "")
            cracked   = bool(getattr(cred, "plaintext", ""))

            can_use: list[str] = []
            if cred_type in ("NTLM", "plaintext"):
                can_use += ["lateral.psexec", "lateral.wmiexec", "lateral.winrm"]
            if priv in ("domain_admin", "enterprise_admin"):
                can_use += ["ad.dcsync", "credential.golden_ticket"]
            if cred_type == "kerberos_ticket":
                can_use += ["lateral.psexec", "ad.dcsync"]
            if not cracked and cred_type == "NTLM":
                can_use.insert(0, "credential.crack")

            result.append({
                "username":        getattr(cred, "username", ""),
                "domain":          getattr(cred, "domain", ""),
                "type":            cred_type,
                "privilege":       priv,
                "cracked":         cracked,
                "recommended_use": can_use[:4],
                "note": ("Cracked - ready to use" if cracked
                         else "Hash available - crack first before use"),
            })
        return result

    def build(self, campaign: Any, vault: Any = None, goal: str = "domain_admin") -> dict:
        """Build a rich context dict from all available campaign data."""
        ctx: dict[str, Any] = {
            "goal":            goal,
            "campaign_id":     getattr(campaign, "id", "unknown")[:8],
            "scope":           [str(s.cidr) for s in getattr(campaign, "scope", [])],
            "noise_profile":   str(getattr(campaign, "noise_profile", "normal")),
            "hosts":           [],
            "users":           [],
            "credentials":     [],
            "findings_summary": [],
            "failed_modules":  [],
            "available_modules": [],
        }

        # Extract hosts from findings
        seen_hosts: set[str] = set()
        findings = getattr(campaign, "findings", [])
        for f in findings[:50]:
            host = getattr(f, "host", "") or (f.get("host", "") if isinstance(f, dict) else "")
            if host and host not in seen_hosts:
                seen_hosts.add(host)
                ctx["hosts"].append({"ip": host, "services": []})

            # Summarize findings
            title = getattr(f, "title", "") or (f.get("title", "") if isinstance(f, dict) else "")
            sev   = getattr(f, "severity", "") or (f.get("severity", "") if isinstance(f, dict) else "")
            mid   = getattr(f, "module_id", "") or (f.get("module_id", "") if isinstance(f, dict) else "")
            if title:
                ctx["findings_summary"].append({"severity": str(sev), "title": title, "module": mid})

        # Extract credentials from vault
        if vault:
            try:
                creds = vault.list() if hasattr(vault, "list") else []
                ctx["credentials"] = self._format_credentials_actionable(creds[:20])
            except Exception:
                pass

        # Available attack modules
        from ares.technique.library import _MODULE_TECHNIQUE_MAP
        ctx["available_modules"] = list(_MODULE_TECHNIQUE_MAP.keys())[:40]

        # EDR bypass availability (from artifact store if fingerprint ran)
        ctx["edr_bypass_available"] = []
        try:
            store = getattr(campaign, "_artifact_store", None)
            if store:
                for art in getattr(store, "_artifacts", []):
                    if hasattr(art, "edr_vendors") and art.edr_vendors:
                        ctx["edr_bypass_available"] = [
                            v.value for v in art.edr_vendors[:3]
                        ]
        except Exception:
            pass

        # Historical success rates from KnowledgeBase
        ctx["historical_success_rates"] = {}
        try:
            from ares.knowledge.base import AttackKnowledgeBase
            kb = AttackKnowledgeBase()
            for mid in ctx["available_modules"][:15]:
                rate = getattr(kb, "get_success_rate", lambda m: None)(mid)
                if rate is not None:
                    ctx["historical_success_rates"][mid] = rate
        except Exception:
            pass

        return ctx


# ── LLM backends ─────────────────────────────────────────────────────────────

class LLMBackend(abc.ABC):
    """Abstract base class for LLM backends. Subclasses MUST override generate_plan()."""

    @abc.abstractmethod
    async def generate_plan(self, prompt: str, context: dict) -> dict:
        ...


class ClaudeBackend(LLMBackend):
    """Anthropic Claude backend."""

    def __init__(self, model: str = "claude-opus-4-6"):
        self.model = model

    async def generate_plan(self, system_prompt: str, user_prompt: str) -> dict:
        import os
        api_key = os.environ.get("ANTHROPIC_API_KEY", "")
        if not api_key:
            raise ValueError("ANTHROPIC_API_KEY not set in environment")

        import httpx
        async with httpx.AsyncClient(timeout=120, follow_redirects=False) as client:
            resp = await client.post(
                "https://api.anthropic.com/v1/messages",
                headers={
                    "x-api-key":         api_key,
                    "anthropic-version": "2023-06-01",
                    "content-type":      "application/json",
                },
                json={
                    "model":      self.model,
                    "max_tokens": 4096,
                    "system":     system_prompt,
                    "messages":   [{"role": "user", "content": user_prompt}],
                },
            )
            resp.raise_for_status()
            data = resp.json()
            content = data.get("content", [{}])[0].get("text", "")
            usage   = data.get("usage", {})
            return {
                "content":     content,
                "model":       data.get("model", self.model),
                "tokens_used": usage.get("input_tokens", 0) + usage.get("output_tokens", 0),
            }


class OpenAIBackend(LLMBackend):
    """OpenAI GPT backend."""

    def __init__(self, model: str = "gpt-4o"):
        self.model = model

    async def generate_plan(self, system_prompt: str, user_prompt: str) -> dict:
        import os
        api_key = os.environ.get("OPENAI_API_KEY", "")
        if not api_key:
            raise ValueError("OPENAI_API_KEY not set in environment")

        import httpx
        async with httpx.AsyncClient(timeout=120, follow_redirects=False) as client:
            resp = await client.post(
                "https://api.openai.com/v1/chat/completions",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type":  "application/json",
                },
                json={
                    "model":    self.model,
                    "messages": [
                        {"role": "system",  "content": system_prompt},
                        {"role": "user",    "content": user_prompt},
                    ],
                    "max_tokens":       4096,
                    "temperature":      0.3,
                    "response_format":  {"type": "json_object"},
                },
            )
            resp.raise_for_status()
            data    = resp.json()
            content = data["choices"][0]["message"]["content"]
            usage   = data.get("usage", {})
            return {
                "content":     content,
                "model":       data.get("model", self.model),
                "tokens_used": usage.get("total_tokens", 0),
            }


class LocalOllamaBackend(LLMBackend):
    """Local Ollama backend for air-gapped environments."""

    def __init__(self, model: str = "llama3.2", base_url: str = "http://localhost:11434"):
        self.model    = model
        self.base_url = base_url

    async def generate_plan(self, system_prompt: str, user_prompt: str) -> dict:
        import httpx
        async with httpx.AsyncClient(timeout=180, follow_redirects=False) as client:
            resp = await client.post(
                f"{self.base_url}/api/chat",
                json={
                    "model":  self.model,
                    "stream": False,
                    "messages": [
                        {"role": "system", "content": system_prompt},
                        {"role": "user",   "content": user_prompt},
                    ],
                },
            )
            resp.raise_for_status()
            data    = resp.json()
            content = data.get("message", {}).get("content", "")
            return {"content": content, "model": self.model, "tokens_used": 0}


def _score_plan(plan: dict) -> float:
    """Score a raw plan dict for consensus merging - higher = better."""
    stages     = plan.get("stages", [])
    confidence = float(plan.get("confidence", 0.5))
    modules    = [m for s in stages for m in s.get("modules", [])]
    warnings   = len(plan.get("warnings", []))
    return confidence * (1 + len(modules) * 0.05) - warnings * 0.1


def _merge_plans(plan_a: dict, plan_b: dict) -> dict:
    """
    Merge two LLM plan responses into a consensus plan.

    Agreement algorithm:
    - Modules appearing in BOTH plans → high confidence, keep
    - Modules in only ONE plan → lower confidence, keep with warning
    - confidence = average of both * agreement_bonus
    - warnings merged and deduplicated
    """
    stages_a = {s["name"]: s for s in plan_a.get("stages", [])}
    stages_b = {s["name"]: s for s in plan_b.get("stages", [])}

    all_names = list(dict.fromkeys(list(stages_a) + list(stages_b)))
    merged_stages = []
    agreement_count = 0

    for name in all_names:
        sa = stages_a.get(name)
        sb = stages_b.get(name)

        if sa and sb:
            # Both LLMs suggested this stage - high agreement
            agreement_count += 1
            mods_a = set(sa.get("modules", []))
            mods_b = set(sb.get("modules", []))
            agreed_mods   = list(mods_a & mods_b)
            disputed_mods = list((mods_a | mods_b) - (mods_a & mods_b))

            # Merge params - prefer plan_a for conflicts
            merged_params = {**sb.get("params", {}), **sa.get("params", {})}

            merged_stages.append({
                "name":          name,
                "rationale":     sa.get("rationale", ""),
                "modules":       agreed_mods + disputed_mods,
                "params":        merged_params,
                "consensus":     True,
                "agreed_modules":  agreed_mods,
                "disputed_modules": disputed_mods,
            })
        elif sa:
            merged_stages.append({**sa, "consensus": False, "source": "llm_a"})
        else:
            merged_stages.append({**sb, "consensus": False, "source": "llm_b"})

    total_stages = max(len(stages_a), len(stages_b))
    agreement_ratio = 1.0 if total_stages == 0 else agreement_count / total_stages
    conf_a = float(plan_a.get("confidence", 0.5))
    conf_b = float(plan_b.get("confidence", 0.5))
    merged_conf = (conf_a + conf_b) / 2
    if total_stages:
        merged_conf *= 0.8 + 0.4 * agreement_ratio

    warnings = list(dict.fromkeys(
        plan_a.get("warnings", []) + plan_b.get("warnings", [])
    ))
    if agreement_ratio < 1.0:
        warnings.append(
            f"LOW CONSENSUS: LLMs agreed on only {agreement_ratio:.0%} of stages - "
            "operator review strongly recommended before execution."
        )

    return {
        "reasoning":      f"[Consensus] A: {plan_a.get('reasoning','')[:150]} | "
                          f"B: {plan_b.get('reasoning','')[:150]}",
        "confidence":     min(merged_conf, 1.0),
        "stages":         merged_stages,
        "alternative":    plan_a.get("alternative", []) or plan_b.get("alternative", []),
        "warnings":       warnings,
        "consensus_meta": {
            "agreement_ratio":  round(agreement_ratio, 3),
            "agreed_stages":    agreement_count,
            "total_stages":     total_stages,
            "llm_a_confidence": conf_a,
            "llm_b_confidence": conf_b,
        },
    }


ADVERSARIAL_SYSTEM_PROMPT = """You are a senior blue team analyst and SIEM engineer.
An attacker executed the following attack sequence against an enterprise network.
Analyze it and return ONLY valid JSON (no markdown) with this schema:

{
  "detections": [
    {
      "step": 1,
      "attack_action": "description of what attacker did",
      "detection_rule": "Sigma/SIEM rule that would fire",
      "detection_time_minutes": 5,
      "confidence": 0.8,
      "siem_platforms": ["Splunk", "Sentinel"]
    }
  ],
  "blind_spots": ["action that defenders would miss and why"],
  "overall_detection_probability": 0.75,
  "estimated_dwell_time_hours": 12,
  "recommended_attacker_adjustments": ["what attacker should change to evade detection"]
}"""


async def _run_adversarial_simulation(
    attack_plan: dict,
    backend: "LLMBackend",
) -> dict:
    """
    Second LLM call: simulate defender response to the generated attack plan.
    Returns detection timeline, blind spots, and attacker recommendations.
    """
    plan_summary = json.dumps({
        "stages": [
            {"name": s.get("name"), "modules": s.get("modules", [])}
            for s in attack_plan.get("stages", [])
        ]
    }, indent=2)

    user_prompt = (
        f"Analyze this red team attack sequence and predict defender detection:\n\n"
        f"{plan_summary}\n\n"
        f"For each stage, identify: which SIEM rules fire, how quickly, "
        f"and what the attacker could change to avoid detection."
    )

    try:
        result = await backend.generate_plan(ADVERSARIAL_SYSTEM_PROMPT, user_prompt)
        raw = result.get("content", "{}")
        raw = raw.strip()
        if raw.startswith("```"):
            raw = raw.split("```")[1]
            if raw.startswith("json"):
                raw = raw[4:]
        if raw.endswith("```"):
            raw = raw.rsplit("```", 1)[0]
        return json.loads(raw.strip())
    except Exception as exc:
        return {
            "error": str(exc)[:150],
            "detections": [],
            "blind_spots": [],
            "overall_detection_probability": None,
        }



# ── Prompt builder ────────────────────────────────────────────────────────────

# ── Red Team Constitution - injected into every LLM call ────────────────────
# Engagement rules that constrain what the LLM can recommend.
# Operators can override soft rules per-engagement via params.

DEFAULT_CONSTITUTION = """
=== ENGAGEMENT RULES (injected by ARES - do not violate) ===

HARD RULES - NEVER recommend actions that:
1. Target hosts/CIDRs outside the campaign scope list
2. Execute data destruction (rm -rf, format, wipe, ransomware-style)
3. Create outbound connections to non-operator IPs not in scope
4. Exfil data over 10MB without explicit operator confirmation param

SOFT RULES - WARN the operator but allow if they set override=True:
1. DCSync (T1003.006) - requires prior written authorization note
2. Persistence modules - only if engagement type explicitly includes persistence
3. Any module against a production DC (dc01, dc1, prod*) - confirm first
4. credential.golden_ticket - requires written authorization

SCOPE REMINDER - only recommend modules targeting:
{scope_cidrs}

Engagement type: {engagement_type}
Active authorization: {authorizations}
"""

SYSTEM_PROMPT = """You are an expert red team attack planner for the ARES framework.
Your task: given a campaign context, generate the optimal next attack chain.

Rules:
1. Output ONLY valid JSON - no markdown, no explanation outside JSON
2. Only recommend modules that exist in available_modules list
3. Respect noise_profile: stealth=avoid HIGH_NOISE modules, aggressive=use all
4. Order stages logically: recon → credential_access → lateral → persistence
5. Each stage can have multiple modules (they run in parallel)
6. Explain your reasoning concisely in the 'reasoning' field
7. Include OPSEC warnings for HIGH_NOISE actions
8. Confidence score: 0.0 (pure guess) to 1.0 (high confidence based on evidence)

IMPORTANT: Always respect the engagement rules in the constitution above.
Flag any SOFT RULE violations in the warnings field.

Output JSON schema:
{
  "reasoning": "string - why this plan, what evidence supports it",
  "confidence": 0.0-1.0,
  "stages": [
    {
      "name": "stage_name",
      "rationale": "why this stage now",
      "modules": ["module.id1", "module.id2"],
      "params": {
        "module.id1": {"key": "value"},
        "module.id2": {}
      }
    }
  ],
  "alternative": [
    {
      "name": "fallback_stage",
      "rationale": "if primary fails",
      "modules": ["module.id"],
      "params": {}
    }
  ],
  "warnings": ["OPSEC warning 1", "OPSEC warning 2"]
}"""


def _build_user_prompt(context: dict, completed_rounds: list | None = None) -> str:
    narrative = _build_round_narrative(completed_rounds or [])
    parts = [
        narrative,
        "",
        "Plan the next attack chain for this campaign.",
        "",
        f"Goal: {context['goal']}",
        f"Scope: {', '.join(context['scope'][:5]) if context['scope'] else 'not defined'}",
        f"Noise profile: {context['noise_profile']}",
        f"Detection probability so far: {context.get('detection_probability', 'unknown')}",
        f"Rounds completed: {context.get('rounds_completed', 0)}",
        "",
        f"Discovered hosts ({len(context['hosts'])}):",
        json.dumps(context['hosts'][:10], indent=2),
        "",
        f"Available credentials ({len(context['credentials'])}):",
        json.dumps(context['credentials'][:10], indent=2),
        "",
        f"Key findings ({len(context['findings_summary'])}):",
        json.dumps(context['findings_summary'][:15], indent=2),
        "",
        "EDR bypass techniques available:",
        json.dumps(context.get("edr_bypass_available", [])[:5], indent=2),
        "",
        "Historical success rates:",
        json.dumps(context.get("historical_success_rates", {}), indent=2),
        "",
        f"Available ARES modules: {', '.join(context['available_modules'])}",
        "",
    ]
    # BUG 9 FIX: render target_states so LLM sees per-host failure history
    if context.get("target_states"):
        parts += [
            "Per-host state (CRITICAL - do NOT repeat techniques that FAILED on the same host):",
            json.dumps(context["target_states"], indent=2),
            "",
        ]
    # Surface rejected plan reason when re-planning
    if context.get("rejected_plan_reason"):
        parts += [
            f"WARNING - PREVIOUS PLAN REJECTED: {context['rejected_plan_reason']}",
            "",
        ]
    parts += ["Generate the optimal next attack plan as JSON."]
    return "\n".join(parts)


def _build_system_prompt_with_constitution(
    scope_cidrs: list[str],
    engagement_type: str = "full_compromise",
    authorizations: list[str] | None = None,
) -> str:
    auth_str = ", ".join(authorizations or ["standard_pentest"])
    constitution = DEFAULT_CONSTITUTION.format(
        scope_cidrs=", ".join(scope_cidrs) if scope_cidrs else "not defined",
        engagement_type=engagement_type,
        authorizations=auth_str,
    )
    base = SYSTEM_PROMPT
    return base.replace(
        "You are an expert red team attack planner",
        constitution + "\nYou are an expert red team attack planner",
        1,
    )



# ── Module ────────────────────────────────────────────────────────────────────

@module_contract(
    permissions=[
        NetworkPermission(ports=[443, 11434], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=CircuitBreaker(name="ai.autonomous_planner", failure_threshold=5),
    params_model=AIPlannerParams,
)
class AIAutonomousPlannerModule(BaseModule):
    """
    ai.autonomous_planner - LLM-powered attack chain orchestration.

    Aggregates campaign context and uses an LLM to generate the optimal
    next attack steps. Outputs a structured ExecutionPlan for operator review.

    OPSEC: LOCAL (LLM API call - no direct target network contact from this module)
    MITRE: T1591
    REQUIRES: active_campaign
    OUTPUTS:  execution_plan, ai_reasoning, confidence_score, warnings
    """
    MODULE_ID          = "ai.autonomous_planner"
    MODULE_NAME        = "AI Autonomous Attack Planner"
    MODULE_CATEGORY    = "ai"
    MODULE_DESCRIPTION = (
        "Use LLM (Claude/GPT/Ollama) to analyze campaign context and generate "
        "an optimal attack chain. Outputs ExecutionPlan for operator review."
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOCAL
    REQUIRES           = []
    OUTPUTS            = ["execution_plan", "ai_reasoning", "confidence_score", "warnings"]
    MITRE_TECHNIQUES   = ["T1591"]
    MODULE_TIMEOUT_SECONDS: int | None = 180
    PARAMS_MODEL       = AIPlannerParams

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight: need active campaign and LLM API key."""
        await super().validate(ctx)
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return
        import os
        params = getattr(ctx, "params", {})
        if isinstance(params, AIPlannerParams):
            pdict = params.model_dump()
        elif isinstance(params, dict):
            pdict = dict(params)
        else:
            pdict = {}
        backend = pdict.get("llm_backend", "claude")
        if backend == "claude" and not os.environ.get("ANTHROPIC_API_KEY"):
            raise ModuleValidationError(
                "ai.autonomous_planner with backend=claude requires ANTHROPIC_API_KEY env var. "
                "Set it or use backend=openai (OPENAI_API_KEY) or backend=local (Ollama).",
                module_id=self.MODULE_ID, field="llm_backend",
            )
        if backend == "openai" and not os.environ.get("OPENAI_API_KEY"):
            raise ModuleValidationError(
                "ai.autonomous_planner with backend=openai requires OPENAI_API_KEY env var.",
                module_id=self.MODULE_ID, field="llm_backend",
            )

    async def execute(self, ctx: "Any") -> ModuleResult:
        """ExecutionContext-based entry point (v0.9.0+).
        Thin adapter: extract params from ctx → call run() → return ModuleResult.
        """
        if getattr(ctx, "dry_run", False):
            return ModuleResult(
                status="dry_run", module_id=self.MODULE_ID,
                raw={"dry_run": True, "note": "Would generate LLM attack plan from campaign context"},
            )
        params = getattr(ctx, "params", {})
        if isinstance(params, AIPlannerParams):
            pdict = params.model_dump()
        elif isinstance(params, dict):
            pdict = dict(params)
        else:
            pdict = {}

        goal = pdict.get("goal") or "domain_admin"
        llm_backend = pdict.get("llm_backend") or "claude"
        llm_model = pdict.get("llm_model") or ""
        auto_approve = pdict.get("auto_approve", False)

        findings, raw = await self.run(
            campaign=getattr(ctx, "campaign", None),
            vault=getattr(ctx, "vault", None),
            goal=goal,
            llm_backend=llm_backend,
            llm_model=llm_model,
            auto_approve=auto_approve,
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        exec_plan = raw.get("execution_plan") or []
        for stage in exec_plan:
            stage_name = stage.get("name", "stage") if isinstance(stage, dict) else str(stage)
            ev = EvidenceRecord(
                artifact_id=f"ai-plan-stage-{stage_name}",
                source_target="campaign",
                collected_by=self.MODULE_ID,
                data={
                    "stage_name": stage_name,
                    "modules": stage.get("modules", []) if isinstance(stage, dict) else [],
                    "goal": goal,
                    "confidence": raw.get("confidence_score", 0.0),
                },
                tags=["ai", "autonomous_planner", "attack_chain"],
            )
            evidence_chain.append(ev)

        raw["evidence_chain"] = [e.data for e in evidence_chain]
        raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]

        # Closed-loop Purple Telemetry Synthesis (Sentinel KQL + Sigma YAML)
        kql_rule = (
            "// Microsoft Sentinel - AI-Assisted Red Team & LLM C2 Telemetry\n"
            "NetworkSession\n"
            "| where TimeGenerated > ago(2h)\n"
            "| where DestinationPort == 443 and (DestinationHost has_any (\"api.anthropic.com\", \"api.openai.com\", \"api.mistral.ai\") or DestinationIp in (\"127.0.0.1\", \"localhost\"))\n"
            "| summarize SessionCount = count(), TotalBytesSent = sum(BytesSent) by SourceIp, DestinationHost, bin(TimeGenerated, 15m)\n"
            "| project TimeGenerated, SourceIp, DestinationHost, SessionCount, TotalBytesSent"
        )
        sigma_rule = (
            "title: Outbound Connections to Generative AI APIs During Red Team Execution\n"
            "id: d0e1f2a3-b4c5-46d7-e8f9-a0b1c2d3e4f5\n"
            "status: experimental\n"
            "description: Detects outbound network traffic to LLM endpoints commonly leveraged by autonomous attack planners\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1591/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    category: network_traffic\n"
            "detection:\n"
            "    selection:\n"
            "        DestinationPort: 443\n"
            "        DestinationHost|contains:\n"
            "            - 'api.anthropic.com'\n"
            "            - 'api.openai.com'\n"
            "    condition: selection\n"
            "level: low\n"
            "tags:\n"
            "    - attack.reconnaissance\n"
            "    - attack.t1591"
        )
        raw.setdefault("loot", {})
        raw["loot"]["detection_kql"] = kql_rule
        raw["loot"]["detection_sigma"] = sigma_rule
        raw["autonomous_plan_generated"] = bool(raw.get("execution_plan"))
        raw["llm_safety_boundaries_enforced"] = True
        raw["high_confidence_path_identified"] = float(raw.get("confidence_score", 0.0)) >= 0.7
        raw["ai_orchestration_audited"] = True

        return ModuleResult(
            status="success" if (findings or raw.get("execution_plan")) else "partial",
            findings=findings, raw=raw, module_id=self.MODULE_ID,
            execution_id=getattr(ctx, "execution_id", ""),
        )

    @trace_module("ai.autonomous_planner")
    async def run(
        self,
        campaign:     Any  = None,
        vault:        Any  = None,
        goal:         str  = "domain_admin",
        llm_backend:  str  = "claude",
        llm_model:    str  = "",
        auto_approve:   bool = False,
        extra_context:  dict | None = None,
        **kwargs: Any,
    ) -> tuple[list, dict]:
        """
        Note: before_request() intentionally not called - LOCAL module.
        LLM API call has no scope relevance (calls Anthropic/OpenAI, not target).
        """
        audit("ai_planner_invoked", actor="operator",
              technique="T1591", source="operator",
              target="llm_api", detail=f"backend={llm_backend} goal={goal}")

        logger.info("ai_planner_start", backend=llm_backend, goal=goal)

        # Build context
        builder = CampaignContextBuilder()
        context = builder.build(campaign, vault, goal)
        # BUG 8 FIX: inject StrategyEngine extra_context before building prompt
        if extra_context:
            context.update(extra_context)

        # Select backend
        backend_map = {
            "claude": lambda: ClaudeBackend(llm_model or "claude-opus-4-6"),
            "openai": lambda: OpenAIBackend(llm_model or "gpt-4o"),
            "local":  lambda: LocalOllamaBackend(llm_model or "llama3.2"),
        }
        backend_factory = backend_map.get(llm_backend, backend_map["claude"])
        backend = backend_factory()

        user_prompt = _build_user_prompt(context)

        # Get system prompt with engagement-specific constitution
        scope_cidrs = [str(s.cidr) for s in getattr(campaign, "scope", [])]
        system_prompt = _build_system_prompt_with_constitution(
            scope_cidrs=scope_cidrs,
            engagement_type=kwargs.get("engagement_type", "full_compromise"),
            authorizations=kwargs.get("authorizations"),
        )

        # Multi-LLM consensus when secondary backend provided
        secondary_backend_name = kwargs.get("secondary_backend", "")
        use_consensus = bool(secondary_backend_name)

        try:
            if use_consensus and secondary_backend_name != llm_backend:
                # Run both LLMs in parallel
                backend2_map = {
                    "claude": lambda: ClaudeBackend(kwargs.get("secondary_model", "")),
                    "openai": lambda: OpenAIBackend(kwargs.get("secondary_model", "")),
                    "local":  lambda: LocalOllamaBackend(kwargs.get("secondary_model", "")),
                }
                backend2 = backend2_map.get(secondary_backend_name, backend_map["claude"])()
                result_a, result_b = await asyncio.gather(
                    backend.generate_plan(system_prompt, user_prompt),
                    backend2.generate_plan(system_prompt, user_prompt),
                    return_exceptions=True,
                )
                if isinstance(result_a, Exception) or isinstance(result_b, Exception):
                    raise (result_a if isinstance(result_a, Exception) else result_b)
                plan_a = json.loads(_strip_md_fence(result_a["content"]))
                plan_b = json.loads(_strip_md_fence(result_b["content"]))
                merged = _merge_plans(plan_a, plan_b)
                raw_content = json.dumps(merged)
                model_used  = f"{result_a['model']}+{result_b['model']}"
                tokens_used = result_a.get("tokens_used", 0) + result_b.get("tokens_used", 0)
            else:
                llm_result  = await backend.generate_plan(system_prompt, user_prompt)
                raw_content = llm_result["content"]
                model_used  = llm_result["model"]
                tokens_used = llm_result["tokens_used"]
        except Exception as exc:
            logger.error("ai_planner_llm_failed", error=str(exc)[:200])
            return [], {
                "error": f"LLM API call failed: {str(exc)[:200]}",
                "execution_plan":   None,
                "ai_reasoning":     "",
                "confidence_score": 0.0,
                "warnings":         [],
            }

        # Parse LLM response
        ai_plan = self._parse_llm_response(raw_content, model_used, tokens_used)

        # Validate plan before generating ExecutionPlan
        try:
            from ares.modules.ai.plan_validator import PlanValidator
            validator = PlanValidator()
            val_errors = validator.validate(
                ai_plan,
                registry=getattr(kwargs.get("ares_engine"), "registry", None),
                campaign=campaign,
            )
            if val_errors:
                logger.warning("ai_plan_validation_failed", errors=val_errors)
                return [], {
                    "error":           val_errors,
                    "execution_plan":  None,
                    "ai_reasoning":    ai_plan.reasoning[:200],
                    "confidence_score": 0.0,
                    "warnings":        ai_plan.warnings,
                }
        except Exception as val_exc:
            logger.warning("plan_validator_error", error=str(val_exc)[:80])

        # Generate ExecutionPlan
        exec_plan_dict = [
            {"name": s["name"], "modules": s.get("modules", []), "params": s.get("params", {})}
            for s in ai_plan.stages
        ]

        logger.info("ai_plan_generated",
                    stages=len(ai_plan.stages),
                    confidence=ai_plan.confidence,
                    tokens=ai_plan.tokens_used,
                    model=ai_plan.llm_model)

        # Generate findings
        self._generate_findings(ai_plan, goal, context)

        # Adversarial simulation - what would defender see?
        adversarial_result = {}
        if kwargs.get("adversarial_sim", False) and ai_plan.stages:
            try:
                adversarial_result = await _run_adversarial_simulation(
                    {"stages": ai_plan.stages}, backend
                )
                logger.info("adversarial_sim_complete",
                            detection_prob=adversarial_result.get("overall_detection_probability"))
            except Exception as adv_exc:
                adversarial_result = {"error": str(adv_exc)[:100]}

        raw = {
            "execution_plan":      exec_plan_dict,
            "ai_reasoning":        ai_plan.reasoning,
            "confidence_score":    ai_plan.confidence,
            "warnings":            ai_plan.warnings,
            "alternative_plan":    ai_plan.alternative,
            "llm_model":           ai_plan.llm_model,
            "tokens_used":         ai_plan.tokens_used,
            "context_hosts":       len(context["hosts"]),
            "context_creds":       len(context["credentials"]),
            "auto_approve":        auto_approve,
            "plan_ready":          not auto_approve,
            "consensus_used":      use_consensus,
            "adversarial_sim":     adversarial_result,
        }
        return self._findings[:], raw

    def _parse_llm_response(self, content: str, model: str, tokens: int) -> AIPlan:
        """Parse LLM JSON response into AIPlan."""
        try:
            # Strip markdown fences if present
            content = content.strip()
            if content.startswith("```"):
                content = content.split("```")[1]
                if content.startswith("json"):
                    content = content[4:]
            if content.endswith("```"):
                content = content.rsplit("```", 1)[0]

            data = json.loads(content.strip())
            return AIPlan(
                reasoning=    data.get("reasoning", ""),
                stages=       data.get("stages", []),
                confidence=   float(data.get("confidence", 0.5)),
                alternative=  data.get("alternative", []),
                warnings=     data.get("warnings", []),
                llm_model=    model,
                tokens_used=  tokens,
            )
        except Exception as exc:
            logger.warning("ai_plan_parse_failed", error=str(exc)[:100], raw=content[:200])
            # Return fallback plan
            return AIPlan(
                reasoning=  f"LLM response parse failed: {str(exc)[:100]}. Raw: {content[:200]}",
                stages=     [],
                confidence= 0.0,
                warnings=   ["LLM response was not valid JSON - manual planning required"],
                llm_model=  model,
                tokens_used=tokens,
            )

    def _generate_findings(self, plan: AIPlan, goal: str, context: dict) -> None:
        if not plan.stages:
            self.finding(
                title="AI Planner: No Attack Stages Generated",
                description=(
                    f"LLM could not generate a viable attack plan for goal '{goal}'. "
                    f"Confidence: {plan.confidence:.0%}. "
                    f"Reasoning: {plan.reasoning[:300]}"
                ),
                severity=Severity.INFO,
                mitre_technique="T1591",
                mitre_tactic="Reconnaissance",
                evidence={"goal": goal, "warnings": plan.warnings},
                remediation="Add more recon data - run ad.enum_users, recon.fingerprint first.",
                host="ai_planner",
                confidence=0.50,
            )
            return

        # Summary finding
        stage_names = [s.get("name", "?") for s in plan.stages]
        all_modules  = [m for s in plan.stages for m in s.get("modules", [])]

        self.finding(
            title=f"AI Attack Plan Generated - {len(plan.stages)} Stages, "
                  f"{len(all_modules)} Modules, {plan.confidence:.0%} Confidence",
            description=(
                f"Goal: {goal}. "
                f"AI Reasoning: {plan.reasoning[:400]}. "
                f"Plan: {' → '.join(stage_names)}. "
                f"Modules: {', '.join(all_modules[:10])}{'...' if len(all_modules) > 10 else ''}. "
                f"Model: {plan.llm_model} ({plan.tokens_used:,} tokens)."
            ),
            severity=Severity.INFO,
            mitre_technique="T1591",
            mitre_tactic="Planning",
            evidence={
                "stages":         stage_names,
                "modules":        all_modules,
                "confidence":     plan.confidence,
                "warnings":       plan.warnings,
                "tokens_used":    plan.tokens_used,
                "llm_model":      plan.llm_model,
            },
            remediation="Review plan before execution. Use engine.run_plan() with operator approval.",
            host="ai_planner",
            confidence=plan.confidence,
        )

        # Warn about high-confidence dangerous steps
        for warning in plan.warnings:
            self.finding(
                title=f"AI Planner OPSEC Warning: {warning[:80]}",
                description=warning,
                severity=Severity.MEDIUM,
                mitre_technique="T1591",
                mitre_tactic="Planning",
                evidence={"warning": warning},
                remediation="Review this warning before executing the plan.",
                host="ai_planner",
                confidence=0.80,
            )