Skip to content

fix(bin): throttle declared external-wait wake resurfacing - #2884

Closed
NicoKJarvinen wants to merge 2 commits into
kunchenguid:mainfrom
NicoKJarvinen:fm/fix-watch-pause-resurface-default
Closed

NicoKJarvinen wants to merge 2 commits into
kunchenguid:mainfrom
NicoKJarvinen:fm/fix-watch-pause-resurface-default

Conversation

@NicoKJarvinen

Copy link
Copy Markdown

Intent

Fix firstmate issue #2873: a declared external-wait pause must not re-surface as a stale wake on every poll; it must re-surface once per long cadence. The established root cause is that bin/fm-watch.sh reads PAUSE_RESURFACE_SECS from FM_PAUSE_RESURFACE_SECS_DEFAULT without directly sourcing bin/fm-classify-lib.sh, where the single default FM_PAUSE_RESURFACE_SECS_DEFAULT=3600 is defined. The empty value defeats the throttle comparison. Do not re-derive or broaden that diagnosis.

Make the watcher obtain the shared default without hardcoding 3600 a second time. Keep one owner for the default, and prefer the existing source conventions. Harden the comparison so unset, empty, or nonnumeric overrides cannot silently disable the throttle; use a safe shared fallback or a loud failure. Do not change the wedge-escalation path or stale threshold and do not broaden into a supervision refactor.

bin/fm-supervise-daemon.sh already directly sources bin/fm-classify-lib.sh, so it does not have the same missing-default source defect. It must use the same safe cadence resolution so invalid overrides are handled consistently. State explicitly in the PR that the daemon was already sourcing the classifier and was not affected by the missing direct source, while the watcher was fixed to source it directly.

Add or retain executable behavior tests proving the watcher resolves a numeric default, invalid overrides fall back safely, and the throttle behavior itself: a paused task inside the window does not re-emit, and after the window it emits once rather than on every poll. Cover daemon cadence fallback where applicable. Keep existing watcher tests green; bin/fm-watcher-lock.test.sh may flake under full concurrent load per issue #2844 and must be checked in isolation if it fails.

The issue title saying the default is never defined is inaccurate. The default is defined in bin/fm-classify-lib.sh, but it was in the wrong file for the watcher consumer. Say this explicitly in the PR so the issue text does not mislead future readers. Reference issue #2873 in the PR.

Constraints: shellcheck-clean; use the repository's test conventions; never hardcode a second 3600; do not change wedge escalation or stale detection thresholds; do not merge the PR. Delivery is no-mistakes with standard execution, and run the pipeline through a green PR.

Validation evidence already established: commit a1b1d78 implements the fix. bin/fm-lint.sh and the focused watcher and daemon tests pass. The full tests/fm-daemon.test.sh reports not ok - wedge marker unexpectedly persisted in an unwritable state directory under the current branch. The same test run on the unmodified default origin/main at f170ced reports the identical failure. Both runs were under uid 0, and a direct chmod u-w probe still allowed root to create a file, proving this is a pre-existing root-only environment artifact in the test's unwritable-directory assumption, not a regression. State the exact evidence and command comparison in the PR rather than working around the test.

What Changed

  • Fixes fm-watch.sh: declared external wait re-surfaces every poll — PAUSE_RESURFACE_SECS default is never defined #2873 by sourcing bin/fm-classify-lib.sh directly in the watcher, ensuring it resolves the shared declared-wait cadence default. The default is defined in the classifier; the daemon already sourced it and was not affected by the missing direct source.
  • Adds one shared cadence resolver that falls back safely for blank or nonnumeric overrides, then uses it in both the watcher and away-mode daemon without duplicating the default.
  • Updates configuration and AFK documentation plus executable watcher and daemon tests for default resolution, invalid-override fallback, and long-cadence paused rechecks.

Risk Assessment

✅ Low: The change is well-bounded and no source-verifiable defects were found.

Testing

Watcher tests demonstrated cadence resolution, invalid fallback, pause throttling, and one-per-window re-surfacing without wedge escalation. Daemon tests demonstrated long-cadence re-surfacing and invalid fallback. The isolated watcher-lock suite passed. The daemon suite reproduced the documented root-only unwritable-directory failure; the supplied baseline has the identical failure, and the uid-0 probe confirms the environment cause.

Evidence: Watcher cadence evidence

ok - the watcher resolves the shared pause cadence and falls back safely for invalid overrides ok - a declared pause is absorbed on first sight, then re-surfaced as a recheck past the threshold, never wedge-escalated ok - exited declared-pause and captain-held panes use bounded pause cadence while a live decision gate still surfaces once

ok - signal_reason_is_actionable: benign absorbed, captain verbs and coalesced batches surfaced
ok - stale_is_terminal: terminal status surfaces, non-terminal and no-status are benign
ok - scan_captain_relevant_statuses lists only captain-relevant statuses
ok - classifier primitives: keyed decisions and activity phases, captain relevance, window-to-task, and overrides
ok - the watcher resolves the shared pause cadence and falls back safely for invalid overrides
ok - crew_is_provably_working: only working+run-step/pane is provable; idle/finished/parked/failed/unknown surface
ok - status_is_paused: only the leading paused verb matches, paused is not captain-relevant, and the two declared-wait verbs stay separable
ok - crew_absorb_class: working/paused/none from one read; crew_is_paused and crew_is_provably_working agree
ok - crew_worktree_written_since: real writes are evidence; no worktree, no anchor, quiet trees, .git churn and a mate's own home are not
ok - an empty FM_WORKTREE_WRITE_PRUNE widens the probe to the whole depth-bounded tree instead of disabling it
ok - an empty FM_WORKTREE_WRITE_PRUNE exported into the environment prunes nothing, widening the probe
ok - the worktree write probe is wall-clock bounded, and hitting the bound reads as no write evidence
ok - signal_crew_provably_working: benign only when every referenced crew is provably working
ok - a secondmate's status signal is never absorbed as provably working; crewmates are unaffected
ok - a no-verb signal whose crew is provably working is absorbed (no exit, no queue, suppressor advanced, beacon present)
ok - a bare turn-end whose crew is provably working (busy pane) is absorbed
ok - a bare turn-end whose crew is not provably working is surfaced (the swallowed-finish fix)
ok - a no-verb working: note whose crew is idle with no running pipeline is surfaced
ok - a secondmate's status note surfaces even while its own agent is busy
ok - a self-announced close never wakes its own home, and the next real note still does
ok - captain-relevant signal is surfaced (queue + exit) and marked surfaced
ok - a stale pane sitting on a terminal status is surfaced (queue + exit)
ok - a stale terminal-looking status is overridden and absorbed while a run is actively working, then wedge-escalated
ok - provably-working non-terminal stale is absorbed on first sight, then wedge-escalated past the threshold
ok - consecutive wedge escalations on the same pane accumulate and demand deep inspection at the threshold
ok - a pane becoming active again resets the consecutive wedge-escalation counter
ok - a busy worker below the turn-age bound remains working with no escalation
ok - a busy worker with a stable pane hash still escalates once its completed-turn age reaches the bound
ok - a busy worker whose pane hash changes every poll still escalates once its completed-turn age reaches the bound
ok - touching a busy worker's completed-turn marker resets the age and prevents an old-age escalation
ok - repeated busy turn-age escalations reuse the existing escalation counter and demand deep inspection at the threshold
ok - the production default busy-turn-age bound is 3600s (5min under does not wedge, 66min over does)
ok - a busy pane under a declared pause is rechecked on the long cadence, and lifting the pause restores the wedge escalation
ok - a not-provably-working non-terminal stale is surfaced immediately (never left to wait out the timer)
ok - a declared pause is absorbed on first sight, then re-surfaced as a recheck past the threshold, never wedge-escalated
ok - exited declared-pause and captain-held panes use bounded pause cadence while a live decision gate still surfaces once
ok - a declared paused secondmate re-surfaces on the bounded normal-mode cadence
ok - a captain-held secondmate re-surfaces on the bounded normal-mode cadence
ok - a non-paused secondmate retains normal stale suppression
ok - a resumed secondmate clears pause and stale tracking before stale exemption
ok - unchanged stale hashes reclassify when a crew enters or leaves pause
ok - a declared pause is periodically rechecked against authoritative active-run state
ok - a paused status overridden by authoritative working preserves its wedge timer and escalates
ok - matching non-terminal stale suppressors repair missing or corrupt stale-since timers
ok - a quiet pane writing its own worktree is deferred, while one writing nothing still wedge-escalates on the unchanged schedule
ok - a write deferral re-surfaces once on the bounded pause cadence, so a churning worktree cannot stay invisible
ok - a secondmate's own home supervision churn is not crew write evidence, so a pane recording that home keeps the unchanged escalation schedule
ok - an idle-window timer repair drops a finished write-deferral chain, so the next deferral gets a fresh re-surface window
ok - both first-sight paths through a captain-relevant status drop a finished write-deferral chain with the idle window
ok - triage log capping handles wc byte counts with leading spaces
ok - a captured process-event result wakes a healthy watcher proactively, with no manual drain
ok - an unacknowledged process-event result re-drains until handling is acknowledged
ok - complete process-event queue keys map to distinct seen markers
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 473587.1787507757.rUydqV
ok - queue revalidation, proactive output, and marker commit serialize with drain
/root/.no-mistakes/worktrees/7f0ec18181b6/01M0QVWZ8Y8QGXBZFMFNF5HYV5/bin/fm-push-transition-lib.sh: line 96: echo: write error: Broken pipe
tests/wake-helpers.sh: line 282: 475300 Killed                  PATH="$dir/fakebin:$PATH" FM_HOME="$dir" FM_PROCEVENT_CLAIM_ROOT="$dir/claims" FM_CREW_STATE_BIN="$dir/fakebin/fm-crew-state.sh" FM_POLL=0.2 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 "$WATCH" > "$out"
tests/wake-helpers.sh: line 282: 476198 Killed                  PATH="$dir/fakebin:$PATH" FM_HOME="$dir" FM_PROCEVENT_CLAIM_ROOT="$dir/claims" FM_CREW_STATE_BIN="$dir/fakebin/fm-crew-state.sh" FM_POLL=0.2 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 "$WATCH" > "$out"
ok - surfacing failures replay until post-handling acknowledgement
ok - marker failure exits through the shared wake owner, releases its lock, and replays later
ok - a heartbeat with no captain-relevant change is absorbed and backs off the cadence
ok - heartbeat backstop fail-safe surfaces a captain-relevant status the per-wake path missed
ok - the liveness beacon stays fresh while the watcher absorbs benign wakes (fm-guard never false-alarms)
ok - with .afk present the watcher reverts to one-shot so the daemon owns triage (no double-triage)
ok - AFK changed paused panes hand off plain stale identities for daemon-owned pause triage
Evidence: Daemon cadence evidence

ok - housekeeping re-surfaces a stale declared pause on the long cadence and resets its window ok - the daemon falls back to the shared pause cadence for an invalid override not ok - wedge marker unexpectedly persisted in an unwritable state directory

ok - fm-afk-start.sh fails before daemon startup when the afk flag cannot be written
ok - fm-afk-start.sh ignores stale pidfile-only live pids
ok - fm-afk-start.sh reclaims stale daemon locks whose live pid identity no longer matches
ok - supervise daemon state root is scoped by FM_HOME
ok - routine signal self-handles
ok - captain-relevant status verbs escalate
ok - check + unknown escalate; heartbeat self-handles
ok - transient stale self-handles and records a persistence marker
ok - enriched stale wedges bypass status absorption without disturbing busy workers
ok - stale + terminal status escalates immediately
ok - paused reasons with captain phrases remain pause-classified
ok - a captain-held transfer classifies as pause, not as a wedge candidate
ok - handle_wake on a paused stale records a pause marker, drops the wedge marker, and does not escalate
ok - handle_wake records a declared pause from a routine signal for long-cadence rechecks
ok - a terminal signal clears pause and stale tracking across both supervisors
ok - housekeeping migrates a normal-watcher's declared pause into daemon tracking
ok - housekeeping clears an already-resumed watcher pause across both supervisors
ok - housekeeping seeds pause tracking from status without a watcher marker
ok - persistent stale escalates after threshold and clears its marker
ok - resumed (busy) stale clears its marker without escalating
ok - housekeeping re-surfaces a stale declared pause on the long cadence and resets its window
ok - the daemon falls back to the shared pause cadence for an invalid override
ok - housekeeping re-surfaces a forgotten captain hold on the long cadence and resets its window
ok - housekeeping clears a paused marker whose pane became busy again, without escalating
ok - housekeeping clears a paused marker once the crew is no longer declaring the pause
ok - housekeeping clears the pause marker once a captain hold is answered
ok - housekeeping moves an existing stale marker to pause before wedge escalation
ok - housekeeping moves a captain hold's existing stale marker to pause before wedge escalation
ok - housekeeping clears tracking when a crew leaves pause
ok - persistent herdr stale resolves the target from metadata and escalates
ok - herdr idle busy-footer stale clears through capture corroboration
ok - resumed herdr stale clears through backend-aware busy state
ok - persistent Orca stale resolves the terminal from metadata
ok - multiple escalations flush as a single batched digest
ok - batch flush measures max-delay from the first append, not the last
ok - catch-all scan escalates a missed terminal once, not twice
ok - handle_wake routes routine->self and captain->escalate
ok - INJECT_SKIP forces self-handle, bypassing captain-relevant classification
ok - is_wake_reason distinguishes watcher wake reasons from singleton-status stdout
ok - terminal-stale escalate removes its marker so housekeeping does not re-escalate
ok - captain signal escalate marks seen so the catch-all scan does not re-fire
ok - _collapse_newlines replaces newlines with literal separator
ok - afk flag absent: daemon does not inject, buffer preserved
ok - busy-guard defers injection when supervisor pane is busy
ok - marker detection: marker -> stay afk, no marker -> exit afk
ok - /afk invocation is exempt from afk exit (no self-cancel)
ok - should_exit_afk returns false when afk is not active
ok - strip_injection_marker removes the sentinel marker cleanly
ok - pane_input_pending detects partial input on the cursor line
ok - pane_input_pending: a blank unidentified cursor row defers (strict container-proof rule)
ok - pane_input_pending: only proven empty agent prompts pass
ok - fm_tmux_composer_state: a bare shell prompt ($/%/#/>) reads unknown, never empty (dead-shell injection safety)
ok - fm_tmux_composer_state: a bordered composer box and bare agent glyphs (❯/›) still read empty
ok - fm_tmux_composer_state: only matching edge borders form a composer box
ok - pane_input_pending preserves bright placeholder-like drafts in styled captures
ok - classify_signal dedupes against the catch-all scan seen marker
ok - classify_stale dedupes against the signal path seen marker
ok - AFK nonterminal working:+merged keeps wedge aging and re-escalates at bound
ok - genuine done: and merge-check events still escalate
ok - pane_input_pending: an idle bordered composer is NOT pending (afk-invx-i5)
ok - pane_input_pending: text inside a bordered composer is still pending
ok - submit-ACK confirms a submit when the composer returns to a bordered-empty box
ok - submit-ACK reports pending on a persistently swallowed Enter (type-once)
ok - max-defer on an empty stuck pane types once, alarms, and preserves the buffer
ok - max-defer flushes and clears the buffer on an empty bordered pane
ok - max-defer on a pending composer alarms without typing
ok - normal flush clears a stale wedge marker
ok - below MAX_DEFER: no inject, no alarm, buffer preserved
ok - max-defer does not flush or alarm while afk is inactive
ok - library mode: sourcing the daemon defaults FM_WEDGE_ALARM_EXEC to discard (no test can fire a real notification)
ok - wake helpers replace inherited notifier overrides with the safe recorder
ok - the discard seam suppresses every notifier, including command: (fires nothing)
ok - direct notifier helpers honor the discard seam, including command:
ok - osascript channel routes through the notifier seam with the summary (never a real notification)
ok - herdr channel routes through the notifier seam with the summary (never a real notification)
ok - command channel runs the captain command with the summary on $1 and on stdin
ok - command channel failures redact configured commands while logging their exit status
ok - unknown channel directives are redacted while the alarm keeps running
ok - off disables every active alert regardless of directive position (marker and tmux flash are unaffected)
ok - auto resolves to the macOS osascript notifier on Darwin (default-on)
ok - auto on a non-macOS platform selects no built-in OS channel (the marker or a configured command carries it)
ok - config/wedge-alarm selects every configured channel and skips comment and blank lines
ok - a failing channel logs and falls back to the next channel, never crashing the alarm
ok - a hung notifier is bounded, logged, and falls through to the next channel
ok - a backgrounded command notifier remains bounded until its process group is reaped
ok - a hung notifier override is bounded, logged, and proceeds to the next channel
[1]+  Terminated              sh -c 'sleep 30 & printf "%s" "$!" > "$1"; wait' sh "$child_file"
ok - daemon shutdown stops and reaps the active notifier process group
ok - inject_wedge_alarm writes the marker AND emits the active alert even with no tmux status-line (herdr backend)
not ok - wedge marker unexpectedly persisted in an unwritable state directory
Evidence: Unwritable-directory environment probe

uid=0 chmod=u-w create_file=allowed

uid=0 chmod=u-w create_file=allowed
Evidence: Isolated watcher-lock suite log
ok - simultaneous watcher starts leave exactly one live process
ok - fm_pid_identity real ps fallback is locale-invariant
ok - fm_pid_identity is locale-invariant across LC_ALL/LC_TIME
ok - /proc process identity ignores simulated btime changes
ok - /proc process identity detects pid reuse
ok - MSYS /proc process identity regression skipped on non-Windows host
ok - killed watcher stale lock is reclaimed
tests/fm-watcher-lock.test.sh: line 1038: 504309 Killed                  FM_STATE_OVERRIDE="$state" bash -c '
    . "$1"
    fm_lock_remove_path() {
      if [ "$1" = "$STATE/.watch.lock" ]; then
        kill -KILL "${BASHPID:-$$}"
      fi
      return 1
    }
    fm_lock_try_acquire "$2"
  ' _ "$LIB" "$lockdir" > /dev/null 2>&1
ok - stale watcher reclaim publishes durable recovery evidence before clear
ok - live watcher lock with stale heartbeat is actionable
ok - guard banner leads when down with pending wakes (repair-after-drain) and stays silent when live and fresh
ok - concurrent fm_lock_try_acquire yields exactly one winner
ok - dead-pid stale lock is reclaimed by a single acquirer
ok - concurrent stale-lock steal yields exactly one winner
ok - live steal mutex is not reclaimed
ok - live-held lock is not stolen
ok - empty mid-acquire lock keeps a minimum grace
ok - late original claimant cannot claim a recreated lock
ok - paused mid-acquire claimant backs off to active stealer
ok - watch restart preserves recovery without signaling a reused pid
ok - watch restart attaches to a verified healthy peer and later surfaces a successor gap
ok - watcher self-evicts when the lock pid no longer names it
ok - arm turns clean self-eviction without a successor into a typed failure
ok - arm attaches to a live fresh watcher and fails loudly when that cycle has no successor
ok - attached arm signals record a classified lifecycle entry
ok - arm starts cleanly and resurfaces recovery after a dead-pid lock
ok - arm cleans child watcher and temp output on HUP
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 517540.1787507905.dOZfnp
ok - arm propagates an immediate watcher wake before confirmation
ok - arm attaches to a peer watcher after child stands down and surfaces a missing successor
watcher: lock held by live pid 518594 but heartbeat is stale for 840830309s (>300s); inspect or stop that watcher before re-arming.
ok - arm reports FAILED and exits non-zero when no fresh watcher can be confirmed
ok - cycle-exit ledger links a verified successor and remains size-capped
ok - SIGSTOP distinguishes live PID from stale beacon and termination records the exit class
- Outcome: ⚠️ 1 warning across 1 run (7m33s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

⚠️ **Test** - 1 warning
  • ⚠️ tests/fm-daemon.test.sh:1663 - The focused daemon suite reports the known wedge marker unexpectedly persisted in an unwritable state directory failure. This is a root-only environment artifact: the run is uid 0, and a direct chmod u-w probe still allows file creation. The supplied baseline comparison reports the identical failure on unmodified commit f170ced, so this is not a regression.
  • rtk bash tests/fm-watch-triage.test.sh
  • rtk bash tests/fm-daemon.test.sh
  • rtk bash tests/fm-watcher-lock.test.sh (isolated)
  • rtk id -u
  • direct chmod u-w/file-create probe under /tmp/no-mistakes-evidence/01M0QVWZ8Y8QGXBZFMFNF5HYV5
  • rtk git status --short
⚠️ **Document** - 1 warning
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (2): Last reviewed commit: "no-mistakes(document): Document pause ca..." | Re-trigger Greptile

@NicoKJarvinen
NicoKJarvinen force-pushed the fm/fix-watch-pause-resurface-default branch from 04eb4a1 to 0ffd9f0 Compare August 23, 2026 19:04
@NicoKJarvinen

Copy link
Copy Markdown
Author

Closing: out of scope. Work is scoped to the kaamos and devflow repositories only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fm-watch.sh: declared external wait re-surfaces every poll — PAUSE_RESURFACE_SECS default is never defined

1 participant