diff --git a/bin/backends/herdr.sh b/bin/backends/herdr.sh index 4676462f7aa..73a0612069b 100644 --- a/bin/backends/herdr.sh +++ b/bin/backends/herdr.sh @@ -2322,6 +2322,37 @@ EOF printf 'shell' } +# fm_backend_herdr_pane_owns_session: 0 only when provably runs as +# 's foreground occupant - the pane's own process-info shows a +# shell_pid that is an ancestor-or-self of AND 's process group is +# the pane's foreground process group. This is the herdr equivalent of the +# tmux proof bin/fm-supervision-handoff.sh makes from pane_pid and tpgid: an +# inherited pane id is only ever a hint, and delivery authority comes from the +# process table, never from the pane naming a session. Every read failure, +# malformed field, dead link in the ancestry chain, or disagreement between the +# two records refuses. +fm_backend_herdr_pane_owns_session() { # + local session=$1 pane_id=$2 pid=$3 info shell_pid fg_pgid ancestor pgid + case "$pid" in ''|*[!0-9]*) return 1 ;; esac + info=$(fm_backend_herdr_cli "$session" pane process-info --pane "$pane_id" 2>/dev/null) || return 1 + printf '%s' "$info" | jq -e --arg pane "$pane_id" ' + .result.type == "pane_process_info" + and .result.process_info.pane_id == $pane + ' >/dev/null 2>&1 || return 1 + shell_pid=$(printf '%s' "$info" | jq -er \ + '.result.process_info.shell_pid | select(type == "number" and . > 1) | floor' 2>/dev/null) || return 1 + fg_pgid=$(printf '%s' "$info" | jq -er \ + '.result.process_info.foreground_process_group_id | select(type == "number" and . > 1) | floor' 2>/dev/null) || return 1 + ancestor=$pid + while [ "$ancestor" != 1 ] && [ "$ancestor" != "$shell_pid" ]; do + ancestor=$(ps -o ppid= -p "$ancestor" 2>/dev/null | tr -d ' ') + case "$ancestor" in ''|*[!0-9]*) return 1 ;; esac + done + [ "$ancestor" = "$shell_pid" ] || return 1 + pgid=$(ps -o pgid= -p "$pid" 2>/dev/null | tr -d ' ') || return 1 + [ -n "$pgid" ] && [ "$pgid" = "$fg_pgid" ] +} + # fm_backend_herdr_pane_agent_state: classify in as one of # dead|no-agent|stale-agent|live|unknown, from the JSON body of two read-only # calls plus, for a registered agent, the pane's process-level view - never diff --git a/bin/fm-supervision-handoff.sh b/bin/fm-supervision-handoff.sh index e29b207f7cc..8e49e2d44c6 100755 --- a/bin/fm-supervision-handoff.sh +++ b/bin/fm-supervision-handoff.sh @@ -10,13 +10,19 @@ # host stops it before taking over the arm recorded in .supervision-host-left. # Ack and TERM both leave that verified arm for the next park, not a second arm. # -# Automatic delivery is restricted to the inherited tmux pane on Claude. Its -# pane pid must be an ancestor of the pinned session-lock pid, that session -# must still be in the terminal's foreground group, and its composer must be -# empty with no busy signature. All other endpoints retain the queued wake -# and keep watching but need a normal turn or human message to resume main. -# No terminal text proves acknowledgement. Busy, unknown, or pending input is -# never overwritten. The existing backend submit primitive owns Enter retries. +# Automatic delivery is restricted to the inherited pane on Claude, proven +# through the transport the pane itself declares: TMUX_PANE for tmux, or +# HERDR_ENV+HERDR_PANE_ID+HERDR_SESSION for herdr (a named session's pane, +# including the fm-remote session remote homes run under). On tmux the pane's +# pid must be an ancestor of the pinned session-lock pid and that session must +# still be in the terminal's foreground group; on herdr the pane's own +# process-info must show the same ancestor-or-self and foreground-group facts +# for the pinned pid, and the pane's registered agent identity must be claude. +# In both transports the agent must read idle and the composer must be +# positively empty. All other endpoints retain the queued wake and keep +# watching but need a normal turn or human message to resume main. No terminal +# text proves acknowledgement. Busy, unknown, or pending input is never +# overwritten. The existing backend submit primitive owns Enter retries. # Removing the opt-in, losing the pinned session, or entering daemon-backed # away mode stops retries and leaves the current arm for its next owner. set -u @@ -34,6 +40,19 @@ CONFIG="${FM_CONFIG_OVERRIDE:-$FM_HOME/config}" # shellcheck source=bin/fm-session-lock-lib.sh . "$SCRIPT_DIR/fm-session-lock-lib.sh" fm_backend_source tmux || exit 1 +# Delivery transport: only the pane identity the pane runtime injected is +# trusted, mirroring bin/fm-supervisor-target-lib.sh's discovery order. An +# explicit target variable is deliberately NOT honored - the handoff must +# never deliver to a pane another home or a stray environment configured. +TRANSPORT= +HERDR_TARGET= +if [ -n "${TMUX_PANE:-}" ]; then + TRANSPORT=tmux +elif [ "${HERDR_ENV:-}" = 1 ] && [ -n "${HERDR_PANE_ID:-}" ] && [ -n "${HERDR_SESSION:-}" ]; then + fm_backend_source herdr || exit 1 + TRANSPORT=herdr + HERDR_TARGET="$HERDR_SESSION:$HERDR_PANE_ID" +fi TOKEN=${1:-} PREDECESSOR=${2:-} case "$TOKEN" in ''|*[!A-Za-z0-9._-]*) exit 2 ;; esac @@ -82,25 +101,55 @@ session_owned() { retry_delivery() { local pane_pid ancestor message verdict=deferred tmp pgid tpgid + local target proven=0 agent_out h_session h_pane # No fallback target: a guessed pane can belong to another home. - if [ -n "${TMUX_PANE:-}" ] && session_owned; then - pane_pid=$(tmux display-message -p -t "$TMUX_PANE" '#{pane_pid}' 2>/dev/null) || pane_pid= - ancestor=$SESSION - case "$pane_pid" in ''|*[!0-9]*) ancestor= ;; esac - while [ -n "$ancestor" ] && [ "$ancestor" != 1 ] && [ "$ancestor" != "$pane_pid" ]; do - ancestor=$(ps -o ppid= -p "$ancestor" 2>/dev/null | tr -d ' ') - done - read -r pgid tpgid < <(ps -o pgid=,tpgid= -p "$SESSION" 2>/dev/null) || pgid= - if [ -n "$ancestor" ] && [ "$ancestor" = "$pane_pid" ] \ - && [ -n "$pgid" ] && [ "$pgid" = "$tpgid" ] && [ "$pgid" -gt 0 ] 2>/dev/null \ - && fm_harness_pid_alive "$SESSION" \ - && [ "$(fm_pane_busy_state "$TMUX_PANE" claude 2>/dev/null)" = idle ] \ - && [ "$(fm_backend_composer_state tmux "$TMUX_PANE" 2>/dev/null)" = empty ] \ - && session_owned && [ "$(cat "$PENDING" 2>/dev/null)" = "$TOKEN" ]; then - if fm_operational_record_write "$STATE" watcher \ - 'check: supervision-handoff - the host hand-back is still unacknowledged. Run bin/fm-wake-drain.sh, handle its queued work, and run its exact WAKE_ACK_REQUIRED command. This is automatic supervision, not a captain return.' message; then - verdict=$(fm_backend_send_text_submit tmux "$TMUX_PANE" "$message" 2 0.2 0.2 2>/dev/null) || verdict=unconfirmed - fi + if session_owned; then + case "$TRANSPORT" in + tmux) + target=$TMUX_PANE + pane_pid=$(tmux display-message -p -t "$TMUX_PANE" '#{pane_pid}' 2>/dev/null) || pane_pid= + ancestor=$SESSION + case "$pane_pid" in ''|*[!0-9]*) ancestor= ;; esac + while [ -n "$ancestor" ] && [ "$ancestor" != 1 ] && [ "$ancestor" != "$pane_pid" ]; do + ancestor=$(ps -o ppid= -p "$ancestor" 2>/dev/null | tr -d ' ') + done + read -r pgid tpgid < <(ps -o pgid=,tpgid= -p "$SESSION" 2>/dev/null) || pgid= + if [ -n "$ancestor" ] && [ "$ancestor" = "$pane_pid" ] \ + && [ -n "$pgid" ] && [ "$pgid" = "$tpgid" ] && [ "$pgid" -gt 0 ] 2>/dev/null \ + && fm_harness_pid_alive "$SESSION" \ + && [ "$(fm_pane_busy_state "$TMUX_PANE" claude 2>/dev/null)" = idle ] \ + && [ "$(fm_backend_composer_state tmux "$TMUX_PANE" 2>/dev/null)" = empty ]; then + proven=1 + fi + ;; + herdr) + target=$HERDR_TARGET + if fm_backend_herdr_parse_target "$target" \ + && [ "$(fm_backend_herdr_server_running_state "$FM_BACKEND_HERDR_SESSION")" = running ]; then + h_session=$FM_BACKEND_HERDR_SESSION + h_pane=$FM_BACKEND_HERDR_PANE + # One read carries both halves of the registered-identity proof: the + # pane's agent must be claude, and any session binding it carries + # must be claude's own - a foreign label or binding never delivers. + agent_out=$(fm_backend_herdr_cli "$h_session" agent get "$h_pane" 2>/dev/null) || agent_out= + if fm_backend_herdr_pane_owns_session "$h_session" "$h_pane" "$SESSION" \ + && [ "$(printf '%s' "$agent_out" | jq -r '.result.agent.agent // empty' 2>/dev/null)" = claude ] \ + && printf '%s' "$agent_out" | jq -er '(.result.agent.agent_session.agent // "claude") == "claude"' >/dev/null 2>&1 \ + && fm_harness_pid_alive "$SESSION" \ + && [ "$(fm_backend_herdr_busy_state "$target" 2>/dev/null)" = idle ] \ + && [ "$(fm_backend_herdr_rendered_busy_state "$target" claude 2>/dev/null)" = idle ] \ + && [ "$(fm_backend_composer_state herdr "$target" 2>/dev/null)" = empty ]; then + proven=1 + fi + fi + ;; + esac + fi + if [ "$proven" -eq 1 ] \ + && session_owned && [ "$(cat "$PENDING" 2>/dev/null)" = "$TOKEN" ]; then + if fm_operational_record_write "$STATE" watcher \ + 'check: supervision-handoff - the host hand-back is still unacknowledged. Run bin/fm-wake-drain.sh, handle its queued work, and run its exact WAKE_ACK_REQUIRED command. This is automatic supervision, not a captain return.' message; then + verdict=$(fm_backend_send_text_submit "$TRANSPORT" "$target" "$message" 2 0.2 0.2 2>/dev/null) || verdict=unconfirmed fi fi printf '%s\tretry\t%s\t%s\n' "$(date +%s)" "$TOKEN" "$verdict" >> "$LOG" diff --git a/docs/supervision-host.md b/docs/supervision-host.md index c449edc3b53..618a7c197b5 100644 --- a/docs/supervision-host.md +++ b/docs/supervision-host.md @@ -247,16 +247,17 @@ The helper's header owns the records, retry interval, process cleanup, and trans The first delivery remains the Stop hook's exit-2 feedback. A later retry does not depend on that hook or on another Stop firing. -The detached owner writes a durable operational-input record and submits its watcher doorbell through the existing tmux submit primitive. -It uses only the inherited pane, proves that pane's process contains the pinned session owner, and requires an idle agent with an empty composer. +The detached owner writes a durable operational-input record and submits its watcher doorbell through the backend's existing submit primitive: the tmux pane the session inherited as `TMUX_PANE`, else the herdr pane the environment itself names through `HERDR_ENV`, `HERDR_SESSION`, and `HERDR_PANE_ID`. +On herdr that identity comes only from the injected environment, so a remote home's `fm-remote` session hands its scripts the same path and remote homes need no extra plumbing. +It uses only the inherited pane, proves the pinned session owner lives in that pane's foreground process tree, and requires an idle agent with an empty composer. +On herdr the pane's registered agent and any registered session binding must also identify `claude`, and idle must hold in both the native agent state and the rendered footer, because a live Claude turn can leave the native status reading idle. Busy, unreadable, foreign, and partially typed panes defer delivery without changing the queued check. The default retry interval is five minutes, and successful submission still does not acknowledge the hand-back. -Automatic retries currently reach Claude only through that verified tmux pane. -A primary outside tmux, an unavailable pane, or a blocked composer keeps its watcher and queued work but needs another normal turn or a human message. +Automatic retries currently reach Claude only through that verified tmux or herdr pane. +A primary outside both, an unavailable pane, or a blocked composer keeps its watcher and queued work but needs another normal turn or a human message. A failed watcher restart or a terminated retry owner is not a guarantee of continued supervision. -The portable tests prove the process hand-off and transport guards, not a real Claude session accepting the retried input. -No new live-harness verification is claimed. +[verification/supervision.md](verification/supervision.md#supervision-host) owns the dated live results and verification entry points for both transports. All other primaries and the host-off Stop path retain their existing behavior. ## Failure direction @@ -467,6 +468,7 @@ Each arm owner's own suite covers its host mode against a stub host. | `tests/fm-afk-return.test.sh` | The return's drain-owned read-cursor advance through the away window on a host home, and none on Pi. | | `tests/fm-supervision-host-live-e2e.test.sh` | Runs a real engine turn; opt-in because it spends tokens. | | `tests/fm-supervision-host-attended-live-e2e.test.sh` | Opt-in credentialed guard for repeated attended main-only hand-backs to an idle Claude primary, the successor's own close, a close that turns main-only at its turn, and a stand-in remote listener; accepts a pre-fix ref for a negative control. | +| `tests/fm-supervision-host-herdr-live-e2e.test.sh` | Opt-in credentialed guard that a real Claude primary in an isolated herdr session loses its hand-back continuation, receives the detached retry through the inherited pane, drains, and acknowledges, with one watcher retained. | | `tests/fm-host-mirror-live-e2e.test.sh` | Proves the Claude and Cursor mirror writers against the real harnesses; opt-in because it spends tokens. | [verification/supervision.md](verification/supervision.md#supervision-host) records the dated live results. diff --git a/docs/verification/supervision.md b/docs/verification/supervision.md index e9af03d96ec..507ed830321 100644 --- a/docs/verification/supervision.md +++ b/docs/verification/supervision.md @@ -970,6 +970,35 @@ tests/fm-afk-return.test.sh tests/fm-branch-supervision.test.sh ``` +### Acknowledged hand-back retry over herdr, 2026-11-09 + +This supports [Reaching a lost Claude continuation](../supervision-host.md#reaching-a-lost-claude-continuation): the detached hand-back retry delivers to a Claude primary running in herdr through the inherited `HERDR_SESSION`/`HERDR_PANE_ID` pane identity, with the same ownership, idle, and composer guards as the verified tmux pane. +It was measured on 2026-11-09 on macOS arm64 with Claude Code 2.1.321 (model `haiku`) in an isolated `fm-lab-*` herdr session; the default and `fm-remote` sessions were not touched. + +```text +$ FM_SUPERVISION_HOST_HERDR_LIVE_E2E=1 tests/fm-supervision-host-herdr-live-e2e.test.sh +# step 3: no Stop-hook rewake reached the transcript; owner 87432 alive on watcher 87805; pending host-83156-1794258417 unchanged +# step 4: retry confirmed delivery - handoff log: 1794258429 retry host-83156-1794258417 empty +# step 5: pending marker removed only after the acknowledgement +# step 6: turn end re-armed: 1794258437 start gen=host-6155-1794258437; watcher 87805 under host 6155 +ok - herdr live e2e: a lost Claude hand-back is recovered by the detached retry, acknowledged, and supervision retained +``` + +| Case | Observed | +| --- | --- | +| Lost continuation | superseding the owning Stop hook's generation made it exit 0 with no exit-2, no banner, and no failure notice; the transcript shows no `firstmate watcher wake` between the hand-back and the doorbell | +| Detached owner | stayed alive on the same pending token and kept a verified watcher | +| Retry delivery | `retry empty` in `.supervision-handoff.log`; the operational doorbell reached the inherited pane as a primary message | +| Acknowledgement | the primary ran `bin/fm-wake-drain.sh` then `--ack-through 3 --recovery-generation `; the pending marker disappeared only after the ack | +| After the acknowledged turn | the next Stop claimed a new generation, parked a host, and took over the detached owner's arm - one watcher retained | + +Deterministic entry points: + +```sh +tests/fm-supervision-host-hook.test.sh +tests/fm-backend-herdr.test.sh +``` + ## Wedge-alarm channels The two real notification channels were bounded manually on 2026-07-10 on macOS 26.5.2 with Herdr 0.7.3. diff --git a/docs/watcher-continuity.md b/docs/watcher-continuity.md index 1bfee468e95..d02ae4d7718 100644 --- a/docs/watcher-continuity.md +++ b/docs/watcher-continuity.md @@ -587,7 +587,7 @@ OpenCode support targets persistent TUI sessions rather than headless `opencode The other harnesses rely on these mechanisms: - Claude normally depends on the [auto-arm hook's rewake](#claude-stop-hook). - The host's opt-in [acknowledged hand-back](supervision-host.md#acknowledged-hand-back) adds guarded tmux retries when that continuation is lost. + The host's opt-in [acknowledged hand-back](supervision-host.md#acknowledged-hand-back) owns guarded retries when that continuation is lost. - Cursor depends on its awaited stop-hook park. - Grok retains native background-completion notifications. - Codex retains bounded foreground checkpoints unless the home opts in to its [native Stop park](supervision-protocols/codex.md). diff --git a/tests/fm-backend-herdr.test.sh b/tests/fm-backend-herdr.test.sh index 7b21551310d..773457140b2 100755 --- a/tests/fm-backend-herdr.test.sh +++ b/tests/fm-backend-herdr.test.sh @@ -607,6 +607,55 @@ test_registered_agent_with_a_live_foreground_process_stays_alive() { pass "herdr stale registration: a registered agent with a live Pi foreground process still reads alive" } +# --- the foreground-occupant session proof ---------------------------------- +# +# fm_backend_herdr_pane_owns_session is the herdr equivalent of the tmux +# pane_pid ancestor + tpgid proof the hand-back retry makes before delivery: +# the pane's own process-info must name a shell pid that is an ancestor-or-self +# of the pinned pid AND that pid's process group must be the pane's foreground +# group. The canned `pane process-info` body is paired with a real child +# process so the ancestry walk and pgid read run against the real process +# table, and every foreign, malformed, or unreadable half refuses. + +owns_session_process_info() { # + printf '{"result":{"type":"pane_process_info","process_info":{"pane_id":"w1:p2","shell_pid":%s,"foreground_process_group_id":%s,"foreground_processes":[]}}}' "$1" "$2" +} + +owns_session_case() { # [process-info-exit] + local dir resp log fb + dir=$(mktemp -d "$TMP_ROOT/owns-session.XXXXXX") + mkdir -p "$dir/responses"; resp="$dir/responses"; log="$dir/log"; : > "$log" + [ "$1" = - ] || printf '%s\n' "$1" > "$resp/1.out" + [ -z "${3:-}" ] || printf '%s\n' "$3" > "$resp/1.exit" + fb=$(make_herdr_fakebin "$dir") + PATH="$fb:$PATH" FM_HERDR_LOG="$log" FM_HERDR_RESPONSES="$resp" \ + bash -c '. "$0/bin/backends/herdr.sh"; fm_backend_herdr_pane_owns_session fmtest w1:p2 "$1"' "$ROOT" "$2" +} + +test_pane_owns_session_proves_the_foreground_occupant() { + local sleep_bin pid pgid + sleep_bin=$(command -v sleep) || fail "sleep not found" + "$sleep_bin" 300 & + pid=$! + pgid=$(ps -o pgid= -p "$pid" | tr -d ' ') + # shell_pid = the suite's own pid $$ - a real ancestor of the child. + owns_session_case "$(owns_session_process_info "$$" "$pgid")" "$pid" \ + || { kill "$pid" 2>/dev/null; fail "a real ancestor shell pid plus a matching foreground group must prove ownership"; } + # shell_pid = the pinned pid itself - the pane's top process IS the session. + owns_session_case "$(owns_session_process_info "$pid" "$pgid")" "$pid" \ + || { kill "$pid" 2>/dev/null; fail "a pane whose top process is the session must prove ownership"; } + if owns_session_case "$(owns_session_process_info 999999 "$pgid")" "$pid" \ + || owns_session_case "$(owns_session_process_info "$$" 999999)" "$pid" \ + || owns_session_case - "$pid" 1 \ + || owns_session_case "$(owns_session_process_info 1 "$pgid")" "$pid" \ + || owns_session_case "$(owns_session_process_info "$$" "$pgid")" not-a-pid; then + kill "$pid" 2>/dev/null + fail "a foreign shell pid, foreign foreground group, unreadable read, invalid shell pid, or invalid pid must all refuse" + fi + kill "$pid" 2>/dev/null || true + pass "herdr pane owns session: the foreground-occupant proof accepts only the real ancestry plus foreground group" +} + # --- the bound agent session reference (relaunch session continuity) -------- # # Herdr applies only reports carrying the session identity it bound to a pane, @@ -6500,6 +6549,7 @@ test_stale_registration_ignores_status_and_reads_the_process test_pane_agent_session_ref_reports_a_resumable_reference_with_its_agent test_pane_agent_session_ref_degrades_to_nothing_when_not_resumable test_registered_agent_with_a_live_foreground_process_stays_alive +test_pane_owns_session_proves_the_foreground_occupant test_registered_agent_with_a_non_shell_foreground_process_stays_alive test_transient_prompt_helper_settles_into_stale_agent test_exhausted_settle_window_keeps_a_non_shell_foreground_live diff --git a/tests/fm-supervision-host-herdr-live-e2e.test.sh b/tests/fm-supervision-host-herdr-live-e2e.test.sh new file mode 100755 index 00000000000..b1d9089fbcd --- /dev/null +++ b/tests/fm-supervision-host-herdr-live-e2e.test.sh @@ -0,0 +1,465 @@ +#!/usr/bin/env bash +# Opt-in credentialed live guard for the acknowledged hand-back's detached +# retry reaching a real Claude primary running in an isolated Herdr lab +# session (bin/fm-supervision-handoff.sh's herdr transport, +# bin/fm-supervision-host.sh "Acknowledged hand-back"). +# +# Proves against the real installed Claude Code and a real Herdr server, in an +# isolated lab copy of this checkout opted into both the supervision host and +# config/supervision-handoff-ack (never a live fleet home and never the live +# fm-remote or default session), that when the Stop hook's exit-2 continuation +# is lost: +# 1. the host still records .supervision-handoff-pending, queues the +# token-bound check, and verifies a detached hand-off owner holding a +# replacement watcher; +# 2. no "firstmate watcher wake" banner reaches the primary's transcript; +# 3. the owner's retry delivers the record-backed doorbell into the primary's +# own inherited pane (target "$HERDR_SESSION:$HERDR_PANE_ID" - the exact +# form remote homes running under fm-remote inherit); +# 4. the primary reads the record, drains, and runs the sequence-bound +# acknowledgement, and only that acknowledgement removes the pending +# marker; submission alone never did; +# 5. the owner exits, leaving its verified arm for the next park to adopt. +# Every deferral guarantee stays a fixture concern +# (tests/fm-supervision-host-hook.test.sh); this guard proves the delivered +# case end to end. Evidence lines start with "# ". +# +# FM_SUPERVISION_HOST_HERDR_LIVE_E2E=1 tests/fm-supervision-host-herdr-live-e2e.test.sh +# +# FM_SUPERVISION_HOST_HERDR_LIVE_MODEL (default haiku) picks the primary's +# model. Claude keeps its existing managed authentication; the lab path gets a +# project transcript directory in Claude's own store. +# FM_HERDR_LAB_FLEET_SESSION names the live fleet session the lab tripwire +# protects (default: the helper's own default); when this test is launched +# inside a pane, the pane's inherited HERDR_SESSION supplies it. +# shellcheck disable=SC2016 # single-quoted scripts expand inside their own shells +set -u + +# shellcheck source=tests/lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +# shellcheck source=tests/herdr-test-safety.sh +. "$ROOT/tests/herdr-test-safety.sh" + +FLEET_SESSION=${FM_HERDR_LAB_FLEET_SESSION:-${HERDR_SESSION:-}} +herdr_forget_inherited_pane +fm_live_gate opt-in FM_SUPERVISION_HOST_HERDR_LIVE_E2E claude herdr jq node perl git + +HERDR_LAB_HELPER=${HERDR_LAB_HELPER:-$ROOT/bin/fm-herdr-lab.sh} +[ -x "$HERDR_LAB_HELPER" ] || { echo "skip: live: Herdr lab helper not executable at $HERDR_LAB_HELPER"; exit 0; } +[ -n "$FLEET_SESSION" ] && export FM_HERDR_LAB_FLEET_SESSION=$FLEET_SESSION + +CLAUDE_VERSION=$(claude --version 2>/dev/null | head -n 1) +MODEL=${FM_SUPERVISION_HOST_HERDR_LIVE_MODEL:-haiku} +LAB=$(fm_test_tmproot fm-sh-herdr-live) +LAB=$(cd -P "$LAB" && pwd -P) +PROJECTS="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects" +TURN_POLLS=${FM_SUPERVISION_HOST_HERDR_LIVE_POLLS:-1800} +HERDR_ORIGINAL_PATH=$PATH +HERDR_LAB_SESSION=$("$HERDR_LAB_HELPER" name fm-sh-herdr-retry) \ + || fail "could not mint a lab session name" +export HERDR_LAB_SESSION +unset FM_HOME FM_ROOT_OVERRIDE FM_STATE_OVERRIDE FM_CONFIG_OVERRIDE FM_DATA_OVERRIDE TMUX TMUX_PANE PI_CODING_AGENT NO_MISTAKES_GATE +# Claude Code keeps no transcript for a session that inherits another session's +# markers, so the lab primary starts without the invoking session's. +while IFS= read -r name; do + unset "$name" +done < <(env | grep -E '^(CLAUDECODE|CLAUDE_CODE_[A-Z_]+|CLAUDE_PID|CLAUDE_EFFORT)=' | cut -d= -f1 | sort -u) + +evidence() { printf '# %s %s\n' "$(date '+%H:%M:%S')" "$*"; } + +stop_lab() { # + local lab=$1 fm=$1/fm pid + for pid in \ + "$(cut -f1 "$fm/state/.supervision-handoff-owner" 2>/dev/null)" \ + "$(awk -F '\t' '$1 == "host" { print $2; exit }' "$fm/state/.supervision-host" 2>/dev/null)" \ + "$(cat "$fm/state/.watch.lock/pid" 2>/dev/null)"; do + [ -z "$pid" ] || kill -TERM "$pid" 2>/dev/null || true + done + FM_HOME="$fm" FM_PROCEVENT_CLAIM_ROOT="$lab/claims" "$fm/bin/fm-procevent.sh" sweep-home >/dev/null 2>&1 || true + rm -rf "${PROJECTS:?}/$(printf '%s' "$fm" | sed 's/[^A-Za-z0-9]/-/g')" +} +cleanup() { + local status=$? lab + for lab in "$LAB"/*/; do + [ -d "$lab/fm" ] && stop_lab "${lab%/}" + done + env PATH="$HERDR_ORIGINAL_PATH" "$HERDR_LAB_HELPER" teardown "$HERDR_LAB_SESSION" || status=1 + fm_test_cleanup + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'exit 129' HUP + +# Non-lifecycle Herdr calls go through the helper so every one carries +# --session . The fakebin herdr lets backend functions under test use +# their ordinary ambient binary while the helper still owns isolation. +FAKEBIN=$LAB/fakebin +mkdir -p "$FAKEBIN" +cat > "$FAKEBIN/herdr" <:" target. +backend() { + PATH="$FAKEBIN:$HERDR_ORIGINAL_PATH" bash -c ' + set -u + . "$1/bin/backends/herdr.sh" + shift + "$@" + ' _ "$ROOT" "$@" +} + +wait_until() { # + local limit=$1 i=0 + shift + while [ "$i" -lt "$limit" ]; do + "$@" && return 0 + sleep 0.1 + i=$((i + 1)) + done + return 1 +} + +# --- one lab ------------------------------------------------------------------ + +make_lab() { # + local lab="$LAB/$1" fm + fm="$lab/fm" + mkdir -p "$fm" "$lab/bin" "$lab/claims" + git -C "$ROOT" ls-files -z -co --exclude-standard \ + | (cd "$ROOT" && tar --null -T - -cf -) | (cd "$fm" && tar -xf -) + git -C "$fm" init -q -b main + git -C "$fm" add -A >/dev/null + git -C "$fm" -c user.name=fmtest -c user.email=fmtest@example.invalid commit -q -m lab + mkdir -p "$fm/state" "$fm/config" "$fm/data" + : > "$fm/config/supervision-host" + : > "$fm/config/supervision-handoff-ack" + printf 'project=demo\nwindow=fm-demo\nharness=claude\n' > "$fm/state/demo.meta" + : > "$fm/state/demo.status" + # Unreachable tmux and ssh: no endpoint read succeeds, so the only wakes are + # the events this guard appends. herdr is deliberately NOT stubbed - the + # owner must reach the real lab session's server. + printf '#!/usr/bin/env bash\nexit 1\n' > "$lab/bin/tmux" + printf '#!/usr/bin/env bash\nexit 255\n' > "$lab/bin/ssh" + chmod +x "$lab/bin/tmux" "$lab/bin/ssh" + cat > "$lab/env" < "$lab/launch.sh" < "\$FM_HOME/state/.lock" +exec claude --model $MODEL --effort low --dangerously-skip-permissions +ENV + chmod +x "$lab/launch.sh" + printf '%s\n' "$lab" +} + +# Claude's own project transcript for the lab checkout. +transcript() { # + local dir + dir="$PROJECTS/$(printf '%s' "$1/fm" | sed 's/[^A-Za-z0-9]/-/g')" + find "$dir" -maxdepth 1 -name '*.jsonl' -print 2>/dev/null | head -n 1 +} +# Epochs of rewake deliveries (Claude's queued "Stop hook feedback") at or after . +rewakes_since() { # + local t + t=$(transcript "$1") + [ -n "$t" ] || return 0 + jq -r --argjson since "$2" ' + select(.type == "queue-operation" and .operation == "enqueue") + | select((.content // "" | tostring) | contains("firstmate watcher wake")) + | (.timestamp | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) as $at + | select($at >= $since) | $at' "$t" 2>/dev/null +} +# Epochs of user messages carrying the record-backed operational doorbell. +doorbells_since() { # + local t + t=$(transcript "$1") + [ -n "$t" ] || return 0 + jq -r --argjson since "$2" ' + select(.type == "user") + | select((.message.content // "" | tostring) | contains("Firstmate operational input waiting")) + | (.timestamp | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) as $at + | select($at >= $since) | $at' "$t" 2>/dev/null +} +# Bash commands the primary ran at or after . +commands_since() { # + local t + t=$(transcript "$1") + [ -n "$t" ] || return 0 + jq -r --argjson since "$2" ' + select(.type == "assistant") + | (.timestamp | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) as $at + | select($at >= $since) + | .message.content[]? | select(.type == "tool_use" and .name == "Bash") | .input.command' "$t" 2>/dev/null +} +drained_since() { commands_since "$1" "$2" | grep -q 'fm-wake-drain\.sh'; } +acked_since() { commands_since "$1" "$2" | grep -q 'fm-wake-drain\.sh --ack-through [0-9]* --recovery-generation'; } +turn_idle() { # : a turn ended at or after the epoch + local t + t=$(transcript "$1") + [ -n "$t" ] || return 1 + jq -e --argjson since "$2" ' + select(.type == "system" and .subtype == "turn_duration") + | select((.timestamp | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) >= $since)' "$t" >/dev/null 2>&1 +} +host_log_since() { # + awk -F '\t' -v t="$2" '$1 >= t' "$1/fm/state/.supervision-host.log" 2>/dev/null | grep -E -- "$3" +} +host_live() { + local pid + pid=$(awk -F '\t' '$1 == "host" { print $2; exit }' "$1/fm/state/.supervision-host" 2>/dev/null) + [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null +} +watcher_pid() { cat "$1/fm/state/.watch.lock/pid" 2>/dev/null; } +watcher_live() { local pid; pid=$(watcher_pid "$1") && [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; } +ledger() { head -n 1 "$1/fm/state/.claude-autoarm-epoch" 2>/dev/null; } +marker() { cat "$1/fm/state/.watcher-down" 2>/dev/null; } +hook_pid() { # : the auto-arm generation's recorded owner pid + sed -n '1s/.*owner_pid=\([0-9][0-9]*\).*/\1/p' "$1/fm/state/.claude-autoarm-epoch" 2>/dev/null +} +handoff_owner_pid() { cut -f1 "$1/fm/state/.supervision-handoff-owner" 2>/dev/null; } +pending_token() { cat "$1/fm/state/.supervision-handoff-pending" 2>/dev/null; } +diagnose() { # + local pane + pane=$(cat "$1/pane-id" 2>/dev/null) + printf -- '--- host log\n%s\n--- handoff log\n%s\n--- cycle exits\n%s\n--- queue\n%s\n--- ledger: %s\n--- marker: %s\n--- screen\n%s\n' \ + "$(tail -n 8 "$1/fm/state/.supervision-host.log" 2>/dev/null)" \ + "$(tail -n 8 "$1/fm/state/.supervision-handoff.log" 2>/dev/null)" \ + "$(tail -n 4 "$1/fm/state/.watch-cycle-exits.log" 2>/dev/null | cut -f1-8)" \ + "$(cat "$1/fm/state/.wake-queue" 2>/dev/null)" "$(ledger "$1")" "$(marker "$1")" \ + "$([ -n "$pane" ] && lab pane read "$pane" --source visible 2>/dev/null | tail -n 25)" +} +# A .supervision-handoff.log retry row for carrying a confirmed +# delivery verdict (empty = composer proved clear after Enter; queued-enter = +# Enter confirmed queued behind a generating turn). +retry_confirmed() { # + awk -F '\t' -v t="$2" '$2 == "retry" && $3 == t && ($4 == "empty" || $4 == "queued-enter") { found=1 } END { exit !found }' \ + "$1/fm/state/.supervision-handoff.log" 2>/dev/null +} +doorbell_seen() { [ -n "$(doorbells_since "$1" "$2")" ]; } +pending_gone() { [ ! -e "$1/fm/state/.supervision-handoff-pending" ]; } +pid_dead() { ! kill -0 "$1" 2>/dev/null; } + +# Answer one first-run dialog by moving its cursor to