#!/usr/bin/env python3
# briefing — pre-loads the skills a subagent declares into its context.
#
# One script, three entry points:
#
#   PreToolUse on the Agent tool (Claude Code)  deny an unbriefable spawn
#   SubagentStart (both)                         additionalContext, or abort
#   SessionStart (both)                          warn about broken declarations
#
# Run as `briefing-doctor` (or `briefing-preload doctor`) it checks every
# briefing-aware agent of a project and exits 1 if a spawn would fail.
#
# Hard-fail policy: if any declared skill cannot be resolved, nothing
# proceeds on a partial briefing.
#
# On Windows, Claude Code starts briefing-preload.exe (winlaunch) next to this
# file, which picks a Python and runs this script:
# winlaunch: run python {self}

import glob
import json
import os
import re
import sys


# Above this many bytes of injected skill text the spawn still goes ahead,
# but the human hears about it: that much context is rarely intended.
BUDGET_BYTES = 64 * 1024


def slurp(path):
    try:
        with open(path, "r", encoding="utf-8") as f:
            return f.read()
    except OSError:
        return ""


def find_first_readable(*paths):
    for p in paths:
        if p and os.access(p, os.R_OK) and os.path.isfile(p):
            return p
    return None


_FM_RE = re.compile(r"\A---\r?\n(.*?)\r?\n---\r?\n(.*)\Z", re.DOTALL)


def split_frontmatter(text):
    # A UTF-8 byte order mark (some editors write one) would hide the leading "---".
    if text.startswith("\ufeff"):
        text = text[1:]
    m = _FM_RE.match(text)
    if m:
        return m.group(1), m.group(2)
    return "", text


_BRIEFING_BLOCK_RE = re.compile(
    r"^briefing:[ \t]*\r?\n((?:[ \t]+[^\r\n]*(?:\r?\n|$))+)", re.MULTILINE
)
_SKILLS_BLOCK_RE = re.compile(
    r"^skills:[ \t]*\r?\n((?:[ \t]*-[ \t]*[^\r\n]+\r?\n?)+)", re.MULTILINE
)
_BLOCK_ITEM_RE = re.compile(
    r'^[ \t]*-[ \t]*(["\']?)([^"\'\r\n]+)\1[ \t]*$', re.MULTILINE
)
_SKILLS_FLOW_RE = re.compile(r"^skills:[ \t]*\[([^\]\r\n]+)\]", re.MULTILINE)


def _dedent(block):
    lines = block.splitlines()
    indents = [
        len(l) - len(l.lstrip(" \t")) for l in lines if l.strip()
    ]
    if not indents:
        return block
    common = min(indents)
    return "\n".join(l[common:] if len(l) >= common else l for l in lines) + "\n"


def parse_skills_list(fm):
    """Extract the `briefing.skills` list from agent frontmatter.

    Expected shape:

        briefing:
          skills:
            - foo
            - bar:baz

    Flow form (`skills: [foo, bar]`) is also accepted under the
    `briefing:` block. The bare top-level `skills:` key is reserved
    for Claude Code itself and is intentionally NOT read here.
    """
    if not fm:
        return []

    m = _BRIEFING_BLOCK_RE.search(fm)
    if not m:
        return []

    block = _dedent(m.group(1))

    sm = _SKILLS_BLOCK_RE.search(block)
    if sm:
        out = []
        for item in _BLOCK_ITEM_RE.finditer(sm.group(1)):
            v = item.group(2).strip()
            if v:
                out.append(v)
        return out

    fm_match = _SKILLS_FLOW_RE.search(block)
    if fm_match:
        return [
            v.strip().strip('"').strip("'")
            for v in fm_match.group(1).split(",")
            if v.strip()
        ]

    return []


_FM_NAME_RE = re.compile(r"""^name:[ \t]*(["']?)([^"'\r\n]+?)\1[ \t]*$""", re.MULTILINE)


def parse_fm_name(fm):
    m = _FM_NAME_RE.search(fm or "")
    return m.group(2).strip() if m else None


def _walk_files(root, suffix):
    """Every file below `root` ending in `suffix`, in a stable order."""
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames.sort()
        for fn in sorted(filenames):
            if fn.endswith(suffix):
                yield os.path.join(dirpath, fn)


def claude_agent_roots(cwd, home):
    return [f"{cwd}/.claude/agents", f"{home}/.claude/agents"]


def claude_agent_name(path):
    fm, _ = split_frontmatter(slurp(path))
    return parse_fm_name(fm) or os.path.splitext(os.path.basename(path))[0]


def find_claude_agent(subagent, cwd, home):
    """Find the agent file Claude Code spawns as `subagent`.

    The agent's identity is its frontmatter `name`; the file name is only
    the fast path, and a file named after the agent that declares another
    name is not it.
    """
    for root in claude_agent_roots(cwd, home):
        if not os.path.isdir(root):
            continue
        direct = f"{root}/{subagent}.md"
        if find_first_readable(direct) and claude_agent_name(direct) == subagent:
            return direct
        for path in _walk_files(root, ".md"):
            if path != direct and claude_agent_name(path) == subagent:
                return path
    return None


def list_claude_agents(cwd, home):
    """{name: path} for every Claude Code agent; project beats user."""
    agents = {}
    for root in claude_agent_roots(cwd, home):
        if os.path.isdir(root):
            for path in _walk_files(root, ".md"):
                agents.setdefault(claude_agent_name(path), path)
    return agents


def _load_json(path):
    try:
        data = json.loads(slurp(path) or "{}")
    except ValueError:
        return {}
    return data if isinstance(data, dict) else {}


def _within(path, root):
    # normcase: on Windows case and slash direction do not count, and
    # normpath leaves backslashes there.
    path = os.path.normcase(os.path.normpath(path))
    root = os.path.normcase(os.path.normpath(root))
    return path == root or path.startswith(root.rstrip(os.sep) + os.sep)


def user_home():
    """$HOME, else the platform's idea of it: Claude Code on Windows without
    Git Bash starts hooks with no HOME at all."""
    return os.environ.get("HOME") or os.path.expanduser("~")


def enabled_plugins(cwd, home):
    """The merged enabledPlugins map, `<plugin>@<origin>` -> bool, from the
    settings files a hook can see — user, then project, then project-local,
    each winning per key over the one before.

    Claude Code layers `--settings` and managed settings above these, but a
    hook is handed neither, so a plugin enabled or disabled *only* there is
    read here as if the setting were absent.
    """
    merged = {}
    for path in (f"{home}/.claude/settings.json",
                 f"{cwd}/.claude/settings.json",
                 f"{cwd}/.claude/settings.local.json"):
        ep = _load_json(path).get("enabledPlugins")
        if isinstance(ep, dict):
            for key, val in ep.items():
                if isinstance(val, bool):
                    merged[key] = val
    return merged


def claude_plugins(cwd, home):
    """(namespace, root, manifest) of every plugin Claude Code has installed
    AND enabled for `cwd`, project-scoped installs first.

    installed_plugins.json is the index, not the cache: the cache keeps
    versions that are no longer installed, and some versions are commit
    hashes, so no ordering of the version directories finds the live one.

    An installed marketplace plugin is off until enabledPlugins turns it on,
    so a name absent from the merged map is skipped — matching Claude Code,
    which loads a disabled plugin's skills for no one.
    """
    plugins = _load_json(f"{home}/.claude/plugins/installed_plugins.json").get("plugins")
    if not isinstance(plugins, dict):
        return []
    enabled = enabled_plugins(cwd, home)
    found = []
    for key, entries in plugins.items():
        if not enabled.get(key, False):
            continue
        for e in entries if isinstance(entries, list) else ():
            root = e.get("installPath") if isinstance(e, dict) else None
            if not isinstance(root, str):
                continue
            project = e.get("projectPath")
            if isinstance(project, str) and project:
                if not _within(cwd, project):
                    continue
                found.append((-len(project), key, root))
            else:
                found.append((0, key, root))
    out = []
    for _, key, root in sorted(found):
        manifest = _load_json(f"{root}/.claude-plugin/plugin.json")
        name = manifest.get("name")
        out.append((name if isinstance(name, str) else key.partition("@")[0],
                    root, manifest))
    return out


def plugin_skill_dirs(root, manifest):
    """Every skill directory Claude Code loads from the plugin at `root`: the
    default skills/<name>/ scan, plus the manifest's `skills` paths, each one
    skill directory or a directory of them."""
    extra = manifest.get("skills")
    extra = [extra] if isinstance(extra, str) else extra
    bases = [f"{root}/skills"] + [
        os.path.normpath(os.path.join(root, p))
        for p in (extra if isinstance(extra, list) else ())
        if isinstance(p, str)
    ]
    for base in bases:
        if not _within(base, root):
            continue
        if os.path.isfile(f"{base}/SKILL.md"):
            yield base
        elif os.path.isdir(base):
            for d in sorted(os.listdir(base)):
                if os.path.isfile(f"{base}/{d}/SKILL.md"):
                    yield f"{base}/{d}"


def resolve_plugin_skill(skill, cwd, home, plugin=None):
    for name, root, manifest in claude_plugins(cwd, home):
        if plugin is None or name == plugin:
            for d in plugin_skill_dirs(root, manifest):
                if os.path.basename(d) == skill and os.access(f"{d}/SKILL.md", os.R_OK):
                    return f"{d}/SKILL.md"
    return None


def resolve_skill(name, cwd, home):
    # explicit plugin namespace: plugin:skill
    if ":" in name and not name.startswith(":"):
        plugin, _, skill = name.partition(":")
        if plugin and skill and " " not in plugin:
            return resolve_plugin_skill(skill, cwd, home, plugin)

    for base in (f"{cwd}/.claude/skills", f"{home}/.claude/skills"):
        p = f"{base}/{name}/SKILL.md"
        if os.access(p, os.R_OK):
            return p

    return resolve_plugin_skill(name, cwd, home)


_TOML_COMMENT_RE = re.compile(
    r"^[ \t]*#[ \t]*briefing:[ \t]*skills[ \t]*=[ \t]*\[([^\]\r\n]*)\]"
)


def _toml_string_state(line, state):
    """Return the open multi-line string delimiter at the end of `line`.

    `state` is the delimiter open at the start of the line, or None. Just
    enough of a TOML lexer to tell a comment from a line of prose inside a
    multi-line `developer_instructions` string.
    """
    i, n = 0, len(line)
    while i < n:
        if state is None:
            c = line[i]
            if c == "#":
                break
            if line.startswith('"""', i) or line.startswith("'''", i):
                state = line[i:i + 3]
                i += 3
                continue
            if c in "\"'":
                i += 1
                while i < n and line[i] != c:
                    i += 2 if (c == '"' and line[i] == "\\") else 1
            i += 1
            continue
        if state == '"""' and line[i] == "\\":
            i += 2
            continue
        if line.startswith(state, i):
            state = None
            i += 3
            continue
        i += 1
    return state


def parse_skills_comment(text):
    """Extract the skill list from a `# briefing: skills = [...]` comment.

    Codex rejects agent files carrying keys it does not know, so the
    declaration lives in a comment every TOML parser ignores. Lines inside
    multi-line strings are prose, not declarations.
    """
    state = None
    for line in (text or "").splitlines():
        if state is None:
            m = _TOML_COMMENT_RE.match(line)
            if m:
                return [v.strip() for v in _TOML_ITEM_RE.findall(m.group(1)) if v.strip()]
        state = _toml_string_state(line, state)
    return []


_TOML_BRIEFING_RE = re.compile(
    r"^\[briefing\][ \t]*\r?\n(.*?)(?=^\[|\Z)", re.MULTILINE | re.DOTALL
)
_TOML_SKILLS_RE = re.compile(r"^skills[ \t]*=[ \t]*\[(.*?)\]", re.MULTILINE | re.DOTALL)
_TOML_ITEM_RE = re.compile(r"""["']([^"']+)["']""")


def parse_skills_toml(text):
    """Extract the legacy `[briefing] skills` list from a Codex agent TOML file.

    Expected shape:

        [briefing]
        skills = ["foo", "bar:baz"]

    Codex 0.153 drops any agent file carrying this table ("unknown field
    `briefing`"), so it is read only to keep older setups briefed and to
    tell their owners to move to the comment form.

    `tomllib` is stdlib only from Python 3.11 and the hook still has to run
    on older interpreters, so a regex fallback covers the single table and
    single key we care about.
    """
    if not text:
        return []

    try:
        import tomllib
    except ImportError:
        tomllib = None

    if tomllib is not None:
        try:
            doc = tomllib.loads(text)
        except Exception:
            return []
        block = doc.get("briefing")
        if not isinstance(block, dict):
            return []
        skills = block.get("skills")
        if not isinstance(skills, list):
            return []
        return [s.strip() for s in skills if isinstance(s, str) and s.strip()]

    m = _TOML_BRIEFING_RE.search(text)
    if not m:
        return []
    sm = _TOML_SKILLS_RE.search(m.group(1))
    if not sm:
        return []
    return [v.strip() for v in _TOML_ITEM_RE.findall(sm.group(1)) if v.strip()]


_TOML_NAME_RE = re.compile(r"""^[ \t]*name[ \t]*=[ \t]*(?:"([^"\\]*)"|'([^']*)')""")
_TOML_HEADER_RE = re.compile(r"^[ \t]*\[")


def parse_toml_name(text):
    """Return the top-level `name` of an agent file, or None."""
    state = None
    for line in (text or "").splitlines():
        if state is None:
            if _TOML_HEADER_RE.match(line):
                return None
            m = _TOML_NAME_RE.match(line)
            if m:
                return m.group(1) if m.group(1) is not None else m.group(2)
        state = _toml_string_state(line, state)
    return None


def codex_home_dir(home):
    return os.environ.get("CODEX_HOME") or f"{home}/.codex"


def project_dirs(cwd):
    """Directories from cwd up to the project root, nearest first.

    Codex treats each of them as a config layer. The root is the nearest
    directory holding `.git` (Codex's default `project_root_markers`);
    without one, cwd stands alone.
    """
    cwd = os.path.abspath(cwd)
    dirs = []
    d = cwd
    while True:
        dirs.append(d)
        if os.path.exists(os.path.join(d, ".git")):
            return dirs
        parent = os.path.dirname(d)
        if parent == d:
            return [cwd]
        d = parent


def codex_layers(cwd, home):
    """Config folders Codex layers, highest priority first."""
    return [f"{d}/.codex" for d in project_dirs(cwd)] + [codex_home_dir(home), "/etc/codex"]


_TOML_AGENT_SECTION_RE = re.compile(
    r"""^\[agents\.(?:"([^"\]]+)"|([A-Za-z0-9_-]+))\][ \t]*\r?\n(.*?)(?=^\[|\Z)""",
    re.MULTILINE | re.DOTALL,
)
_TOML_CONFIG_FILE_RE = re.compile(
    r"""^config_file[ \t]*=[ \t]*(?:"([^"]*)"|'([^']*)')""", re.MULTILINE
)


def declared_roles(layer):
    """{name: path} for roles `<layer>/config.toml` declares with a config_file.

    Codex lets `[agents.<name>] config_file = "..."` point at a role file
    anywhere; relative paths resolve against the config.toml's directory.
    """
    text = slurp(f"{layer}/config.toml")
    if not text:
        return {}

    try:
        import tomllib
    except ImportError:
        tomllib = None

    found = {}
    if tomllib is not None:
        try:
            agents = tomllib.loads(text).get("agents", {})
        except Exception:
            return {}
        if isinstance(agents, dict):
            for name, role in agents.items():
                if isinstance(role, dict) and isinstance(role.get("config_file"), str):
                    found[name] = role["config_file"]
    else:
        for m in _TOML_AGENT_SECTION_RE.finditer(text):
            cm = _TOML_CONFIG_FILE_RE.search(m.group(3))
            if cm:
                found[m.group(1) or m.group(2)] = (
                    cm.group(1) if cm.group(1) is not None else cm.group(2)
                )

    return {
        name: os.path.join(layer, os.path.expanduser(path))
        for name, path in found.items() if path
    }


def find_codex_agent(agent_type, cwd, home):
    """Find the agent file Codex would load for `agent_type`.

    Codex takes the role name from the `name` field and discovers every
    `*.toml` below each `agents/` directory, recursively — project layers
    nearest first, then CODEX_HOME, then the system layer. Within a layer
    a role declared in config.toml wins. `<name>.toml` is only the fast
    path.
    """
    for layer in codex_layers(cwd, home):
        declared = declared_roles(layer).get(agent_type)
        if declared and find_first_readable(declared):
            return declared, slurp(declared)

        root = f"{layer}/agents"
        if not os.path.isdir(root):
            continue
        direct = f"{root}/{agent_type}.toml"
        if find_first_readable(direct):
            text = slurp(direct)
            if parse_toml_name(text) in (None, agent_type):
                return direct, text
        for path in _walk_files(root, ".toml"):
            if path == direct:
                continue
            text = slurp(path)
            if parse_toml_name(text) == agent_type:
                return path, text
    return None, ""


def list_codex_agents(cwd, home):
    """{name: path} for every Codex role, resolved the way Codex layers them."""
    agents = {}
    for layer in codex_layers(cwd, home):
        layer_agents = {
            name: path for name, path in declared_roles(layer).items()
            if find_first_readable(path)
        }
        root = f"{layer}/agents"
        if os.path.isdir(root):
            for path in _walk_files(root, ".toml"):
                name = parse_toml_name(slurp(path))
                if name:
                    layer_agents.setdefault(name, path)
        for name, path in layer_agents.items():
            agents.setdefault(name, path)
    return agents


def resolve_skill_codex(name, cwd, home):
    """Resolve a skill name against the locations Codex itself searches."""
    codex_home = codex_home_dir(home)
    # explicit plugin namespace: plugin:skill — Codex uses the same syntax
    # as Claude Code, but installs plugins under a versioned cache path.
    if ":" in name and not name.startswith(":"):
        plugin, _, skill = name.partition(":")
        if plugin and skill and " " not in plugin:
            for pat in (
                f"{codex_home}/plugins/cache/*/{plugin}/*/skills/{skill}/SKILL.md",
                f"{codex_home}/plugins/cache/{plugin}/*/skills/{skill}/SKILL.md",
                f"{codex_home}/plugins/cache/*/{plugin}/skills/{skill}/SKILL.md",
            ):
                for g in sorted(glob.glob(pat)):
                    if os.access(g, os.R_OK):
                        return g
            return None

    bases = []
    for d in project_dirs(cwd):
        bases += [f"{d}/.codex/skills", f"{d}/.agents/skills"]
    bases += [
        f"{codex_home}/skills",
        f"{home}/.agents/skills",
        f"{codex_home}/skills/.system",
        "/etc/codex/skills",
    ]
    for base in bases:
        p = f"{base}/{name}/SKILL.md"
        if os.access(p, os.R_OK):
            return p

    return None


# ---- the shared part: declaration -> checked briefing ------------------------

LEGACY_NOTE = (
    "declares skills in a [briefing] table. Codex 0.153+ rejects that as an "
    "unknown field and ignores the whole agent. Replace the table with a "
    "comment line: # briefing: skills = [...]"
)


def claude_declaration(path):
    """(skills, legacy) of a Claude Code agent file."""
    fm, _ = split_frontmatter(slurp(path))
    return parse_skills_list(fm), False


def codex_declaration(text):
    """(skills, legacy) of a Codex agent file; the comment wins over a table."""
    legacy = parse_skills_toml(text)
    return (parse_skills_comment(text) or legacy), bool(legacy)


class Briefing:
    """Everything known about briefing one agent, before anything is emitted."""

    def __init__(self, agent, path, skills, resolver, legacy=False):
        self.agent = agent
        self.path = path
        self.skills = skills
        self.legacy = legacy
        self.missing = []
        blocks = []
        for name in skills:
            skill_path = resolver(name)
            if not skill_path:
                self.missing.append(name)
                continue
            _, body = split_frontmatter(slurp(skill_path))
            skill_dir = os.path.dirname(os.path.abspath(skill_path))
            blocks.append(
                f'<skill name="{name}" dir="{skill_dir}">\n{body.strip()}\n</skill>'
            )
        self.text = "\n\n".join(blocks)
        self.size = len(self.text.encode("utf-8"))

    @property
    def oversized(self):
        return self.size > BUDGET_BYTES

    def audit_line(self):
        kb = max(1, round(self.size / 1024)) if self.size else 0
        return f"briefing: {self.agent} ← {', '.join(self.skills)} ({kb} kB)"

    def size_note(self):
        return (
            f"briefing: agent '{self.agent}' is briefed with {self.size // 1024} kB "
            f"of skill text (over {BUDGET_BYTES // 1024} kB) — consider declaring "
            "fewer or smaller skills."
        )

    def legacy_note(self):
        return f"briefing: {self.path} {LEGACY_NOTE}"

    def missing_note(self):
        return (
            f"briefing: agent '{self.agent}' references unknown skill(s): "
            + ", ".join(self.missing)
        )


def claude_briefing(agent, path, cwd, home):
    skills, legacy = claude_declaration(path)
    if not skills:
        return None
    return Briefing(agent, path, skills, lambda n: resolve_skill(n, cwd, home), legacy)


def codex_briefing(agent, path, text, cwd, home):
    skills, legacy = codex_declaration(text)
    if not skills:
        return None
    return Briefing(agent, path, skills, lambda n: resolve_skill_codex(n, cwd, home), legacy)


BRIEFING_HEADER = (
    "# Briefing — pre-loaded skills\n\n"
    "The skills below have been injected directly into your context by the\n"
    "briefing plugin, one <skill> element each. Treat them as already loaded —\n"
    "{dont}; their content is already here. Only the SKILL.md body is\n"
    "included: paths a skill mentions (references/, scripts/, …) are relative to\n"
    "its element's dir, so read them from there when you need them.\n\n"
)


# ---- spawn time --------------------------------------------------------------

ABORT_CONTEXT = (
    "# Briefing — FAILED\n\n"
    "The skills this agent declares could not be loaded: {names}.\n\n"
    "You are NOT briefed for this task. Do NOT attempt it and do NOT\n"
    "improvise a substitute. Report this exact failure to whoever\n"
    "delegated to you, and stop.\n"
)

DONT = {
    "claude": "do NOT call the Skill tool for any of these names",
    "codex": "do NOT go looking for their SKILL.md files",
}


def spawn_harness(data, cwd, home):
    """Which harness sent this SubagentStart.

    Both send it. The transcript path tells them apart; without one, a
    `turn_id` is Codex's, and otherwise whichever harness has the agent.
    """
    harnesses = harness_of(data)
    if len(harnesses) == 1:
        return harnesses[0]
    if "turn_id" in data:
        return "codex"
    agent_type = data.get("agent_type") or ""
    return "claude" if find_claude_agent(agent_type, cwd, home) else "codex"


def spawn_briefing(harness, agent_type, cwd, home):
    if harness == "claude":
        path = find_claude_agent(agent_type, cwd, home)
        return claude_briefing(agent_type, path, cwd, home) if path else None
    path, text = find_codex_agent(agent_type, cwd, home)
    return codex_briefing(agent_type, path, text, cwd, home) if path else None


def main_subagent_start(data):
    """SubagentStart — inject the skills as additionalContext.

    Both harnesses brief here. Neither can deny a spawn at this point, so a
    missing skill becomes an instruction to stop; Claude Code has normally
    refused the spawn already, in main_claude_guard.
    """
    agent_type = data.get("agent_type") or ""
    if not agent_type:
        return 0

    cwd = data.get("cwd") or os.environ.get("PWD") or "."
    home = user_home()

    harness = spawn_harness(data, cwd, home)
    b = spawn_briefing(harness, agent_type, cwd, home)
    if b is None:
        return 0

    notes = [b.legacy_note()] if b.legacy else []

    if b.missing:
        msg = b.missing_note()
        sys.stderr.write(msg + "\n")
        sys.stdout.write(json.dumps({
            "systemMessage": "\n".join([msg] + notes),
            "hookSpecificOutput": {
                "hookEventName": "SubagentStart",
                "additionalContext": ABORT_CONTEXT.format(names=", ".join(b.missing)),
            },
        }))
        return 0

    if b.oversized:
        notes.append(b.size_note())
    if notes:
        sys.stderr.write("\n".join(notes) + "\n")

    header = BRIEFING_HEADER.format(dont=DONT[harness])
    sys.stdout.write(json.dumps({
        "systemMessage": "\n".join([b.audit_line()] + notes),
        "hookSpecificOutput": {
            "hookEventName": "SubagentStart",
            "additionalContext": header + b.text,
        },
    }))
    return 0


def main_claude_guard(data):
    """PreToolUse on the Agent tool — deny a spawn that cannot be briefed.

    The input is never changed: auto mode reviews the call before hooks run
    and refuses one a hook rewrote. The skills arrive at SubagentStart.
    """
    ti = data.get("tool_input") or {}
    subagent = ti.get("subagent_type") or ""
    if not subagent:
        return 0

    cwd = data.get("cwd") or os.environ.get("PWD") or "."
    home = user_home()

    agent_file = find_claude_agent(subagent, cwd, home)
    if not agent_file:
        return 0

    b = claude_briefing(subagent, agent_file, cwd, home)
    if b is None or not b.missing:
        return 0

    msg = b.missing_note()
    sys.stderr.write(msg + "\n")
    sys.stdout.write(json.dumps({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": msg,
        }
    }))
    return 0


# ---- before any spawn: doctor and SessionStart pre-flight -------------------

HARNESSES = ("claude", "codex")
HARNESS_LABEL = {"claude": "Claude Code", "codex": "Codex"}


def check(cwd, home, harnesses=HARNESSES):
    """[(harness, Briefing)] for every agent that declares skills."""
    out = []
    if "claude" in harnesses:
        for name, path in sorted(list_claude_agents(cwd, home).items()):
            b = claude_briefing(name, path, cwd, home)
            if b is not None:
                out.append(("claude", b))
    if "codex" in harnesses:
        for name, path in sorted(list_codex_agents(cwd, home).items()):
            b = codex_briefing(name, path, slurp(path), cwd, home)
            if b is not None:
                out.append(("codex", b))
    return out


def problems(b):
    """(failures, warnings) as short strings."""
    fails, warns = [], []
    if b.missing:
        fails.append("unknown skill(s): " + ", ".join(b.missing))
    if b.legacy:
        fails.append("[briefing] table — Codex 0.153+ ignores this whole agent; "
                     "use # briefing: skills = [...]")
    if b.oversized:
        warns.append(f"{b.size // 1024} kB of skill text, over {BUDGET_BYTES // 1024} kB")
    return fails, warns


def harness_of(data):
    """Which harness sent this SessionStart — by where it keeps transcripts."""
    # Forward slashes throughout: Windows reports C:\Users\...\.claude\...
    tp = (data.get("transcript_path") or "").replace("\\", "/")
    codex_home = (os.environ.get("CODEX_HOME") or "").replace("\\", "/")
    if "/.codex/" in tp or (codex_home and tp.startswith(codex_home.rstrip("/") + "/")):
        return ("codex",)
    if "/.claude/" in tp:
        return ("claude",)
    return HARNESSES


def main_session_start(data):
    """Warn the human about declarations that would fail at spawn time."""
    if data.get("source") not in (None, "startup", "resume"):
        return 0
    cwd = data.get("cwd") or os.environ.get("PWD") or "."
    home = user_home()

    # Only what would fail at spawn time. An oversized briefing still works;
    # it shows in the doctor and in the spawn's own audit line, and repeating
    # it at every session start would be noise.
    lines = []
    for harness, b in check(cwd, home, harness_of(data)):
        fails, _ = problems(b)
        for p in fails:
            lines.append(f"  {HARNESS_LABEL[harness]} agent '{b.agent}': {p}")
    if not lines:
        return 0

    shown = lines[:8]
    if len(lines) > len(shown):
        shown.append(f"  … and {len(lines) - len(shown)} more")
    sys.stdout.write(json.dumps({
        "systemMessage": "briefing: declared skills that will not work — "
                         "run briefing-doctor for details\n" + "\n".join(shown),
    }))
    return 0


def doctor(argv):
    import argparse

    ap = argparse.ArgumentParser(
        prog="briefing-doctor",
        description="Check every briefing-aware agent of a project; exit 1 if "
                    "a spawn would fail.",
    )
    ap.add_argument("--cwd", default=".", help="project directory (default: .)")
    ap.add_argument("--harness", choices=("claude", "codex", "both"), default="both")
    args = ap.parse_args(argv)

    cwd = os.path.abspath(args.cwd)
    home = user_home()
    harnesses = HARNESSES if args.harness == "both" else (args.harness,)
    results = check(cwd, home, harnesses)

    print(f"briefing doctor — {cwd}")
    if not results:
        print("  no agents declare skills")
        return 0

    failed = False
    for harness in harnesses:
        entries = [b for h, b in results if h == harness]
        if not entries:
            continue
        print(f"\n{HARNESS_LABEL[harness]}")
        for b in entries:
            fails, warns = problems(b)
            where = os.path.relpath(b.path, cwd) if b.path.startswith(cwd + os.sep) else b.path
            status = "FAIL" if fails else "WARN" if warns else "ok"
            failed = failed or bool(fails)
            print(f"  {status:<4}  {b.agent}  ({where})")
            print(f"        {', '.join(b.skills)}  ({b.size // 1024} kB)")
            for p in fails + warns:
                print(f"        → {p}")
    return 1 if failed else 0


def main():
    if os.path.basename(sys.argv[0]) == "briefing-doctor":
        return doctor(sys.argv[1:])
    if sys.argv[1:2] == ["doctor"]:
        return doctor(sys.argv[2:])

    raw = sys.stdin.read()
    if not raw:
        return 0

    try:
        data = json.loads(raw)
    except (ValueError, TypeError):
        return 0
    if not isinstance(data, dict):
        return 0

    event = data.get("hook_event_name")
    if event == "SubagentStart":
        return main_subagent_start(data)
    if event == "SessionStart":
        return main_session_start(data)
    if data.get("tool_name") == "Agent":
        return main_claude_guard(data)
    return 0


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