#!/usr/bin/env python3
"""
aw-orchestrator — reference runtime for the "interpreter owns context,
a FRESH Claude executes" architecture.

    User
      │
      ▼  (a Claude Code skill launches this runtime)
    Python Workflow / Interpreter Runtime  ── THIS FILE
      │
      ├─ build_context     Builds the COMPLETE context for the next request
      │                    (reads standards + rule files + prior outputs and
      │                     assembles a self-contained system + user payload).
      ▼
    Invoke Claude Code (FRESH generation)
      │                    `claude -p --bare --system-prompt-file … --tools …`
      │                    • -p        → a brand-new conversation (the calling
      │                                  agent's transcript is NOT inherited)
      │                    • --bare     → no CLAUDE.md / auto-memory / hooks;
      │                                  the ONLY context is what we pass
      │                    • system     → the interpreter-authored standards
      │                    • stdin      → the interpreter-authored task
      ├─ Claude uses tools (Edit / Write / Bash …) to do the actual work
      ▼
    Return structured result  (a trailing ```json {…} ``` block → dict)
      │
      ▼
    Interpreter continues to the next workflow step
      │
      ├─ agent_review   Review the current output (another FRESH generation)
      ▼
    build_context → … continues

Key property (your R6): every model request sees ONLY the payload the
interpreter assembled. The orchestrating Claude Code's own context is never
part of a generation — because generation happens in a separate `--bare`
process, not in this conversation.

Stdlib only. Reuses the production YAML loader from ../interpreter/run-skill.py
so skills stay in the same dialect family.

Workflow dialect: aw-spec.orchestrator/v1 (see ORCH-DIALECT.md). On top of the
demo actions (set / build_context / agent_generate / agent_review / loop /
break) the engine provides the full vocabulary the aw-spec-* conversions need:
  execute_script   run a shared deterministic script (decl port; --os sh/ps1)
  verify_context   the four decl gate forms (files / non-empty / true / value)
  load_standards   sticky SYSTEM standards set, prepended to every payload
  agent_author     authored artifact: interpreter-owned output path, read-only
                   generation under EVERY strategy, the ENGINE writes the file
  agent_query      generic read-only structured JSON query (outputs[] binding)
  ask/user_select  HITL — suspends via the checkpoint channel under ANY
                   strategy (the launcher relays to the user), or --answer /
                   --select / --non-interactive prefills
  dispatch_hooks   hands resolved hooks to the INVOKING agent (suspend 'hook')
  include          run a module .orch.yaml inline (shared vars/scripts/cache)
  loop over:/as:   foreach over a list var (plus the existing while: form)

Usage:
  orchestrator.py <workflow.yaml> [--transport mock|real]
      [--model opus] [--budget 0.50] [--var k=v ...] [--input "<text>"]
      [--answer k=v ...] [--select stepid=v ...] [--non-interactive]
      [--os posix|windows] [--show-full] [--json]
  orchestrator.py <workflow.yaml> --validate [--json]   # lint, don't execute

Execution strategies (--strategy, overridable per step via `strategy:`):
  The interpreter assembles 100% of every payload in ALL strategies; they only
  differ in WHO executes it and WHO applies the file changes.

  sdk        Strategy 1: an isolated Agent SDK instance generates AND
             implements with its own tools. Fresh context per step; the
             invoking agent's conversation never enters a request. EVERYTHING
             SDK-specific is declared by the agent profile's `sdk` block
             (--agent-profile, e.g. agent.json) — the package/module to import
             (pip-installed on demand with --sdk-install or sdk.auto_install)
             and the `adapter` (a Python file exporting generate(request);
             shared per-SDK adapters live in .aw-spec/orchestrator/adapters/)
             that owns that SDK's calling convention — so the engine names no
             agent, has no default, and stays agent-agnostic. Imported
             lazily; needs API auth.
  sdk-apply  Strategy 2: the SDK instance (same profile-declared sdk block)
             generates read-only (full intended file contents as an artifact);
             the interpreter then SUSPENDS (checkpoint) and the INVOKING agent
             applies the artifact with its tools — visible diffs, native
             permission prompts. Generation is isolated; only the apply phase
             runs in the invoker. Needs --checkpoint.
  spawn      Strategy 3 (the original transport): a fresh CLI process per
             generation, described by --agent-profile (claude -p --bare /
             gemini -p). Isolated, but cold-starts every step.
  agent      Strategy 4: zero new instances — the run-skill.py suspend/resume
             method. The interpreter exits (code 2) at each generation and the
             INVOKING agent fulfills it in its own conversation (payload
             ownership kept; context isolation is best-effort only). Needs
             --checkpoint.

  Legacy inference when --strategy is omitted: --agent-profile → spawn,
  --checkpoint → agent, neither → mock transport (no model call; prints the
  exact payloads and simulates the writes).

  Loop + checkpoint machinery is strategy-independent: completed generations
  are written to the replay cache, so any mix of strategies survives
  suspend/resume.
"""
import argparse
import importlib.util
import json
import os
import re
import subprocess
import sys

# ── reuse the production YAML-subset loader ──────────────────────────────────
_INTERP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "interpreter", "run-skill.py")
_spec = importlib.util.spec_from_file_location("aw_run_skill", _INTERP)
_run_skill = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_run_skill)
load_yaml = _run_skill.load_yaml


BANNER = "─" * 70


class Stop(Exception):
    pass


class Suspend(Exception):
    """Raised in checkpoint mode when a generation is needed: the interpreter
    persists state and exits so the INVOKING agent can fulfill the request
    (run-skill.py's suspend/resume method — no new agent instance)."""
    def __init__(self, request):
        self.request = request


def _norm_files(entries):
    """Normalize a system:/context: list into [(path, optional)]."""
    out = []
    for e in entries or []:
        if isinstance(e, dict):
            out.append((e.get("path"), bool(e.get("optional"))))
        else:
            out.append((e, False))
    return out


def _extract_json(text):
    """Pull a structured result out of a free-form model reply: the last
    ```json … ``` fence, else the last bare {...}."""
    if not text:
        return {}
    fences = re.findall(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
    for blob in reversed(fences):
        try:
            return json.loads(blob)
        except Exception:
            continue
    i, j = text.rfind("{"), text.rfind("}")
    if 0 <= i < j:
        try:
            return json.loads(text[i:j + 1])
        except Exception:
            pass
    return {}


def _strip_fence(text):
    """If the ENTIRE reply is one fenced code block, unwrap it (models often
    fence authored file content despite being told not to)."""
    t = (text or "").strip()
    m = re.fullmatch(r"```[A-Za-z0-9_+-]*\n(.*?)\n?```", t, re.DOTALL)
    return m.group(1) + "\n" if m else (text or "")


class Orchestrator:
    def __init__(self, wf, opts):
        self.wf = wf
        self.opts = opts
        self.vars = dict(wf.get("vars", {}) or {})
        self.vars.update(opts.vars)
        # the CURRENT context envelope, produced by build_context and consumed
        # by the next agent_generate / agent_review.
        self.envelope = {"system": [], "context": []}
        # F4: sticky standards — _assemble_system always prepends these, so the
        # system prefix stays byte-stable across steps (prompt-cache lever)
        # while build_context keeps declaring only the per-request delta.
        self.standards = list(wf.get("standards", []) or [])
        # F1: top-level scripts ref map {ref: {sh: path, ps1: path}} (decl shape)
        self.scripts = dict(wf.get("scripts", {}) or {})
        # every file that has entered any payload (verify_context required_files)
        self.loaded = []
        # every REQUIRED system:/context: file that was declared but absent at
        # assembly time (item H). Distinct, run-cumulative, surfaced in the run
        # result + the context_missing/_count vars so a workflow can gate on it.
        self.missing_required = []
        self.last_result = {}
        # agent-specific transport profile (None in mock mode). This engine is
        # general — the profile (loaded from a .claude/.agents/.kilocode file)
        # describes HOW to spawn that agent's fresh generation CLI.
        self.profile = getattr(opts, "profile", None)
        # checkpoint transport (run-skill.py method): replay + response cache
        # keyed by a loop-aware invocation path. No new agent instance.
        self.checkpoint = getattr(opts, "checkpoint", None)
        self.cache = getattr(opts, "_cache", {}) or {}
        self.key_stack = []

    # -- variable resolution --------------------------------------------------
    def _lookup(self, key):
        """Dotted/indexed lookup into vars ('q.text', 'items.0'). (found, raw)."""
        parts = key.split(".")
        if parts[0] not in self.vars:
            return (False, None)
        cur = self.vars[parts[0]]
        for p in parts[1:]:
            if isinstance(cur, dict) and p in cur:
                cur = cur[p]
            elif isinstance(cur, list) and p.isdigit() and int(p) < len(cur):
                cur = cur[int(p)]
            else:
                return (False, None)
        return (True, cur)

    def _get(self, key):
        found, cur = self._lookup(key)
        if not found or cur is None:
            return ""
        return cur if isinstance(cur, str) else json.dumps(cur)

    def resolve(self, val):
        if isinstance(val, str):
            return re.sub(r"\{\{\s*([^}]+?)\s*\}\}", lambda m: str(self._get(m.group(1).strip())), val)
        if isinstance(val, list):
            return [self.resolve(x) for x in val]
        if isinstance(val, dict):
            return {k: self.resolve(v) for k, v in val.items()}
        return val

    def resolve_value(self, x):
        """resolve(), except a value that is EXACTLY one {{ref}} returns the raw
        object (list/dict/bool) instead of its JSON string (run-skill parity —
        needed for loop over:, ask options_from, set, include with:)."""
        if isinstance(x, str):
            m = re.fullmatch(r"\{\{\s*([^}]+?)\s*\}\}", x.strip())
            if m:
                found, v = self._lookup(m.group(1).strip())
                return v if found else x
            return self.resolve(x)
        if isinstance(x, list):
            return [self.resolve_value(i) for i in x]
        return x

    def _json_get(self, obj, path):
        if not isinstance(obj, dict):
            return None
        if not path.startswith("$."):
            return obj.get(path)
        cur = obj
        for part in path[2:].split("."):
            cur = cur.get(part) if isinstance(cur, dict) else None
        return cur

    def _bind(self, step, data):
        for out in step.get("outputs", []) or []:
            self.vars[out["name"]] = self._json_get(data, out["from"])

    def _cond(self, expr):
        expr = self.resolve(expr).strip()
        for op in ("==", "!="):
            if op in expr:
                lhs, rhs = [s.strip().strip("'\"") for s in expr.split(op, 1)]
                return (lhs == rhs) if op == "==" else (lhs != rhs)
        return expr not in ("", "false", "False", "None", "null", "[]")

    def emit(self, msg):
        if not self.opts.json:
            print(msg)

    # -- strategy selection -----------------------------------------------------
    def _effective_strategy(self, step):
        """Per-step `strategy:` overrides the run default (--strategy). In mock
        transport the strategy is informational only — nothing executes."""
        s = step.get("strategy") or self.opts.strategy
        if self.opts.transport == "mock":
            return s
        if s == "spawn" and not self.profile:
            raise Stop(f"step {step.get('id')}: strategy 'spawn' needs --agent-profile")
        if s in ("sdk", "sdk-apply") and not self.profile:
            raise Stop(f"step {step.get('id')}: strategy '{s}' needs --agent-profile "
                       "(its sdk block declares the SDK + adapter; no built-in default)")
        if s in ("agent", "sdk-apply") and not self.checkpoint:
            raise Stop(f"step {step.get('id')}: strategy '{s}' needs --checkpoint <statefile>")
        return s

    # -- checkpoint machinery (run-skill.py suspend/resume method) --------------
    def _key(self, step):
        """Stable, loop-aware invocation key for a step (for the replay cache)."""
        return "/".join(self.key_stack + [step.get("id", "?")])

    def _suspend(self, kind, step_key, system, user, tools, permission_mode,
                 instructions=None, extra=None):
        """Write the fully-assembled payload to sidecar files next to the
        checkpoint, then raise Suspend so main() persists state and exits.
        The INVOKING agent fulfills the request — no new instance is spawned.
        The interpreter keeps 100% ownership of what goes INTO the payload;
        it cannot strip what the invoking agent's own conversation adds AROUND
        it (that is the isolation trade-off of this transport)."""
        base = self.checkpoint
        os.makedirs(os.path.dirname(base) or ".", exist_ok=True)
        with open(base + ".system.md", "w", encoding="utf-8") as fh:
            fh.write(system)
        with open(base + ".user.md", "w", encoding="utf-8") as fh:
            fh.write(user)
        req = {
            "kind": kind, "step": step_key,
            "tools": tools, "permission_mode": permission_mode,
            "system_path": base + ".system.md",
            "user_path": base + ".user.md",
            "response_path": base + ".response.md",
            "instructions": instructions or (
                "Perform this task YOURSELF, in this conversation. Read "
                "system_path + user_path and treat them as your ONLY standards "
                "and context (ignore anything else you know about this "
                "session). Use the listed tools within the permission mode. "
                "Write your full final reply — ending with the required "
                "```json fence — to response_path, then re-run the resume "
                "command. Do not edit the checkpoint state file."),
            "resume": self._resume_cmd(),
        }
        req.update(extra or {})
        raise Suspend(req)

    def _suspend_simple(self, request):
        """Suspend WITHOUT payload sidecars (kinds ask/select/hook): the
        launcher needs only the request itself. This is the D1 interaction
        channel — it works under EVERY strategy (strategies govern who
        GENERATES; the checkpoint carries everything human-facing)."""
        base = self.checkpoint
        os.makedirs(os.path.dirname(base) or ".", exist_ok=True)
        request.setdefault("response_path", base + ".response.md")
        request.setdefault("resume", self._resume_cmd())
        raise Suspend(request)

    def _resume_cmd(self):
        cmd = f"python3 {sys.argv[0]} {self.opts.workflow} --checkpoint {self.checkpoint}"
        return cmd + (" --json" if self.opts.json else "")

    def _suspend_apply(self, step_key, artifact, tools, permission_mode):
        """Strategy 2 (sdk-apply) handoff: the isolated SDK generation already
        DECIDED the changes (full intended file contents, in `artifact`); the
        invoking agent only applies them. Same suspend/resume channel."""
        base = self.checkpoint
        os.makedirs(os.path.dirname(base) or ".", exist_ok=True)
        with open(base + ".artifact.md", "w", encoding="utf-8") as fh:
            fh.write(artifact or "")
        raise Suspend({
            "kind": "apply", "step": step_key,
            "tools": tools, "permission_mode": permission_mode,
            "artifact_path": base + ".artifact.md",
            "response_path": base + ".response.md",
            "instructions": (
                "An ISOLATED generation already decided these changes — apply "
                "them, do not redesign them. Read artifact_path and write its "
                "file contents EXACTLY to the paths it names, using the listed "
                "tools within the permission mode. Then write your full final "
                'reply — ending with a fenced block ```json {"status":"ok",'
                '"files":["<path you wrote>"],"summary":"<one line>"} ``` — to '
                "response_path, and re-run the resume command."),
            "resume": self._resume_cmd(),
        })

    # -- context assembly (the "Builds Complete Context" box) -----------------
    def _read(self, path):
        try:
            with open(path, encoding="utf-8") as fh:
                return fh.read()
        except OSError:
            return ""

    def _collect_files(self, entries, kind):
        """Resolve a normalized [(path, optional)] list to the files that exist,
        HONOURING the `optional:` flag (item H).

        Both assembly paths used to do `for p, _ in entries` and filter on
        os.path.exists alone — the flag was parsed by _norm_files and then
        discarded, so a missing REQUIRED standard/context file was dropped
        exactly as silently as an optional one. The payload simply came up
        short (an empty '# ENGINEERING STANDARDS & RULES' heading, a domain
        constitution the task text still claimed was 'in context') and every
        workflow went on to report OK. Required now ANNOUNCES itself.

        It announces rather than stops: a declared context path is often
        legitimately conditional (a delta doc on the bootstrap path, an
        overlay before a domain is selected), so a hard stop here would fail
        green flows. Workflows that genuinely require a file gate on it
        deliberately — verify_context `required_files`, or `context_missing_count`
        against the run-cumulative set (cf. concept-paths' `missing`).

        A path that resolves to "" is an unbound {{var}} on this branch, not a
        missing file — skipped silently, as before."""
        files, seen = [], set()
        for p, optional in entries:
            rp = self.resolve(p)
            if not rp or rp in seen:
                continue
            if os.path.exists(rp):
                seen.add(rp)
                files.append(rp)
            elif optional:
                self.emit(f"[{kind}] optional missing, skip {rp}")
            else:
                self.emit(f"[{kind}] MISSING (required): {rp}")
                if rp not in self.missing_required:
                    self.missing_required.append(rp)
        self.vars["context_missing"] = ",".join(self.missing_required)
        self.vars["context_missing_count"] = str(len(self.missing_required))
        return files

    def _assemble_system(self, include_standards=True):
        """The interpreter-authored SYSTEM block: the sticky standards set (F4)
        + the envelope's per-request system files. The standards prefix is
        byte-stable across steps — the prompt-cache lever in a real deployment.
        include_standards=False is the decl `include_loaded_context: false`
        analog for narrow judgments (e.g. a constitution gate)."""
        entries = (_norm_files(self.standards) if include_standards else [])
        entries += _norm_files(self.envelope["system"])
        files = self._collect_files(entries, "system")
        self._track_loaded(files)
        parts = [
            "You are a fresh generation agent invoked by the AppWeaver spec "
            "interpreter. Follow ONLY the standards and the task provided. Do "
            "not assume any prior conversation.\n",
            "\n# ENGINEERING STANDARDS & RULES (authoritative)\n",
        ]
        for f in files:
            parts.append(f"\n===== RULE FILE: {f} =====\n{self._read(f)}\n")
        return "".join(parts), files

    def _assemble_user(self, task, extra=None):
        """The interpreter-authored USER block: prior artifacts + the task.
        `extra` = per-step context paths appended for THIS request only. Both
        lists go through _norm_files, so a step-level `context:` entry may use
        the { path:, optional: } form too — it used to be filtered out for not
        being a str, i.e. dropped even harder than a missing file."""
        entries = _norm_files(self.envelope["context"]) + _norm_files(extra or [])
        files = self._collect_files(entries, "context")
        self._track_loaded(files)
        parts = []
        if files:
            parts.append("# CONTEXT ARTIFACTS\n")
            for f in files:
                parts.append(f"\n===== FILE: {f} =====\n{self._read(f)}\n")
        parts.append("\n# TASK\n" + task)
        return "".join(parts), files

    def _track_loaded(self, files):
        for f in files:
            if f not in self.loaded:
                self.loaded.append(f)

    # -- the fresh-generation transport ---------------------------------------
    def _print_envelope(self, kind, system, sys_files, user, ctx_files, tools, strat=None):
        if self.opts.transport == "mock":
            tag = "transport=mock" + (f"  strategy={strat}" if strat else "")
        elif strat == "agent":
            tag = "strategy=agent (INVOKING agent fulfills — no new instance)"
        elif strat == "sdk":
            tag = "strategy=sdk (isolated SDK instance generates + implements)"
        elif strat == "sdk-apply":
            tag = "strategy=sdk-apply (isolated SDK generates; invoking agent applies)"
        else:
            tag = (f"strategy=spawn  agent={(self.profile or {}).get('name', '?')}"
                   f"  isolation={self.opts.isolation}")
        head = "AGENT REQUEST" if strat == "agent" else "FRESH AGENT INVOCATION"
        self.emit(f"\n{BANNER}\n{head}  ({kind})   {tag}")
        self.emit(f"  tools : {tools or '(none / read-only)'}")
        self.emit(f"  system: {len(system)} chars  files={sys_files}")
        self.emit(f"  user  : {len(user)} chars  context={ctx_files}")
        if strat == "agent":
            self.emit("  isolation: BEST-EFFORT — the payload is interpreter-assembled, "
                      "but it runs in the invoking agent's own conversation.")
        elif strat == "sdk-apply":
            self.emit("  isolation: generation is fully isolated; only the APPLY phase "
                      "runs in the invoking agent.")
        else:
            self.emit("  isolation: the fresh agent sees ONLY the two blocks below — "
                      "NOT this orchestrator's conversation.")
        cut = None if self.opts.show_full else 1400
        self.emit("\n── SYSTEM (--system-prompt) ──")
        self.emit(system if cut is None else system[:cut] + ("\n…[truncated; --show-full]" if len(system) > cut else ""))
        self.emit("\n── USER (stdin) ──")
        self.emit(user if cut is None else user[:cut] + ("\n…[truncated; --show-full]" if len(user) > cut else ""))
        self.emit(BANNER)

    def _run_fresh(self, system, user, tools, permission_mode, model=None):
        """Invoke a fresh, isolated generation using the loaded agent PROFILE.
        Returns (structured, raw).

        The engine is agent-agnostic: the profile (agent-specific, from a
        .claude/.agents/.kilocode file) declares the CLI to spawn. A SEPARATE
        process → a brand-new conversation that does NOT inherit this
        orchestrator's transcript. The profile maps our neutral knobs
        (system / user / tools / permission_mode / isolation / model / budget)
        onto that CLI's actual flags."""
        if self.opts.transport == "mock":
            # No model call. The banner (already printed) is the demonstration.
            return None, None
        prof = self.profile or {}
        argv = [prof["bin"]] + list(prof.get("args", []))
        model = model or self.opts.model   # per-step `model:` beats --model
        if model and prof.get("model_flag"):
            argv += [prof["model_flag"], model]
        # system: either injected as a CLI flag, or folded into the prompt when
        # the CLI has no system-prompt flag (e.g. gemini).
        sysmode = prof.get("system", "prepend")
        prompt_user = user
        if isinstance(sysmode, dict) and sysmode.get("flag"):
            argv += [sysmode["flag"], system]
        elif sysmode == "prepend":
            prompt_user = system + "\n\n---\n\n" + user
        if tools and prof.get("tools_flag"):
            argv += [prof["tools_flag"], tools]
        approval = prof.get("approval", {})
        argv += approval.get(permission_mode, approval.get("default", []))
        argv += prof.get("isolation", {}).get(self.opts.isolation, [])
        if self.opts.budget and prof.get("budget_flag"):
            argv += [prof["budget_flag"], str(self.opts.budget)]
        umode = prof.get("user", {"mode": "stdin"})
        stdin_data = None
        if umode.get("mode") == "arg":
            argv += [umode.get("flag", "-p"), prompt_user]
        else:
            stdin_data = prompt_user

        if self.opts.dry_run:
            shown = [a if len(a) < 120 else f"<{len(a)} chars>" for a in argv]
            self.emit(f"[dry-run] {prof.get('name', '?')} would run:\n  " + " ".join(shown))
            if stdin_data is not None:
                self.emit(f"[dry-run] + stdin: {len(stdin_data)} chars")
            raise Stop("dry-run: command shown above (nothing executed)")

        proc = subprocess.run(argv, input=stdin_data, capture_output=True, text=True)
        if proc.returncode != 0:
            raise Stop(f"fresh agent failed ({proc.returncode}): {proc.stderr.strip()[:500]}")
        try:
            obj = json.loads(proc.stdout)
        except Exception:
            return _extract_json(proc.stdout), proc.stdout  # text-output fallback
        raw = ""
        for k in prof.get("result_keys", ["result"]):
            if isinstance(obj, dict) and obj.get(k):
                raw = obj[k]
                break
        if not raw:
            raw = proc.stdout
        return _extract_json(raw), raw

    def _ensure_sdk_module(self, module_name, package_name):
        """Import the profile-declared sdk module; if missing, optionally pip
        install the profile-declared package (--sdk-install or the sdk block's
        `auto_install: true`), then import again."""
        try:
            return importlib.import_module(module_name)
        except ImportError:
            allowed = (getattr(self.opts, "sdk_install", False)
                       or bool(((self.profile or {}).get("sdk") or {}).get("auto_install")))
            if not allowed:
                raise Stop(f"strategy 'sdk'/'sdk-apply' needs the '{package_name}' "
                           f"package (module '{module_name}', declared in the agent "
                           f"profile's sdk block): pip install {package_name}, or "
                           "re-run with --sdk-install to install it automatically")
        self.emit(f"[sdk] module '{module_name}' not importable — installing "
                  f"'{package_name}' (declared in the agent profile) …")
        cmd = [sys.executable, "-m", "pip", "install", package_name]
        proc = subprocess.run(cmd, capture_output=True, text=True)
        if proc.returncode != 0 and "externally-managed-environment" in (proc.stderr or ""):
            # PEP 668 python (e.g. Homebrew): fall back to a user-site install
            self.emit("[sdk] environment is externally managed — retrying with "
                      "--user --break-system-packages")
            proc = subprocess.run(cmd + ["--user", "--break-system-packages"],
                                  capture_output=True, text=True)
        if proc.returncode != 0:
            raise Stop(f"pip install {package_name} failed: {proc.stderr.strip()[:400]}")
        importlib.invalidate_caches()
        try:
            return importlib.import_module(module_name)
        except ImportError as e:
            raise Stop(f"installed '{package_name}' but module '{module_name}' "
                       f"still won't import: {e}")

    def _load_sdk_adapter(self, adapter_rel):
        """Load the profile-declared adapter file (the Python module that owns
        that SDK's calling convention; shared per-SDK adapters live in
        .aw-spec/orchestrator/adapters/) and return its generate(request)
        callable. Paths are relative to the profile file."""
        base = getattr(self.opts, "profile_dir", "") or "."
        path = adapter_rel if os.path.isabs(adapter_rel) else os.path.join(base, adapter_rel)
        if not os.path.exists(path):
            raise Stop(f"sdk adapter not found: {path} (sdk.adapter in the agent "
                       "profile) — point it at an existing adapter (shared ones "
                       "live in .aw-spec/orchestrator/adapters/)")
        try:
            spec = importlib.util.spec_from_file_location("aw_sdk_adapter", path)
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
        except Exception as e:
            raise Stop(f"sdk adapter {path} failed to load: {e}")
        fn = getattr(mod, "generate", None)
        if not callable(fn):
            raise Stop(f"sdk adapter {path} must export generate(request)")
        return fn

    def _run_sdk(self, system, user, tools, permission_mode, model=None):
        """Strategy 1/2 executor: an isolated generation via the agent's SDK.
        Each call is a NEW session — the only context is the payload we pass
        (system + user). Returns (structured, raw).

        Agent-agnostic, like `spawn`: the engine has NO built-in SDK and no
        default agent — EVERYTHING SDK-specific comes from the loaded
        profile's `sdk` block (agent.json):
          module / package   what to import; installed on demand when missing
                             (--sdk-install or sdk.auto_install)
          adapter            REQUIRED — a Python file (path relative to the
                             profile; shared per-SDK adapters live in
                             .aw-spec/orchestrator/adapters/) exporting
                             generate(request) -> reply text; it owns that
                             SDK's calling convention (sync or async)
        Everything is imported lazily so the engine stays stdlib-only
        otherwise."""
        if not self.profile:
            raise Stop("strategy 'sdk'/'sdk-apply' needs --agent-profile — the "
                       "profile's sdk block declares the SDK to use (the engine "
                       "has no default agent)")
        sdk_cfg = self.profile.get("sdk") or {}
        module_name = sdk_cfg.get("module")
        package_name = sdk_cfg.get("package")
        adapter_rel = sdk_cfg.get("adapter")
        missing = [k for k, v in (("module", module_name), ("package", package_name),
                                  ("adapter", adapter_rel)) if not v]
        if missing:
            raise Stop(f"agent profile '{self.profile.get('name', '?')}': sdk block "
                       f"is missing {', '.join(missing)} — strategy 'sdk'/'sdk-apply' "
                       "is fully profile-driven (no built-in default); declare the "
                       "sdk module/package to import and the adapter file that "
                       "drives it")

        if self.opts.dry_run:
            self.emit(f"[dry-run] sdk would run: module={module_name}  "
                      f"package={package_name}  adapter={adapter_rel}  "
                      f"system={len(system)} chars  user={len(user)} chars  "
                      f"tools={tools or '(none)'}  permission_mode={permission_mode}")
            raise Stop("dry-run: sdk request shown above (nothing executed)")

        self._ensure_sdk_module(module_name, package_name)
        generate = self._load_sdk_adapter(adapter_rel)
        import asyncio
        request = {"system": system, "user": user, "tools": tools,
                   "permission_mode": permission_mode,
                   "model": model or self.opts.model or None, "sdk": sdk_cfg}
        try:
            out = generate(request)
            raw = asyncio.run(out) if asyncio.iscoroutine(out) else out
        except Stop:
            raise
        except Exception as e:
            raise Stop(f"sdk adapter '{adapter_rel}' generation failed: {e}")
        if not isinstance(raw, str):
            raise Stop(f"sdk adapter '{adapter_rel}' generate(request) must return "
                       "the reply text (str)")
        return _extract_json(raw), raw

    # -- actions --------------------------------------------------------------
    def act_set(self, step):
        assigns = step.get("vars") or step.get("parameters") or {}
        for k, v in assigns.items():
            self.vars[k] = self.resolve_value(v)
        self.emit(f"[set] {list(assigns.keys())}")

    def act_build_context(self, step):
        ctx = list(step.get("context", []) or [])
        # dynamic context: append a var holding a list of paths — e.g. the files a
        # prior agent_generate reported it wrote (since IT, not we, chose them).
        cf = step.get("context_from")
        if cf:
            ctx += list(self.vars.get(cf) or [])
        self.envelope = {"system": step.get("system", []) or [], "context": ctx}
        for k, v in (step.get("vars", {}) or {}).items():
            self.vars[k] = self.resolve(v)
        sysn = len(_norm_files(self.envelope["system"]))
        self.emit(f"[build_context] system={sysn} file(s)  context={len(ctx)} file(s)")

    def act_agent_generate(self, step):
        tools = step.get("tools", "Read,Write,Edit,Bash")
        permission_mode = step.get("permission_mode", "acceptEdits")
        task = self.resolve(step.get("task", ""))
        strat = self._effective_strategy(step)
        # checkpoint replay: this step was already fulfilled (any strategy) —
        # bind its cached structured result instead of executing again.
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            structured = self.cache[ck]
            self.last_result = structured
            self._bind(step, structured)
            self.emit(f"[agent_generate] (cached) result={json.dumps(structured)[:200]}")
            return
        # The interpreter does NOT dictate output paths. The generating runtime +
        # LLM decide where files go (per the loaded folder-structure/architecture
        # standards) and report back the paths.
        if strat == "sdk-apply" and self.opts.transport != "mock":
            # Strategy 2: generation is read-only — it DECIDES paths + content;
            # the invoking agent applies them afterwards (via suspend "apply").
            instr = task + (
                "\n\nDecide the correct file path(s) yourself by following the "
                "loaded standards (folder-structure / architecture rules) and "
                "the project's existing layout, but DO NOT write any files — "
                "you have no write tools. Output the COMPLETE intended content "
                "of every file in your reply: one fenced code block per file, "
                "each immediately preceded by its path, so another process can "
                "apply it verbatim."
                '\n\nEnd your reply with a fenced block:\n```json\n{"status":"ok",'
                '"planned_files":["<path>"],"summary":"<one line>"}\n```')
        else:
            instr = task + (
                "\n\nDecide the correct file path(s) yourself by following the loaded "
                "standards (folder-structure / architecture rules) and the project's "
                "existing layout. Create or edit them with your Write/Edit tools."
                '\n\nWhen done, end your reply with a fenced block listing the paths YOU '
                'chose to write:\n```json\n{"status":"ok","files":["<path you wrote>"],'
                '"summary":"<one line>"}\n```')
        system, sys_files = self._assemble_system()
        user, ctx_files = self._assemble_user(instr)
        self._print_envelope("agent_generate", system, sys_files, user, ctx_files, tools, strat)

        if self.opts.transport == "mock":
            structured = self._mock_generate(task)
        elif strat == "agent":
            self._suspend("agent_generate", ck, system, user, tools, permission_mode)
        elif strat == "sdk":
            structured, _ = self._run_sdk(system, user, tools, permission_mode,
                                          model=step.get("model"))
        elif strat == "sdk-apply":
            _, raw = self._run_sdk(system, user, "Read", "readonly",
                                   model=step.get("model"))
            self._suspend_apply(ck, raw, tools, permission_mode)
        else:  # spawn
            structured, _ = self._run_fresh(system, user, tools, permission_mode,
                                            model=step.get("model"))
        self.last_result = structured
        if self.checkpoint:
            self.cache[ck] = structured
        self._bind(step, structured)
        self.emit(f"[agent_generate] strategy={strat or 'mock'} "
                  f"result={json.dumps(structured)[:200]}")

    def act_agent_review(self, step):
        # Review the files the generation actually produced. Prefer a var holding
        # the reported paths (review_of_var) over any statically-listed review_of.
        if step.get("review_of_var"):
            review_of = list(self.vars.get(step["review_of_var"]) or [])
        else:
            review_of = [self.resolve(r) for r in (step.get("review_of", []) or [])]
        task = self.resolve(step.get("task", ""))
        instr = task + "\n\nFiles under review:\n" + "\n".join(f"- {r}" for r in review_of)
        instr += ('\n\nEnd your reply with a fenced block:\n'
                  '```json\n{"pass":true,"issues":[]}\n```')
        # review is read-only: put the files to review INTO context, tools=Read only
        # (mutate BEFORE the checkpoint-cache branch so a replayed run rebuilds
        # the exact same envelope state for the steps that follow)
        self.envelope["context"] = list(self.envelope["context"]) + review_of
        strat = self._effective_strategy(step)
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            structured = self.cache[ck]
            self.last_result = structured
            self._bind(step, structured)
            self.emit(f"[agent_review] (cached) result={json.dumps(structured)[:200]}")
            return
        system, sys_files = self._assemble_system()
        user, ctx_files = self._assemble_user(instr)
        self._print_envelope("agent_review", system, sys_files, user, ctx_files, "Read", strat)

        if self.opts.transport == "mock":
            # mock: pass if every reviewed file exists
            ok = all(os.path.exists(r) for r in review_of)
            structured = {"pass": ok, "issues": ([] if ok else ["missing output file(s)"])}
        elif strat == "agent":
            self._suspend("agent_review", ck, system, user, "Read", "readonly")
        elif strat in ("sdk", "sdk-apply"):
            # review has no apply phase — sdk-apply degrades to a plain sdk read
            structured, _ = self._run_sdk(system, user, "Read", "readonly",
                                          model=step.get("model"))
        else:  # spawn
            structured, _ = self._run_fresh(system, user, "Read", "acceptEdits",
                                            model=step.get("model"))
        self.last_result = structured
        if self.checkpoint:
            self.cache[ck] = structured
        self._bind(step, structured)
        self.emit(f"[agent_review] strategy={strat or 'mock'} "
                  f"result={json.dumps(structured)[:200]}")

    def _mock_generate(self, task):
        # No output path was specified — the mock stands in for the runtime/LLM
        # DECIDING one. Here it lifts a name from the first `backtick` token in the
        # task and places it under the out_dir workspace hint. A real fresh agent
        # would instead derive the path from the loaded folder-structure standard.
        first = task.strip().splitlines()[0] if task.strip() else ""
        m = re.search(r"`([A-Za-z_][A-Za-z0-9_]*)`", task)
        name = m.group(1) if m else "GeneratedComponent"
        out_dir = self.vars.get("out_dir") or ".aw-spec/orchestrator/.demo-out"
        path = os.path.join(out_dir, name + ".cs")
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        with open(path, "w", encoding="utf-8") as fh:
            fh.write(
                "// [mock fresh-agent output]\n"
                "// The PATH was decided by the fresh runtime (mock stand-in), NOT\n"
                "// specified by the interpreter.\n"
                f"// saw only: system={[self.resolve(p) for p,_ in _norm_files(self.envelope['system'])]}\n"
                f"//           context={[self.resolve(p) for p,_ in _norm_files(self.envelope['context'])]}\n"
                f"// task: {first}\n")
        return {"status": "ok", "files": [path], "summary": f"mock implemented: {first}"}

    # -- F1: deterministic scripts ---------------------------------------------
    def _script_path(self, ref):
        variants = self.scripts.get(ref) or {}
        return variants.get("ps1" if self.opts.os == "windows" else "sh")

    def act_execute_script(self, step):
        """F1 — run a shared deterministic script (decl `execute_script` port).
        Top-level `scripts:` declares {ref: {sh:…, ps1:…}}; --os picks the
        variant. stdout's LAST line must be JSON, bound via outputs[]. Results
        enter the replay cache, so scripts never re-fire across resumes.
        Scripts run for real even under the mock transport (they are the
        deterministic, model-free part of every skill)."""
        p = step.get("parameters") or step
        ref = (p.get("script") or {}).get("ref")
        script = self._script_path(ref)
        if not script or not os.path.exists(script):
            raise Stop(f"step {step.get('id')}: script not found for ref '{ref}': {script}")
        sub = p.get("subcommand")
        args = [self.resolve(a) for a in (p.get("args") or [])]
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self._bind(step, self.cache[ck])
            self.emit(f"[execute_script] {sub} (cached)")
            return
        runner = (["pwsh", "-NoProfile", "-File", script]
                  if self.opts.os == "windows" else ["bash", script])
        self.emit(f"[execute_script] {sub} {' '.join(args)}")
        if self.opts.dry_run:
            self._bind(step, {})
            return
        proc = subprocess.run(runner + [sub] + args, capture_output=True, text=True)
        if proc.returncode != 0:
            if p.get("on_error") == "continue":
                self.emit(f"[execute_script] {sub} failed (continuing): "
                          f"{proc.stderr.strip()[:200]}")
                self._bind(step, {})
                return
            raise Stop(f"script failed ({sub}): {proc.stderr.strip()[:500]}")
        try:
            data = json.loads(proc.stdout.strip().splitlines()[-1])
        except Exception as e:
            raise Stop(f"script did not return JSON ({sub}): {proc.stdout!r} ({e})")
        self._bind(step, data)
        if self.checkpoint:
            self.cache[ck] = data
        self.emit(f"[execute_script] -> {json.dumps(data)[:200]}")

    # -- F2: gates ---------------------------------------------------------------
    def act_verify_context(self, step):
        """F2 — the four decl gate forms: required_files (+allow_missing),
        require_non_empty (+on_empty), require_true (+on_false),
        require_value/equals (+on_mismatch). Messages interpolate {{vars}}."""
        p = step.get("parameters") or step
        if p.get("require_non_empty"):
            var = p["require_non_empty"]
            val = self.vars.get(var)
            if not val:
                msg = self.resolve(p.get("on_empty_message", f"{var} is empty"))
                self.emit(f"[verify_context] {var} is empty: {msg}")
                if p.get("on_empty") == "stop":
                    raise Stop(msg)
            else:
                self.emit(f"[verify_context] {var} non-empty")
        if p.get("require_true"):
            var = p["require_true"]
            v = self.vars.get(var)
            truthy = (v.strip() not in ("", "false", "False", "None", "null", "[]")
                      if isinstance(v, str) else bool(v))
            if not truthy:
                msg = self.resolve(p.get("on_false_message", f"{var} is not satisfied"))
                self.emit(f"[verify_context] gate failed ({var}): {msg}")
                if p.get("on_false", "stop") == "stop":
                    raise Stop(msg)
            else:
                self.emit(f"[verify_context] gate ok ({var})")
        if p.get("require_value"):
            var = p["require_value"]
            actual = str(self.vars.get(var, ""))
            expected = str(self.resolve(p.get("equals", "")))
            if actual != expected:
                msg = self.resolve(p.get("on_mismatch_message", f"{var} != {expected}"))
                self.emit(f"[verify_context] value gate failed ({var}={actual!r}): {msg}")
                if p.get("on_mismatch", "stop") == "stop":
                    raise Stop(msg)
            else:
                self.emit(f"[verify_context] value gate ok ({var}=={expected})")
        for rf in p.get("required_files", []) or []:
            rf = self.resolve(rf)
            if rf in self.loaded or os.path.exists(rf):
                self.emit(f"[verify_context] present {rf}")
            elif p.get("allow_missing"):
                self.emit(f"[verify_context] missing (allowed) {rf}")
            else:
                raise Stop(f"required file not in context: {rf}")

    # -- F4: sticky standards ------------------------------------------------------
    def act_load_standards(self, step):
        """F4 — append files to the sticky standards set (dedup; `optional:`
        tolerated). _assemble_system prepends the set to EVERY payload, so a
        skill loads its standards once (decl load_context → system per D3)."""
        p = step.get("parameters") or step
        files = p.get("files") or []
        if p.get("files_from_variable"):
            files = [{"path": x} for x in (self.vars.get(p["files_from_variable"]) or [])]
        step_optional = p.get("optional", False)
        have = {self.resolve(pp) for pp, _ in _norm_files(self.standards)}
        for f in files:
            path = self.resolve(f["path"] if isinstance(f, dict) else f)
            optional = f.get("optional", step_optional) if isinstance(f, dict) else step_optional
            if path in have:
                self.emit(f"[load_standards] dedup skip {path}")
                continue
            if os.path.exists(path):
                self.standards.append({"path": path})
                have.add(path)
                self.emit(f"[load_standards] loaded {path}")
            elif optional:
                self.emit(f"[load_standards] optional missing, skip {path}")
            else:
                raise Stop(f"required standards file missing: {path}")

    # -- F5: authored artifacts ------------------------------------------------
    def _write_target(self, target, content):
        os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
        with open(target, "w", encoding="utf-8") as fh:
            fh.write(content)

    def _mock_author(self, target, task):
        sysf = [self.resolve(p) for p, _ in _norm_files(self.envelope["system"])]
        ctxf = [self.resolve(p) for p, _ in _norm_files(self.envelope["context"])]
        return ("<!-- authored by aw-orchestrator MOCK transport -->\n"
                f"<!-- target: {target} -->\n"
                f"<!-- envelope: system={sysf} context={ctxf} -->\n"
                f"<!-- task chars: {len(task)} -->\n\n# (mock content)\n")

    def act_agent_author(self, step):
        """F5 — authored artifact (decl `llm_generate` port): the INTERPRETER
        owns output_target.path (scaffold scripts created it). Generation is
        READ-ONLY under EVERY strategy — the returned content is written by
        the ENGINE, so sdk-apply needs no apply phase and degrades to sdk.
        The replay cache stores the raw content (idempotent rewrites)."""
        p = step.get("parameters") or step
        target = self.resolve((p.get("output_target") or {}).get("path", ""))
        if not target:
            raise Stop(f"step {step.get('id')}: agent_author needs output_target.path")
        task = self.resolve(p.get("task") or p.get("prompt") or "")
        extra = [c for c in (self.resolve_value(p.get("context")) or []) if isinstance(c, (str, dict))]
        strat = self._effective_strategy(step)
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self._write_target(target, self.cache[ck])
            structured = {"status": "ok", "files": [target], "summary": f"authored {target}"}
            self.last_result = structured
            self._bind(step, structured)
            self.emit(f"[agent_author] (cached) rewrote {target}")
            return
        instr = task + (
            f"\n\nAuthor the COMPLETE content of the file `{target}`. You have "
            "no write tools — return the content itself. Reply with ONLY the "
            "full file content: no commentary, no surrounding code fence.")
        system, sys_files = self._assemble_system(p.get("include_standards", True))
        user, ctx_files = self._assemble_user(instr, extra=extra)
        self._print_envelope("agent_author", system, sys_files, user, ctx_files, "Read", strat)
        if self.opts.transport == "mock":
            content = self._mock_author(target, task)
        elif strat == "agent":
            self._suspend("author", ck, system, user, "Read", "readonly",
                          instructions=(
                              "Author this artifact YOURSELF, in this conversation. "
                              "Read system_path + user_path as your ONLY standards "
                              "and context. Write the COMPLETE file content — the "
                              "content ONLY, no commentary, no code fence — to "
                              "response_path, then re-run the resume command. Do "
                              "NOT write the target file yourself; the interpreter "
                              "does that."),
                          extra={"target": target})
        else:
            run = self._run_sdk if strat in ("sdk", "sdk-apply") else self._run_fresh
            _, raw = run(system, user, "Read", "readonly", model=step.get("model"))
            content = _strip_fence(raw)
            if not content.strip():
                raise Stop(f"step {step.get('id')}: agent_author returned empty content")
        if self.opts.dry_run:
            self.emit(f"[agent_author] dry-run: not writing {target}")
            return
        self._write_target(target, content)
        structured = {"status": "ok", "files": [target], "summary": f"authored {target}"}
        self.last_result = structured
        if self.checkpoint:
            self.cache[ck] = content
        self._bind(step, structured)
        self.emit(f"[agent_author] strategy={strat or 'mock'} wrote {target} "
                  f"({len(content)} chars)")

    # -- F6: structured queries --------------------------------------------------
    def _structured_fresh(self, step, strat, system, user):
        """spawn/sdk executor for JSON-returning steps, with ONE malformed-JSON
        retry (agent strategy instead re-suspends with a note on resume)."""
        run = self._run_sdk if strat in ("sdk", "sdk-apply") else self._run_fresh
        structured, _ = run(system, user, "Read", "readonly", model=step.get("model"))
        if not structured:
            self.emit(f"[retry] {step.get('id')}: no parseable ```json fence — asking once more")
            user2 = user + ("\n\nYour previous reply could not be parsed. Return "
                            "ONLY the required ```json fenced block, nothing else.")
            structured, _ = run(system, user2, "Read", "readonly", model=step.get("model"))
        if not structured:
            raise Stop(f"step {step.get('id')}: fresh agent returned no parseable JSON")
        return structured

    def act_agent_query(self, step):
        """F6 — generic READ-ONLY structured query (decl `llm_query` port): the
        caller states the JSON shape (schema:), the reply's trailing ```json
        fence is bound via outputs[]. agent_review stays the {pass,issues}
        specialization of this. `mock:` supplies the mock-transport result."""
        p = step.get("parameters") or step
        task = self.resolve(p.get("task") or p.get("prompt") or "")
        extra = [c for c in (self.resolve_value(p.get("context")) or []) if isinstance(c, (str, dict))]
        strat = self._effective_strategy(step)
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            structured = self.cache[ck]
            self.last_result = structured
            self._bind(step, structured)
            self.emit(f"[agent_query] (cached) result={json.dumps(structured)[:200]}")
            return
        schema = p.get("schema")
        hint = json.dumps(schema) if isinstance(schema, (dict, list)) else (schema or "{ … }")
        instr = task + ("\n\nDo not modify any files. End your reply with a "
                        "fenced block containing ONLY the JSON result, shaped "
                        "like:\n```json\n" + hint + "\n```")
        system, sys_files = self._assemble_system(p.get("include_standards", True))
        user, ctx_files = self._assemble_user(instr, extra=extra)
        self._print_envelope("agent_query", system, sys_files, user, ctx_files, "Read", strat)
        if self.opts.transport == "mock":
            structured = self.resolve_value(p.get("mock")) or {}
        elif strat == "agent":
            self._suspend("agent_query", ck, system, user, "Read", "readonly")
        else:
            structured = self._structured_fresh(step, strat, system, user)
        self.last_result = structured
        if self.checkpoint:
            self.cache[ck] = structured
        self._bind(step, structured)
        self.emit(f"[agent_query] strategy={strat or 'mock'} "
                  f"result={json.dumps(structured)[:200]}")

    # -- F7: HITL (D1 — the checkpoint is the interaction channel under EVERY
    #    strategy; --answer/--select/--non-interactive prefill for headless runs)
    def _prompt_choice(self, prompt, options):
        print(prompt)
        for i, o in enumerate(options, 1):
            print(f"  {i}) {o}")
        try:
            raw = input("> ").strip()
        except EOFError:
            return None
        if raw.isdigit() and 1 <= int(raw) <= len(options):
            return options[int(raw) - 1]
        return raw if raw in options else None

    def act_ask(self, step):
        """F7 — single/multi-select question. Answer sources, in order: replay
        cache → --answer key=value → --non-interactive default (first option;
        all for multi) → checkpoint suspend kind 'ask' (the launcher asks the
        USER) → interactive stdin. Binds answer_var (default 'answer')."""
        p = step.get("parameters") or step
        prompt = self.resolve(p.get("prompt", "?"))
        if p.get("options_from"):
            options = self.resolve_value(p["options_from"]) or []
        elif p.get("options_from_variable"):
            options = self.vars.get(p["options_from_variable"]) or []
        else:
            options = [self.resolve(o) for o in (p.get("options") or [])]
        multi = bool(p.get("multi"))
        key = self.resolve(p["answer_key"]) if p.get("answer_key") else step.get("id", "")
        var = p.get("answer_var", "answer")
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self.vars[var] = self.cache[ck]
            self.emit(f"[ask] {key} -> {self.cache[ck]} (cached)")
            return
        raw = self.opts.answers.get(key)
        if raw is None and self.opts.non_interactive:
            raw = ",".join(str(o) for o in options) if multi else \
                (options[0] if options else "")
        if raw is None and self.checkpoint:
            self._suspend_simple({
                "kind": "ask", "key": key, "step": ck,
                "prompt": prompt, "options": options, "multi": multi,
                "instructions": (
                    "Ask the USER this question (the options are the allowed "
                    "choices" + ("; several may be picked" if multi else "") +
                    "). Write the answer as PLAIN TEXT" +
                    (" (comma-separated)" if multi else "") +
                    " to response_path, then re-run the resume command.")})
        if raw is None:
            raw = self._prompt_choice(prompt, options) if options else \
                input(prompt + " ").strip()
        if raw is None:
            raise Stop("question cancelled")
        answer = [s.strip() for s in str(raw).split(",") if s.strip()] if multi else raw
        self.vars[var] = answer
        if self.checkpoint:
            self.cache[ck] = answer
        self.emit(f"[ask] {key} -> {answer}")

    def act_user_select(self, step):
        """F7 — pick ONE option from a variable. Order: replay cache →
        preselect_from (direct-argument fast path) → --select stepid=value →
        single_option_confirm → --non-interactive (first) → checkpoint suspend
        kind 'select' → interactive stdin. Binds `selection` + outputs[]."""
        p = step.get("parameters") or step
        options = self.vars.get(p.get("options_from_variable")) or []
        pre = p.get("preselect_from")
        pre_val = self.vars.get(pre) if pre else None
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            chosen = self.cache[ck]
        elif pre_val and pre_val in options:
            chosen = pre_val
        elif self.opts.selects.get(step.get("id")):
            chosen = self.opts.selects[step["id"]]
        elif len(options) == 1 and p.get("single_option_confirm"):
            chosen = options[0]
        elif self.opts.non_interactive:
            chosen = options[0] if options else None
        elif self.checkpoint:
            self._suspend_simple({
                "kind": "select", "step": ck,
                "prompt": self.resolve(p.get("prompt", "Select:")),
                "options": options,
                "instructions": (
                    "Ask the USER to pick ONE of the options. Write the chosen "
                    "value as plain text to response_path, then re-run the "
                    "resume command.")})
        else:
            chosen = self._prompt_choice(self.resolve(p.get("prompt", "Select:")), options)
        if not chosen:
            raise Stop("selection cancelled")
        self.vars["selection"] = chosen
        for out in step.get("outputs", []) or []:
            src = out["from"]
            self.vars[out["name"]] = chosen if src == "selection" else self.vars.get(src)
        if self.checkpoint:
            self.cache[ck] = chosen
        self.emit(f"[user_select] chosen: {chosen}")

    # -- F8: hooks ----------------------------------------------------------------
    def act_dispatch_hooks(self, step):
        """F8 — hand the resolved hooks (slash commands of the INVOKING agent)
        to the launcher via suspend kind 'hook' (D4 phase 1). Without a
        checkpoint (mock/CI) the intent is only logged, like run-skill. Cached
        so hooks never re-fire across resumes."""
        p = step.get("parameters") or step
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self.emit("[dispatch_hooks] (cached)")
            return
        hooks = self.vars.get(p.get("hooks_from_variable")) or []
        if not hooks:
            self.emit("[dispatch_hooks] none")
            if self.checkpoint:
                self.cache[ck] = True
            return
        for h in hooks:
            kind = "optional" if h.get("optional") else "mandatory"
            self.emit(f"[dispatch_hooks] {kind}: {h.get('slash')} ({h.get('extension')})")
        if self.checkpoint and self.opts.transport != "mock":
            self._suspend_simple({
                "kind": "hook", "step": ck, "hooks": hooks,
                "instructions": (
                    "Run each MANDATORY hook (a slash command of YOUR agent) in "
                    "this conversation; optional hooks are at your discretion. "
                    "Then write 'done' to response_path and re-run the resume "
                    "command.")})
        if self.checkpoint:
            self.cache[ck] = True

    # -- F9: modules --------------------------------------------------------------
    def act_include(self, step):
        """F9 — run a module .orch.yaml inline: shares vars, envelope, sticky
        standards, the caller's scripts map and the replay cache. `with:` seeds
        module inputs; cache keys are namespaced under the include id. Stop
        propagates to the caller (module gates stop the whole skill)."""
        module_path = self.resolve(step.get("module", ""))
        for k, v in (step.get("with", {}) or {}).items():
            self.vars[k] = self.resolve_value(v)
        try:
            with open(module_path, encoding="utf-8") as fh:
                mod = load_yaml(fh.read())
        except OSError as e:
            raise Stop(f"include: module not found: {module_path} ({e})")
        # module-declared scripts extend the caller's map (caller wins on clash)
        for ref, variants in (mod.get("scripts", {}) or {}).items():
            self.scripts.setdefault(ref, variants)
        self.standards += list(mod.get("standards", []) or [])
        self.emit(f"[include] {module_path}")
        self.key_stack.append("inc:" + step.get("id", "include"))
        try:
            self._run_steps(mod.get("workflow", []) or [])
        finally:
            self.key_stack.pop()

    # -- runner ---------------------------------------------------------------
    def _run_steps(self, steps):
        for step in steps:
            cond = step.get("condition")
            if cond is not None and not self._cond(cond):
                self.emit(f"[skip] {step.get('id')} (condition false)")
                continue
            action = step.get("action")
            if action == "break":
                return "break"
            if action == "loop":
                self._run_loop(step)
                continue
            fn = getattr(self, f"act_{action}", None)
            if fn is None:
                raise Stop(f"unknown action: {action}")
            fn(step)
        return None

    def _run_loop(self, step):
        """foreach (`over:` a list var, binding `as:`/`<as>_index`) or while
        (`while:` + `max_iterations`). F3: the foreach items come through
        resolve_value, so `over: "{{list}}"` yields the RAW list."""
        substeps = step.get("steps", []) or []
        loop_id = step.get("id", "loop")
        as_name = step.get("as", "item")
        max_it = step.get("max_iterations")
        if "over" in step:
            items = self.resolve_value(step["over"]) or []
            if isinstance(items, str):
                try:
                    items = json.loads(items)
                except Exception:
                    pass
            if not isinstance(items, list):
                raise Stop(f"loop '{loop_id}': 'over' is not a list: {step.get('over')}")
            for idx, item in enumerate(items):
                if max_it is not None and idx >= max_it:
                    break
                self.vars[as_name] = item
                self.vars[as_name + "_index"] = idx
                self.vars["iteration"] = idx
                self.emit(f"[loop] {loop_id} item {idx}")
                # iteration-scoped key prefix: each pass gets its own cache entries
                self.key_stack.append(f"{loop_id}#{idx}")
                try:
                    broke = self._run_steps(substeps) == "break"
                finally:
                    self.key_stack.pop()
                if broke:
                    break
            return
        max_it = 5 if max_it is None else max_it
        i = 0
        while self._cond(step.get("while", "true")):
            if i >= max_it:
                self.emit(f"[loop] {loop_id} hit max_iterations={max_it}")
                break
            self.vars["iteration"] = i
            self.vars[as_name + "_index"] = i
            self.emit(f"[loop] {loop_id} iteration {i}")
            # iteration-scoped key prefix: each pass gets its own cache entries
            self.key_stack.append(f"{loop_id}#{i}")
            try:
                broke = self._run_steps(substeps) == "break"
            finally:
                self.key_stack.pop()
            if broke:
                break
            i += 1

    def _bind_inputs(self):
        """F10 — bind the workflow's declared `inputs:` to --input (decl
        USER_INPUT shape). The bound value is persisted in the checkpoint
        state, so resumes keep it without re-passing --input."""
        for name, spec in (self.wf.get("inputs") or {}).items():
            if not isinstance(spec, dict) or not spec.get("bind"):
                continue
            bind = spec["bind"]
            if getattr(self.opts, "input", ""):
                self.vars[bind] = self.opts.input
            else:
                self.vars.setdefault(bind, "")
            if spec.get("required") and not self.vars.get(bind):
                raise Stop(f"input '{name}' is required — pass --input \"<text>\"")

    def run(self):
        self._bind_inputs()
        self._run_steps(self.wf.get("workflow", []) or [])
        return {"status": "ok", "outputs": self.resolve(self.wf.get("outputs", {}) or {}),
                "vars": self.vars, "missing_required": list(self.missing_required)}


# ─────────────────────────────────────────────────────────────────────────────
# F11 — static validator (--validate): lints a workflow without executing it.
# ─────────────────────────────────────────────────────────────────────────────
DIALECT = "aw-spec.orchestrator/v1"
KNOWN_ACTIONS = {
    "set", "build_context", "load_standards", "agent_generate", "agent_review",
    "agent_author", "agent_query", "execute_script", "verify_context",
    "dispatch_hooks", "user_select", "ask", "loop", "break", "include",
}
STRATEGIES = {"sdk", "sdk-apply", "spawn", "agent"}
# engine-produced vars a workflow may reference without declaring: the loop/ask
# bindings, plus the context-assembly miss report (_collect_files, item H).
_SPECIAL_VARS = {"selection", "answer", "iteration",
                 "context_missing", "context_missing_count"}


def _refs_in(v):
    found = set()
    if isinstance(v, str):
        for m in re.findall(r"\{\{\s*([^}]+?)\s*\}\}", v):
            found.add(m.strip())
    elif isinstance(v, list):
        for x in v:
            found |= _refs_in(x)
    elif isinstance(v, dict):
        for x in v.values():
            found |= _refs_in(x)
    return found


def validate_workflow(wf, base_dir):
    errors, warnings = [], []
    if not isinstance(wf, dict):
        return (["top-level YAML is not a mapping"], [])
    steps = wf.get("workflow")
    if not isinstance(steps, list) or not steps:
        errors.append("missing or empty 'workflow' list")
        steps = steps if isinstance(steps, list) else []
    if wf.get("dialect") not in (None, DIALECT):
        warnings.append(f"dialect is '{wf.get('dialect')}' — this engine implements {DIALECT}")
    elif not wf.get("dialect"):
        warnings.append(f"no 'dialect:' header (expected {DIALECT})")
    scripts = wf.get("scripts", {}) or {}

    def walk(ss):
        for s in ss or []:
            if isinstance(s, dict):
                yield s
                if s.get("action") == "loop":
                    yield from walk(s.get("steps"))

    def _params(s):
        return s.get("parameters") or s

    # pre-scan everything that produces variables, so ordering never false-alarms
    produced = set(_SPECIAL_VARS) | set((wf.get("vars") or {}).keys())
    for _, spec in (wf.get("inputs") or {}).items():
        if isinstance(spec, dict) and spec.get("bind"):
            produced.add(spec["bind"])

    def scan_produced(ss):
        for s in walk(ss):
            for o in s.get("outputs") or []:
                if isinstance(o, dict) and o.get("name"):
                    produced.add(o["name"])
            p = _params(s)
            act = s.get("action")
            if act == "ask":
                produced.add(p.get("answer_var", "answer"))
            elif act == "set":
                produced.update((s.get("vars") or s.get("parameters") or {}).keys())
            elif act == "build_context":
                produced.update((s.get("vars") or {}).keys())
            elif act == "loop":
                produced.add(s.get("as", "item"))
                produced.add(s.get("as", "item") + "_index")
            elif act == "include":
                produced.update((s.get("with") or {}).keys())
                mpath = s.get("module", "")
                for cand in (mpath, os.path.join(base_dir, mpath)):
                    if mpath and os.path.exists(cand):
                        try:
                            mwf = load_yaml(open(cand, encoding="utf-8").read())
                            scan_produced(mwf.get("workflow", []))
                        except Exception:
                            pass
                        break

    scan_produced(steps)

    seen_ids = set()
    for step in walk(steps):
        loc = step.get("id") or "step"
        sid = step.get("id")
        if not sid:
            warnings.append(f"{loc}: missing id")
        elif sid in seen_ids:
            errors.append(f"duplicate step id: {sid}")
        else:
            seen_ids.add(sid)

        action = step.get("action")
        if action not in KNOWN_ACTIONS:
            errors.append(f"{loc}: unknown action '{action}' "
                          f"(known: {', '.join(sorted(KNOWN_ACTIONS))})")
        if step.get("strategy") and step["strategy"] not in STRATEGIES:
            errors.append(f"{loc}: unknown strategy '{step['strategy']}' "
                          f"(known: {', '.join(sorted(STRATEGIES))})")
        p = _params(step)

        if action == "loop" and "over" not in step and "while" not in step:
            errors.append(f"{loc}: loop needs 'over:' or 'while:'")
        if action == "ask" and not (p.get("options_from") or p.get("options_from_variable")
                                    or p.get("options")):
            warnings.append(f"{loc}: ask has no options source (free-text input)")
        if action == "user_select" and not p.get("options_from_variable"):
            errors.append(f"{loc}: user_select needs options_from_variable")
        if action == "include":
            m = step.get("module")
            if not m:
                errors.append(f"{loc}: include needs 'module'")
            elif not (os.path.exists(m) or os.path.exists(os.path.join(base_dir, m))):
                warnings.append(f"{loc}: include module not found on disk: {m}")
        if action == "agent_query" and not step.get("outputs"):
            warnings.append(f"{loc}: agent_query has no outputs[] to bind")
        if action == "agent_author" and not (p.get("output_target") or {}).get("path"):
            errors.append(f"{loc}: agent_author needs output_target.path")
        if action in ("agent_generate", "agent_author", "agent_query") \
                and not (p.get("task") or p.get("prompt")):
            warnings.append(f"{loc}: {action} has an empty task")
        if action == "execute_script":
            ref = (p.get("script") or {}).get("ref")
            if not ref:
                errors.append(f"{loc}: execute_script needs script.ref")
            elif ref not in scripts:
                # a module declares no scripts: map — the ref resolves against
                # the INCLUDING caller's map, so standalone it's only a warning
                (warnings if not scripts else errors).append(
                    f"{loc}: script ref '{ref}' not declared in top-level scripts:"
                    + ("" if scripts else " (module? the including caller must declare it)"))
            else:
                variants = scripts.get(ref) or {}
                if not any(variants.get(v) and (os.path.exists(variants[v]) or
                           os.path.exists(os.path.join(base_dir, variants[v])))
                           for v in ("sh", "ps1")):
                    warnings.append(f"{loc}: no script variant file found on disk for ref '{ref}'")
            if not p.get("subcommand"):
                errors.append(f"{loc}: execute_script needs subcommand")

    used = _refs_in(steps) | _refs_in(wf.get("outputs", {}))
    for name in sorted(used):
        if name.split(".")[0] not in produced:
            warnings.append(f"variable {{{{{name}}}}} referenced but never produced")
    return errors, warnings


def _print_suspended(pending, opts):
    """Checkpoint transport: hand the pending request to the INVOKING agent."""
    if opts.json:
        print(json.dumps({"status": "suspended", "pending": pending}, indent=2))
    else:
        print("\n=== SUSPENDED (invoking agent: fulfill this, then resume) ===")
        print(json.dumps(pending, indent=2))


def _clear_checkpoint(opts):
    """Terminal end (ok/stopped): remove the state file and its sidecars."""
    if not opts.checkpoint:
        return
    for p in (opts.checkpoint, opts.checkpoint + ".system.md",
              opts.checkpoint + ".user.md", opts.checkpoint + ".artifact.md",
              opts.checkpoint + ".response.md"):
        if os.path.exists(p):
            os.remove(p)


def main(argv=None):
    ap = argparse.ArgumentParser(description="aw-orchestrator — interpreter-owned context, fresh-Claude execution")
    ap.add_argument("workflow")
    ap.add_argument("--transport", choices=["mock", "real"], default="mock",
                    help="mock = no model call (prints the payloads); "
                         "real = spawn the agent profile's CLI per generation")
    ap.add_argument("--agent-profile", default="", dest="agent_profile",
                    help="path to an agent transport profile JSON "
                         "(.claude/.agents/.kilocode/...); implies --transport real")
    ap.add_argument("--isolation", choices=["bare", "fresh"], default="bare",
                    help="selects the profile's isolation.<mode> args (bare = strongest)")
    ap.add_argument("--model", default="", help="model alias/name for the fresh agent")
    ap.add_argument("--budget", default="", help="value for the profile's budget_flag, if it declares one")
    ap.add_argument("--dry-run", action="store_true", dest="dry_run",
                    help="print the exact command the profile would run, without executing")
    ap.add_argument("--sdk-install", action="store_true", dest="sdk_install",
                    help="if the profile's sdk module isn't importable, pip install "
                         "the package its sdk block declares, then continue")
    ap.add_argument("--strategy", choices=["sdk", "sdk-apply", "spawn", "agent"],
                    default=None,
                    help="execution strategy for generations (per-step `strategy:` "
                         "overrides): sdk = isolated SDK instance generates + implements; "
                         "sdk-apply = isolated SDK generates, INVOKING agent applies "
                         "(needs --checkpoint); spawn = fresh CLI process per generation "
                         "(needs --agent-profile); agent = invoking agent fulfills via "
                         "suspend/resume, zero new instances (needs --checkpoint). "
                         "Omitted: inferred from --agent-profile/--checkpoint, else mock")
    ap.add_argument("--checkpoint", metavar="STATEFILE",
                    help="suspend/resume state file (run-skill.py method). Required by "
                         "strategies 'agent' and 'sdk-apply'; at each handoff the "
                         "interpreter writes the payload/artifact sidecars next to "
                         "STATEFILE and exits 2 so the INVOKING agent fulfills the "
                         "pending request (writes STATEFILE.response.md) and re-runs "
                         "the same command")
    ap.add_argument("--var", action="append", default=[], help="k=value (seed vars)")
    ap.add_argument("--input", default="",
                    help="positional user input, bound via the workflow's inputs: block")
    ap.add_argument("--answer", action="append", default=[],
                    help="key=value prefill for ask steps (key = answer_key, else step id)")
    ap.add_argument("--select", action="append", default=[],
                    help="stepid=value prefill for user_select steps")
    ap.add_argument("--non-interactive", action="store_true", dest="non_interactive",
                    help="asks answer with the first option (all options for multi), "
                         "selects take the first option — CI/smoke mode")
    default_os = "windows" if os.name == "nt" else "posix"
    ap.add_argument("--os", choices=["posix", "windows"], default=default_os,
                    help="script variant for execute_script (sh vs ps1)")
    ap.add_argument("--validate", action="store_true",
                    help="lint the workflow (static checks) without executing")
    ap.add_argument("--show-full", action="store_true", help="print entire payload, no truncation")
    ap.add_argument("--json", action="store_true")
    opts = ap.parse_args(argv)
    opts.vars = dict(v.split("=", 1) for v in opts.var if "=" in v)
    opts.answers = dict(s.split("=", 1) for s in opts.answer if "=" in s)
    opts.selects = dict(s.split("=", 1) for s in opts.select if "=" in s)

    # ---- F11: --validate lints and exits (never executes) --------------------
    if opts.validate:
        try:
            with open(opts.workflow, encoding="utf-8") as fh:
                wf = load_yaml(fh.read())
        except Exception as e:
            print(json.dumps({"status": "invalid", "errors": [f"parse: {e}"]})
                  if opts.json else f"ERROR: parse: {e}")
            return 1
        errors, warnings = validate_workflow(
            wf, os.path.dirname(os.path.abspath(opts.workflow)))
        if opts.json:
            print(json.dumps({"status": "valid" if not errors else "invalid",
                              "errors": errors, "warnings": warnings}, indent=2))
        else:
            for w in warnings:
                print("WARN: ", w)
            for e in errors:
                print("ERROR:", e)
            print(f"\n{opts.workflow}: {len(errors)} error(s), {len(warnings)} warning(s)")
        return 1 if errors else 0

    # ---- checkpoint mode: load prior state + ingest the agent's response ----
    # (before profile/strategy resolution, so a bare `--checkpoint` resume
    # restores the original run's profile/strategy/model/os and prefills)
    opts._cache = {}
    if opts.checkpoint and os.path.exists(opts.checkpoint):
        with open(opts.checkpoint, encoding="utf-8") as fh:
            state = json.load(fh)
        opts._cache = state.get("cache", {})
        # replay with the original seeds; freshly passed flags override/extend
        merged = dict(state.get("vars", {}))
        merged.update(opts.vars)
        opts.vars = merged
        if not opts.strategy and state.get("strategy"):
            opts.strategy = state["strategy"]
        if not opts.model and state.get("model"):
            opts.model = state["model"]
        if not opts.agent_profile and state.get("agent_profile"):
            opts.agent_profile = state["agent_profile"]
        if opts.isolation == "bare" and state.get("isolation"):
            opts.isolation = state["isolation"]
        if opts.os == default_os and state.get("os"):
            opts.os = state["os"]
        if not opts.input:
            opts.input = state.get("input", "")
        merged = dict(state.get("answers", {}))
        merged.update(opts.answers)
        opts.answers = merged
        merged = dict(state.get("selects", {}))
        merged.update(opts.selects)
        opts.selects = merged
        pending = state.get("pending")
        if pending:
            rp = pending.get("response_path", "")
            if rp and os.path.exists(rp):
                with open(rp, encoding="utf-8") as fh:
                    raw = fh.read()
                os.remove(rp)
                # ingest by suspend kind (the pending.kind protocol)
                kind = pending.get("kind", "")
                note = None
                if kind == "ask":
                    val = raw.strip()
                    parsed = ([s.strip() for s in val.split(",") if s.strip()]
                              if pending.get("multi") else val)
                elif kind == "select":
                    parsed = raw.strip()
                    if not parsed:
                        note = "response_path was empty — write the chosen option's value"
                elif kind == "author":
                    parsed = raw
                    if not raw.strip():
                        note = ("response_path was empty — write the complete "
                                "file content, then re-run the resume command")
                elif kind == "hook":
                    parsed = True
                else:  # agent_generate / agent_review / agent_query / apply
                    parsed = _extract_json(raw)
                    if not parsed:
                        note = ("response_path had no parseable ```json fence — "
                                "rewrite it ending with the required fenced block, "
                                "then re-run the resume command")
                if note:
                    pending["note"] = note
                    _print_suspended(pending, opts)
                    return 2
                opts._cache[pending["step"]] = parsed
            else:
                # no response yet — re-emit the same pending request
                _print_suspended(pending, opts)
                return 2

    opts.profile = None
    opts.profile_dir = ""
    if opts.agent_profile:
        with open(opts.agent_profile, encoding="utf-8") as fh:
            opts.profile = json.load(fh)
        # sdk adapters are declared relative to the profile file
        opts.profile_dir = os.path.dirname(os.path.abspath(opts.agent_profile))
        if opts.transport == "mock":
            opts.transport = "real"

    # ---- strategy resolution -------------------------------------------------
    # explicit --strategy wins; else legacy inference from the flags given.
    if not opts.strategy:
        if opts.profile:
            opts.strategy = "spawn"
        elif opts.checkpoint:
            opts.strategy = "agent"
    if opts.strategy and opts.transport == "mock":
        opts.transport = "real"
    if opts.strategy == "spawn" and not opts.profile:
        print("ERROR: strategy 'spawn' requires --agent-profile <profile.json>")
        return 2
    if opts.strategy in ("sdk", "sdk-apply") and not opts.profile:
        print(f"ERROR: strategy '{opts.strategy}' requires --agent-profile "
              "<profile.json> — its sdk block declares the SDK module/package "
              "and adapter (the engine has no default agent)")
        return 2
    if opts.strategy in ("agent", "sdk-apply") and not opts.checkpoint:
        print(f"ERROR: strategy '{opts.strategy}' requires --checkpoint <statefile>")
        return 2
    if opts.transport == "real" and not opts.strategy:
        print("ERROR: --transport real needs --strategy (or --agent-profile / --checkpoint)")
        return 2

    with open(opts.workflow, encoding="utf-8") as fh:
        wf = load_yaml(fh.read())

    orch = Orchestrator(wf, opts)
    try:
        result = orch.run()
        _clear_checkpoint(opts)
    except Suspend as e:
        # persist state (vars seeds + strategy/model + replay cache + the
        # pending request) and hand control back to the INVOKING agent.
        # Exit 2 = "suspended".
        with open(opts.checkpoint, "w", encoding="utf-8") as fh:
            json.dump({"vars": opts.vars, "strategy": opts.strategy,
                       "model": opts.model, "input": opts.input,
                       "answers": opts.answers, "selects": opts.selects,
                       "agent_profile": opts.agent_profile,
                       "isolation": opts.isolation, "os": opts.os,
                       "cache": orch.cache, "pending": e.request}, fh, indent=2)
        _print_suspended(e.request, opts)
        return 2
    except Stop as e:
        result = {"status": "stopped", "reason": str(e), "vars": orch.vars,
                  "missing_required": list(orch.missing_required)}
        _clear_checkpoint(opts)

    if opts.json:
        print(json.dumps(result, indent=2))
    else:
        print(f"\n=== {result['status'].upper()} ===")
        if result.get("reason"):
            print(result["reason"])
        # item H: a required system:/context: file that never made it into a
        # payload is a silent quality hole — the model was told it had rules it
        # never received. Repeat it at the end, where the operator will see it.
        if result.get("missing_required"):
            print(f"\nWARNING: {len(result['missing_required'])} required context "
                  "file(s) were declared but MISSING — every payload that named "
                  "them was assembled without them:")
            for m in result["missing_required"]:
                print(f"  - {m}")
        if result.get("outputs"):
            print(json.dumps(result["outputs"], indent=2))
    return 0 if result["status"] == "ok" else 1


if __name__ == "__main__":
    sys.exit(main())
