Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bin/fm-claude-stop-autoarm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 79 additions & 2 deletions bin/fm-inbox.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,20 @@
# fm-inbox.sh reply [--json] <id> <text>... | reply [--json] <id> -
# fm-inbox.sh receipts [--after <cursor>] [--all-pending] [--all-handled] [--all-replies]
# fm-inbox.sh ready
# fm-inbox.sh subscribe | unsubscribe | input-receipts
# fm-inbox.sh say [<file.wav>] (default: audio on stdin)
# fm-inbox.sh status
# fm-inbox.sh ask <question>...
# fm-inbox.sh list
# fm-inbox.sh drain [--ack <id>...]
#
# 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
Expand Down Expand Up @@ -1117,25 +1125,94 @@ cmd_drain() {
if [ "${1:-}" = "--ack" ]; then
shift
[ "$#" -gt 0 ] || die "usage: fm-inbox.sh drain --ack <id>..."
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 <id>...\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 "$@" ;;
Expand Down
29 changes: 29 additions & 0 deletions bin/fm-input-wait.py
Original file line number Diff line number Diff line change
@@ -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 <notification-file> <observed-value> <seconds>
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]))
6 changes: 4 additions & 2 deletions bin/fm-supervision-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions bin/fm-wake-drain.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
73 changes: 73 additions & 0 deletions bin/fm-wake-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -1819,6 +1819,10 @@ fm_autoarm_write_owned() { # <state-dir> <gen> <outcome> [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 ! {
Expand All @@ -1833,6 +1837,13 @@ fm_autoarm_write_owned() { # <state-dir> <gen> <outcome> [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
Expand Down Expand Up @@ -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"
Expand All @@ -2041,9 +2057,66 @@ 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() { # <state> <generation> <session-pid> <recovery-generation>
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() { # <cutoff> <owned-sequence-file> <recovery-generation>
local cutoff=$1 rows=$2 recovery=$3 epoch seq kind key payload id tmp
[ -f "$STATE/.captain-input" ] || return 0
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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
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 <kind>
# Print the distinct keys currently queued for <kind>, oldest first. Read under
# the append lock so a concurrent append is never observed half-written. The
Expand Down
16 changes: 14 additions & 2 deletions bin/fm-watch-arm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading