Repository navigation
Description
What to build
A checkout can be replaced before its original Worktree owner goes out of scope. Cleanup currently treats the checkout pathname and Issue branch name as ownership: it can force-remove the replacement and its work, even when the replacement has the same branch and HEAD.
Deepen the Worktree module so successful acquisition carries checkout and registration identity through the lifetime. Runs, Spec runs and Architecture reviews keep their existing create/use/drop interface. On scope exit, one private cleanup implementation removes only the checkout that owner acquired; local Issue branch deletion follows successful checkout removal and verifies the ref it deletes. Replaced or uncertain resources are retained and named in progress warnings.
Acceptance criteria
- Fresh Worktrees, both Continuation local-branch states, and detached review Worktrees transfer successful acquisition identity to one private lifetime owner. Ownership capture finishes while acquisition is still guarded and the repository worktree lock is held; capture failure uses the existing acquisition recovery rules.
- Dropping an old owner preserves a replacement checkout, its registration, its files and its local refs. Cover recreation with the same checkout pathname, administrative pathname, Issue branch and HEAD; those values alone must not establish ownership. Cover both the Issue branch and detached review interfaces.
- Cleanup detects a replaced checkout directory or administrative directory, a symlink substitution, a changed attached/detached identity, a locked registration and unreadable or inconsistent ownership evidence. It retains uncertain resources and reports the path, branch when applicable, available head and reason.
- Cleanup acquires the existing repository worktree lock through completion execution. Failure to establish the lock causes retention and a warning before any destructive step.
- The local Issue branch is removed only after the owned checkout was successfully removed, a complete registration inspection establishes that no checkout still uses the branch, and an atomic comparison confirms its observed head. A ref moved between observation and deletion survives. A failed checkout removal retains the branch. Normal tracking configuration is cleaned with the deleted ref; configuration changed since its cleanup snapshot or belonging to an observed recreated ref is retained.
- Ordinary successful cleanup still removes the owned checkout and local Issue branch for fresh and continued Runs. Equal pre-existing Continuation branches are still adopted on successful acquisition. Owned review scratch, including edits and detached commits, is still disposable at scope exit. Tests allow legitimate Run commits to advance HEAD after acquisition.
- Failed run preservation keeps its current retention decision: a failed preservation retains local work, while successful preservation permits verified cleanup. SIGINT, SIGTERM and SIGHUP do not prevent finishing cleanup or clear recorded interruption; ordinary Git remains interrupted afterward.
- Cleanup problems remain warnings and do not replace the Run outcome, unwind again or start a session, salvage, fetch, commit or push. A missing original checkout or uncertain registration produces conservative retention rather than deletion by name.
- Both lifetime owners delegate cleanup to the same implementation; replace their duplicated destructive cleanup paths. Reuse existing registration and qualified local-ref observations where their guarantees fit.
- Update the Worktree definition in the domain glossary to say that successful acquisition carries checkout and registration identity through its lifetime and that cleanup retains replaced or uncertain resources. Preserve the existing acquisition and Failed run definitions. No ADR change is required.
- Tests cross the existing Worktree and ReviewWorktree acquisition/scope-exit interfaces with real local Git, temporary origin and controlled fault/interleaving fixtures. Assert filesystem contents, registration state, exact refs and retention diagnostics; retain acquisition, synchronization and preservation coverage.
- Run focused Worktree tests and relevant command lifecycle tests, followed by the repository's formatting, clippy and full test checks. Leave the suite green on Linux and macOS.
Blocked by
None (can start immediately).
Decisions
The design tree is settled in four rounds: responsibility and constraints → identity transfer → cleanup and failure behavior → verification, documentation and plan size. Every decision includes its reason; no branch requires a human decision.
Round 1: responsibility and constraints
- Deepen successful lifetime ownership inside the Worktree module. Acquisition already owns partial effects, but its successful return discards the facts that could establish ownership later. Keeping those facts through scope exit removes an implicit caller obligation to ensure that a reusable path still names the original checkout, and concentrates this knowledge for locality.
- Cover both live lifetime owners in one change. Worktree and ReviewWorktree have the same path-identity gap and duplicate cleanup. A private owner provides leverage across Runs, Spec runs and Architecture reviews while keeping their existing interface.
- Preserve existing disposal and adoption policies. An owned Issue branch checkout retains its current cleanup eligibility, governed by Failed run preservation; owned review scratch remains disposable. Successful Continuation acquisition adopts an equal pre-existing local branch as today. The change establishes which instance may be disposed of, following the documented promise to remove only thirdshift's own resources, rather than redefining what work an owned checkout may contain. ADR 0002 remains intact.
- Keep origin sampling, branch selection and stale review recovery on their established paths. Launch validation and Worktree acquisition continue to sample independently. Removal of a leftover review checkout before a new acquisition is the existing separate recovery policy: there is no live original owner to supply directory handles. This Ticket concerns disposal by a live owner, so it needs neither a persistent ownership marker nor a stale-checkout policy change.
Round 2: identity transfer and dependencies
- Retain open directory handles for the checkout root and its Git administrative directory. Compare current directory metadata with those handles using Unix device/inode identity, alongside the captured paths and repository identity. Git can reuse both pathnames, branch and HEAD after recreation; holding the original directories open prevents an inode from being recycled into a false match while the owner lives. Linux and macOS are the supported targets and production already uses Unix interfaces, so this adds no platform restriction or dependency.
- Capture and transfer ownership before disarming acquisition recovery. Once Git successfully adds the checkout, establish its root, administrative directory, common repository and expected attached Issue branch or detached review identity while the acquisition lock and guard remain active. Transfer the fully established private owner to the returned lifetime. If capture fails, existing conservative recovery still accounts for the add's effects; no unguarded successful-add gap is introduced. A successfully accepted empty target directory is adopted as today.
- Keep instance identity distinct from the starting commit. Capture the expected branch/detached mode, but allow its commit to change during sessions and review scratch experiments. Pinning cleanup to the acquisition HEAD would reject legitimate work, so cleanup observes the current attached Issue branch head only when preparing ref deletion.
- Use the existing Git adapter and filesystem observations behind an internal seam. Dependencies are local-substitutable: the current temporary clone, bare origin and hooks already exercise real Git. The interface is the test surface; no additional external adapter or hypothetical port is justified. Share registration parsing and local-ref observations with acquisition rather than duplicate the ownership vocabulary.
Round 3: cleanup and failure behavior
- Check ownership under the existing completion worktree lock before destructive cleanup. Verify that the current non-symlink checkout root and administrative directory match the pinned handles, belong to the captured common repository, and agree with the expected registration and attached/detached identity. Refuse locked, missing, replaced or unreadable evidence. Completion execution preserves cleanup after interruption; retaining on a lock error replaces the unsafe fallback that cleans without serialization. The lock serializes cooperating thirdshift writers; identity checks establish the instance observed at cleanup, while the ref deletion comparison closes its own ref-movement race.
- Force-remove only a positively identified owned checkout. Keep the current disposal behavior for that checkout, including owned review scratch. If inspection or removal fails, retain and report the local Issue branch too. Removing a branch after a checkout-removal error would sever the cleanup dependency and could strand or erase work.
- Delete the fully qualified Issue ref conditionally. Before checkout removal, observe the current attached branch head. After successful removal, verify through a complete registration inspection that no checkout uses it, then use Git's atomic old-value comparison to delete that exact ref. Reuse the acquisition recovery precedent for conditional ref removal. A changed ref or uncertain registration survives. After a successful ref deletion, preserve ordinary cleanup of its per-branch configuration only when the ref is still absent and that section still matches a NUL-delimited snapshot captured during cleanup; otherwise retain the section. Capture the snapshot through the error-preserving full local configuration listing with includes disabled and NUL-delimited records. Select the exact branch subsection by splitting each key at its last dot; preserve subsection case, duplicate order, embedded newlines, and valueless versus empty values. Remove only that exact local subsection after rechecking ref absence and snapshot equality. This preserves normal tracking-metadata cleanup while refusing an observed replacement or later edit, under the same cooperative worktree lock. Detached reviews have no Issue ref to delete.
- Keep Failed run retention authoritative. A Worktree kept because preservation failed performs no destructive cleanup. Successful preservation restores cleanup eligibility, and the same instance checks still apply. This preserves the existing salvage contract while making the later disposal safe for both normal and completion execution.
- Report retention without changing the command outcome. The private cleanup implementation names the retained path, Issue branch if present, available head and failed ownership/removal step. Drop remains best effort and does not panic on observation errors. Missing original resources are uncertainty, not permission to delete whatever later occupies their names; cleanup cannot replace a Delivery result that has already been decided.
Round 4: verification, documentation and size
- Test through acquisition and scope exit with real local Git. Reuse the existing fixture seam, not a new cleanup trait. The principal regression removes and recreates a checkout at the same path and administrative path, on the same Issue branch and HEAD, writes replacement work, and drops the old owner. Assert that the replacement and its work survive. A corresponding detached review case proves the shared ownership rule.
- Verify the positive lifecycle and each destructive dependency. Keep fresh/Continuation cleanup, advancement of the owned branch, disposable review scratch and Failed run preservation cases. Add controlled cases for checkout and administrative-directory replacement, unexpected mode/symlink/lock, inspection/removal failure, ref movement immediately before conditional deletion, and changed branch configuration or a recreated ref before configuration cleanup. Use barriers or existing fault fixtures instead of timing guesses, and assert outcomes rather than internal call sequences. These cases verify ownership and ordering that the current happy-path tests cannot expose.
- Keep interruption verification at the existing isolated signal seam. Exercise SIGINT, SIGTERM and SIGHUP and assert cleanup/retention plus continued refusal of ordinary Git. This protects finishing behavior without introducing process-global interference between tests. Run the focused suite, then the required repository checks because both acquisition construction and Drop are shared across command lifecycles.
- Sharpen the existing Worktree glossary entry through this Ticket. Worktree already names the deepened module; its definition should cover successful lifetime identity and retention of replacements. The choice of private ownership representation is reversible and introduces no new domain term or hard-to-reverse trade-off, so it warrants no ADR.
- Publish one standalone Ticket with no blockers. This is one ownership transfer and cleanup rule across two live owners, with existing Git and test fixtures. It fits one fresh context window; acquisition, disposal and their tests must land together to be verifiable, so a Spec or horizontal prefactor would not improve the work's size.
Validation from this Architecture review
Reviewed main at 3b01804e034bdc1f4c54809e5799f01b590ad10d. A disposable regression through the actual Worktree create/drop interface failed as expected: the replacement reused the checkout path, administrative path, attached Issue branch and HEAD, yet dropping the old owner erased its untracked file. This establishes why path/ref/head observations alone cannot identify the acquired instance. A local directory-handle probe distinguished a removed original from its replacement by device/inode identity. The prototype was removed; cargo test --bin thirdshift worktree:: then passed all 62 tests. Implementation and its full checks remain this Ticket's work.
Architecture review
Strength: Strong · Dependencies: local-substitutable
Files: src/worktree.rs, src/worktree/acquisition.rs, src/worktree/acquisition_tests.rs, src/worktree/preservation_tests.rs, CONTEXT.md
Before
flowchart LR
C["Run / Spec run / Architecture review"] --> A["Worktree acquisition module"]
A --> L["Worktree lifetime module"]
L --> D["Worktree cleanup module"]
A -. "identity discarded on success" .-> D
D --> G["Git adapter"]
T["Tests"] --> A
T --> L
classDef shallow stroke:#dc2626,stroke-width:2px;
class L,D shallow;
After
flowchart LR
C["Run / Spec run / Architecture review"] --> A
subgraph W["Worktree module"]
A["Worktree acquisition module"] -->|"transfer identity"| L["Worktree lifetime module"]
L -->|"pinned instance"| D["Worktree cleanup module"]
end
D --> G["Git adapter"]
T["Tests"] --> A
T --> L
classDef deep stroke:#2563eb,stroke-width:4px;
class W deep;
Problem: The Worktree lifetime's scope-exit interface assumes reusable paths and Issue branch names still identify its checkout, so cleanup can erase a replacement's work.
Solution: Carry successful acquisition identity behind the existing Worktree interface and deepen both lifetimes through one private cleanup seam using the existing Git adapter.
Wins
- Locality joins acquisition and cleanup
- Leverage covers both Worktree lifetimes
- Replacement checkouts and work survive
- Tests use the lifetime interface
- Depth hides ownership proof from callers
Deletion test: Removing the deeper owner would put identity proof, completion locking, retention and conditional cleanup back into both lifetime owners or their callers; the complexity would spread rather than disappear.
Coverage: All 49 open issues were read and coverage was checked again before publication. None proposes this successful-lifetime deepening. #120 and #53 ask for error guidance; the already-closed #501 owns failed acquisition effects. Existing ADRs are preserved.
Activity