Repository navigation
feat(logbook): supervise the attention board's liveness with a watcher reap - #3
Merged
Merged
Conversation
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.
…stdin EPIPE crash
SchokoShake
force-pushed
the
fm/logbook-supervise-b4
branch
from
July 15, 2026 11:13
870c8c5 to
e2beb42
Compare
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
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.
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:
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.
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
bin/fm-logbook-reap.sh, a watcher-side liveness reap wired throughstate/logbook-reap.check.shinbin/fm-bootstrap.sh: each check cycle it health-checks the board (curl LOGBOOK_URL/health) and relaunches a dead one via the idempotentbin/fm-logbook-up.sh, staying a hard no-op when logbook is not opted in and never manufacturing acheck:/signal:wake for the housekeeping.state/dedupe marker and stop relaunching until the board has been continuously healthy forSTABLE_SECS, giving identical behavior at 15s and 300s watcher cadences.systemd --userunit (Restart=always+enable-linger, with theLOGBOOK_DATAand absolute-node-path traps called out) as the recommended setup and the reap as the portable fallback, rewritetests/fm-logbook.test.shto 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)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 relaunchEvidence: Reap demo harness (drives real fm-logbook-reap.sh + fm-logbook-up.sh)
Evidence: Crash-loop demo harness
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-bootstrap.sh:571- In logbook_setup's missing-tool (curl/jq absent) cleanup, the guard isif [ -e "$shim" ] || [ -e "$cadence" ]and omits$reap_shim, unlike the opt-out block andlogbook_remove_inbound_artifactswhich were both updated to include it. Harmless today because the three artifacts are armed/removed atomically (so$reap_shimnever exists without$shim), and the reap self-gates on curl+LOGBOOK_ENABLE, but the condition is inconsistent with its siblings. Add|| [ -e "$reap_shim" ]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 detachednode server.mjswhenever /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 ✅
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 "$t"; done— full suite, exit 0, no failuresbash 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.shRan a focused crash-loop demo to capture the second distinct diagnostic: /tmp/no-mistakes-evidence/01KXJGSXC7443P8VG7AFJT1HTS/reap-crashloop-demo.shgit diff --name-only <base> <target> -- bin/fm-watch.sh— empty, confirming the reap is additive via the check railgrep -n logbook-reap bin/fm-bootstrap.sh— confirms bootstrap wires state/logbook-reap.check.sh -> bin/fm-logbook-reap.shReviewed docs/configuration.md 'Board liveness' — systemd --user unit + Restart=always + enable-linger and both load-bearing traps present✅ **Document** - passed
✅ No issues found.
🔧 Fix: scripts already lint-clean under pinned shellcheck 0.11.0
1 warning still open:
🔧 Fix: no lint fixes needed; scripts clean under shellcheck 0.11.0
1 warning still open:
🔧 Fix: no lint fixes needed; scripts pass shellcheck 0.11.0
1 warning still open:
✅ **Push** - passed
✅ No issues found.