#!/usr/bin/env bash
# note-command-use.sh  -  UserPromptSubmit hook: count which /multi-agent
# commands are typed, by name only.
#
# A prompt counts when its first token is `/multi-agent:<name>`, or when it is
# `/multi-agent <name>` and <name> is a shipped command. <name> is looked up in
# the shipped command list (lib/usage-names.generated.mjs, SHIPPED_COMMANDS);
# the line appended to <log root>/cmd-calls.log is that shipped name, or the
# constant `other` for a colon-form name that is not on the list. Nothing else
# of the prompt is read past its first two tokens, and nothing else is stored:
# no arguments, no text, no length, no time. The log is folded into
# cmd-counts.json under a lock by note-command-use.mjs when a report is built.
#
# It starts no node process and parses no JSON beyond a depth-aware scan of the
# first 8 KiB of the payload for the top-level `hook_event_name` and `prompt`
# keys (a `prompt` inside any nested object is never read; the depth is kept
# across the lines of a payload that is not on one line). Off, with nothing
# read or written, unless the marker file <log root>/cmd-counting-on exists, is
# not a symlink, and is not older than the preferences file; the marker is
# written with a real parser by note-command-use.mjs (syncCommandSentinel) only
# while usageLog.enabled is true and usageLog.optOut is not, and removed
# otherwise. One short append is atomic, so concurrent prompts need no lock; the
# fold takes the counter lock.
#
# Never blocks the prompt: no output, exit 0 on every path. The log stops
# growing at 1 MiB until the next report folds it.

set -u

PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
MARKER="$DIR/cmd-counting-on"
[ -f "$MARKER" ] || exit 0
[ -L "$MARKER" ] && exit 0
[ -f "$PREFS" ] || exit 0
[ "$PREFS" -nt "$MARKER" ] && exit 0

HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd)" || exit 0
LIST="$HERE/../lib/usage-names.generated.mjs"
[ -f "$LIST" ] || exit 0

HEAD="$(head -c 8192 2>/dev/null)" || exit 0

TOKENS="$(printf '%s' "$HEAD" | awk '
BEGIN { d = 0; st = 0 }
{
  s = $0; n = length(s); i = 1
  while (i <= n) {
    c = substr(s, i, 1)
    if (c == "\"") {
      j = i + 1; str = ""
      while (j <= n) {
        ch = substr(s, j, 1)
        if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
        if (ch == "\"") break
        str = str ch; j++
      }
      if (d == 1) {
        if (st == 0) { key = str; st = 1 }
        else if (st == 2) {
          if (key == "hook_event_name") event = str
          else if (key == "prompt" && !seen) {
            seen = 1
            first = str; rest = ""
            if (match(str, /[ \\]/)) {
              first = substr(str, 1, RSTART - 1)
              if (substr(str, RSTART, 1) == " ") rest = substr(str, RSTART + 1)
            }
            second = rest
            if (match(rest, /[ \\]/)) second = substr(rest, 1, RSTART - 1)
          }
          st = 3
        }
      }
      i = j + 1; continue
    }
    if (c == ":" && d == 1) st = 2
    else if (c == "," && d == 1) st = 0
    else if (c == "{" || c == "[") d++
    else if (c == "}" || c == "]") d--
    i++
  }
}
END { print event; print first; print second }')" || exit 0

{
  IFS= read -r EVENT
  IFS= read -r FIRST
  IFS= read -r SECOND
} <<EOF
$TOKENS
EOF

[ "$EVENT" = "UserPromptSubmit" ] || exit 0

NAME="" COLON=0
case "$FIRST" in
  /multi-agent:*) NAME="${FIRST#/multi-agent:}"; COLON=1 ;;
  /multi-agent) NAME="$SECOND" ;;
  *) exit 0 ;;
esac
printf '%s' "$NAME" | grep -Eq '^[a-z0-9-]{1,40}$' || exit 0

SHIPPED="$(awk -v n="$NAME" '
  /SHIPPED_COMMANDS = / { on = 1; next }
  on && /^\]\)/ { exit }
  on { gsub(/^[ \t]*"|",?[ \t]*$/, ""); if ($0 == n) { print "yes"; exit } }
' "$LIST" 2>/dev/null)"

if [ "$SHIPPED" = "yes" ]; then
  COUNTED="$NAME"
elif [ "$COLON" = "1" ]; then
  COUNTED="other"
else
  exit 0
fi

LOG="$DIR/cmd-calls.log"
( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
[ -L "$LOG" ] && exit 0
if [ -f "$LOG" ]; then
  SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
  [ "${SIZE:-0}" -ge 1048576 ] 2>/dev/null && exit 0
fi
( umask 077; printf '%s\n' "$COUNTED" >> "$LOG" ) 2>/dev/null
exit 0
