Skip to content

fix(bin): bind Herdr task records to the pane's terminal identity - #5435

Open
AgardnerAU wants to merge 30 commits into
kunchenguid:mainfrom
AgardnerAU:fm/fm-herdr-pane-id-reuse-misbinds-task
Open

AgardnerAU wants to merge 30 commits into
kunchenguid:mainfrom
AgardnerAU:fm/fm-herdr-pane-id-reuse-misbinds-task

Conversation

@AgardnerAU

@AgardnerAU AgardnerAU commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Update the existing pull request #5435 (branch fm/fm-herdr-pane-id-reuse-misbinds-task, from the AgardnerAU fork) onto current upstream main and push so CI re-runs. The earlier CI failures came from GitHub moving ubuntu-latest to ubuntu-26.04, fixed on main by upstream PR 7798 (an ubuntu-24.04 pin), and were not caused by this change. That PR binds Herdr task records to the pane's terminal identity so a reissued pane id is not misbound to another task. Keep updating the existing PR; do not replace it. If only the known flaky cases fail on main itself (fm-supervision-host serial 1, fm-watch-wedge-cap serial 4), report that rather than chasing them.

What Changed

  • Herdr spawn now records the pane's stable herdr_terminal_id= (from the pane-create response, or from the record of an adopted endpoint). Before it publishes the record, spawn reads the pane back. If that read fails or returns a different id, spawn refuses to publish and exits nonzero. It closes a pane it created only when it could read the pane's identity.
  • The new fm_backend_herdr_endpoint_identity in bin/backends/herdr.sh runs before every Herdr liveness read, capture, input, control action and close. Callers that act for one task now bind that task's own record first, through the new fm_backend_bind_task_record in bin/fm-backend.sh. These callers include the watcher, session-start, teardown, send, peek, crew-state and fleet snapshot.
    • Reissued pane id: a pane id that another terminal now holds reads as the task's endpoint gone (missing). Nothing is closed and the landed-work checks still run.
    • Unreadable identity: every action and close is refused.
    • Legacy records: a record without the field matches only when the pane's foreground working directory is inside its worktree and no other record of the home claims that terminal.
  • Teardown now accepts a Herdr record whose window= was cleared. It makes no Herdr call for that record and still runs its landed-work checks.
    • fm-watch.sh now walks task records rather than panes, so a live task keeps its stall detection when an old record names the same reissued pane id.
    • docs/herdr-backend.md and docs/verification/runtime-backends.md describe the pane-id reissue behaviour, measured on Herdr 0.9.1.
    • A new end-to-end test, tests/fm-backend-herdr-pane-reuse-e2e.test.sh, and wider unit and e2e tests cover these paths.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The new merge of upstream main (7da4c36) applied cleanly with no conflict resolution (empty remerge-diff). Main's overlapping changes in fm-spawn.sh (the Rex local-server ensure on new spawns), fm-test-run.sh (family and duration entries), configuration.md (the warm-compact section) and fm-watch-triage.test.sh (the FM_TEST_STOCK_BASH gate) are independent of the PR's Herdr terminal-identity binding. Main's new warm-compact path targets an unrecorded primary pane, which the identity check treats as unbound and leaves unchanged, so the earlier-reviewed PR behaviour is preserved.

Testing

I ran the branch's dedicated real-Herdr e2e at the merged commit in a throwaway fm-lab session, and all 5 assertions passed. The test first reproduces the bug: after a restart, Herdr gives pane w2:p2 to an unrelated terminal. It then shows that liveness, existence, capture, steering, interrupt and cleanup all leave that pane untouched. Bound and legacy records that own the pane still read their agent as alive. The targeted Herdr backend and teardown scripts passed with no failures. The control-relaunch script was stopped before it finished, and the watch-triage script never started, because the batch reached its time limit on a loaded host. Remote CI still runs both and covers broad regression.

  • Live validation: ✅ go - 2 of 3 scenarios driven live against the product
Scenario Result Live Evidence
After a Herdr restart reissues a finished task's pane id to an unrelated agent, firstmate does not misbind or act on that pane ✅ pass live herdr-pane-reuse-e2e.log (tests/fm-backend-herdr-pane-reuse-e2e.test.sh, real herdr 0.9.1, fm-lab session)
A task record still matches its own live pane (bound terminal id or legacy worktree match) ✅ pass live herdr-pane-reuse-e2e.log assertions 1 and 5
Teardown refuses to clean up a pane whose terminal identity does not match the task record ⏸️ untested no The prior payload did not establish a live result for this scenario as a separate check: fm-teardown.test.sh (44 ok) and fm-backend-herdr.test.sh (239 ok) use stubbed backends. Only the cleanup assert…
Evidence: Real-Herdr pane reuse e2e transcript

Source: Real-Herdr pane reuse e2e transcript

ok - a task record matches its own live pane, bound or legacy ok - repro: after a restart Herdr reissued pane w2:p2 to an unrelated terminal ok - repro: read by pane id alone, the finished task record names a live agent ok - liveness, existence, capture, steering, interrupt, and cleanup all treat the reissued pane as the finished task endpoint gone, and leave it untouched ok - the record that owns the pane, bound or legacy, still reads its agent alive

ok - a task record matches its own live pane, bound or legacy
ok - repro: after a restart Herdr reissued pane w2:p2 to an unrelated terminal
ok - repro: read by pane id alone, the finished task record names a live agent
ok - liveness, existence, capture, steering, interrupt, and cleanup all treat the reissued pane as the finished task endpoint gone, and leave it untouched
ok - the record that owns the pane, bound or legacy, still reads its agent alive
Evidence: fm-backend-herdr test log

Source: fm-backend-herdr test log

ok - fm_backend_herdr_version_check: accepts the current protocol (14)
ok - fm_backend_herdr_version_check: refuses an old protocol loudly
ok - fm_backend_herdr_version_check: refuses loudly when herdr is not installed
ok - fm_backend_herdr_workspace_label: a primary home (no marker) resolves to 'firstmate'
ok - fm_backend_herdr_workspace_label: a secondmate home (.fm-secondmate-home) resolves to '2ndmate-<id>'
ok - fm_backend_herdr_workspace_label: trims whitespace around the marker's secondmate id
ok - fm_backend_herdr_workspace_label: an empty marker file falls back to the primary label 'firstmate'
ok - fm_backend_herdr_workspace_label: two different secondmate homes get two different, non-colliding labels
ok - fm_backend_herdr_cli: sets HERDR_SESSION AND appends a trailing --session flag on every call
ok - herdr client selection: a live pane behind a stale shadowing client reads alive
ok - herdr recovery-grade read: a stopped server means missing there, and nowhere else
ok - herdr stale registration: a shell-only pane with a lingering Pi record is agent-free with an explicit reason
ok - herdr stale registration: no registered status can outrank a shell-only process view
ok - herdr pane agent session: a resumable reference is reported with the agent label that reported it
ok - herdr pane agent session: anything unresumable degrades to a nonzero read with no output
ok - herdr stale registration: a registered agent with a live Pi foreground process still reads alive
ok - herdr stale registration: only a shell-only pane demotes a registration
ok - herdr stale registration: a transient prompt helper settles into stale-agent instead of reading live
ok - herdr stale registration: an exhausted settle window still reads a non-shell foreground as live
Terminated
ok - herdr stale registration: an agent process outside the foreground group still counts as alive
Terminated
ok - herdr stale registration: the descendant walk reads a spaced executable path whole
ok - herdr stale registration: an unreadable process view refuses instead of guessing either way
ok - herdr stale registration: an empty foreground list over a real shell is not unreadable, it settles via the descendant walk
ok - herdr stale registration: presentation reclaim never closes a stale-registration pane
ok - herdr stale registration: busy_state proves a working record at process level before reporting busy
ok - herdr client selection: one selected client is reused per process
ok - herdr client selection: selected clients remain scoped to their session
ok - herdr client selection: only protocol_mismatch triggers reselection; other failures pass through untouched
ok - herdr client selection: the happy path makes no extra call
ok - herdr client status: .server.compatible, legacy protocol equality, unknown, and stopped shapes all normalize
ok - fm_backend_herdr_launcher_identity: a firstmate not running inside herdr has no launcher workspace to inherit
ok - fm_backend_herdr_launcher_identity: HERDR_ENV=1 without a pane id selects the backend but binds no parent
ok - fm_backend_herdr_launcher_identity: resolves the launcher's exact workspace even when a same-labeled workspace sorts first
ok - fm_backend_herdr_launcher_identity: refuses a launcher pane that names a different herdr session
ok - fm_backend_herdr_launcher_identity: refuses a claimed pane without exact server identity
ok - fm_backend_herdr_launcher_identity: refuses a launcher pane whose injected socket belongs to another herdr server
ok - fm_backend_herdr_launcher_identity: refuses when the launcher's own pane no longer resolves
ok - fm_backend_herdr_launcher_identity: refuses when the launcher's pane and tab disagree about their workspace
ok - fm_backend_herdr_launcher_identity: refuses when the launcher's workspace is gone from its own session
ok - fm_backend_herdr_workspace_ensure: places a worker in the launcher's exact workspace, not the first same-labeled one
ok - fm_backend_herdr_workspace_ensure: refuses to guess between two same-labeled home workspaces
ok - fm_backend_herdr_workspace_ensure: a --secondmate container resolves that home's own workspace, not the launcher's
ok - fm_backend_herdr_container_ensure: surfaces the exact ambiguous-placement refusal instead of a generic failure
ok - fm_backend_herdr_container_ensure: version-gates, starts the server, ensures the firstmate workspace, echoes session:workspace_id + the seeded default tab id
ok - fm_backend_herdr_server_ensure: scrubs home and harness identity without disturbing unrelated environment or session routing
ok - fm_backend_herdr_container_ensure: reuses an existing firstmate workspace without recreating it, and reports no seeded default tab (adopted, not created)
ok - fm_backend_herdr_container_ensure: workspace create passes --no-focus
ok - fm_backend_herdr_container_ensure: creates the workspace under the SECONDMATE home's own label, not 'firstmate'
ok - fm_backend_herdr_create_task: prunes exactly the seeded default tab container_ensure identified, once the first real task tab exists
ok - herdr repeated spawn/teardown: one persistent firstmate workspace reused, zero orphans, default tab pruned, create ran once
ok - fm_backend_herdr_create_task: an ADOPTED workspace's pre-existing tab is never pruned (the created-vs-adopted gate)
ok - fm_backend_herdr_create_task: the label-collision startup-workspace scenario (2026-07-02 incident) leaves the captain's live tab untouched
ok - fm_backend_herdr_workspace_prune_seeded_default_tab: refuses to close the seeded default tab when its pane reports a working agent (defense in depth)
ok - fm_backend_herdr_create_task: refuses a duplicate tab label (herdr's own tab create has no uniqueness check)
ok - fm_backend_herdr_create_task: a same-labeled tab with a live (even idle) registered agent still refuses exactly as before
ok - fm_backend_herdr_create_task: scans every same-labeled tab and refuses if any duplicate is live
ok - fm_backend_herdr_create_task: closes and replaces a same-labeled tab whose pane is dead (pane_not_found)
ok - fm_backend_herdr_create_task: closes and replaces a same-labeled tab whose pane is alive but hosts no registered agent (a restored plain shell)
ok - fm_backend_herdr_create_task: closes every confirmed same-labeled husk only after creating the replacement
ok - fm_backend_herdr_create_task: refuses success when a preexisting husk tab remains after replacement
ok - fm_backend_herdr_create_task: refuses (fail-safe) rather than guessing when the duplicate's agent state cannot be classified confidently
ok - fm_backend_herdr_create_task: creates the replacement tab BEFORE closing the husk tab, never the reverse
ok - fm_backend_herdr_create_task: creates a tab and parses tab_id/pane_id from the JSON response, prunes nothing when no seeded tab id is given
ok - fm_backend_herdr_create_task: tab create passes --no-focus
ok - herdr presentation: a home that set nothing gets the projection by default at or above the floor
ok - herdr presentation: an unconfigured home below the floor falls back flat with one naming warning
ok - herdr presentation: an unreadable client release falls back flat instead of guessing
ok - herdr presentation: a deliberate opt-in is never silently downgraded below the floor
ok - herdr presentation: an explicit off opts the home out
ok - herdr presentation: an unrecognized value warns and follows the default instead of failing a spawn
ok - herdr presentation: the below-floor warning is one per home per release, not one per spawn
ok - herdr presentation: warning marker publication is atomic, symlink-safe, and fails visible
ok - herdr presentation: client and selected server floors compose conservatively without overriding explicit opt-in
ok - herdr presentation floor: every measured release, and each signal alone, classifies correctly
ok - herdr presentation floor: either signal alone can carry an above verdict, and each divergence is real
ok - herdr presentation: config parsing separates a deliberate choice from an unconfigured default
ok - herdr presentation journal: atomically publishes one non-authoritative 128-bit correlator and refuses overwrite
ok - herdr present

... [9850 bytes truncated] ...

end_herdr_composer_state: non-faint codex prompt text still reads pending
ok - fm_backend_herdr_wait_for_working: reports 'busy' immediately on the first poll, without spending the rest of the budget
ok - fm_backend_herdr_wait_for_working: a slow transition landing on a later sample within one window is still caught (robust against the 'slow transition' failure direction)
ok - fm_backend_herdr_wait_for_working: spreads six samples across the full budget endpoint without a final trailing sleep
ok - fm_backend_herdr_send_text_submit: applies the herdr minimum confirmation budget before polling agent-state
ok - fm_backend_herdr_wait_for_working: reports 'idle' (readable, genuinely not yet working) when 'busy' never appears
ok - fm_backend_herdr_wait_for_working: reports 'unknown' (a hard read failure, not a timing race) only when EVERY poll in the window fails
ok - fm_backend_herdr_wait_for_working: treats blocked as submit-active for confirmation without changing watcher busy-state semantics
ok - fm_backend_herdr_send_text_submit: reports 'empty' once agent_status reports working after one Enter, without ever reading the composer
ok - fm_backend_herdr_send_text_submit: reports 'pending' when agent_status stays idle and the composer still holds unsent text after retried Enters (swallowed)
ok - fm_backend_herdr_send_text_submit: a failed literal send reports send-failed and replays the transport's stderr
ok - fm_backend_herdr_send_text_submit: a slash-command popup's placeholder fill on Enter #1 never flips agent_status to working, so it does not short-circuit as submitted; Enter #2 is retried and lands it
ok - fm_backend_herdr_send_text_submit: the Claude background-task exit picker gets no confirming Enter
ok - fm_backend_send_text_submit (herdr): a picker behind a blocked verdict is named by the caller's next composer read
ok - fm_backend_herdr_send_text_submit: a post-Enter blocked state confirms delivery without retrying into the prompt
ok - fm_backend_herdr_send_text_submit: native working + proven pending after retries reports empty (queued Enter)
ok - fm_backend_herdr_send_text_submit: a failed Enter cannot borrow preexisting working state as queued-delivery proof
ok - fm_backend_herdr_send_text_submit: a failed Enter cannot borrow a later native transition as delivery proof
ok - fm_backend_herdr_send_text_submit: idle native agent-state plus empty composer reports empty (landed Claude turn)
ok - fm_backend_herdr_send_text_submit: idle native baseline uses a rendered busy footer to confirm a queued Enter
ok - fm_backend_herdr_composer_state: cursor's mid-turn placeholder-plus-busy-token row reads pending (why delivery needs a separate signal)
ok - fm_backend_herdr_rendered_busy_state: busy/idle/unknown from the rendered footer, with an unreadable pane never reading idle
ok - fm_backend_herdr_send_text_submit: a rendered-footer idle-to-busy transition confirms delivery when native agent-state never reports idle
ok - fm_backend_herdr_send_text_submit: an already-busy footer baseline is never accepted as proof that this Enter landed
ok - fm_backend_herdr_send_text_submit: confirms submission via native agent-state alone, immune to a codex-style dynamic idle-tip composer that would have misread as 'pending' under the old composer-based confirmation
ok - fm_backend_herdr_composer_state: a faint real-codex dynamic idle-tip composer row reads empty
ok - fm_backend_composer_state (herdr): the pre-injection empty-box guard still refuses a genuinely non-empty composer, unaffected by the submit-confirmation change
ok - fm_backend_herdr_send_text_submit: a slow transition landing on a later sample within one Enter's budget is confirmed WITHOUT sending a needless extra Enter
ok - fm_backend_herdr_send_text_submit: reports 'send-failed' when the literal send-text call itself errors
ok - fm_backend_herdr_send_text_submit: reports 'unknown' when the post-Enter agent-get read fails (never retries past an unreadable target)
ok - fm_backend_herdr_send_text_submit: an unreadable composer stops Enter retries after native status stays idle
ok - fm_backend_herdr_send_text_submit: a 1500-character payload a Claude composer still holds is submitted whole
ok - fm_backend_herdr_send_text_submit: a long payload whose Claude composer kept only the tail is not submitted, is cleared, and reports send-failed
ok - fm_backend_herdr_send_text_submit: a refused suffix whose clear cannot be verified reports unknown, not send-failed
ok - fm_backend_herdr_send_text_submit: a refused 480-character suffix wrapped over five rows is cleared one row per Ctrl+U and reports send-failed
ok - fm_backend_herdr_send_text_submit: after a refused suffix is cleared, a resend starts from an empty Claude composer and submits only the message
ok - fm_backend_herdr_send_text_submit: a Claude composer holding leftover text is refused before anything is typed
ok - fm_backend_herdr_send_text_submit: a matching head in the transcript does not prove the current composer
ok - fm_backend_herdr_send_text_submit: an away-mode digest and a marked steer are submitted when Claude's read-back only drops U+2063
ok - fm_backend_herdr_send_text_submit: dropping U+2063 does not let a marked digest missing its head be submitted
ok - fm_backend_herdr_composer_state: a slash-command popup cannot hide a typed composer
ok - fm_backend_herdr_send_text_submit: a typed slash command hidden behind its popup is still proven and submitted
ok - fm_backend_herdr_send_text_submit: a typed slash command Claude draws in muted truecolor grey is proven and submitted
ok - fm_backend_herdr_send_text_submit: a lone paste placeholder still submits the full long payload
ok - fm_backend_herdr_send_text_submit: a lone multi-line paste placeholder still submits the long multi-line payload
ok - fm_backend_herdr_send_text_submit: a paste placeholder followed by a literal remainder is not submitted and is cleared
ok - fm_backend_herdr_send_text_submit: three paste placeholders with no literal remainder submit the long payload
ok - fm_backend_herdr_send_text_submit: non-Claude and unidentified panes keep the pre-proof type-then-Enter behavior
ok - fm_backend_validate: herdr is a known backend (P2)
ok - fm_backend_busy_state: tmux (no native primitive) always reports unknown, preserving the P1 regex-only path
error: unknown backend 'bogus' (known: tmux herdr zellij orca cmux paseo rex t3code tern)
ok - fm_backend_composer_state dispatches every backend to its named thin classifier, unknown for unrecognized backends
ok - fm-peek/fm-send: explicit stale targets matching metadata use the recorded backend
ok - fm_backend_herdr_normalize_event routes through the shared record with an empty from_status
ok - fm_backend_herdr_escalation_marker keys the dedupe marker exactly like the watcher's .stale-<key>
ok - fm_backend_herdr_apply_transition: blocked dedupe starts only after explicit commit
ok - fm_backend_herdr_apply_transition: a working edge clears the marker so the next ->blocked re-escalates
ok - fm_backend_herdr_clear_transition removes task-owned dedupe state
ok - fm_backend_herdr_apply_transition: idle/done (defer) and unknown/empty (fallback) take no fast action
ok - fm_backend_herdr_wait_transition: a home with no herdr panes falls back to polling (rc 2)
ok - fm_backend_herdr_wait_transition: below-capability protocol/schema falls back to polling (rc 2)
ok - fm_backend_herdr_wait_transition: reconnect level-reconcile returns an uncommitted blocked pane
ok - fm_backend_herdr_wait_transition: subscribes before reconnect level-reconcile
ok - fm_backend_herdr_wait_transition: a still-blocked, already-escalated pane is not re-delivered on reconnect
ok - fm_backend_herdr_wait_transition: a streamed ->blocked edge returns the record sub-poll
ok - fm_backend_herdr_wait_transition: streamed working clears the marker, idle/done are deferred (clean timeout)
ok - fm_backend_herdr_wait_transition: a reader/subscribe failure falls back to polling (rc 2)
ok - fm_backend_herdr_wait_transition: Bash 3.2-safe bad-ack path closes fd 9 and removes its FIFO
ok - fm_backend_herdr_wait_transition: stock macOS Bash clean timeout closes fd 9 and returns 1
Evidence: fm-teardown test log

Source: fm-teardown test log

ok - teardown leaves opencode's busy plugin in the returned pool worktree as on main
ok - status archival is opt-in and preserves the complete log
ok - config-absent teardown does not read or invoke record export
ok - unopted teardown ignores symlinked config when record export is absent
ok - teardown commits the record archive before deleting sources and fails closed when export cannot commit
ok - forced secondmate teardown exports task records from the child sub-state
ok - record export waits for endpoint quiescence and retry captures records changed after refusal
ok - forced secondmate retirement preserves two descendant levels and refuses linked child directories
ok - local missing-status retirement stays lock-free without creating an archive
ok - reused task IDs never overwrite archives and retention removes only old owned logs
ok - archive sources and directories reject symlinks; pruning never follows children links
ok - failed archive publication preserves presentation and watcher bookkeeping
ok - cursor retirement failure removes its archive so retry publishes one history
ok - archive publication and cold logs never re-wake or re-present
ok - retention failures warn without aborting unrelated teardown
ok - a missing teardown startup source refuses before cleanup
ok - an unreadable teardown startup source refuses before cleanup
ok - a missing adapter sibling refuses before cleanup
ok - a forced descendant with a missing adapter sibling refuses before cleanup
ok - a forced secondmate with a missing own adapter sibling refuses before child cleanup
ok - present required sources still reach the ordinary teardown refusal
ok - local-only worktree with HEAD on a fork remote is torn down and the home summary is refreshed
ok - teardown closes its own backlog item before reporting success
ok - teardown closes a landed Gerrit task with its change URL as a note and a GitHub task with --pr
ok - teardown closes a landed GitLab task with its merge request URL as a note and GitHub and Forgejo tasks with --pr
ok - teardown honors config/backlog-backend=manual and still finishes cleanly
ok - local-only worktree with truly unpushed work is refused (safety preserved)
ok - local-only worktree with work merged into local main is torn down (no regression)
ok - no-mistakes worktree with HEAD on origin is torn down (no regression)
ok - no-mistakes worktree with genuinely unlanded work is refused (safety preserved)
ok - local-only worktree with unpushed work is torn down under --force (escape hatch)
ok - fm-pr-check publishes the PR-ready line on a secondmate's parent channel once
ok - fm-pr-check withholds the PR-ready line until checks are green when config/ready-after-green is present
ok - fm-pr-check releases the PR-ready line on a checks-green report that carries surrounding text
ok - a secondmate home's teardown delivers the child's final line or refuses until it can
ok - teardown completes when an exact busy-state sidecar is already absent
ok - teardown retires a polytoken task's generated worktree wiring on pool return
ok - teardown never deletes a tracked .polytoken hook layer
ok - teardown never deletes a .polytoken hook layer firstmate did not generate
ok - teardown scopes .polytoken wiring removal to polytoken tasks
ok - herdr teardown removes pane-owned escalation dedupe state
ok - herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly
ok - herdr flat teardown never closes a pane id reissued to another terminal and still runs its landed-work checks
ok - herdr flat teardown never erases records when pane presence is unparseable
Terminated

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 2 of 3 scenarios driven live against the product
Scenario Result Live Evidence
After a Herdr restart reissues a finished task's pane id to an unrelated agent, firstmate does not misbind or act on that pane ✅ pass live herdr-pane-reuse-e2e.log (tests/fm-backend-herdr-pane-reuse-e2e.test.sh, real herdr 0.9.1, fm-lab session)
A task record still matches its own live pane (bound terminal id or legacy worktree match) ✅ pass live herdr-pane-reuse-e2e.log assertions 1 and 5
Teardown refuses to clean up a pane whose terminal identity does not match the task record ⏸️ untested no The prior payload did not establish a live result for this scenario as a separate check: fm-teardown.test.sh (44 ok) and fm-backend-herdr.test.sh (239 ok) use stubbed backends. Only the cleanup assert…
  • bash tests/fm-backend-herdr-pane-reuse-e2e.test.sh against real herdr 0.9.1, via bin/fm-herdr-lab.sh with a disposable fm-lab session that the test tears down
  • bash tests/fm-backend-herdr.test.sh (239 ok, 0 not ok)
  • bash tests/fm-teardown.test.sh (44 ok, 0 not ok)
  • bash tests/fm-control-relaunch.test.sh started but did not finish before the background time limit; tests/fm-watch-triage.test.sh did not start
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Herdr reissues a closed workspace's id, and with it its pane ids, after a
server restart, so a task record that bound only <session>:<pane> could
name an unrelated live pane and read it as the task's agent. Spawn now
records the pane's terminal_id as herdr_terminal_id=, and one adapter
identity check gates liveness, existence, capture, input, control, and
every pane close. A pane now held by another terminal reads as the task's
endpoint gone: nothing reaches it and cleanup closes nothing while still
running its landed-work checks. Legacy records match only while the pane
works inside the recorded worktree, and an unreadable identity refuses.

Cleanup also accepts a finished Herdr record whose window= binding was
cleared, keeping its herdr_* lines as history without any Herdr call.

A live lab regression reproduces the reissue and pins the fix.
…euse-misbinds-task

# Conflicts:
#	bin/fm-spawn.sh
@AgardnerAU AgardnerAU changed the title fix(bin): bind Herdr task endpoints to the pane's terminal identity fix(bin): verify Herdr terminal identity before trusting a reused pane id Sep 25, 2026
…euse-misbinds-task

# Conflicts:
#	bin/fm-teardown.sh
#	docs/configuration.md
#	docs/herdr-backend.md
…arts

A refused validation left the previous record bound, so a later identity
check could read a record that no longer passed validation. The endpoint
safety test also read a variable name that no longer exists.
@AgardnerAU AgardnerAU changed the title fix(bin): verify Herdr terminal identity before trusting a reused pane id fix(bin): stop reused Herdr pane ids binding finished tasks to other panes Sep 25, 2026
Resolve conflicts with upstream's bounded, crash-isolated session-start
endpoint read: bind the task record inside the isolated read so the Herdr
identity check still reads this task's own record, and adapt upstream's
newer session-start Herdr fakes to answer a live pane with its pane JSON.
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The changes affect Herdr task reads and actions, watching, and teardown within the Herdr backend.

Do not merge yet: spawn abort and teardown can still close a replacement terminal.

Reviews (7) · Last reviewed commit: "Merge branch 'main' of https://github.co..." · Reviewed by Greptile

Comment thread bin/fm-spawn.sh Resolved
@AgardnerAU

Copy link
Copy Markdown
Contributor Author

Merged current main into this branch (head 8623583); it is up to date with main and ready for CI.

… finding (ci-1). A new spawn could publish a task record naming the wrong Herdr terminal, or no terminal at all. The rule now is: a Herdr task record is published only when the pane's terminal ID is confirmed, and that ID must match what Herdr returned when it created the pane. What changed: - `bin/backends/herdr.sh`: every pane-create path now keeps the terminal ID from Herdr's create response, if the response has one. That covers `fm_backend_herdr_create_task`, which now prints it as an optional third field, plus the two presentation (projection) create paths. - `bin/fm-spawn.sh`: spawn and relaunch keep that create-time ID. On relaunch, an adopted pane keeps the ID from its existing record. Just before the record is written, the pane is always read back. If that read fails, or returns a different terminal ID from the kept one, spawn stops with "refusing to publish its record" and writes nothing. The old behaviour (log a warning, write the record without an ID, and fall back to checking the working directory) is gone. - Seven Herdr test scripts that read `create_task` output now accept the optional third field. - `tests/fm-control-relaunch.test.sh`: added one mismatch test, `test_herdr_rebind_refuses_a_terminal_identity_the_create_did_not_return`. The fake create returns `term-created`, the read-back returns `term-survivor`, and the test checks that relaunch exits 1, the record is untouched, no terminal ID is stored and no agent is launched. Verification: - As you asked, I ran only the `fm-spawn*` tests that touch Herdr: `fm-spawn-compact-adviser-disable-remote` and `fm-spawn-orca-worktree`. Both pass. - `shellcheck -x` is clean on the three files I changed. - **The new test has not run.** It is in `fm-control-relaunch.test.sh`, which is outside the tests you allowed. One earlier run of that file on this machine stopped at an unrelated test, the Herdr Pi relaunch. That test calls `sed -i` in the GNU form, which macOS sed does not accept, and it then fails with "pi executable not found on PATH". My new test comes after it, so it never ran. That failure is in code I did not change. My attempt to run the file without the Pi test was denied. **Before committing:** the earlier timed-out agent left a scratch folder, `.tmp-ci/`. It is not ignored by git, so it would be committed with everything else. I tried to delete it but that was not allowed. Please remove it first
Comment thread bin/fm-spawn.sh Resolved
Comment thread .tmp-ci/bin/pi Resolved
…i-2 I did not close the pane in the mismatch case, which is not what you literally asked for. The reason is below. **ci-3 (generated files committed).** I ran `git rm -r .tmp-ci`, which removed all 27 files from git and from disk. `.gitignore` did not already cover the folder, so I added `.tmp-ci/`. I made no other change for this finding. **ci-2 (flat pane survives a refusal).** The rule is: if spawn refuses to publish a record, it closes the pane it created, but never a pane that now holds another terminal. In `bin/fm-spawn.sh` the refusal now sets the existing abort-handler variables (`HERDR_PROJECTION_ABORT_*`) before it exits. The existing guarded close (`fm_backend_herdr_projection_cleanup_exact`) then does the work, so there is no new mechanism. This applies only when this spawn created the pane. Relaunch keeps a pane it adopted, because that path never sets the identity pin. There are two cases: - **The read-back fails.** The pane is still the one this spawn created, so it is closed, in both the flat and the projected (presentation) layouts. - **The read-back returns a different terminal ID.** I do not close the pane here. A different ID means Herdr gave the pane ID to someone else's terminal, and our own pane is already gone. The pin would pass the close check, so the close would kill the other terminal - the exact wrong-pane close this PR exists to prevent. In the projected layout, only the task pane is dropped from cleanup; the extra pane made with the new workspace is still closed. **Test.** I added the assertion to `test_herdr_rebind_refuses_a_terminal_identity_the_create_did_not_return`: the log must contain no `pane close`, so the live pane with the other terminal is not closed. This test would not catch a regression: in this fake, the close cannot take the presentation lock, so no close would run even if cleanup were wrongly set up. **Verification.** - `shellcheck -x` is clean on both changed files. - `fm-spawn-compact-adviser-disable-remote` and `fm-spawn-orca-worktree` pass. These are the `fm-spawn*` test files that touch Herdr. - I ran the mismatch test alone, without the rest of `fm-control-relaunch.test.sh`. It passes. - In a scratch variant (not committed) where the read-back has no terminal ID, the refusal sets up cleanup and the abort handler reaches the guarded close. The fake then gives the warning "herdr presentation focus lock unavailable" and the close does not run. **The actual pane close on refusal has not run in any test**, with the fake or with real Herdr
Comment thread bin/fm-spawn.sh Resolved
…nstructed. **The rule:** spawn only arms the abort-path close when the pane is pinned (this spawn created it) and its terminal identity was actually read. If the identity cannot be read, spawn never gets permission to close by pane ID alone. **Change in `bin/fm-spawn.sh`** (the refusal branch before the record is published): - **Identity read, but different from the create response:** the abort cleanup is armed (`HERDR_PROJECTION_ABORT_*`). The existing guarded close then closes the pane, flat or projected. - **Identity unreadable (read failed, or no ID returned):** the task-pane cleanup is cleared, so a projected layout does not close it either. The pane is left open, and one stderr line names it: `error: herdr pane <session>:<pane> was left open; close it by hand`. In the projected layout, the extra pane created with the new workspace is still cleaned up as before. - A pane that relaunch adopted (not pinned) is never closed, as before. **Tests in `tests/fm-control-relaunch.test.sh`:** - I extended the fake Herdr so that the guarded close can actually run in a test. It now answers `session list` with a socket so the lock works, has a focused captain workspace and tab, answers `terminal title clear` with `no_foreground_client`, and handles `pane close`. Two flag files switch these on only for the new cases. - `test_herdr_rebind_refuses_a_terminal_identity_the_create_did_not_return` now asserts that `pane close %9` runs. - New test `test_herdr_rebind_leaves_a_pane_with_an_unreadable_identity_open`: the pane read has no `terminal_id`. The test asserts that spawn refuses, runs no `pane close`, and prints the "was left open" line naming `fmlab:%9`. - Against the previous `fm-spawn.sh`, both tests fail: the first because no `pane close` runs, the second because an unexpected `pane close` runs. With the fix, both pass. - The unreadable case in the test uses a read that returns no ID, not a failed CLI call. The code treats both the same way, but the failed-call form is not tested directly. **Verification:** - I ran all nine Herdr tests in `fm-control-relaunch.test.sh`, including the two above, in a scratch runner. All pass. - `fm-spawn-compact-adviser-disable-remote` and `fm-spawn-orca-worktree` pass. - `shellcheck -x` is clean on both changed files. **Two things to note:** 1. **Your decision reverses round 4.** In the mismatch case, the pane that is closed reads back a different terminal (`term-survivor`) from the one Herdr returned at create. Round 4 left that pane open because it may belong to someone else. It is now closed, as you decided. 2. **Two scratch files must be removed before commit:** `bin/.fm-spawn-old.sh` and `tests/.scratch-one.test.sh`. They are untracked. I tried to delete them, but the deletes were denied
bin/.fm-spawn-old.sh and tests/.scratch-one.test.sh were working copies
left by the pipeline's fix agent and are not part of this change.
…euse-misbinds-task

# Conflicts:
#	bin/backends/herdr.sh
#	bin/fm-spawn.sh
@AgardnerAU

Copy link
Copy Markdown
Contributor Author

Merged current main into this branch and resolved the conflicts in bin/fm-spawn.sh and bin/backends/herdr.sh. The new passive read gate from main now also applies the endpoint identity check, with a test. The branch is up to date with main and ready for CI.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @AgardnerAU — binding Herdr endpoints to create-time terminal_id so a reused pane id cannot steer/teardown another agent's pane is a real restore of backend honesty. Appreciate the main merge and the passive-read gate wiring.

VISION (each rule):

  • One captain, one interface: aligns (finished tasks stop mis-binding).
  • Authority is explicit: aligns (mismatched identity refuses destructive actions).
  • Scripts own the mechanics: aligns (identity check in the backend).
  • A restart is a non-event: aligns (survives Herdr pane-id reuse after restart).
  • Delegation with a spine: aligns (strengthens the refusal path).
  • The fleet outlives any vendor: aligns (quarantined Herdr adapter; terminal_id is what the vendor exposes).
  • Scope: aligns.

Contract-class: restore. Herdr already promised task↔endpoint binding; reused pane ids broke finished records onto strangers. This restores that binding via create-time terminal identity (legacy path still covered). Live go 5/7 (two scenarios fake-Herdr only; attestation verdict go).

Where it stands: attestation MATCH da035e9a, up to date with main. Diff reviewed (identity tightening only; no workflow/secret surface) — approved fork CI for this tip. Main is red; no merge this wake. Overlaps: shares fm-teardown/fm-backend with #6229 and fm-spawn/fm-watch/fm-classify-lib with #6249 — land one-at-a-time when green. Waiting on CI.

…e PR's new test tests/fm-backend-herdr-pane-reuse-e2e.test.sh called `herdr pane report-agent --source ... --agent ... --state idle "$PANE"`, with the pane id after the options. Herdr 0.7.4, which CI uses, needs the pane id positional first, so it failed with "unknown option: fm-pane-reuse-e2e" / "not ok - could not register the unrelated agent". Invariant: every report-agent call in the suite passes the pane id before the options. All the other report-agent callers (smoke, control, eventwait, respawn, presentation, afk-inject) already do this; this was the only call that did not. Fix: one-line reorder to `lab pane report-agent "$PANE" --source fm-pane-reuse-e2e --agent claude --state idle`. Verified locally: the test passes end to end against real Herdr 0.9.1 (all 5 assertions ok). Herdr 0.7.4 is not available locally, so the CI-version run is not verified. shellcheck shows only the existing SC1091 source-following info notices. ci-1 (Behavior portable parallel 1): not caused by this PR. The only failing script is tests/fm-pi-primary-types.test.sh, with TS2339 "Property 'prompt' does not exist on type 'BeforeAgentStartEvent'" in .pi/extensions/fm-branch-supervision.ts and fm-primary-pi-watch.ts. This PR does not touch those files. Upstream main CI run 38316792015, at this PR's base commit 6407052, fails with the identical errors (plus a Pi codemode failure), so this is drift in the globally installed Pi package. No code change is made for it
# Conflicts:
#	bin/fm-spawn.sh
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @AgardnerAU. 4b574611 reorders one report-agent call so the pane id comes first for Herdr 0.7.4, which matches every other caller. That makes sense. The no-mistakes attestation matches 4b574611. I approved the held fork runs: CI 38423299849 and Require no-mistakes 38423299834.

Main has moved: #7172 landed and touched bin/fm-spawn.sh, bin/fm-session-start.sh, docs/configuration.md and tests/fm-session-start.test.sh, all of which this PR also changes. It is now CONFLICTING. When you have a moment, could you merge main and re-raise through git push no-mistakes?

Contract-class: I'm revising my earlier read from restore to new-default. Binding new records to herdr_terminal_id= restores the existing promise that a task's endpoint is its own pane. But going by the PR's own docs, two parts change existing default paths:

  1. A legacy record without herdr_terminal_id= now reads its own live pane as gone when the foreground process works outside the recorded worktree. Main reads it by pane id.
  2. After a Herdr server restart, a restored pane now reads missing to its terminal-bound record, so recovery replaces it instead of reusing it.

Both are reasonable choices, but they're Kun's to make. So once this is rebased and green on a green main, it goes to Kun to merge or leave instead of auto-merging. You don't need to change anything for this.

VISION.md: one captain / authority / scripts / restart / spine / vendor / scope all align. It strengthens a refusal path, a mismatch now refuses to close, and it stays inside the named Herdr adapter. Security: this is a tightening.

Overlaps: #6760 (stale Herdr endpoints after session resets) has a closely related goal and touches the same herdr.sh/backend/teardown/spawn/watch files. #7227 changes herdr.sh's unregistered-pane branch. #6229 touches teardown/backend, and #6249 touches spawn/watch/classify.

…euse-misbinds-task

# Conflicts:
#	bin/fm-backend.sh
#	bin/fm-spawn.sh
#	tests/fm-watch-triage.test.sh
@AgardnerAU AgardnerAU changed the title fix(bin): stop reused Herdr pane ids binding finished tasks to other panes fix(backend): bind Herdr task records to the pane's terminal identity so reissued pane ids are not misbound Oct 18, 2026
@AgardnerAU

Copy link
Copy Markdown
Contributor Author

Merged current upstream main into this branch and re-raised it through no-mistakes (head 64c0883). It is up to date with main and ready for CI; the workflow runs for this head are waiting for maintainer approval.

…euse-misbinds-task

# Conflicts:
#	bin/fm-backend.sh
#	bin/fm-classify-lib.sh
#	bin/fm-secondmate-liveness-lib.sh
#	bin/fm-spawn.sh
#	bin/fm-teardown.sh
#	docs/herdr-backend.md
#	tests/fm-teardown-endpoint-safety.test.sh
@AgardnerAU AgardnerAU changed the title fix(backend): bind Herdr task records to the pane's terminal identity so reissued pane ids are not misbound fix(bin): bind Herdr task records to the pane terminal identity Oct 26, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @AgardnerAU for keeping this current, and sorry your 10-18 re-raise sat without a reply.

What changed since my 10-13 note: two merges of main (64c08832, 9d8c6032) and one doc commit d2427b85, which drops the stale "only tmux and Herdr can host the away-mode supervisor" line. The PR's own logic is the same create-time herdr_terminal_id= binding I reviewed before. I re-read the net diff against main 127f0f30 (0 behind, MERGEABLE). There are no workflow edits and nothing reaches the network or credentials; the evals are test-harness snippets. So I approved this head's held fork runs: CI 40322900466 and Require no-mistakes 40322900576 / 40322951951.

Gates:

  • The no-mistakes attestation binds d2427b85, and live validation is go 2/3.
  • CI: just approved and running. Main's own CI is currently red on several Linux serial shards after GitHub moved ubuntu-latest to 26.04. If the same shards go red here, that's on our side, not yours.
  • On my 10-13 rebase ask: you don't need to rebase or merge main for us again. If a conflict shows up later, it's ours to fix once Kun says merge.

Contract-class (my own read, unchanged from 10-13): new-default. New records binding to the pane's terminal identity restores an existing promise. But two default paths change, and your docs state both plainly: a legacy record without herdr_terminal_id= reads its own pane as gone when the foreground process works outside the worktree, and a restored pane after a Herdr restart reads missing, so recovery replaces it instead of reusing it. VISION aligns on every rule (refusal path strengthened, quarantined Herdr adapter binding to a vendor-exposed id, scripted mechanics). So this is Kun's merge-or-leave call, not an auto-merge.

This isn't waiting on you. It's waiting on CI. Once this head is green, it goes to Kun.

…/fm-teardown.sh:1323. The teardown script sets FM_BACKEND_HERDR_IDENTITY_PIN, but only the Herdr adapter it sources (bin/backends/herdr.sh) reads it. Rule that must hold: lint passes for an output global that a sourced library reads. The only other place that sets this variable is bin/fm-spawn.sh, which also reads it later (line ~6612), so it gets no warning. Fix: I expanded the `match)` case arm and added `# shellcheck disable=SC2034 # Read by the sourced Herdr adapter.`, the same style as bin/fm-backlog-transition-lib.sh. Behaviour does not change. Verification with ShellCheck 0.11.0 (the CI version): `shellcheck -x bin/fm-teardown.sh` exits 0, a run over every shell script this branch changes gives no warnings, and `bash -n` passes. Behavior portable serial 3/4/5/6/7/9 (not caused by this PR): the same test scripts also fail in main's own CI run at base commit 127f0f3: fm-public-followup (serial 3), fm-contributions, fm-fleet-ledger and fm-herdr-groups (serial 4), fm-record-export (serial 5), fm-remote-secondmate-lifecycle-e2e (serial 6), fm-backend-rex and fm-pr-health (serial 7), and fm-watch-checkpoint (serial 9). The failures are timing checks that break under runner load, for example "watcher checkpoint did not run" and "expected exit 124, got 137". Following the user's instruction to run only targeted tests, I ran the five fast-failing scripts locally (fm-fleet-ledger, fm-herdr-groups, fm-record-export, fm-watch-checkpoint, fm-backend-rex) and all pass. I did not run the slower scripts locally. I made no code change for these checks
@AgardnerAU AgardnerAU changed the title fix(bin): bind Herdr task records to the pane terminal identity fix(bin): bind Herdr task records to the pane's terminal identity Oct 27, 2026
# Conflicts:
#	tests/fm-watch-triage.test.sh
Comment thread bin/fm-teardown.sh
Comment on lines +1323 to +1325
match)
# shellcheck disable=SC2034 # Read by the sourced Herdr adapter.
FM_BACKEND_HERDR_IDENTITY_PIN=$T

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Cleanup closes a replacement pane

Teardown sets FM_BACKEND_HERDR_IDENTITY_PIN after its first successful check. Every later identity check then returns match without reading the terminal. If Herdr restarts while teardown returns the worktree, the same pane id can name a fresh terminal when cleanup closes it. Cleanup skips the recorded terminal check and can close that replacement pane.

Save the verified terminal id, not just the pane id, and compare it again before closing. This also avoids relying on the legacy working-directory check after the worktree moves.

…fm/fm-herdr-pane-id-reuse-misbinds-task

# Conflicts:
#	bin/fm-procevent.sh
#	bin/fm-spawn.sh
#	bin/fm-teardown.sh
Comment thread bin/fm-spawn.sh
Comment on lines +7217 to +7220
if [ -n "$HERDR_READ_TERMINAL_ID" ]; then
HERDR_PROJECTION_ABORT_CLEANUP=1
HERDR_PROJECTION_ABORT_SESSION=$HERDR_SES
HERDR_PROJECTION_ABORT_TASK_PANE=$HERDR_PANE_ID

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Failed spawn closes replacement terminal

If Herdr reissues the pane ID before the publication read, fm-spawn.sh detects the different terminal ID and refuses the record. But this branch still arms cleanup for that pane. FM_BACKEND_HERDR_IDENTITY_PIN makes the cleanup check return match without rereading the terminal, so the abort handler can close another task's terminal.

On an identity mismatch, leave the pane untouched rather than arming cleanup.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @AgardnerAU for keeping #5435 current — tip moved to 3578a034 via merges of main since my 26 Oct stamp on d2427b85. Contract-class stays new-default (create-time Herdr terminal-identity binding plus the related spawn/teardown pin paths).

Waiting on you for two things on this tip:

  1. Resolve the two open Greptile P1s: "Failed spawn closes replacement terminal" (bin/fm-spawn.sh) and "Cleanup closes a replacement pane" (bin/fm-teardown.sh) — on an identity mismatch, leave the pane untouched rather than arming cleanup that the identity pin can then match without rereading.
  2. Re-raise through git push no-mistakes so the attestation binds this tip (body still binds 5928f3d9, and Require no-mistakes fails on 3578a034).

Unlabelled Full failure is expected. Rockets: none. Overlaps still noted with #6229/#6249/#6760.

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