Skip to content

feat(logbook): supervise the attention board's liveness with a watcher reap - #3

Merged
SchokoShake merged 4 commits into
mainfrom
fm/logbook-supervise-b4
Jul 15, 2026
Merged

SchokoShake merged 4 commits into
mainfrom
fm/logbook-supervise-b4

Conversation

@SchokoShake

Copy link
Copy Markdown
Owner

Intent

Close the gap where nothing owns the logbook attention board's liveness in the firstmate repo. The board (node projects/logbook/server.mjs on loopback 127.0.0.1:8137) was only ever started at a firstmate session start by bin/fm-bootstrap.sh via bin/fm-logbook-up.sh, with no supervisor to restart it when it dies (evidence: 14 startup banners in state/logbook-server.log; SIGKILL under crewmate memory pressure is the leading theory). Symptom: 'logbook didnt start'.

What was built, all firstmate-side (bin/, docs/, and tests only; projects/logbook is out of scope per AGENTS.md section 15):

  1. A watcher-side liveness reap added to bin/fm-watch.sh so firstmate health-checks a dead board (curl -m2 LOGBOOK_URL/health) and relaunches it via the idempotent bin/fm-logbook-up.sh, in the same watcher beat. Strictly additive: it does NOT change wake cadence or wake classification, and a reaped/relaunched board must NOT manufacture a check:/signal: wake (reaping is housekeeping, not a captain event). A hard no-op when config/logbook.env is absent or LOGBOOK_ENABLE is falsy (same discipline as fm-logbook-up.sh and fm-x-poll.sh); a non-adopter sees zero behaviour change and pays zero cost. Cheap and non-blocking: the health check must never block or hang a watcher cycle, and the launch is reused, not reimplemented.

  2. The anti-thrash guard was redesigned (this relaunch's approved change). The earlier rate/window/decay model could not be patched into correctness (it was patched three times, each fix opening a new hole: backoff decays into thrash because backing off stops generating the events the window counts; a false crash-loop wake fired from one unanswered /health probe before the grace re-probe; and under /afk the 300s cadence made both give-up and backoff unreachable). It was replaced entirely with two monotone streak counters plus a wall-clock stability reset - no window, no rate, no decay, no floor, no cadence assumption - so it behaves identically at a 15s and a 300s watcher cadence:

  • wont-start streak: consecutive relaunch attempts where the board still does not answer /health afterward; at a bounded max, surface 'logbook board won't start' to the captain ONCE (dedupe marker under state/, following the state/logbook-poll.error precedent) and stop relaunching until reset.
  • crash-loop streak: consecutive revivals that did not stick (the board came back up but died again before it had been healthy for STABLE_SECS); at a bounded max, surface 'logbook board is crash-looping' to the captain ONCE and stop relaunching until reset.
  • wall-clock stability reset: once the board has been continuously healthy for STABLE_SECS since the last relaunch, reset BOTH streaks to zero. This monotone reset replaces the decaying window and drops a config knob.
  1. Colocated tests were updated to the new streak model (they mock curl), and any doc/comment that still described the rate/window/decay behaviour was corrected.

  2. docs document the systemd --user unit (Restart=always + loginctl enable-linger) as the recommended setup where systemd exists, with the watcher reap as the portable fallback. Two load-bearing traps are called out: Environment=LOGBOOK_DATA=<FM_HOME>/state/logbook.data (omitting it points the board at an empty SQLite store and looks like data loss) and an absolute node path in ExecStart (a systemd --user unit does not inherit the interactive shell PATH). Paths are generalised to <FM_HOME>, not hardcoded.

Deliberate design choices a reviewer reading only the diff would not know: keeping the reap out of the wake rail is intentional (do not wake the captain for housekeeping); reusing bin/fm-logbook-up.sh rather than reimplementing the launch is intentional; the hard no-op when logbook is not opted in is required; and NOT trying to detect or defer to systemd is intentional (where a supervisor owns the board it will answer /health and the reap is a correct no-op).

What Changed

  • Add bin/fm-logbook-reap.sh, a watcher-side liveness reap wired through state/logbook-reap.check.sh in bin/fm-bootstrap.sh: each check cycle it health-checks the board (curl LOGBOOK_URL/health) and relaunches a dead one via the idempotent bin/fm-logbook-up.sh, staying a hard no-op when logbook is not opted in and never manufacturing a check:/signal: wake for the housekeeping.
  • Guard against thrash with two monotone streak counters plus a wall-clock stability reset (replacing the earlier rate/window/decay model): a won't-start streak and a crash-loop streak each surface once to the captain at a bounded max via a state/ dedupe marker and stop relaunching until the board has been continuously healthy for STABLE_SECS, giving identical behavior at 15s and 300s watcher cadences.
  • Document the systemd --user unit (Restart=always + enable-linger, with the LOGBOOK_DATA and absolute-node-path traps called out) as the recommended setup and the reap as the portable fallback, rewrite tests/fm-logbook.test.sh to the streak model, and fix pre-existing failing tests plus a turn-end guard stdin EPIPE crash.

Risk Assessment

✅ Low: The change is strictly additive (a new watcher check shim plus its script, bootstrap wiring, docs, and colocated tests), self-gated to a hard no-op when logbook is off, does not touch the watcher backbone or wake classification, and its careful streak-based state machine is well-covered by tests; I found no correctness bugs, only two minor consistency/tradeoff notes.

Testing

Baseline full test suite (already run) plus my re-run both pass with exit 0, including all 9 new reap tests; the round-1 exit-1 failure was a pre-existing test issue fixed by the final commit. Beyond unit tests, I demonstrated the intent end-to-end by driving the real fm-logbook-reap.sh against a fake board and capturing the captain's wake channel per watcher cycle: a dead board is silently revived (health 000→200, no wake), and only an unfixable board surfaces exactly one diagnostic — "won't start" or "crash-looping" — then stops relaunching, with a stability reset re-arming the report. No rendered-UI artifact applies because this is a CLI/watcher operational change with no firstmate-side visual surface (the board's own web UI lives in projects/logbook, which is out of scope). No source changes were introduced and the working tree is clean.

Evidence: Reap demo transcript (captain's-eye: silent revival, one won't-start wake, no thrash, recovery)

SCENARIO 2 Board dies mid-session - reaped and revived SILENTLY (housekeeping) board killed; /health=000 after reap: /health=200 state: up 0 0 ... (silent - housekeeping, no captain wake) SCENARIO 3 Board that WON'T start - one diagnostic, ONCE, then no thrash watcher cycle 1: launching 1 0 ... (silent) watcher cycle 2: launching 2 0 ... (silent) watcher cycle 3 (give-up): wontstart 3 0 ... CAPTAIN SEES A WAKE -> logbook-error logbook board won't start at http://127.0.0.1:8137; 3 relaunch attempts failed: ... watcher cycle 4 (backed off - NOT relaunching): (silent)

==================================================================
 logbook board-liveness reap - captain's-eye demonstration
 board URL http://127.0.0.1:8137 ; MAX_STRIKES=3 for a short demo
==================================================================

�[1mSCENARIO 0  Not opted in - a hard no-op (a non-adopter pays nothing)�[0m
   exit=0  stdout=[]  state-files-written=0
   (silent - housekeeping, no captain wake)

�[1mSCENARIO 1  Board healthy - silent and cheap (the overwhelming common path)�[0m
   board /health=200  state: (no state - steady/healthy)
   (silent - housekeeping, no captain wake)

�[1mSCENARIO 2  Board dies mid-session - reaped and revived SILENTLY (housekeeping)�[0m
   board killed (an OOM kill under crewmate memory pressure); /health=000
   after reap: /health=200   state: up 0 0 1784110446
   (silent - housekeeping, no captain wake)
   -> the board is back up and the captain was never interrupted.

�[1mSCENARIO 3  Board that WON'T start - one diagnostic, ONCE, then no thrash�[0m
   watcher cycle 1:  state: launching 1 0 1784110446
   (silent - housekeeping, no captain wake)
   watcher cycle 2:  state: launching 2 0 1784110449
   (silent - housekeeping, no captain wake)
   watcher cycle 3 (give-up):  state: wontstart 3 0 1784110452
   CAPTAIN SEES A WAKE  ->  logbook-error logbook board won't start at http://127.0.0.1:8137; 3 relaunch attempts failed: board launched but not yet healthy at http://127.0.0.1:8137 (see state/logbook-server.log)
   watcher cycle 4 (backed off - NOT relaunching):  state: wontstart 3 0 1784110452
   (silent - housekeeping, no captain wake)
   -> exactly one wake for the whole incident; no per-cycle thrash.

�[1mSCENARIO 4  Recovery - an external revival clears the diagnostic once stable�[0m
   board healthy again; reap moves to 'proving' phase:  state: up 3 0 1784110456
   diagnostic marker still held: yes  (board must PROVE stable first)
   (silent - housekeeping, no captain wake)
   after STABLE_SECS of continuous health:
     state: (no state - steady/healthy)
     diagnostic marker cleared: yes  (report re-armed for a future death)
   (silent - housekeeping, no captain wake)

==================================================================
 DONE.  A board firstmate can revive costs the captain nothing;
 only a board it truly cannot keep alive wakes the captain, once.
==================================================================
Evidence: Crash-loop demo transcript (second distinct diagnostic, surfaced once)

cycle 1: revived silently (up 0 0) cycle 2: non-sticking revival -> up 0 1 (silent) cycle 3: non-sticking revival -> up 0 2 (silent) cycle 4 (give-up): crashloop 0 3 CAPTAIN SEES A WAKE -> logbook-error logbook board is crash-looping at http://127.0.0.1:8137; revived 3 times but it keeps dying cycle 5 (backed off): board still down, reap stays quiet, does NOT relaunch

==================================================================
 SCENARIO 3b  Crash-looping board - revives but keeps dying
==================================================================

cycle 1: board's first death -> reap revives it (node binds).
   /health=200  state: up 0 0 1784110499
   (silent - housekeeping)
cycle 2: the revived board died again before proving stable (non-sticking revival).
   /health=200  state: up 0 1 1784110500
   (silent - housekeeping)
cycle 3: the revived board died again before proving stable (non-sticking revival).
   /health=200  state: up 0 2 1784110500
   (silent - housekeeping)
cycle 4 (give-up): the crash streak hits the ceiling.
   /health=000  state: crashloop 0 3 1784110500
   CAPTAIN SEES A WAKE  ->  logbook-error logbook board is crash-looping at http://127.0.0.1:8137; revived 3 times but it keeps dying
cycle 5 (backed off): board still down, reap stays quiet and does NOT relaunch.
   /health=000  state: crashloop 0 3 1784110500
   (silent - housekeeping)

 -> distinct 'crash-looping' message, surfaced exactly once, then no thrash.
Evidence: Reap demo harness (drives real fm-logbook-reap.sh + fm-logbook-up.sh)
#!/usr/bin/env bash
# End-to-end demonstration of the logbook board-liveness reap, captain's-eye view.
#
# Exercises the REAL bin/fm-logbook-reap.sh (which itself calls the REAL
# bin/fm-logbook-up.sh) against a fake board built from stub `curl` + `node`,
# exactly the way the colocated test does. A shared FAKE_HEALTH_FILE holds the
# board's current /health code; the stub `node` "binds the port" by flipping it to
# 200, and a test can "kill the board" by flipping it back to 000. Every line the
# reap prints on stdout is what the watcher turns into a captain-facing wake; a
# blank line is housekeeping the captain never sees.
set -u

ROOT=$1                       # firstmate repo root (has bin/fm-logbook-reap.sh)
WORK=$2                       # scratch dir for this demo
mkdir -p "$WORK"

FAKEBIN="$WORK/fakebin"; mkdir -p "$FAKEBIN"
HEALTH="$WORK/health.code"; printf '200' > "$HEALTH"

# --- stub curl: serves /health from the shared code file -----------------------
cat > "$FAKEBIN/curl" <<'SH'
#!/usr/bin/env bash
ofile="" url=""
while [ $# -gt 0 ]; do
  case "$1" in
    -o) ofile=$2; shift 2 ;;
    -m|-w|-X|-H) shift 2 ;;
    -s) shift ;;
    http://*|https://*) url=$1; shift ;;
    *) shift ;;
  esac
done
case "$url" in
  */health)
    [ -n "$ofile" ] && : > "$ofile"
    printf '%s' "$(cat "$FAKE_HEALTH_FILE" 2>/dev/null || printf '000')" ;;
  *) printf '000' ;;
esac
exit 0
SH
chmod +x "$FAKEBIN/curl"

# --- stub node: the board "comes up" by flipping /health to 200 ----------------
cat > "$FAKEBIN/node" <<'SH'
#!/usr/bin/env bash
[ -n "${FAKE_HEALTH_FILE:-}" ] && printf '200' > "$FAKE_HEALTH_FILE"
exit 0
SH
chmod +x "$FAKEBIN/node"

# --- opted-in home -------------------------------------------------------------
HOME_A="$WORK/home"; mkdir -p "$HOME_A/config" "$HOME_A/state" "$HOME_A/projects/logbook"
: > "$HOME_A/projects/logbook/server.mjs"      # the launcher insists on finding this
printf 'LOGBOOK_ENABLE=1\nLOGBOOK_URL=http://127.0.0.1:8137\n' > "$HOME_A/config/logbook.env"

# stub `node` that WON'T bind (board that can never come up): does nothing.
cat > "$WORK/node-dead" <<'SH'
#!/usr/bin/env bash
exit 0
SH
chmod +x "$WORK/node-dead"

JQ_DIR=$(command -v jq 2>/dev/null); JQ_DIR=${JQ_DIR:+$(dirname "$JQ_DIR")}
PATH_HEALTHY="$FAKEBIN${JQ_DIR:+:$JQ_DIR}:/usr/bin:/bin"

run_reap() {  # run_reap <extra-env...> -- captures stdout, the wake channel
  env -i PATH="$PATH_HEALTHY" \
    FM_HOME="$HOME_A" FM_ROOT_OVERRIDE="$ROOT" FM_STATE_OVERRIDE="$HOME_A/state" \
    FAKE_HEALTH_FILE="$HEALTH" "$@" \
    bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null
}

kill_board() { printf '000' > "$HEALTH"; }
board_code() { cat "$HEALTH"; }
say() { printf '\n\033[1m%s\033[0m\n' "$*"; }
show_wake() {  # show_wake <stdout>
  if [ -n "$1" ]; then
    printf '   CAPTAIN SEES A WAKE  ->  %s\n' "$1"
  else
    printf '   (silent - housekeeping, no captain wake)\n'
  fi
}
state_line() { cat "$HOME_A/state/logbook-reap.state" 2>/dev/null || printf '(no state - steady/healthy)'; }

echo "=================================================================="
echo " logbook board-liveness reap - captain's-eye demonstration"
echo " board URL http://127.0.0.1:8137 ; MAX_STRIKES=3 for a short demo"
echo "=================================================================="

# ---------------------------------------------------------------------------
say "SCENARIO 0  Not opted in - a hard no-op (a non-adopter pays nothing)"
HOME_OFF="$WORK/home-off"; mkdir -p "$HOME_OFF/state"    # no config/logbook.env
probe_before=$(ls "$HOME_OFF/state" | wc -l | tr -d ' ')
out=$(env -i PATH="$PATH_HEALTHY" FM_HOME="$HOME_OFF" FM_ROOT_OVERRIDE="$ROOT" \
  FM_STATE_OVERRIDE="$HOME_OFF/state" FAKE_HEALTH_FILE="$HEALTH" \
  bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null); rc=$?
echo "   exit=$rc  stdout=[$out]  state-files-written=$(( $(ls "$HOME_OFF/state" | wc -l | tr -d ' ') - probe_before ))"
show_wake "$out"

# ---------------------------------------------------------------------------
say "SCENARIO 1  Board healthy - silent and cheap (the overwhelming common path)"
printf '200' > "$HEALTH"
out=$(run_reap); echo "   board /health=$(board_code)  state: $(state_line)"
show_wake "$out"

# ---------------------------------------------------------------------------
say "SCENARIO 2  Board dies mid-session - reaped and revived SILENTLY (housekeeping)"
kill_board; echo "   board killed (an OOM kill under crewmate memory pressure); /health=$(board_code)"
out=$(run_reap)
echo "   after reap: /health=$(board_code)   state: $(state_line)"
show_wake "$out"
echo "   -> the board is back up and the captain was never interrupted."

# ---------------------------------------------------------------------------
say "SCENARIO 3  Board that WON'T start - one diagnostic, ONCE, then no thrash"
rm -f "$HOME_A/state/logbook-reap.state" "$HOME_A/state/logbook-reap.error"
kill_board
PATH_DEAD="$FAKEBIN${JQ_DIR:+:$JQ_DIR}:/usr/bin:/bin"
cp "$WORK/node-dead" "$FAKEBIN/node"     # node that never binds the port
for i in 1 2; do
  out=$(env -i PATH="$PATH_DEAD" FM_HOME="$HOME_A" FM_ROOT_OVERRIDE="$ROOT" \
    FM_STATE_OVERRIDE="$HOME_A/state" FAKE_HEALTH_FILE="$HEALTH" \
    FM_LOGBOOK_REAP_MAX_STRIKES=3 bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null)
  echo "   watcher cycle $i:  state: $(state_line)"
  show_wake "$out"
done
out=$(env -i PATH="$PATH_DEAD" FM_HOME="$HOME_A" FM_ROOT_OVERRIDE="$ROOT" \
  FM_STATE_OVERRIDE="$HOME_A/state" FAKE_HEALTH_FILE="$HEALTH" \
  FM_LOGBOOK_REAP_MAX_STRIKES=3 bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null)
echo "   watcher cycle 3 (give-up):  state: $(state_line)"
show_wake "$out"
out=$(env -i PATH="$PATH_DEAD" FM_HOME="$HOME_A" FM_ROOT_OVERRIDE="$ROOT" \
  FM_STATE_OVERRIDE="$HOME_A/state" FAKE_HEALTH_FILE="$HEALTH" \
  FM_LOGBOOK_REAP_MAX_STRIKES=3 bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null)
echo "   watcher cycle 4 (backed off - NOT relaunching):  state: $(state_line)"
show_wake "$out"
echo "   -> exactly one wake for the whole incident; no per-cycle thrash."

# ---------------------------------------------------------------------------
say "SCENARIO 4  Recovery - an external revival clears the diagnostic once stable"
cp "$FAKEBIN/curl" "$WORK/.keepcurl"          # keep healthy curl
cat > "$FAKEBIN/node" <<'SH'
#!/usr/bin/env bash
[ -n "${FAKE_HEALTH_FILE:-}" ] && printf '200' > "$FAKE_HEALTH_FILE"
exit 0
SH
chmod +x "$FAKEBIN/node"
printf '200' > "$HEALTH"     # a systemd unit / new session bootstrap brought it back
out=$(run_reap FM_LOGBOOK_REAP_MAX_STRIKES=3)
echo "   board healthy again; reap moves to 'proving' phase:  state: $(state_line)"
echo "   diagnostic marker still held: $( [ -f "$HOME_A/state/logbook-reap.error" ] && echo yes || echo no )  (board must PROVE stable first)"
show_wake "$out"
# fast-forward the stability clock: rewrite the 'since' to 200s ago, STABLE_SECS=100
read -r ph ws cl _ < "$HOME_A/state/logbook-reap.state"
now=$(date +%s); printf '%s %s %s %s\n' "$ph" "$ws" "$cl" "$((now-200))" > "$HOME_A/state/logbook-reap.state"
out=$(run_reap FM_LOGBOOK_REAP_STABLE_SECS=100)
echo "   after STABLE_SECS of continuous health:"
echo "     state: $(state_line)"
echo "     diagnostic marker cleared: $( [ -f "$HOME_A/state/logbook-reap.error" ] && echo no || echo yes )  (report re-armed for a future death)"
show_wake "$out"

echo
echo "=================================================================="
echo " DONE.  A board firstmate can revive costs the captain nothing;"
echo " only a board it truly cannot keep alive wakes the captain, once."
echo "=================================================================="
Evidence: Crash-loop demo harness
#!/usr/bin/env bash
# Focused demo of the SECOND captain-facing diagnostic: a crash-looping board.
# The board revives (node binds -> /health 200) but dies again before it has been
# healthy for STABLE_SECS, over and over. The reap re-revives it silently while the
# streak is short, then surfaces ONE "crash-looping" wake and stops relaunching.
set -u
ROOT=$1; WORK=$2; mkdir -p "$WORK"
FAKEBIN="$WORK/fakebin"; mkdir -p "$FAKEBIN"
HEALTH="$WORK/health.code"; printf '200' > "$HEALTH"

cat > "$FAKEBIN/curl" <<'SH'
#!/usr/bin/env bash
ofile="" url=""
while [ $# -gt 0 ]; do case "$1" in
  -o) ofile=$2; shift 2 ;; -m|-w|-X|-H) shift 2 ;; -s) shift ;;
  http://*|https://*) url=$1; shift ;; *) shift ;; esac; done
case "$url" in
  */health) [ -n "$ofile" ] && : > "$ofile"; printf '%s' "$(cat "$FAKE_HEALTH_FILE" 2>/dev/null || printf '000')" ;;
  *) printf '000' ;;
esac
exit 0
SH
chmod +x "$FAKEBIN/curl"
cat > "$FAKEBIN/node" <<'SH'
#!/usr/bin/env bash
[ -n "${FAKE_HEALTH_FILE:-}" ] && printf '200' > "$FAKE_HEALTH_FILE"
exit 0
SH
chmod +x "$FAKEBIN/node"

H="$WORK/home"; mkdir -p "$H/config" "$H/state" "$H/projects/logbook"
: > "$H/projects/logbook/server.mjs"
printf 'LOGBOOK_ENABLE=1\nLOGBOOK_URL=http://127.0.0.1:8137\n' > "$H/config/logbook.env"
JQ_DIR=$(command -v jq 2>/dev/null); JQ_DIR=${JQ_DIR:+$(dirname "$JQ_DIR")}
P="$FAKEBIN${JQ_DIR:+:$JQ_DIR}:/usr/bin:/bin"

reap() { env -i PATH="$P" FM_HOME="$H" FM_ROOT_OVERRIDE="$ROOT" FM_STATE_OVERRIDE="$H/state" \
  FAKE_HEALTH_FILE="$HEALTH" FM_LOGBOOK_REAP_MAX_STRIKES=3 bash "$ROOT/bin/fm-logbook-reap.sh" 2>/dev/null; }
st() { cat "$H/state/logbook-reap.state" 2>/dev/null || printf '(none)'; }
wake() { if [ -n "$1" ]; then printf '   CAPTAIN SEES A WAKE  ->  %s\n' "$1"; else printf '   (silent - housekeeping)\n'; fi; }

echo "=================================================================="
echo " SCENARIO 3b  Crash-looping board - revives but keeps dying"
echo "=================================================================="
printf '200' > "$HEALTH"
echo
echo "cycle 1: board's first death -> reap revives it (node binds)."
printf '000' > "$HEALTH"; out=$(reap); echo "   /health=$(cat "$HEALTH")  state: $(st)"; wake "$out"
for n in 1 2; do
  echo "cycle $((n+1)): the revived board died again before proving stable (non-sticking revival)."
  printf '000' > "$HEALTH"; out=$(reap); echo "   /health=$(cat "$HEALTH")  state: $(st)"; wake "$out"
done
echo "cycle 4 (give-up): the crash streak hits the ceiling."
printf '000' > "$HEALTH"; out=$(reap); echo "   /health=$(cat "$HEALTH")  state: $(st)"; wake "$out"
echo "cycle 5 (backed off): board still down, reap stays quiet and does NOT relaunch."
printf '000' > "$HEALTH"; out=$(reap); echo "   /health=$(cat "$HEALTH")  state: $(st)"; wake "$out"
echo
echo " -> distinct 'crash-looping' message, surfaced exactly once, then no thrash."
- Outcome: 🔧 1 issue found → auto-fixed ✅ across 2 runs (56m12s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ℹ️ bin/fm-bootstrap.sh:571 - In logbook_setup's missing-tool (curl/jq absent) cleanup, the guard is if [ -e &#34;$shim&#34; ] || [ -e &#34;$cadence&#34; ] and omits $reap_shim, unlike the opt-out block and logbook_remove_inbound_artifacts which were both updated to include it. Harmless today because the three artifacts are armed/removed atomically (so $reap_shim never exists without $shim), and the reap self-gates on curl+LOGBOOK_ENABLE, but the condition is inconsistent with its siblings. Add || [ -e &#34;$reap_shim&#34; ] for defensiveness and parity.
  • ℹ️ bin/fm-logbook-reap.sh:253 - While the board is down/launching the reap calls fm-logbook-up.sh every check cycle, and fm-logbook-up.sh spawns a fresh detached node server.mjs whenever /health is not 2xx without checking for a launch already in flight. A board that takes longer than one watcher cadence to bind, or crash-loops on boot, can therefore have multiple node processes race for the port (each extra one crashes on EADDRINUSE) before the wont-start/crash-loop streak gives up. Bounded by MAX_STRIKES and corrected on the next healthy cycle, and this non-idempotent-while-launching behavior is inherited from fm-logbook-up.sh rather than introduced here; the 15s default cadence usually gives ample bind time, so real accumulation is unlikely. Noting the tradeoff, not requesting a change.
🔧 **Test** - 1 issue found → auto-fixed ✅
  • 🚨 tests failed with exit code 1
  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"

🔧 Fix: fix pre-existing failing tests and turn-end guard stdin EPIPE crash
✅ Re-checked - no issues remain.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
  • for t in tests/*.test.sh; do bash &#34;$t&#34;; done — full suite, exit 0, no failures
  • bash tests/fm-logbook.test.sh — 54 checks pass incl. the 9 reap tests (hard no-op when off, silent revival, won't-start give-up, crash-loop give-up, single-death-not-crash-loop, stability reset, cadence-independence, recovery re-arm)
  • Ran the real bin/fm-logbook-reap.sh (calling the real bin/fm-logbook-up.sh) against a stub curl/node board across 5 captain-facing scenarios: /tmp/no-mistakes-evidence/01KXJGSXC7443P8VG7AFJT1HTS/reap-demo.sh
  • Ran a focused crash-loop demo to capture the second distinct diagnostic: /tmp/no-mistakes-evidence/01KXJGSXC7443P8VG7AFJT1HTS/reap-crashloop-demo.sh
  • git diff --name-only &lt;base&gt; &lt;target&gt; -- bin/fm-watch.sh — empty, confirming the reap is additive via the check rail
  • grep -n logbook-reap bin/fm-bootstrap.sh — confirms bootstrap wires state/logbook-reap.check.sh -> bin/fm-logbook-reap.sh
  • Reviewed docs/configuration.md 'Board liveness' — systemd --user unit + Restart=always + enable-linger and both load-bearing traps present
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 127)

🔧 Fix: scripts already lint-clean under pinned shellcheck 0.11.0
1 warning still open:

  • ⚠️ linter found issues (exit code 127)

🔧 Fix: no lint fixes needed; scripts clean under shellcheck 0.11.0
1 warning still open:

  • ⚠️ linter found issues (exit code 127)

🔧 Fix: no lint fixes needed; scripts pass shellcheck 0.11.0
1 warning still open:

  • ⚠️ linter found issues (exit code 127)
✅ **Push** - passed

✅ No issues found.

Nothing owned the board's liveness. It is a bare detached `node server.mjs`,
and bootstrap was its only launcher, so a board killed mid-session (an OOM kill
under crewmate memory pressure is the observed cause) stayed dead until the next
session start - silently, since the answer-loop poll just finds nothing to drain.

Add bin/fm-logbook-reap.sh, the body of a new state/logbook-reap.check.sh shim
that bootstrap drops on opt-in beside the poll shim. The watcher runs it every
check cycle (15s once logbook is on): it health-checks GET /health and, when the
board is down, brings it back through the existing idempotent fm-logbook-up.sh.

Riding the check rail keeps the watcher backbone untouched, preserving the
purely-additive guarantee in docs/configuration.md - fm-watch.sh, fm-watch-arm.sh,
fm-wake-lib.sh, fm-logbook-poll.sh and the afk daemon are all unchanged.

Reaping is housekeeping, so the reap is silent: a healthy board and a board it
revives both print nothing, which is exactly what the check rail defines as no
wake. Only a board it cannot fix speaks, once - after FM_LOGBOOK_REAP_MAX_TRIES
failed relaunches it emits one logbook-error line carrying the launcher's own
reason, deduped by state/logbook-reap.error on the state/logbook-poll.error
precedent, on the existing logbook-error wake kind so no new classification is
needed. The streak in state/logbook-reap.fails then gates retries to one every
FM_LOGBOOK_REAP_RETRY_INTERVAL, so a broken board self-heals without thrashing;
the counter is bumped before the attempt so a reap killed at the watcher's check
timeout still advances the backoff.

Inert unless opted in: bootstrap drops the shim only on opt-in and removes it on
opt-out, and the script hard no-ops without a truthy LOGBOOK_ENABLE.

Document the systemd --user unit (Restart=always + linger) as the recommended
setup where systemd exists, since it also covers "no firstmate session running at
all", with the reap as the portable fallback. Records both traps: LOGBOOK_DATA is
load-bearing (omit it and the board looks like it lost the captain's data), and
ExecStart needs an absolute node path.
The reap's anti-thrash guard used a rate/window/decay model that could not be
patched into correctness (three fixes, three new holes). Replace it wholesale
with two monotone streak counters plus a wall-clock stability reset - no window,
rate, decay, floor, or cadence assumption - so the reap behaves identically at
the 15s default cadence and the 300s away-mode cadence.

All state lives in one line of state/logbook-reap.state, "<phase> <ws> <cl>
<since>":
- wont-start streak (ws): consecutive relaunch attempts after which the board
  still does not answer /health. At FM_LOGBOOK_REAP_MAX_STRIKES it surfaces
  "logbook board won't start ..." once and stops relaunching until reset.
- crash-loop streak (cl): consecutive revivals that did not stick - the board
  came up but died again before it had been healthy for
  FM_LOGBOOK_REAP_STABLE_SECS. At the same bound it surfaces "logbook board is
  crash-looping ..." once and stops relaunching until reset.
- stability reset: once the board has been continuously healthy for STABLE_SECS
  since the last relaunch, both streaks and the diagnostic clear.

This kills all three defects by construction:
1. no decay-into-thrash: give-up is a terminal phase that stops relaunching; the
   only reset is wall-clock health, never a decaying in-window count.
2. no false crash-loop from one probe: a wake needs MAX_STRIKES consecutive
   non-sticking revivals, so a single miss self-corrects.
3. cadence-independent: give-up is by consecutive-cycle count and reset is by
   wall-clock health, so a broken board is diagnosed exactly once even under away
   mode, where the old 600s window could never hold enough events to give up.

Drops FM_LOGBOOK_REAP_RETRY_INTERVAL and the mtime-schedule; adds
FM_LOGBOOK_REAP_STABLE_SECS and renames MAX_TRIES to MAX_STRIKES. Keeps every
prior property: strictly additive (zero watcher-backbone diff), silent on
revival (out of the wake rail), a hard no-op when logbook is off, bounded and
non-blocking, and reusing the idempotent fm-logbook-up.sh for the launch.

Rewrites the colocated reap tests to the streak model (regressions for each of
the three defects) and corrects docs/configuration.md "Board liveness", AGENTS.md
section 2, and the logbook-respond skill, which described the old model.
@SchokoShake
SchokoShake force-pushed the fm/logbook-supervise-b4 branch from 870c8c5 to e2beb42 Compare July 15, 2026 11:13
@SchokoShake
SchokoShake merged commit 830c27d into main Jul 15, 2026
@SchokoShake
SchokoShake deleted the fm/logbook-supervise-b4 branch July 15, 2026 11:28
SchokoShake added a commit that referenced this pull request Jul 21, 2026
…awn reuse

Address the review on PR #7:

- treehouse_reservation replaces the boolean holds-check and captures the
  `treehouse status` exit code separately, so a treehouse outage reports
  could-not-ask instead of a false "no longer reserves" on every respawn (#1).
- Match the leased `(held by <holder>)` against this task's fm-<id>, so a
  worktree treehouse re-leased to a different task is caught, not silently
  adopted; an in-use row carries no holder, so the gate only strengthens (#3).
- Cover the lease-release trap for a turn-end hook-block failure between the
  lease and the meta write, the leak class new to this change (#2).
- Record the deliberate readiness-barrier trade at the cd site, marking the
  brief's isolation assertion load-bearing and forbidding a re-added pane probe (#4).
- Make the two treehouse human-text couplings a conscious v2.0.0 assumption;
  v2.0.0 has no --json/--porcelain and both fail loud-but-wrong (#5).

The test treehouse stub now records the real --lease-holder so status renders
the caller's fm-<id>, exercising the holder match faithfully.
SchokoShake added a commit that referenced this pull request Jul 22, 2026
…ane-cwd discovery (#7)

* fix(spawn): capture crew worktree via treehouse get --lease; guard against $FM_HOME

Every projects/* spawn recorded worktree=$FM_HOME (the primary checkout) in
state/<id>.meta instead of the crew's real ~/.treehouse/... worktree, forcing a
manual repair each time and risking teardown/review on the wrong path. The crew
itself was always fine; firstmate-self spawns were immune.

Root cause: worktree discovery sent `treehouse get` into the pane and polled
#{pane_current_path} until it differed from the project dir, taking that as the
worktree. Right after `tmux new-window -c <project>`, the pane process is still
the forked tmux-server child (the shell has not yet exec'd and chdir'd), so
#{pane_current_path} transiently reports the tmux SERVER's own cwd - $FM_HOME
(the server was started there) - before settling on the -c dir a moment later.
The poll's "any path != project dir" exit latched that transient $FM_HOME on the
first iteration of a projects/* spawn ($FM_HOME != $FM_HOME/projects/<repo>),
before `treehouse get` even ran; a firstmate-self spawn ($FM_HOME == project dir)
kept polling to the real worktree - the exact projects/*-only signature. kunchenguid#134's
stable-window-id targeting could not help: the correctly-targeted pane
transiently reports the server cwd.

Fix (bin/fm-spawn.sh):
- Capture authoritatively: lease from fm-spawn itself with `treehouse get
  --lease` (prints only the ~/.treehouse/... path to stdout, banners to stderr)
  and cd the pane into that exact path. No poll, no startup-transient race.
  worktree= and the turn-end hook use the leased path; fm-teardown's existing
  `treehouse return --force <worktree=>` releases it, same as before. Consistent
  with fm-home-seed.sh's existing lease pattern. Applies to every non-orca
  backend and to batch (which re-execs the single path per pair).
- Loud backstop in validate_spawn_worktree: assert the worktree is not the
  primary checkout ($FM_HOME/$FM_ROOT). Because firstmate is a git repo of
  itself, $FM_HOME is a valid git toplevel that cleared every prior clause
  silently; now a regression aborts loudly instead of corrupting meta.

Tests updated to the lease-based capture; new cases pin real-worktree capture
(never $FM_HOME) and the $FM_HOME abort. Docs: tmux-backend.md gains a
root-cause/verification section; architecture.md and herdr-backend.md corrected.
Root cause reproduced with tmux 3.6; fix verified end-to-end against real
treehouse (worktree= records a real .treehouse/... path, pane cd's into it).

Refs fm-spawn-wt-batch-x5.

* test(spawn): strengthen symlinked-prefix test with a tangle case guarding PROJ_ABS_REAL

Review (decision A, captain rule: fix the root cause, do not soften) found the
reframed test_spawn_symlinked_project_prefix_avoids_false_refusal no longer
exercised the PROJ_ABS_REAL canonicalization its comment claimed to guard: its
leased worktree was entirely distinct from the project, so validate_spawn_worktree's
only project-dependent clause (wt_real == proj_real) was never near-triggered and
the test would pass even if PROJ_ABS_REAL regressed to a logical PROJ_ABS.

Add a tangle case: the treehouse stub leases the PROJECT ITSELF reached back
through the symlinked prefix (physical path equal to the project), and the spawn
must be REFUSED with "did not yield an isolated worktree". That refusal holds
ONLY because validate_spawn_worktree resolves both sides with pwd -P; were
PROJ_ABS_REAL the logical PROJ_ABS the physical worktree path would compare
unequal and the tangle would be wrongly allowed. Test-only; bin/fm-spawn.sh
unchanged.

Refs fm-spawn-wt-batch-x5.

* no-mistakes(review): fix(spawn): release treehouse lease on abort; drop dead current_path ops

* no-mistakes(review): fix(spawn): reuse recorded worktree on respawn; refresh stale adapter docs

* no-mistakes(review): fix(spawn): gate respawn reuse on meta identity and lease reservation

* no-mistakes(review): extend respawn identity gate to recorded backend

* no-mistakes(review): scope respawn backend refusal to orca; derive --help range

* no-mistakes(document): sync backend docs with treehouse-lease worktree capture and respawn

* fix(spawn): distinguish treehouse-status failure and re-lease on respawn reuse

Address the review on PR #7:

- treehouse_reservation replaces the boolean holds-check and captures the
  `treehouse status` exit code separately, so a treehouse outage reports
  could-not-ask instead of a false "no longer reserves" on every respawn (#1).
- Match the leased `(held by <holder>)` against this task's fm-<id>, so a
  worktree treehouse re-leased to a different task is caught, not silently
  adopted; an in-use row carries no holder, so the gate only strengthens (#3).
- Cover the lease-release trap for a turn-end hook-block failure between the
  lease and the meta write, the leak class new to this change (#2).
- Record the deliberate readiness-barrier trade at the cd site, marking the
  brief's isolation assertion load-bearing and forbidding a re-added pane probe (#4).
- Make the two treehouse human-text couplings a conscious v2.0.0 assumption;
  v2.0.0 has no --json/--porcelain and both fail loud-but-wrong (#5).

The test treehouse stub now records the real --lease-holder so status renders
the caller's fm-<id>, exercising the holder match faithfully.

* no-mistakes(document): sync tmux worktree-capture doc with --lease-holder flag

---------

Co-authored-by: SchokoShake <[email protected]>
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.

1 participant