#!/usr/bin/env bash
# SWE-agent ACI command: search_dir <query> [dir]
#
# Routes the classic SWE-agent "search a directory for a string" slot to
# `prism grep <query>` (literal-first, a superset of grep over the working
# tree per spec §9). The bundle is the agent's FRONT DOOR for search, so on
# any prism failure we FAIL OPEN to the real grep — the agent must never lose
# the search capability mid-trajectory (spec §10 Step 4).
#
# Directory scoping: `prism grep` scopes to the git working tree from the CWD,
# so we `cd` into [dir] before invoking it (rather than pass an unsupported
# positional). The real-grep fallback takes the dir explicitly.
#
# No `set -e`: a non-zero prism must fall through to the real tool, not abort.
set -u

query=${1:-}
dir=${2:-.}

# Prefer prism when reachable AND it succeeds; otherwise fall back to grep.
if command -v prism >/dev/null 2>&1; then
  if (cd "$dir" 2>/dev/null && prism grep "$query"); then
    exit 0
  fi
fi

# Fail-open: recursive, line-numbered grep mirrors the classic ACI search_dir.
exec grep -rn -- "$query" "$dir"
