#!/usr/bin/env bash
# PreToolUse gate — DENY root-filesystem scans (`find /`, `ft find /`).
# Rationale: a scan rooted at `/` walks the entire filesystem. With
# BASH_DEFAULT_TIMEOUT_MS=86400000 it does NOT self-timeout, so it hangs the
# calling (sub)agent for hours (observed: a sub-agent stuck 34 min on
# `ft find / -name schema.ts`). Scope every scan to a named directory instead.
#
# Blocks (target is exactly root `/`):   find / -name x   |   ft find /   |
#   bash -c 'find / ...'   |   /usr/bin/find /   |   find "/"
# Allows (scoped):   find /tmp/cr -name x   |   find . -name x   |   find /home/...
set -euo pipefail

INPUT=""; IFS= read -rd '' INPUT || true

# Fast path: the only trigger is the literal `find` (raw JSON is a superset of
# tool_input.command). Absent it, skip the jq/perl work entirely.
case "$INPUT" in
  *find*) ;;
  *) exit 0 ;;
esac

CMD=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // empty')
[[ -z "$CMD" ]] && exit 0

deny() {
  jq -n --arg r "$1" '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: $r
    }
  }'
  exit 0
}

REASON='fs-scan-gate: full-filesystem scan rooted at `/` is blocked (find / , ft find /). It walks the entire tree and will not self-timeout (BASH_DEFAULT_TIMEOUT_MS=24h), hanging the agent. Scope the scan to a named directory, e.g. `find /tmp/cr -name X` or `find . -name X`.'

# Match `find` (optionally a path-prefixed or `ft `-wrapped invocation) whose
# search root is exactly `/`: `find` + ws + optional quote + `/` + optional
# quote + (whitespace|end). `find /tmp` is NOT matched (a non-ws char follows /).
if printf '%s' "$CMD" | perl -ne 'exit 0 if /(?<![\w.\-])find\s+["'"'"']?\/["'"'"']?(?:\s|$)/; exit 1'; then
  deny "$REASON"
fi

exit 0
