#!/usr/bin/env bash
# Differential audit of cpu-guard's heavy classifier across every project.
#
# Ground truth  = the package.json script BODY invokes a heavy runner.
# Actual        = cpu-guard.sh routes `<pm> <script>` to local-gate (remote).
# A script that is heavy but routes LOCAL is a remote-offload hole.
#
# Runs the real cpu-guard.sh against a sandbox HOME whose local-gate is a probe,
# so the audit exercises the shipped code path rather than a copy of its rules.
#
# Usage: bb-audit-heavy [--runner <regex>] [--root <dir>] [-v]
# Exit:  0 = every heavy script routes remote, 1 = holes found.
set -uo pipefail

ROOT="$HOME/Projects"
# Each runner is matched with the subcommand that makes it a build, not by name:
# `playwright show-report`, `playwright install` and `turbo run dev` are viewer,
# download and dev-server steps that correctly stay local.
RUNNER='playwright\s+test|vitest|jest|\btsc\b|(next|astro|vite|ng)\s+build|turbo\s+run\s+(build|test|typecheck|check|coverage|lint)|cargo\s+(test|build|check)|go\s+(test|build)'
VERBOSE=0
while [ $# -gt 0 ]; do
  case "$1" in
    --runner) RUNNER="$2"; shift 2 ;;
    --root) ROOT="$2"; shift 2 ;;
    -v|--verbose) VERBOSE=1; shift ;;
    -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
    *) echo "bb-audit-heavy: unknown arg $1" >&2; exit 2 ;;
  esac
done

command -v jq >/dev/null || { echo "bb-audit-heavy: jq required" >&2; exit 2; }

SANDBOX=$(mktemp -d "${TMPDIR:-/tmp}/bb-audit-XXXXXX")
trap 'rm -rf "$SANDBOX"' EXIT
FAKE="$SANDBOX/home"
mkdir -p "$FAKE/.claude/bin" "$FAKE/.claude/lib"
cp "$HOME/.claude/lib/cpu-guard.sh" "$FAKE/.claude/lib/cpu-guard.sh"
printf '#!/usr/bin/env bash\necho ROUTED\n' > "$FAKE/.claude/bin/local-gate"
printf '#!/usr/bin/env bash\nexit 0\n' > "$FAKE/.claude/lib/buildslot.sh"
chmod +x "$FAKE/.claude/bin/local-gate" "$FAKE/.claude/lib/buildslot.sh"
# The classifier only routes when remote offload is enabled; the audit asks what
# the classifier decides, independent of the live host's enabled flag.
echo '{"enabled": true}' > "$FAKE/.claude/build-remote.json"

routes_remote() { # cwd, argv... -> 0 if routed to local-gate
  local dir="$1"; shift
  local out
  out=$(cd "$dir" && env -i HOME="$FAKE" PATH="/usr/bin:/bin" \
    bash "$FAKE/.claude/lib/cpu-guard.sh" "$@" 2>/dev/null | head -1)
  [ "$out" = "ROUTED" ]
}

ws_root_for() { # package dir -> workspace root, empty if standalone
  local d="$1"
  while [ "$d" != "/" ] && [ -n "$d" ]; do
    [ -f "$d/pnpm-workspace.yaml" ] && { printf '%s' "$d"; return 0; }
    d=$(dirname "$d")
  done
  return 1
}

# Deliberately re-derived here rather than sourced from cpu-guard.sh: an oracle that
# reuses the code under test cannot catch that code's bugs.
ws_globs() {
  awk '/^packages:/{f=1;next} /^[^[:space:]#-]/{f=0}
       f && /^[[:space:]]*-/{sub(/^[[:space:]]*-[[:space:]]*/,""); gsub(/["'"'"']/,"");
                             sub(/[[:space:]]+$/,""); if ($0 !~ /^!/ && $0 != "") print}' \
    "$1/pnpm-workspace.yaml" 2>/dev/null
}

ws_member() { # root, package dir -> 0 if the root declares that dir a package
  local root="$1" dir="$2" glob d
  while IFS= read -r glob; do
    [ -n "$glob" ] || continue
    for d in "$root"/$glob; do
      [ "$d" = "$dir" ] && return 0
    done
  done < <(ws_globs "$root")
  return 1
}

pm_for() { # workspace lockfile -> package manager the agent would type
  local dir="$1"
  while [ "$dir" != "/" ]; do
    [ -f "$dir/pnpm-lock.yaml" ] && { echo pnpm; return; }
    [ -f "$dir/bun.lock" ] || [ -f "$dir/bun.lockb" ] && { echo bun; return; }
    [ -f "$dir/yarn.lock" ] && { echo yarn; return; }
    [ -f "$dir/package-lock.json" ] && { echo npm; return; }
    dir=$(dirname "$dir")
  done
  echo pnpm
}

> "$SANDBOX/rows"
while IFS= read -r pkg; do
  dir=$(dirname "$pkg")
  pm=$(pm_for "$dir")
  jq -r --arg re "$RUNNER" --arg pm "$pm" --arg dir "$dir" '
      (.name // "") as $pkgname
      | (.scripts // {}) | to_entries[]
      | select(.value | test($re))
      | [$pm, .key, .value, $dir, $pkgname] | @tsv' "$pkg" 2>/dev/null >> "$SANDBOX/rows"
done < <(find "$ROOT" \( -name node_modules -o -name .git -o -name dist -o -name .next -o -name target \) -prune \
  -o -name package.json -print 2>/dev/null)

total=$(wc -l < "$SANDBOX/rows")
# The verdict depends only on (manager, script name, body) — worktrees replicate
# the same script thousands of times, so classify each distinct one once.
holes=0; checked=0; unique=0
while IFS=$'\t' read -r pm name body dir pkgname; do
  [ -n "$name" ] || continue
  unique=$((unique + 1))
  if routes_remote "$dir" "$pm" "$name"; then
    checked=$((checked + 1))
    [ "$VERBOSE" = 1 ] && printf 'REMOTE  %s  %s %s\n' "${dir#"$ROOT"/}" "$pm" "$name"
  else
    holes=$((holes + 1))
    printf 'LOCAL   %s  %s %s\n        body: %s\n' "${dir#"$ROOT"/}" "$pm" "$name" "$body"
  fi
  # Agents and git hooks drive a monorepo from its root (`pnpm --filter web run x`),
  # which resolves the script against a different package.json than `cd`-ing in does.
  [ -n "$pkgname" ] || continue
  wsroot=$(ws_root_for "$dir") || continue
  [ "$wsroot" != "$dir" ] || continue
  ws_member "$wsroot" "$dir" || continue
  case "$pm" in
    pnpm|bun) sel=(--filter "$pkgname") ;;
    npm) sel=(-w "$pkgname") ;;
    *) continue ;;
  esac
  unique=$((unique + 1))
  if routes_remote "$wsroot" "$pm" "${sel[@]}" run "$name"; then
    checked=$((checked + 1))
    [ "$VERBOSE" = 1 ] && printf 'REMOTE  %s  %s %s %s run %s\n' "${wsroot#"$ROOT"/}" "$pm" "${sel[0]}" "$pkgname" "$name"
  else
    holes=$((holes + 1))
    printf 'LOCAL   %s  %s %s %s run %s\n        body: %s\n' "${wsroot#"$ROOT"/}" "$pm" "${sel[0]}" "$pkgname" "$name" "$body"
  fi
done < <(sort -u -t$'\t' -k1,3 "$SANDBOX/rows")

printf '\nheavy scripts=%d distinct=%d routed-remote=%d holes=%d\n' "$total" "$unique" "$checked" "$holes"
[ "$unique" -gt 0 ] || { echo "bb-audit-heavy: no heavy scripts matched — oracle is broken, not clean" >&2; exit 2; }
[ "$holes" -eq 0 ]
