Repository navigation
fix(afk): release the away-mode launcher lock on a signal during acquisition - #5
Merged
Merged
Conversation
fm_afk_launch_main acquired the launcher lock and only then armed the EXIT/INT/TERM traps. A SIGTERM or SIGINT landing in that window killed the process with the lock held but no cleanup trap installed, leaking the lock: the default signal disposition terminates without running the not-yet-armed EXIT trap. This made the signal case in tests/fm-afk-launch.test.sh flaky and could strand a later away-mode start on the stale lock. Arm the EXIT/INT/TERM traps before acquisition. fm_afk_launch_lock_release only removes a lock this process owns (pid stamped) or created but had not yet published, so arming it early never touches another launcher's lock and always releases ours. A new FM_AFK_LAUNCH_LOCK_MINE marker lets release clean up the directory even if a signal fires in the tiny mkdir-then-stamp-pid gap. Rewrite the signal unit to deliver TERM deterministically while the launcher is inside acquire (an fm_pid_identity synchronization seam) instead of racing a poll-then-kill, so it fails on the old ordering and passes on the new one regardless of machine timing.
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
Fix a lock-leak trap race in firstmate's away-mode launcher bin/fm-afk-launch.sh that made tests/fm-afk-launch.test.sh flaky and could strand a later away-mode start on a leaked lock. This is firstmate's own shared, tracked material, shipped through the no-mistakes gate.
Root cause: fm_afk_launch_main acquired the launcher lock and only THEN armed the EXIT/INT/TERM traps. A SIGTERM or SIGINT landing in that window terminated the process under the default signal disposition, which skips the not-yet-armed EXIT trap, so the lock directory was never released (leaked).
Deliberate fix decisions in bin/fm-afk-launch.sh:
The normal-path cleanup (release then trap - EXIT INT TERM at the end of fm_afk_launch_main) is intentionally unchanged.
Deliberate test decisions in tests/fm-afk-launch.test.sh (unit_signal_exits_with_lock_cleanup):
Verification performed before committing: the rewritten unit fails 15/15 on the old ordering and passes 15/15 on the new ordering; the full tests/fm-afk-launch.test.sh passes 10/10 in a loop; and bin/fm-lint.sh (the full canonical shellcheck set both gates run) is clean with exit 0 and zero findings. No Markdown was changed. No project files outside firstmate were touched.
What Changed
EXIT/INT/TERMcleanup traps beforefm_afk_launch_lock_acquireinstead of after, and clear them on the acquire-failure path (trap - EXIT INT TERM), so a signal landing while the lock is held now releases it; the old arm-after-acquire ordering let the defaultINT/TERMdisposition kill the process before any trap was installed, leaking the lock directory and potentially stranding a later away-mode start.FM_AFK_LAUNCH_LOCK_MINEmodule marker, set the instant this process's ownmkdircreates the lock directory and reset on release or on each acquire rollback path, plus a new clause infm_afk_launch_lock_releaseso it also reclaims a self-created-but-not-yet-pid-stamped lock while never touching a peer launcher's lock; the trap-guarantee comments were corrected to acknowledge the residual mkdir-call window that acquire's initialization-grace path reaps on the next start.unit_signal_exits_with_lock_cleanuptest to deliverTERMdeterministically while the launcher is provably inside acquisition — using anfm_pid_identityoverride as a synchronization seam in place of the flaky poll-the-lock-dir-then-kill approach — and switch the keep-alive stub from a singlesleep 30to an interruptible short-sleep loop so the deferred trap fires promptly.Risk Assessment
✅ Low: A tightly-scoped, well-reasoned trap-ordering fix plus an accuracy-only comment correction; the release guard provably never touches a peer's lock, all failure/rollback paths reset the new marker and clear traps, and the previously-flagged comment overclaim is now corrected to match the real guarantee.
Testing
Baseline test command and the full tests/fm-afk-launch.test.sh suite both pass (exit 0). I then isolated the fixed test into a focused runner and ran paired controls: 15/15 passes against the fixed launcher (confirming the previously-flaky signal case is now deterministic) and 14/14 deterministic failures against a faithful copy of the pre-fix launcher (confirming the rewritten test actually detects the leak rather than passing vacuously). A CLI transcript artifact demonstrates the real end-user consequence — a SIGTERM while the launcher holds its lifecycle lock leaves the lock directory leaked on the old ordering (would strand a later away-mode start) and released on the fix. This is a shell/CLI-only change with no UI surface, so no visual artifact applies; the CLI transcript is the appropriate end-user-visible evidence. Worktree left clean, all scratch under the evidence dir.
Evidence: Lock leaked (pre-fix) vs released (fixed) after SIGTERM — product demo transcript
== PRE-FIX launcher (28b741d, arm-after-acquire) == lock held before signal? YES (pid=2472601) RESULT: lock directory STILL PRESENT after TERM -> LEAKED (next away-mode start would be stranded) == FIXED launcher (d7a50ba, arm-before-acquire) == lock held before signal? YES (pid=2472640) RESULT: lock directory gone after TERM -> RELEASED (clean; next start unblocked)Evidence: Paired-control loop results (flakiness fix + detector validity)
Evidence: Reproducible leak-demo script
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 1 issue found → auto-fixed ✅
bin/fm-afk-launch.sh:93- The FM_AFK_LAUNCH_LOCK_MINE marker is set on line 93, the statement immediately AFTERmkdirsucceeds (line 92) - but bash runs a caught signal's trap that arrives whilemkdiris the foreground command only after mkdir returns, and it runs the deferred trap BEFORE executing line 93. So a TERM/INT landing during the mkdir at line 92 fires the EXIT trap -> fm_afk_launch_lock_release with FM_AFK_LAUNCH_LOCK_MINE still 0 and the just-created (un-stamped) lock directory present; the release guard ([ pid = $$ ]false,[ MINE = 1 ]false) declines to remove it, leaking the lock. I reproduced this 3/3 with a faithful model of the mkdir->MINE=1 sequence (leaked dirs, has-pid=no). This is the exact leak class the change set out to eliminate, so the code comments' guarantee ('released no matter when a signal lands', line 619; 'set to 1 the instant this process's own mkdir creates the lock directory', line 70) is not literally true - the mkdir command's own execution remains uncovered. It is a large improvement and not a regression (the old code leaked this window and much more), and the rewritten test can't observe it because it synchronizes via fm_pid_identity, which runs after the pid stamp. To fully close it: set FM_AFK_LAUNCH_LOCK_MINE=1 on the line BEFOREmkdirand reset it to 0 in the mkdir-failure/else path (release would then reclaim our own just-created empty dir; weigh the narrower, session-lock-mitigated peer-dir race this introduces), or otherwise soften the comment's guarantee to acknowledge the residual mkdir window rather than assert full closure.🔧 Fix: correct fm-afk-launch lock trap comments to match real guarantee
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
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"bash tests/fm-afk-launch.test.sh(full suite, exit 0; includes 'launcher signal: TERM during lock acquisition releases the held lock')Positive control: focusedunit_signal_exits_with_lock_cleanuprunner against the fixed launcher x15 -> 15/15 PASS deterministicallyNegative control: same runner againstgit show 28b741d:bin/fm-afk-launch.sh(real pre-fix arm-after-acquire ordering) x14 (9 + bounded 5) -> 14/14 FAIL deterministicallyProduct demo: launched fm_afk_launch_main via the fm_pid_identity sync seam, sent SIGTERM while the lock was held, and inspected the .afk-launch.lock directory afterward for pre-fix (leaked) vs fixed (released)✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.