Skip to content

Retire merged local branches during cleanup - #2

Closed
brettheap wants to merge 10 commits into
mainfrom
cleanup
Closed

brettheap wants to merge 10 commits into
mainfrom
cleanup

Conversation

@brettheap

@brettheap brettheap commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Lane: cleanup
Claim: #2 (comment)

Summary

  • Adds project clean and project doctor repository-health reporting for branches, linked worktrees, remote freshness, merge state, and ignored-file blockers.
  • Lets confirmed worktree cleanup discard only an explicit Python cache allowlist: non-symlink pycache directories and non-symlink regular .pyc/.pyo files.
  • Distinguishes a branch merged into a last-fetched remote target, a squash/rebase merge confirmed by the exact GitHub PR head, a genuinely unmerged branch, and unavailable remote evidence. Remote evidence never enables removal; local ancestry remains required.
  • Preserves every unknown ignored artifact, symlink, remote branch, and forceful Git operation; post-removal Git commands run from the surviving default-branch worktree.

Validation

  • 61 isolated py-bench unit tests pass.
  • python3 -m py_compile project, strict OpenSpec validation, git diff --check, and live clean/doctor audits pass.

Governed changes

  • add-project-cleanup-command
  • add-doctor-repository-health
  • allow-disposable-ignored-cache-cleanup
  • clarify-remote-merge-status

Summary by Sourcery

Strengthen repository cleanup and diagnostics with actionable health reporting, safer merged-worktree retirement, and explicit local-versus-remote merge evidence.

New Features:

  • Add repository-health reporting to project doctor, including cleanup classifications, branch drift, blockers, merge evidence, and recommendations in human and JSON output.
  • Allow confirmed removal of safely merged worktrees to discard only allowlisted Python cache artifacts and retire the paired local branch.
  • Distinguish local, last-fetched remote, and exact-head GitHub pull-request merge evidence while preserving local ancestry as the destructive-cleanup requirement.

Bug Fixes:

  • Clarify unavailable and remote-only merge states so branches are not incorrectly labeled unmerged or removed without local verification.
  • Prevent cleanup from deleting unknown ignored files, symlinks, or remote branches.

Enhancements:

  • Keep cleanup read-only by default and anchor post-removal operations to a surviving worktree with revalidation and failure containment.

Documentation:

  • Update README guidance for repository health, remote merge freshness, disposable cache cleanup, and paired branch retirement.

Tests:

  • Expand isolated Git fixture coverage for doctor health reporting, merge-state classification, cache safety, branch retirement, revalidation, and failure handling.

Chores:

  • Add governed OpenSpec change records covering doctor health, disposable cache cleanup, remote merge status, and merged branch retirement.

Copilot AI lite review requested due to automatic review settings September 11, 2026 10:03
@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@sourcery-ai

sourcery-ai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR makes explicit cleanup of a safely removable merged worktree retire its paired local branch in the same confirmed operation, using non-force git branch -d after worktree removal. It preserves read-only defaults and all existing safety gates, reports partial failures without deleting branches forcefully, adds focused success/failure tests and OpenSpec documentation, and updates the README.

Sequence diagram for paired worktree and branch cleanup

sequenceDiagram
    actor User
    participant Project as project clean
    participant Git as Git repository

    User->>Project: clean --apply --action remove --worktree PATH --yes
    Project->>Git: Revalidate clean, non-current, merged worktree
    alt Safety checks pass
        Project->>Git: remove worktree PATH
        Project->>Git: git branch -d BRANCH
        alt Branch deletion succeeds
            Git-->>Project: Local branch retired
            Project-->>User: Cleanup succeeds
        else Branch deletion fails
            Git-->>Project: Branch deletion failure
            Project-->>User: Return failure, branch remains
        end
    else Safety checks fail
        Project-->>User: Refuse cleanup
    end
Loading

File-Level Changes

Change Details Files
Extend confirmed safe worktree removal to retire the paired local branch.
  • Execute worktree removal first, then normal git branch -d for the verified merged branch.
  • Display both operations in the cleanup plan while preserving confirmation and pre-execution state revalidation.
  • Report branch-deletion failures after worktree removal without force-deleting or affecting remote branches.
project
tests/test_project.py
Add specification and design coverage for paired branch retirement and its safety boundaries.
  • Define successful retirement, refusal conditions, and partial-failure behavior.
  • Record implementation decisions, non-goals, risks, migration steps, and completed validation tasks.
openspec/changes/auto-delete-merged-branches/.openspec.yaml
openspec/changes/auto-delete-merged-branches/design.md
openspec/changes/auto-delete-merged-branches/proposal.md
openspec/changes/auto-delete-merged-branches/specs/project-clean-branch-retirement/spec.md
openspec/changes/auto-delete-merged-branches/tasks.md
Update user-facing cleanup documentation to describe automatic local branch retirement.
  • Clarify that only explicitly confirmed removal of clean, non-current, locally merged worktrees retires branches.
  • Document normal branch deletion, remote-branch preservation, and failure behavior.
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. A confirmed cleanup now removes the paired local branch after deleting its worktree, so an incorrect classification could remove a local ref that is not straightforwardly restored by reverting the code. The committed history remains available through the remote, merge history, or Git recovery mechanisms, making the loss bounded and generally repairable; branch deletion also uses Git's non-force guard.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved cleanup safety issues and regression-test gaps remain.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Extends cleanup to retire the paired local branch after safely removing a confirmed merged worktree.

Changes:

  • Adds sequential worktree removal and non-force branch deletion.
  • Adds cleanup success and failure tests.
  • Updates README and OpenSpec documentation.
File summaries
File Summary
tests/test_project.py Tests branch retirement and failure behavior.
README.md Documents cleanup semantics.
project Implements paired worktree and branch cleanup.
openspec/changes/auto-delete-merged-branches/tasks.md Tracks implementation and verification tasks.
openspec/changes/auto-delete-merged-branches/specs/project-clean-branch-retirement/spec.md Defines branch-retirement requirements.
openspec/changes/auto-delete-merged-branches/proposal.md Defines scope and impact.
openspec/changes/auto-delete-merged-branches/design.md Records design decisions and risks.
openspec/changes/auto-delete-merged-branches/.openspec.yaml Provides change metadata.
Review details

Suppressed comments (3)

project:602

  • The prior suite's successful delete-branch assertion was removed, and the remaining tests only cover refusal for unmerged/default branches. This refactor now routes the retained explicit orphan-branch action through this command loop, so add a disposable success-path test to verify that action still deletes a verified merged local branch after the worktree is already gone.
    for command in commands:
        code = execute(command)
        if code:
            return code
    return 0

project:573

  • After the single cleanup-state check, this path removes the worktree and then deletes the branch without re-checking that the branch is still an ancestor of the local cleanup target. git branch -d can accept a tracking branch based on its configured upstream instead, so if main is rewound while the worktree removal is in progress, this can delete a branch that is no longer merged into main. Re-check the saved branch head/target ancestry after the removal and abort the branch step if it no longer matches, or otherwise serialize the two operations.
        commands = [["git", "-C", str(root), "worktree", "remove", str(wanted)],
                    ["git", "-C", str(root), "branch", "-d", row["branch"]]]

tests/test_project.py:467

  • The added failure test only exercises [0, 7], so it does not cover the safety branch where worktree removal itself fails. A regression could then continue to branch -d after a failed removal; add a case with a nonzero first result and assert that only the worktree command is executed.
             patch.object(module, "execute", side_effect=[0, 7]) as execute:
            self.assertEqual(module.clean(args), 7)
        commands = [call.args[0] for call in execute.call_args_list]
        self.assertEqual(commands[0][-2:], ["remove", str(tree)])
        self.assertEqual(commands[1][-2:], ["-d", "001-feature"])
  • Files reviewed: 8/8 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread project Resolved
Copilot AI review requested due to automatic review settings September 11, 2026 10:08

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Targeting the worktree being removed can break branch deletion, and the updated path lacks a successful regression test.

Review details

Suppressed comments (3)

openspec/changes/auto-delete-merged-branches/proposal.md:30

  • This change updates the existing project-clean behavior, but the active cleanup spec still says that worktree removal must leave the branch for a separate explicit action (openspec/changes/add-project-clean-command/specs/project-clean/spec.md:54-67). Declaring Modified Capabilities as None leaves the requirements contradictory, so please reconcile the existing requirement/scenario and mark project-clean as modified (or otherwise make the overlay explicit).
### Modified Capabilities

None. The existing cleanup change has not been archived into baseline specs;
this change records the additional branch-retirement contract separately.

project:573

  • Using root for the second command breaks when args.target resolves to the worktree being removed: discover() returns that worktree's top-level path, so after line 572 removes it, git -C root branch -d ... cannot start in the missing directory and the local branch is left behind. Build the branch command from a surviving worktree (ideally the worktree on report["target_branch"]) and add a regression test for targeting the linked worktree.
        commands = [["git", "-C", str(root), "worktree", "remove", str(wanted)],
                    ["git", "-C", str(root), "branch", "-d", row["branch"]]]

project:601

  • The refactor routes delete-branch through this new commands loop, but the previous successful delete-branch assertion was removed from the renamed test and no other test invokes that action successfully (the remaining cases only cover refusal). Please retain/add a disposable-repository success case so this updated execution path is covered, including its zero exit status.
        commands = [command]
    show_plan(commands, root)
    confirm(args.yes)
    if args.action == "delete-branch":
        require_unchanged_cleanup_state(root, args.action, {"target_branch": report["target_branch"]},
                                        branch=args.branch, branch_head=branch_head)
    else:
        require_unchanged_cleanup_state(root, args.action, expected, **action_target)
    for command in commands:
        code = execute(command)
        if code:
            return code
  • Files reviewed: 8/8 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@brettheap

brettheap commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor Author

CLAIMED (lane cleanup, 2026-09-11T10:25:00Z)

Object: doctor repository-health reporting on PR #2 head 3cca8b1.
Required sibling checks: PR #2 comments contained no existing claim for this object; GitHub search for doctor repository health returned no PR; origin heads matching doctor or health returned none.

Copilot AI review requested due to automatic review settings September 11, 2026 10:31
@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved critical and moderate findings remain in cleanup safety, health-state handling, and specification consistency.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (4)

openspec/changes/auto-delete-merged-branches/proposal.md:30

  • This behavior changes the existing project-clean capability, but this proposal declares no modified capabilities. The still-active openspec/changes/add-project-clean-command/specs/project-clean/spec.md:56-67 requires worktree removal to leave the branch for a separate action, so the repository now contains contradictory normative requirements. Mark project-clean as modified and update or supersede that requirement/scenario together with this change.
### Modified Capabilities

None. The existing cleanup change has not been archived into baseline specs;
this change records the additional branch-retirement contract separately.

openspec/changes/auto-delete-merged-branches/tasks.md:10

  • This task is marked complete even though its final clause—resolving any review findings with regression evidence—cannot be complete while this pull request is still under review. Leaving it checked makes the change record's progress state inaccurate; keep it unchecked until the review cycle is finished.
- [x] 2.3 Commit and push the governed change on `cleanup`, request review, and resolve any resulting review findings with regression evidence.

project:743

  • When Git cannot inspect a linked default worktree, repo_state supplies dirty=None and/or ignored_files=None; these truthiness checks treat those unknown values as clean and fall through to an ok/protected-default result. The same fall-through happens when an upstream exists but ahead/behind could not be computed, so doctor can report an uninspectable default as healthy. Treat unknown cleanliness/ignored/tracking values as warning states before returning the healthy status.
        if row.get("dirty"):
            return ("warning", "dirty-default",
                    "Preserve or commit the default-branch working changes before further maintenance.")
        if row.get("ignored_files"):
            return ("warning", "ignored-local-files-default",

project:890

  • The new repository-health check is only exercised through ordinary doctor; the suite has no doctor --strict case with a health warning. Since strict mode's nonzero result is the behavior this added warning check is meant to drive, add an assertion that a fixture with one of these warnings returns the strict failure code while ordinary doctor remains zero.
        attach_repository_health(report)
        checks = check_rows(report)
        checks.extend(repository_health_checks(report))
  • Files reviewed: 13/13 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread project Resolved
Copilot AI review requested due to automatic review settings September 11, 2026 10:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved cleanup safety and repository-health issues remain, with related test and specification follow-ups.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (7)

openspec/changes/auto-delete-merged-branches/proposal.md:30

  • This change updates the existing project-clean behavior, but the active cleanup spec still requires worktree removal to leave the branch for a separate explicit action. Declaring Modified Capabilities as None leaves contradictory normative requirements; mark project-clean as modified and update or supersede that requirement/scenario together with this change.
None. The existing cleanup change has not been archived into baseline specs;
this change records the additional branch-retirement contract separately.

openspec/changes/auto-delete-merged-branches/tasks.md:10

  • This task is marked complete even though its final clause says to resolve resulting review findings with regression evidence, while this pull request still has unresolved safety and test findings. Keep the task unchecked until those follow-up changes and evidence are complete so the change record reflects the actual state.
- [x] 2.3 Commit and push the governed change on `cleanup`, request review, and resolve any resulting review findings with regression evidence.

project:573

  • When --target resolves to the linked worktree being removed, discover() makes root equal wanted. The first command deletes that directory, so the second git -C root branch -d cannot start and cleanup returns a failure with the branch left behind, contrary to the paired-retirement contract. Build the branch command from a surviving worktree or the common Git directory, and add a regression test that targets the linked worktree itself.
        commands = [["git", "-C", str(root), "worktree", "remove", str(wanted)],
                    ["git", "-C", str(root), "branch", "-d", row["branch"]]]

project:573

  • The only merged-state revalidation occurs before both commands. After the worktree is removed, the branch or target can change; git branch -d may validate against the branch's configured upstream rather than report['target_branch'], allowing deletion even though it is no longer merged into the local cleanup target. Re-check the saved branch head's ancestry against the target after removal before running branch deletion.
        commands = [["git", "-C", str(root), "worktree", "remove", str(wanted)],
                    ["git", "-C", str(root), "branch", "-d", row["branch"]]]

project:744

  • The root worktree never gets an ignored_files field: that field is only populated inside the linked-worktree loop in repo_state. Consequently, an ignored-only file in the default checkout makes row.get("ignored_files") return None, so doctor reports the protected default as healthy instead of surfacing the blocker. Populate the root worktree's ignored-file count in the audit (or inspect it before this status check) and add a regression case for ignored files in the default checkout.
        if row.get("ignored_files"):
            return ("warning", "ignored-local-files-default",
                    "Preserve or relocate ignored local files before further maintenance.")

tests/test_project.py:487

  • Renaming this test removed the only successful delete-branch invocation; the remaining calls only assert refusals. The new commands list/loop is also the execution path for that explicit action, so a regression could leave a verified orphan branch behind without failing the suite. Keep or add a disposable success case for --action delete-branch after its worktree is already gone.
    def test_clean_retires_merged_worktree_and_local_branch(self):

tests/test_project.py:527

  • This failure regression only exercises [0, 7], so it verifies branch-deletion failure but not the safety branch where worktree removal itself fails. Add a case with a nonzero first result and assert that execute is called once; otherwise a later refactor could run branch -d after failed worktree removal.
             patch.object(module, "execute", side_effect=[0, 7]) as execute:
            self.assertEqual(module.clean(args), 7)
        commands = [call.args[0] for call in execute.call_args_list]
        self.assertEqual(commands[0][-2:], ["remove", str(tree)])
        self.assertEqual(commands[1][-2:], ["-d", "001-feature"])
  • Files reviewed: 13/13 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread project Resolved
Comment thread project
if args.command == "doctor":
attach_repository_health(report)
checks = check_rows(report)
checks.extend(repository_health_checks(report))
@brettheap

Copy link
Copy Markdown
Contributor Author

CLAIMED (lane cleanup, 2026-09-11T10:52:55Z)

Object: allowlisted disposable ignored-cache removal during confirmed worktree cleanup.
Required sibling checks: PR #2 comments contained no existing claim for this object; GitHub search for safe ignored cache cleanup returned no PR; origin heads matching safe ignored, ignored cache, or cache cleanup returned none.

Copilot AI review requested due to automatic review settings September 11, 2026 11:15
@brettheap

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copilot AI commented Sep 11, 2026 •

Copy link
Copy Markdown

@copilot review

Addressed in bb91a49.

I tightened cleanup safety by validating the target command-root worktree against the repository/common Git dir and target branch, constrained disposable __pycache__ handling to recursively allowlisted non-symlink content, switched disposable deletion to descriptor-relative no-follow operations, and ensured default-branch divergence warnings take precedence over disposable-cache OK status.

@copilot review

Addressed in bb91a49.

Cleanup now verifies the target command-root worktree belongs to the same repository and is on the target branch, validates __pycache__ directories recursively before classifying them as disposable, uses descriptor-relative no-follow deletion for disposable cache artifacts, and keeps default-branch drift warnings ahead of disposable-cache OK reporting.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Unresolved moderate correctness and safety findings remain in cleanup, merge evidence, and health reporting.

Review details

Suppressed comments (8)

openspec/changes/add-doctor-repository-health/design.md:22

  • This non-goal conflicts with the implementation and the remote-merge contract: attach_repository_health() calls cleanup_report(), which performs github_merge_evidence() lookups, and doctor output exposes that state. Remove determine pull-request state from this non-goal (or explicitly scope it to no fetch/mutation) so the design matches the shipped behavior.
- Fetch remote refs, determine pull-request state, mutate Git state, or make

openspec/changes/auto-delete-merged-branches/specs/project-clean-branch-retirement/spec.md:12

  • This new requirement conflicts with the still-active add-project-clean-command specification, which says worktree removal leaves branch deletion as a separate explicit action (openspec/changes/add-project-clean-command/specs/project-clean/spec.md:54-67). Since this change intentionally alters that contract, update or explicitly supersede the prior requirement rather than declaring this capability independent; otherwise the active specifications describe incompatible cleanup behavior.
When confirmed cleanup removes a clean, merged, non-current linked worktree,
it SHALL then delete that worktree's local branch using normal verified Git
branch deletion. The plan SHALL show both operations before confirmation.

project:508

  • remote_merge_target is derived only from a present worktree whose branch is the target. A valid repository can have main as a local branch and remote-tracking ref while no worktree checks it out (for example, the root worktree is on a feature branch); this then incorrectly reports remote evidence as unavailable and skips the required remote/GitHub comparison. Resolve the target branch's configured branch.<target>.remote/merge directly when target_source is absent, without using the current worktree's @{upstream}.
        return {"state": "unavailable", "number": None, "url": None}
    try:
        candidates = json.loads(result.stdout)
    except ValueError:

project:724

  • This lookup is performed for every apply action, not just remove. A repository can have the default branch locally but not checked out in any worktree (for example, its primary worktree is currently on a feature branch); in that case valid push and orphaned delete-branch actions now refuse before building their commands, even though only post-removal operations require a surviving target worktree. Use the target worktree only for remove and retain root for the other actions.
    if action == "delete-branch":

project:358

  • The classifier validates only the __pycache__ directory entry, not its contents. Git reports an ignored directory as one !! __pycache__/ record, so a cache containing a symlink is classified as disposable and shutil.rmtree will unlink that nested symlink. That violates the stated boundary to preserve symlinks; inspect descendants and classify such a directory as blocking before removal.
        return None
    if candidate.is_dir() and candidate.name in DISPOSABLE_IGNORED_DIRECTORY_NAMES and disposable_cache_tree(candidate):
        return candidate
    if candidate.is_file() and candidate.suffix in DISPOSABLE_IGNORED_FILE_SUFFIXES:

project:478

  • The gh pr list --state all call relies on gh's default result limit (30). If a branch has more historical pull requests, a merged PR with the matching head OID can be outside the returned page and this code reports not-merged, contradicting the exact-head evidence contract. Use explicit pagination/limit or a query that filters by head OID.
def ancestor_ref(root, commit, ref):
    if not commit or not ref:
        return None

project:955

  • The disposable-cache branch returns ok before checking the default branch's ahead/behind counts. A default checkout with only a Python cache and both local/remote drift will therefore be reported as protected-default-with-disposable-cache instead of the required diverged-default warning (the same masking occurs for ahead-only or behind-only drift). Evaluate drift before returning the cache-only status.
    org = repository.split("/", 1)[0]
    orgs = config.get("orgs", {})
    if not isinstance(orgs, dict):

project:1089

  • When ignored-file inspection fails, repo_state sets ignored_files and both path lists to None. This rendering prints ignored=None; disposable=0; blocking=0, so doctor presents an unknown state as concrete counts; preserve unknown for all three fields here just as the clean report does.
            "target_branch": cleanup["target_branch"],
            "remote_merge_target": cleanup["remote_merge_target"],
            "remote_merge_target_available": cleanup["remote_merge_target_available"],
  • Files reviewed: 23/23 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 11, 2026 13:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Final review comments identify unresolved implementation and specification issues.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (11)

Previously missed (1) — in code that hasn't changed since the last review.

project:503

  • gh pr list applies its default result limit before this code filters by headRefOid. A branch with more than the default number of historical PRs can therefore have a merged exact-head PR omitted and be incorrectly reported as not-merged. Use explicit pagination or an appropriate --limit for the exact-head lookup.

openspec/changes/add-doctor-repository-health/design.md:23

  • This non-goal is no longer true: attach_repository_health() calls cleanup_report(), which invokes github_merge_evidence(), and doctor exposes that state. Scope the non-goal to no fetch/mutation or remove the pull-request clause so the design matches the implementation.
- Add a `cleanup` command alias or change `project clean` command semantics.
- Fetch remote refs, determine pull-request state, mutate Git state, or make
  a repository-health warning an ordinary doctor error.

openspec/changes/allow-disposable-ignored-cache-cleanup/proposal.md:31

  • This change also modifies the active cleanup preservation contract: the existing review-safety spec says ignored files are preservation blockers, while this proposal permits a Python-cache allowlist to be deleted during remove. Declaring Modified Capabilities as None leaves those requirements contradictory; reconcile the existing capability with this exception.
### Modified Capabilities

None. The active cleanup change records are not archived baseline
specifications; this change defines the additional disposable-artifact
contract separately.

openspec/changes/auto-delete-merged-branches/proposal.md:30

  • This change changes the existing project-clean contract: the active cleanup spec still requires worktree removal to leave branch deletion as a separate explicit action, while this proposal makes paired branch deletion part of remove. Declaring Modified Capabilities as None leaves two active normative behaviors for the same command; update or explicitly supersede the existing capability.
### Modified Capabilities

None. The existing cleanup change has not been archived into baseline specs;
this change records the additional branch-retirement contract separately.

openspec/changes/auto-delete-merged-branches/proposal.md:16

  • This proposal wording is now inaccurate because the same pull request intentionally permits removal of worktrees whose only ignored artifacts are on the disposable Python-cache allowlist. Replace the blanket “ignored” refusal with “blocking ignored artifacts” so the governed change records agree with the implemented contract.
- Preserve the read-only default, the explicit single-branch deletion action
  for orphaned branches, and every existing refusal for dirty, ignored,
  detached, unmerged, current, or default-branch work.

openspec/changes/auto-delete-merged-branches/specs/project-clean-branch-retirement/spec.md:24

  • With the disposable-cache change in this same pull request, “ignored” is too broad here: a worktree containing only the allowlisted non-symlink __pycache__/.pyc/.pyo artifacts is intentionally removable and its branch is retired. Qualify this as blocking ignored files so the branch-retirement contract does not contradict the disposable-artifact contract.
MUST preserve the branch when the worktree is dirty, ignored, detached,
current, default, unmerged, or cannot be verified as merged.

project:533

  • remote_merge_target is derived only from a currently present worktree checked out on the target branch. If the primary worktree is on a feature branch, or the target has no upstream even though a GitHub remote is configured, the later remote ancestry and exact-head PR evidence are reported unavailable. Resolve branch.<target>.remote/merge independently and select the GitHub repository separately so diagnostic evidence is not lost.
    target_source = next((row for row in state["worktrees"]
                          if row.get("present") and row.get("branch") == target), None)
    remote_merge_target = target_source.get("upstream") if target_source else None
    remote_target_ref = remote_tracking_ref(root, remote_merge_target)

project:516

  • Selecting the highest-numbered matching PR before checking its state can report not-merged when an older exact-head match is merged but a newer matching row is open or closed. The exact-head contract is satisfied by any merged matching PR, so prefer the highest-numbered merged match before falling back to the newest non-merged match.
    item = max(matching, key=lambda value: value.get("number", 0) if isinstance(value.get("number"), int) else 0)
    return {"state": "merged" if item.get("state") == "MERGED" else "not-merged",

project:1193

  • When ignored-file inspection fails, these fields are None, but this rendering turns ignored into None and both path lists into zero counts. That contradicts the warning/JSON unknown state and can falsely reassure a human operator about an uninspectable worktree; preserve unknown as print_clean_report does.
                          f"dirty={row.get('dirty', 'unknown')}; ignored={row.get('ignored_files', 'unknown')}; "
                          f"disposable={len(row.get('disposable_ignored_paths') or [])}; "
                          f"blocking={len(row.get('blocking_ignored_paths') or [])}; "
                          f"{delta}; merged-remote={remote_merged}; github-merge={github_merged}")

project:869

  • The two Git commands are built from command_root before confirmation, but the post-confirmation check only compares the selected feature row. It never revalidates the target-branch worktree/path that supplies -C; if that checkout is removed or replaced while confirmation is pending, cleanup can fail from a stale path or run against the wrong checkout instead of the surviving target worktree. Include the command-root identity in the revalidated state or derive it again after revalidation.
        commands = [["git", "-C", str(command_root), "worktree", "remove", str(wanted)],
                    ["git", "-C", str(command_root), "branch", "-d", row["branch"]]]

project:759

  • The report classifier accepts caches and bytecode files under arbitrary contained directories (for example src/__pycache__), but this revalidation rejects every parent whose name is not __pycache__. Those paths are therefore advertised as disposable and then cleanup aborts after confirmation. Validate each parent as a contained non-symlink directory without restricting its name.
                    if (stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode) or
                            part not in DISPOSABLE_IGNORED_DIRECTORY_NAMES):
                        raise Refused("Disposable cache state changed after confirmation; no command was run.")
  • Files reviewed: 23/23 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread project
Comment on lines +744 to +748
for path in paths:
candidate = None
opened = []
try:
candidate = disposable_ignored_artifact(root, path)
@sonarqubecloud

sonarqubecloud Bot commented Oct 7, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
18.5% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@brettheap

Copy link
Copy Markdown
Contributor Author

CLOSED — lane openRepoProject-2, session 297bd1b9-d664-4905-bda4-178840dbfdb1@Eagle, 2026-10-07T10:15:38Z, unmerged

Decision

Closed unmerged on Brett Heap's word ("go with your recommendation", 2026-10-07). The cleanup branch stays on origin as the harvest source for the extensions below. Nothing is deleted.

Why

  • The project-maintenance design packet (branch docs/project-maintenance-design, ideation/brainstorm/) targets origin/main at a040790 and keeps branch deletion, cache disposal and remote queries out of the MVP as separately governed extensions. Three of this PR's four governed changes are exactly those extensions, and the batch-cleanup design names this branch's commits by SHA as work the MVP must not depend on.
  • auto-delete-merged-branches changes the governed behaviour of the remove action (main's project-clean spec: a removed worktree keeps its branch unless deletion is separately requested) while declaring "Modified Capabilities: None". It needs to be a MODIFIED requirement on project-clean.
  • Six Copilot review threads are open and live at head: doctor --strict health-warning coverage; remote merge target resolved only from a checked-out target worktree; remote-only merge evidence bypassed when the feature's upstream is gone; doctor rendering unknown inspection state as zero counts; the doctor design's non-goals denying the GitHub lookup the code performs; cache deletion revalidating per path rather than before the first unlink, contrary to its own spec.
  • Head bb91a49 (Copilot-authored) has no CI result: the tests workflow is held at "action required". The eight preceding commits passed.

Harvest plan

Commits Governed change Lands when
acf0133, 80fdef3 add-doctor-repository-health Absorbed into the packet's project-overview design as local-only, read-only reporting.
1789ad9, bb91a49 allow-disposable-ignored-cache-cleanup A cache-disposal extension proposal. bb91a49's O_NOFOLLOW/dir_fd deletes already match the packet's stated requirement; resolve the whole-list prevalidation thread first.
09af8c8 clarify-remote-merge-status A remote-queries extension proposal; resolve the upstream-gone and target-worktree threads first.
5fc2b51 auto-delete-merged-branches A paired-retirement extension proposal, written as a MODIFIED requirement on project-clean.

Per the batch-cleanup design ("Deferred cache and paired-retirement extension"), each extension proposal updates the cleanup specification and adds its failure and recovery contract before any of these commits is cherry-picked.

Claims

The three CLAIMED comments on this PR by lane cleanup (doctor health, disposable cache removal, remote merge status) are superseded by this close. That lane has no register row and no object log.

@brettheap brettheap closed this Oct 7, 2026
brettheap added a commit that referenced this pull request Oct 7, 2026
Apply the second review round to the four-document brainstorm packet and
re-align the overview, synthesis and handoff with the feature documents:

- Probe directory rule: worktree-specific probes run in the worktree's own
  index (`git -C <worktree path>`), repository-wide probes at the canonical
  root; without it the hidden-local-state probe read the main index.
- Caps follow the removal floor: a removal child is spawned only with at
  least `removal_floor_seconds` (5 s) of the work deadline left, so the
  batch target cap is 16, not 24 (128 worktree rows unchanged); the
  overview's listing phase is an estimate counted against the deadline,
  with a 5 s bound per root, and the break-even and single-repository
  figures move with it.
- Submodules: any gitlink, or an admin `modules` directory, excludes a
  worktree as `contains-submodule` from the same bounded `ls-files` probe.
- One path-escaping form in both documents (`\xHH` bytes, `\uXXXX` code
  points, lowercase hex); the packet carries no raw bidirectional control
  character.
- Merge target: strip `refs/remotes/origin/` from the `origin/HEAD` symref;
  manifest revalidation compares against the plan-time value.
- Rewritten scenarios whose expectations the documents' own rules made
  impossible ("Repository replaced mid-batch", "Gated merged worktrees");
  explicit error-row fields; `{"error", "code"}` exit-2 JSON; `doctor`'s Git
  refusal; the overview's fifth gate also withholds `--all-safe` above the
  batch row cap.
- Handoff resolution record updated with the round-2 result and the cap
  decision; baseline notes record origin/main at ca4c615 (PR #5, OpenSpec
  only) and the closure of PR #2 (`cleanup`, retained on origin) with the
  follow-ups its decision record names.

Design only: no code, tests, OpenSpec or Speckit artifacts. Packet
validator passes; review rounds 1 and 2 resolved for every high and medium
finding; targeted re-verification recorded in the PR.

Lane: openRepoProject-3
Co-Authored-By: Claude Fable 5.1 <[email protected]>
brettheap added a commit that referenced this pull request Oct 7, 2026
…only) (#7)

Design documents only: extends the four-document brainstorm packet under
ideation/brainstorm/ for project overview and project clean --all-safe and
resolves the five pre-PR review findings recorded in the handoff
next-session-project-maintenance-fix-handoff.md. No code, tests, OpenSpec
proposal or Speckit artifacts. Baseline a040790; origin/main ca4c615 noted;
PR #2 closure noted. Governing issue #6.

Lane: openRepoProject-3
Co-Authored-By: Claude Fable 5.1 <[email protected]>
brettheap pushed a commit that referenced this pull request Oct 19, 2026
Follow-up 7 applies the packet-side items of three fidelity reviews,
of draft PRs #26 (874d1ad), #27 (3c08613 to 9ebe9f0) and #29
(c8a9f30), and section D of verification 9, to packet revision 1 at
382b3b9. It records what the ratified changes and the drafts say and
redesigns nothing.

- The packet overview's extension points now name paired branch
  retirement, which change 1's OQ-27 makes a change of its own.
- The deferred remote boundary records that change 1, ratified since,
  keeps 15 s for children other than Git, so its 5 s per request is
  open; draft PR #29 puts that to Brett Heap as its second open
  question.
- The cache and paired-retirement deferrals in Batch cleanup, the
  remote boundary in Overview and attention, and the handoff's
  paired-retirement and remote process text now name drafts PR #27,
  PR #26 and PR #29, each pending.
- The six present-tense baseline sentences ("is now 7a9134b", "has
  since") are dated as past ("became", "had since"), as section D of
  verification 9 asked, since main has moved on to e9d6711.

The other review items are declined: each is design for the drafts'
author, or the packet already matches the ratified text, the PR #2
decision record or revision 1's own record. Design record only; the
packet validator passes, the JSON fixtures and plan digests are
unchanged, and the D-A and D-B text stays verbatim.

Lane: openRepoProject-3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

3 participants