Skip to content

fix: fetch origin before creating worktree to prevent stale branches#488

Open
lukeinglis wants to merge 3 commits into
mainfrom
fix/fetch-before-worktree
Open

fix: fetch origin before creating worktree to prevent stale branches#488
lukeinglis wants to merge 3 commits into
mainfrom
fix/fetch-before-worktree

Conversation

@lukeinglis

Copy link
Copy Markdown
Collaborator

Summary

  • create_worktree() now runs git fetch origin <base_branch> before creating the worktree, branching from origin/<base_branch> instead of the (possibly stale) local branch
  • Falls back gracefully to the local branch for repos without a remote
  • Logs a warning with the commit delta when the local branch is behind origin

Problem

When a PR is merged to origin/main but the user hasn't pulled locally, the factory creates a worktree from the stale local main. The CEO then researches outdated code, distills an improvement spec, and proposes re-doing work that was already completed in the merged PR. The failure mode is silent and expensive: the entire research/distill/strategy cycle is wasted.

Closes #487

Test plan

  • 26/26 worktree tests pass (5 new)
  • TestFetchAndResolveBase: verifies origin/main is returned when behind, when up-to-date, and that local branch is returned when there's no remote
  • TestCreateWorktreeWithRemote: end-to-end test confirming the worktree contains commits from origin that the local branch doesn't have
  • ruff check and mypy clean

create_worktree() previously branched from the local base branch, which
could be behind origin after a PR merge. This caused the CEO to research
stale code and propose duplicating already-completed work.

Now fetches origin/<base_branch> before creating the worktree. Falls back
to the local branch for repos without a remote. Logs a warning with the
commit delta when the local branch is behind.

Closes #487

Signed-off-by: Luke Inglis <lukeinglis21@yahoo.com>
@codecov

codecov Bot commented Jun 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.97%. Comparing base (8097461) to head (9cae271).
⚠️ Report is 83 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #488      +/-   ##
==========================================
- Coverage   87.31%   86.97%   -0.34%     
==========================================
  Files          61       64       +3     
  Lines        9339     9956     +617     
==========================================
+ Hits         8154     8659     +505     
- Misses       1185     1297     +112     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Prevents the factory from hanging when the remote is unreachable but not
immediately refusing connections. Falls back to the local branch on
timeout, same as when there is no remote.

Signed-off-by: Luke Inglis <lukeinglis21@yahoo.com>
Move the git author/committer env dict to a single module-level GIT_ENV
constant and use it in all four fixtures that were defining it inline.

Signed-off-by: Luke Inglis <lukeinglis21@yahoo.com>
@xukai92

xukai92 commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

@ceo-review

@github-actions github-actions 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.

✅ Factory Review: KEEP

Verdict: KEEP
Reason: Solves stale branch problem — fetch before worktree creation prevents wasted research cycles. Tests comprehensive (27/27 pass, 6 new). Minor edge case identified (should validate remote ref exists) — recommended 3-line fix but not blocking.

Guard Checks

Check Result
correctness ✅ PASS
security ✅ PASS
edge_cases ❌ PASS_WITH_REC
tests ✅ PASS
style ✅ PASS
scope ✅ PASS

Posted by Factory CEO

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown

Detailed Review Findings

Edge Case Identified

Location: factory/worktree.py:48-50 (in _fetch_and_resolve_base())

Issue: Missing validation that the remote ref exists before returning it.

Scenario:

# Local repo has a 'develop' branch, remote does not
git fetch origin develop  # succeeds (returncode 0) but fetches nothing
git rev-parse origin/develop  # fails (returncode 128)
# But _fetch_and_resolve_base() returns "origin/develop" regardless

Impact: If fetch succeeds but origin/<base_branch> doesn't exist, the code returns the ref anyway, causing git worktree add to fail with a confusing error instead of gracefully falling back to the local branch.

Recommended Fix (3 lines):

# After line 40, before logging worktree_fetch_ok:
if remote_rev.returncode != 0:
    log.warning("worktree_fetch_skipped", reason="remote_ref_missing", base=base_branch)
    return base_branch

Severity: Minor — unlikely in practice (requires a branch to exist locally but not on the remote). Worst case is a clear git error, not silent failure.


Test Count Note

PR description says "26/26 worktree tests pass (5 new)" but actual count is 27/27 tests pass (6 new tests added). This is just documentation drift — the tests themselves are excellent.


What Works Well

Solves the core problem — Prevents wasted research cycles when origin/main is ahead of local main
Comprehensive test coverage — 6 new tests cover: remote ahead, up-to-date, no remote, timeout, end-to-end verification
Graceful degradation — Falls back to local branch for repos without remotes, fetch failures, and timeouts
Proper timeout handling — 30s timeout prevents hangs on slow networks
Good observability — Structured logging at all decision points (worktree_fetch_skipped, worktree_local_behind, worktree_fetch_ok)
No security issues — Branch name is passed as subprocess argument, not shell-interpolated
Follows factory style — snake_case, docstrings, structured logging, proper type hints


Recommendation: The PR is merge-worthy as-is. The edge case identified is minor and self-evident when it occurs. Adding the 3-line validation check would improve robustness, but is not a hard blocker.

@osilkin98 osilkin98 added kind:fix Something was wrong stage:execution Running agents: runners, dispatch, workspace plumbing labels Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:fix Something was wrong stage:execution Running agents: runners, dispatch, workspace plumbing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Worktree created from stale local branch, not origin

3 participants