Skip to content

Deepen Worktree acquisition to own failed adds #501

Closed

Description

@JacobStephens2

What to build

A failed Worktree acquisition accounts for its partial local effects before it returns. Today an occupied target can leave a newly created local Issue branch, and a failing checkout hook can leave a registered checkout, even though no Worktree owner was returned. A later Run then refuses on artifacts left by the earlier failure.

Deepen the Worktree module so fresh Runs, Continuations and detached Architecture reviews share acquisition ownership from the first new local branch or checkout mutation. A successful acquisition hands that ownership to the existing lifetime. A failed acquisition removes only its own unchanged, clean artifacts; it retains and names anything containing work or whose ownership cannot be established. Callers use the existing acquisition interface.

Acceptance criteria

  • A fresh acquisition refused by a nonempty occupied target leaves its files, existing registrations and origin untouched, and leaves no new local Issue branch. A later attempt is not blocked by a branch the refusal created.
  • The same holds for a Continuation whose local Issue branch was absent. A Continuation with an equal pre-existing branch preserves that branch's exact head and reflog on acquisition failure.
  • Refusal because the branch is already checked out elsewhere preserves that checkout, its edits and its registration.
  • A checkout hook that exits nonzero without changing the newly created checkout causes clean failure recovery: remove the checkout and its registration, then remove only an unchanged Issue branch created by this attempt. Cover fresh acquisition, both Continuation branch states, and detached Architecture review acquisition.
  • A failing hook that creates tracked edits, staged edits, untracked files or ignored files leaves that checkout and its work intact. A failing hook that commits also preserves the commit, including on a detached Architecture review checkout.
  • A changed local ref, an unexpected checkout identity, a locked checkout, a failed inspection or a failed removal leads to conservative retention and an explicit diagnostic identifying the retained path and, where applicable, branch and available head. A cleanup failure does not replace the acquisition error.
  • A path that existed before the new add, including an empty directory or symlink, is not deleted by failure recovery. If Git created a registration there before failing, retain and report it, and retain any branch still referenced by a checkout.
  • A newly created Issue branch is removed only at the expected sampled head and only after establishing that no registered checkout still uses it. A ref that changes before deletion survives.
  • SIGINT, SIGTERM and SIGHUP during an add use the same recovery rules. Clean partial artifacts are removed through completion execution; dirty or uncertain artifacts are retained and reported. Recorded interruption continues to block ordinary Git afterward.
  • Errors during acquisition inspection occur before the new add mutation. Recovery performs no fetch, commit or push, and does not start Delivery, a session or Failed run salvage.
  • Successful acquisition still returns the expected checkout and branch, preserving the current local-work refusals, acquisition serialization, normal lifetime cleanup and Failed run preservation behavior.
  • Tests exercise the existing acquisition interface with real local Git, temporary origin and local hooks, asserting returned failures and observable resource state. Extend the occupied-target test to check initially absent branch state, and retain the existing acquisition and preservation coverage.
  • One command-level regression demonstrates a failed clean acquisition followed by a successful retry after the hook is corrected; no session starts for the failed attempt, and its Claim ends through the current finishing path.
  • Add Worktree to the domain glossary: a factory-owned checkout, on an Issue branch for a Run or detached for an Architecture review; acquisition accounts for partial local effects, removing only attempt-owned clean artifacts on failure and retaining and naming work or uncertain artifacts. The existing Failed run entry continues to describe preservation after successful acquisition.

Blocked by

None (can start immediately).

Decisions

The design tree is settled in four rounds. Each round resolves the decisions enabled by the preceding round; no branch needs a human decision.

Round 1: responsibility and scope

  1. Deepen acquisition inside the Worktree module. The shallow add helper currently treats a failed Git exit as if no owner were needed. Ownership must include the mutation and its failure reconciliation, because only acquisition knows which local resources existed beforehand. Moving this knowledge into Run or Architecture review callers would spread it across the seam and fail locality.
  2. Cover fresh acquisition, Continuation acquisition and detached Architecture review acquisition in one implementation. All three use the same fallible add and have the same ownership gap; this gives leverage without changing the existing caller interface. One session is enough because these are three uses of one local ownership rule, not independently deliverable features.
  3. Use the current domain and ADR constraints. Preserve Continuation semantics from ADR 0002 and ordinary/completion execution semantics already established by the Command. The acquisition recovery policy is a reversible local implementation decision, so no ADR is warranted. Define Worktree in the glossary through this Ticket because the term is already used there but has no definition.

Round 2: ownership and dependencies

  1. Keep a private acquisition owner under the existing repository worktree lock. After origin fetching and the current stale review-checkout handling, and before the new add, record the target's existence, including symlinks, its registration, the Issue branch's existence and head if applicable, and the exact intended start commit. Arm ownership before mutation; on success disarm or transfer it to the returned lifetime. Fallible acquisition inspection happens before the new add mutation. The snapshot concerns this new attempt; it does not undo origin fetching or reconstruct a stale review checkout already removed by the existing policy. This keeps reconciliation serialized with cooperating thirdshift acquisitions and avoids re-acquiring the same lock during recovery or unwinding.
  2. Use one exact start commit throughout acquisition and reconciliation. Continue the current sampled origin behavior for Issue branches and resolve the detached review start to an unambiguous commit before adding it. A mutable tracking name cannot establish whether a hook advanced the checkout. Use fully qualified refs and machine-readable Git observations; Git's error text is not ownership evidence.
  3. Use the existing Git adapter; add no new port. Dependencies are local-substitutable: real Git with a temporary bare origin and local hooks already exercises the seam. A separate cleanup adapter would add an interface without a second justified adapter.

Round 3: failure recovery

  1. Reconcile a failed add through completion execution while the acquisition lock is still held. This includes execution interruption and normal errors. Once mutation may have happened, cleanup is finishing work, and ordinary execution would refuse it after a recorded signal. Keep the original failure as the returned cause; add retention/cleanup diagnostics, and never clear interruption.
  2. Require positive ownership and work checks before removing a checkout. Only a previously absent target with a newly created matching registration qualifies. Its current branch or detached identity and HEAD must match the acquisition's intended start. Its index and working tree must be unchanged, including untracked and ignored files. Then remove it without force. Dirty state, initialized submodules, a lock, unexpected identity or a failed inspection/removal means retain and report. Ordinary non-force removal alone is insufficient: it deletes ignored files and accepts a clean checkout containing a new commit.
  3. Treat pre-existing paths and branches as retained resources on failure. A pre-existing equal Continuation branch is never deleted or reset by failed acquisition. A directory or symlink that existed before adding is not an attempt-owned path, even when empty. If the add partially registered it, report that retained checkout rather than remove the pre-existing path. This conservatively preserves resources acquired outside this attempt.
  4. Recover the checkout before its newly created branch. Delete a branch only if it was absent before this attempt, is still at the intended sampled commit, and no registered checkout uses it. Use an expected-head conditional ref deletion so a ref movement refuses the deletion. A remaining or uncertain checkout keeps its branch; a changed ref is retained even if the checkout is otherwise removable. This prevents loss of work and avoids deleting a checked-out branch, which conditional ref deletion alone permits.
  5. Make retention observable, and keep recovery local. Name the retained checkout/ref and known head with the reason recovery declined or failed; if inspection cannot establish a head, say so. Do not publish or commit hook work, invoke Failed run salvage, or ask callers to recover it. Acquisition failed before those callers received a Worktree. The existing Claim finishing path receives that failure as usual.
  6. Handle unwinding through the same private owner. Its fallback performs conservative completion reconciliation and cannot panic; the explicit error path can enrich the returned error. Do not construct a normal Worktree early: its current Drop force-removes the target and deletes the local Issue branch, which is unsafe for a refused acquisition.

Round 4: verification and publication

  1. The existing acquisition interface is the test surface. Reuse the real-Git acquisition fixture and its temporary hooks directory. Observe refs, reflogs, registration, checkout contents and returned errors, rather than private ownership state or command ordering. A hook can deterministically fail, create work, commit or lock its checkout, so another test seam is unnecessary. Replace assertions tied only to the shallow add helper if any arise; retain behavior coverage for successful acquisition and preservation.
  2. Use isolated signal tests and one retry regression. Reuse the existing signal helper's subprocess isolation for all three supported signals, including ordinary Git remaining blocked after completion recovery. Use an exact recorded child/task identity for test cleanup. One command-level test verifies the effect callers need—retry works and the failed attempt started no session—without duplicating the full direct-interface matrix.
  3. Publish one standalone Ticket labelled only needs-triage. The change fits one fresh context window: one acquisition owner, three constructor paths, real-Git behavior tests and a glossary definition. There is no parent or blocker and no repository edit in this review.

Evidence at the reviewed main head (33dbaa1): all nine current acquisition tests passed with cargo test --bin thirdshift worktree::acquisition_tests -- --nocapture. Foreground experiments with real Git in isolated temporary clones reproduced both gaps: an occupied target returned exit 128 with a new branch but no registration; a clean failing checkout hook returned exit 1 with a branch, checkout and registration. Further hook experiments established the ignored-file, changed-head, detached-commit and checked-out-ref hazards addressed above. No open issue among the 49 read proposes this ownership deepening; #120 requests corrective commands for existing local-state errors.

Architecture review

Strength: Strong · Dependencies: local-substitutable

Files: src/worktree.rs, src/worktree/acquisition_tests.rs, src/worktree/preservation_tests.rs, src/test_support.rs, src/run.rs, src/pass.rs, tests/continuation.rs, tests/architect_run.rs, CONTEXT.md

Before

flowchart LR
  R[Run] --> A[Worktree acquisition]
  V[Architecture review] --> A
  A --> G[Git adapter]
  A -->|success| L[Worktree lifetime]
  G -. failed add .-> E[Local checkout and Issue branch]
  classDef leak stroke:#dc2626,stroke-width:2px;
  class E leak
Loading

After

flowchart LR
  R[Run] --> A
  V[Architecture review] --> A
  subgraph W[Worktree module]
    A[Worktree acquisition] -->|success| L[Worktree lifetime]
    A -->|failure recovery| E[Local checkout and Issue branch]
  end
  A --> G[Git adapter]
  classDef deep stroke-width:3px;
  class W deep
Loading

Problem: the shallow add module returns Git failure while partial checkout and Issue branch effects escape the Worktree ownership seam.

Solution: deepen acquisition so its implementation reconciles partial effects behind the existing interface before returning failure.

Wins

  • depth: recovery behind existing interface
  • locality: acquisition owns partial effects
  • leverage: three callers share recovery
  • seam: tests exercise acquisition

Activity

  1. added
    needs-triage
    ready-for-agent
    architect-plan
    in-progress
    and removed
    needs-triage
    ready-for-agent
    on Oct 7, 2026
  2. removed
    in-progress
    on Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    architect-plan

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions