diff --git a/bin/fm-claude-stop-autoarm.sh b/bin/fm-claude-stop-autoarm.sh index f42e0846cb6..71872d406bf 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..cbb3faff48a 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 + 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" + 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 c4d51a24731..7c78eee5a7a 100755 --- a/bin/fm-wake-lib.sh +++ b/bin/fm-wake-lib.sh @@ -1954,6 +1954,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 ! { @@ -1968,6 +1972,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 @@ -2152,6 +2163,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" @@ -2176,9 +2192,68 @@ 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_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 + 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" ] || [ -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. + # shellcheck source=bin/fm-session-lock-lib.sh + . "${BASH_SOURCE[0]%/*}/fm-session-lock-lib.sh" + 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 + 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 3a996a0320e..9315f02c634 100755 --- a/bin/fm-watch-arm.sh +++ b/bin/fm-watch-arm.sh @@ -415,6 +415,16 @@ 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" ] && cycle_delivered_reason \ + && [ "${DELIVERED_REASON#check: captain-input }" != "$DELIVERED_REASON" ]; then + printf '%s\n' "$DELIVERED_REASON" + 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 16b7845dfb2..75e83372fbc 100755 --- a/bin/fm-watch.sh +++ b/bin/fm-watch.sh @@ -2336,6 +2336,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 @@ -2370,7 +2400,7 @@ event_wait_or_sleep() { done < <(recorded_windows) if [ "${#windows[@]}" -eq 0 ]; then - sleep "$POLL" + input_wait "$POLL" return fi @@ -2386,7 +2416,7 @@ event_wait_or_sleep() { _event_cap_fails=0 fi if [ "$_event_cap_ok" != 1 ]; then - sleep "$POLL" + input_wait "$POLL" return fi @@ -2403,7 +2433,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 @@ -2715,6 +2745,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 @@ -2735,6 +2767,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 @@ -2746,6 +2779,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. @@ -2754,6 +2789,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 @@ -2761,6 +2798,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 @@ -2782,6 +2820,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 @@ -2793,6 +2833,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 @@ -2924,7 +2965,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 @@ -3306,5 +3347,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/scripts.md b/docs/scripts.md index e6e8da4bb6d..72195efab7b 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -160,7 +160,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 new file mode 100644 index 00000000000..ffec317c81d --- /dev/null +++ b/docs/verification/captain-input.md @@ -0,0 +1,76 @@ +# Continuous captain input verification + +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 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, 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 | 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 | +| 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 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 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 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. + +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 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. +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 profile + +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 listener 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 listener acceptance | 650 ms | + +Interval medians are independent and should not be summed as a measured whole-turn percentile. +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. +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/verification/supervision.md b/docs/verification/supervision.md index 11bf2525fb9..3f7f16997ec 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 b82ccf2e712..2b63a6805c2 100644 --- a/docs/watcher-continuity.md +++ b/docs/watcher-continuity.md @@ -32,6 +32,23 @@ 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. +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. + +#### 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. diff --git a/tests/fm-claude-stop-autoarm.test.sh b/tests/fm-claude-stop-autoarm.test.sh index 0cae21c30e9..2efd7073e14 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" : > "$dir/config/supervision-host-off" 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) ---------------------- @@ -1750,6 +1767,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 @@ -1767,3 +1809,38 @@ 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_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 + 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 "" "$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 +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..32cd3264ced 100644 --- a/tests/fm-inbox.test.sh +++ b/tests/fm-inbox.test.sh @@ -544,3 +544,154 @@ 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() { + # 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"; "$@"; exit' 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" +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" + +# 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" + +# 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) +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 1c3fa7fa0bd..c240c89e365 100755 --- a/tests/fm-watch-arm.test.sh +++ b/tests/fm-watch-arm.test.sh @@ -1744,3 +1744,15 @@ test_take_over_attaches_to_a_cycle_the_named_arm_does_not_own test_take_over_owns_a_fresh_cycle_and_keeps_queued_work_surfacing test_take_over_preserves_downtime_from_watcher_self_exit test_opencode_arm_plugin_decides_with_the_shared_predicate + +# 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"