Skip to content

fix(placement): reattach worktree sessions after HEAD moves - #2624

Merged
tgrunnagle merged 3 commits into
mainfrom
vast-baron-96eda8af
Nov 2, 2026
Merged

tgrunnagle merged 3 commits into
mainfrom
vast-baron-96eda8af

Conversation

@tgrunnagle

Copy link
Copy Markdown
Contributor

Fixes #1797

Summary

A session bound to a git worktree stopped working once anything moved that worktree's HEAD, such as the agent running git commit through Shell. Every later run, and every scheduled fire from such a session, failed before inference with placement selector not found. The cause was that the local placement provider stored the bind-time HEAD SHA as the ref's Revision and required an exact match on reattach. This PR keeps the HEAD check at bind time, where it guards against a selector that has gone stale. At reattach, the worktree is now identified by path alone, as long as the repository still lists it.

Changes Made

Local placement provider (internal/app/placement.go)

  • New worktree bindings persist Revision: "worktree-v1" instead of the HEAD SHA.
  • currentWorktree matches on path only. It accepts worktree-v1 or a legacy full SHA-1/SHA-256 object ID as the revision and rejects anything else, so unknown revisions fail closed with ErrPlacementNotFound.
  • bindWorktree returns the persisted ref unchanged. Legacy SHA-valued refs keep their exact identity on reattach and are not rewritten.
  • Bind-time behavior is unchanged: bindSelectedWorktree still re-enumerates and returns ErrPlacementChanged if the selected worktree moved between listing and binding.

Architecture docs (docs/architecture/microvm-environments.md)

  • Corrected the worktree-selector paragraph so it says a bound worktree reattaches by path while the repository still lists it.

Implementation Details

  • The issue shows that matching HEAD at reattach pinned the worktree's content, which the session's own work then invalidated. ADR 0291 says reattach should fail when the provider inventory changes, and a commit does not change the inventory.
  • Trade-off: if a worktree is removed and then recreated at the same path, a ref bound to it reattaches to the new worktree. That's an accepted consequence of path identity. A removed worktree that has not been recreated still fails with ErrPlacementNotFound.

API compatibility

  • Assessment: compatible relaxation. No proto, field, or error-code changes.
  • Rationale: EnvironmentRef never appears on the public wire. The display-only PlacementMetadata.revision still reports the worktree's current HEAD. The wire-stable placement_selector_not_found code is unchanged. The only observable difference is that runs and schedules that used to fail with that code now succeed.
  • Major/feature changes: no major version bump and no new feature identifier.
  • Approval for any break: not needed, because nothing breaks.
  • Stored data: new worktree refs persist Revision: "worktree-v1" instead of a HEAD SHA. Existing SHA-valued refs keep reattaching without a rewrite, and sessions already stranded by this bug recover.
  • Upgrade implications (downgrade caveat): an older binary can't reattach worktree-v1 refs. If you roll back after upgrading, worktree sessions and schedules bound after the upgrade are stranded. They fail with placement_selector_not_found, the same symptom as the bug fixed here.

Testing

  • New TestInvariant_worktree_ref_survives_head_move uses real git and the production gitWorktreeLister. It binds a worktree through a selector, commits in it, and checks that reattach returns the same ref while metadata reports the new HEAD. It also checks that ListWorktrees from the worktree source still works, that a legacy SHA-valued ref still reattaches, and that a removed worktree fails with not found.
  • New TestWorktreeReattachRejectsUnknownRevision covers revision validation: empty, short, and long values, uppercase hex, and unknown markers are rejected. Legacy 40-character (SHA-1) and 64-character (SHA-256) object IDs are accepted, and an unlisted path is rejected.
  • Existing placement invariants pass.
  • go run ./cmd/mecademo shows the tool call, permission ask/approval, and result.
  • task docs:check is clean (matlatl reports 0 broken links).
  • task lint reports one finding, which predates this PR: gosec G703 in environment/microvm/launch_ownership_darwin.go, a file untouched since feat: add microVM execution environments #580.
  • task test:race did not pass locally because of environment problems:
    • The first run ran out of disk space.
    • The rerun failed in packages this change doesn't touch (cmd/mecated, cmd/mecatui, forker, ACP, git-worktree subagent tests, and others).
    • The internal/app and internal/adapter/server failures fail the same way on unmodified main (ac34f9e).
    • The microVM test TestRepositoryGuestAuthenticationRejectsCompetingConnectorBeforeDisclosure passed when rerun alone.
    • We're relying on CI for the full race suite.

Additional Notes

Out-of-scope follow-ups:

  • Snapshot Placement.Revision can be stale after HEAD moves.
  • The reattach error text is misleading: it says "selector not found" even though no selector is involved at reattach.

🤖 Generated with Claude Code

tgrunnagle and others added 2 commits October 29, 2026 20:03
Worktree-bound sessions failed every run with placement_selector_not_found
once anything moved the worktree's HEAD, because the ref pinned the
bind-time SHA and reattach required an exact HEAD match.

Implements the plan from issue #1797:
- New worktree refs carry the constant revision "worktree-v1"; reattach
  identifies the worktree by path among the configured repo's listing and
  returns the persisted ref unchanged.
- Legacy refs whose revision is a full git object ID still reattach, so
  already-stranded sessions and schedules recover without a store rewrite.
- Unknown revisions and removed worktrees still fail closed; the
  bind-time HEAD check (ErrPlacementChanged) is unchanged.

Fixes #1797

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses review feedback on #1797: accept 40- and 64-character legacy
object IDs and reject off-by-one lengths, and rewrap the edited
architecture paragraph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Multi-Agent Consensus Review

Agents consulted: correctness-security, test-coverage, architecture-compat, general-quality, comment-hygiene, scope-discipline (codex not available)

Consensus Summary

# Finding Consensus Severity Action
1 Bare repository entry can now bind and reattach as a workspace 8/10 MEDIUM Fix
2 Regression-test docstring claims unknown-revision coverage it does not have 8/10 LOW Fix
3 isGitObjectID hex range is not pinned by a test 8/10 LOW Fix
4 isGitObjectID doc uses history phrasing and omits lowercase-only 7/10 LOW Fix
5 Architecture doc does not state the path-identity trade-off 7/10 LOW Fix
6 bindWorktree receives the worktree path twice 7/10 LOW Fix

Overall

This is a narrow, well-targeted bug fix that implements the plan agreed in #1797. New worktree refs carry the constant worktree-v1. Reattach identifies the worktree by path within the configured repository's listing and returns the persisted ref byte-for-byte, so PlacementBinder's exact-reattachment check still holds. Legacy full-SHA refs keep working without a store rewrite. The bind-time HEAD check (ErrPlacementChanged) is untouched, and there are no server, binder, scheduler, or proto changes. The approach is sound. The compatibility statement checks out: EnvironmentRef never reaches the public wire, and the downgrade path fails closed. Mutation testing of the regression test confirms it is load-bearing: restoring the HEAD-equality check, dropping legacy acceptance, or binding with choice.Head each fail a test.

One finding needs a code change before merge. Before this PR, a bare repository entry from git worktree list (no HEAD line) produced an empty Revision, so validatePlacementBinding rejected it. That rejection was incidental, but it was the only thing stopping it. With the constant revision, the bare git directory now binds and reattaches as a workspace and governance root. An explicit Bare check restores the old behavior. The other findings are polish: a test docstring that overstates its coverage, an unpinned hex-range check, comment wording, stating the accepted path-reuse trade-off in the architecture doc, and a signature that lets the path and ref disagree.

Documentation

  • docs/architecture/microvm-environments.md:61: the new sentence is accurate. Consider also stating that a worktree removed and recreated at the same path (or switched to another branch) reattaches, since the "Exact reattachment" section above it argues against silently moving a session onto a different tree.

Generated with Claude Code

Comment thread internal/app/placement.go Resolved
Comment thread internal/app/placement_test.go Resolved
Comment thread internal/app/placement_test.go Resolved
Comment thread internal/app/placement.go Resolved
Comment thread internal/app/placement.go Resolved
Addresses #2624 review comments:
- MEDIUM internal/app/placement.go (4436212859): reject bare repository entries at bind and reattach
- LOW internal/app/placement_test.go (4436212860): narrow regression-test docstring to its coverage
- LOW internal/app/placement_test.go (4436212869): pin isGitObjectID's hex range with non-hex cases
- LOW internal/app/placement.go (4436212874): state lowercase-only in isGitObjectID doc
- LOW docs/architecture/microvm-environments.md (4436212877): state the path-identity trade-off
- LOW internal/app/placement.go (4436212880): build the worktree ref from choice.Path

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@tgrunnagle
tgrunnagle marked this pull request as ready for review November 1, 2026 16:37
@tgrunnagle
tgrunnagle merged commit 7d74f30 into main Nov 2, 2026
72 checks passed
@tgrunnagle
tgrunnagle deleted the vast-baron-96eda8af branch November 2, 2026 21:10
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Nov 18, 2026
2 tasks
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.

Worktree-bound sessions fail to reattach after HEAD moves (e.g. a commit)

1 participant