Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions bin/fm-push-transition-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,36 @@ triage_log() {
fi
}

DELIVERY_RECEIPT="$STATE/.watch-cycle-delivery"

# Publish the identity-bound receipt for this cycle's delivered wake.
# An ATTACHED arm never sees this stdout - the reason goes to the arm that owns
# this watcher as its child - so without a receipt it can only observe the lock
# disappearing and would classify a successful delivering close as an
# unexplained cycle end. bin/fm-watch-arm.sh is the only reader; it requires the
# recorded pid, identity, and timestamp to match the cycle it was attached to,
# so a stale or foreign receipt can never excuse a genuinely failed cycle.
publish_delivery_receipt() { # <reason>
local pid tmp
pid=${BASHPID:-$$}
tmp="$DELIVERY_RECEIPT.tmp.$pid"
printf 'watcher_pid=%s\tidentity=%s\tdelivered_at=%s\treason=%s\n' \
"$pid" \
"$(fm_pid_identity "$pid" 2>/dev/null || true)" \
"$(date +%s)" \
"$(printf '%s' "$1" | tr '\t\r\n' ' ')" \
> "$tmp" 2>/dev/null \
&& mv -f "$tmp" "$DELIVERY_RECEIPT" 2>/dev/null
rm -f "$tmp" 2>/dev/null || true
}

# Exit after reporting one actionable wake. Tests override this callback.
wake() {
case "$1" in
heartbeat*) echo $(( $(cat "$STATE/.heartbeat-streak" 2>/dev/null || echo 0) + 1 )) > "$STATE/.heartbeat-streak" ;;
*) echo 0 > "$STATE/.heartbeat-streak" ;;
esac
publish_delivery_receipt "$1"
echo "$1"
exit 0
}
Expand Down
76 changes: 68 additions & 8 deletions bin/fm-session-lock-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,83 @@
# Known harness command names; extend when a new adapter is verified.
FM_HARNESS_RE='claude|codex|opencode|grok|kimi|^pi$'

# Read one process's parent, command name, and full argument string into
# FM_ROW_PPID / FM_ROW_COMM / FM_ROW_ARGS. Returns 1 when the pid is gone or
# unreadable.
#
# Prefer /proc, which needs no fork at all; the ps snapshot is the portable
# fallback for hosts without a Linux-format /proc (macOS). The snapshot is taken
# at most once per shell because a single ps costs about half a second on a
# loaded machine.
FM_ROW_PPID=
FM_ROW_COMM=
FM_ROW_ARGS=
FM_PROCESS_SNAPSHOT=
fm_process_row() { # <pid>
local pid=$1 proc_root stat_line rest arg row_pid found
FM_ROW_PPID=; FM_ROW_COMM=; FM_ROW_ARGS=
proc_root=${FM_PROC_ROOT_OVERRIDE:-/proc}
if [ -r "$proc_root/$pid/stat" ]; then
IFS= read -r stat_line < "$proc_root/$pid/stat" 2>/dev/null || return 1
# "<pid> (<comm>) <state> <ppid> ...", where comm may contain spaces and
# parentheses: take it between the first "(" and the LAST ")".
FM_ROW_COMM=${stat_line#*(}
FM_ROW_COMM=${FM_ROW_COMM%)*}
rest=${stat_line##*)}
# After the comm delimiter the fields are "<state> <ppid> ...".
read -r _ FM_ROW_PPID _ <<< "$rest"
case "$FM_ROW_PPID" in
''|*[!0-9]*) FM_ROW_PPID=; FM_ROW_COMM=; return 1 ;;
esac
if [ -r "$proc_root/$pid/cmdline" ]; then
while IFS= read -r -d '' arg; do
FM_ROW_ARGS="$FM_ROW_ARGS $arg"
done < "$proc_root/$pid/cmdline"
fi
return 0
fi
if [ -z "$FM_PROCESS_SNAPSHOT" ]; then
FM_PROCESS_SNAPSHOT=$(ps -A -o pid= -o ppid= -o comm= -o args= 2>/dev/null) || return 1
[ -n "$FM_PROCESS_SNAPSHOT" ] || return 1
fi
found=0
while read -r row_pid FM_ROW_PPID FM_ROW_COMM FM_ROW_ARGS; do
[ "$row_pid" = "$pid" ] || continue
found=1
break
done <<EOF
$FM_PROCESS_SNAPSHOT
EOF
[ "$found" -eq 1 ] || { FM_ROW_PPID=; FM_ROW_COMM=; FM_ROW_ARGS=; return 1; }
return 0
}

# Walk the current process ancestry (up to 8 hops) and print the first pid whose
# command looks like a verified harness. The harness pid lives as long as the
# session, unlike the transient subshell pid of any one tool call.
#
# One process-table snapshot, then a fork-free walk. Latency is load-bearing:
# bin/fm-claude-stop-autoarm.sh resolves ancestry before it may claim a home,
# and bin/fm-turnend-guard.sh --claude allows a stop only if that claim lands
# inside FM_CLAUDE_AUTOARM_SYNC_WAIT_MS. Per-hop ps/basename/grep forks put the
# walk at 2.5-3.3s on a loaded machine (measured 2026-07-27), far past that
# window, so the guard blocked turns whose auto-arm was working normally.
fm_harness_ancestry_pid() {
local pid=$$ comm args
local pid=$$
for _ in 1 2 3 4 5 6 7 8; do
comm=$(ps -o comm= -p "$pid" 2>/dev/null) || return 1
args=$(ps -o args= -p "$pid" 2>/dev/null)
if printf '%s' "$(basename "$comm")" | grep -qE "$FM_HARNESS_RE"; then
fm_process_row "$pid" || return 1
if [[ ${FM_ROW_COMM##*/} =~ $FM_HARNESS_RE ]]; then
echo "$pid"; return 0
fi
# Bare interpreter (e.g. node): match the harness name in its script path.
case "$comm" in
*node*|*python*) printf '%s' "$args" | grep -qE "$FM_HARNESS_RE" && { echo "$pid"; return 0; } ;;
case "$FM_ROW_COMM" in
*node*|*python*) [[ $FM_ROW_ARGS =~ $FM_HARNESS_RE ]] && { echo "$pid"; return 0; } ;;
esac
pid=$FM_ROW_PPID
case "$pid" in
''|*[!0-9]*) return 1 ;;
esac
pid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
[ -n "$pid" ] && [ "$pid" -gt 1 ] || return 1
[ "$pid" -gt 1 ] || return 1
done
return 1
}
Expand Down
76 changes: 70 additions & 6 deletions bin/fm-watch-arm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@
# watcher: started pid=<N> (beacon fresh) - it launched one and confirmed it
# watcher: attached pid=<N> (beacon <age>s) - a live+fresh successor holds the lock;
# this arm attaches and follows it
# watcher: closed pid=<N> (wake delivered by its owning arm)
# - an attached cycle closed after its
# watcher delivered a wake; the reason
# line follows and this arm exits 0
# watcher: FAILED - no live watcher with a fresh beacon - could not confirm one
# watcher: FAILED - cycle ended without an actionable reason
# - a clean cycle ended with no wake and no
Expand All @@ -37,10 +41,11 @@
# dead lock per the singleton self-eviction/steal path and is confirmed) or this
# returns the FAILED line. On started it waits the child and propagates the wake
# reason; on attached it stays live across identity-matched successors. An
# attached cycle that ends without a healthy successor is a typed nonzero failure,
# never a clean empty completion. On FAILED it exits non-zero so the failure is
# loud. A live cycle already present means re-arm attaches - do not start a second
# watcher.
# attached cycle that ends with neither a healthy successor nor a matching
# delivery receipt (state/.watch-cycle-delivery, written by the watcher that
# delivered the wake) is a typed nonzero failure, never a clean empty completion.
# On FAILED it exits non-zero so the failure is loud. A live cycle already
# present means re-arm attaches - do not start a second watcher.
#
# Every observed watcher cycle appends one tab-separated lifecycle record to
# state/.watch-cycle-exits.log. The arm layer owns that bounded ledger; it records
Expand Down Expand Up @@ -71,6 +76,7 @@ GRACE=${FM_GUARD_GRACE:-300}
CONFIRM_TIMEOUT=${FM_ARM_CONFIRM_TIMEOUT:-10}
# Poll interval while attached to an existing healthy watcher.
ATTACH_POLL=${FM_ARM_ATTACH_POLL:-0.5}
DELIVERY_RECEIPT="$STATE/.watch-cycle-delivery"
CYCLE_LOG="$STATE/.watch-cycle-exits.log"
CYCLE_LOG_LOCK="$STATE/.watch-cycle-exits.lock"
CYCLE_LOG_MAX_BYTES=${FM_WATCH_CYCLE_LOG_MAX_BYTES:-262144}
Expand Down Expand Up @@ -255,9 +261,63 @@ fail_unexplained_cycle() {
return 1
}

# An attached arm never sees the watcher's stdout: the wake reason goes to the
# arm that owns that watcher as its child. Read the watcher's identity-bound
# delivery receipt (bin/fm-push-transition-lib.sh) so a close that DID deliver
# its wake is accounted as the successful cycle end it is. Every field must
# match the cycle this arm was attached to - the same pid, the same lock
# identity captured at attach, and a delivery no older than this cycle - so a
# stale, foreign, or recycled-pid receipt still falls through to the typed
# failure. Sets DELIVERED_REASON on success.
DELIVERED_REASON=
attached_cycle_delivered() { # <attached-pid>
local pid=$1 lock_pid lock_identity receipt_pid receipt_identity delivered_at reason
DELIVERED_REASON=
lock_pid=${cycle_lock_before%%|*}
lock_pid=${lock_pid#pid:}
lock_identity=${cycle_lock_before#*|identity:}
[ "$lock_pid" = "$pid" ] || return 1
[ -n "$lock_identity" ] && [ "$lock_identity" != none ] || return 1

[ -r "$DELIVERY_RECEIPT" ] || return 1
IFS=$'\t' read -r receipt_pid receipt_identity delivered_at reason < "$DELIVERY_RECEIPT" || return 1
[ "$receipt_pid" != "${receipt_pid#watcher_pid=}" ] || return 1
[ "$receipt_identity" != "${receipt_identity#identity=}" ] || return 1
[ "$delivered_at" != "${delivered_at#delivered_at=}" ] || return 1
[ "$reason" != "${reason#reason=}" ] || return 1
receipt_pid=${receipt_pid#watcher_pid=}
receipt_identity=${receipt_identity#identity=}
delivered_at=${delivered_at#delivered_at=}
reason=${reason#reason=}

[ "$receipt_pid" = "$pid" ] || return 1
[ "$(cycle_clean_field "$receipt_identity")" = "$lock_identity" ] || return 1
case "$delivered_at" in
''|*[!0-9]*) return 1 ;;
esac
[ "$delivered_at" -ge "$cycle_started_at" ] || return 1
[ -n "$reason" ] || return 1
DELIVERED_REASON=$reason
}

# Report an attached watcher's delivering close. The cycle ended for a real
# supervision reason, so this arm closes successfully and repeats that reason:
# no watcher is left running, and the adapter that started this arm must notify
# the model exactly as it does for an owned actionable close. The durable wake
# queue is the delivery mechanism, so a repeated notification is idempotent
# while a silent zero close would leave the home unsupervised until the next
# turn end.
report_delivered_close() { # <attached-pid>
local pid=$1
cycle_log_append unknown unknown attached-cycle-delivered none
echo "watcher: closed pid=$pid (wake delivered by its owning arm)"
printf '%s\n' "$DELIVERED_REASON"
}

# Stay alive across identity-matched healthy holders. If one cycle ends, attach
# to a verified successor. With no successor, fail loudly instead of returning a
# clean empty completion that an adapter could mistake for a no-op.
# to a verified successor. With no successor, report a proven delivering close
# or else fail loudly - never a clean empty completion an adapter could mistake
# for a no-op.
attach_and_wait() {
local attached_pid=$1
while :; do
Expand All @@ -278,6 +338,10 @@ attach_and_wait() {
report_attached
continue
fi
if attached_cycle_delivered "$attached_pid"; then
report_delivered_close "$attached_pid"
return 0
fi
cycle_log_append unknown unknown attached-cycle-ended none
fail_unexplained_cycle
return 1
Expand Down
1 change: 1 addition & 0 deletions docs/turnend-guard.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ In the default Codex mode, a true value lets the second stop finish after one fo
Claude runs the guard with `--claude`, which ignores `stop_hook_active` and cooperates with the Stop-owned auto-arm.
Claude Code sets `stop_hook_active=true` on every stop after any stop-hook continuation, including `asyncRewake` rewakes, which re-opened the 2026-07-21 blind window under the default one-shot behavior.
The Claude mode waits up to `FM_CLAUDE_AUTOARM_SYNC_WAIT_MS` (default 800 milliseconds) and allows the stop when the watcher is healthy, `state/.claude-autoarm.lock` has a live owner, or `state/.claude-autoarm-epoch` contains a fresh rewake outcome.
That window is load-bearing in both directions: the auto-arm's own pre-claim work, dominated by the session-lock ancestry walk in `bin/fm-session-lock-lib.sh`, must stay well inside it or the guard blocks turns whose auto-arm is working normally.
When none of those proofs appears, it re-blocks up to `FM_CLAUDE_TURNEND_BLOCK_BUDGET` times (default 3, below Claude's 8-block override), then allows degraded with a visible `systemMessage`.
Any allow resets the budget.

Expand Down
9 changes: 6 additions & 3 deletions docs/watcher-continuity.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ The turn-end guard remains the final backstop rather than the normal continuity
`bin/fm-watch-arm.sh` never returns a clean empty success.
An actionable child output returns that reason normally.
A zero/empty child return rechecks the home lock and beacon, attaches to a verified healthy successor when one exists, or emits `watcher: FAILED - cycle ended without an actionable reason` and exits nonzero.
An attached arm follows verified identity-matched successors and reports the same typed failure if that chain ends without one.
An attached arm follows verified identity-matched successors.
When that chain ends, the arm distinguishes a delivering close from a failure through the watcher's own receipt in `state/.watch-cycle-delivery`: the watcher publishes its pid, lock identity, timestamp, and reason as it delivers a wake, because the reason itself goes to the stdout of the arm that owns that watcher as a child and an attached arm can otherwise only observe the lock disappearing.
A receipt matching the exact attached pid, the lock identity captured at attach, and a delivery no older than that cycle closes the arm successfully with `watcher: closed pid=<N> (wake delivered by its owning arm)` followed by the delivered reason, so the adapter notifies exactly as it does for an owned actionable close.
Any other outcome, including a stale, foreign, or recycled-pid receipt, still reports the typed failure and exits nonzero.

The arm layer appends one tab-separated record per observed cycle to `state/.watch-cycle-exits.log`.
Each record includes arm and watcher PIDs, start and end timestamps, exit code and signal, classified reason, beacon age, lock identity before and after close, and successor disposition.
Expand All @@ -52,9 +55,9 @@ Only the watcher process touches `state/.last-watcher-beat`; no helper process c
## Regression coverage

`tests/fm-pi-watch-extension.test.sh` checks Pi's first-cycle-or-explicit-repair tool metadata and ownership-based redundant-call no-ops, then simulates actionable and empty child closes against the actual Pi and OpenCode close handlers, blocks prompt delivery to prove the successor launches first, verifies single-flight behavior, changes the session lock before close to prove ownership is rechecked, and hangs each successor arm to prove bounded fallback delivery includes the typed restoration failure.
`tests/fm-watcher-lock.test.sh` covers verified-successor attach, the typed self-eviction failure, bounded and successor-linked lifecycle rows, and a SIGSTOP counterfactual that distinguishes a live PID from a stale beacon before classifying termination.
`tests/fm-watcher-lock.test.sh` covers verified-successor attach, the typed self-eviction failure, bounded and successor-linked lifecycle rows, a SIGSTOP counterfactual that distinguishes a live PID from a stale beacon before classifying termination, an attached cycle whose watcher delivered its wake closing successfully, and a stale delivery receipt that still reports the typed failure.
`tests/fm-subagent-pretool-check.test.sh` proves Claude retains only the non-status Bash seatbelts.
`tests/fm-claude-stop-autoarm.test.sh` covers the auto-arm's scope, stale and live session owners, unchanged AFK and need boundaries, single-flight, and exit-2 translation.
`tests/fm-claude-stop-autoarm.test.sh` covers the auto-arm's scope, stale and live session owners, unchanged AFK and need boundaries, single-flight, exit-2 translation, and the fork-frugal session-lock ancestry resolution its claim latency depends on.
`FM_CLAUDE_LIVE_E2E=1 tests/fm-claude-stop-autoarm-live-e2e.test.sh` starts with the reproduced stale-lock state, runs session start first, completes two tokenless cycles, and checks the competing-live-owner negative control.
`tests/fm-turnend-guard.test.sh` covers the cooperative `--claude` guard.

Expand Down
Loading