#!/bin/bash
# PreToolUse hook on EVERY tool — the /close scope guard (act:ab53d030).
#
# /close defines itself as a 15–30 second verb: commit, push, one closing
# line. Measured across eight pattern-promotion filings from four projects,
# sessions running /close have run test suites, updated tracker actions,
# triaged feedback files, and written page-long summaries. The prose says one
# line; the sessions produced pages. Per enforcement-pipeline.md that is the
# promotion case, so the scope is now mechanical: while /close is the active
# skill, every tool call outside commit-and-push is refused with one line
# naming the rule.
#
# WHAT "ACTIVE" MEANS HERE — read from the skill-telemetry hooks' own record
# (skill-telemetry.sh + skill-tool-telemetry.sh append one `skill-invoke` line
# per invocation to TELEMETRY_FILE); this guard invents no second tracker.
# The telemetry has no "skill ended" event, so "active" is bounded three ways:
#   1. The last skill-invoke record for THIS session_id must be `close`, and it
#      must be OPERATOR-TYPED (no `source: tool`). A /close that a parent skill
#      invoked programmatically (/session-handoff, /execute) is a sub-step of
#      that parent — the parent's scope governs and the parent cannot be
#      delimited from here. A nested skill invoked FROM /close (the orphan
#      merge path hands off to /qa-handoff by reference) becomes the last
#      record and releases the guard, which is the right semantics.
#   2. A recency window (CC_CLOSE_SCOPE_WINDOW_SEC, default 15 minutes) —
#      wide enough for the orphan-merge path, narrow enough that an operator
#      who typed /close and then kept working is not blocked for the rest of
#      the session.
#   3. /close's own closing sentinel in the transcript after the invocation
#      ("Work saved." / "You're good to close.") releases early.
# If no active skill is recorded, or anything about reading state fails, the
# guard passes (fail open — a guard that errors is a spurious block every
# turn).
#
# THE ALLOWLIST is what the /close skill's own text needs and nothing more:
# git status/add/commit/push/fetch/merge-base/rev-parse/log/diff/merge/
# merge-tree/symbolic-ref/pull/branch/rev-list (the merge-now recipe's
# commands included), the mux worktree health/dirty checks it defers to, the
# commitments/residue script + queue reads it names, Read of files under
# .git/, the AskUserQuestion dialogs it asks with, the Skill tool (a hand-off
# by reference), pib_create_action (Step 6c "file as action") /
# pib_update_action (Step 6c "write verify plan") / pib_complete_action (the
# orphan-merge path), and Read/Write/Edit under .claude/methodology/ (Step 6c
# "write methodology record" — the methodology-capture phase's write path,
# committed in its own follow-up commit). Everything else is blocked.
# Simplification Project 2 plan B3 / decision default 13 (act:73dd31d4)
# widened the list by EXACTLY pib_update_action and the methodology dir.
#
# Reads the payload from STDIN as .tool_input.* — Claude Code sets no
# $CLAUDE_TOOL_INPUT env var; a hook that reads one silently no-ops forever.
# SECURITY (security-0004): payload reaches python3 via the ENVIRONMENT, never
# interpolated into the program source.

INPUT=$(cat)

TELEMETRY_DIR="${TELEMETRY_DIR:-${HOME}/.claude/telemetry}"
TELEMETRY_FILE="${TELEMETRY_FILE:-${TELEMETRY_DIR}/telemetry.jsonl}"

# Fired-at-least-once telemetry (act:ff693d4c): a matcher that never matches is
# otherwise undetectable. Env-overridable for tests; fail-open.
FIRED_LOG="${CC_HOOK_FIRED_LOG:-${CLAUDE_PROJECT_DIR:-.}/.claude/state/hooks-fired.jsonl}"
record_fired() {
  mkdir -p "$(dirname "$FIRED_LOG")" 2>/dev/null \
    && printf '{"hook":"close-scope-guard","fired_at":"%s","evaluated":%s}\n' \
       "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$FIRED_LOG" 2>/dev/null || true
}

# Phase-file override, matching the other guards' convention.
PHASE_FILE=".claude/skills/hooks/phases/close-scope-guard.md"
if [ -f "$PHASE_FILE" ] && [ "$(head -1 "$PHASE_FILE")" = "skip: true" ]; then
  exit 0
fi

# Cheap pre-check before spawning python on every tool call: no telemetry, or
# no /close ever recorded in it, means nothing to evaluate.
if [ ! -f "$TELEMETRY_FILE" ] || ! grep -q '"close"' "$TELEMETRY_FILE" 2>/dev/null; then
  record_fired false
  exit 0
fi

record_fired true

CC_HOOK_INPUT="$INPUT" TELEMETRY_FILE="$TELEMETRY_FILE" python3 - <<'PY' 2>/dev/null
import json, os, re, sys
from datetime import datetime, timezone

RULE = "act:ab53d030"
WINDOW = int(os.environ.get("CC_CLOSE_SCOPE_WINDOW_SEC", "900"))
SENTINELS = ("Work saved.", "You're good to close.")

GIT_OK = {"status", "add", "commit", "push", "fetch", "merge-base", "rev-parse", "log",
          "diff", "merge", "merge-tree", "symbolic-ref", "pull", "branch", "rev-list"}
SHELL_OK = {"echo", "exit", "dirname", "sed", "printf", "true", "false", "[", "[[", "test", ":"}
CONTROL_PREFIX = {"if", "then", "else", "elif", "fi", "!"}
SCRIPT_OK = ("worktree-dirty-check.sh", "worktree-session-health.sh")
NODE_OK = ("watchtower-commitments.mjs", "watchtower-queue.mjs")
# ToolSearch only loads a deferred tool's schema — the call it enables is still
# gated here. Without it the two allowlisted pib tools are unreachable in a
# real session (they are deferred behind ToolSearch; measured live in the QA
# drain of dec-bedb66d1, 2026-08-28).
TOOLS_OK = {"AskUserQuestion", "Skill", "ToolSearch", "mcp__pib-db__pib_create_action",
            "mcp__pib-db__pib_update_action", "mcp__pib-db__pib_complete_action"}
# Step 6c's methodology write path: the one directory Read/Write/Edit may
# touch while /close is active. Matched on a normalized path so a traversal
# (`.claude/methodology/../plans/x.md`) or a shared-prefix sibling
# (`.claude/methodology-notes/`) never qualifies.
METHODOLOGY_DIR = "/.claude/methodology/"


def in_methodology_dir(fp):
    if not fp:
        return False
    norm = os.path.normpath("/" + fp.lstrip("/")) if not fp.startswith("/") else os.path.normpath(fp)
    return METHODOLOGY_DIR in norm + ("/" if norm.endswith("/.claude/methodology") else "")


def block(what):
    print(json.dumps({"decision": "block",
                      "reason": f"/close is commit-and-push; {what} is outside it ({RULE}). "
                                f"If /close has already finished, say its closing line "
                                f"(\"Work saved. The watchtower will process this session shortly.\") "
                                f"and re-run."}))
    sys.exit(0)


def segments(cmd):
    """Split a shell command into simple-command segments, blind to quoted text.
    Single-quoted and double-quoted spans collapse to QUOTED; a $( ... ) inside
    double quotes is still inspected (its own segment); heredoc bodies collapse
    to HEREDOC. Good enough for the shapes /close emits; anything the scanner
    cannot follow ends up as an unknown first word, which is a block, not a
    pass."""
    segs, bufs, stack, i, n = [], [[]], [], 0, len(cmd)

    def flush():
        s = "".join(bufs[-1]).strip()
        bufs[-1].clear()
        if s:
            segs.append(s)

    while i < n:
        ch = cmd[i]
        top = stack[-1] if stack else None
        if top == "dq":
            if ch == "\\":
                i += 2
                continue
            if ch == '"':
                stack.pop()
                bufs[-1].append("QUOTED")
                i += 1
                continue
            if cmd.startswith("$(", i):
                stack.append("sub")
                bufs.append([])
                i += 2
                continue
            i += 1
            continue
        if ch == "'":
            j = cmd.find("'", i + 1)
            bufs[-1].append("QUOTED")
            i = (n if j < 0 else j) + 1
            continue
        if ch == '"':
            stack.append("dq")
            i += 1
            continue
        if ch == "\\":
            bufs[-1].append(cmd[i:i + 2])
            i += 2
            continue
        if cmd.startswith("$(", i):
            stack.append("sub")
            bufs.append([])
            i += 2
            continue
        if ch == ")" and top == "sub":
            flush()
            bufs.pop()
            stack.pop()
            bufs[-1].append("SUBST")
            i += 1
            continue
        if cmd.startswith("<<", i):
            m = re.match(r"<<-?\s*(['\"]?)(\w+)\1", cmd[i:])
            if m:
                tag = m.group(2)
                nl = cmd.find("\n", i)
                rest = cmd[i + m.end():nl] if nl >= 0 else cmd[i + m.end():]
                bufs[-1].append("HEREDOC" + rest)
                if nl < 0:
                    i = n
                    continue
                end = n
                term = re.search(r"^\t*" + re.escape(tag) + r"[ \t]*$", cmd[nl + 1:], flags=re.M)
                if term:
                    end = nl + 1 + term.end()
                flush()
                i = end
                continue
        if ch in ";|&\n`{}()":
            flush()
            i += 1
            continue
        bufs[-1].append(ch)
        i += 1
    flush()
    return segs


def first_disallowed(cmd):
    for seg in segments(cmd):
        toks = seg.split()
        while toks and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", toks[0]) or toks[0] in CONTROL_PREFIX):
            toks.pop(0)
        if not toks:
            continue
        w = toks[0]
        if w in SHELL_OK:
            continue
        if w == "cat" and len(toks) > 1 and toks[1] == "HEREDOC":
            continue
        if w == "git":
            i = 1
            while i < len(toks) and toks[i].startswith("-"):
                i += 2 if toks[i] in ("-C", "-c", "--git-dir", "--work-tree") else 1
            sub = toks[i] if i < len(toks) else ""
            if sub in GIT_OK:
                continue
            return f"git {sub}".strip()
        if w == "node" and any(s in seg for s in NODE_OK):
            continue
        if any(w.endswith(s) for s in SCRIPT_OK):
            continue
        return w
    return None


def real_user_text(entry):
    """The text of an operator prompt, or None for tool results / other rows."""
    if entry.get("type") != "user" or entry.get("isSidechain"):
        return None
    c = (entry.get("message") or {}).get("content")
    if isinstance(c, str):
        return c
    if isinstance(c, list):
        if any(b.get("type") == "tool_result" for b in c if isinstance(b, dict)):
            return None
        return "\n".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")
    return None


def close_finished(transcript_path):
    """True when the transcript shows /close's closing line after the last
    typed /close. Unreadable transcript → False (the window still bounds it)."""
    try:
        rows = [json.loads(l) for l in open(transcript_path, encoding="utf-8") if l.strip()]
    except Exception:
        return False
    start = None
    for idx, e in enumerate(rows):
        t = real_user_text(e)
        if t is not None and "<command-name>/close</command-name>" in t:
            start = idx
    if start is None:
        return False
    for e in rows[start + 1:]:
        if e.get("type") != "assistant" or e.get("isSidechain"):
            continue
        for b in (e.get("message") or {}).get("content") or []:
            if isinstance(b, dict) and b.get("type") == "text" and any(s in b.get("text", "") for s in SENTINELS):
                return True
    return False


try:
    d = json.loads(os.environ["CC_HOOK_INPUT"])
except Exception:
    sys.exit(0)
sid = d.get("session_id")
tool = d.get("tool_name") or ""
ti = d.get("tool_input") or {}
if isinstance(ti, str):
    try:
        ti = json.loads(ti)
    except Exception:
        ti = {}
if not sid:
    sys.exit(0)

last = None
try:
    with open(os.environ["TELEMETRY_FILE"], encoding="utf-8") as f:
        for line in f:
            try:
                r = json.loads(line)
            except Exception:
                continue
            if r.get("event") == "skill-invoke" and r.get("session_id") == sid:
                last = r
except Exception:
    sys.exit(0)

if not last or last.get("skill") != "close" or last.get("source") == "tool":
    sys.exit(0)
try:
    ts = datetime.strptime(last.get("ts", ""), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    if (datetime.now(timezone.utc) - ts).total_seconds() > WINDOW:
        sys.exit(0)
except Exception:
    sys.exit(0)
tp = d.get("transcript_path")
if tp and os.path.exists(tp) and close_finished(tp):
    sys.exit(0)

# /close IS active. Allow what its own text needs; block the rest.
if tool in TOOLS_OK:
    sys.exit(0)
if tool == "Read":
    fp = str(ti.get("file_path") or "")
    if "/.git/" in fp or fp.startswith(".git/") or fp.endswith("/.git"):
        sys.exit(0)
    if in_methodology_dir(fp):
        sys.exit(0)
    block(f"Read of {fp or 'that file'}")
if tool in ("Write", "Edit"):
    fp = str(ti.get("file_path") or "")
    if in_methodology_dir(fp):
        sys.exit(0)
    block(f"{tool} of {fp or 'that file'}")
if tool == "Bash":
    bad = first_disallowed(str(ti.get("command") or ""))
    if bad is None:
        sys.exit(0)
    block(f"Bash `{bad}`")
block(tool or "that tool")
PY

exit 0
