Skip to content

Deepen Worktree disposal with per-attempt ownership checks #528

Closed

Description

@JacobStephens2

What to build

Deepen the Worktree ownership module so disposal keeps authority checks beside every destructive Git attempt. A Run's cleanup, live Architecture review cleanup and disposal of eligible stale review scratch must retain replacement or uncertain resources when ownership changes during a retry. Ordinary owned cleanup must still finish, including after Command interruption.

This is one standalone Ticket: the private disposal operation, checked Git execution, regressions and glossary clarification fit one fresh session.

Acceptance criteria

  • One private disposal operation owns checkout removal, local Issue branch removal and branch configuration removal; all successful-acquisition disposal paths use it through the existing Worktree interface.
  • Each destructive subprocess attempt, including retries, has fresh checks before execution and checks of its observed outcome afterward. Failed authority checks prevent the attempt or any later mutation.
  • Checkout removal requires the acquired root, administrative directory, common repository and registration identity. A replaced checkout or registration at identical paths, branch and head is retained; locked, switched, symlinked, missing or unreadable ownership evidence also refuses mutation.
  • A successful checkout removal advances only after the captured checkout and administration paths and its registration are absent, with the common repository unchanged. Failed attempts with partial or uncertain effects stop disposal and retain remaining resources.
  • Every local-ref deletion attempt freshly verifies complete registration information, absence of the removed checkout and administration paths, an unused expected Issue branch and its captured cleanup head. Keep Git's expected-old-value deletion; a same-head branch newly attached elsewhere survives.
  • Every configuration-removal attempt freshly verifies ref absence, no registration using that branch, absence of the removed checkout and administration paths, and exact equality with the original local subsection snapshot. Changed configuration or a recreated ref retains the configuration.
  • Healthy disposal still removes only the selected local subsection, preserving included configuration, case-sensitive and dotted subsections, duplicate ordering, embedded newlines and valueless versus empty values.
  • Live cleanup uses completion operations; stale review recovery keeps its ordinary interruption behavior. Completion preserves recorded interruption, uses the existing Worktree-then-refs lock order and holds both locks through disposal. Retention diagnostics identify the checkout, expected branch or detached state, available head and cause; cleanup remains best effort.
  • Stale review disposal failures stop acquisition before its fetch or session, without extending disposal authority to failed acquisition, unmarked scratch or changed durable evidence.
  • Regression tests exercise replacement during checkout-removal retry, same-head attachment during ref-deletion retry, configuration changes and ref recreation during configuration-removal retry, common-repository changes and partial failures. Positive controls prove unchanged authority can retry and complete each transition.
  • Existing Worktree behavior tests remain green, including interruption and sibling-operation serialization; formatting, all-target clippy and the full test suite pass.
  • Sharpen the existing Worktree glossary definition to include disposal's per-attempt, stage-specific checks and conservative retention after partial failure. Keep ADR 0014's eligibility decision and evidence format unchanged.

Blocked by

None (can start immediately).

Decisions

The design tree was settled in three rounds. Each later round depends on the earlier one; every branch is settled.

Round 1 — scope and constraints

  1. Deepen successful-acquisition disposal inside the existing ownership module. Live Run cleanup, live Architecture review cleanup and stale review recovery already share removal. Keep their public interface and put a private stateful disposal operation behind it, so one implementation supplies locality and leverage for all three callers. Deleting that operation would scatter stage authority across checkout, ref and configuration mutations again.
  2. Keep acquisition recovery and confirmed Self-merge origin deletion outside this Ticket. Failed acquisition has incomplete identity evidence and clean-only recovery rules; origin deletion has independent authority from the captured Launch repository. Neither can inherit successful-checkout disposal authority.
  3. Preserve existing ownership policy and lock discipline. Capture the current cleanup head and exact local configuration snapshot after the Worktree and refs locks are held; preserve the acquired directory identities and selected branch. Advanced owned commits remain disposable. Live scope-exit cleanup uses its existing completion view; stale recovery stays ordinary and interruptible because it precedes a new acquisition. ADR 0014 already authorizes successfully acquired detached scratch; this refactor does not reopen that decision.
  4. Promise refreshed authority between attempts, with the existing limits of advisory locks. Keep conditional expected-head ref deletion. Git offers no atomic acquired-directory or configuration-snapshot precondition, so this design does not claim to exclude an arbitrary outside writer acting between the final check and a subprocess mutation. Retry windows must not reuse old authority.

Round 2 — implementation, depending on decisions 1–4

  1. Use distinct checkout, ref and configuration stages in the private disposal operation. Each stage owns its observations, attempt guards and permitted outcome. Only a successful command with the expected observable transition advances the operation; private stages may be represented by types or an enum. This avoids applying the acquired-checkout inspector after the checkout has intentionally been removed.
  2. Extend checked Git execution with separate before- and after-attempt guards for transitions. The after guard receives the execution result, including nonzero exit or execution failure, so it can check the correct resulting state. Reuse the existing retry classification, wait budget, selected interruption behavior and error formatting; ordinary checked execution keeps its current contract. Do not duplicate Git's retry loop in disposal.
  3. Before checkout removal, verify full acquired identity and the captured cleanup head on every attempt. After success, require the checkout path, administration path and matching registration to be absent, with the captured common repository intact. After failure, retry only if the original acquired state and head remain positively established. A replacement or partial removal ends authority for further attempts.
  4. Before ref removal, verify repository identity, removed-path absence, a complete registration listing with no use of the branch, and the expected local head. Delete conditionally at that head. After success, require ref absence and recheck the other predicates; after failure, retry only while the original ref remains unused at the same head. Git permits deleting a checked-out branch at the expected head, so the head comparison alone is insufficient.
  5. Before configuration removal, repeat the repository, removed-path, registration, ref-absence and exact-snapshot checks. After success, require the selected subsection to be absent and recheck those other predicates. After failure, retry only while the original snapshot and authority remain intact. An initially empty subsection requires no mutation, but changed configuration is retained and named.
  6. Stop conservatively on failed commands with partial effects or unverifiable outcomes. Do not infer success or perform another destructive attempt merely because the target disappeared. Real Git returns an error when repeating expected-head deletion of an absent ref or removal of an absent subsection. Keep removed resources removed, retain everything that remains, and preserve the original failure alongside the authority diagnostic.
  7. Keep every authority observation tied to the captured common repository. Verify repository identity around inspections and after lock waits; guard inspections must not recursively invoke their own attempt checks. This prevents a changed Launch repository from granting authority for a later destructive step.

Round 3 — testing and documentation, depending on decisions 5–11

  1. Test through the same interface as callers: Worktree scope exit and ReviewWorktree acquisition. Use real temporary repositories and bare origins, with the existing isolated Git fault adapter to change state at an attempt. These two adapters already justify the subprocess seam; no new external seam or disposal trait is needed. Assert retained files, refs, configuration, registrations and actionable diagnostics, not private stage names.
  2. Pair each refusal regression with an unchanged-authority retry control. Cover both live lifetimes and the stale-review route, plus a failed attempt that partially removes a resource. Keep useful existing ownership, configuration, interruption and serialization tests; replace overlapping procedural assertions instead of adding a second implementation-shaped test surface.
  3. Clarify the existing Worktree term in the Ticket's implementation. Per-attempt disposal is a sharper guarantee of an existing concept, not a new domain term. The internal refactor is reversible and follows the current ADRs, so it needs no new ADR.
  4. Publish one standalone Ticket with no blockers. All three transitions form one small disposal protocol and can land and be verified together; splitting implementation from callers or tests would provide no independent behavior.

Evidence used to settle the design

At main/origin head fee9a587efd7a5195bb285b3d43a0be000695f43, a throwaway test through the existing Worktree interface made the first checkout-removal attempt recreate the checkout at the same path, branch and head, write replacement work, then emit a retryable lock error. cargo test review_probe_cleanup_retry_retains_recreated_checkout -- --nocapture exited 101 with “cleanup's retry deleted a recreated checkout.” The test was removed after the experiment; no implementation changes were made.

Real-Git probes also confirmed that expected-head ref deletion can delete a branch attached to another Worktree, and that repeating ref or subsection deletion after it is absent fails. On the restored baseline, cargo test --bin thirdshift worktree:: passed all 144 tests (0 failed).

All 47 open issue titles and bodies were read and rechecked before publication; none covers this deepening. The recommendation ranks first because it closes reproduced destructive behavior in a recently changed module and shares the correction across all successful-acquisition disposal paths.

Architecture review

Strength: Strong · Dependencies: local-substitutable

Files: src/worktree/ownership.rs, src/git.rs, src/worktree/review_recovery.rs, src/worktree/cleanup_tests.rs, src/worktree/review_recovery_tests.rs, CONTEXT.md

Before

flowchart LR
  Run["Run Worktree"] --> Disposal["Worktree disposal"]
  Review["Architecture review Worktree"] --> Disposal
  Stale["Stale review recovery"] --> Disposal
  Disposal --> Inspection["Ownership inspection"]
  Disposal --> Checkout["Checkout removal"]
  Disposal --> Ref["Issue branch removal"]
  Disposal --> Config["Branch configuration removal"]
  Checkout -. "snapshot then retries" .-> Git["Git attempts"]
  Ref -. "snapshot then retries" .-> Git
  Config -. "snapshot then retries" .-> Git
  classDef leak stroke:#dc2626,stroke-width:2px;
  class Checkout,Ref,Config leak;
Loading

After

flowchart LR
  Run["Run Worktree"] --> Disposal
  Review["Architecture review Worktree"] --> Disposal
  Stale["Stale review recovery"] --> Disposal
  subgraph Disposal["Worktree disposal"]
    Inspection["Ownership inspection"] --> Checkout["Checkout removal"]
    Checkout --> Ref["Issue branch removal"]
    Ref --> Config["Branch configuration removal"]
  end
  Checkout --> Git["Git attempts"]
  Ref --> Git
  Config --> Git
  Git -->|"attempt guards"| Inspection
  classDef deep stroke-width:3px;
  class Disposal deep;
Loading

Problem: Disposal's shallow Git interface separates ownership inspection from retryable mutations, allowing retries to erase replacement resources.

Solution: Add depth to the Worktree ownership module with one disposal interface whose implementation owns stage authority around every attempt at the existing Git adapter seam.

Wins

  • locality: authority stays with disposal
  • leverage: three callers share checked transitions
  • Tests cross the existing interface
  • Replacement work survives retry refusal

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