Skip to content

fix(integration): OR over local + upstream for integration detection - #2507

Merged
max-sixty merged 2 commits into
mainfrom
bug
Apr 30, 2026
Merged

max-sixty merged 2 commits into
mainfrom
bug

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Summary

Repository::integration_reason picked a single target via effective_integration_target and checked only that, silently dropping half of history in the diverged case. After wt merge updates local main (while it's still diverged from origin/main), the upstream-only check would report the just-merged branch as unmerged and skip removal. The symmetric hole existed in wt remove: a branch merged into local main on a diverged main was misreported.

Behavior change

integration_reason(branch, target) now considers both local and upstream:

  • No upstream / same commit: check local only.
  • Local strictly behind upstream: check upstream (superset).
  • Upstream strictly behind local: check local (superset).
  • Diverged: check local, then upstream — integrated if either matches.

The local/upstream ancestor checks run git directly with ref names (merge-base --is-ancestor) rather than going through cached is_ancestor/rev_parse_commit. The local target may have just been updated mid-command (e.g. wt merge's ref update), so cached SHAs would be stale.

effective_integration_target stays as a display helper for wt list's status column — the docstring is updated to make clear it's not for safety-critical checks.

Test plan

Two new regression tests cover the symmetric cases:

  • test_merge_removes_branch_when_local_main_diverged_from_upstream — wt merge after the user's reported scenario (remote-only commit + local-only commit on main create divergence). Verified failing without the fix; passing with it.
  • test_remove_merged_locally_when_upstream_diverged — wt remove for a branch merged into local main while origin/main has diverged. Verified failing without the fix; passing with it.

One existing snapshot (merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge) was capturing the buggy Branch unmerged output for an in-process scenario where the SHA cache went stale across the merge ref-update; updated to the correct integration message.

All 3405 tests pass; all lints clean.

This was written by Claude Code on behalf of @max-sixty

`Repository::integration_reason` picked a single target via
`effective_integration_target` and checked only that, which silently dropped
half of history in the diverged case. After `wt merge` updates local main
(while it's still diverged from `origin/main`), the upstream-only check would
report the just-merged branch as unmerged and skip removal. The symmetric
hole exists in `wt remove`: a branch merged into local main on a diverged
main was misreported.

Behavior now:
- No upstream / same commit: check local only.
- Local strictly behind upstream: check upstream (superset).
- Upstream strictly behind local: check local (superset).
- Diverged: check local, then upstream — integrated if either matches.

The local/upstream ancestor checks run git directly with ref names
(`merge-base --is-ancestor`) rather than going through the cached
`is_ancestor`/`rev_parse_commit`. The local target may have just been updated
mid-command (e.g. `wt merge`'s ref update), so cached SHAs would be stale.

`effective_integration_target` is retained as a display helper for `wt list`'s
status column, with the docstring updated to make clear it's not for
safety-critical checks.

One snapshot (`merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge`)
was capturing the buggy `Branch unmerged` output and is updated to the
correct integration message.

Co-Authored-By: Claude <[email protected]>
worktrunk-bot
worktrunk-bot previously approved these changes Apr 30, 2026

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

codecov/patch is failing at 94.11% (target 96.76%) — 2 of 34 new lines uncovered. Cross-referencing the cobertura report from the code-coverage job, the two zero-hit lines are closing braces:

  • Line 651 (} closing if check_local { … }): line 650 (the inner } for the nested if let Some(reason)) reports 122 hits, but line 651 reports 0 — even though execution flows through it on every fall-through. The mirror brace at line 658 reports 121 hits, so this is asymmetric per-brace artifact behavior, not a code-path gap.
  • Line 657 (} closing the inner if let Some(reason) = check_integration(&signals) in the upstream block): same shape.

Every other new line shows triple-digit hits — the function is exercised, including all three diverged-case match arms. The misses appear to be llvm-cov line-coverage artifacts on closing braces (LLVM's debug-info line table doesn't always credit closing braces with their own instruction), not real coverage gaps that more tests could fix.

Per CLAUDE.md the policy is to ask before merging past a codecov/patch failure. Dismissing my approval to surface the gate. If you read this the same way (false positive), happy to re-approve; if you'd rather dodge the artifact, collapsing the inner if let Some(reason) { return … } into a let-chain (if check_local && let Some(reason) = …) tends to fold both braces away.

@worktrunk-bot
worktrunk-bot dismissed their stale review April 30, 2026 23:12

codecov/patch failed — flagging for human verdict on whether the closing-brace miss is a tooling artifact

…age artifact

llvm-cov's line table doesn't credit some closing braces with their own
instruction, leaving the inner `if let` braces at L651 / L657 with 0 hits
even though every adjacent line shows 121-122. Folding the inner check into
a let-chain removes the asymmetric brace and keeps codecov/patch above the
project target.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit 5a12324 into main Apr 30, 2026
26 of 27 checks passed
@max-sixty
max-sixty deleted the bug branch April 30, 2026 23:26
max-sixty added a commit that referenced this pull request May 1, 2026
## Summary

- `wt list`'s integration column now agrees with the safety path (`wt
remove` / `wt merge`) in the local/upstream-diverged case introduced by
#2507. A branch merged into local `main` while `origin/main` has unique
commits no longer renders as unintegrated.
- New `Repository::integration_targets()` returns a `(primary, optional
secondary)` pair that mirrors `compute_integration_reason_uncached`'s
preamble: a single ref for same-commit / strict-subset cases, both refs
only when local and upstream have diverged.
- Each integration task (`IsAncestor`, `CommittedTreesMatch`,
`HasFileChanges`, `WouldMergeAdd`) combines signals across the pair — OR
for positive signals (ancestor, trees match, patch-id), AND for inverted
ones — and short-circuits when the primary alone proves integration, so
the common one-sided case stays one git op.
- `effective_integration_target` is still used by the `step prune` path;
it's the column that needed the OR semantics.

## Test plan
- [x] New regression test
`test_list_integrated_when_merged_locally_with_upstream_diverged`
mirrors `test_remove_merged_locally_when_upstream_diverged`. Verified to
fail without the fix (renders `main_state == "behind"`) and pass with
it.
- [x] Symmetric
`test_list_integrated_when_squash_merged_on_remote_with_local_diverged`
covers the merged-on-remote direction.
- [x] `cargo run -- hook pre-merge --yes` — 3407/3407 pass, no snapshots
to review.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <[email protected]>
max-sixty added a commit that referenced this pull request May 1, 2026
…2515)

## Summary

`wt step prune` was the lone remaining caller of
`Repository::effective_integration_target` — a "pick one ref" helper
whose own docstring warned it was unsafe for safety-critical checks. In
the diverged case it returned `origin/main`, then handed it to
`integration_reason`, which couldn't resolve an upstream of an
already-remote ref and ended up checking only that single side. Branches
merged into local `main` while `origin/main` had unique commits never
got pruned — the same diverged-case false negative #2513 fixed for `wt
list` and #2507 fixed for `wt remove` / `wt merge`.

This change passes the local default branch directly to
`integration_reason`, letting it OR over local + upstream internally
like `wt remove` and `wt merge` already do. The actual deletion gate
inside `prepare_worktree_removal` was already correct, so this just
stops the outer filter from silently dropping legitimately-integrated
candidates.

`effective_integration_target`, `integration_target`, and their
`RepoCache` fields are now dead and deleted.

## Test plan
- [x] New regression `test_prune_locally_merged_when_upstream_diverged`
(mirrors `test_remove_merged_locally_when_upstream_diverged`). Verified
to fail on the pre-fix code path with `No merged worktrees to remove`,
passes on the fix.
- [x] Symmetric `test_prune_squash_merged_on_remote_when_local_diverged`
covers the merged-on-remote direction; pins forward-compatibility.
- [x] `cargo run -- hook pre-merge --yes` — 3411/3411 pass, no snapshots
to review.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty pushed a commit that referenced this pull request May 1, 2026
… flakes (#2523)

## Problem

[Run
25196909437](https://github.com/max-sixty/worktrunk/actions/runs/25196909437)
(tend-review on PR #2512, "Add Codex support") burned ~116 minutes /
$6.90 because the bot:

1. Approved the PR
2. Saw `test (windows)` fail on `test_prune_json_orphan_branch` —
explicitly identified as a `step_prune` test "unrelated to this PR"
3. **Dismissed its own approval anyway** (dismissal message:
*"Dismissing — `test (windows)` failed on
`test_prune_json_orphan_branch`... Will retry once it completes; if the
rerun is green, this is a flake and the PR is fine."*)
4. Tried `POST /repos/.../actions/jobs/<id>/rerun` → HTTP 403 *"The
workflow run containing this job is already running"*
5. Wrote a background script that polled for ~90 minutes waiting for the
non-required `benchmarks` job to clear so it could call `gh run rerun
--failed`

The dismissal-on-flake pattern is structural: given (approved review +
clearly-unrelated test failure), the bot reasoned its way into "must
rerun → must dismiss approval first → must wait for `benchmarks`." This
contradicts the spirit of `CLAUDE.md`'s existing *"Don't wait for CI
`benchmarks` before merging"* note, which only covered the merge path.

This is distinct from the codecov dismissal pattern (PRs #2521, #2516,
#2512, #2507) — those are correct per `CLAUDE.md`'s *"NEVER merge a PR
with failing `codecov/patch` without explicit user approval"* and aren't
touched here.

## Change

Adds a `## PR Review: Don't Self-Dismiss Over Unrelated Test Flakes`
section to `.claude/skills/running-tend/SKILL.md` (~22 lines)
explaining:

- Leave approval in place for unrelated flakes; post a comment instead
- GitHub blocks both `--failed` and per-job rerun while *any* job in the
workflow is `in_progress`
- `benchmarks` routinely runs 80+ min, so the wait cascades wastefully
- The codecov-dismiss pattern is unchanged

## Gates

- **Evidence**: 1 occurrence (this run); structural failure with
explicit reasoning chain → 1 occurrence is sufficient per
`review-gates.md`
- **Magnitude**: Targeted fix, ~22 lines added to a 231-line skill

Co-authored-by: worktrunk-bot <[email protected]>
max-sixty added a commit that referenced this pull request May 2, 2026
…class (#2528)

## Summary

Replaces the ambient ref-keyed caches in `RepoCache` with an explicit,
point-in-time `RefSnapshot` value threaded through read paths. This
closes the bug class behind PR #2507 (post-`update-ref` integration
check seeing pre-write SHAs) — and several latent variants — by making
the caches that could go stale unrepresentable.

## Why

`RepoCache` cached ref-name → SHA in `commit_shas: DashMap<String,
String>`, plus composite caches keyed off it (`integration_reasons`,
`effective_integration_targets`, `ahead_behind`, `integration_target`
OnceCell, `tree_shas`, `resolved_refs`). When wt itself moved a ref
mid-command — most prominently `wt merge` running `git update-ref
refs/heads/<target>` to advance the local target — those caches went
stale, and any downstream read returned pre-write SHAs.

PR #2507 patched one symptom by adding `ref_is_ancestor` (a cache-bypass
helper) at the integration-check call site. That works locally; every
other ref-name read after a write was a latent bug.

The structural fix: there is no longer an ambient ref-name → SHA cache.
Callers explicitly capture a `RefSnapshot` at known points and thread it
through the read paths. After ref-mutating operations, callers capture a
fresh snapshot — the discipline lives at the small set of write
boundaries (currently one site, `finish_after_merge`), not at every
ref-name accessor.

Background analysis: `docs/dev/cache-staleness.md` (commit ba8b239)
walks through six options and the trade-offs.

## What changed

- **New `src/git/repository/ref_snapshot.rs`** — `RefSnapshot` value
type. One `for-each-ref` over local + remote refs, optional ahead/behind
batch. Cloned by value, no `OnceCell`/`Arc`. ~330 lines including unit
tests (the freshness contract test mutates a ref and re-captures).
- **Two-tier API** — `_by_sha` siblings of cached methods
(`is_ancestor_by_sha`, `merge_base_by_sha`, `branch_diff_stats_by_sha`,
`ahead_behind_by_sha`, `has_added_changes_by_sha`, `trees_match_by_sha`,
`merge_integration_probe_by_sha`, …). The persistent on-disk `sha_cache`
(already SHA-keyed) sits behind these.
- **Snapshot-taking integration path** — `compute_integration_lazy`,
`integration_reason`, `compute_integration_reason_uncached`,
`integration_targets`, `delete_branch_if_safe`,
`remove_worktree_with_cleanup` all take `&RefSnapshot`.
- **Post-write fresh-snapshot pattern** — `wt merge`'s
`finish_after_merge` captures a *fresh* snapshot AFTER
`handle_no_ff_merge`/`handle_push` runs `update-ref`. This is the
structural fix for PR #2507. The `ref_is_ancestor` workaround is
deleted.
- **`wt list` migration** — pre-skeleton phase captures one snapshot;
`TaskContext` carries it; tasks call `_by_sha` siblings via the
snapshot. No regression intended (one extra `for-each-ref` upfront, lose
per-task `rev-parse` fallbacks).
- **Cache deletions** — `commit_shas`, `tree_shas`,
`effective_integration_targets`, `integration_reasons`, `ahead_behind`,
`integration_target` OnceCell, `resolved_refs` all gone from
`RepoCache`. `LocalBranchInventory`'s priming side-effects (writes to
`commit_shas`/`resolved_refs`) removed.
- **Uncached primitives** — `rev_parse_commit`, `rev_parse_tree`,
`resolve_preferring_branch` no longer cache; consumers that need
SHA-stable lookups thread a `RefSnapshot`.
- **Persistent caches retained** — on-disk `sha_cache::*` and the
in-memory `merge_base` / `branch_diff_stats` caches keep their SHA-keyed
contract.

## Snapshot test deltas

Three `list_*_with_nonexistent_default_branch.snap` snapshots no longer
show the same-commit `_` symbol when the configured default branch is
missing — that was a false positive (no ref to compare against).
`list_warns_when_commit_details_batch_fails.snap` now embeds the
resolved SHA in the error rather than the literal `"main"` ref name
(strict improvement — the SHA is what was passed to git).

## Regression coverage

- PR #2507's regression test
(`test_remove_merged_locally_when_upstream_diverged`) passes without
`ref_is_ancestor`.
- PR #2513's
`test_list_integrated_when_merged_locally_with_upstream_diverged`
passes.
- New unit test: `RefSnapshot` capture-mutate-recapture confirms two
captures observe distinct SHAs after `update-ref`.

## Out of scope (deferred)

Both flagged by `/reviewing-code` and explicitly deferred:

- `prepare_worktree_removal` re-captures a snapshot per candidate inside
`step_prune` — N+1 `for-each-ref` calls. Threading an optional
`&RefSnapshot` would make `step_prune` reuse its entry snapshot. Affects
display consistency in unusual hook setups (a `post-remove` hook that
runs `git fetch` between candidates can desync the displayed integration
target from the safety decision); not a safety bug.
- `head_shas` cache retained. Different staleness model (per-worktree,
mutated by `commit`/`reset` rather than `update-ref`); design doc lists
it as a remaining vector. Out of scope for this PR's integration-target
focus.

## Test plan

- [x] `cargo run -- hook pre-merge --yes` (3413 tests pass before the
merge of `origin/main`)
- [x] 1071 lib + 607 bin + 1588 integration tests pass after merging
`origin/main`
- [x] `cargo check --all-targets` clean
- [ ] CI green

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@max-sixty max-sixty mentioned this pull request May 3, 2026
max-sixty added a commit that referenced this pull request May 3, 2026
Cuts v0.47.0. Highlights:

- **Integration detection fix** across `wt list`, `wt remove`, `wt
merge`, `wt step prune` for the local/upstream-diverged case (#2507,
#2513, #2515).
- **Faster shell-command dispatch** (~10ms per invocation, 1.49× on
trivial aliases) via event-driven signal forwarding (#2537, #2538), plus
parallel config load (#2543) and merged cold-start prewarm rev-parse
(#2541).
- **`wt switch <number>` suggests `pr:N` / `mr:N`** instead of just
`--create` (#2516).
- **Library API breaking changes**: `RefSnapshot` cutover (#2528, #2530)
and the `for-each` direct-exec change (#2465). Full list in
`CHANGELOG.md`.

See `CHANGELOG.md` for the complete entry.

> _This was written by Claude Code on behalf of @max-sixty_

---------

Co-authored-by: Claude <[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.

2 participants