Skip to content

fix(herdr): restore restarted workers in their worktree, not the primary checkout - #7856

Closed
rob-mur wants to merge 12 commits into
kunchenguid:mainfrom
rob-mur:fm/fm-herdr-restore-cwd
Closed

rob-mur wants to merge 12 commits into
kunchenguid:mainfrom
rob-mur:fm/fm-herdr-restore-cwd

Conversation

@rob-mur

@rob-mur rob-mur commented Oct 27, 2026 •

Copy link
Copy Markdown

Intent

Make a patch so a Herdr server restart no longer resumes firstmate workers in the wrong folder, and open a PR for it upstream.

Context: after a Herdr restart, Herdr (0.9.5, [session] resume_agents_on_restore, on by default) resumed every herdr-backed worker's agent session (claude --resume <id>) in the pane's saved cwd. For every ordinary spawn that saved cwd is the project's primary checkout (e.g. <home>/projects/aegis), not the worker's isolated worktree, so all restored workers ended up running in the primary checkout. Because projects/ sits inside the firstmate home, Claude also offered to import the home's own AGENTS.md (an "Allow external CLAUDE.md file imports?" dialog), and the project's direnv reported .envrc blocked. Herdr's session.json showed panes with "cwd": "<home>/projects/aegis" and an agent_session id belonging to the session recorded under the worktree path.

We need to make sure that restarts in general don't lose these kinds of workers.

What Changed

  • Spawn: a fresh Herdr ship/scout now leases its slot up front with treehouse get --lease --lease-holder <id> and opens its task pane in that worktree. Before, the pane opened in the project's primary checkout and ran an interactive treehouse get inside it. Herdr restores a pane, and resumes its agent, in the pane's top-level shell cwd, so after this change a restart brings the worker back in its worktree.
  • Restart recovery: a same-id spawn over an existing record reuses the slot the record still has leased. That happens only when the recorded pane holds no agent, Treehouse reports the slot leased to this id, and the slot claim names this task. Otherwise the spawn leases a new slot.
  • Abort cleanup and teardown:
    • When a spawn aborts, it returns the lease only if no record names the slot, no launch was sent, and no pane is left in the slot. fm_backend_herdr_projection_cleanup_exact now reports whether the task-pane close was confirmed, and abort cleanup uses that for the last check. If a pane may still be there, or the worktree is dirty or couldn't be inspected, the lease stays and the spawn prints the treehouse return --force command to run.
    • Teardown now closes the Herdr pane (focus-preserving, lock held) before it reaps the worktree's processes or returns the worktree. The pane's shell now lives in the worktree, so the reap would otherwise kill it.
    • The Herdr docs, verification notes, presentation e2e test and relaunch test are updated to match.

🤖 Generated with Claude Code

Risk Assessment

⚠️ Medium: The change reorders Herdr spawn and teardown lifecycles: durable leases, same-id slot reuse, and closing the pane before the worktree return. Earlier review findings are fixed and I found no new blocking defect, but the teardown reorder is still unconfirmed on the Herdr 0.7.4 that CI runs.

Testing

I drove three checks. First, a real Claude crewmate through a real Herdr 0.9.5 lab-session restart with agent resume on: the pane's saved cwd, the restored pane's cwd and the resumed claude --resume process cwd were all the leased worktree, and teardown left no lease. Second, the real-Herdr presentation e2e passed in full; it covers restored-pane cwd, reusing the same-id leased worktree on reclaim, the opted-out tab's --cwd, lease return on abort cleanup, and no leftover leases after teardown. Third, the hermetic relaunch suite passed every case it could run on this host. That needed a temporary copy that calls sleep from PATH instead of /bin/sleep (missing on NixOS) and skips the case that needs pi, which is not installed. The guard for a slot whose status can't be read is covered only by that hermetic test, so it is marked untested here. I made no source changes, and all lab sessions, lab homes and temp files were removed.

  • Live validation: ✅ go - 5 of 6 scenarios driven live against the product
Scenario Result Live Evidence
After a Herdr restart with agent resume on, a real Claude crewmate is resumed (claude --resume) in its own worktree, not the project's primary checkout ✅ pass live claude-restart-live.log: the session.json pane cwd, the restored pane get cwd and the resumed process cwd from /proc and process-info were all ~/.treehouse/demo-eb7512/1/demo
A fresh projected task's pane is restored in its recorded worktree after a lab restart, and the same-id reclaim reuses that leased worktree instead of leasing a second slot ✅ pass live presentation-e2e.log: 'Hi Bit and Wheelhouse-style same-identity restarts reclaim one nested space with exact focus and idempotence' (asserts RESTORED_CWD == worktree and NEW_RESTART_WT == OLD_RESTART…
An opted-out flat spawn opens its task tab with --cwd set to its leased worktree ✅ pass live presentation-e2e.log: 'an opted-out spawn retains the Stage 1 Herdr command sequence with zero ordering calls'
Teardown after restart recovery leaves no pool slot leased to the task, closing the pane once under the session lock ✅ pass live presentation-e2e.log restart case (treehouse status lease check); claude-restart-live.log: teardown rc=0 with 0 leases held
Adversarial: a spawn that aborts after creating its pane in a leased slot returns every lease it took and restores focus ✅ pass live presentation-e2e.log: 'concurrent post-create abort cleanup stays serialized with exact focus restoration' (leases == returns)
Adversarial: a leased slot whose git status cannot be read is kept leased, never force-returned, and no pane is opened in it ⏸️ untested no The prior payload did not establish a live result. Only the hermetic stubbed-git test covers this guard ('fm-spawn herdr: a fresh spawn keeps a leased slot it could not inspect instead of force-return…
Evidence: Real-Claude Herdr restart transcript (saved/restored pane cwd, resumed claude cwd, teardown leases)

Source: Real-Claude Herdr restart transcript (saved/restored pane cwd, resumed claude cwd, teardown leases)

95:resume_agents_on_restore = true
lab session=fm-lab-claude-cwd-1029685-30542 home=/tmp/fm-lab.eDOQb2
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.eDOQb2
warning: /tmp/fm-lab.eDOQb2/data/democwd/launch-brief.md records no ship branch; defaulting to legacy branch fm/democwd
warning: /tmp/fm-lab.eDOQb2/data/democwd/launch-brief.md records no delivery contract line (scaffolded before ship briefs recorded one); launching on the explicit --mode local-only - confirm its definition of done matches
notice: democwd ships mode=local-only while the standing posture for demo is no-mistakes - less rigor than the captain's standing posture; proceed only on a current explicit captain instruction or an intake judgment you can state
🌳 Setting up worktree...
🌳 Leased worktree at ~/.treehouse/demo-eb7512/1/demo. Run 'treehouse return ~/.treehouse/demo-eb7512/1/demo' to release it.
warning: herdr presentation parent is absent or ambiguous; using the ordinary flat layout without projection
spawned democwd harness=claude kind=ship mode=local-only yolo=off window=fm-lab-claude-cwd-1029685-30542:w1:p2 worktree=~/.treehouse/demo-eb7512/1/demo
--- meta
worktree=~/.treehouse/demo-eb7512/1/demo
backend=herdr
herdr_session=fm-lab-claude-cwd-1029685-30542
herdr_pane_id=w1:p2
--- before restart (agent status: idle)
{"cwd":"~/.treehouse/demo-eb7512/1/demo","foreground_cwd":"~/.treehouse/demo-eb7512/1/demo"}
worktree=~/.treehouse/demo-eb7512/1/demo
--- saved session.json (~/.config/herdr/sessions/fm-lab-claude-cwd-1029685-30542/session.json)
[{"cwd":"~/.treehouse/demo-eb7512/1/demo","agent_session":{"source":"herdr:claude","agent":"claude","kind":"id","value":"d5db30ac-4b8c-4b3f-9e7f-75574f930bc1"}}]
--- after restart
{"cwd":"~/.treehouse/demo-eb7512/1/demo","foreground_cwd":"~/.treehouse/demo-eb7512/1/demo","agent_status":"idle"}
{"id":"cli:pane:process_info","result":{"process_info":{"foreground_process_group_id":1049426,"foreground_processes":[{"argv":["~/.nix-profile/bin/claude","--resume","d5db30ac-4b8c-4b3f-9e7f-75574f930bc1"],"cmdline":"~/.nix-profile/bin/claude --resume d5db30ac-4b8c-4b3f-9e7f-75574f930bc1","cwd":"~/.treehouse/demo-eb7512/1/demo","name":".claude-wrapped","pid":1049426}],"pane_id":"w1:p2","shell_pid":1048870},"type":"pane_process_info"}}

resumed pid=1049426 cmd=~/.nix-profile/bin/claude --resume d5db30ac-4b8c-4b3f-9e7f-75574f930bc1  cwd=~/.treehouse/demo-eb7512/1/demo
--- teardown task
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
warning: lsof is unavailable; cannot resolve a process-group fallback for herdr task democwd
🌳 Worktree returned to pool.
teardown democwd complete (window fm-lab-claude-cwd-1029685-30542:w1:p2, worktree ~/.treehouse/demo-eb7512/1/demo)
Backlog: democwd just finished (this home keeps no markdown backlog at /tmp/fm-lab.eDOQb2/data/backlog.md). Update /tmp/fm-lab.eDOQb2/data/backlog.md - move democwd to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
teardown task rc=0
--- leases held by democwd after teardown
0
teardown rc=0
Evidence: Script that drove the real-Claude restart check

Source: Script that drove the real-Claude restart check

#!/usr/bin/env bash
# Live check: real Claude crewmate spawned via fm-spawn --backend herdr into a lab
# home, Herdr lab session restarted with resume_agents_on_restore=true, then the
# restored pane cwd and the resumed claude process cwd are read.
set -u
ROOT=$PWD
H=$ROOT/bin/fm-herdr-lab.sh
unset HERDR_PANE_ID HERDR_TAB_ID HERDR_WORKSPACE_ID HERDR_SOCKET_PATH HERDR_ENV NO_MISTAKES_GATE FM_GATE_REFUSE_BYPASS FM_ROOT_OVERRIDE FM_STATE_OVERRIDE FM_DATA_OVERRIDE FM_CONFIG_OVERRIDE FM_PROJECTS_OVERRIDE
LAB=$(mktemp -d "${TMPDIR:-/tmp}/fm-lab.XXXXXX")
"$ROOT/bin/fm-lab-home.sh" create "$LAB" >/dev/null
CFGDIR=$(mktemp -d /tmp/fm-lab-cfg.XXXXXX)
sed 's/^resume_agents_on_restore = false/resume_agents_on_restore = true/' ~/.config/herdr/config.toml > "$CFGDIR/config.toml"
grep -n resume_agents "$CFGDIR/config.toml"
export HERDR_CONFIG_PATH="$CFGDIR/config.toml"
S=$("$H" name claude-cwd); export HERDR_SESSION=$S
echo "lab session=$S home=$LAB"
cleanup() {
  [ -n "${WT:-}" ] && treehouse return --force "$WT" >/dev/null 2>&1
  "$H" teardown "$S" >/dev/null 2>&1; echo "teardown rc=$?"
  rm -rf "$LAB" "$CFGDIR"
}
trap cleanup EXIT
"$H" provision "$S" || exit 1
P=$LAB/projects/demo; mkdir -p "$P"
git -C "$P" init -q -b main; echo demo > "$P/README.md"; git -C "$P" add .; git -C "$P" -c user.name=t -c user.email=t@e commit -qm init
git clone -q --bare "$P" "$P.origin.git"; git -C "$P" remote add origin "file://$P.origin.git"
ID=democwd
mkdir -p "$LAB/data/$ID"
cat > "$LAB/data/$ID/brief.md" <<B
# Task
## Captain's intent
Reply with the single word READY and then stop. Do not edit any files.

## Firstmate spec
Reply READY. Make no changes.
B
FM_HOME="$LAB" FM_SPAWN_NO_GUARD=1 "$ROOT/bin/fm-spawn.sh" $ID "$P" --mode local-only --yolo off --harness claude --backend herdr 2>&1 | tail -15
echo "--- meta"; cat "$LAB/state/$ID.meta" | grep -E '^(worktree|herdr_pane_id|herdr_session|backend)='
WT=$(grep '^worktree=' "$LAB/state/$ID.meta" | cut -d= -f2-)
PANE=$(grep '^herdr_pane_id=' "$LAB/state/$ID.meta" | cut -d= -f2-)
for i in $(seq 1 60); do
  st=$("$H" run "$S" pane get "$PANE" | jq -r '.result.pane.agent_status // .result.pane.agent_state // empty'); [ "$st" = idle ] && break; sleep 3; done
echo "--- before restart (agent status: $st)"
"$H" run "$S" pane get "$PANE" | jq -c '.result.pane | {cwd, foreground_cwd}'
echo "worktree=$WT"
"$H" stop "$S" >/dev/null || echo STOPFAIL
SJ=$(ls -d ~/.config/herdr/sessions/"$S"/session.json "$CFGDIR"/sessions/"$S"/session.json 2>/dev/null | head -1)
echo "--- saved session.json ($SJ)"
[ -n "$SJ" ] && jq -c '[.. | objects | select(.agent_session? != null)] | map({cwd, agent_session})' "$SJ"
"$H" provision "$S" >/dev/null || echo PROVFAIL
sleep 15
echo "--- after restart"
"$H" run "$S" pane get "$PANE" | jq -c '.result.pane | {cwd, foreground_cwd, agent_status}'
"$H" run "$S" pane process-info --pane "$PANE" | jq -c '.' | head -c 1500; echo
for pid in $(pgrep -f 'claude --resume'); do
  c=$(readlink /proc/$pid/cwd); case "$c" in "$LAB"*|*treehouse*demo*) echo "resumed pid=$pid cmd=$(tr '\0' ' ' < /proc/$pid/cmdline) cwd=$c";; esac
done
echo "--- teardown task"
FM_HOME="$LAB" "$ROOT/bin/fm-teardown.sh" $ID --force 2>&1 | tail -5; echo "teardown task rc=${PIPESTATUS[0]}"
echo "--- leases held by $ID after teardown"
(cd "$P" && treehouse status --json | jq -r --arg id $ID '[.[] | select(.lease_holder == $id) | .path] | length')
Evidence: Real-Herdr lab presentation e2e output

Source: Real-Herdr lab presentation e2e output

ok - real Herdr lab: an opted-out spawn retains the Stage 1 Herdr command sequence with zero ordering calls
ok - real Herdr lab: a home that configured nothing is projected by default on herdr 0.9.5
ok - real Herdr lab: every projected create, task-tab create, seeded prune, and move preserves active workspace and tab
ok - real Herdr lab: persisted-focused seeded prune proceeds when no live client is attached
ok - real Herdr lab: bounded lock contention warns and falls back flat without projection or focus drift
ok - real Herdr lab: concurrent primary workers form one stable contiguous block without active workspace/tab drift
ok - real Herdr lab: forced workspace.move failure leaves a successful worker in default order with a warning and no cleanup
ok - real Herdr lab: concurrent post-create abort cleanup stays serialized with exact focus restoration
ok - real Herdr lab: Treehouse commands and metadata shape are byte-identical except for endpoint IDs and spawn incarnation
ok - real Herdr lab: exact task-pane close removes the projected workspace with no unrestored wrong-focus interval
ok - real Herdr lab: concurrent projected cleanup is serialized and leaves active workspace/tab unchanged
ok - real Herdr lab: three repeated concurrent create/order/cleanup waves have zero active workspace or tab drift
ok - real Herdr lab: the primary presentation setting inherits into real secondmate homes
ok - real Herdr lab: primary and two secondmate homes each own a top-level contiguous child block
ok - real Herdr lab: concurrent primary/A/B spawns preserve parent order and exact focus
ok - real Herdr lab: session lock contention from a secondmate home falls back flat with no journal
ok - real Herdr lab: Hi Bit and Wheelhouse-style same-identity restarts reclaim one nested space with exact focus and idempotence
ok - real Herdr lab: secondmate restart binding and reclaim stay isolated to the exact child home and parent
ok - real Herdr lab: concurrent cross-home recoveries replace exact husks under one session lock with no focus drift
ok - real Herdr lab: default resumed identity refuses session lock contention
ok - real Herdr lab: --herdr-resume-lock-wait waits out session lock contention instead of refusing
ok - real Herdr lab: legacy projection labels and flat secondmate tabs are left unmigrated
ok - real Herdr lab: multi-home exact-pane teardowns restore captain focus without workspace close authority
warning: no exact herdr presentation token match for missing1; leaving any stale space untouched and spawning flat
warning: no exact herdr presentation token match for renamed1; leaving any stale space untouched and spawning flat
warning: 2 exact herdr presentation token matches for duplicate1 are quarantined; inspecting only for duplicate-agent risk
warning: quarantined herdr presentation for duplicate1 is dead or agent-free; exact bound reclaim may proceed, otherwise spawning flat
warning: 2 exact herdr presentation token matches for duplicate1 are quarantined; inspecting only for duplicate-agent risk
error: quarantined herdr presentation for duplicate1 has a stale-agent pane; refusing duplicate launch
ok - real Herdr lab: missing, renamed, and duplicate tokens trigger zero destructive or adoptive calls, and live duplicate risk refuses launch
ok - real Herdr lab validation completed on Herdr 0.9.5 with the default-session tripwire intact
env -u NO_MISTAKES_GATE HERDR_LAB_HELPER=bin/fm-herdr-lab.sh bash   148.13s user 131.66s system 82% cpu 5:38.65 total
Evidence: Hermetic relaunch suite output

Source: Hermetic relaunch suite output

ok - fm-spawn --relaunch: tracked opencode wiring is retired as on main
ok - fm-control removes the dialog file after exit and after relaunch
ok - fm-control exit removes the dialog file before it releases the control lock
ok - fm-control relaunch: a same-harness relaunch replaces the agent in the same endpoint and worktree
ok - fm-control relaunch: pending composer text refuses before the exit command is typed
ok - fm-control relaunch: an unreadable composer fails safe before the exit command is typed
ok - fm-control relaunch: a linked spawning home preserves committed and unfinished work in the recorded copy
ok - fm-control relaunch: durable task metadata survives replacement launch publication
ok - fm-control relaunch: delivery and concurrent task metadata publication serialize
ok - fm-control relaunch: disabling tracing clears metadata and pane context
ok - fm-control relaunch: progress and the Firstmate-worktree worker identity reach the replacement
ok - fm-control relaunch: the progress note's inbox listing is silent on an empty inbox
ok - fm-control relaunch: a ship task refuses without the progress note its replacement needs
ok - fm-control relaunch: switching harness is one ordinary relaunch, and the old wiring goes with the old agent
ok - fm-control relaunch: a refused relaunch onto polytoken keeps the project's own hook layer and the running agent
ok - fm-control relaunch: a refused polytoken profile leaves the running agent untouched
ok - fm-spawn --relaunch: retiring a raw polytoken launch's wiring keeps the project's own layers
ok - fm-control relaunch: a harness switch resets model and effort unless they are named too
ok - fm-control relaunch: a prefixed recorded harness can switch adapters transactionally
ok - fm-control relaunch: a prefixed command requires an explicit replacement harness
ok - fm-control relaunch: a same-harness relaunch keeps the profile axes it was running with
ok - native Ultra relaunch preserves its profile and rejects an unsupported model before stopping
ok - fm-control relaunch: a signed-out worker account pin refuses before the old agent stops
ok - fm-control relaunch: the replacement follows the home's current worker account pin
ok - fm-control relaunch: mate pins are re-read for Claude and Pi, and unusable pins refuse before stopping the agent
ok - fm-control relaunch: a Pi replacement keeps the home's tool exclusions
ok - fm-control relaunch: exclusion-list refusals happen before the running agent stops
ok - fm-control relaunch: explicit model and effort win over the recorded ones
ok - fm-control relaunch: refuses to relaunch onto an adapter with no verified mechanics
ok - fm-control relaunch: the retired incarnation's global turn-end token is revoked
ok - fm-control relaunch: wiring cleanup failure refuses replacement arming
ok - fm-control-lib: one owner resolves each harness's turn-end registry entry, and refuses a malformed token
ok - fm-control relaunch: a secondmate relaunch re-resolves its durable configured harness pin
ok - fm-control relaunch: a claude secondmate keeps settings.local.json and retires the state settings file and the Stop pointer
ok - fm-control relaunch: a mate with a per-mate override line lands on that override, not the default pin
ok - fm-control relaunch: a mate with no override line still resolves the default pin
ok - fm-control relaunch: a legacy secondmate pin file still relaunches the mate onto its first line
ok - fm-control relaunch: an unparseable secondmate pin refuses before anything is stopped
ok - fm-control relaunch: invalid configured effort is ignored before stop
ok - fm-control relaunch: an adapter unverified for this task kind refuses before the agent is stopped
ok - fm-control relaunch: explicit secondmate harness resets unnamed profile axes
ok - fm-control relaunch: a ship task keeps its recorded harness instead of re-reading crew config
ok - fm-spawn --relaunch: with no explicit harness it reuses the task's recorded one, never the crew default
ok - fm-spawn --relaunch: a promoted scout with a recorded custom branch relaunches on it instead of being refused
ok - fm-promote/fm-spawn --relaunch: the current ship contract supersedes stale scout delivery text
ok - fm-spawn --relaunch: wiring armed under a prefixed harness name is still retired
ok - fm-spawn --relaunch: switching away from muse retires its session binding
ok - fm-spawn --relaunch: switching away from cursor retires its session binding
ok - fm-control relaunch: an unaccountable local copy refuses before the agent is touched
ok - fm-control relaunch: a worker with nothing to work from is never launched
ok - fm-control relaunch: a refusal before the agent is stopped leaves the durable record untouched
ok - fm-control relaunch: checkpoint inspection failures refuse before stopping
ok - fm-control relaunch: a launch failure after the stop keeps the prior record and reports the real state
ok - fm-control relaunch: unpublished rollback keeps concurrent durable metadata
ok - fm-control relaunch: post-publication failure keeps the new durable record
ok - fm-control relaunch: partial stop reconciles actual agent state
ok - fm-control relaunch: failed journal replacement preserves durable phase
ok - fm-spawn relaunch: prepublication abort removes replacement state
ok - fm-control relaunch: the checkpoint records the exact unlanded work it preserved
ok - fm-control relaunch: a secondmate's child work is accounted for and its charter is left alone
ok - fm-control relaunch: a secondmate home that is not this secondmate's is refused
ok - fm-control relaunch: unreadable child records fail checkpoint
ok - fm-control relaunch: unlistable state fails checkpoint
ok - fm-control relaunch: a vanished watcher scratch file does not fail the child-record checkpoint
ok - fm-control relaunch: two control actions on one task serialize instead of interleaving
ok - fm-spawn relaunch: direct entry participates in lifecycle serialization
ok - fm-promote: promotion participates in lifecycle serialization
ok - fm-spawn --relaunch: refuses to launch a second agent into a live endpoint
ok - fm-spawn --relaunch: symlinked records refuse before inspection
ok - fm-spawn --relaunch: keeps its early meta lock continuous
ok - fm-spawn --relaunch: pending closes refuse before replacement begins
ok - fm-spawn --relaunch: every identity axis comes from the record, and a contradicting flag refuses
ok - fm-spawn --relaunch: an unrecorded task is refused
ok - fm-spawn --relaunch: refuses to start a replacement outside the copy holding its work
ok - tmux: a window absent from its session refuses both verbs rather than being assumed gone
ok - tmux: an unfindable session refuses both verbs, so a live agent is never duplicated
ok - tmux: a dead server on this socket refuses both verbs rather than proving absence
ok - reclaim: an unclassifiable endpoint is still refused, so two agents cannot share one
ok - reclaim: a herdr pane that outlived its stopped server is adopted, never orphaned beside a new tab
ok - fm-control exit: a herdr pane that outlived its stopped server is already-stopped, not gone
ok - reclaim: a herdr rebind is created in the session the record names, never the ambient one
ok - reclaim: a herdr agent that came back with its server refuses, so one worktree keeps one agent
ok - reclaim: a herdr reclaim rebinds the endpoint and leaves the whole rest of the task alone
ok - reclaim: a herdr secondmate whose endpoint is gone is sent to its own respawn owner
ok - reclaim: a rebind refused from a plain shell reports the real cause, not a fabricated session mismatch
ok - fm-spawn herdr: a fresh spawn keeps a leased slot it could not inspect instead of force-returning it
ok - relaunch re-reads the backlog item instead of blindly re-running the transition
ok - relaunch heals an item that drifted out of In flight while the task stayed live
ok - away supervision relaunches existing In-flight and queued items under the saturated fresh-spawn spend cap
Evidence: Key restart evidence
before restart: pane cwd=~/.treehouse/demo-eb7512/1/demo
saved pane: [{"cwd":"~/.treehouse/demo-eb7512/1/demo","agent_session":{"agent":"claude","value":"d5db30ac-..."}}]
after restart: pane cwd=~/.treehouse/demo-eb7512/1/demo agent_status=idle
resumed cmd=claude --resume d5db30ac-... cwd=~/.treehouse/demo-eb7512/1/demo
teardown democwd complete; leases held by democwd after teardown: 0
- Outcome: ⚠️ 1 info across 1 run (7m7s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ℹ️ bin/fm-spawn.sh:5094 - Commit 58696bd gives freshen_spawn_worktree_base a separate exit code 3 for a worktree whose git status cannot run. The Herdr lease branch (bin/fm-spawn.sh:4765-4772) treats both 2 and 3 as 'keep the lease', following its own comment that only a slot proven clean may be force-returned. The T3 sibling branch, which also leases durably, still checks only [ &#34;$?&#34; -eq 2 ]. With exit 3 it leaves T3CODE_LEASED=1, so abort cleanup runs treehouse return --force on a worktree whose state was never inspected. The old code had the same outcome through exit 1, so this is not a regression. It is the one remaining caller where the invariant this commit introduced does not hold. Fix: handle the code the same way as the Herdr branch, for example case $? in 2|3) T3CODE_LEASED=0; echo ...;; esac.
⚠️ **Test** - 1 info
  • ℹ️ tests/fm-control-relaunch.test.sh:511 - This host can't run tests/fm-control-relaunch.test.sh as written. It calls /bin/sleep (line 511, older than this change), which NixOS doesn't have, and its Pi relaunch case needs pi, which isn't installed. I ran a temporary copy that calls sleep from PATH and skips the Pi case; every other case passed. This has nothing to do with this change.
  • Live validation: ✅ go - 5 of 6 scenarios driven live against the product
Scenario Result Live Evidence
After a Herdr restart with agent resume on, a real Claude crewmate is resumed (claude --resume) in its own worktree, not the project's primary checkout ✅ pass live claude-restart-live.log: the session.json pane cwd, the restored pane get cwd and the resumed process cwd from /proc and process-info were all ~/.treehouse/demo-eb7512/1/demo
A fresh projected task's pane is restored in its recorded worktree after a lab restart, and the same-id reclaim reuses that leased worktree instead of leasing a second slot ✅ pass live presentation-e2e.log: 'Hi Bit and Wheelhouse-style same-identity restarts reclaim one nested space with exact focus and idempotence' (asserts RESTORED_CWD == worktree and NEW_RESTART_WT == OLD_RESTART…
An opted-out flat spawn opens its task tab with --cwd set to its leased worktree ✅ pass live presentation-e2e.log: 'an opted-out spawn retains the Stage 1 Herdr command sequence with zero ordering calls'
Teardown after restart recovery leaves no pool slot leased to the task, closing the pane once under the session lock ✅ pass live presentation-e2e.log restart case (treehouse status lease check); claude-restart-live.log: teardown rc=0 with 0 leases held
Adversarial: a spawn that aborts after creating its pane in a leased slot returns every lease it took and restores focus ✅ pass live presentation-e2e.log: 'concurrent post-create abort cleanup stays serialized with exact focus restoration' (leases == returns)
Adversarial: a leased slot whose git status cannot be read is kept leased, never force-returned, and no pane is opened in it ⏸️ untested no The prior payload did not establish a live result. Only the hermetic stubbed-git test covers this guard ('fm-spawn herdr: a fresh spawn keeps a leased slot it could not inspect instead of force-return…
  • env -u NO_MISTAKES_GATE HERDR_LAB_HELPER=bin/fm-herdr-lab.sh bash tests/fm-backend-herdr-presentation-e2e.test.sh (real Herdr 0.9.5, isolated fm-lab-* session, 25/25 ok, about 5.6 min)
  • Live real-Claude restart: a lab home made with bin/fm-lab-home.sh create; a lab session from bin/fm-herdr-lab.sh name/provision using a HERDR_CONFIG_PATH copy with resume_agents_on_restore = true; bin/fm-spawn.sh democwd &lt;lab&gt;/projects/demo --mode local-only --yolo off --harness claude --backend herdr; then fm-herdr-lab.sh stop + provision, reading pane get, pane process-info, session.json and /proc/<pid>/cwd; then bin/fm-teardown.sh democwd --force and treehouse status --json lease check; the lab was torn down afterwards
  • tests/fm-control-relaunch.test.sh from a temporary copy (deleted afterwards) that calls sleep from PATH instead of /bin/sleep and skips the Pi-only case, since pi is not installed; every case passed, including the new 'fresh spawn keeps a leased slot it could not inspect'
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 1)
✅ **Push** - passed

✅ No issues found.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @rob-mur, this is a real bug with unusually strong live evidence. I checked the premise on latest main 7da4c362. A Herdr ship/scout pane opens in the project's primary checkout and leases its slot from a treehouse get child shell, so the pane's top-level cwd (the one Herdr saves and resumes claude --resume in) stays the primary checkout. Main's own comment above spawn_enter_recorded_worktree promises that a later restart inherits the task worktree. Your base-vs-branch transcripts show that promise broken on base and holding on the branch.

What I read in the diff: a fresh Herdr spawn takes a durable treehouse get --lease --lease-holder <id> and opens the pane in that worktree. A same-id spawn over an existing record reuses the recorded slot when the pane holds no agent, Treehouse still says it's leased to the id, and the slot claim names the task. Abort cleanup returns a fresh lease only when no record names it and no pane is left, and it never returns a reused slot. No workflow, credential or network changes, so I approved the fork CI runs for head 684c59d9 (CI 40534456394, Require no-mistakes 40534456355). Your no-mistakes attestation binds this head. One trade-off the review left open is worth the captain seeing: if the spawn process is hard-killed, a durable lease outlives it with no record, so a retry leases a second slot. Before this change, the process lease freed the slot.

VISION: aligns. It makes a restart a non-event, keeps project changes in isolated copies, and holds up as a verified Herdr adapter that binds to Herdr's real restore semantics. Unlanded work is never torn down: the reused slot is never force-returned.

contract-class: new-default. Opening the pane in the leased worktree restores a promise main already makes. But the same-id recovery that adopts the old leased slot, and the switch from a process lease to a durable lease on the default Herdr spawn path, are new unconfigured behavior. So this goes to the captain for the merge call, not auto-merge.

Next step is on our side: CI just started on this head. If it comes back green, I'll pass this to the captain to decide whether to merge. Nothing is needed from you right now.

Rob Murphy and others added 10 commits October 29, 2026 09:28
A Herdr restart restores each pane's shell, and resumes its agent, in the
cwd of the pane's top-level shell. Herdr ship and scout panes were opened in
the project's primary checkout and entered their worktree through an
interactive `treehouse get` subshell, so a restart resumed every worker in
the primary checkout.

A fresh Herdr task now leases its slot with `treehouse get --lease` before
its pane exists and opens the pane in that worktree. A spawn that aborts
before its record or launch returns the lease once no pane is left in the
slot, and otherwise prints the return command.

The presentation lab test now asserts the restored pane cwd is the worktree,
and the verification record holds a real Claude restart before and after.
A fresh Herdr task now durably leases its slot, and that lease outlives the
pane. A same-id spawn after a Herdr restart therefore leased a second slot
and stranded the first one, still leased to the task, with its work.

When the task's record names a Herdr pane that holds no agent and Treehouse
still reports the recorded slot leased to this id with a matching slot
claim, the recovery reuses that worktree untouched instead of leasing a new
one. Abort cleanup keeps a slot the record names and returns one it does
not.

The presentation lab test asserts the reclaim reuses the leased worktree
and that teardown leaves no slot leased to the task.
Covered: a fresh crewmate or scout opens its pane in its leased worktree, a
same-identity recovery after a restart reuses that worktree, a relaunch whose
pane is gone opens its new pane in the recorded worktree, and a secondmate
opens in its own home.

Not covered: a pane created before this change, including one a relaunch
reuses in place, keeps its original cwd until it is re-created, and a
restart resumes only the agents Herdr itself restores.
…in/fm-teardown.sh`. The "Behavior portable serial 1" failure (ci-1) is a flake outside this PR. The fix is unconfirmed on Herdr 0.7.4, the version CI runs. **ci-2, "Behavior tests (Herdr)", caused by this PR.** The step "projected teardown changed active workspace/tab from w3/w3:t1 to w8/w8:t2" failed. - **Cause:** this PR opens a fresh Herdr task pane in its leased worktree, so the pane's top-level shell now lives there. Teardown killed every process in the worktree (the reap, then `treehouse return --force`) before closing the pane. That killed the pane's shell, and Herdr removed the pane itself instead of through the focus-preserving close. On Herdr 0.7.4 that removal moves focus to the next workspace (upstream kunchenguid#1621). The close then found the pane gone and never restored focus. Herdr 0.9.5 has fixed that bug, so the test passes locally either way. - **Invariant:** a Herdr task pane must be closed through the focus-preserving, lock-held close before anything kills the processes in its worktree. That applies to both the reap and the return in teardown, for projected and flat panes. Spawn abort cleanup already returns its lease only after the pane close is confirmed. Secondmate panes are unchanged by this PR. - **Fix:** I moved the whole Herdr close block in `bin/fm-teardown.sh` ahead of the reap and return. It now runs after every landed-work refusal and before any destructive step, the same way the T3 kill already runs before its return. The block covers the journal check, the projected or flat close, journal retirement, and the confirmed-gone refusal. The rex and generic close chain stays where it was, and I updated the two comments about ordering. - **If the return then fails:** teardown exits and keeps every record. A rerun still works because the preflight accepts a pane that is already gone. **ci-1, "Behavior portable serial 1", not caused by this PR.** The failure is in `tests/fm-supervision-host.test.sh` ("noack: the host counted an unacknowledged wake handled"), which this PR doesn't touch. The same file fails in the same shard on main with different assertions: run 40437879779 ("latch: the second engine error did not hand the wake back") and run 40413622972 ("return-fail: the host did not hand the wake to main"). I made no change for it. **Verification, all on real Herdr 0.9.5 (only version installed):** - These pass with the fix: `fm-backend-herdr-presentation-e2e`, `fm-backend-herdr-launcher-workspace-e2e`, `fm-backend-herdr-workspace-per-home-e2e`, `fm-backend-autodetect-smoke`. - Two tests fail locally, but they fail the same way with the PR head's original `bin/fm-teardown.sh`. They are `fm-teardown-endpoint-safety.test.sh` ("teardown reported success after a close that failed") and `fm-teardown.test.sh` ("fixture never attempted publication"). Both cover tmux and archive fixtures, not Herdr, so my change didn't cause them. - The 0.7.4 focus failure could not be reproduced here. The next Herdr CI run is the first real check of the fix
…tree

The base branch extended freshen_spawn_worktree_base with project and mode
arguments; the Herdr lease call site added on this branch still passed two.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@rob-mur
rob-mur force-pushed the fm/fm-herdr-restore-cwd branch from 1fc4594 to cc2de91 Compare October 29, 2026 08:46
@rob-mur rob-mur changed the title fix(herdr): restore restarted workers in their worktree fix(herdr): open task panes in their leased worktree so restarts resume workers in place Oct 29, 2026
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no new actionable issue was found.

Reviews (3) · Last reviewed commit: "no-mistakes(ci): ci-2 (Behavior tests (H..." · Reviewed by Greptile

Comment thread bin/fm-spawn.sh Resolved
A fresh Herdr spawn leases its slot before inspecting it, and abort cleanup
force-returns that lease. An inspection failure returned the generic refresh
error, so the unchecked slot was handed back with --force. Report it
distinctly and keep the lease, so only a slot proven clean goes back.
@rob-mur rob-mur changed the title fix(herdr): open task panes in their leased worktree so restarts resume workers in place fix(herdr): restore restarted workers in their worktree, not the primary checkout Oct 29, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @rob-mur. I read the new head 58696bd4 against main. Besides the original fix, it now does three things:

  • Teardown closes the Herdr pane (focus-preserving, lock held) before it reaps the worktree's processes or returns the worktree. This answers the Herdr CI failure, where the reap killed the pane's shell and Herdr 0.7.4 moved focus.
  • Herdr is kept out of teardown's generic backend close.
  • A leased slot whose git status can't be read is kept leased and never force-returned.

The attestation binds this head with test/document/lint completed, and live validation is 5 of 6. There are no workflow, credential or network changes, so I approved the fork runs for this head: CI 40850076186 and Require no-mistakes 40850076229 / 40850132928. As your notes say, this CI run is the first real check of the teardown reorder on Herdr 0.7.4.

VISION: aligns, unchanged. A restart becomes a non-event, the work stays in isolated copies, and unlanded work is never torn down (a slot it can't inspect stays leased).

contract-class: new-default, unchanged, and a bit stronger now. Durable leases, same-id slot reuse, and now a reordered default Herdr teardown are new unconfigured behavior. The hard-killed-spawn trade-off from my last note still stands: a durable lease can outlive a killed spawn.

Next step is on our side. If CI comes back green on this head, it goes to the captain as a merge-or-leave decision. Nothing is needed from you right now.

…and is fixed; ci-1 (Behavior portable serial 6) was not, and has no change. ci-2: the step "fm-hibit-resume-r1 reclaim leased .../2/recovery-project instead of reusing its leased worktree .../1/..." failed. herdr_task_own_leased_worktree (bin/fm-spawn.sh) checked that the task's old slot was still leased to its id by running `treehouse status --json`. CI pins Treehouse 2.0.1 (bin/fm-install-treehouse.sh), and in that version `status` has no --json option, so the check always failed in CI and the recovery leased a second slot. It passed locally because Treehouse 3.1.4 has the option. - Invariant: a same-id restart recovery must recognise a slot still leased to its id, whichever Treehouse version is installed. - The only other place that read leases through `status --json` was the e2e test's check that teardown released every slot leased to the task. On 2.0.1 it got no output and so always passed without checking anything. - Fix: both places now read the pool's treehouse-state.json directly (`.worktrees[]` with `.leased == true` and `.lease_holder == id`). The 2.0.1 source and local 3.1.4 pools both store leases this way, and fm_treehouse_pool_slot already requires that file. - Files: bin/fm-spawn.sh (the lease check in herdr_task_own_leased_worktree) and tests/fm-backend-herdr-presentation-e2e.test.sh (the RESTART_HELD teardown check). ci-1: tests/fm-watcher-lock.test.sh failed ("recovery drain after forced arm interruption failed"). This PR's only change to the watcher code is comment lines in bin/fm-wake-lib.sh. Locally the test fails at a different step ("acquirer could not reclaim dead steal owner rc=8") both on this branch and on base commit 6613c3e, so the failure comes from timing or the environment, not from this change. Verification: - tests/fm-backend-herdr-presentation-e2e.test.sh passes in full on real Herdr 0.9.5 with Treehouse 3.1.4, including the restart-reuse and teardown-release checks. - The new jq query, run against a real pool state file, matches the correct lease holder and rejects any other. - Not run: Treehouse 2.0.1, because its prebuilt binary won't start on this NixOS host, and Herdr 0.7.4, which isn't installed. The 2.0.1 state-file format is confirmed only from its source, so the next Herdr CI run is the first real check of the fix
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @rob-mur, that's a good catch. CI's pinned Treehouse 2.0.1 has no status --json, so the same-id lease check could never pass there. It was also quietly turning the e2e teardown-release check into a no-op.

Delta since 58696bd4: herdr_task_own_leased_worktree and the e2e teardown check now read the pool's treehouse-state.json directly (.worktrees[], leased == true, lease_holder == id). fm_treehouse_pool_slot already requires that file. It's a small change and I found nothing risky in it: no workflow, network, or credential changes. I agree the serial 6 "recovery drain after forced arm interruption" failure is a known flake on our side, not yours.

CI: I approved the fork runs on 634754f3: CI 40865698011 and no-mistakes 40865697970. The attestation binds this head. The Herdr job is the real check of the Treehouse 2.0.1 path. Contract-class is unchanged: new-default (durable lease, same-id slot reuse, and a reordered Herdr teardown). So once CI is green, this goes to Kun as a merge-or-leave decision. Nothing is needed from you while CI runs.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @rob-mur. The Treehouse 2.0.1 fix worked. Every lane passed on head 634754f3 (CI run 40865698011: all Behavior portable serial and parallel lanes, Herdr, macOS, lint, the coverage guard and repo invariants). That run happened before the new full-ci label gate landed, so it counts as the full suite on this head. You don't need to do anything for the label.

Where it stands:

  • no-mistakes binds this head and every step completed. Greptile gives it 5/5. There are no unresolved threads, and the PR is CLEAN against current main.
  • VISION: aligns. A Herdr restart becomes a non-event, workers resume in their own isolated worktree, and unlanded work is kept.
  • Contract class: new-default. It changes the default Herdr path: a durable lease, same-id slot reuse, and teardown closing the pane before reap/return.

Because it changes a default, it's waiting on the captain's merge-or-leave decision, not on you. FYI: #7941 just landed and also touches bin/fm-spawn.sh and bin/fm-wake-lib.sh. It still merges cleanly. If anything shifts, fixing it is on us.

@rob-mur

rob-mur commented Nov 7, 2026

Copy link
Copy Markdown
Author

Closing: #8052 now covers most of this change (durable treehouse leases at spawn, lease cleanup on abort and teardown). I will send the one remaining part, where a restarted worker reuses its own leased slot, separately if it is still needed.

@rob-mur rob-mur closed this Nov 7, 2026
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