#!/bin/bash
# The inline-send invariant (2026-10-27, after two real sends left Apple Mail unprompted):
# an inline AppleScript send statement ALWAYS produces ask/deny. A file the command merely
# references (read POSIX file "...") can only ADD evidence of a send, never remove it —
# whether or not the file exists, and whatever its path contains.
# Root cause of the silent allow: comments were stripped before string literals, so a `--`
# inside a quoted path (the prospect desk's scratchpad lives under …/-Users-orenmagid--mux-
# worktrees-…) was read as an AppleScript line comment, which swallowed the string's closing
# quote and hid `send m` inside a "string". Also covers the apostrophe-in-subject truncation.
H="${H:-$HOME/.claude/hooks/email-send-gate.sh}"
# Test runs never append to the real gate log: the judge honours EMAIL_GATE_LOG.
if [ -z "${EMAIL_GATE_LOG:-}" ]; then EMAIL_GATE_LOG=$(mktemp /tmp/email-gate-test-log.XXXXXX); _GATE_LOG_TMP=1; fi; export EMAIL_GATE_LOG
pass=0; fail=0
run() { printf '%s' "$1" | "$H"; }
decide() { case "$1" in *'"permissionDecision":"ask"'*) echo ask;; *'"permissionDecision":"deny"'*) echo deny;; *) echo allow;; esac; }
check() { # name expected payload
  local got; got=$(run "$3"); local dec; dec=$(decide "$got")
  if [ "$dec" = "$2" ]; then pass=$((pass+1)); echo "ok    $1 -> $dec"; else fail=$((fail+1)); echo "FAIL  $1 -> $dec (expected $2)"; echo "      $got" | head -c 400; echo; fi
}
check_blocks() { # name payload — ask OR deny both pass; only a silent allow fails
  local got; got=$(run "$2"); local dec; dec=$(decide "$got")
  if [ "$dec" != "allow" ]; then pass=$((pass+1)); echo "ok    $1 -> $dec"; else fail=$((fail+1)); echo "FAIL  $1 -> allow (expected ask or deny)"; fi
}
check_reason_has() { # name needle payload
  local got; got=$(run "$3")
  case "$got" in *"$2"*) pass=$((pass+1)); echo "ok    $1 (reason names: $2)";; *) fail=$((fail+1)); echo "FAIL  $1 — reason lacks: $2"; echo "      $got" | head -c 400; echo;; esac
}

# Fixture: an existing plain-text body file under a path that contains `--`, like the real one.
T=$(mktemp -d /tmp/gate--fixtures.XXXXXX)
trap 'rm -rf "$T"' EXIT
printf 'Hi Derek,\n\nbody text\n' > "$T/derek-king.body.txt"
P=$(mktemp -d /tmp/gate-plain.XXXXXX)
trap 'rm -rf "$T" "$P"' EXIT
printf 'plain path body\n' > "$P/body.txt"

D='"description":"Send email from oren@orenmagid.com to derekking@preservationstudios.com, subject \"An idea about the Part 2 write-up on multi-building jobs\""'
prog() { # $1 = body path → the exact inline program shape that sent unprompted at 10:35 and 10:43
  printf 'osascript -e '"'"'set theBody to read POSIX file \\"%s\\" as «class utf8»\\ntell application \\"Mail\\"\\nset m to make new outgoing message with properties {subject:\\"An idea about the Part 2 write-up on multi-building jobs\\", sender:\\"Oren Magid <oren@orenmagid.com>\\", content:theBody, visible:false}\\ntell m to make new to recipient at end of to recipients with properties {address:\\"derekking@preservationstudios.com\\"}\\nsend m\\nend tell\\nreturn \\"sent\\"'"'"'' "$1"
}

# --- the invariant: the referenced file cannot remove the inline send --------------
check "inline-send+read-posix-file-existing-dashdash-path" ask '{"tool_name":"Bash","cwd":"'"$T"'","tool_input":{'"$D"',"command":"'"$(prog "$T/derek-king.body.txt")"'"}}'
check "inline-send+read-posix-file-missing-dashdash-path" ask '{"tool_name":"Bash","cwd":"'"$T"'","tool_input":{'"$D"',"command":"'"$(prog "$T/nope.body.txt")"'"}}'
check "inline-send+read-posix-file-existing-plain-path" ask '{"tool_name":"Bash","cwd":"'"$P"'","tool_input":{'"$D"',"command":"'"$(prog "$P/body.txt")"'"}}'
check "inline-send+read-posix-file-no-description" deny '{"tool_name":"Bash","cwd":"'"$T"'","tool_input":{"description":"Send the Derek King email","command":"'"$(prog "$T/derek-king.body.txt")"'"}}'
check_reason_has "inline-send+read-posix-file-names-recipient" "derekking@preservationstudios.com" '{"tool_name":"Bash","cwd":"'"$T"'","tool_input":{'"$D"',"command":"'"$(prog "$T/derek-king.body.txt")"'"}}'

# --- comment and string handling that the one-pass scanner must keep right --------
# `--` and `(*` INSIDE a string are text; the send after them still counts.
check "send-after-string-containing-comment-markers" ask '{"tool_name":"Bash","tool_input":{"description":"Send email from oren@orenmagid.com to a@b.com, subject \"re: (* draft -- v2\"","command":"osascript -e '"'"'tell application \"Mail\"\nset m to make new outgoing message with properties {subject:\"re: (* draft -- v2\", sender:\"Oren Magid <oren@orenmagid.com>\"}\nmake new to recipient at end of to recipients of m with properties {address:\"a@b.com\"}\nsend m\nend tell'"'"'"}}'
# A send that only appears in a real comment is still not a send.
check "inline-send-only-in-line-comment" allow '{"tool_name":"Bash","tool_input":{"description":"Save a draft","command":"osascript -e '"'"'tell application \"Mail\"\nset m to make new outgoing message with properties {subject:\"x\", sender:\"Oren Magid <oren@orenmagid.com>\", visible:true}\n-- send m\nsave m\nend tell'"'"'"}}'
check "inline-send-only-in-block-comment" allow '{"tool_name":"Bash","tool_input":{"description":"Save a draft","command":"osascript -e '"'"'tell application \"Mail\"\nset m to make new outgoing message with properties {subject:\"x\", sender:\"Oren Magid <oren@orenmagid.com>\", visible:true}\n(* later:\nsend m\n*)\nsave m\nend tell'"'"'"}}'
# Unterminated string → judged raw → fail closed (ask or deny, never allow).
check_blocks "inline-send-unterminated-string-fails-closed" '{"tool_name":"Bash","tool_input":{"description":"Send email from oren@orenmagid.com to a@b.com, subject \"x\"","command":"osascript -e '"'"'tell application \"Mail\"\nset m to make new outgoing message with properties {subject:\"x, sender:\"Oren Magid <oren@orenmagid.com>\"}\nmake new to recipient at end of to recipients of m with properties {address:\"a@b.com\"}\nsend m\nend tell'"'"'"}}'
# JXA: a `--` inside a string is not a comment there either; a `//` comment is.
check_blocks "jxa-send-with-dashdash-path-in-string" '{"tool_name":"Bash","tool_input":{"description":"Send email from oren@orenmagid.com to a@b.com, subject \"x\"","command":"osascript -l JavaScript -e '"'"'const body = $.NSString.stringWithContentsOfFileEncodingError(\"/tmp/x--y/body.txt\", 4, null).js; const Mail = Application(\"Mail\"); const m = Mail.OutgoingMessage({sender: \"Oren Magid <oren@orenmagid.com>\", subject: \"x\", content: body}); Mail.outgoingMessages.push(m); m.toRecipients.push(Mail.ToRecipient({address: \"a@b.com\"})); Mail.send(m)'"'"'"}}'
check "jxa-send-only-in-line-comment" allow '{"tool_name":"Bash","tool_input":{"description":"count","command":"osascript -l JavaScript -e '"'"'const Mail = Application(\"Mail\"); // later: Mail.send(m)\nMail.inbox.messages.length'"'"'"}}'

# --- apostrophe inside a double-quoted subject is text (peer report, 14:26Z send) ----
A='"description":"Send email from oren@orenmagid.com to a@b.com, subject \"An idea about checking driver'"'"'s license appeal files for consistency\""'
AP='osascript -e '"'"'tell application \"Mail\"\nset m to make new outgoing message with properties {subject:\"An idea about checking driver'"'"'\"'"'"'\"'"'"'s license appeal files for consistency\", sender:\"Oren Magid <oren@orenmagid.com>\"}\nmake new to recipient at end of to recipients of m with properties {address:\"a@b.com\"}\nsend m\nend tell'"'"''
check "apostrophe-subject-still-asks" ask '{"tool_name":"Bash","tool_input":{'"$A"',"command":"'"$AP"'"}}'
check_reason_has "apostrophe-subject-not-truncated" "subject \\\"An idea about checking driver's license appeal files for consistency\\\"" '{"tool_name":"Bash","tool_input":{'"$A"',"command":"'"$AP"'"}}'

echo "passed=$pass failed=$fail"
[ -n "${_GATE_LOG_TMP:-}" ] && rm -f "$EMAIL_GATE_LOG"
[ "$fail" -eq 0 ]
