Skip to content

fix(bin): only resurface recovery episodes that have something to present - #2784

Closed
EternalTime wants to merge 27 commits into
kunchenguid:mainfrom
EternalTime:fm/fm-rearm-resurface-empty-wakes
Closed

EternalTime wants to merge 27 commits into
kunchenguid:mainfrom
EternalTime:fm/fm-rearm-resurface-empty-wakes

Conversation

@EternalTime

Copy link
Copy Markdown

Intent

Stop the firstmate watcher waking firstmate with nothing to report, without breaking the resurfacing it exists to do.

Observed symptom: in the captain's main home, 'check: rearm-resurface' fired eleven times in a row over roughly fifteen minutes, and every one cost a visible turn and found nothing. Verified at each occurrence: bin/fm-wake-drain.sh returned empty, zero state/.meta so no work was under way, zero state/.check.sh so nothing was armed, and state/.last-watcher-beat was current so the watcher itself was healthy. The fleet had just been fully torn down. With no work under way and no armed checks, the correct behaviour is silence.

This is supervision machinery. Breaking real resurfacing is far worse than leaving the noise in place; that priority was explicit and drives several choices in the diff.

Required and done: the loop was reproduced end to end first, in a disposable FM_HOME, before anything was changed. The reproduction confirmed the suspected cause and refined it: an ordinary watcher close publishes a downtime episode unconditionally, and because every re-arm closes the previous watcher, a torn-down fleet re-arms straight into another empty episode, so resurface_after_downtime delivers a recovery wake whose handling drain presents zero bytes.

Two candidate defects were named up front, with a requirement to address both or give a written reason for only one.
Defect 1 (resurface fires with nothing to resurface) was confirmed and fixed: the wake is now gated on the three sources docs/watcher-continuity.md says the recovery presentation contains - unacknowledged queue rows, still-open decisions, and unread informational status lines - and an episode proved empty is retired under the queue lock fm_wake_append holds, so later arms cannot re-fire it.
Defect 2 (the marker is not cleared by the wake meant to consume it) was deliberately REFUTED rather than fixed, and this is intentional, not an oversight. Preserving the episode across delivery is the durability guarantee behind the release-lock-existing transition: the wake is delivered but not yet handled, and preserving it is what lets an interrupted handling turn re-drain the same work. Commit f9b9d43 and tests/fm-watch-arm.test.sh's interrupted-handling case pin that behaviour. Clearing the marker at delivery time would lose work on any interruption, so release-lock-existing is deliberately untouched.

Deliberate implementation choice worth knowing: recovery_has_presentable_work uses the whole-file scan_open_decisions rather than its incremental sibling scan_open_decisions_incremental. The incremental one writes a per-task cursor that the unread-status scan falls back to when no presentation manifest exists, so using it made the watcher silently blind the very drain the check protects. That was caught by the unread-note regression test and is why the seemingly more efficient incremental variant is not used here. Any failure to read one of the three sources is deliberately treated as work present, because a redundant wake costs a turn while a suppressed one costs the work.

Tests were required to be colocated in tests/ as .test.sh, extending an existing script rather than adding a runner, and the resurfacing-still-works test was required to be written first because it is the one protecting the feature. Both are in tests/fm-watch-arm.test.sh: one case proves each of the three presentation sources alone still resurfaces after a real down stretch, and one proves a fully torn-down fleet re-arms silently across consecutive cycles. The silence case was verified to fail against the unfixed watcher with the exact reported symptom, and the protective case passes against both the old and new watcher so it protects the feature rather than the fix.

Deliberate test change worth knowing: three pre-existing cases (marker publication failure, malformed marker quarantine, and reused-pid/dead-pid lock reclaim, across tests/fm-watch-arm.test.sh and tests/fm-watcher-lock.test.sh) used the empty-fleet recovery wake itself as the observable proof that lock or marker evidence had survived. Those assertions were asserting the noise being removed. They now seed a real open decision via a shared seed_open_decision helper in tests/wake-helpers.sh, so they still prove evidence retention while exercising genuine resurfacing. This is an intended change to existing assertions, not an incidental one.

Constraints: bin/*.sh must pass shellcheck and bin/fm-lint.sh must pass; both were run clean. Markdown in this repo is one full sentence per line, plain dashes, and no em dash anywhere. This is firstmate's own shared tracked material, so .agents/skills/firstmate-coding-guidelines/SKILL.md applies, including its one-owner rule: docs/watcher-continuity.md is the single owner of the recovery contract and was patched in place rather than having a second copy of the contract added elsewhere, and AGENTS.md was deliberately left unchanged to preserve its size discipline.

What Changed

  • bin/fm-watch.sh now gates check: rearm-resurface behind a new recovery_has_presentable_work, which reads the three sources docs/watcher-continuity.md names as the recovery presentation - unacknowledged queue rows, still-open decisions, and unread informational status lines - through their owners, read-only, and answers "work present" on any read failure. When all three are empty, retire_empty_recovery_episode acknowledges that downtime generation under the same queue lock fm_wake_append holds, so a torn-down fleet stops re-firing the episode on every re-arm; release-lock-existing is deliberately untouched so a delivered-but-unhandled wake still survives an interrupted handling turn.
  • bin/fm-classify-lib.sh adds FM_DECISION_OPENING_VERB_RE and pre-filters each .status file (rejecting symlinks first) before scan_open_decisions runs its per-line fold, keeping the fleet-wide scan off the watcher's arm critical path without changing its output; bin/fm-test-run.sh maps bin/fm-pr-check-migrate.sh into the watcher family, and docs/watcher-continuity.md narrows its unconditional-resurface claim and records the retirement and reclaim paths.
  • tests/fm-watch-arm.test.sh gains cases proving each presentation source alone still resurfaces after a real down stretch, that an empty fleet re-arms silently across consecutive cycles, and that the stale-lock reclaim path behaves the same way; a shared seed_open_decision helper in tests/wake-helpers.sh reseeds three pre-existing cases in that suite and tests/fm-watcher-lock.test.sh that had been using the removed empty wake as their proof of evidence retention.

Note: the branch also carries 23 commits that exist only on the local main (local-only project landing on secondmate routes, the /updatethecaptain loop, AGENTS.md guidelines). They are unrelated to this fix and drop out of the delta once main is pushed to origin.

Risk Assessment

✅ Low: Round 4 changes no executable code - a comment-stripped diff of bin/fm-watch.sh and tests/fm-watch-arm.test.sh against round 3 is identical - and it resolves the last outstanding concern by making every code, test, and documentation claim match source, with the one race-only state now honestly recorded as deliberately untested rather than silently claimed as covered.

Testing

I reproduced the reported symptom first, end to end in a disposable FM_HOME driving the real arm, watcher, and drain binaries: against the pre-fix watcher, 9 of 11 consecutive re-arms over a fully torn-down fleet delivered check: rearm-resurface and every one of those drains presented zero bytes, with zero state/.meta, zero state/.check.sh, and a current .last-watcher-beat at each occurrence, matching the captain's report. Running the identical script against this change produced 0 of 11 wakes and 11 silent arms, and in the same run a watcher that went down with a real open decision still emitted the recovery wake and still presented the OPEN DECISIONS block, so the resurfacing the change exists to protect is intact. On the automated side, the full fm-watch-arm and fm-watcher-lock suites pass including the three new cases and the reseeded pre-existing ones, and every consumer of the changed decision-scan pre-filter passes unchanged; the changed-test mapping was confirmed to select the watcher suites for this diff. This change has no UI surface - it is a background supervision daemon whose only end-user surface is the wake line and the drain transcript, so the CLI transcripts above are the reviewer-visible evidence rather than screenshots. No failures or flakes were observed, the worktree is clean, and the temporary pre-fix tree used for the comparison was removed.

Evidence: Before/after CLI transcript summary: 9 of 11 empty wakes before, 0 of 11 after, resurfacing intact

BEFORE | re-arm 1: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 2: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 3: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 4: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 5: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 6: SILENT (watcher still live, no wake) drain presented 0 bytes BEFORE | re-arm 7: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 8: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 9: check: rearm-resurface drain presented 0 bytes BEFORE | re-arm 10: SILENT (watcher still live, no wake) drain presented 0 bytes BEFORE | re-arm 11: check: rearm-resurface drain presented 0 bytes BEFORE | RESULT: 9 of 11 re-arms woke firstmate; 2 stayed silent AFTER | re-arm 1..11: SILENT (watcher still live, no wake) drain presented 0 bytes AFTER | RESULT: 0 of 11 re-arms woke firstmate; 11 stayed silent AFTER | --- Phase 3: the same home, but one real open decision is waiting ------ AFTER | re-arm after downtime: check: rearm-resurface AFTER | $ bin/fm-wake-drain.sh AFTER | OPEN DECISIONS (still open, folded from the durable status logs - not just the latest line): AFTER | held [key=ship-the-release] needs-decision: fixture is held for a decision

Reported symptom reproduced end to end in a disposable FM_HOME, then re-run
against this change. Same script, same fixture, only bin/fm-watch.sh differs.

BEFORE | --- Phase 2: 11 consecutive re-arms over the torn-down fleet -------------
BEFORE |   re-arm  1: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  2: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  3: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  4: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  5: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  6: SILENT (watcher still live, no wake)       drain presented 0 bytes
BEFORE |   re-arm  7: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  8: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm  9: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   re-arm 10: SILENT (watcher still live, no wake)       drain presented 0 bytes
BEFORE |   re-arm 11: check: rearm-resurface                     drain presented 0 bytes
BEFORE |   RESULT: 9 of 11 re-arms woke firstmate; 2 stayed silent

AFTER  | --- Phase 2: 11 consecutive re-arms over the torn-down fleet -------------
AFTER  |   re-arm  1: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  2: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  3: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  4: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  5: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  6: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  7: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  8: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm  9: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm 10: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   re-arm 11: SILENT (watcher still live, no wake)       drain presented 0 bytes
AFTER  |   RESULT: 0 of 11 re-arms woke firstmate; 11 stayed silent

Resurfacing the fix must not break, same run, after the fix:
AFTER  | --- Phase 3: the same home, but one real open decision is waiting ------
AFTER  | the watcher went down while a decision was still open; firstmate re-arms
AFTER  |   re-arm after downtime: check: rearm-resurface
AFTER  | $ bin/fm-wake-drain.sh
AFTER  |   OPEN DECISIONS (still open, folded from the durable status logs - not just the latest line):
AFTER  |   held [key=ship-the-release] needs-decision: fixture is held for a decision
AFTER  |   OPEN DECISIONS: close one by answering it: bin/fm-send.sh <task> --resolve-key <key> '<answer>'
AFTER  | 
Evidence: Full pre-fix E2E transcript (watcher at 89bdcb8, symptom reproduced)
========================================================================
 BEFORE the fix - watcher at 89bdcb8 (the captain's reported symptom)
 tree: /var/folders/ym/vnmfjh5n7dn2vdzdgy7zrbjh0000gn/T//fm-prefix-tree.Jt7tXq
 watcher: bin/fm-watch.sh @ n/a
========================================================================

--- Phase 1: the home does real work, the captain handles it -----------
crew reports:  done: the last task finished
watcher wakes firstmate: 
$ bin/fm-wake-drain.sh
  1787377493	2	signal	lastjob.status	signal: /var/folders/ym/vnmfjh5n7dn2vdzdgy7zrbjh0000gn/T//fm-rearm-evidence.yicafh/captain-main-home/state/lastjob.status
  wake annotation: latest wake-EVENT observed at drain, not current state: lastjob.status: done: the last task finished
$ bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 83465.1787377493.eqMx3T

the fleet is torn down: the finished task is cleared, nothing is left
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present

--- Phase 2: 11 consecutive re-arms over the torn-down fleet -------------
  re-arm  1: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  2: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  3: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  4: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  5: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  6: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  7: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  8: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  9: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm 10: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm 11: check: rearm-resurface                     drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present

  RESULT: 9 of 11 re-arms woke firstmate; 2 stayed silent

--- Phase 3: the same home, but one real open decision is waiting ------
the watcher went down while a decision was still open; firstmate re-arms
  re-arm after downtime: check: rearm-resurface
$ bin/fm-wake-drain.sh
  OPEN DECISIONS (still open, folded from the durable status logs - not just the latest line):
  held [key=ship-the-release] needs-decision: fixture is held for a decision
  OPEN DECISIONS: close one by answering it: bin/fm-send.sh <task> --resolve-key <key> '<answer>'
Evidence: Full post-fix E2E transcript (watcher at 4d90bda, silent plus still resurfacing)
========================================================================
 AFTER the fix - watcher at 4d90bda (this change)
 tree: /Users/owlshome/.no-mistakes/worktrees/5e738cfca1e1/01M0KTMMR2VBHK4V6BQDPDN7SN
 watcher: bin/fm-watch.sh @ 4d90bda
========================================================================

--- Phase 1: the home does real work, the captain handles it -----------
crew reports:  done: the last task finished
watcher wakes firstmate: 
$ bin/fm-wake-drain.sh
  1787377574	2	signal	lastjob.status	signal: /var/folders/ym/vnmfjh5n7dn2vdzdgy7zrbjh0000gn/T//fm-rearm-evidence.uWFYLZ/captain-main-home/state/lastjob.status
  wake annotation: latest wake-EVENT observed at drain, not current state: lastjob.status: done: the last task finished
$ bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 45525.1787377574.baSrcM

the fleet is torn down: the finished task is cleared, nothing is left
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present

--- Phase 2: 11 consecutive re-arms over the torn-down fleet -------------
  re-arm  1: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  2: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  3: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  4: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  5: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  6: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  7: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  8: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm  9: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm 10: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present
  re-arm 11: SILENT (watcher still live, no wake)       drain presented 0 bytes
    state/*.meta=0  state/*.check.sh=0  .last-watcher-beat=present

  RESULT: 0 of 11 re-arms woke firstmate; 11 stayed silent

--- Phase 3: the same home, but one real open decision is waiting ------
the watcher went down while a decision was still open; firstmate re-arms
  re-arm after downtime: check: rearm-resurface
$ bin/fm-wake-drain.sh
  OPEN DECISIONS (still open, folded from the durable status logs - not just the latest line):
  held [key=ship-the-release] needs-decision: fixture is held for a decision
  OPEN DECISIONS: close one by answering it: bin/fm-send.sh <task> --resolve-key <key> '<answer>'
Evidence: Reproduction script used for both runs (takes the tree under test as an argument)
#!/usr/bin/env bash
# End-to-end reproduction of the captain's reported symptom against a chosen
# firstmate tree. Usage: e2e-rearm-resurface.sh <tree> <label>
set -u
TREE=$1
LABEL=$2
CYCLES=${3:-11}

# shellcheck source=/dev/null
. "$TREE/tests/wake-helpers.sh"

# The seed helper is part of the change under test; define the identical
# fixture when running against the pre-fix tree so both runs seed the same way.
if ! declare -F seed_open_decision >/dev/null 2>&1; then
  seed_open_decision() {  # <state> <key>
    printf 'needs-decision [key=%s]: fixture is held for a decision\n' "$2" \
      > "$1/held.status"
    prime_status_seen "$1" "$1/held.status"
  }
fi

DRAIN="$TREE/bin/fm-wake-drain.sh"
ARM="$TREE/bin/fm-watch-arm.sh"
TMP_ROOT=$(fm_test_tmproot fm-rearm-evidence)
ARM_PID=

start_arm() {  # <home> <state> <fakebin> <out>
  PATH="$3:$PATH" FM_HOME="$1" FM_STATE_OVERRIDE="$2" \
    FM_POLL=1 FM_SIGNAL_GRACE=0 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 \
    "$ARM" --restart > "$4" 2>&1 &
  ARM_PID=$!
}

close_watcher() {  # <state>
  local pid
  pid=$(cat "$1/.watch.lock/pid" 2>/dev/null || true)
  [ -n "$pid" ] && kill -TERM "$pid" 2>/dev/null
  wait "$ARM_PID" 2>/dev/null || true
}

watcher_live() {  # <state>
  local pid
  pid=$(cat "$1/.watch.lock/pid" 2>/dev/null || true)
  [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null
}

# After a wake the watcher exits with it, so the handling turn ends with the
# ordinary auto-arm putting a fresh watcher back in place. Replay that here, so
# every counted cycle below is the same thing the captain's home does: a re-arm
# that closes a LIVE watcher.
ensure_live_watcher() {  # <home> <state> <fakebin> <out>
  watcher_live "$2" && return 0
  start_arm "$1" "$2" "$3" "$4"
  local i=0
  while [ "$i" -lt 60 ]; do
    watcher_live "$2" && return 0
    is_live_non_zombie "$ARM_PID" || return 0
    sleep 0.1
    i=$((i + 1))
  done
}

# Wait up to ~8s for the arm to finish delivering a wake; echo the reason or
# the literal word SILENT when it settled into its live wait instead.
arm_outcome() {  # <out>
  local out=$1 i=0
  while [ "$i" -lt 80 ]; do
    is_live_non_zombie "$ARM_PID" || break
    sleep 0.1
    i=$((i + 1))
  done
  if is_live_non_zombie "$ARM_PID"; then
    printf 'SILENT (watcher still live, no wake)\n'
    return
  fi
  wait "$ARM_PID" 2>/dev/null || true
  grep -Eo 'check: rearm-resurface|watcher: [A-Za-z-]+ [^ ]*' "$out" | tail -1
}

home_health() {  # <state>
  local metas checks beat drain
  metas=$(find "$state" -maxdepth 1 -name '*.meta' | wc -l | tr -d ' ')
  checks=$(find "$state" -maxdepth 1 -name '*.check.sh' | wc -l | tr -d ' ')
  if [ -e "$state/.last-watcher-beat" ]; then beat=present; else beat=missing; fi
  printf '    state/*.meta=%s  state/*.check.sh=%s  .last-watcher-beat=%s\n' \
    "$metas" "$checks" "$beat"
}

printf '========================================================================\n'
printf ' %s\n' "$LABEL"
printf ' tree: %s\n' "$TREE"
printf ' watcher: bin/fm-watch.sh @ %s\n' \
  "$(cd "$TREE" 2>/dev/null && git log -1 --format=%h -- bin/fm-watch.sh 2>/dev/null || echo n/a)"
printf '========================================================================\n\n'

dir=$(make_case captain-main-home)
home="$dir/home"; state="$dir/state"; fakebin="$dir/fakebin"
mkdir -p "$home/data"

printf -- '--- Phase 1: the home does real work, the captain handles it -----------\n'
start_arm "$home" "$state" "$fakebin" "$dir/work.out"
sleep 1
printf 'crew reports:  done: the last task finished\n'
printf 'done: the last task finished\n' > "$state/lastjob.status"
i=0; while [ "$i" -lt 120 ] && is_live_non_zombie "$ARM_PID"; do sleep 0.1; i=$((i+1)); done
wait "$ARM_PID" 2>/dev/null || true
printf 'watcher wakes firstmate: %s\n' "$(grep -Eo 'check: [a-z-]+|status: .*' "$dir/work.out" | tail -1)"
printf '$ bin/fm-wake-drain.sh\n'
FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" 2>/dev/null | sed 's/^/  /'
FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" >/dev/null 2> "$dir/ack.err" || true
seq_n=$(sed -n 's/.*--ack-through \([0-9]*\) --recovery-generation \([A-Za-z0-9._-]*\)$/\1/p' "$dir/ack.err")
gen=$(sed -n 's/.*--ack-through \([0-9]*\) --recovery-generation \([A-Za-z0-9._-]*\)$/\2/p' "$dir/ack.err")
if [ -n "$seq_n" ]; then
  printf '$ bin/fm-wake-drain.sh --ack-through %s --recovery-generation %s\n' "$seq_n" "$gen"
  FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" --ack-through "$seq_n" --recovery-generation "$gen" >/dev/null 2>&1 || true
fi
printf '\nthe fleet is torn down: the finished task is cleared, nothing is left\n'
rm -f "$state/lastjob.status"
home_health "$state"
printf '\n'

printf -- '--- Phase 2: %s consecutive re-arms over the torn-down fleet -------------\n' "$CYCLES"
noisy=0; silent=0
c=1
while [ "$c" -le "$CYCLES" ]; do
  out="$dir/rearm-$c.out"
  ensure_live_watcher "$home" "$state" "$fakebin" "$dir/settle-$c.out"
  start_arm "$home" "$state" "$fakebin" "$out"
  outcome=$(arm_outcome "$out")
  # A handling turn drains and then acknowledges, exactly as the captain's turn
  # does, so each cycle here is a faithful copy of one reported occurrence.
  FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" > "$dir/drain-$c.out" 2> "$dir/drain-$c.err" || true
  bytes=$(wc -c < "$dir/drain-$c.out" | tr -d ' ')
  aseq=$(sed -n 's/.*--ack-through \([0-9]*\) --recovery-generation \([A-Za-z0-9._-]*\)$/\1/p' "$dir/drain-$c.err")
  agen=$(sed -n 's/.*--ack-through \([0-9]*\) --recovery-generation \([A-Za-z0-9._-]*\)$/\2/p' "$dir/drain-$c.err")
  # Only a drain that actually presented something is acknowledged; a handling
  # turn shown zero bytes has nothing to acknowledge, which is precisely the
  # reported situation.
  if [ -n "$aseq" ] && [ "$bytes" != 0 ]; then
    FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" --ack-through "$aseq" \
      --recovery-generation "$agen" >/dev/null 2>&1 || true
  fi
  case "$outcome" in
    SILENT*) silent=$((silent+1)) ;;
    *rearm-resurface*) noisy=$((noisy+1)) ;;
  esac
  printf '  re-arm %2d: %-42s drain presented %s bytes\n' "$c" "$outcome" "$bytes"
  home_health "$state"
  close_watcher "$state"
  c=$((c+1))
done
printf '\n  RESULT: %s of %s re-arms woke firstmate; %s stayed silent\n\n' "$noisy" "$CYCLES" "$silent"

printf -- '--- Phase 3: the same home, but one real open decision is waiting ------\n'
dir=$(make_case captain-home-with-work)
home="$dir/home"; state="$dir/state"; fakebin="$dir/fakebin"
mkdir -p "$home/data"
seed_open_decision "$state" ship-the-release
start_arm "$home" "$state" "$fakebin" "$dir/first.out"
sleep 1
close_watcher "$state"
printf 'the watcher went down while a decision was still open; firstmate re-arms\n'
start_arm "$home" "$state" "$fakebin" "$dir/recovery.out"
outcome=$(arm_outcome "$dir/recovery.out")
printf '  re-arm after downtime: %s\n' "$outcome"
printf '$ bin/fm-wake-drain.sh\n'
FM_HOME="$home" FM_STATE_OVERRIDE="$state" "$DRAIN" 2>/dev/null | sed 's/^/  /'
close_watcher "$state" 2>/dev/null || true
printf '\n'

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

⚠️ **Rebase** - 1 warning
  • ⚠️ .agents/skills/afk/SKILL.md - branch carries 23 commit(s) that exist on your local main branch but were never pushed to origin/main; rebasing would bundle this unrelated work (121 file(s)) into the PR:
  • 89bdcb8 Merge the fleet-wide crew guidelines and plain-language rule
  • 5791630 no-mistakes(test): map GROK_BOT.md in changed-test selection table
  • fcac1fe no-mistakes(review): read AGENTS.md section literally in brief drift guard
  • dc825c3 no-mistakes(review): split scout brief guidelines, add AGENTS.md drift guard
  • dae18d3 Merge local-only project support on secondmate routes into the captain's firstmate
  • f69ffb0 Merge the /updatethecaptain worker report loop into the captain's firstmate
  • 2725ed2 no-mistakes(review): restore repo style rules, drop captain-personal line, brief guidelines
  • 0277a4f doc: add fleet-wide general guidelines to AGENTS.md
  • 76caade no-mistakes(document): list captain-report timer in bin toolbelt inventory
  • 3b42880 no-mistakes(test): fix timing flake in captain-report timer test
  • a4df23d no-mistakes(review): roll back armed check on verify failure, fix usage range, document timer
  • 7a2f7b4 feat(skills): add the updatethecaptain worker report loop and its stop companion
  • 8ce9114 no-mistakes(document): register spawn base-freshen suite in backend-dispatch family
  • 38ebb58 no-mistakes(document): tolerate an origin-less clone when freshening a spawn base
  • 7dadb82 no-mistakes(document): align landing doc comments with anchored-origin advisory
  • dbd7a98 no-mistakes(review): drop the orphaned local-path origin helper and its coverage
  • c692797 no-mistakes(review): judge an already-anchored landing origin as a local path
  • c4f6348 no-mistakes(lint): silence intentional literal-tilde SC2088 warnings
  • 2ff37c1 no-mistakes(document): correct stale seeding and origin-lib docs for local-only landing
  • 9a462d3 no-mistakes(review): refuse ignored files blocking directories a landing needs
  • 0f64338 no-mistakes(review): narrow ignored-path collisions and advise relative origins
  • 7ff796e no-mistakes(review): guard ignored-path and relative-origin landings
  • 85bd175 feat(bin): carry local-only projects on secondmate routes and land them back in the folder that holds the project

Push main to origin, or rebase your branch onto origin/main, before gating.

🔧 **Review** - 2 issues found → auto-fixed (3) ✅
  • ⚠️ bin/fm-watch.sh:844 - recovery_has_presentable_work runs the whole-file fleet-wide decision fold on the watcher's arm critical path, and bin/fm-classify-lib.sh itself documents that this exact usage is what the incremental sibling exists to avoid (lines 377-391: "A fleet-wide scan using that whole-file function would pay that cost for every task on every wake, which grows unbounded as tasks run longer"). status_open_decisions forks a subshell per line for the fold, and _fm_decision_fold_line forks ~3 more (status_line_verb, _fm_decision_key, status_line_note), so cost is roughly 4-5 forks per status line per task. Because an ordinary watcher close republishes downtime unconditionally, essentially every re-arm now reaches this fold, and it reaches it precisely in the quiet case the cheaper checks did not short-circuit. Concretely: 5 live tasks with 300-line status logs is ~1500 lines, i.e. several thousand forks blocking the watcher before it settles into its live wait; a long-running task with a few thousand status lines makes that noticeably worse. The intent explains why scan_open_decisions_incremental cannot be substituted (its cursor write blinds the unread-status fallback), and that reasoning is correct - but a cheap sound pre-filter avoids the tradeoff entirely: a decision can only be opened by a needs-decision or blocked verb, so grep -qE &#39;^[[:space:]]*(needs-decision|blocked)&#39; per status file (one fork per file) can skip the fold for any file that provably has no open decision, and the full fold still runs for files that do. That keeps the read-only property and the whole-file semantics intact. Flagging rather than fixing because the scan choice is a deliberate, documented decision in this diff.
  • ℹ️ bin/fm-watch.sh:885 - The new gate only takes effect on the pending:downtime:* branch, so one narrow path still delivers check: rearm-resurface with nothing to present. When fm-watch.sh reclaims a stale watcher lock itself, FM_LOCK_RECOVERED_PID sets WATCHER_RECOVERY_PENDING=1 (line 774); if the queue is empty and no marker exists, _fm_recovery_marker_arm_check writes no marker and leaves FM_RECOVERY_MARKER_ACTION=none (bin/fm-wake-lib.sh:794-800), so WATCHER_RECOVERY_PENDING stays 1. resurface_after_downtime then skips the arm check at line 867, finds nothing presentable, snapshots an empty FM_RECOVERY_MARKER_TOKEN, matches no case arm, and falls through to wake at line 885. The same fall-through applies if the snapshot reads pending:handling:*. This is pre-existing behaviour that the fix narrows rather than introduces, and it self-limits: the next arm's clear_stale_recorded_watcher_lock (bin/fm-watch-arm.sh:233) publishes a real downtime marker, after which the new gate retires it silently. It also matches the change's stated bias that a redundant wake is cheaper than a suppressed one. Noting it only so the residual path is on record; no action needed for this change.

🔧 Fix: pre-filter decision fold, gate every empty recovery wake
1 warning still open:

  • ⚠️ tests/fm-watch-arm.test.sh:934 - start_reclaiming_watcher does not actually exercise the path it was added for, so the closed gap stays unpinned. bin/fm-watch.sh runs &#34;$SCRIPT_DIR/fm-pr-check-migrate.sh&#34; --checks-safe as its very first action, before its own fm_lock_try_acquire. On the fresh state make_case creates there is no .pr-check-migration-scan-v1, so scan_complete fails, migration_complete fails, and the [ &#34;$ALLOW_INCOMPLETE_REPAIRS&#34; -eq 1 ] &amp;&amp; scan_complete short-circuit fails too (bin/fm-pr-check-migrate.sh:259-262) - the migration therefore falls through to fm_lock_try_acquire &#34;$WATCH_LOCK&#34;. The lock the helper planted holds a numeric dead pid, so fm_lock_mid_acquire_is_fresh returns 1 (it only guards empty/non-numeric pids) and the migration steals it, setting FM_LOCK_RECOVERED_PID and therefore watch_recovery_required=1 (bin/fm-pr-check-migrate.sh:312). Its EXIT trap then runs fm_recovery_transition ... release-lock &#34;$WATCH_LOCK&#34; downtime (line 332), which PUBLISHES a downtime marker and releases the lock. By the time fm-watch.sh reaches its own fm_lock_try_acquire, the lock is free, FM_LOCK_RECOVERED_PID is reset to empty at the top of that function (bin/fm-wake-lib.sh:730), WATCHER_RECOVERY_PENDING stays 0, and arm_check recovers an ordinary pending:downtime:* episode. The test therefore re-covers the published-downtime case test_empty_fleet_recovery_stays_silent_across_rearms already covers, and never reaches the FM_LOCK_RECOVERED_PID-with-no-marker case the fix at bin/fm-watch.sh:889 exists for. Both sub-cases still pass, so this is silent under-coverage rather than a failure, and docs/watcher-continuity.md:90 now asserts coverage ("which reaches recovery without any arm-side publication") that does not exist. The guard at line 963 does not catch it: lock_pid = ARM_PID holds either way. Remedy: seed the migration short-circuit markers in start_reclaiming_watcher the way tests/fm-watcher-lock.test.sh:18-23 does for its own dead-pid lock cases (.pr-check-migration-scan-v1 and .pr-check-migration-v1, mode 0600) - ideally by promoting that helper into tests/wake-helpers.sh so the two suites share one owner - and add a positive premise guard after the lock-ownership check, [ ! -e &#34;$state/.watcher-down&#34; ] || fail &#34;... so this case proves nothing&#34;, matching the idiom already used at lines 963-964 and in the round-1 cases.

🔧 Fix: pin stale-lock reclaim test to the real reclaim path
2 issues (1 warning, 1 info) still open:

  • ⚠️ tests/fm-watch-arm.test.sh:940 - The stale-lock reclaim case still does not discriminate the regression it was added for, and the reason is that the markerless state it targets is not reachable. fm_lock_try_acquire publishes the downtime marker as PART of the watch-lock steal: bin/fm-wake-lib.sh:804-805 runs _fm_recovery_marker_publish &#34;$STATE/.watcher-down&#34; downtime after fm_lock_recheck_stale_owner succeeds and before FM_LOCK_RECOVERED_PID=$cur at line 816. I verified every gate on that path passes for the planted fixture (plain directory lock, dead numeric pid: fm_lock_recheck_stale_owner takes its elif [ -e &#34;$lockdir&#34; ] branch, the pid matches, fm_pid_alive is false, and fm_lock_mid_acquire_is_fresh returns 1 because the pid is numeric). So FM_LOCK_RECOVERED_PID non-empty for $STATE/.watch.lock IMPLIES the marker exists as pending:downtime:&lt;gen&gt;. The guard at line 950 checks the marker before the watcher starts, which the watcher's own steal then creates. Concretely for this fixture: migration short-circuits, watcher steals the lock and mints pending:downtime:G, WATCHER_RECOVERY_PENDING=1 (bin/fm-watch.sh:774), arm_check reads pending:downtime:G so FM_RECOVERY_MARKER_ACTION=recover, and resurface_after_downtime matches the pending:downtime:* case arm and retires. That is byte-identical behaviour under the round-1 form of the branch, so the case does NOT fail if the nothing-presentable branch is restricted back to only pending:downtime:* - the exact discriminating property you required. This also corrects my round-1 finding 2: the 'no marker at all' path I described is not reachable through the watch-lock steal. The same misconception is embedded in the code comment at bin/fm-watch.sh:876-878, which contrasts 'a recovery pending through the watcher's own stale-lock reclaim' with 'a published downtime episode' when the reclaim IS one, and in the fixture comment at lines 934-939, whose stated goal (avoid 'turning this case back into the published-episode case') is not achieved because the watcher publishes it instead of the migration. What the round-2 generalization genuinely closes is narrower but real: after the steal leaves pending:downtime:G with WATCHER_RECOVERY_PENDING=1, a drain racing the watcher's first poll can move the token to pending:handling:G or acked:handling:G, and only the generalized branch stays silent there. That state needs a concurrent drain, so no deterministic fixture reaches it without a new watcher-side test seam (the drain already has FM_WAKE_DRAIN_TEST_DELAY_BEFORE_COMMIT; an analogous delay before the first resurface_after_downtime would let a test ack the generation first). Recommendation: do not run another mechanical round chasing an unreachable fixture. Either (a) keep the generalized gate as documented defensive hardening and correct the two comments plus the test's stated premise to say what the case actually pins - that the reclaim path reaches recovery through a marker the steal itself publishes, and that the discriminating race-only state is deliberately untested - or (b) if a pinned regression test is required, add the watcher-side test seam. This is your call because it turns on whether a production test seam is acceptable for a defensive branch; the production behaviour itself is correct and strictly safer than the round-1 form either way.
  • ℹ️ bin/fm-test-run.sh:934 - tests/fm-watch-arm.test.sh now invokes bin/fm-pr-check-migrate.sh directly and hard-fails on its marker short-circuit (lines 946-951), but families_for_changed_path maps bin/fm-pr-* to pr-forge only, so editing the migration's short-circuit conditions would not select the watcher-wake-lock family in --changed mode. The dependency is pre-existing - bin/fm-watch.sh already runs that binary as its first action, and tests/fm-watcher-lock.test.sh already relied on the same short-circuit - so this commit hardens rather than creates it, and --all plus the portable shards still cover it. Noting it only because the map's own stated policy is to over-select rather than under-select; adding watcher-wake-lock to that case arm would restore that property. No action needed for this change.

🔧 Fix: correct reclaim-path descriptions, map migration to watcher family
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-watch-arm.test.sh (all 17 cases, including the three new presentation-source, empty-fleet-silence, and stale-lock-reclaim cases)
  • bash tests/fm-watcher-lock.test.sh (31 cases, covering the reused-pid and dead-pid reclaim assertions reseeded with seed_open_decision)
  • bash tests/fm-classify-decision-key.test.sh, bash tests/fm-wake-drain-open-decisions.test.sh, bash tests/fm-wake-drain-open-decisions-cursor.test.sh, bash tests/fm-wake-drain-unread-status.test.sh (output-neutrality of the new FM_DECISION_OPENING_VERB_RE pre-filter in scan_open_decisions)
  • bash tests/fm-decision-hold-lifecycle.test.sh, bash tests/fm-watch-triage.test.sh, bash tests/fm-pending-reply.test.sh (remaining consumers of the decision fold)
  • Manual E2E reproduction: bash e2e-rearm-resurface.sh &lt;pre-fix-tree @89bdcb8&gt; &#39;BEFORE the fix&#39; 11 - real bin/fm-watch-arm.sh --restart, real bin/fm-watch.sh, real bin/fm-wake-drain.sh in a disposable FM_HOME; work done, handled, acknowledged, fleet torn down, then 11 re-arms each closing a live watcher
  • Manual E2E re-run of the same script against this change: bash e2e-rearm-resurface.sh &lt;worktree&gt; &#39;AFTER the fix&#39; 11
  • bash bin/fm-test-run.sh --list --changed --base 89bdcb8 to confirm the watcher suites are selected for this diff
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 22, 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(test): count report lines po..." | Re-trigger Greptile

Comment thread bin/fm-classify-lib.sh Resolved
…em back in the folder that holds the project
Land the captain's edits: refreshed nautical-seasoning examples, a pointer
to ~/VOICE.md when writing under his identity, a new general-guidelines
section for all crewmates, and a plain-language rule in section 9.

Give the sentence-per-line, plain-dash, and no-agent-co-author rules a
single owner in that new section, replacing the copies in the coding
guidelines skill, CONTRIBUTING.md, and section 1 with cross-references.
…resent

A watcher close publishes a downtime episode unconditionally, and
resurface_after_downtime woke firstmate for any pending episode without
testing whether anything actually needed resurfacing. With a torn-down
fleet that produced a self-sustaining loop: each re-arm closed the
previous watcher, which republished downtime, so the next successor
delivered another "check: rearm-resurface" whose handling turn found an
empty queue, no work under way and nothing armed.

Gate the wake on the three sources docs/watcher-continuity.md says the
recovery presentation contains - unacknowledged queue rows, still-open
decisions, and unread informational status lines - and retire an episode
proved empty so later arms cannot re-fire it. The emptiness re-check and
the generation-bound acknowledgement share the queue lock fm_wake_append
holds, so a wake racing that decision keeps its episode, and any failure
to read a source is treated as work present.

Delivering the wake still does not retire the episode. That is the
durability guarantee behind release-lock-existing: the wake is delivered
but not yet handled, and preserving it is what lets an interrupted
handling turn re-drain the same work.

The decision fold uses the whole-file scan rather than its incremental
sibling, which writes a cursor the unread-status scan falls back to and
would otherwise let this check blind the drain it protects.

Three existing cases asserted the recovery wake on an empty fleet as
proof that lock or marker evidence survived. They now hold a real open
decision, so they still prove evidence retention while exercising
resurfacing rather than the noise.
…annot be read

The open-decision pre-filter read grep's nonzero exit as proof that a
status file holds no opening verb, so a read failure (exit 2) looked
exactly like a file with nothing open. The recovery gate then retired the
episode and stayed silent about a decision it never managed to read.

Only grep's no-match (exit 1) is that proof now; any other exit, and any
failure of the fold itself, propagates out of scan_open_decisions so the
gate takes its documented fail-open path and still resurfaces.
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Corrective intent is right: stop check: rearm-resurface when the drain would present nothing, without breaking real recovery. The gate on queue rows / open decisions / unread status, the queue-lock retirement, and leaving release-lock-existing untouched all match that contract.

VISION:

  • Peace of mind / token efficiency — eleven empty recovery turns are noise, not news. Aligns.
  • The interface must stay honest and never hide a decision — the stated fail-open on a failed scan aligns; the new grep -qE pre-filter in scan_open_decisions does not. A grep I/O error is treated as "no opening verb", the fold is skipped, and recovery_has_presentable_work can retire the episode. That can hide a still-open decision. Does not align until grep failures propagate.
  • A restart is a non-event / obligations close by records — preserving the episode across delivery is correct. Aligns.

Security: no.

This branch is not the isolated watcher fix. HEAD is 28 ahead / 10 behind origin/main, merge state DIRTY, and the delta bundles the local-only landing, /updatethecaptain, spawn-base freshen, and AGENTS.md guidelines work that already have their own PRs (#2700, #2724, #2735). That spawn/teardown slice overlaps the held pair #2637/#2692 and the other lifecycle PRs (#2760/#2770/#2768), and the spawn-freshen hold #2622/#2693. Intended watcher files also overlap other open watch PRs on bin/fm-watch.sh (including #2749). Do not land this with any of those.

Greptile is red on the grep-error path. No Actions runs are queued on this SHA yet, so there is no fork workflow to approve and no-mistakes has not run.

This is waiting on the author, not the captain: rebase onto origin/main with only the resurface commits, fix the grep fail-open, then CI can run.

…ck suite

BSD wc pads its count, so the three one-line report assertions compared
a padded "       1" against "1" and failed on macOS while passing on
the Linux CI runners. Strip the padding the way the probe-count
assertion in the same script already does.
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: closing this as stale. It has been waiting on a contributor update for 14+ days with no author push or comment (the last author activity was the push on 2026-08-22, about 97 days ago). Thank you @EternalTime for tracking down the empty check: rearm-resurface loop; the symptom was real and worth fixing.

For anyone picking it up again: the open points from my earlier review still stand. The branch bundled unrelated work (28 commits ahead of main, overlapping other PRs' files) and should carry only the resurface commits, the grep -qE pre-filter in scan_open_decisions needs its I/O failures to propagate so it can't hide an open decision, and it needs a fresh no-mistakes run. Reopen if you want to pick it back up.

Contract class: cannot-tell (not re-inspected against current main; the branch is far behind and bundled). VISION: the honest-interface rule did not align at the last review (a failed grep could retire an episode that hides a decision); the others were fine.

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.

2 participants