#!/usr/bin/env python3
"""
run-skill.py — reference interpreter for aw-spec declarative skills
(dialect: aw-spec.declarative/v1).

╔══════════════════════════════════════════════════════════════════════════════╗
║ RETIRED AS AN ENTRY POINT — BUT DO NOT DELETE THIS FILE.                      ║
║                                                                              ║
║ The declarative tier it drove (the `aw-spec-decl-*` skills across .claude/,   ║
║ .agents/ and .kilocode/) was removed 2026-08-03; nothing launches this        ║
║ interpreter any more. It survives for ONE reason:                            ║
║                                                                              ║
║   .appweaver/orchestrator/orchestrator.py imports this module at load time      ║
║   for its YAML-subset loader (`load_yaml`) — see orchestrator.py ~L112.       ║
║                                                                              ║
║ Deleting this file makes EVERY orchestrator workflow fail with               ║
║ FileNotFoundError before a single step runs. Fold `load_yaml` into            ║
║ orchestrator.py first if you want this gone.                                 ║
╚══════════════════════════════════════════════════════════════════════════════╝

This was the "no-prompt" execution path: it PARSES a skill.yaml and EXECUTES the
`workflow:` itself. The model is invoked in exactly one place — the `llm_generate`
action — and only to author content. Everything else (loading context, verifying,
running the shared scripts, dispatching hooks, interactive selection) is done here.

Stdlib only — no PyYAML dependency. A compact YAML-subset loader (loader tuned to
the dialect) is bundled below and validated against a full YAML parser in tests.

Usage:
  run-skill.py <skill.yaml> [--input "<user input>"] [--select name=value ...]
               [--llm mock|command:<cmd>|agent] [--os posix|windows] [--dry-run] [--json]
  run-skill.py <skill.yaml> --validate [--json]     # lint without executing

LLM backends:
  --llm mock              (default) writes a deterministic placeholder file; no model call.
  --llm command:<cmd>     pipes the resolved prompt on stdin to <cmd>; stdout is the content.
  --llm agent             defers each llm_generate to the CALLING agent (e.g. Claude):
                          the interpreter records the request in `pending_generation`
                          and continues; the agent authors the content afterward.
"""
import argparse
import json
import os
import re
import subprocess
import sys

# ─────────────────────────────────────────────────────────────────────────────
# Minimal YAML-subset loader
#
# Supports the constructs the dialect uses: nested block mappings, block
# sequences (items may sit at the parent key's indent), inline flow maps/lists,
# literal block scalars ("|"), quoted/plain scalars, comments, bool/int/null.
# Not a general YAML parser — intentionally small and predictable.
# ─────────────────────────────────────────────────────────────────────────────
class YamlError(Exception):
    pass


def _indent(line):
    return len(line) - len(line.lstrip(" "))


def _strip_comment(s):
    """Strip a trailing ' #...' comment that is outside quotes/flow. Inside double
    quotes a backslash escapes the next character, so \\" does not end the string."""
    out, i, depth = [], 0, 0
    quote = None
    while i < len(s):
        c = s[i]
        if quote:
            out.append(c)
            if quote == '"' and c == "\\" and i + 1 < len(s):
                out.append(s[i + 1])
                i += 2
                continue
            if c == quote:
                quote = None
        elif c in ("'", '"'):
            quote = c
            out.append(c)
        elif c in "[{":
            depth += 1
            out.append(c)
        elif c in "]}":
            depth = max(0, depth - 1)
            out.append(c)
        elif c == "#" and depth == 0 and (i == 0 or s[i - 1] == " "):
            break
        else:
            out.append(c)
        i += 1
    return "".join(out).rstrip()


def _scalar(tok):
    tok = tok.strip()
    if tok == "" or tok == "~" or tok.lower() == "null":
        return None
    if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in "'\"":
        if tok[0] == '"':
            # A double-quoted value reads \" as " and \\ as \, as YAML does.
            return re.sub(r'\\(["\\])', r"\1", tok[1:-1])
        return tok[1:-1]
    low = tok.lower()
    if low == "true":
        return True
    if low == "false":
        return False
    if re.fullmatch(r"-?\d+", tok):
        return int(tok)
    if re.fullmatch(r"-?\d+\.\d+", tok):
        return float(tok)
    return tok


def _parse_flow(s):
    """Parse a JSON-ish flow scalar: {a: b, c: [x, y]} / [a, b] / plain.

    A flow collection lives ENTIRELY on the line it opens on: this parser is
    handed one line's text and never reads ahead. An unterminated `[`/`{` is
    therefore a syntax error and is raised as one — silently returning the
    partial collection would truncate the value AND swallow every line the
    caller has not consumed yet, which is invisible at every later stage
    (a `--validate` pass lints whatever survived the parse, not what was written).
    """
    s = s.strip()
    pos = [0]

    def skip_ws():
        while pos[0] < len(s) and s[pos[0]] in " \t":
            pos[0] += 1

    def parse_value():
        skip_ws()
        if pos[0] >= len(s):
            return None
        c = s[pos[0]]
        if c == "{":
            return parse_map()
        if c == "[":
            return parse_list()
        return _scalar(read_until(",]}"))

    def read_until(stops):
        start = pos[0]
        quote = None
        while pos[0] < len(s):
            ch = s[pos[0]]
            if quote:
                if quote == '"' and ch == "\\":
                    pos[0] += 1  # the escaped character never closes the quote
                elif ch == quote:
                    quote = None
            elif ch in "'\"":
                quote = ch
            elif ch in stops:
                break
            pos[0] += 1
        return s[start:pos[0]]

    def parse_map():
        obj = {}
        pos[0] += 1  # {
        skip_ws()
        if pos[0] < len(s) and s[pos[0]] == "}":
            pos[0] += 1
            return obj
        while True:
            skip_ws()
            key = read_until(":").strip()
            if pos[0] < len(s) and s[pos[0]] == ":":
                pos[0] += 1
            val = parse_value()
            obj[_scalar(key)] = val
            skip_ws()
            if pos[0] < len(s) and s[pos[0]] == ",":
                pos[0] += 1
                continue
            if pos[0] < len(s) and s[pos[0]] == "}":
                pos[0] += 1
                break
            raise YamlError(
                "unterminated flow mapping — a '{' must close with '}' on the "
                f"SAME line; put the whole mapping on one line: {s!r}")
        return obj

    def parse_list():
        arr = []
        pos[0] += 1  # [
        skip_ws()
        if pos[0] < len(s) and s[pos[0]] == "]":
            pos[0] += 1
            return arr
        while True:
            arr.append(parse_value())
            skip_ws()
            if pos[0] < len(s) and s[pos[0]] == ",":
                pos[0] += 1
                skip_ws()
                if pos[0] < len(s) and s[pos[0]] == "]":   # tolerated trailing comma
                    pos[0] += 1
                    break
                continue
            if pos[0] < len(s) and s[pos[0]] == "]":
                pos[0] += 1
                break
            raise YamlError(
                "unterminated flow sequence — a '[' must close with ']' on the "
                f"SAME line; put the whole sequence on one line: {s!r}")
        return arr

    if s and s[0] in "[{":
        return parse_value()
    return _scalar(s)


class _Lines:
    def __init__(self, text):
        self.raw = text.splitlines()
        self.i = 0

    def peek(self):
        while self.i < len(self.raw):
            line = self.raw[self.i]
            stripped = line.strip()
            if stripped == "" or stripped.startswith("#"):
                self.i += 1
                continue
            return line
        return None

    def next(self):
        line = self.peek()
        if line is not None:
            self.i += 1
        return line


def _parse_block(lines, min_indent):
    line = lines.peek()
    if line is None or _indent(line) < min_indent:
        return None
    indent = _indent(line)
    if line.strip().startswith("- "):
        return _parse_seq(lines, indent)
    return _parse_map(lines, indent)


def _parse_map(lines, indent):
    obj = {}
    while True:
        line = lines.peek()
        if line is None or _indent(line) != indent or line.strip().startswith("- "):
            break
        content = _strip_comment(line.strip())
        m = re.match(r"^(.*?):(?:\s+(.*))?$", content)
        if not m:
            raise YamlError(f"bad mapping line: {line!r}")
        key = _scalar(m.group(1))
        rest = m.group(2)
        lines.next()
        if rest is None or rest == "":
            child = _parse_block(lines, indent + 1)
            obj[key] = child
        elif rest in ("|", "|-", "|+", ">", ">-", ">+"):
            obj[key] = _parse_block_scalar(lines, indent, folded=rest[0] == ">",
                                           chomp=(rest[1:] or ""))
        elif rest[0] in "[{":
            obj[key] = _parse_flow(rest)
        else:
            obj[key] = _scalar(rest)
    return obj


def _parse_seq(lines, indent):
    arr = []
    while True:
        line = lines.peek()
        if line is None or _indent(line) != indent or not line.strip().startswith("- "):
            break
        content = _strip_comment(line.strip()[2:])
        lines.next()
        if content == "":
            arr.append(_parse_block(lines, indent + 1))
        elif content[0] in "[{":
            arr.append(_parse_flow(content))
        elif re.match(r"^.*?:(?:\s+.*)?$", content) and ":" in content:
            # inline map entry starting on the "- " line; parse it + following keys
            m = re.match(r"^(.*?):(?:\s+(.*))?$", content)
            item = {}
            key = _scalar(m.group(1))
            rest = m.group(2)
            if rest is None or rest == "":
                item[key] = _parse_block(lines, indent + 2)
            elif rest[0] in "[{":
                item[key] = _parse_flow(rest)
            else:
                item[key] = _scalar(rest)
            # subsequent sibling keys at indent+2
            sub = _parse_map(lines, indent + 2)
            if sub:
                item.update(sub)
            arr.append(item)
        else:
            arr.append(_scalar(content))
    return arr


def load_yaml(text):
    lines = _Lines(text)
    result = _parse_block(lines, 0)
    return result if result is not None else {}


def _parse_block_scalar(lines, parent_indent, folded, chomp):
    """Collect a block scalar ('|' literal or '>' folded) with chomping.

    chomp: '' clip (single trailing \\n), '-' strip, '+' keep all trailing \\n.
    """
    block, block_indent = [], None
    while lines.i < len(lines.raw):
        raw = lines.raw[lines.i]
        if raw.strip() == "":
            block.append("")
            lines.i += 1
            continue
        if _indent(raw) <= parent_indent:
            break
        if block_indent is None:
            block_indent = _indent(raw)
        block.append(raw[block_indent:])
        lines.i += 1

    trailing = 0
    while block and block[-1] == "":
        block.pop()
        trailing += 1

    if folded:
        # YAML folding: one line break between two lines becomes a space, a line break
        # followed by k empty lines becomes k newlines, and the break before or after a
        # more-indented line is kept as it is.
        parts, prev, empties = [], None, 0
        for ln in block:
            if ln == "":
                empties += 1
                continue
            if prev is None:
                parts.append("\n" * empties)
            elif prev[:1] not in " \t" and ln[:1] not in " \t":
                parts.append("\n" * empties if empties else " ")
            else:
                parts.append("\n" * (empties + 1))
            parts.append(ln)
            prev, empties = ln, 0
        text = "".join(parts)
    else:
        text = "\n".join(block)

    if chomp == "-":
        return text
    if chomp == "+":
        return text + "\n" * (trailing + 1 if block else trailing)
    return text + "\n"  # clip


# ─────────────────────────────────────────────────────────────────────────────
# Interpreter
# ─────────────────────────────────────────────────────────────────────────────
class Stop(Exception):
    pass


class Suspend(Exception):
    """Raised in checkpoint mode when the interpreter needs the agent (generate a
    file / answer a query / ask a question). Carries the typed request."""
    def __init__(self, request):
        self.request = request


class Interp:
    def __init__(self, skill, opts):
        self.skill = skill
        self.opts = opts
        self.vars = {}
        self.context = []          # ordered list of loaded file paths
        self.log = []
        self.pending = []          # deferred llm_generate requests (--llm agent)
        # checkpoint mode: replay + response cache keyed by invocation path
        self.checkpoint = getattr(opts, "checkpoint", None)
        self.cache = getattr(opts, "_cache", {}) or {}
        self.key_stack = []        # loop-aware invocation-key prefix
        # session context ledger: files loaded by earlier commands this session
        self.session_loaded = set(getattr(opts, "_session_loaded", None) or set())
        self.ledger_path = getattr(opts, "_ledger_path", None)
        self.session_id = getattr(opts, "session", None)

    # -- helpers --------------------------------------------------------------
    def emit(self, msg):
        self.log.append(msg)
        if not self.opts.json:
            print(msg)

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

    def resolve(self, val):
        """Recursively substitute {{name}} / {{a.b}} in strings using self.vars."""
        if isinstance(val, str):
            def sub(m):
                found, v = self._lookup(m.group(1).strip())
                if not found:
                    return m.group(0)
                return v if isinstance(v, str) else json.dumps(v)
            return re.sub(r"\{\{\s*([^}]+?)\s*\}\}", sub, 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):
        """Like resolve, but if x is exactly one {{ref}} return the raw object
        (list/dict/bool), not a stringified form."""
        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)
        return x

    def truthy(self, v):
        if isinstance(v, str):
            return v.strip() not in ("", "false", "False", "None", "null", "[]")
        return bool(v)

    def eval_condition(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 self.truthy(expr)

    # -- checkpoint helpers ---------------------------------------------------
    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, request):
        """Persist a pending agent-request and raise Suspend."""
        request["response_path"] = self.checkpoint + ".response"
        raise Suspend(request)

    def script_path(self, ref):
        s = self.skill.get("scripts", {}).get(ref, {})
        variant = "ps1" if self.opts.os == "windows" else "sh"
        return s.get(variant)

    def act_include(self, step):
        """Run a reusable workflow module inline — shares vars, context, cache, and
        the caller's `scripts:` map. `with:` seeds module inputs; the module's steps
        are namespaced under the include id for stable checkpoint keys."""
        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 YamlError(f"include: module not found: {module_path} ({e})")
        self.emit(f"[include] {module_path}")
        self.key_stack.append("inc:" + step.get("id", "include"))
        try:
            self._run_steps(mod.get("workflow", []) or [])
        finally:
            self.key_stack.pop()

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

    # -- actions --------------------------------------------------------------
    def run(self):
        self._run_steps(self.skill.get("workflow", []))
        return 0

    def _run_steps(self, steps):
        """Run a list of steps. Returns 'break' if a break bubbled up, else None."""
        for step in steps:
            cond = step.get("condition")
            if cond is not None and not self.eval_condition(cond):
                self.emit(f"[skip] {step.get('id')} (condition false)")
                continue
            action = step.get("action")
            if action == "break":
                self.emit(f"[break] {step.get('id', '')}")
                return "break"
            if action == "loop":
                self.act_loop(step)   # a break inside is consumed by the loop itself
                continue
            fn = getattr(self, f"act_{action}", None)
            if fn is None:
                raise YamlError(f"unknown action: {action}")
            fn(step)
        return None

    def act_loop(self, step):
        """foreach (`over:` a list var) or while (`while:` + `max_iterations`)."""
        as_name = step.get("as", "item")
        max_it = step.get("max_iterations")
        substeps = step.get("steps", []) or []
        if "over" in step:
            items = self.resolve_value(step["over"]) or []
            if not isinstance(items, list):
                raise YamlError(f"loop 'over' is not a list: {step.get('over')}")
            loop_id = step.get("id", "loop")
            for idx, item in enumerate(items):
                if max_it is not None and idx >= max_it:
                    break
                self.vars[as_name] = item
                self.vars[as_name + "_index"] = idx
                self.key_stack.append(f"{loop_id}#{idx}")
                try:
                    brk = self._run_steps(substeps)
                finally:
                    self.key_stack.pop()
                if brk == "break":
                    break        # break exits THIS loop (consumed here), not the caller
            return None
        # while variant
        cond = step.get("while", "true")
        loop_id = step.get("id", "loop")
        i = 0
        while self.eval_condition(cond):
            if max_it is not None and i >= max_it:
                break
            self.vars[as_name + "_index"] = i
            self.key_stack.append(f"{loop_id}#{i}")
            try:
                brk = self._run_steps(substeps)
            finally:
                self.key_stack.pop()
            if brk == "break":
                break        # break exits THIS while-loop (consumed here)
            i += 1
        return None

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

    def act_load_context(self, step):
        p = step.get("parameters", {})
        files = p.get("files") or []
        if p.get("files_from_variable"):
            var = self.vars.get(p["files_from_variable"]) or []
            files = [{"path": x} for x in var]
        step_optional = p.get("optional", False)
        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 p.get("deduplicate") and path in self.context:
                self.emit(f"[load_context] dedup skip {path}")
                continue
            # session ledger: a file already loaded by an EARLIER command in this
            # agent session is already in the model's context — don't reload/re-attach.
            if path in self.session_loaded:
                self.emit(f"[load_context] session-dedup skip {path} (loaded earlier this session)")
                continue
            if os.path.exists(path):
                self.context.append(path)
                self.emit(f"[load_context] loaded {path}")
            elif optional:
                self.emit(f"[load_context] optional missing, skip {path}")
            else:
                raise YamlError(f"required context file missing: {path}")

    def act_verify_context(self, step):
        p = step.get("parameters", {})
        if p.get("require_non_empty"):
            var = p["require_non_empty"]
            val = self.vars.get(var)
            if not val:
                self.emit(f"[verify_context] {var} is empty: {p.get('on_empty_message','')}")
                if p.get("on_empty") == "stop":
                    raise Stop(p.get("on_empty_message", "stopped"))
            else:
                self.emit(f"[verify_context] {var} non-empty ({len(val)})")
        if p.get("require_true"):
            var = p["require_true"]
            if not self.truthy(self.vars.get(var)):
                msg = self.resolve(p.get("on_false_message", f"{var} is not satisfied"))
                self.emit(f"[verify_context] gate failed ({var}): {msg}")
                if p.get("on_false", "stop") == "stop":
                    raise Stop(msg)
            else:
                self.emit(f"[verify_context] gate ok ({var})")
        if p.get("require_value"):
            var = p["require_value"]
            actual = str(self.vars.get(var, ""))
            expected = str(self.resolve(p.get("equals", "")))
            if actual != expected:
                msg = self.resolve(p.get("on_mismatch_message", f"{var} != {expected}"))
                self.emit(f"[verify_context] value gate failed ({var}={actual!r}): {msg}")
                if p.get("on_mismatch", "stop") == "stop":
                    raise Stop(msg)
            else:
                self.emit(f"[verify_context] value gate ok ({var}=={expected})")
        for rf in p.get("required_files", []) or []:
            rf = self.resolve(rf)
            present = rf in self.context or os.path.exists(rf)
            if present:
                self.emit(f"[verify_context] present {rf}")
            elif p.get("allow_missing"):
                self.emit(f"[verify_context] missing (allowed) {rf}")
            else:
                raise YamlError(f"required file not in context: {rf}")

    def act_execute_script(self, step):
        p = step.get("parameters", {})
        ref = p["script"]["ref"]
        script = self.script_path(ref)
        if not script or not os.path.exists(script):
            raise YamlError(f"script not found for ref '{ref}': {script}")
        args = [self.resolve(a) for a in (p.get("args") or [])]
        # checkpoint replay: reuse cached output, don't re-run the side effect
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self._bind_outputs(step, self.cache[ck])
            self.emit(f"[execute_script] {p['subcommand']} (cached)")
            return
        runner = ["pwsh", "-NoProfile", "-File", script] if self.opts.os == "windows" else ["bash", script]
        cmd = runner + [p["subcommand"]] + args
        self.emit(f"[execute_script] {p['subcommand']} {' '.join(args)}")
        if self.opts.dry_run:
            self._bind_outputs(step, {})
            return
        proc = subprocess.run(cmd, capture_output=True, text=True)
        if proc.returncode != 0:
            raise YamlError(f"script failed ({p['subcommand']}): {proc.stderr.strip()}")
        try:
            data = json.loads(proc.stdout.strip().splitlines()[-1])
        except Exception as e:
            raise YamlError(f"script did not return JSON ({p['subcommand']}): {proc.stdout!r} ({e})")
        self._bind_outputs(step, data)
        if self.checkpoint:
            self.cache[ck] = data
        self.emit(f"[execute_script] -> {json.dumps(data)}")

    def act_dispatch_hooks(self, step):
        p = step.get("parameters", {})
        # checkpoint replay: don't re-dispatch hooks already handled
        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 hooks:
            for h in hooks:
                kind = "mandatory" if not h.get("optional") else "optional"
                self.emit(f"[dispatch_hooks] {kind}: {h.get('slash')} ({h.get('extension')})")
                # An agent runs the slash command here; the interpreter records intent.
        else:
            self.emit("[dispatch_hooks] none")
        if self.checkpoint:
            self.cache[ck] = True

    def act_user_select(self, step):
        p = step.get("parameters", {})
        options = self.vars.get(p.get("options_from_variable")) or []
        # Direct-argument fast path
        pre = p.get("preselect_from")
        pre_val = self.vars.get(pre) if pre else None
        chosen = None
        if 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
        else:
            chosen = self._prompt_choice(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)
        self.emit(f"[user_select] chosen: {chosen}")

    def _prompt_choice(self, prompt, options):
        print(prompt)
        for i, o in enumerate(options, 1):
            print(f"  {i}) {o}")
        try:
            raw = input("> ").strip()
        except EOFError:
            return None
        if raw.isdigit() and 1 <= int(raw) <= len(options):
            return options[int(raw) - 1]
        return raw if raw in options else None

    def act_ask(self, step):
        """Single or multi-select question. Answer sources, in order:
           --answer <key>=<value>  (key = resolved `answer_key`, else step id)
           interactive stdin        (unless --non-interactive)
        Binds the answer to `answer_var` (default 'answer')."""
        p = step.get("parameters", {})
        prompt = self.resolve(p.get("prompt", "?"))
        options = []
        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 []
        elif p.get("options"):
            options = [self.resolve(o) for o in p["options"]]
        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.checkpoint:
            # need the agent/user — suspend with an ask request
            self._suspend({"kind": "ask", "key": key, "step": ck,
                           "prompt": prompt, "options": options, "multi": multi})
        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:
            raw = self._prompt_choice(prompt, options) if options else \
                (input(prompt + " ").strip() if not self.opts.non_interactive else "")
        if raw is None:
            raise Stop("question cancelled")
        # multi-select: split on commas and DROP empties, so "" => [] (empty selection)
        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_set(self, step):
        """Set variables from literals/expressions (parameters: {name: value})."""
        for k, v in (step.get("parameters", {}) or {}).items():
            self.vars[k] = self.resolve_value(v)
        self.emit(f"[set] {list((step.get('parameters') or {}).keys())}")

    def act_llm_query(self, step):
        """In-run LLM call that returns STRUCTURED JSON bound to vars via outputs[].
        Requires a synchronous backend (mock/command); not available with --llm agent."""
        p = step.get("parameters", {})
        ck = self._key(step)
        if self.checkpoint and ck in self.cache:
            self._bind_outputs(step, self.cache[ck])
            self.emit(f"[llm_query] (cached) -> {json.dumps(self.cache[ck])[:120]}")
            return
        prompt = self.resolve(p.get("prompt", ""))
        ctx_files = [self.resolve_value(c) for c in (p.get("context") or [])]
        ctx_files = [c for c in ctx_files if isinstance(c, str)]
        if p.get("include_loaded_context", True):
            for c in self.context:
                if c not in ctx_files:
                    ctx_files.append(c)
        if self.checkpoint:
            self._suspend({"kind": "llm_query", "step": ck,
                           "prompt": prompt, "context": ctx_files})
        if self.opts.llm == "agent":
            raise YamlError("llm_query needs a synchronous --llm backend "
                            "(mock/command:...) or --checkpoint, not --llm agent")
        raw = self._invoke_llm(prompt, ctx_files, None)
        try:
            data = json.loads(raw.strip().splitlines()[-1] if raw.strip() else "{}")
        except Exception as e:
            raise YamlError(f"llm_query did not return JSON: {raw!r} ({e})")
        self._bind_outputs(step, data)
        self.emit(f"[llm_query] -> {json.dumps(data)[:200]}")

    def act_llm_generate(self, step):
        p = step.get("parameters", {})
        prompt = self.resolve(p.get("prompt", ""))
        ctx_files = [self.resolve(c) for c in (p.get("context") or [])]
        # Fix #1: augment with everything pulled in by load_context so the standards
        # and domain rules actually reach generation (dedup, order-preserving).
        if p.get("include_loaded_context", True):
            for c in self.context:
                if c not in ctx_files:
                    ctx_files.append(c)
        target = self.resolve(p["output_target"]["path"])
        ck = self._key(step)
        # checkpoint replay: rewrite the target from cached content (idempotent)
        if self.checkpoint and ck in self.cache:
            os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
            with open(target, "w", encoding="utf-8") as fh:
                fh.write(self.cache[ck])
            self.emit(f"[llm_generate] (cached) rewrote {target}")
            return
        self.emit(f"[llm_generate] context={ctx_files} -> {target}")
        if self.checkpoint:
            self._suspend({"kind": "llm_generate", "step": ck, "target": target,
                           "prompt": prompt, "context": ctx_files})
        if self.opts.llm == "agent":
            # Defer generation to the calling agent (e.g. Claude). The interpreter
            # does NOT write the file; it records the request and continues the
            # remaining deterministic steps. The agent fulfills these afterward.
            self.pending.append({"target": target, "context": ctx_files, "prompt": prompt})
            self.emit("[llm_generate] deferred to agent (see pending_generation)")
            return
        content = self._invoke_llm(prompt, ctx_files, target)
        if self.opts.dry_run:
            self.emit("[llm_generate] dry-run: not writing")
            return
        os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
        with open(target, "w", encoding="utf-8") as fh:
            fh.write(content)
        self.emit(f"[llm_generate] wrote {len(content)} chars")

    def _invoke_llm(self, prompt, ctx_files, target):
        backend = self.opts.llm
        if backend.startswith("command:"):
            cmd = backend[len("command:"):]
            ctx_blob = ""
            for c in ctx_files:
                if os.path.exists(c):
                    ctx_blob += f"\n\n===== CONTEXT: {c} =====\n" + open(c, encoding="utf-8").read()
            proc = subprocess.run(cmd, shell=True, input=prompt + ctx_blob,
                                  capture_output=True, text=True)
            if proc.returncode != 0:
                raise YamlError(f"llm command failed: {proc.stderr.strip()}")
            return proc.stdout
        # mock backend — deterministic, no model call
        return (
            "<!-- generated by run-skill.py mock LLM backend -->\n"
            f"<!-- target: {target} -->\n"
            f"<!-- context files: {', '.join(ctx_files)} -->\n"
            f"<!-- prompt chars: {len(prompt)} -->\n\n"
            "# (mock content)\n\nReplace --llm mock with a real backend to author this file.\n"
        )


# ─────────────────────────────────────────────────────────────────────────────
# Static validator (--validate): lints a skill.yaml without executing it.
# ─────────────────────────────────────────────────────────────────────────────
KNOWN_ACTIONS = {
    "load_context", "verify_context", "execute_script",
    "dispatch_hooks", "user_select", "llm_generate",
    "loop", "ask", "llm_query", "set", "break", "include",
}
_SPECIAL_VARS = {"selection", "answer"}


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


def validate_skill(skill, base_dir):
    errors, warnings = [], []
    if not isinstance(skill, dict):
        return (["top-level YAML is not a mapping"], [])

    wf = skill.get("workflow")
    if not isinstance(wf, list) or not wf:
        errors.append("missing or empty 'workflow' list")
        wf = wf if isinstance(wf, list) else []
    scripts = skill.get("scripts", {}) or {}

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

    produced = set(_SPECIAL_VARS)
    for _, spec in (skill.get("inputs") or {}).items():
        if isinstance(spec, dict) and spec.get("bind"):
            produced.add(spec["bind"])
    # pre-scan everything that produces variables (recursively) so ordering /
    # forward references don't false-alarm
    for step in walk(wf):
        for o in step.get("outputs") or []:
            if isinstance(o, dict) and o.get("name"):
                produced.add(o["name"])
        p = step.get("parameters", {}) or {}
        act = step.get("action")
        if act == "ask":
            produced.add(p.get("answer_var", "answer"))
        elif act == "set":
            produced.update((step.get("parameters") or {}).keys())
        elif act == "loop" and step.get("as"):
            produced.add(step["as"])
            produced.add(step["as"] + "_index")
        elif act == "include":
            # vars the module seeds + produces become available to the caller
            produced.update((step.get("with") or {}).keys())
            mpath = step.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()).get("workflow", [])
                        for ms in walk(mwf):
                            for o in ms.get("outputs") or []:
                                if isinstance(o, dict) and o.get("name"):
                                    produced.add(o["name"])
                            mp = ms.get("parameters", {}) or {}
                            if ms.get("action") == "ask":
                                produced.add(mp.get("answer_var", "answer"))
                            elif ms.get("action") == "set":
                                produced.update((ms.get("parameters") or {}).keys())
                    except Exception:
                        pass
                    break

    seen_ids = set()
    for step in walk(wf):
        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}' (known: {', '.join(sorted(KNOWN_ACTIONS))})")
        p = step.get("parameters", {}) or {}

        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 == "include":
            m = step.get("module")
            if not m:
                errors.append(f"{loc}: include needs 'module'")
            elif not (os.path.exists(m) or os.path.exists(os.path.join(base_dir, m))):
                warnings.append(f"{loc}: include module not found on disk: {m}")
        if action == "llm_query" and not (step.get("outputs")):
            warnings.append(f"{loc}: llm_query has no outputs[] to bind")

        if action == "execute_script":
            ref = (p.get("script") or {}).get("ref")
            if not ref:
                errors.append(f"{loc}: execute_script needs parameters.script.ref")
            elif ref not in scripts:
                errors.append(f"{loc}: script ref '{ref}' not declared in top-level scripts:")
            else:
                variants = scripts.get(ref) or {}
                found = False
                for v in ("sh", "ps1"):
                    path = variants.get(v)
                    if path and (os.path.exists(path) or os.path.exists(os.path.join(base_dir, path))):
                        found = True
                if not found:
                    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 parameters.subcommand")

        if action == "user_select":
            if not p.get("options_from_variable"):
                errors.append(f"{loc}: user_select needs parameters.options_from_variable")

        if action == "llm_generate":
            if not p.get("prompt"):
                warnings.append(f"{loc}: llm_generate has an empty prompt")
            if not (p.get("output_target") or {}).get("path"):
                errors.append(f"{loc}: llm_generate needs parameters.output_target.path")

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

    return errors, warnings


def main(argv=None):
    ap = argparse.ArgumentParser(description="aw-spec declarative skill interpreter")
    ap.add_argument("skill")
    ap.add_argument("--input", default="")
    ap.add_argument("--select", action="append", default=[], help="stepid=value")
    ap.add_argument("--answer", action="append", default=[], help="key=value (for ask steps)")
    ap.add_argument("--llm", default="mock")
    ap.add_argument("--os", choices=["posix", "windows"],
                    default="windows" if os.name == "nt" else "posix")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--non-interactive", action="store_true")
    ap.add_argument("--validate", action="store_true",
                    help="lint the skill (parse + static checks) without executing")
    ap.add_argument("--checkpoint", metavar="STATEFILE",
                    help="suspend/resume mode: persist state to STATEFILE and "
                         "suspend when the agent is needed (see docs)")
    ap.add_argument("--session", default=os.environ.get("AW_SPEC_SESSION"),
                    help="agent session id (or $AW_SPEC_SESSION); enables cross-command "
                         "context dedup via .appweaver/.context-ledger.json")
    ap.add_argument("--session-reset", action="store_true",
                    help="clear the session context ledger and exit")
    ap.add_argument("--json", action="store_true")
    opts = ap.parse_args(argv)
    opts.selects = dict(s.split("=", 1) for s in opts.select if "=" in s)
    opts.answers = dict(s.split("=", 1) for s in opts.answer if "=" in s)

    # ---- session context ledger --------------------------------------------
    # Files loaded to context by an earlier command in the SAME agent session are
    # already in the model's window; later commands skip re-loading / re-attaching
    # them. Opt-in via --session / $AW_SPEC_SESSION (safe no-op when unset — e.g.
    # stateless headless runs where each model call has no memory).
    LEDGER = ".appweaver/.context-ledger.json"
    if opts.session_reset:
        try:
            os.remove(LEDGER)
            msg = "context ledger reset"
        except FileNotFoundError:
            msg = "no context ledger to reset"
        print(json.dumps({"status": "ok", "message": msg}) if opts.json else msg)
        return 0
    opts._ledger_path = None
    opts._session_loaded = set()
    if opts.session:
        opts._ledger_path = LEDGER
        if os.path.exists(LEDGER):
            try:
                led = json.load(open(LEDGER, encoding="utf-8"))
                # only reuse the ledger when it belongs to THIS session id
                if led.get("session") == opts.session:
                    opts._session_loaded = set(led.get("loaded", []))
            except Exception:
                pass

    # --validate: parse + static checks only, never execute.
    if opts.validate:
        try:
            with open(opts.skill, encoding="utf-8") as fh:
                skill = load_yaml(fh.read())
        except (OSError, YamlError) as e:
            print(json.dumps({"status": "invalid", "errors": [f"parse: {e}"]})
                  if opts.json else f"ERROR: parse: {e}")
            return 1
        errors, warnings = validate_skill(skill, os.path.dirname(os.path.abspath(opts.skill)))
        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.skill}: {len(errors)} error(s), {len(warnings)} warning(s)")
        return 1 if errors else 0

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

    # ---- checkpoint mode: load prior state + ingest the agent's response ------
    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", {})
        # merge stored inputs; CLI-provided --answer/--input override/extend them
        if not opts.input:
            opts.input = state.get("input", "")
        merged = dict(state.get("answers", {}))
        merged.update(opts.answers)
        opts.answers = merged
        # ingest the response the agent wrote for the pending request
        pending = state.get("pending")
        if pending:
            rp = pending.get("response_path")
            if rp and os.path.exists(rp):
                raw = open(rp, encoding="utf-8").read()
                kind = pending["kind"]
                if kind == "llm_query":
                    opts._cache[pending["step"]] = json.loads(
                        raw.strip().splitlines()[-1] if raw.strip() else "{}")
                elif kind == "llm_generate":
                    opts._cache[pending["step"]] = raw
                elif kind == "ask":
                    val = raw.strip()
                    opts._cache[pending["step"]] = (
                        [s.strip() for s in val.split(",") if s.strip()] if pending.get("multi") else val)
                os.remove(rp)
            else:
                # no response yet — re-emit the same pending request
                _print_result({"status": "suspended", "pending": pending}, opts)
                return 2

    interp = Interp(skill, opts)
    # bind declared inputs
    for _, spec in (skill.get("inputs") or {}).items():
        if isinstance(spec, dict) and spec.get("bind"):
            interp.vars[spec["bind"]] = opts.input

    def _persist_ledger():
        # Record this run's loaded files into the session ledger — ONLY at a terminal
        # end (ok/stop), never on suspend (mid-run), so a checkpoint run's own resumes
        # keep seeing the pre-run snapshot and reload their context consistently.
        if not opts._ledger_path:
            return
        merged = sorted(set(opts._session_loaded) | set(interp.context))
        try:
            with open(opts._ledger_path, "w", encoding="utf-8") as fh:
                json.dump({"session": opts.session, "loaded": merged,
                           "updated_at": __import__("time").strftime("%Y-%m-%dT%H:%M:%S")}, fh)
        except OSError:
            pass

    rc = 0
    try:
        interp.run()
        result = {"status": "ok",
                  "outputs": interp.resolve(skill.get("outputs", {})),
                  "pending_generation": interp.pending,
                  "vars": interp.vars}
        if opts.checkpoint and os.path.exists(opts.checkpoint):
            os.remove(opts.checkpoint)   # finished — clear state
        _persist_ledger()
    except Suspend as e:
        # persist state and emit the request for the agent to fulfill (NOT the ledger)
        with open(opts.checkpoint, "w", encoding="utf-8") as fh:
            json.dump({"input": opts.input, "answers": opts.answers,
                       "cache": interp.cache, "pending": e.request}, fh, indent=2)
        _print_result({"status": "suspended", "pending": e.request}, opts)
        return 2
    except Stop as e:
        result = {"status": "stopped", "reason": str(e), "vars": interp.vars}
        if opts.checkpoint and os.path.exists(opts.checkpoint):
            os.remove(opts.checkpoint)
        _persist_ledger()
    except YamlError as e:
        result = {"status": "error", "error": str(e), "vars": interp.vars}
        rc = 1

    _print_result(result, opts)
    return rc


def _print_result(result, opts):
    if opts.json:
        print(json.dumps(result, indent=2))
        return
    print(f"\n=== {result['status'].upper()} ===")
    if result.get("pending"):
        print("PENDING (agent action needed):")
        print(json.dumps(result["pending"], indent=2))
    if result.get("outputs"):
        print(json.dumps(result["outputs"], indent=2))
    if result.get("pending_generation"):
        print("PENDING_GENERATION:", json.dumps(result["pending_generation"], indent=2))
    if result.get("reason"):
        print(result["reason"])
    if result.get("error"):
        print("ERROR:", result["error"])


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