#!/usr/bin/env bash
# R3 memo + R4 dedupe, one HEAD scanner instance, 3 scans, execve traced.
set -uo pipefail
C=/tmp/ev-23690/capture; D=$C/drivers; F=$C/fx-r3
HEADWT=$HOME/wt/pr-23690
echo "## R3/R4 memo + dedupe at HEAD $(git -C $HEADWT rev-parse HEAD)  $(date -u +%FT%TZ)"
rm -rf $F; mkdir -p $F/ws $F/codex $F/claude/projects
cd $F/ws
export GIT_CONFIG_NOSYSTEM=1 HOME=$F
git config --global user.email ev@x; git config --global user.name ev; git config --global init.defaultBranch main
# R3: plain repo whose .git/config is a FIFO
mkdir -p fifo-repo/.git && mkfifo fifo-repo/.git/config
# R4: bare repo with two linked worktrees; then replace its config with a FIFO
git init -q src && git -C src commit -q --allow-empty -m i
git init -q --bare shared.git && git -C src push -q ../shared.git main
git -C shared.git worktree add -q ../wt-a main && git -C shared.git worktree add -q --detach ../wt-b main
cp shared.git/config shared.git/config.real && rm shared.git/config && mkfifo shared.git/config
# normal neighbour
git init -q normal && git -C normal remote add origin https://github.com/acme/normal.git
ls -l fifo-repo/.git/config shared.git/config; cat wt-a/.git wt-b/.git
i=0; for d in fifo-repo wt-a wt-b normal; do i=$((i+1)); mkdir -p $F/claude/projects/p$i
  printf '{"type":"user","cwd":"%s","sessionId":"s%d"}\n{"type":"assistant"}\n' "$F/ws/$d" $i > $F/claude/projects/p$i/a.jsonl; done
cd $HEADWT/apps/server
echo "\$ EV_MARK=1 strace -f -qq -s 300 -e trace=execve -o $C/r3-strace.log node scan.ts $HEADWT ... 3"
EV_MARK=1 strace -f -qq -s 300 -e trace=execve -o $C/r3-strace.log node $D/scan.ts $HEADWT $F/claude $F/codex 3 > $C/r3-head.json
echo "exit=$?"
echo "per-scan results:"; jq -c '.[] | {scan, ms, candidates: [.result.candidates[] | {path: (.path|split("/")|last), git}]}' $C/r3-head.json
echo; echo "cat execs per scan (from strace execve, split on marker execs):"
awk -v fifo="$F/ws/fifo-repo/.git/config" -v shared="$F/ws/shared.git/config" '
  /execve\(.*ev-scan-marker-/ { match($0, /ev-scan-marker-[0-9]+/); scan=substr($0, RSTART+15, RLENGTH-15); next }
  /execve\("\/usr\/bin\/cat", \["cat", "--"/ && scan != "" {
    total[scan]++; if (index($0, fifo)) f[scan]++; if (index($0, shared)) s[scan]++ }
  END { for (i=1;i<=3;i++) printf "scan %d: cat execs=%d  fifo-repo/.git/config=%d  shared.git/config=%d\n", i, total[i], f[i], s[i] }' $C/r3-strace.log
echo; echo "raw cat execve lines:"; grep -E 'ev-scan-marker|execve\("/usr/bin/cat"' $C/r3-strace.log | sed -E 's/^[0-9]+ +//'
echo; echo "cleanup FIFOs by explicit path:"
rm -v $F/ws/fifo-repo/.git/config $F/ws/shared.git/config
