#!/bin/bash
# PreToolUse hook on Edit|Write|MultiEdit|NotebookEdit — the dispatch stop
# rule as a MECHANISM (act:48d6790a; design: .claude/plans/console-dispatch.md
# §13-§14; contract: cabinet/dispatch-contract.md §2).
#
# Pilot run 2 (2026-08-23) measured a stop rule stated in prose — verbatim,
# under its own heading, marked as overriding the ambient "keep going" — losing
# to momentum on its first real test: the worker touched a file outside the
# plan's declared `## Surface Area`, a case the plan had PRE-NAMED as a stop,
# and classified it routine. Reinforcement of the same kind is not the fix;
# this hook changes the KIND of enforcement. It is NOT registered globally:
# /dispatch Step 3 writes it into the lane's `.claude/settings.local.json` at
# lane creation, pointing at the plan the brief names, so it governs exactly
# one worker in exactly one worktree.
#
#   surface-area-guard.sh --plan <path>          build flow: the plan's
#                                                 `## Surface Area` is the list
#   surface-area-guard.sh --allow <p> [--allow …] drafting flow: the named
#                                                 paths are the list (a trailing
#                                                 slash marks a directory)
#
# Verdicts (all exit 0; a block is the JSON decision on stdout):
#   - inside the list → pass.
#   - outside the list → BLOCK, naming the stop rule and the park path
#     ("Surface Area is missing <file> because <reason>" as a DECISION
#     REQUEST). The list may be wrong — run 2's was — and that is the
#     console's to widen, never the worker's to guess.
#   - the plan file, .claude/settings*.json, .claude/hooks/ → BLOCK always,
#     even when listed: the allowlist is not writable by the guarded party.
#   - .claude/state/ and the OS temp dir → pass: runtime state and scratch
#     are not project files the plan scopes.
#   - the plan is unreadable or has no `## Surface Area` → BLOCK (fail
#     CLOSED, distinct message): an unreadable list makes every path
#     outside it, and a wrong plan path must fail loudly on the first write.
#   - no path in the payload → pass (a shape this guard does not understand).
#
# Known limit, recorded not hidden: the matcher sees Edit/Write-family tools.
# A write through Bash (`sed -i`, `>`) is not seen. The refusal text says so
# to the worker; the landing's trust ratchet is the audit for the rest.
#
# Reads the tool payload from stdin (`.tool_input.file_path` /
# `.notebook_path`), never an env var (CLAUDE.md § hooks). stdin is read ONCE.
INPUT=$(cat)

# Fired-at-least-once telemetry (act:ff693d4c) — fail-open, never breaks the gate.
FIRED_LOG="${CC_HOOK_FIRED_LOG:-${CLAUDE_PROJECT_DIR:-.}/.claude/state/hooks-fired.jsonl}"
mkdir -p "$(dirname "$FIRED_LOG")" 2>/dev/null \
  && printf '{"hook":"surface-area-guard","fired_at":"%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$FIRED_LOG" 2>/dev/null || true

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"

SAG_INPUT="$INPUT" python3 - "$PROJECT_DIR" "$@" <<'PY'
import json, os, sys, tempfile

project = os.path.realpath(sys.argv[1])
args = sys.argv[2:]
plan_arg = None
allow = []
i = 0
while i < len(args):
    if args[i] == '--plan' and i + 1 < len(args):
        plan_arg = args[i + 1]; i += 2
    elif args[i] == '--allow' and i + 1 < len(args):
        allow.append(args[i + 1]); i += 2
    else:
        i += 1

def block(reason):
    print(json.dumps({"decision": "block", "reason": reason}))
    sys.exit(0)

try:
    payload = json.loads(os.environ.get('SAG_INPUT') or '{}')
except Exception:
    sys.exit(0)  # unparseable payload: not ours to judge
ti = payload.get('tool_input', payload) or {}
target = ti.get('file_path') or ti.get('notebook_path')
if not target:
    sys.exit(0)  # a shape this guard does not understand — pass

if not os.path.isabs(target):
    target = os.path.join(project, target)
target = os.path.realpath(target)

def under(p, root):
    return p == root or p.startswith(root.rstrip('/') + '/')

# Scratch is not a project file the plan scopes — but only OUTSIDE the
# project: a project that itself lives under the temp dir (a test fixture, a
# throwaway checkout) is still governed for every path inside it.
temp_roots = {os.path.realpath(tempfile.gettempdir()), '/tmp', '/private/tmp'}
if os.environ.get('TMPDIR'):
    temp_roots.add(os.path.realpath(os.environ['TMPDIR']))
if not under(target, project) and any(under(target, r) for r in temp_roots):
    sys.exit(0)

def norm(rel):
    rel = rel.strip()
    while rel.startswith('./'):
        rel = rel[2:]
    return rel.rstrip('/')

plan_path = os.path.realpath(plan_arg if os.path.isabs(plan_arg) else os.path.join(project, plan_arg)) if plan_arg else None
plan_label = plan_arg or ', '.join(allow) or '(no list given)'

# The allowlist is not writable by the guarded party — even when listed.
locked = (target == plan_path) if plan_path else False
if under(target, project):
    rel = norm(os.path.relpath(target, project))
    if rel.startswith('.claude/settings') or under(rel, '.claude/hooks'):
        locked = True
if locked:
    block(
        f"Surface Area guard: `{target}` is part of this lane's allowlist machinery (the plan, "
        f".claude/settings*.json, .claude/hooks/) and is not writable by the guarded party, even when "
        f"the Surface Area lists it. If the plan's list is wrong, that is the console's to widen: park "
        f"with a DECISION REQUEST (act:48d6790a)."
    )

if not under(target, project):
    block(
        f"Surface Area guard: `{target}` is outside this lane's project (`{project}`), so it cannot be in "
        f"the plan's Surface Area ({plan_label}). The stop rule (dispatch-contract.md §2) pre-names a file "
        f"outside the declared Surface Area as a STOP, not a judgment call (act:48d6790a). Park: finish what "
        f"does not depend on this file, commit, and end your run with a DECISION REQUEST whose decision line "
        f"reads 'Surface Area is missing {target} because <reason>'. The console widens the list and resumes you."
    )

rel = norm(os.path.relpath(target, project))

# Runtime state written by hooks and tooling — gitignored, never scoped by a plan.
if under(rel, '.claude/state'):
    sys.exit(0)

files, dirs = set(), set()
if plan_path:
    try:
        with open(plan_path, encoding='utf-8') as fh:
            text = fh.read()
    except Exception as e:
        block(
            f"Surface Area guard: cannot read the plan at `{plan_label}` ({e.__class__.__name__}). The guard "
            f"fails CLOSED — no write proceeds until the console repoints it (the lane's "
            f".claude/settings.local.json names the plan path). Park with a DECISION REQUEST (act:48d6790a)."
        )
    lines = text.split('\n')
    start = next((n for n, l in enumerate(lines) if l.strip() == '## Surface Area'), None)
    if start is None:
        block(
            f"Surface Area guard: the plan at `{plan_label}` has no `## Surface Area` section, so every path is "
            f"outside it. The guard fails CLOSED. A dispatched plan must carry the section in pib-db's exact "
            f"format (`## Surface Area`, then `- files: path` / `- dirs: path/`). Park with a DECISION REQUEST "
            f"(act:48d6790a)."
        )
    for l in lines[start + 1:]:
        if l.startswith('## '):
            break
        s = l.strip()
        if not s.startswith('-'):
            continue
        body = s.lstrip('-').strip()
        kind, sep, rest = body.partition(':')
        kind = kind.strip()
        if not sep or kind not in ('files', 'dirs'):
            continue
        token = rest.strip().split()[0] if rest.strip() else ''
        token = token.strip('`,;')
        if not token:
            continue
        (files if kind == 'files' else dirs).add(norm(token))
    if not files and not dirs:
        block(
            f"Surface Area guard: the plan at `{plan_label}` has a `## Surface Area` section that lists no "
            f"`- files:` / `- dirs:` entries. The guard fails CLOSED. Park with a DECISION REQUEST (act:48d6790a)."
        )
for a in allow:
    (dirs if a.endswith('/') else files).add(norm(a))

if rel in files or any(under(rel, d) for d in dirs):
    sys.exit(0)

block(
    f"Surface Area guard: `{rel}` is not in the plan's ## Surface Area ({plan_label}). The stop rule "
    f"(dispatch-contract.md §2) pre-names this case: a file outside the declared Surface Area is a STOP, not a "
    f"judgment call — the list may be incomplete, and that is the console's to widen, not yours to guess "
    f"(act:48d6790a; pilot run 2 lost exactly this way). Park: finish what does not depend on this file, "
    f"commit, and end your run with a DECISION REQUEST whose decision line reads 'Surface Area is missing "
    f"{rel} because <reason>'. The console widens the plan's list and resumes you. Do not route around this "
    f"guard through Bash — a write the guard cannot see is still a write the plan did not scope."
)
PY
