#!/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 .appweaver/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 glob
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 Return(Exception):
    """A gate's `return` outcome: end the module being included and carry on with the
    step after the `include`. A Stop ends the whole skill, which is wrong for a caller
    that runs one module per lane — the frontend lane must still run when the backend's
    scaffold was declined. At the top level of a workflow it ends the run normally, with
    the outputs resolved, rather than as a stop."""
    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 _last_json_line(text):
    """The object on stdout's LAST line — the script contract — or None when that
    line is missing or is not a JSON object."""
    lines = (text or "").strip().splitlines()
    if not lines:
        return None
    try:
        data = json.loads(lines[-1])
    except Exception:
        return None
    return data if isinstance(data, dict) else None


def _script_reason(data, stderr, returncode):
    """Why a script failed, in its own words where it gave any. A script that
    prints `{"ok": "false", "error": …}` and exits non-zero has already said why;
    stderr is often only its progress log, so the JSON is read first."""
    data = data or {}
    for key in ("error", "problems", "message", "reason"):
        v = data.get(key)
        if isinstance(v, str) and v.strip():
            return v.strip()
    errs = data.get("errors")
    if isinstance(errs, list) and errs:
        return "; ".join(str(e) for e in errs)
    return (stderr or "").strip() or f"exit code {returncode}, no output"


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 [])
        # The workflow's DECLARED seed, kept apart from what steps load later. A phase
        # that generates for two lanes needs each lane's rule set and NOT the other's,
        # but standards only ever accumulate — so the second lane inherited the first's
        # rules and both prompts had to argue their way out of an envelope that
        # contradicted them. `load_standards: replace` resets to this seed and then
        # appends, which swaps the lane rules while leaving the always-on set (ai-rules
        # and anything else the workflow declared up front) exactly where it was.
        self.standards_seed = list(self.standards)
        # 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 = []
        # paths an agent_generate reply named as written that were not on disk —
        # run-cumulative, reported at the end beside missing_required.
        self.reported_missing = []
        # the messages of gates that failed and let the run CONTINUE — distinct, in
        # order, returned in the run result. Under --json the run log is not printed,
        # so this list is the only way a warning reaches the operator. A resumed run
        # replays from the top, which rebuilds the list rather than doubling it.
        self.warnings = []
        # agent_author targets a --dry-run left unwritten; required_files gates
        # count them as present, so a dry run reaches the steps after them.
        self.dry_run_unwritten = []
        self.last_result = {}
        # agent-specific transport profile (None in mock mode). This engine is
        # general — the profile (loaded from a .claude/.agents/.kilo 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. "
                    if tools else
                    "You have NO tools: the payload is the entire world for "
                    "this request, so do not open other project files. ") +
                "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.

        A file named twice is sent once, compared by the file it resolves to rather
        than by spelling: a script returns `knowledge/x.md` where a workflow writes
        `{{bundle_dir}}/x.md` with an absolute bundle_dir, and both are one file."""
        files, seen = [], set()
        for p, optional in entries:
            rp = self.resolve(p)
            if not rp:
                continue
            key = os.path.normcase(os.path.realpath(rp))
            if key in seen:
                continue
            if os.path.exists(rp):
                seen.add(key)
                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/.kilo 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
        argv, stdin_data = self._fresh_command(system, user, tools, permission_mode, model)

        if self.opts.dry_run:
            # Safety net: every model step prints its command through _mock_step and
            # takes its mock result, so a dry run never reaches here — and must never
            # execute if a new caller does.
            self._emit_fresh_command(argv, stdin_data)
            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 (self.profile or {}).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 _fresh_command(self, system, user, tools, permission_mode, model=None):
        """The argv (and stdin, or None) for one fresh generation, built from the
        PROFILE's neutral knobs — shared by the real run and the dry-run print."""
        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
        # Always pass the allowlist when the CLI has a tools flag — omitting it
        # lets the CLI fall back to its default set (Write/Bash/…), which is
        # how a read-only author/query leaked the rest of the repo. An empty
        # string is a real allowlist of nothing: the inlined payload is the
        # entire world.
        if prof.get("tools_flag") is not None:
            argv += [prof["tools_flag"], tools or ""]
        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
        return argv, stdin_data

    def _emit_fresh_command(self, argv, stdin_data):
        """Print the command a dry run would have executed (long args elided)."""
        shown = [a if len(a) < 120 else f"<{len(a)} chars>" for a in argv]
        self.emit(f"[dry-run] {(self.profile or {}).get('name', '?')} would run:\n  "
                  + " ".join(shown))
        if stdin_data is not None:
            self.emit(f"[dry-run] + stdin: {len(stdin_data)} chars")

    def _mock_step(self, strat, system, user, tools, permission_mode, model=None):
        """True when a model step takes its mock result instead of running: the
        mock transport, or --dry-run under spawn/sdk/sdk-apply. A dry run first
        prints the request the profile would send, then lets the step carry on
        with its mock result, so one dry run prints every model step's command.
        The agent strategy is left alone: the invoking agent fulfils it."""
        if self.opts.transport == "mock":
            return True
        if not self.opts.dry_run or strat == "agent":
            return False
        if strat in ("sdk", "sdk-apply"):
            self._emit_sdk_request(system, user, tools, permission_mode)
        else:
            self._emit_fresh_command(
                *self._fresh_command(system, user, tools, permission_mode, model))
        return True

    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
        .appweaver/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 .appweaver/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 _sdk_config(self):
        """(module, package, adapter) from the profile's sdk block — a dry run
        checks them too, so it catches a profile that cannot run sdk/sdk-apply."""
        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")
        return module_name, package_name, adapter_rel

    def _emit_sdk_request(self, system, user, tools, permission_mode):
        """Print the SDK request a dry run would have sent."""
        module_name, package_name, adapter_rel = self._sdk_config()
        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}")

    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
                             .appweaver/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."""
        module_name, package_name, adapter_rel = self._sdk_config()
        sdk_cfg = self.profile.get("sdk") or {}   # handed to the adapter whole

        if self.opts.dry_run:
            # Safety net, as in _run_fresh: _mock_step prints the request first.
            self._emit_sdk_request(system, user, tools, 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). A list
        # of var names appends each in order.
        cf = step.get("context_from")
        for name in (cf if isinstance(cf, list) else [cf] if cf else []):
            ctx += list(self.vars.get(name) 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 _step_extra_context(self, step):
        """Per-step `context:` files, THIS request only — never sticky. The
        workflow maps what the model may see; the envelope is the sticky set
        `build_context` replaced, and this list is the extra the step named."""
        p = step.get("parameters") or step
        extra = self.resolve_value(p.get("context")) or []
        return [c for c in extra if isinstance(c, (str, dict))]

    def _step_read_tools(self, step):
        """The read tools an `agent_author` / `agent_query` / `agent_review`
        step declares.

        The default is NONE — those three actions are payload-only, and the
        interpreter inlines every file the workflow mapped. A step whose task
        names files by PATH rather than inlining them declares `tools:` and gets
        exactly that set. The brownfield reversals are the reason it exists:
        adopt hands the model the slice's `source_files` as a LIST and tells it
        to read the code, which cannot be inlined (a legacy tree is far larger
        than any payload) — with no tools those steps authored a spec, a design
        and a source-map from a list of filenames, and the fidelity check that
        exists to catch exactly that fabrication could not read the code either.
        Declaring it in the workflow keeps the dependency where a reader can see
        it; the permission mode stays readonly either way."""
        p = step.get("parameters") or step
        v = p.get("tools", "")
        if isinstance(v, (list, tuple)):
            v = ",".join(str(x) for x in v)
        return (self.resolve(str(v)) or "").strip()

    def _written_only(self, step, structured):
        """The generation result with `files` narrowed to paths that exist on disk.

        `files` is the paths the agent SAYS it wrote. Every workflow gates on it with
        `require_non_empty`, which proved only that the reply named something: a reply
        listing a file whose write had failed passed the gate, and the next step read
        a template that was never written. A path that is not on disk is dropped here
        and announced, so an existing gate stops when nothing real was written, and a
        step that builds context from the list gets only real files. The unfiltered
        list stays in the replay cache, so every replay re-checks the disk."""
        if not isinstance(structured, dict) or not isinstance(structured.get("files"), list):
            return structured
        kept, missing = [], []
        for f in structured["files"]:
            (kept if isinstance(f, str) and f.strip() and os.path.exists(f) else missing).append(f)
        if not missing:
            return structured
        self.emit(f"[agent_generate] {step.get('id')}: {len(missing)} reported file(s) "
                  f"not on disk, dropped: {', '.join(str(m) for m in missing)}")
        for m in missing:
            if m not in self.reported_missing:
                self.reported_missing.append(m)
        return dict(structured, files=kept, files_not_written=missing)

    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", ""))
        extra = self._step_extra_context(step)
        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._written_only(step, 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(step.get("include_standards", True))
        user, ctx_files = self._assemble_user(instr, extra=extra)
        self._print_envelope("agent_generate", system, sys_files, user, ctx_files, tools, strat)

        # sdk-apply's generation is the read-only one; the dry run shows that request
        sent_tools, sent_mode = (("Read", "readonly") if strat == "sdk-apply"
                                 else (tools, permission_mode))
        if self._mock_step(strat, system, user, sent_tools, sent_mode, step.get("model")):
            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"))
        # A dry run's result is a mock: caching it would let a later run without
        # --dry-run replay it as if a model had produced it.
        if self.checkpoint and not self.opts.dry_run:
            self.cache[ck] = structured
        structured = self._written_only(step, structured)
        self.last_result = 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 files are inlined into THIS request only. They used to be
        # appended onto the sticky envelope, so every later generation in the
        # same run inherited them — context the workflow never mapped.
        extra = list(review_of) + self._step_extra_context(step)
        # Payload-only like author/query, and the same opt-in: a review whose
        # files are inlined needs nothing, but the escape hatch has to exist on
        # all three or a `tools:` added here later would be silently ignored.
        tools = self._step_read_tools(step)
        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(step.get("include_standards", True))
        user, ctx_files = self._assemble_user(instr, extra=extra)
        # No file tools by default: the files under review are already in the payload.
        self._print_envelope("agent_review", system, sys_files, user, ctx_files, tools, strat)

        if self._mock_step(strat, system, user, tools, "readonly", step.get("model")):
            # 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, tools, "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, tools, "readonly",
                                          model=step.get("model"))
        else:  # spawn
            structured, _ = self._run_fresh(system, user, tools, "readonly",
                                            model=step.get("model"))
        self.last_result = structured
        if self.checkpoint and not self.opts.dry_run:   # never cache a dry run's mock
            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 ".appweaver/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 [])]
        # `error_var` receives why the script failed, and "" whenever it answered — what a
        # gate reads to tell "this step gave no result" apart from a result. It is set
        # before the outputs bind, so an output of the same name still wins on success.
        err_var = p.get("error_var")
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            if err_var:
                self.vars[err_var] = ""
            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:
            if err_var:
                self.vars[err_var] = ""
            self._bind(step, {})
            return
        proc = subprocess.run(runner + [sub] + args, capture_output=True, text=True)
        if proc.returncode != 0:
            # A script that fails can still have answered: many print their verdict as
            # JSON (`ok: false` plus the reason) and exit non-zero. Under `on_error:
            # continue` that object is bound like a success's, so the gate after the
            # step reads the script's own reason instead of a blank. A failure with no
            # JSON binds nothing, as before.
            data = _last_json_line(proc.stdout)
            reason = _script_reason(data, proc.stderr, proc.returncode)
            if p.get("on_error") == "continue":
                self.emit(f"[execute_script] {sub} failed (continuing): {reason[:200]}")
                self._bind(step, data or {})
                if err_var:
                    self.vars[err_var] = reason
                # With no JSON every output binds empty and the reason is the only account
                # of why, so it goes out with the run's warnings, not only into its log.
                if data is None:
                    note = f"step {step.get('id')}: script {sub} gave no result — {reason[:300]}"
                    if note not in self.warnings:
                        self.warnings.append(note)
                return
            raise Stop(f"script failed ({sub}): {reason[: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})")
        if err_var:
            self.vars[err_var] = ""
        self._bind(step, data)
        if self.checkpoint:
            self.cache[ck] = data
        self.emit(f"[execute_script] -> {json.dumps(data)[:200]}")

    # -- F2: gates ---------------------------------------------------------------
    def _gate_failed(self, p, outcome, msg, explicit=True):
        """Apply a failed gate's outcome: `stop` ends the skill, `return` ends the module
        being included (see Return), anything else continues. `message_var` binds the
        resolved message first, so a caller that continues or returns can still report
        why — a message that only reaches the run log is not seen by the operator.
        A gate that continues with a message of its own (`explicit`) and no
        `message_var` adds it to the run's `warnings`; a gate with `message_var`
        reports through the variable instead."""
        if p.get("message_var"):
            self.vars[p["message_var"]] = msg
        if outcome == "stop":
            raise Stop(msg)
        if outcome == "return":
            raise Return(msg)
        if explicit and not p.get("message_var") and msg not in self.warnings:
            self.warnings.append(msg)

    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}}.
        Outcomes: stop | return | continue; `message_var` binds a failed gate's message,
        and a continued gate's own message is otherwise collected into `warnings`."""
        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}")
                self._gate_failed(p, p.get("on_empty"), msg, "on_empty_message" in p)
            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}")
                self._gate_failed(p, p.get("on_false", "stop"), msg, "on_false_message" in p)
            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}")
                self._gate_failed(p, p.get("on_mismatch", "stop"), msg, "on_mismatch_message" in p)
            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 rf in self.dry_run_unwritten:
                self.emit(f"[verify_context] present {rf} (dry-run: its author step did not write it)")
            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).

        `replace: true` first resets the set to the workflow's DECLARED seed,
        dropping everything steps have loaded since. That is how a phase serving
        two lanes gives each one its own rule set instead of the union: the
        second lane replaces the first's rules rather than stacking on them.
        The seed survives, so the always-on standards are never dropped."""
        p = step.get("parameters") or step
        # Through _cond, so a rendered "{{flag}}" that resolves to "false" is FALSE.
        # Plain truthiness would read that non-empty string as true and silently drop
        # every loaded standard on the path meant to keep them.
        if self._cond(str(p.get("replace", ""))):
            dropped = len(self.standards) - len(self.standards_seed)
            self.standards = list(self.standards_seed)
            self.emit(f"[load_standards] replace — reset to the declared seed "
                      f"({len(self.standards_seed)} file(s), {max(dropped, 0)} dropped)")
        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 = self._step_extra_context(step)
        tools = self._step_read_tools(step)
        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}`. " + (
                f"Your tools are read-only ({tools}), and they are for the files "
                "this task names by PATH — everything else you need is already in "
                "the payload. "
                if tools else
                "You have no tools — the payload is the entire world for this "
                "request. ") +
            "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, tools, strat)
        if self._mock_step(strat, system, user, tools, "readonly", step.get("model")):
            content = self._mock_author(target, task)
        elif strat == "agent":
            self._suspend("author", ck, system, user, tools, "readonly",
                          instructions=(
                              "Author this artifact YOURSELF, in this conversation. "
                              "Read system_path + user_path as your ONLY standards "
                              "and context" + (
                                  ", and open ONLY the files the task names by path. "
                                  if tools else
                                  " — do not open other project files. ") +
                              "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, tools, "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:
            # The target can be a real project file, so a dry run never writes it.
            # A later required_files gate counts it as present, and the step's
            # outputs still bind, so the run reaches the steps after it.
            self.emit(f"[agent_author] dry-run: not writing {target}")
            if target not in self.dry_run_unwritten:
                self.dry_run_unwritten.append(target)
            structured = {"status": "ok", "files": [target],
                          "summary": f"dry-run: {target} not written"}
            self.last_result = structured
            self._bind(step, structured)
            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, tools=""):
        """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, tools, "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, tools, "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 = self._step_extra_context(step)
        tools = self._step_read_tools(step)
        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. " + (
                        f"Your tools are read-only ({tools}), and they are for the "
                        "files this task names by PATH — everything else you need is "
                        "already in the payload. "
                        if tools else
                        "The payload is the entire world for this request. ") +
                        "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, tools, strat)
        if self._mock_step(strat, system, user, tools, "readonly", step.get("model")):
            structured = self.resolve_value(p.get("mock")) or {}
        elif strat == "agent":
            self._suspend("agent_query", ck, system, user, tools, "readonly")
        else:
            structured = self._structured_fresh(step, strat, system, user, tools)
        self.last_result = structured
        if self.checkpoint and not self.opts.dry_run:   # never cache a dry run's mock
            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, multi=False):
        print(prompt)
        for i, o in enumerate(options, 1):
            print(f"  {i}) {o}")
        if multi:
            print("  (pick any: numbers or names, comma-separated — "
                  "'all', or blank for none)")
        try:
            raw = input("> ").strip()
        except EOFError:
            return None
        if not multi:
            if raw.isdigit() and 1 <= int(raw) <= len(options):
                return options[int(raw) - 1]
            return raw if raw in options else None
        # A multi-select answer is a SET, and a set has no single-token spelling. Read by
        # the single-select parser, "1,3" was neither a number in range nor an option, so it
        # returned None and the run stopped as "question cancelled" — leaving exactly two
        # reachable answers, "the first one" and "abort". act_ask splits the string it gets
        # back on commas, so returning one is all that is needed here.
        if raw.lower() in ("all", "*"):
            return ",".join(str(o) for o in options)
        if raw.lower() in ("", "none"):
            return ""
        picked = []
        for tok in re.split(r"\s*,\s*|\s+", raw):
            if not tok:
                continue
            if tok.isdigit() and 1 <= int(tok) <= len(options):
                v = options[int(tok) - 1]
            elif tok in options:
                v = tok
            else:
                return None      # an unrecognised token is a typo, not a silent omission
            if v not in picked:
                picked.append(v)
        return ",".join(str(o) for o in picked)

    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, multi) 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); a gate's
        `return` outcome ends only this module and the caller carries on."""
        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 [])
        except Return as r:
            self.emit(f"[include] {module_path} returned early: {str(r)[:200]}")
        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:
                    # Says so, the way the while branch does. A foreach that stops early
                    # drops the tail of its list, and a run that drops work in silence
                    # reports the same success as one that did all of it.
                    self.emit(f"[loop] {loop_id} hit max_iterations={max_it} — "
                              f"{len(items) - max_it} item(s) not run")
                    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()
        try:
            self._run_steps(self.wf.get("workflow", []) or [])
        except Return as r:
            self.emit(f"[return] workflow ended early: {str(r)[:200]}")
        return {"status": "ok", "outputs": self.resolve(self.wf.get("outputs", {}) or {}),
                "vars": self.vars, "missing_required": list(self.missing_required),
                "reported_not_written": list(self.reported_missing),
                "warnings": list(self.warnings)}


# ─────────────────────────────────────────────────────────────────────────────
# 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"}
GATE_OUTCOMES = {"stop", "return", "continue"}
# 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 _module_script_refs(mpath, base_dir, seen):
    """(step id, script ref) for every execute_script step an included module runs,
    following nested includes. Modules that cannot be read contribute nothing — the
    include check already warns about a module missing from disk."""
    path = next((c for c in (mpath, os.path.join(base_dir, mpath)) if c and os.path.exists(c)), "")
    if not path or path in seen:
        return []
    seen.add(path)
    try:
        with open(path, encoding="utf-8") as fh:
            mwf = load_yaml(fh.read())
    except Exception:
        return []
    out = []

    def walk(ss):
        for s in ss or []:
            if not isinstance(s, dict):
                continue
            p = s.get("parameters") or s
            if s.get("action") == "execute_script":
                ref = (p.get("script") or {}).get("ref")
                if ref:
                    out.append((s.get("id") or "step", ref))
            elif s.get("action") == "include" and s.get("module"):
                out.extend(_module_script_refs(s["module"], base_dir, seen))
            elif s.get("action") == "loop":
                walk(s.get("steps"))

    walk((mwf or {}).get("workflow"))
    return out


def validate_workflow(wf, base_dir, path=""):
    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 == "verify_context" and p.get("message_var"):
                produced.add(p["message_var"])
            elif act == "execute_script" and p.get("error_var"):
                produced.add(p["error_var"])
            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 == "verify_context":
            # Any value other than stop/return continues, so a misspelt outcome is a gate
            # that silently never fires.
            for k in ("on_empty", "on_false", "on_mismatch"):
                if p.get(k) is not None and p[k] not in GATE_OUTCOMES:
                    errors.append(f"{loc}: {k} '{p[k]}' is not a gate outcome "
                                  f"(known: {', '.join(sorted(GATE_OUTCOMES))})")
        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}")
            elif scripts:
                # A module declares no scripts: of its own — its refs resolve against
                # THIS workflow's map, so an undeclared one is this workflow's defect.
                for mid, ref in _module_script_refs(m, base_dir, set()):
                    if ref not in scripts:
                        errors.append(f"{loc}: included step {mid} uses script ref "
                                      f"'{ref}', not declared in top-level scripts:")
        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")
    errors_n, warnings_n = _validate_next(wf, base_dir, path)
    return errors + errors_n, warnings + warnings_n


# outputs.next is the ONLY channel a finished run has for telling the operator what
# to run next: the engine returns wf["outputs"] and the launching agent relays it.
# Both faults it guards are silent — a next: indented out of the outputs map is
# parsed and dropped, and a retired command name still reads as a valid sentence —
# so the run ends looking successful and the agent invents a successor to fill the
# gap. Warnings, not errors: a workflow may legitimately name a command that is
# designed but not yet built, and pre-flight refuses to start on errors alone.
def _validate_next(wf, base_dir, path=""):
    errors, warnings = [], []
    outputs = wf.get("outputs") or {}
    known = {os.path.basename(p)[len("aw-spec-"):-len(".orch.yaml")]
             for p in glob.glob(os.path.join(base_dir, "aw-spec-*.orch.yaml"))}
    # A module has no successor to name: it is included INTO a caller, and the caller's
    # own next covers the run. Only a launchable aw-spec-<name> workflow is asked for one.
    launchable = os.path.basename(path).startswith("aw-spec-") if path else bool(known)
    if launchable and "next" not in outputs:
        where = " (it is at the document's top level, OUTSIDE outputs:, so the " \
                "engine parses it and then drops it)" if "next" in wf else ""
        warnings.append(f"outputs: declares no 'next' — the run ends with no "
                        f"suggested successor{where}")
    if not known:          # validating a module, or a workflow read from elsewhere
        return errors, warnings
    for text in _output_strings(outputs):
        for cmd in re.findall(r"/appweaver\s+([a-z][a-z0-9-]*)", text):
            if cmd not in known:
                warnings.append(f"outputs names '/appweaver {cmd}', which resolves "
                                f"to no aw-spec-{cmd}.orch.yaml")
    return errors, warnings


def _output_strings(v):
    if isinstance(v, str):
        yield v
    elif isinstance(v, list):
        for x in v:
            yield from _output_strings(x)
    elif isinstance(v, dict):
        for x in v.values():
            yield from _output_strings(x)


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/.kilo/...); 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 for every model "
                         "step, without executing any; each step then takes its mock result")
    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)), 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

    # ---- pre-flight: a workflow --validate rejects is never started ----------
    # An undeclared script ref, an unknown action or a duplicate step id is a defect in
    # the workflow file, and no run can recover from it — `on_error: continue` covers a
    # script that RAN and failed, not one the workflow never declared. Found mid-run, it
    # strands the operator after the questions were answered; found here, nothing has
    # happened yet. Runs BEFORE the checkpoint ingest, so a refused resume leaves the
    # pending response on disk for the run after the fix. Warnings do not block.
    try:
        with open(opts.workflow, encoding="utf-8") as fh:
            wf = load_yaml(fh.read())
        errors, _ = validate_workflow(
            wf, os.path.dirname(os.path.abspath(opts.workflow)), opts.workflow)
    except Exception as e:
        wf, errors = None, [f"parse: {e}"]
    if errors:
        reason = (f"workflow {opts.workflow} has {len(errors)} defect(s) and was not started: "
                  + "; ".join(errors)
                  + " — fix the workflow file (python3 .appweaver/orchestrator/orchestrator.py "
                  "<workflow> --validate lists them) and re-run.")
        if opts.json:
            print(json.dumps({"status": "stopped", "reason": reason, "errors": errors}, indent=2))
        else:
            print("\n=== STOPPED ===")
            print(reason)
        return 1

    # ---- 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

    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),
                  "reported_not_written": list(orch.reported_missing),
                  "warnings": list(orch.warnings)}
        _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("reported_not_written"):
            print(f"\nWARNING: {len(result['reported_not_written'])} file(s) a generation "
                  "reported as written are not on disk — dropped from its result, so no "
                  "later step read them:")
            for m in result["reported_not_written"]:
                print(f"  - {m}")
        if result.get("warnings"):
            print(f"\nWARNING: {len(result['warnings'])} warning(s) from gates that let "
                  "the run continue:")
            for w in result["warnings"]:
                print(f"  - {w}")
        if result.get("outputs"):
            print(json.dumps(result["outputs"], indent=2))
        try:
            _chk = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts", "python", "aw-check-update.py")
            if os.path.exists(_chk):
                subprocess.run([sys.executable, _chk], timeout=2)
        except Exception:
            pass
    return 0 if result["status"] == "ok" else 1


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