From 45320811802a806c74386abb8fc1ee0b8fa8e15f Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Fri, 25 Sep 2026 09:47:58 -0600 Subject: [PATCH 1/8] Add opt-in captain input demand to the shared wake owner --- bin/fm-claude-stop-autoarm.sh | 3 + bin/fm-inbox.sh | 81 ++++++++++++++++++- bin/fm-input-wait.py | 29 +++++++ bin/fm-supervision-lib.sh | 6 +- bin/fm-wake-drain.sh | 1 + bin/fm-wake-lib.sh | 76 +++++++++++++++++ bin/fm-watch-arm.sh | 16 +++- bin/fm-watch.sh | 50 +++++++++++- docs/documentation-audiences.json | 4 + docs/verification/captain-input.md | 55 +++++++++++++ docs/verification/supervision.md | 2 + docs/watcher-continuity.md | 5 ++ tests/fm-claude-stop-autoarm.test.sh | 75 +++++++++++++++++ tests/fm-inbox.test.sh | 117 +++++++++++++++++++++++++++ tests/fm-watch-arm.test.sh | 12 +++ 15 files changed, 522 insertions(+), 10 deletions(-) create mode 100644 bin/fm-input-wait.py create mode 100644 docs/verification/captain-input.md diff --git a/bin/fm-claude-stop-autoarm.sh b/bin/fm-claude-stop-autoarm.sh index 31721989bda..146718a54c9 100755 --- a/bin/fm-claude-stop-autoarm.sh +++ b/bin/fm-claude-stop-autoarm.sh @@ -531,6 +531,9 @@ if [ "$ACTIONABLE" -eq 1 ]; then printf 'This wake comes from automatic supervision under the away-posture record, not from the captain: it is not a return, so handle it under the away posture.\n' fi [ -z "$SUCCESSOR_FAILURE" ] || printf '%s\n' "$SUCCESSOR_FAILURE" + if [ -f "$STATE/.captain-input" ]; then + printf 'For inbox rows, read and handle the saved note through bin/fm-inbox.sh; acknowledge the note before its wake. bin/fm-inbox.sh input-receipts exposes the shared receipt without consuming input.\n' >&2 + fi printf 'Run bin/fm-wake-drain.sh first, handle the wake, then run its exact WAKE_ACK_REQUIRED --ack-through command. Until that post-handling acknowledgement, interruption leaves the wake durable for idempotent re-handling. This Stop hook owns watcher continuity: when the handling turn ends, the next needed cycle arms automatically - do NOT run bin/fm-watch-arm.sh after an ordinary wake.\n' } >&2 if autoarm_commit rewake; then diff --git a/bin/fm-inbox.sh b/bin/fm-inbox.sh index 1e128a657b4..13ae8c8a984 100755 --- a/bin/fm-inbox.sh +++ b/bin/fm-inbox.sh @@ -26,12 +26,20 @@ # fm-inbox.sh reply [--json] ... | reply [--json] - # fm-inbox.sh receipts [--after ] [--all-pending] [--all-handled] [--all-replies] # fm-inbox.sh ready +# fm-inbox.sh subscribe | unsubscribe | input-receipts # fm-inbox.sh say [] (default: audio on stdin) # fm-inbox.sh status # fm-inbox.sh ask ... # fm-inbox.sh list # fm-inbox.sh drain [--ack ...] # +# subscribe explicitly enables continuous, default-off input demand for this +# home, using state/.captain-input. Only the session-lock owner may change it. +# No listener is launched here: the existing supervision owner arms normally. +# input-receipts is a body-free, read-only projection of the queue sequence, +# Claude handoff generation (a committed request, not proof of delivery), and +# post-handling acknowledgement. fm-wake-lib.sh owns those records. +# # `note --request-id` is the idempotent capture path: a repeat of the same # request id returns the original note instead of creating a second one, and # prints `replay` (or JSON `"outcome":"replay"`) so a first submission and a @@ -1117,25 +1125,94 @@ cmd_drain() { if [ "${1:-}" = "--ack" ]; then shift [ "$#" -gt 0 ] || die "usage: fm-inbox.sh drain --ack ..." + local input_locked=0 id + for id in "$@"; do valid_note_id "$id" || die "invalid note id"; done + if [ -f "$STATE/.captain-input" ]; then + # shellcheck source=bin/fm-session-lock-lib.sh + . "$SELF_DIR/fm-session-lock-lib.sh" + fm_session_lock_owned_by_self "$STATE" || die "only the owning session may handle subscribed input" + load_wake_lib || return 1 + fm_lock_acquire_wait "$FM_WAKE_QUEUE_LOCK" || return 1 + input_locked=1 + fi mkdir -p "$INBOX/handled" - local id for id in "$@"; do if [ -f "$INBOX/$id.note" ]; then - mv "$INBOX/$id.note" "$INBOX/handled/$id.note" + if ! mv "$INBOX/$id.note" "$INBOX/handled/$id.note"; then + [ "$input_locked" -eq 0 ] || fm_lock_release "$FM_WAKE_QUEUE_LOCK" + return 1 + fi printf 'acked %s\n' "$id" else printf 'already-acked %s\n' "$id" fi done + [ "$input_locked" -eq 0 ] || fm_lock_release "$FM_WAKE_QUEUE_LOCK" return 0 fi cmd_list printf '\nAck with: fm-inbox.sh drain --ack ...\n' } +# Continuous demand is an explicit owner operation, never implicit in note. +cmd_subscription() { + # shellcheck source=bin/fm-session-lock-lib.sh + . "$SELF_DIR/fm-session-lock-lib.sh" + fm_session_lock_owned_by_self "$STATE" || die "only the owning session may change the input subscription" + load_wake_lib || return 1 + fm_lock_acquire_wait "$FM_WAKE_QUEUE_LOCK" || return 1 + if [ "$1" = subscribe ]; then + printf 'v1\n' > "$STATE/.captain-input" + else + rm -f "$STATE/.captain-input" + fi + fm_lock_release "$FM_WAKE_QUEUE_LOCK" +} + +cmd_input_receipts() { + need_python + python3 - "$STATE" <<'PYRECEIPTS' +import json, sys +from pathlib import Path +state = Path(sys.argv[1]) +records = {} +try: + queued = {line.split("\t")[3][6:] for line in (state / ".wake-queue").read_text().splitlines() + if len(line.split("\t")) >= 5 and line.split("\t")[3].startswith("inbox:")} +except OSError: + queued = None +for kind, fields in [("handoff", ["sequence", "generation", "session_pid", "recovery_generation"]), + ("ack", ["sequence", "recovery_generation"])]: + for path in sorted((state / (".input-" + kind)).glob("*")): + try: + values = path.read_text().strip().split("\t") + except OSError: + continue + if len(values) != len(fields): + continue + if path.name.endswith(".tmp"): + continue + rec = records.setdefault(path.name, {"note_id": path.name}) + rec[kind] = dict(zip(fields, values)) + if kind == "handoff": + try: + commit = (state / ".input-commit" / values[1]).read_text().strip() + except OSError: + commit = "" + rec[kind]["committed"] = commit == "\t".join(values[2:]) +for rec in records.values(): + rec["queue_acknowledged"] = None if queued is None else "ack" in rec and rec["note_id"] not in queued + rec["note_handled"] = (state / "inbox/handled" / (rec["note_id"] + ".note")).is_file() +print(json.dumps({"schema": "fm-input-receipts.v1", "registered": (state / ".captain-input").is_file(), + "records": list(records.values())})) +PYRECEIPTS +} + # ---------------------------------------------------------------- dispatch case "${1:-}" in + subscribe|unsubscribe) cmd_subscription "$1" ;; + input-receipts) cmd_input_receipts ;; note) shift; cmd_note "$@" ;; announce) shift; cmd_announce "$@" ;; reply) shift; cmd_reply "$@" ;; diff --git a/bin/fm-input-wait.py b/bin/fm-input-wait.py new file mode 100644 index 00000000000..70e7367f16d --- /dev/null +++ b/bin/fm-input-wait.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Wait up to a poll budget for a home-local input doorbell to change. + +Usage: fm-input-wait.py +No queue reads, writes, process signalling, or delivery: the owning watcher +checks its durable queue after this bounded wait. A missing hint is harmless. +""" +import sys +import time +from pathlib import Path + + +def wait(path, observed, seconds): + deadline = time.monotonic() + seconds + while True: + try: + current = path.read_text().rstrip("\n") + except OSError: + current = "" + if current != observed: + return + remaining = deadline - time.monotonic() + if remaining <= 0: + return + time.sleep(min(0.1, remaining)) + + +if __name__ == "__main__": + wait(Path(sys.argv[1]), sys.argv[2], float(sys.argv[3])) diff --git a/bin/fm-supervision-lib.sh b/bin/fm-supervision-lib.sh index 1bbc5708834..143297372ec 100644 --- a/bin/fm-supervision-lib.sh +++ b/bin/fm-supervision-lib.sh @@ -38,7 +38,8 @@ fm_sup_stat_mtime() { # FM_SUP_NEEDED true/false - in-flight work, an X-mode relay poll, a # registered event source (a source is a wait on an # external process, not a task, so it has no metadata), -# or a registered custom check +# a registered custom check, or the explicit continuous +# input registration owned by fm-inbox.sh subscribe # FM_SUP_WATCHER_FRESH true/false - a watcher beacon within the grace window # FM_SUP_BEACON_DESC human-readable beacon age, for banners ("never" if absent) # FM_SUP_QUEUE_PENDING true/false - state/.wake-queue has unread records @@ -75,7 +76,8 @@ fm_supervision_status() { if [ "$FM_SUP_IN_FLIGHT" -gt 0 ] \ || [ -f "$state/x-watch.check.sh" ] \ || [ "$FM_SUP_SOURCES" -gt 0 ] \ - || [ "$FM_SUP_CHECKS" -gt 0 ]; then + || [ "$FM_SUP_CHECKS" -gt 0 ] \ + || [ -f "$state/.captain-input" ]; then FM_SUP_NEEDED=true fi diff --git a/bin/fm-wake-drain.sh b/bin/fm-wake-drain.sh index 437c5ae5c7e..3f084820fc9 100755 --- a/bin/fm-wake-drain.sh +++ b/bin/fm-wake-drain.sh @@ -909,6 +909,7 @@ if [ -n "$ACK_THROUGH" ]; then BEGIN { while ((getline line < seqs) > 0) owned[line]=1 } NF < 5 || $2 !~ /^[0-9]+$/ || $2 > cutoff || !($2 in owned) { print } ' "$FM_WAKE_QUEUE" > "$DRAIN_TMP" || exit 1 + fm_input_ack_locked "$ACK_THROUGH" "$MAIN_ROWS_FILE" "$ACK_GENERATION" || exit 1 fm_wake_commit_secondmate_stall_receipts_through "$ACK_THROUGH" "$MAIN_ROWS_FILE" || { echo "wake drain: secondmate stall receipt could not be recorded safely" >&2 exit 1 diff --git a/bin/fm-wake-lib.sh b/bin/fm-wake-lib.sh index 60a9d289090..df2cbf4c05a 100755 --- a/bin/fm-wake-lib.sh +++ b/bin/fm-wake-lib.sh @@ -1819,6 +1819,10 @@ fm_autoarm_write_owned() { # [marker-file] [session fm_lock_release "$lock" return 2 fi + if [ "$outcome" = rewake ] && ! fm_input_handoff "$state" "$gen" "$session" "$recovery"; then + fm_lock_release "$lock" + return 1 + fi identity=$FM_AUTOARM_IDENTITY tmp="$epoch.tmp.$pid" if ! { @@ -1833,6 +1837,13 @@ fm_autoarm_write_owned() { # [marker-file] [session fm_lock_release "$lock" return 1 fi + if [ "$outcome" = rewake ] && [ -f "$state/.captain-input" ]; then + if ! mkdir -p "$state/.input-commit" \ + || ! printf '%s\t%s\n' "$session" "$recovery" > "$state/.input-commit/$gen"; then + fm_lock_release "$lock" + return 2 + fi + fi if [ -n "$marker" ] && ! : > "$marker" 2>/dev/null; then fm_lock_release "$lock" return 2 @@ -2017,6 +2028,11 @@ fm_wake_append_locked() { esac clean_key=$(printf '%s' "$key" | fm_wake_clean_field) + # Registered input uses the ordinary queue and recovery episode, with no + # user text in any internal banner or durable notification. + if [ -f "$STATE/.captain-input" ] && [ "$kind" = check ]; then + case "$key" in inbox:*) payload="check: captain inbox note ${key#inbox:}" ;; esac + fi clean_payload=$(printf '%s' "$payload" | fm_wake_clean_field) epoch=$(date +%s) seq_file="$STATE/.wake-queue.seq" @@ -2041,9 +2057,69 @@ fm_wake_append_locked() { FM_WAKE_APPEND_RECOVERY_PREVIOUS_TOKEN= FM_WAKE_APPEND_RECOVERY_PUBLISHED_TOKEN= fi + if [ "$status" -eq 0 ] && [ -f "$STATE/.captain-input" ] && [ "$kind" = check ]; then + case "$clean_key" in + inbox:*) + # This is only a doorbell: the already committed queue is the authority. + # A failed hint write leaves ordinary recovery/polling intact. + printf '%s\t%s\n' "$seq" "${clean_key#inbox:}" > "$STATE/.captain-input-notify.tmp" \ + && mv -f "$STATE/.captain-input-notify.tmp" "$STATE/.captain-input-notify" || true + ;; + esac + fi return "$status" } +# Input receipts share the queue lock and its exact sequence identities. A +# handoff records the winning Claude generation's request, not vendor delivery. +# An ack is published only after the note is handled, before queue retirement; +# retries overwrite the same identity, never create a second receipt. +fm_input_handoff() { # + local state=$1 gen=$2 session=$3 recovery=$4 epoch seq kind key payload id tmp rc=0 + [ -f "$state/.captain-input" ] || return 0 + [ -f "$state/.wake-queue" ] || return 0 + fm_lock_try_acquire "$state/.wake-queue.lock" || return 1 + mkdir -p "$state/.input-handoff" || rc=1 + while IFS=$'\t' read -r epoch seq kind key payload; do + [ "$kind" = check ] || continue + case "$key" in inbox:*) id=${key#inbox:} ;; *) continue ;; esac + case "$id" in ''|*..*|*[!A-Za-z0-9._-]*) continue ;; esac + tmp="$state/.input-handoff/$id.tmp" + printf '%s\t%s\t%s\t%s\n' "$seq" "$gen" "$session" "$recovery" > "$tmp" \ + && mv -f "$tmp" "$state/.input-handoff/$id" || rc=1 + done < "$state/.wake-queue" + fm_lock_release "$state/.wake-queue.lock" + return "$rc" +} + +fm_input_ack_locked() { # + local cutoff=$1 rows=$2 recovery=$3 epoch seq kind key payload id tmp + [ -f "$STATE/.captain-input" ] || return 0 + while IFS=$'\t' read -r epoch seq kind key payload; do + [ "$kind" = check ] || continue + case "$key" in inbox:*) id=${key#inbox:} ;; *) continue ;; esac + case "$id" in ''|*..*|*[!A-Za-z0-9._-]*) return 1 ;; esac + [ "$seq" -le "$cutoff" ] || continue + grep -qx "$seq" "$rows" || continue + # Scope ownership to input acknowledgement: branch/daemon drains of other + # event kinds keep their existing authority and presentation contract. + # shellcheck source=bin/fm-session-lock-lib.sh + . "${BASH_SOURCE[0]%/*}/fm-session-lock-lib.sh" + fm_session_lock_owned_by_self "$STATE" || { + printf 'wake drain: only the owning session may acknowledge subscribed input\n' >&2 + return 1 + } + if [ ! -f "$STATE/inbox/handled/$id.note" ]; then + printf 'wake drain: handle inbox note %s before acknowledging its wake\n' "$id" >&2 + return 1 + fi + mkdir -p "$STATE/.input-ack" || return 1 + tmp="$STATE/.input-ack/$id.tmp" + printf '%s\t%s\n' "$seq" "$recovery" > "$tmp" \ + && mv -f "$tmp" "$STATE/.input-ack/$id" || return 1 + done < "$FM_WAKE_QUEUE" +} + # fm_wake_queued_keys # Print the distinct keys currently queued for , oldest first. Read under # the append lock so a concurrent append is never observed half-written. The diff --git a/bin/fm-watch-arm.sh b/bin/fm-watch-arm.sh index 1932c0b9414..5d0d2d0c58b 100755 --- a/bin/fm-watch-arm.sh +++ b/bin/fm-watch-arm.sh @@ -326,12 +326,13 @@ fail_unexplained_cycle() { # Close a cycle whose reason line this arm could not read against the bounded # terminal-delivery ledger the watcher publishes before releasing its lock. -close_unobserved_cycle() { - local i reason clean_identity record_pid record_identity record_reason +close_unobserved_cycle() { # [input-only] + local input_only=${1:-} i reason clean_identity record_pid record_identity record_reason clean_identity=$(printf '%s' "$cycle_watcher_identity" | tr '\t\r\n' ' ') i=0 while ! fm_lock_try_acquire "$WATCH_DELIVERY_LOCK"; do [ "$i" -lt 20 ] || { + [ "$input_only" != input-only ] || return 1 fail_unexplained_cycle return 1 } @@ -347,6 +348,9 @@ close_unobserved_cycle() { done < "$WATCH_DELIVERY_LOG" fi fm_lock_release "$WATCH_DELIVERY_LOCK" + if [ "$input_only" = input-only ]; then + case "$reason" in 'check: captain-input '*) ;; *) return 1 ;; esac + fi if [ -n "$reason" ]; then printf '%s\n' "$reason" return 0 @@ -398,6 +402,14 @@ attach_and_wait() { echo "watcher: FAILED - attached watcher pid=$attached_pid stalled (beacon ${age}s at or past hard bound ${STALL_BOUND}s)" return 1 fi + # A subscribed input delivery already names the exact closed cycle in the + # durable ledger. Forward it now instead of spending the successor grace + # window before the Stop owner can request the handling turn. Missing or + # ordinary deliveries retain the existing recovery/attachment behavior. + if [ -f "$STATE/.captain-input" ] && close_unobserved_cycle input-only; then + cycle_log_append unknown unknown attached-delivered-wake none + return 0 + fi if wait_for_healthy_successor; then cycle_log_append unknown unknown attached-cycle-ended "attached:$HEALTHY_PID" attached_pid=$HEALTHY_PID diff --git a/bin/fm-watch.sh b/bin/fm-watch.sh index 96bae225fa5..7b8891e6a35 100755 --- a/bin/fm-watch.sh +++ b/bin/fm-watch.sh @@ -2258,6 +2258,36 @@ heartbeat_scan_finds_actionable() { return "$found" } +# Input demand has no separate watcher. Check the body-free durable doorbell +# between scan units and in otherwise blind sleeps. Backend event waits retain +# their existing bounded budget and ordinary polling remains the backstop. +INPUT_OBSERVED=$(cat "$STATE/.captain-input-notify" 2>/dev/null || true) +input_checkpoint() { + local current seq id rest + [ -f "$STATE/.captain-input" ] || return 0 + current=$(cat "$STATE/.captain-input-notify" 2>/dev/null || true) + [ "$current" != "$INPUT_OBSERVED" ] || return 0 + INPUT_OBSERVED=$current + IFS=$'\t' read -r seq id rest <<< "$current" + case "$seq" in ''|*[!0-9]*) return 0 ;; esac + case "$id" in ''|*..*|*[!A-Za-z0-9._-]*) return 0 ;; esac + [ -z "$rest" ] || return 0 + [ -f "$STATE/inbox/$id.note" ] || return 0 + # The append already made the ordinary recovery episode pending. Do not + # append another row or mark the note handled merely for ringing the bell. + wake "check: captain-input $seq $id" +} + +input_wait() { # + if [ -f "$STATE/.captain-input" ]; then + python3 "$SCRIPT_DIR/fm-input-wait.py" "$STATE/.captain-input-notify" "$INPUT_OBSERVED" "$1" \ + || sleep "$1" + input_checkpoint + else + sleep "$1" + fi +} + # event_wait_or_sleep: the terminal wait of each supervision cycle. For a home # with push-capable windows (herdr), it replaces the blind `sleep POLL` with a # bounded wait on the backend's native transition stream, so a crew going @@ -2292,7 +2322,7 @@ event_wait_or_sleep() { done < <(recorded_windows) if [ "${#windows[@]}" -eq 0 ]; then - sleep "$POLL" + input_wait "$POLL" return fi @@ -2308,7 +2338,7 @@ event_wait_or_sleep() { _event_cap_fails=0 fi if [ "$_event_cap_ok" != 1 ]; then - sleep "$POLL" + input_wait "$POLL" return fi @@ -2325,7 +2355,7 @@ event_wait_or_sleep() { # pure polling for the rest of this watcher process. _event_cap_fails=$((_event_cap_fails + 1)) [ "$_event_cap_fails" -ge "$EVENT_CAP_FAIL_MAX" ] && _event_cap_ok=0 - sleep "$POLL" + input_wait "$POLL" ;; *) # 1: a clean full-budget wait with no actionable edge - the reader already @@ -2636,6 +2666,8 @@ while :; do # alive. Supervision scripts warn when this goes stale with tasks in flight. touch "$STATE/.last-watcher-beat" + input_checkpoint + # Opt-in fleet activity ledger (docs/fleet-ledger.md): pick up newly appended # status lines before this cycle can exit on a wake. Off costs one file test. [ ! -e "$CONFIG/fleet-ledger" ] || FM_HOME=$FM_HOME FM_STATE_OVERRIDE=$STATE FM_CONFIG_OVERRIDE=$CONFIG "$SCRIPT_DIR/fm-fleet-ledger.sh" capture || true @@ -2656,6 +2688,7 @@ while :; do # repost after grace, and escalate once if the recovery turn is also missed. # No conversation scraping; unresolved records are never silently expired. fm_pending_reply_tick "$STATE" || true + input_checkpoint # Endpoint liveness runs before queue observation: a positively dead or # missing secondmate endpoint is relaunched here on a bounded cadence, which @@ -2667,6 +2700,8 @@ while :; do exit 1 } + input_checkpoint + # A live secondmate endpoint does not prove that its own wake loop is alive. # Observe the foreign queue before the rest of this cycle so an aged row wakes # the parent without consuming or rewriting the receiving home's record. @@ -2675,6 +2710,8 @@ while :; do exit 1 } + input_checkpoint + # Process-to-event liveness repair. This never discovers a result by polling: # each registered source has its own child blocking on that source, and this # only republishes results already captured durably and restarts a source @@ -2682,6 +2719,7 @@ while :; do if [ -d "$STATE/procevent" ]; then FM_HOME="$FM_HOME" "$SCRIPT_DIR/fm-procevent.sh" reconcile >/dev/null 2>&1 || true fi + input_checkpoint # Then deliver any queued-but-unsurfaced result, including one a runner # published while this watcher was between cycles. procevent_surface_queued @@ -2703,6 +2741,8 @@ while :; do triage_log "inactive-outcome reconciliation unavailable" fi + input_checkpoint + # Slow per-task checks (firstmate writes these, e.g. a merged-PR poll). # Time-based via .last-check mtime so the cadence survives watcher restarts. # Evaluated BEFORE the signal scan: wake() exits the cycle, so a check placed @@ -2714,6 +2754,7 @@ while :; do rejected_checks= contribution_check_output= for c in "$STATE"/*.check.sh; do + input_checkpoint [ -e "$c" ] || continue is_pr_poll=0 if [ "$(basename "$c")" = x-watch.check.sh ]; then @@ -2845,7 +2886,7 @@ EOF # signature for an already-pending file (last write wins below). pending=$(scan_signals) if [ -n "$pending" ]; then - sleep "$SIGNAL_GRACE" + input_wait "$SIGNAL_GRACE" pending=$(printf '%s\n%s' "$pending" "$(scan_signals)") # The final coalesced signal set is the watcher-carried status-change # trigger for this home's published summary. Start it before either @@ -3226,5 +3267,6 @@ EOF # Terminal wait: a bounded native-event wait for push-capable homes (herdr), # else the blind poll sleep. See event_wait_or_sleep. + input_checkpoint event_wait_or_sleep done diff --git a/docs/documentation-audiences.json b/docs/documentation-audiences.json index a064b1c51a4..f637f211eca 100644 --- a/docs/documentation-audiences.json +++ b/docs/documentation-audiences.json @@ -472,6 +472,10 @@ "path": "docs/verification/agy.md", "audience": "maintainer-verification" }, + { + "path": "docs/verification/captain-input.md", + "audience": "maintainer-verification" + }, { "path": "docs/verification/devin.md", "audience": "maintainer-verification" diff --git a/docs/verification/captain-input.md b/docs/verification/captain-input.md new file mode 100644 index 00000000000..88ad7b20f27 --- /dev/null +++ b/docs/verification/captain-input.md @@ -0,0 +1,55 @@ +# Continuous Input Lab Notes + +This private branch implements an opt-in shared wake owner, with no deployment or upstream contribution. +`bin/fm-inbox.sh --help` owns registration and read-only receipt commands. +No process-event runner was added because input already has a durable inbox and wake queue; a second result queue would duplicate that ownership. + +The exact runtime diff is `fm-supervision-lib.sh` (demand), `fm-inbox.sh` (registration and serialized note acknowledgement), `fm-wake-lib.sh` (body-free notification and generation/sequence receipts), `fm-wake-drain.sh` (post-handling receipt call), `fm-watch.sh` plus `fm-input-wait.py` (interruptible idle sleep and scan checkpoints), and `fm-watch-arm.sh` plus `fm-claude-stop-autoarm.sh` (existing delivery and generation handoff). +Focused cases extend the existing inbox, watcher-arm, and Stop auto-arm suites. +Documentation adds this record, its audience classification, and continuity pointers. +No operational-input protocol, posture marker, live configuration, or external transport code changes. + +## Native evidence + +Measured on 2026-09-25 using Claude Code 2.1.282 and observed `claude-haiku-4-5-20251001`, existing subscription authentication, disposable homes, a 30-second fleet poll, and the merged bridge in mock mode with its independent waiter removed. +The comparison is [the bridge laboratory](https://github.com/lockhartheavyindustries/agent-coordination/pull/64), whose idle sample also had six inputs. +Times start at local mock input receipt, not Slack send time. +Nearest-rank p95 for six samples is the maximum; these are smoke measurements, not an SLA. + +| Measurement | This branch | Bridge baseline | +| --- | ---: | ---: | +| Idle input to reader median | 5,361.992 ms | 2,367.488 ms | +| Idle input to reader p95 | 8,351.968 ms | 4,730.192 ms | +| Idle input to first output median | 2,432.372 ms | 1,217.938 ms | +| Idle input to first output p95 | 2,607.485 ms | 1,225.476 ms | +| Input during a busy turn to reader | 10,637.588 ms | 9,318 ms | + +All seven distinct inputs produced exactly one reader receipt, one committed generation handoff, one note-handling receipt, and one shared queue acknowledgement. +The watcher delivery ledger contains exactly seven input deliveries: zero redundant watcher wakes; a five-second observation after idle sampling had zero extra model results. +The queue was empty, all seven notes were handled, and the disposable watcher lock was absent after cleanup. +This removes the independently competing desk/watcher acknowledgement path seen in the baseline; it does not improve measured latency. +The native run's cumulative reported model cost was $0.049708. +The native command was `.no-mistakes/desk-input-lab/venv/bin/python .no-mistakes/desk-input-lab/native.py`. +Local raw evidence and the synthetic driver remain in the ignored `.no-mistakes/desk-input-lab/native-v4/` and `.no-mistakes/desk-input-lab/native.py` paths, with no credentials recorded. + +## Verification and limits + +Run `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh`. +Run `bin/fm-test-run.sh tests/fm-inbox.test.sh tests/fm-claude-stop-autoarm.test.sh tests/fm-wake-queue.test.sh tests/fm-watch-arm.test.sh tests/fm-watch-recovery-loop.test.sh`. +The local queue suite used a disposable source snapshot with sibling scratch homes because its secondmate fixtures must be outside their code root; all remained inside this task worktree. + +The new cases cover idle demand without tasks, refusal by an unowned session, simultaneous ordinary input, shared queue acknowledgement, concurrent note acknowledgement, a busy bounded check batch, attached-arm delivery, repeated Stop, interrupted arm and re-arm, supersession, and away/quiet ownership. +Default-off regression behavior remains covered by the existing suites. +All five named suites passed, along with lint and the documentation audience check. +The arm suite has a timing-sensitive three-second teardown assertion: it failed during concurrent validation and passed alone, including the new input delivery bound. + +The notification helper only interrupts blind idle sleeps and is checked between scan units; an in-progress bounded check and a backend-native event wait keep their existing timeout. +The attached-arm optimization requires the exact watcher PID/identity delivery receipt and applies only to registered input. +The CLI and receipt fields do not claim exactly-once external actions or that a committed hook request reached the model. +A process death between commit and exit retains the existing durable replay behavior. + +Input ownership checks apply to note and input-wake acknowledgement; ordinary event and branch drain authority is unchanged. +Registration does not authenticate an external human, return an away desk, clear quiet, or change daemon/branch ownership. +The native proof covers attended Claude; other supported harnesses and backend event waits were inspected at their shared integration surfaces but were not revalidated live. +As in the existing Stop owner, a vendor hook timeout retains queued input and requires a subsequent Stop/session event to re-arm; this does not add an independent timeout-repair service. +The prior bridge probe on the same installed Claude version observed no native StopFailure receipt after an injected provider error; this change neither depends on that event nor claims to fix it. diff --git a/docs/verification/supervision.md b/docs/verification/supervision.md index 0e4f6eacaea..48ee67c4449 100644 --- a/docs/verification/supervision.md +++ b/docs/verification/supervision.md @@ -508,6 +508,8 @@ The timeout hook trapped `TERM`, backgrounded `sleep 300`, waited, and on `TERM` ## Watcher continuity +[Continuous input verification](captain-input.md) records the opt-in shared-owner Claude laboratory and its current limits. + The cross-harness evidence combines the 2026-07-17 live pass with Claude's replacement Stop-owned path revalidated on 2026-09-21, all against isolated project and home state. No credential material was copied into a fixture. diff --git a/docs/watcher-continuity.md b/docs/watcher-continuity.md index c2641b368ba..3a35484bd2a 100644 --- a/docs/watcher-continuity.md +++ b/docs/watcher-continuity.md @@ -32,6 +32,11 @@ Codex and Grok keep their own protocols; see [Manual recovery and other harnesse On a non-Pi primary, a home that runs the supervision host also changes what the owner runs; see [Supervision host](#supervision-host). +Continuous input demand is default-off and explicitly registered by the session owner through `bin/fm-inbox.sh subscribe`; that script owns registration and the body-free `input-receipts` interface. +Registered notes use the existing wake queue, handling acknowledgement, and harness owner; the adapter must not run a second waiter. +The subscription does not authenticate an external human or change away/quiet ownership. +See [input verification](verification/captain-input.md) for measured limits. + ### Pi, omp, and OpenCode adapters Pi's `.pi/extensions/fm-primary-pi-watch.ts`, omp's `.omp/extensions/fm-primary-omp-watch.ts`, and OpenCode's `.opencode/plugins/fm-primary-watch-arm.js` own continuous re-arm after an actionable child close. diff --git a/tests/fm-claude-stop-autoarm.test.sh b/tests/fm-claude-stop-autoarm.test.sh index 3f3615b6c78..5c5afcec1ad 100755 --- a/tests/fm-claude-stop-autoarm.test.sh +++ b/tests/fm-claude-stop-autoarm.test.sh @@ -53,6 +53,10 @@ make_primary_dir() { : > "$dir/AGENTS.md" printf 'off\n' > "$dir/config/supervision-host" install_autoarm_scripts "$dir" + if [ "${INPUT_MATRIX:-0}" = 1 ]; then + printf 'v1\n' > "$dir/state/.captain-input" + : > "$dir/state/.wake-queue" + fi printf '%s\n' "$dir" } @@ -803,6 +807,10 @@ test_term_mid_arm_commits_failure_and_rewakes() { local dir out hook_pid i status=0 dir=$(make_primary_dir "$TMP_ROOT/term-mid-arm") : > "$dir/state/task.meta" + if [ "${INPUT_MATRIX:-0}" = 1 ]; then + rm "$dir/state/task.meta" + printf '1\t1\tcheck\tinbox:timeout-1\tcheck: captain inbox note timeout-1\n' > "$dir/state/.wake-queue" + fi write_arm_fixture "$dir" blocking-actionable out="$dir/state/autoarm.out" run_autoarm_bg "$dir" "$out" @@ -828,6 +836,15 @@ test_term_mid_arm_commits_failure_and_rewakes() { assert_contains "$(cat "$out")" "firstmate watcher auto-arm INTERRUPTED" \ "TERM mid-arm omitted the rewake failure banner" pass "auto-arm: TERM mid-arm commits a durable failure and exits 2 for rewake" + if [ "${INPUT_MATRIX:-0}" = 1 ]; then + assert_contains "$(cat "$dir/state/.wake-queue")" timeout-1 "timeout retains input" + write_arm_fixture "$dir" actionable + status=0 + run_autoarm "$dir" > "$out" 2>&1 || status=$? + expect_code 2 "$status" "next Stop must re-arm subscribed input after timeout" + assert_present "$dir/state/.input-handoff/timeout-1" "re-arm must commit the input handoff" + pass "subscribed input survives timeout and re-arms on the next Stop" + fi } # --- abandoned single-flight claim recovery (legacy shim) ---------------------- @@ -1682,6 +1699,31 @@ test_superseded_owner_never_reinvokes_the_arm test_superseded_owner_goes_silent_and_never_double_translates test_need_vanished_mid_cycle_closes_quietly test_afk_mid_cycle_suppresses_rewake + +# Replace the session while its input arm is running: the old session may not +# commit a handoff, even though the watcher closes actionably afterwards. +dir=$(make_primary_dir "$TMP_ROOT/input-session-replaced") +printf 'v1\n' > "$dir/state/.captain-input" +printf '1\t1\tcheck\tinbox:replacement-1\tcheck: captain inbox note replacement-1\n' > "$dir/state/.wake-queue" +write_arm_fixture "$dir" slow-actionable +run_autoarm_bg "$dir" "$dir/state/old-session.out" +old_session=$RUN_AUTOARM_BG_PID +for ((i=0; i<100; i++)); do + [ ! -f "$dir/state/arm-ran" ] || break + sleep 0.02 +done +assert_present "$dir/state/arm-ran" "old session must be actively arming before replacement" +"$FAKE_CLAUDE" -c 'sleep 10; :' & +replacement=$! +printf '%s\n' "$replacement" > "$dir/state/.lock" +status=0 +wait "$old_session" || status=$? +kill "$replacement" 2>/dev/null || true +wait "$replacement" 2>/dev/null || true +expect_code 0 "$status" "replaced session must refuse the native rewake" +assert_absent "$dir/state/.input-handoff/replacement-1" "replaced session must not publish an input handoff" +assert_contains "$(cat "$dir/state/.wake-queue")" replacement-1 "replacement must preserve queued input" +pass "input handoff refuses a session replaced during the active arm" test_active_in_marked_secondmate_home test_long_poll_grace_reaches_arm_wrapper test_host_off_flag_keeps_the_arm @@ -1696,3 +1738,36 @@ test_host_crash_is_retried_then_reported test_arguments_never_arm test_fm_lock_status_still_works_with_shared_lib test_stands_down_only_on_pi_code_transcript_path + +# No sentinel task/check: registered input alone uses the ordinary generation +# and respects both away and quiet daemon ownership and session replacement. +dir=$(make_primary_dir "$TMP_ROOT/subscribed-input") +printf 'v1\n' > "$dir/state/.captain-input" +printf '1\t1\tcheck\tinbox:input-1\tcheck: captain inbox note input-1\n' > "$dir/state/.wake-queue" +write_arm_fixture "$dir" actionable +status=0 +output=$(run_autoarm "$dir") || status=$? +expect_code 2 "$status" "subscribed no-task owner should issue a native rewake" +assert_present "$dir/state/.input-handoff/input-1" "input is bound to the winning generation" +assert_contains "$(cat "$dir/state/.input-handoff/input-1")" fixture-generation "receipt shares recovery generation" +for posture in away quiet; do + printf '%s\n' "$posture" > "$dir/state/.afk" + before=$(cat "$dir/state/.claude-autoarm-epoch") + status=0 + output=$(run_autoarm "$dir") || status=$? + expect_code 0 "$status" "$posture retains daemon ownership" + assert_equals "$before" "$(cat "$dir/state/.claude-autoarm-epoch")" "$posture must not take a new generation" + assert_equals "$posture" "$(cat "$dir/state/.afk")" "$posture remains unchanged" +done +rm "$dir/state/.afk" +pass "continuous input uses the existing Stop generation and preserves away/quiet ownership" + +TMP_ROOT="$TMP_ROOT/input-matrix" +mkdir -p "$TMP_ROOT" +INPUT_MATRIX=1 +test_inert_without_session_lock +test_inert_when_lock_held_by_other_harness +test_single_flight_admits_exactly_one_owner +test_term_mid_arm_commits_failure_and_rewakes +test_superseded_owner_goes_silent_and_never_double_translates +test_afk_mid_cycle_suppresses_rewake diff --git a/tests/fm-inbox.test.sh b/tests/fm-inbox.test.sh index 4898eefa16c..22fcbd1453f 100644 --- a/tests/fm-inbox.test.sh +++ b/tests/fm-inbox.test.sh @@ -544,3 +544,120 @@ run_inbox "$home" drain --ack "$did" >/dev/null || fail "drain --ack failed" assert_absent "$home/state/inbox/$did.note" "acked note leaves pending" assert_present "$home/state/inbox/handled/$did.note" "acked note is in handled" pass "drain --ack still moves the note to handled" + +# --- registered continuous input shares the existing wake owner ------------- +home=$(make_home subscribed) +mkdir -p "$TMP_ROOT/owner-bin" +ln -s /bin/bash "$TMP_ROOT/owner-bin/claude" +owned() { + # shellcheck disable=SC2016 # The fixture harness expands its own environment. + FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" FM_CONFIG_OVERRIDE="$home/config" \ + "$TMP_ROOT/owner-bin/claude" -c 'printf "%s\n" "$$" > "$FM_HOME/state/.lock"; "$@"' owner "$@" +} +needed() { + bash -c '. "$1/bin/fm-supervision-lib.sh"; fm_supervision_needed "$2/state"' check "$ROOT" "$home" +} +if needed; then fail "an idle default-off home must not demand supervision"; fi +if run_inbox "$home" subscribe >/dev/null 2>&1; then fail "unowned registration must refuse"; fi +owned "$INBOX_BIN" subscribe || fail "owner registration failed" +needed || fail "subscription must demand supervision with no tasks or input" +# Existing non-session drain actors retain ordinary-event presentation and ack. +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" bash -c '. "$1/bin/fm-wake-lib.sh"; fm_wake_append check ordinary "check: ordinary"' check "$ROOT" +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" > "$home/ordinary.out" 2> "$home/ordinary.err" +ordinary_seq=$(awk -F '\t' 'NF == 5 {print $2}' "$home/ordinary.out" | tail -1) +ordinary_gen=$(sed -n 's/^WAKE_ACK_REQUIRED:.*--recovery-generation //p' "$home/ordinary.err") +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" --ack-through "$ordinary_seq" --recovery-generation "$ordinary_gen" \ + || fail "subscription must preserve existing ordinary-event drain actors" +first=$(run_inbox "$home" note --request-id input-1 --json 'PRIVATE_BODY_NEVER_IN_BANNER') +id=$(printf '%s' "$first" | json_get id) +assert_not_contains "$(cat "$home/state/.wake-queue")" PRIVATE_BODY_NEVER_IN_BANNER "registered queue is body free" +assert_contains "$(cat "$home/state/.captain-input-notify")" "$id" "doorbell carries note identity" +# Receipt reads cannot take locks or make input handled. +before=$(find "$home/state" -type f | sort) +run_inbox "$home" input-receipts >/dev/null +assert_equals "$before" "$(find "$home/state" -type f | sort)" "read-only projection creates nothing" +if run_inbox "$home" drain --ack "$id" >/dev/null 2>&1; then fail "read-only session must not handle input"; fi +owned "$ROOT/bin/fm-wake-drain.sh" > "$home/drain.out" 2> "$home/drain.err" +seq=$(awk -F '\t' 'NF == 5 {print $2}' "$home/drain.out" | tail -1) +gen=$(sed -n 's/^WAKE_ACK_REQUIRED:.*--recovery-generation //p' "$home/drain.err") +if owned "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" >/dev/null 2>&1; then + fail "wake acknowledgement must not consume an unhandled note" +fi +# shellcheck disable=SC2016 # Both children inherit the same fixture harness owner. +owned bash -c '"$1" drain --ack "$2" & a=$!; "$1" drain --ack "$2" & b=$!; wait "$a"; wait "$b"' \ + ack "$INBOX_BIN" "$id" > "$home/note-ack" +owned "$INBOX_BIN" drain --ack "$id" >> "$home/note-ack" +assert_equals 1 "$(grep -c '^acked ' "$home/note-ack")" "one note-handling receipt on repeated acknowledgement" +if FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" >/dev/null 2>&1; then + fail "read-only session must not acknowledge a subscribed input wake" +fi +owned "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" +assert_equals 1 "$(run_inbox "$home" input-receipts | json_get records | python3 -c 'import ast,sys; print(len(ast.literal_eval(sys.stdin.read())))')" "one shared receipt" +assert_equals 0 "$(count_wakes "$home")" "post-handling ack retires the original wake" +run_inbox "$home" note --request-id input-1 --json retry >/dev/null +assert_equals 0 "$(count_wakes "$home")" "retry after handling has no redundant wake" +owned "$INBOX_BIN" unsubscribe +if needed; then fail "unsubscription should remove idle demand"; fi +pass "idle demand, owner refusal, body-free notification, and one shared acknowledgement" + +# Real watcher, no fake fleet tasks: a thirty-second poll is interrupted by +# input; simultaneous ordinary events stay durable for the same drain. +home=$(make_home input-watch) +owned "$INBOX_BIN" subscribe +printf 'tmux\n' > "$home/config/backend" +touch "$home/state/.last-check" +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" FM_CONFIG_OVERRIDE="$home/config" \ + FM_POLL=30 FM_HEARTBEAT=999999 FM_CHECK_INTERVAL=999999 \ + "$ROOT/bin/fm-watch.sh" > "$home/watch.out" 2> "$home/watch.err" & +watch_pid=$! +fm_test_track_watcher_state "$home/state" +for ((i=0; i<100; i++)); do + [ ! -f "$home/state/.last-watcher-beat" ] || break + sleep 0.1 +done +[ -f "$home/state/.last-watcher-beat" ] || fail "watcher did not start" +# Give the empty first scan time to enter the long sleep. +sleep 1 +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" bash -c '. "$1/bin/fm-wake-lib.sh"; fm_wake_append check ordinary "check: ordinary"' check "$ROOT" +run_inbox "$home" note --request-id wake-1 'synthetic input' >/dev/null +for ((i=0; i<100; i++)); do + grep -q '^check:' "$home/watch.out" && break + sleep 0.1 +done +grep -q '^check:' "$home/watch.out" || { kill "$watch_pid"; fail "input did not interrupt thirty-second wait"; } +wait "$watch_pid" +assert_contains "$(cat "$home/state/.wake-queue")" ordinary "simultaneous ordinary event remains" +assert_equals 1 "$(count_wakes "$home")" "watcher must not append a second input row" +pass "subscribed idle watcher wakes before the unchanged fleet poll and retains simultaneous sources" + +home=$(make_home input-busy) +owned "$INBOX_BIN" subscribe +printf 'tmux\n' > "$home/config/backend" +for check in a b c d; do + cat > "$home/state/$check.check.sh" <<'CHECK' +#!/bin/sh +printf 'started\n' > "$FM_HOME/check-started" +sleep 2 +CHECK + chmod 700 "$home/state/$check.check.sh" + FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-check-register.sh" "$check" >/dev/null +done +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" FM_CONFIG_OVERRIDE="$home/config" \ + FM_POLL=30 FM_HEARTBEAT=999999 FM_CHECK_INTERVAL=999999 \ + "$ROOT/bin/fm-watch.sh" > "$home/watch.out" 2> "$home/watch.err" & +watch_pid=$! +fm_test_track_watcher_state "$home/state" +for ((i=0; i<100; i++)); do + [ ! -f "$home/check-started" ] || break + sleep 0.1 +done +[ -f "$home/check-started" ] || fail "bounded check never started" +run_inbox "$home" note --request-id busy-1 'input during a bounded check' >/dev/null +for ((i=0; i<60; i++)); do + grep -q '^check: captain-input' "$home/watch.out" && break + sleep 0.1 +done +grep -q '^check: captain-input' "$home/watch.out" || { kill "$watch_pid"; fail "input waited for the whole check batch"; } +wait "$watch_pid" +assert_equals 1 "$(count_wakes "$home")" "busy scan retains exactly one note row" +pass "input is delivered between bounded checks without reducing the fleet poll" diff --git a/tests/fm-watch-arm.test.sh b/tests/fm-watch-arm.test.sh index a2c13f946f6..d34cc34d33e 100755 --- a/tests/fm-watch-arm.test.sh +++ b/tests/fm-watch-arm.test.sh @@ -1342,3 +1342,15 @@ test_handling_window_close_keeps_the_acknowledgement_valid test_moved_generation_acknowledgement_is_self_healing test_downtime_marker_does_not_follow_symlink test_stop_ends_the_home_watcher_and_publishes_downtime + +# A delivered input must not spend the ordinary successor confirmation window. +dir=$(make_case attached-input) +state="$dir/state" +printf 'v1\n' > "$state/.captain-input" +start_seed_watcher "$state" "$dir/fakebin" "$dir/watch.out" +start_attached_arm "$state" "$dir/fakebin" "$dir/arm.out" 20 +FM_HOME="$dir" FM_STATE_OVERRIDE="$state" "$ROOT/bin/fm-inbox.sh" note 'synthetic input' >/dev/null +wait_for_exit "$SEED_PID" 80 || fail "input watcher did not close" +wait_for_exit "$ARM_PID" 80 || fail "input arm spent the twenty-second successor window" +grep -q '^check: captain-input ' "$dir/arm.out" || fail "input arm omitted the delivery receipt" +pass "watch-arm: registered input forwards the exact cycle receipt without successor grace" From 8874611a796d78eeb7a503d130c84e80b77c7dd2 Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Fri, 25 Sep 2026 10:04:25 -0600 Subject: [PATCH 2/8] Record input latency profile and rejected timing candidate --- docs/verification/captain-input.md | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/docs/verification/captain-input.md b/docs/verification/captain-input.md index 88ad7b20f27..921cd83dcb7 100644 --- a/docs/verification/captain-input.md +++ b/docs/verification/captain-input.md @@ -1,6 +1,7 @@ # Continuous Input Lab Notes This private branch implements an opt-in shared wake owner, with no deployment or upstream contribution. +The subsequent latency target remains unmet; the retained runtime is the implementation validated at `18391786`. `bin/fm-inbox.sh --help` owns registration and read-only receipt commands. No process-event runner was added because input already has a durable inbox and wake queue; a second result queue would duplicate that ownership. @@ -53,3 +54,40 @@ Registration does not authenticate an external human, return an away desk, clear The native proof covers attended Claude; other supported harnesses and backend event waits were inspected at their shared integration surfaces but were not revalidated live. As in the existing Stop owner, a vendor hook timeout retains queued input and requires a subsequent Stop/session event to re-arm; this does not add an independent timeout-repair service. The prior bridge probe on the same installed Claude version observed no native StopFailure receipt after an injected provider error; this change neither depends on that event nor claims to fix it. + +## Latency target audit + +The follow-up target was idle input-to-reader median at most 2,400 ms and p95 below 5,000 ms, retaining one handling receipt per input and zero redundant wakes. +A same-day profile of the unchanged implementation used the same Haiku model, prompt, reader, six idle inputs, and one busy input. +Lab-only file timestamps marked input checkpoints, successor confirmation, and generation commit; reader timestamps separated drain from bridge acceptance. +No profiling hooks are part of the tracked runtime. + +| Profiled interval | Median | +| --- | ---: | +| Input to watcher checkpoint | 190 ms | +| Checkpoint to successor start | 463 ms | +| Successor confirmation | 648 ms | +| Confirmation end to handoff commit | 194 ms | +| Handoff commit to first model output | 1,010 ms | +| First model output to reader process start | 1,799 ms | +| Reader drain | 497 ms | +| Drain completion to bridge acceptance | 650 ms | + +Interval medians are independent and should not be summed as a measured whole-turn percentile. +The unchanged profile measured 5,606.436 ms idle median, 9,331.920 ms p95, and 10,677.987 ms busy input-to-reader latency. +All seven inputs had one matching reader receipt, committed handoff and queue acknowledgement, with seven watcher deliveries, zero redundant deliveries, zero extra idle model results, an empty final queue, and a stopped disposable watcher. +The median from committed handoff to reader acceptance alone was 4,082.321 ms; eliminating watcher and handoff time alone would still miss the target in this sample. +The scan checkpoint and successor grace are not the dominant remaining delay. + +A shorter input-specific banner measured 5,133.241 ms / 8,504.174 ms and busy 10,537.537 ms, with all seven receipts, but missed the target and did not justify retaining speculative prompt changes. +A candidate with faster bounded startup confirmation and an interruptible attached-owner wait measured 5,354.630 ms / 7,958.498 ms for idle inputs while focused tests also ran. +Its busy input had a committed handoff and one watcher delivery but no reader receipt within the subsequent 60-second wait; it remained durable in the queue. +That failed native acceptance gate disqualified the candidate; this probe does not establish whether its timing changes or an existing busy-turn vendor race caused the miss. +Both candidates were discarded; this follow-up changes only this verification record. +Exactly-once handling was not relaxed, and no faster production guarantee is claimed. +Reaching the target needs a broader investigation of model/tool-call generation, reader integration, and busy-turn native handoff behavior before changing those boundaries. + +The follow-up inbox, Stop auto-arm, and watcher-arm suites passed on the candidate, including a twenty-second attached wait interrupted by input; the retained runtime's five-suite results above remain its validation evidence. +Raw profiles, candidate source snapshots and streams remain under ignored `.no-mistakes/desk-input-lab/native-profile`, `native-concise`, and `native-tuned`. +The profile command is `FM_LAB_NAME= FM_LAB_PROFILE=1 .no-mistakes/desk-input-lab/venv/bin/python .no-mistakes/desk-input-lab/native.py`. +Every probe's disposable watcher and Claude session was stopped, and no live desk or external transport was activated. From 80325ae68e9e65d1ea7bd691de8e6c6e9f20926e Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Tue, 29 Sep 2026 07:19:21 -0600 Subject: [PATCH 3/8] Assert subscribed input wake presentation and posture silence --- tests/fm-claude-stop-autoarm.test.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/fm-claude-stop-autoarm.test.sh b/tests/fm-claude-stop-autoarm.test.sh index 5c5afcec1ad..5f23b2f413a 100755 --- a/tests/fm-claude-stop-autoarm.test.sh +++ b/tests/fm-claude-stop-autoarm.test.sh @@ -1748,6 +1748,7 @@ write_arm_fixture "$dir" actionable status=0 output=$(run_autoarm "$dir") || status=$? expect_code 2 "$status" "subscribed no-task owner should issue a native rewake" +assert_contains "$output" "firstmate watcher wake" "subscribed input should present the native wake" assert_present "$dir/state/.input-handoff/input-1" "input is bound to the winning generation" assert_contains "$(cat "$dir/state/.input-handoff/input-1")" fixture-generation "receipt shares recovery generation" for posture in away quiet; do @@ -1756,6 +1757,7 @@ for posture in away quiet; do status=0 output=$(run_autoarm "$dir") || status=$? expect_code 0 "$status" "$posture retains daemon ownership" + assert_equals "" "$output" "$posture must not present a competing input wake" assert_equals "$before" "$(cat "$dir/state/.claude-autoarm-epoch")" "$posture must not take a new generation" assert_equals "$posture" "$(cat "$dir/state/.afk")" "$posture remains unchanged" done From 5dae9b1b8df840d07859e6723173bc337e78a770 Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Tue, 29 Sep 2026 22:48:26 -0600 Subject: [PATCH 4/8] docs: make continuous captain input docs contribution-ready and add a Slack desk example --- docs/scripts.md | 2 +- docs/verification/captain-input.md | 62 +++++++++++------------------- docs/watcher-continuity.md | 11 ++++++ 3 files changed, 34 insertions(+), 41 deletions(-) diff --git a/docs/scripts.md b/docs/scripts.md index 8d656ec203e..9873f9599c5 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -158,7 +158,7 @@ The shared no-mistakes gate lifecycle boundary is summarized in [architecture.md | `fm-public-followup.sh` | Brief, reconcile, and deliver typed public commitments, surface refusals, then rechain or retire retained loops | | `fm-public-followup-emit.sh` | Validate and report one typed terminal work result into its owning home, or stage it when that home is remote | | `fm-public-followup-collect.sh` | Read and retire the typed terminal results a remote work home staged for the home that owes the public reply | -| `fm-inbox.sh` | The captain's out-of-band capture surface: queue a note (optionally idempotent by request id), announce or repair its wake, record a durable primary reply, and emit bounded receipts and primary-readiness JSON | +| `fm-inbox.sh` | The captain's out-of-band capture surface: queue a note (optionally idempotent by request id), announce or repair its wake, record a durable primary reply, emit bounded receipts and primary-readiness JSON, and opt the home into continuous input demand ([watcher-continuity.md](watcher-continuity.md#continuous-captain-input)) | | `fm-mail.sh` | General-purpose mail plane: read unseen IMAP mail, send one SMTP message, or surface new mail as a `check` wake via `poll` (configuration in the home's gitignored `.env`) | | `fm-mail.py` | The IMAP/SMTP engine behind `fm-mail.sh` | | `fm-mail-check.sh` | Standing received-mail poll: `arm` registers a watcher check that runs `fm-mail.sh poll` on the watcher cadence (new mail still wakes via the poll; the check's own line also wakes unless the poll is a proven no-op), `disarm` removes it | diff --git a/docs/verification/captain-input.md b/docs/verification/captain-input.md index 921cd83dcb7..f260da0dbfb 100644 --- a/docs/verification/captain-input.md +++ b/docs/verification/captain-input.md @@ -1,23 +1,21 @@ -# Continuous Input Lab Notes +# Continuous captain input verification -This private branch implements an opt-in shared wake owner, with no deployment or upstream contribution. -The subsequent latency target remains unmet; the retained runtime is the implementation validated at `18391786`. -`bin/fm-inbox.sh --help` owns registration and read-only receipt commands. +This record covers opt-in continuous captain input demand, registered through `bin/fm-inbox.sh subscribe`. +`bin/fm-inbox.sh --help` owns registration and the read-only `input-receipts` interface, and [watcher continuity](../watcher-continuity.md#continuous-captain-input) owns the operator contract. No process-event runner was added because input already has a durable inbox and wake queue; a second result queue would duplicate that ownership. -The exact runtime diff is `fm-supervision-lib.sh` (demand), `fm-inbox.sh` (registration and serialized note acknowledgement), `fm-wake-lib.sh` (body-free notification and generation/sequence receipts), `fm-wake-drain.sh` (post-handling receipt call), `fm-watch.sh` plus `fm-input-wait.py` (interruptible idle sleep and scan checkpoints), and `fm-watch-arm.sh` plus `fm-claude-stop-autoarm.sh` (existing delivery and generation handoff). -Focused cases extend the existing inbox, watcher-arm, and Stop auto-arm suites. -Documentation adds this record, its audience classification, and continuity pointers. -No operational-input protocol, posture marker, live configuration, or external transport code changes. +The runtime pieces are `fm-supervision-lib.sh` (demand), `fm-inbox.sh` (registration and serialized note acknowledgement), `fm-wake-lib.sh` (body-free notification and generation/sequence receipts), `fm-wake-drain.sh` (post-handling receipt call), `fm-watch.sh` plus `fm-input-wait.py` (interruptible idle sleep and scan checkpoints), and `fm-watch-arm.sh` plus `fm-claude-stop-autoarm.sh` (existing delivery and generation handoff). +Without `state/.captain-input`, every path above keeps its existing behavior. ## Native evidence -Measured on 2026-09-25 using Claude Code 2.1.282 and observed `claude-haiku-4-5-20251001`, existing subscription authentication, disposable homes, a 30-second fleet poll, and the merged bridge in mock mode with its independent waiter removed. -The comparison is [the bridge laboratory](https://github.com/lockhartheavyindustries/agent-coordination/pull/64), whose idle sample also had six inputs. -Times start at local mock input receipt, not Slack send time. +Measured on 2026-09-25 using Claude Code 2.1.282 and observed `claude-haiku-4-5-20251001`, existing subscription authentication, disposable homes, and a 30-second fleet poll. +Input came from a synthetic external listener in mock mode that wrote inbox notes and read the recorded replies, with no chat service or credentials involved. +The baseline is the same listener running its own independent waiter and acknowledgement path instead of the shared owner, with a six-input idle sample. +Times start at local mock input receipt, not at the chat service's send time. Nearest-rank p95 for six samples is the maximum; these are smoke measurements, not an SLA. -| Measurement | This branch | Bridge baseline | +| Measurement | Shared owner | Separate-waiter baseline | | --- | ---: | ---: | | Idle input to reader median | 5,361.992 ms | 2,367.488 ms | | Idle input to reader p95 | 8,351.968 ms | 4,730.192 ms | @@ -28,21 +26,18 @@ Nearest-rank p95 for six samples is the maximum; these are smoke measurements, n All seven distinct inputs produced exactly one reader receipt, one committed generation handoff, one note-handling receipt, and one shared queue acknowledgement. The watcher delivery ledger contains exactly seven input deliveries: zero redundant watcher wakes; a five-second observation after idle sampling had zero extra model results. The queue was empty, all seven notes were handled, and the disposable watcher lock was absent after cleanup. -This removes the independently competing desk/watcher acknowledgement path seen in the baseline; it does not improve measured latency. +This removes the competing listener/watcher acknowledgement path seen in the baseline; it does not improve measured latency. The native run's cumulative reported model cost was $0.049708. -The native command was `.no-mistakes/desk-input-lab/venv/bin/python .no-mistakes/desk-input-lab/native.py`. -Local raw evidence and the synthetic driver remain in the ignored `.no-mistakes/desk-input-lab/native-v4/` and `.no-mistakes/desk-input-lab/native.py` paths, with no credentials recorded. +The synthetic listener driver and its raw evidence are not tracked; the portable suites below are the repeatable regression entry point. ## Verification and limits Run `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh`. Run `bin/fm-test-run.sh tests/fm-inbox.test.sh tests/fm-claude-stop-autoarm.test.sh tests/fm-wake-queue.test.sh tests/fm-watch-arm.test.sh tests/fm-watch-recovery-loop.test.sh`. -The local queue suite used a disposable source snapshot with sibling scratch homes because its secondmate fixtures must be outside their code root; all remained inside this task worktree. The new cases cover idle demand without tasks, refusal by an unowned session, simultaneous ordinary input, shared queue acknowledgement, concurrent note acknowledgement, a busy bounded check batch, attached-arm delivery, repeated Stop, interrupted arm and re-arm, supersession, and away/quiet ownership. Default-off regression behavior remains covered by the existing suites. -All five named suites passed, along with lint and the documentation audience check. -The arm suite has a timing-sensitive three-second teardown assertion: it failed during concurrent validation and passed alone, including the new input delivery bound. +The arm suite has a timing-sensitive three-second teardown assertion that can fail under heavy concurrent load and pass alone, including the new input delivery bound. The notification helper only interrupts blind idle sleeps and is checked between scan units; an in-progress bounded check and a backend-native event wait keep their existing timeout. The attached-arm optimization requires the exact watcher PID/identity delivery receipt and applies only to registered input. @@ -50,16 +45,15 @@ The CLI and receipt fields do not claim exactly-once external actions or that a A process death between commit and exit retains the existing durable replay behavior. Input ownership checks apply to note and input-wake acknowledgement; ordinary event and branch drain authority is unchanged. -Registration does not authenticate an external human, return an away desk, clear quiet, or change daemon/branch ownership. +Registration does not authenticate an external human, end away mode, clear quiet, or change daemon/branch ownership. The native proof covers attended Claude; other supported harnesses and backend event waits were inspected at their shared integration surfaces but were not revalidated live. As in the existing Stop owner, a vendor hook timeout retains queued input and requires a subsequent Stop/session event to re-arm; this does not add an independent timeout-repair service. -The prior bridge probe on the same installed Claude version observed no native StopFailure receipt after an injected provider error; this change neither depends on that event nor claims to fix it. +A probe on the same installed Claude version observed no native StopFailure receipt after an injected provider error; this change neither depends on that event nor claims to fix it. -## Latency target audit +## Latency profile -The follow-up target was idle input-to-reader median at most 2,400 ms and p95 below 5,000 ms, retaining one handling receipt per input and zero redundant wakes. A same-day profile of the unchanged implementation used the same Haiku model, prompt, reader, six idle inputs, and one busy input. -Lab-only file timestamps marked input checkpoints, successor confirmation, and generation commit; reader timestamps separated drain from bridge acceptance. +Lab-only file timestamps marked input checkpoints, successor confirmation, and generation commit; reader timestamps separated drain from listener acceptance. No profiling hooks are part of the tracked runtime. | Profiled interval | Median | @@ -71,23 +65,11 @@ No profiling hooks are part of the tracked runtime. | Handoff commit to first model output | 1,010 ms | | First model output to reader process start | 1,799 ms | | Reader drain | 497 ms | -| Drain completion to bridge acceptance | 650 ms | +| Drain completion to listener acceptance | 650 ms | Interval medians are independent and should not be summed as a measured whole-turn percentile. -The unchanged profile measured 5,606.436 ms idle median, 9,331.920 ms p95, and 10,677.987 ms busy input-to-reader latency. -All seven inputs had one matching reader receipt, committed handoff and queue acknowledgement, with seven watcher deliveries, zero redundant deliveries, zero extra idle model results, an empty final queue, and a stopped disposable watcher. -The median from committed handoff to reader acceptance alone was 4,082.321 ms; eliminating watcher and handoff time alone would still miss the target in this sample. -The scan checkpoint and successor grace are not the dominant remaining delay. - -A shorter input-specific banner measured 5,133.241 ms / 8,504.174 ms and busy 10,537.537 ms, with all seven receipts, but missed the target and did not justify retaining speculative prompt changes. -A candidate with faster bounded startup confirmation and an interruptible attached-owner wait measured 5,354.630 ms / 7,958.498 ms for idle inputs while focused tests also ran. -Its busy input had a committed handoff and one watcher delivery but no reader receipt within the subsequent 60-second wait; it remained durable in the queue. -That failed native acceptance gate disqualified the candidate; this probe does not establish whether its timing changes or an existing busy-turn vendor race caused the miss. -Both candidates were discarded; this follow-up changes only this verification record. +The profiled run measured 5,606.436 ms idle median, 9,331.920 ms p95, and 10,677.987 ms busy input-to-reader latency, with the same one-receipt-per-input and zero-redundant-wake results as above. +The median from committed handoff to reader acceptance alone was 4,082.321 ms, so the scan checkpoint and successor grace are not the dominant remaining delay. +Two timing candidates were measured and rejected: a shorter input-specific banner did not reach a 2,400 ms idle median, and a faster startup confirmation with an interruptible attached-owner wait left one busy input undelivered to the reader within 60 seconds, though it stayed durable in the queue. Exactly-once handling was not relaxed, and no faster production guarantee is claimed. -Reaching the target needs a broader investigation of model/tool-call generation, reader integration, and busy-turn native handoff behavior before changing those boundaries. - -The follow-up inbox, Stop auto-arm, and watcher-arm suites passed on the candidate, including a twenty-second attached wait interrupted by input; the retained runtime's five-suite results above remain its validation evidence. -Raw profiles, candidate source snapshots and streams remain under ignored `.no-mistakes/desk-input-lab/native-profile`, `native-concise`, and `native-tuned`. -The profile command is `FM_LAB_NAME= FM_LAB_PROFILE=1 .no-mistakes/desk-input-lab/venv/bin/python .no-mistakes/desk-input-lab/native.py`. -Every probe's disposable watcher and Claude session was stopped, and no live desk or external transport was activated. +Further latency work belongs in model/tool-call generation, reader integration, and busy-turn native handoff behavior rather than the watcher. diff --git a/docs/watcher-continuity.md b/docs/watcher-continuity.md index 3a35484bd2a..aae80fdf611 100644 --- a/docs/watcher-continuity.md +++ b/docs/watcher-continuity.md @@ -32,11 +32,22 @@ Codex and Grok keep their own protocols; see [Manual recovery and other harnesse On a non-Pi primary, a home that runs the supervision host also changes what the owner runs; see [Supervision host](#supervision-host). +### Continuous captain input + Continuous input demand is default-off and explicitly registered by the session owner through `bin/fm-inbox.sh subscribe`; that script owns registration and the body-free `input-receipts` interface. +While registered, supervision stays armed with no work in flight, and a new inbox note wakes an idle watcher at its next checkpoint instead of after the routine poll interval. Registered notes use the existing wake queue, handling acknowledgement, and harness owner; the adapter must not run a second waiter. The subscription does not authenticate an external human or change away/quiet ownership. See [input verification](verification/captain-input.md) for measured limits. +#### Example: a Slack desk + +A captain who talks to the first mate from Slack can run a small listener outside Firstmate as a dedicated bot in a private channel. +The listener records each captain message as an inbox note with `bin/fm-inbox.sh note --request-id `, with a body that carries the text, the thread it came from, and local paths to any downloaded attachments. +The session owner runs `bin/fm-inbox.sh subscribe` once, so each note wakes the idle session promptly. +The first mate handles the note like any other captain input and replies in the same Slack thread through the listener's bot, and it can post a new captain-facing ask as a top-level message in that channel. +The listener only captures and relays: it keeps its bot credentials outside the Firstmate home, never waits on the session itself, and the channel's membership is what limits who counts as the captain. + ### Pi, omp, and OpenCode adapters Pi's `.pi/extensions/fm-primary-pi-watch.ts`, omp's `.omp/extensions/fm-primary-omp-watch.ts`, and OpenCode's `.opencode/plugins/fm-primary-watch-arm.js` own continuous re-arm after an actionable child close. From 40c6249af654635e0981150d7f0ccfa60b630f09 Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Tue, 29 Sep 2026 23:05:27 -0600 Subject: [PATCH 5/8] no-mistakes(review): Let daemon acks skip input receipts; bound handoff lock wait --- bin/fm-inbox.sh | 2 +- bin/fm-wake-lib.sh | 9 +++------ docs/verification/captain-input.md | 3 ++- tests/fm-inbox.test.sh | 21 ++++++++++++++++++--- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/bin/fm-inbox.sh b/bin/fm-inbox.sh index 13ae8c8a984..cbb3faff48a 100755 --- a/bin/fm-inbox.sh +++ b/bin/fm-inbox.sh @@ -1126,8 +1126,8 @@ cmd_drain() { shift [ "$#" -gt 0 ] || die "usage: fm-inbox.sh drain --ack ..." local input_locked=0 id - for id in "$@"; do valid_note_id "$id" || die "invalid note id"; done if [ -f "$STATE/.captain-input" ]; then + for id in "$@"; do valid_note_id "$id" || die "invalid note id"; done # shellcheck source=bin/fm-session-lock-lib.sh . "$SELF_DIR/fm-session-lock-lib.sh" fm_session_lock_owned_by_self "$STATE" || die "only the owning session may handle subscribed input" diff --git a/bin/fm-wake-lib.sh b/bin/fm-wake-lib.sh index df2cbf4c05a..517bae703d4 100755 --- a/bin/fm-wake-lib.sh +++ b/bin/fm-wake-lib.sh @@ -2078,7 +2078,7 @@ fm_input_handoff() { # local state=$1 gen=$2 session=$3 recovery=$4 epoch seq kind key payload id tmp rc=0 [ -f "$state/.captain-input" ] || return 0 [ -f "$state/.wake-queue" ] || return 0 - fm_lock_try_acquire "$state/.wake-queue.lock" || return 1 + fm_lock_acquire_wait_max "$state/.wake-queue.lock" 2 || return 1 mkdir -p "$state/.input-handoff" || rc=1 while IFS=$'\t' read -r epoch seq kind key payload; do [ "$kind" = check ] || continue @@ -2098,17 +2098,14 @@ fm_input_ack_locked() { # while IFS=$'\t' read -r epoch seq kind key payload; do [ "$kind" = check ] || continue case "$key" in inbox:*) id=${key#inbox:} ;; *) continue ;; esac - case "$id" in ''|*..*|*[!A-Za-z0-9._-]*) return 1 ;; esac [ "$seq" -le "$cutoff" ] || continue grep -qx "$seq" "$rows" || continue # Scope ownership to input acknowledgement: branch/daemon drains of other # event kinds keep their existing authority and presentation contract. # shellcheck source=bin/fm-session-lock-lib.sh . "${BASH_SOURCE[0]%/*}/fm-session-lock-lib.sh" - fm_session_lock_owned_by_self "$STATE" || { - printf 'wake drain: only the owning session may acknowledge subscribed input\n' >&2 - return 1 - } + fm_session_lock_owned_by_self "$STATE" || return 0 + case "$id" in ''|*..*|*[!A-Za-z0-9._-]*) return 1 ;; esac if [ ! -f "$STATE/inbox/handled/$id.note" ]; then printf 'wake drain: handle inbox note %s before acknowledging its wake\n' "$id" >&2 return 1 diff --git a/docs/verification/captain-input.md b/docs/verification/captain-input.md index f260da0dbfb..77fd5ecad23 100644 --- a/docs/verification/captain-input.md +++ b/docs/verification/captain-input.md @@ -44,7 +44,8 @@ The attached-arm optimization requires the exact watcher PID/identity delivery r The CLI and receipt fields do not claim exactly-once external actions or that a committed hook request reached the model. A process death between commit and exit retains the existing durable replay behavior. -Input ownership checks apply to note and input-wake acknowledgement; ordinary event and branch drain authority is unchanged. +Input ownership checks apply to note handling and to input receipts written by the owning session's wake acknowledgement. +A non-session drain actor, such as the away/quiet daemon, retires input rows exactly as before and writes no input receipt; ordinary event and branch drain authority is unchanged. Registration does not authenticate an external human, end away mode, clear quiet, or change daemon/branch ownership. The native proof covers attended Claude; other supported harnesses and backend event waits were inspected at their shared integration surfaces but were not revalidated live. As in the existing Stop owner, a vendor hook timeout retains queued input and requires a subsequent Stop/session event to re-arm; this does not add an independent timeout-repair service. diff --git a/tests/fm-inbox.test.sh b/tests/fm-inbox.test.sh index 22fcbd1453f..6dc5b6abe45 100644 --- a/tests/fm-inbox.test.sh +++ b/tests/fm-inbox.test.sh @@ -588,9 +588,6 @@ owned bash -c '"$1" drain --ack "$2" & a=$!; "$1" drain --ack "$2" & b=$!; wait ack "$INBOX_BIN" "$id" > "$home/note-ack" owned "$INBOX_BIN" drain --ack "$id" >> "$home/note-ack" assert_equals 1 "$(grep -c '^acked ' "$home/note-ack")" "one note-handling receipt on repeated acknowledgement" -if FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" >/dev/null 2>&1; then - fail "read-only session must not acknowledge a subscribed input wake" -fi owned "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" assert_equals 1 "$(run_inbox "$home" input-receipts | json_get records | python3 -c 'import ast,sys; print(len(ast.literal_eval(sys.stdin.read())))')" "one shared receipt" assert_equals 0 "$(count_wakes "$home")" "post-handling ack retires the original wake" @@ -600,6 +597,24 @@ owned "$INBOX_BIN" unsubscribe if needed; then fail "unsubscription should remove idle demand"; fi pass "idle demand, owner refusal, body-free notification, and one shared acknowledgement" +# A non-session actor (the away/quiet daemon) retires a batch holding an +# unhandled input row exactly as before, without writing an input receipt. +home=$(make_home subscribed-daemon) +owned "$INBOX_BIN" subscribe +id=$(run_inbox "$home" note --request-id away-1 --json 'while away' | json_get id) +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" bash -c '. "$1/bin/fm-wake-lib.sh"; fm_wake_append check ordinary "check: ordinary"' check "$ROOT" +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" > "$home/daemon.out" 2> "$home/daemon.err" \ + || fail "daemon-style drain of subscribed input failed" +assert_contains "$(cat "$home/daemon.out")" "inbox:$id" "daemon drain presents the input row" +seq=$(awk -F '\t' 'NF == 5 {print $2}' "$home/daemon.out" | tail -1) +gen=$(sed -n 's/^WAKE_ACK_REQUIRED:.*--recovery-generation //p' "$home/daemon.err") +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" \ + || fail "daemon-style ack of a batch with subscribed input must succeed" +assert_equals 0 "$(count_wakes "$home")" "daemon-style ack retires the whole batch" +assert_equals 0 "$(run_inbox "$home" input-receipts | json_get records | python3 -c 'import ast,sys; print(len(ast.literal_eval(sys.stdin.read())))')" "non-session ack writes no input receipt" +[ -f "$home/state/inbox/$id.note" ] || fail "daemon-style ack must leave the note for the session owner" +pass "non-session drain actors retire subscribed input rows without a receipt" + # Real watcher, no fake fleet tasks: a thirty-second poll is interrupted by # input; simultaneous ordinary events stay durable for the same drain. home=$(make_home input-watch) From 9e7ec1f6a9a1a9036abfb74813990f09e34167ee Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Tue, 29 Sep 2026 23:18:48 -0600 Subject: [PATCH 6/8] no-mistakes(document): Note non-session daemon ack coverage in input verification --- docs/verification/captain-input.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/verification/captain-input.md b/docs/verification/captain-input.md index 77fd5ecad23..ffec317c81d 100644 --- a/docs/verification/captain-input.md +++ b/docs/verification/captain-input.md @@ -35,7 +35,7 @@ The synthetic listener driver and its raw evidence are not tracked; the portable Run `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh`. Run `bin/fm-test-run.sh tests/fm-inbox.test.sh tests/fm-claude-stop-autoarm.test.sh tests/fm-wake-queue.test.sh tests/fm-watch-arm.test.sh tests/fm-watch-recovery-loop.test.sh`. -The new cases cover idle demand without tasks, refusal by an unowned session, simultaneous ordinary input, shared queue acknowledgement, concurrent note acknowledgement, a busy bounded check batch, attached-arm delivery, repeated Stop, interrupted arm and re-arm, supersession, and away/quiet ownership. +The new cases cover idle demand without tasks, refusal by an unowned session, simultaneous ordinary input, shared queue acknowledgement, non-session daemon acknowledgement without a receipt, concurrent note acknowledgement, a busy bounded check batch, attached-arm delivery, repeated Stop, interrupted arm and re-arm, supersession, and away/quiet ownership. Default-off regression behavior remains covered by the existing suites. The arm suite has a timing-sensitive three-second teardown assertion that can fail under heavy concurrent load and pass alone, including the new input delivery bound. From 1b950745ab20e7d1269af5780a3c4ddc7aa7adb2 Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Tue, 29 Sep 2026 23:36:27 -0600 Subject: [PATCH 7/8] no-mistakes(ci): Fixed both Greptile findings; the new regression test fails without the code fix and passes with it. ci-1: the input receipt was lost after unsubscribing. - Rule that must hold: a note handed off while subscribed gets exactly one acknowledgement receipt when it is handled, even if the owner unsubscribes before acking. - Where it applies: only fm_input_ack_locked writes receipts, and fm-wake-drain.sh --ack-through is its only caller. - Code fix (bin/fm-wake-lib.sh): a row now counts if the home is still subscribed or the note already has a .input-handoff/ record. - The function still exits straight away when neither state/.captain-input nor the .input-handoff folder exists, so homes that never subscribed behave exactly as before. - The owner-only check, the handled-note check and the away/quiet daemon skip are unchanged. - Test (tests/fm-inbox.test.sh): subscribes, queues a note, records a handoff, unsubscribes; the owner then handles and acks the note, and the test checks that the wake is retired and exactly one receipt exists. ci-2 (docs only): docs/watcher-continuity.md now says the prompt wake applies to the polling watcher. A backend blocked in its own event wait, such as Herdr, only sees the doorbell when that wait returns. It is one sentence on its own line. Checks run: - tests/fm-inbox.test.sh passes, including the new case. - With the code fix removed, it fails with "handed-off input keeps one receipt (expected '1', got '0')". - tests/fm-claude-stop-autoarm.test.sh and all six tests/fm-wake*.test.sh suites pass. - shellcheck -x reports nothing on the changed shell files --- bin/fm-wake-lib.sh | 4 +++- docs/watcher-continuity.md | 1 + tests/fm-inbox.test.sh | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/bin/fm-wake-lib.sh b/bin/fm-wake-lib.sh index 517bae703d4..8cb40dc9d29 100755 --- a/bin/fm-wake-lib.sh +++ b/bin/fm-wake-lib.sh @@ -2094,11 +2094,13 @@ fm_input_handoff() { # fm_input_ack_locked() { # local cutoff=$1 rows=$2 recovery=$3 epoch seq kind key payload id tmp - [ -f "$STATE/.captain-input" ] || return 0 + [ -f "$STATE/.captain-input" ] || [ -d "$STATE/.input-handoff" ] || return 0 while IFS=$'\t' read -r epoch seq kind key payload; do [ "$kind" = check ] || continue case "$key" in inbox:*) id=${key#inbox:} ;; *) continue ;; esac [ "$seq" -le "$cutoff" ] || continue + # A note handed off while subscribed keeps its receipt after unsubscribe. + [ -f "$STATE/.captain-input" ] || [ -f "$STATE/.input-handoff/$id" ] || continue grep -qx "$seq" "$rows" || continue # Scope ownership to input acknowledgement: branch/daemon drains of other # event kinds keep their existing authority and presentation contract. diff --git a/docs/watcher-continuity.md b/docs/watcher-continuity.md index aae80fdf611..28669419de6 100644 --- a/docs/watcher-continuity.md +++ b/docs/watcher-continuity.md @@ -36,6 +36,7 @@ On a non-Pi primary, a home that runs the supervision host also changes what the Continuous input demand is default-off and explicitly registered by the session owner through `bin/fm-inbox.sh subscribe`; that script owns registration and the body-free `input-receipts` interface. While registered, supervision stays armed with no work in flight, and a new inbox note wakes an idle watcher at its next checkpoint instead of after the routine poll interval. +That prompt wake applies to the polling watcher: on a backend blocked in its native event wait (for example Herdr), the doorbell is only seen when that wait returns. Registered notes use the existing wake queue, handling acknowledgement, and harness owner; the adapter must not run a second waiter. The subscription does not authenticate an external human or change away/quiet ownership. See [input verification](verification/captain-input.md) for measured limits. diff --git a/tests/fm-inbox.test.sh b/tests/fm-inbox.test.sh index 6dc5b6abe45..05142e7122e 100644 --- a/tests/fm-inbox.test.sh +++ b/tests/fm-inbox.test.sh @@ -615,6 +615,23 @@ assert_equals 0 "$(run_inbox "$home" input-receipts | json_get records | python3 [ -f "$home/state/inbox/$id.note" ] || fail "daemon-style ack must leave the note for the session owner" pass "non-session drain actors retire subscribed input rows without a receipt" +# Input handed off while subscribed keeps its receipt after unsubscription. +home=$(make_home subscribed-then-off) +owned "$INBOX_BIN" subscribe +id=$(run_inbox "$home" note --request-id late-1 --json 'handed off' | json_get id) +FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" bash -c '. "$1/bin/fm-wake-lib.sh"; fm_input_handoff "$2/state" gen-1 1 rec-1' check "$ROOT" "$home" \ + || fail "input handoff failed" +owned "$INBOX_BIN" unsubscribe +owned "$ROOT/bin/fm-wake-drain.sh" > "$home/drain.out" 2> "$home/drain.err" +seq=$(awk -F '\t' 'NF == 5 {print $2}' "$home/drain.out" | tail -1) +gen=$(sed -n 's/^WAKE_ACK_REQUIRED:.*--recovery-generation //p' "$home/drain.err") +owned "$INBOX_BIN" drain --ack "$id" >/dev/null || fail "owner handling after unsubscribe failed" +owned "$ROOT/bin/fm-wake-drain.sh" --ack-through "$seq" --recovery-generation "$gen" \ + || fail "owner ack after unsubscribe failed" +assert_equals 0 "$(count_wakes "$home")" "ack after unsubscribe retires the wake" +assert_equals 1 "$(run_inbox "$home" input-receipts | json_get records | python3 -c 'import ast,sys; print(sum(1 for r in ast.literal_eval(sys.stdin.read()) if "ack" in r))')" "handed-off input keeps one receipt" +pass "input handed off while subscribed keeps its receipt after unsubscription" + # Real watcher, no fake fleet tasks: a thirty-second poll is interrupted by # input; simultaneous ordinary events stay durable for the same drain. home=$(make_home input-watch) From 2f0a791c5b3258004ca9b85a73173d6499dd46d8 Mon Sep 17 00:00:00 2001 From: Brian Lockhart Date: Wed, 30 Sep 2026 01:11:10 -0600 Subject: [PATCH 8/8] no-mistakes(ci): I fixed the one failure in "Behavior portable serial 2". It came from the test file this PR adds, not from the product code. tests/fm-inbox.test.sh stopped at "not ok - owner registration failed" with "only the owning session may change the input subscription". The other 22 scripts in the shard passed or were skipped by design. Cause: the test's owned() helper runs a fake `claude` harness, which is a symlink to /bin/bash. It runs `bash -c 'printf $$ > state/.lock; "$@"'`. Newer bash (the Linux runner, and bash 5.3 locally) replaces its own process with the last command in a -c string instead of starting a child. So the fake harness process whose pid is in .lock disappears. fm_session_lock_owned_by_self then no longer finds that pid among the running command's parent processes and refuses. macOS /bin/bash 3.2 does not do this, which is why the test passed locally before. Rule that must hold: the process named in state/.lock must stay alive as a parent of every command owned() runs. owned() is the only place that sets this up, and all of the test's owner-side commands go through it (subscribe and unsubscribe, drain --ack, fm-wake-drain.sh --ack-through). So one change covers all of them. Fix (test only, tests/fm-inbox.test.sh): the -c string is now `...; "$@"; exit`. Because `"$@"` is no longer the last command, bash cannot replace the harness process. A bare `exit` keeps the command's exit status, so the checks that expect a refusal (for example the refused --ack-through at line 583) still work. I added a two-line comment explaining why the exit is there. Checks run: - With the fake harness pointed at bash 5.3 and without the fix, the test fails exactly as in CI ("owner registration failed"). - With the fix, it passes on bash 5.3 and on macOS /bin/bash 3.2: exit 0, no "not ok" lines. - `shellcheck -x tests/fm-inbox.test.sh` reports nothing --- tests/fm-inbox.test.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/fm-inbox.test.sh b/tests/fm-inbox.test.sh index 05142e7122e..32cd3264ced 100644 --- a/tests/fm-inbox.test.sh +++ b/tests/fm-inbox.test.sh @@ -550,9 +550,11 @@ home=$(make_home subscribed) mkdir -p "$TMP_ROOT/owner-bin" ln -s /bin/bash "$TMP_ROOT/owner-bin/claude" owned() { + # The trailing exit keeps newer bash from exec-replacing the owner harness + # with the last command, which would drop it from the command's ancestry. # shellcheck disable=SC2016 # The fixture harness expands its own environment. FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" FM_CONFIG_OVERRIDE="$home/config" \ - "$TMP_ROOT/owner-bin/claude" -c 'printf "%s\n" "$$" > "$FM_HOME/state/.lock"; "$@"' owner "$@" + "$TMP_ROOT/owner-bin/claude" -c 'printf "%s\n" "$$" > "$FM_HOME/state/.lock"; "$@"; exit' owner "$@" } needed() { bash -c '. "$1/bin/fm-supervision-lib.sh"; fm_supervision_needed "$2/state"' check "$ROOT" "$home"