Skip to content

fix(host-service): stop workspace↔PR/diff state drifting from GitHub - #5455

Merged
Kitenite merged 5 commits into
mainfrom
fix-workspace-gh-sync
Jul 5, 2026
Merged

Kitenite merged 5 commits into
mainfrom
fix-workspace-gh-sync

Conversation

@Kitenite

@Kitenite Kitenite commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

Problem

Users report their workspace's main-branch tracking and PR link drifting from GitHub state — a branch that shows 146 files changed vs main, and a PR that never connects — most often on macOS's case-insensitive filesystem. Three distinct causes, all in the v2 host-service path:

Root causes & fixes

1. PR↔branch matching was case-sensitive on the branch. upstreamKey/headKey lowercased owner/repo but kept the branch verbatim, so a local roshvan/mcp-1525-… never matched a PR head Roshvan/mcp-1525-…, and every sync actively re-wrote pullRequestId = null. Now the branch is compared case-insensitively. Because GitHub's head= REST filter is itself case-sensitive server-side (verified against this repo), a per-head lookup for a drifted branch returns nothing — so a shallow open-PR sweep (one page, no checks/statuses, once per repo per 60s TTL, only when a per-head lookup missed) fills the gap and matches case-insensitively. A sweep failure marks keys failed so existing links are kept, never cleared.

2. Workspace creation could mint a case-twin branch. On a case-insensitive filesystem git rev-parse refs/heads/foo happily resolves the refs/heads/Foo file, so resolveRef's exact-case probe couldn't distinguish an exact match from case drift — and git worktree add -b would create a second branch sharing the existing one's loose-ref file (the mechanism that corrupts HEAD underneath the workspace). resolveRef now enumerates real refnames via for-each-ref: exact matches keep prior precedence (local > remote > tag); a case-insensitive match adopts the existing branch's canonical casing, which planBranchSource/create propagate.

3. The Changes panel never fetched its base ref. It diffs origin/<base>...HEAD (3-dot merge-base), but nothing in the status path fetched origin/<base> — so after a rebase onto a newer upstream, every replayed upstream commit was counted as a workspace change, ballooning the file count. getGitStatusSnapshot now schedules a fire-and-forget fetch of the base's remote branch (keyed by the repo common-dir, TTL'd, in-flight-deduped); GitWatcher picks up the ref change and re-queries.

Verification

  • Unit + integration tests, each mutation-checked (revert the fix → test fails).
  • End-to-end against real on-disk repos: resolveRef adopts canonical casing for local/remote/origin/-prefixed drift; diff balloons 4→heals to 1 file after the background fetch.
  • Live-GitHub: exact-head finds the PR, drifted-head misses server-side, the sweep matches it, a bogus branch stays unmatched.
  • Via CDP against the running host-service: getStatus balloon (4 files) → heal (1 file), background fetch fires (FETCH_HEAD + origin/main sha advance confirmed independently), TTL dedup holds on rapid calls.

Notes / prior art

🤖 Generated with Claude Code


Open in Stage

Summary by cubic

Fixes workspace↔GitHub drift that caused inflated file counts and PR links not attaching. Keeps branch casing and base refs accurate so diffs and links stay correct.

  • Bug Fixes
    • PR linking: keep upstreamKey and per-head cache keys case-sensitive to isolate case-variant branches; add a shallow state=open sweep (once per repo per TTL, only when a head lookup misses) that matches case-insensitively to recover drifted branches; cache failures for the TTL and preserve existing links if the sweep fails; tests now use a real, migrated in-memory SQLite DB to verify case-variant isolation across bypass and cached paths.
    • Branch ref resolution: enumerate branches via for-each-ref and adopt canonical casing; prevent case-twin creation on case-insensitive filesystems; propagate the canonical name during workspace creation; surface real for-each-ref failures instead of degrading to “no branches.”
    • Base-ref freshness: background-fetch the base remote branch during status (TTL, in-flight dedup keyed by repo common-dir, resolve common dir per call, never rejects) so origin/<base>...HEAD diffs don’t balloon after a rebase.

Written for commit 2f71991. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Workspace and branch reuse now adopts canonical casing from existing local or remote-tracking refs.
    • Added a repo-wide open-PR sweep fallback to recover missed PR lookups when branch names differ only by letter case.
    • Introduced TTL-based background refresh for remote-tracking base refs to keep comparisons up to date.
  • Bug Fixes

    • Improved Git ref resolution and PR linking for case-drifted branches/tags, including correct “no matches” vs real failures.
    • If the open-PR sweep fails transiently, existing workspace↔PR links are preserved (not cleared).
    • Prevented PR cross-linking between case-variant branch names.
  • Tests

    • Added/expanded regression coverage for these case-handling behaviors.

Three related causes made a workspace's main-branch tracking and PR link
drift from GitHub state (e.g. "146 files changed" and a PR that never
connects), especially on macOS's case-insensitive filesystem.

1. Case-insensitive PR↔branch matching. `upstreamKey`/`headKey` kept the
   branch component case-sensitive, so a local branch `roshvan/x` never
   matched a PR head `Roshvan/x` and every sync re-cleared pullRequestId.
   Lowercase the branch in the match key + cache key. GitHub's `head=`
   filter is itself case-sensitive server-side, so add a shallow open-PR
   sweep (once per repo per TTL, only when a per-head lookup missed) and
   match it case-insensitively. A sweep failure keeps existing links
   rather than clearing them.

2. Canonical branch-casing adoption in resolveRef. On a case-insensitive
   filesystem `git rev-parse refs/heads/foo` resolves the `refs/heads/Foo`
   file, so the old exact-case probe couldn't tell an exact match from case
   drift and workspace creation would mint a case-twin that shares the
   existing branch's loose-ref file. Enumerate real refnames via
   for-each-ref: exact matches keep prior precedence (local > remote >
   tag); a case-insensitive match adopts the existing branch's canonical
   casing. planBranchSource/create propagate that name.

3. TTL background fetch of the base ref. The Changes panel diffs
   `origin/<base>...HEAD` but nothing fetched the base, so a rebase onto a
   newer upstream counted every upstream commit as a workspace change.
   Schedule a fire-and-forget fetch of the base's remote branch (keyed by
   the repo common-dir, TTL'd, in-flight-deduped); GitWatcher picks up the
   ref change and re-queries.

Verified: unit + integration tests (mutation-checked), end-to-end against
real on-disk repos, live-GitHub sweep matching, and via CDP against the
running host-service (balloon 4→heal 1 files; base fetch fires; TTL dedup
holds).
@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR updates git ref resolution, pull request lookup, and base-branch freshness handling to preserve canonical casing and refresh remote-tracking base refs in the background.

Changes

Integrated git and pull-request flow

Layer / File(s) Summary
Ref enumeration and matching
packages/host-service/src/runtime/git/refs.ts, packages/host-service/src/runtime/git/refs.test.ts, packages/host-service/src/trpc/router/workspaces/workspaces.ts
Branch resolution enumerates existing refs, applies exact and case-insensitive matching, updates tests and mock ref listing behavior, and reuses canonical casing in workspace branch planning.
GitHub open-PR query helpers
packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts, packages/host-service/src/runtime/pull-requests/utils/github-query/index.ts, packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts, packages/host-service/src/runtime/pull-requests/pull-requests.ts, packages/host-service/src/runtime/pull-requests/pull-requests.test.ts
Repo-wide open PR fetch helpers are added for gh and Octokit, the head-key comment is clarified, the new helpers are re-exported, and pull-request refresh logic uses a cached open-PR sweep with tests.
Base ref fetch target and freshness
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts, packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts, packages/host-service/src/trpc/router/git/utils/git-helpers.ts, packages/host-service/src/trpc/router/git/utils/git-helpers.integration.test.ts, packages/host-service/src/trpc/router/git/utils/git-status.ts, packages/host-service/src/trpc/router/git/v2-diff-surfaces.integration.test.ts
Base comparison now returns a fetch target, git status schedules a background fetch for it, and the new helper throttles and deduplicates remote-tracking ref refreshes with tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main host-service fix for workspace, PR, and diff drift.
Description check ✅ Passed The description is detailed and covers the problem, fixes, and verification, though it doesn't follow the exact template headings.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-workspace-gh-sync

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ghost

ghost commented Jul 5, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 6 individual chapters for you:

Title
1 Adopt canonical branch casing in Git resolution
2 Propagate canonical casing during workspace creation
3 Add open-PR sweep for case-insensitive matching
4 Integrate PR sweep and fix state drifting
5 Implement background base-ref fetching
6 Wire base-ref fetch into Git status
Open in Stage

Chapters generated by Stage for commit 2f71991 on Jul 5, 2026 8:14am UTC.

@greptile-apps

greptile-apps Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes three distinct causes of workspace↔PR/diff state drift in the v2 host-service: case-sensitive branch matching in upstreamKey/headKey, a case-twin branch hazard during workspace creation on case-insensitive filesystems, and a stale base-ref causing the Changes panel to balloon after a rebase.

  • Case-sensitive branch matching (pull-requests.ts, github-query.ts): upstreamKey and headKey now lowercase the branch component so a local roshvan/fix-thing correctly matches a PR head Roshvan/fix-thing; a shallow open-PR sweep (100 PRs, state=open, once per repo per 60 s TTL) fills the gap when GitHub's server-side head= filter returns nothing for the drifted casing.
  • Case-twin branch hazard (refs.ts, workspaces.ts): resolveRef now enumerates branch names via git for-each-ref instead of probing with rev-parse, giving authoritative casing on case-insensitive filesystems; planBranchSource and workspace creation propagate resolved.shortName (canonical casing) so -b never mints a case-twin sharing an existing loose-ref file.
  • Stale base-ref / ballooning diff (base-ref-freshness.ts, git-status.ts): getGitStatusSnapshot now schedules a fire-and-forget fetch of the base's remote-tracking branch (TTL'd per repo common-dir, in-flight-deduped); GitWatcher picks up the ref update and re-triggers status queries.

Confidence Score: 4/5

Safe to merge; the three bug fixes are well-scoped and each has mutation-tested coverage. The new background-fetch module introduces unbounded module-level Maps, but the risk is limited to a stale TTL key if a workspace path is reused across lifetimes — an uncommon scenario that causes a delayed heal, not data corruption.

All three fix paths are covered by unit/integration tests that are verified to fail without the fix. The open-PR sweep is deliberately narrow (one page, no checks) to avoid the prior 504 regression, and sweep failures preserve existing links rather than clearing them. The only material concern is in the new base-ref-freshness.ts module: its three module-level Maps are never evicted, so in rare cases where a workspace path is reused for a different git repository within the same process lifetime, commonDirByWorktree returns a stale value and TTL deduplication groups fetches under the wrong key.

packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts — the module-level cache Maps warrant a follow-up eviction strategy, especially the commonDirByWorktree entry which is keyed on a filesystem path that could be reused

Important Files Changed

Filename Overview
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts New fire-and-forget module that schedules periodic background fetches of the base remote-tracking ref; uses module-level Maps for TTL/in-flight dedup that are never evicted, creating a potential stale-state bug if a worktree path is reused across workspace lifecycles
packages/host-service/src/runtime/git/refs.ts Replaces per-ref rev-parse probes with for-each-ref enumeration to get authoritative casing; adds a case-insensitive fallback tier that adopts existing canonical branch names; logic and precedence (local > remote > tag, exact > case-insensitive) look correct
packages/host-service/src/runtime/pull-requests/pull-requests.ts Adds an open-PR sweep fallback for case-drifted branches; upstreamKey now lowercases branches for consistent case-insensitive matching; sweep is limited to one page (100 PRs sorted by recently updated) which is an intentional trade-off for repos with many PRs; extracted cachedGitHubFetch helper removes duplication cleanly
packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts Adds fetchOpenPullRequestsFromGh and fetchOpenPullRequests for the shallow open-PR sweep; headKey now lowercases branches for case-insensitive client-side filtering in normalizePullRequestCandidates; both Octokit and gh paths are consistent
packages/host-service/src/trpc/router/git/utils/git-helpers.ts Extends resolveBaseComparison return type with fetchTarget to propagate the remote/branch coordinates needed for the background fetch; the remote === '.' local-tracking case correctly sets fetchTarget: null
packages/host-service/src/trpc/router/git/utils/git-status.ts Calls scheduleBaseRefFetch when base.fetchTarget is set; the fire-and-forget call is correctly placed before the parallel git awaits so it does not block the status snapshot
packages/host-service/src/trpc/router/workspaces/workspaces.ts Propagates canonical branch casing from planBranchSource back to resolvedBranch and fixes planBranchSource to return resolved.shortName instead of the typed input; downstream prefix logic correctly uses the updated resolvedBranch

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant WS as Workspace (local branch: roshvan/fix-thing)
    participant PRRM as PullRequestRuntimeManager
    participant GH as GitHub API
    participant Sweep as Open-PR Sweep Cache

    PRRM->>GH: "GET /pulls?head=owner:roshvan/fix-thing"
    GH-->>PRRM: [] (case-sensitive filter returns nothing)
    Note over PRRM: key not in latestByKey → unmatchedKeys

    PRRM->>Sweep: getCachedOpenPullRequests(repo)
    Sweep->>GH: "GET /pulls?state=open&sort=updated&per_page=100"
    GH-->>Sweep: "[PR#77 head=Roshvan/fix-thing]"
    Sweep-->>PRRM: "[PR#77]"

    Note over PRRM: upstreamKey lowercases branch<br/>→ roshvan/fix-thing matches Roshvan/fix-thing
    PRRM->>PRRM: "latestByKey.set(key, PR#77)"
    PRRM->>GH: "fetch checks + reviews for PR#77"
    GH-->>PRRM: checks/reviews
    PRRM->>WS: "workspace.pullRequestId = PR#77.id"
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant WS as Workspace (local branch: roshvan/fix-thing)
    participant PRRM as PullRequestRuntimeManager
    participant GH as GitHub API
    participant Sweep as Open-PR Sweep Cache

    PRRM->>GH: "GET /pulls?head=owner:roshvan/fix-thing"
    GH-->>PRRM: [] (case-sensitive filter returns nothing)
    Note over PRRM: key not in latestByKey → unmatchedKeys

    PRRM->>Sweep: getCachedOpenPullRequests(repo)
    Sweep->>GH: "GET /pulls?state=open&sort=updated&per_page=100"
    GH-->>Sweep: "[PR#77 head=Roshvan/fix-thing]"
    Sweep-->>PRRM: "[PR#77]"

    Note over PRRM: upstreamKey lowercases branch<br/>→ roshvan/fix-thing matches Roshvan/fix-thing
    PRRM->>PRRM: "latestByKey.set(key, PR#77)"
    PRRM->>GH: "fetch checks + reviews for PR#77"
    GH-->>PRRM: checks/reviews
    PRRM->>WS: "workspace.pullRequestId = PR#77.id"
Loading
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts:19-21
**Module-level maps grow without bound across workspace lifecycles**

`commonDirByWorktree`, `lastFetchStartedAt`, and `inFlightFetches` are never evicted. In a long-running host-service this is a minor memory leak, but the correctness risk is more specific: if a workspace at a path (e.g. `/workspaces/abc`) is destroyed and a new workspace for a *different* git repository is later created at the exact same filesystem path, `resolveCommonDir` will return the stale `commonDir` from the old repo without issuing a fresh `rev-parse`. The resulting key `${stalePath}#remote/branch` would then suppress fetches for the new repo that actually need to run, silently extending the drift window past the 5-minute TTL.

### Issue 2 of 2
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts:23-33
**Concurrent first-callers for the same path both issue `rev-parse --git-common-dir`**

`resolveCommonDir` checks the cache synchronously, but two concurrent async callers that arrive before the cache is populated will both fall through to `git.raw(["rev-parse", "--git-common-dir"])`. Because JS is single-threaded the writes to `commonDirByWorktree` are idempotent (same value) and no double-fetch results, but the double `rev-parse` call is wasteful. A simple in-flight map for the resolve itself (similar to `inFlightFetches`) would avoid the duplicate git call. Not a correctness bug, but an easy optimisation to add if this path is hot.

Reviews (1): Last reviewed commit: "fix(host-service): stop workspace↔PR/dif..." | Re-trigger Greptile

Comment on lines +19 to +21
const commonDirByWorktree = new Map<string, string>();
const lastFetchStartedAt = new Map<string, number>();
const inFlightFetches = new Map<string, Promise<void>>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Module-level maps grow without bound across workspace lifecycles

commonDirByWorktree, lastFetchStartedAt, and inFlightFetches are never evicted. In a long-running host-service this is a minor memory leak, but the correctness risk is more specific: if a workspace at a path (e.g. /workspaces/abc) is destroyed and a new workspace for a different git repository is later created at the exact same filesystem path, resolveCommonDir will return the stale commonDir from the old repo without issuing a fresh rev-parse. The resulting key ${stalePath}#remote/branch would then suppress fetches for the new repo that actually need to run, silently extending the drift window past the 5-minute TTL.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts
Line: 19-21

Comment:
**Module-level maps grow without bound across workspace lifecycles**

`commonDirByWorktree`, `lastFetchStartedAt`, and `inFlightFetches` are never evicted. In a long-running host-service this is a minor memory leak, but the correctness risk is more specific: if a workspace at a path (e.g. `/workspaces/abc`) is destroyed and a new workspace for a *different* git repository is later created at the exact same filesystem path, `resolveCommonDir` will return the stale `commonDir` from the old repo without issuing a fresh `rev-parse`. The resulting key `${stalePath}#remote/branch` would then suppress fetches for the new repo that actually need to run, silently extending the drift window past the 5-minute TTL.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +23 to +33
async function resolveCommonDir(
git: SimpleGit,
worktreePath: string,
): Promise<string> {
const cached = commonDirByWorktree.get(worktreePath);
if (cached) return cached;
// `--git-common-dir` may print a path relative to the worktree root.
const raw = (await git.raw(["rev-parse", "--git-common-dir"])).trim();
const commonDir = resolve(worktreePath, raw);
commonDirByWorktree.set(worktreePath, commonDir);
return commonDir;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Concurrent first-callers for the same path both issue rev-parse --git-common-dir

resolveCommonDir checks the cache synchronously, but two concurrent async callers that arrive before the cache is populated will both fall through to git.raw(["rev-parse", "--git-common-dir"]). Because JS is single-threaded the writes to commonDirByWorktree are idempotent (same value) and no double-fetch results, but the double rev-parse call is wasteful. A simple in-flight map for the resolve itself (similar to inFlightFetches) would avoid the duplicate git call. Not a correctness bug, but an easy optimisation to add if this path is hot.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts
Line: 23-33

Comment:
**Concurrent first-callers for the same path both issue `rev-parse --git-common-dir`**

`resolveCommonDir` checks the cache synchronously, but two concurrent async callers that arrive before the cache is populated will both fall through to `git.raw(["rev-parse", "--git-common-dir"])`. Because JS is single-threaded the writes to `commonDirByWorktree` are idempotent (same value) and no double-fetch results, but the double `rev-parse` call is wasteful. A simple in-flight map for the resolve itself (similar to `inFlightFetches`) would avoid the duplicate git call. Not a correctness bug, but an easy optimisation to add if this path is hot.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/host-service/src/runtime/pull-requests/pull-requests.ts (1)

180-191: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Duplicate case-insensitive key logic across files.

upstreamKey here duplicates the exact same lowercasing/concatenation logic as headKey in github-query.ts (line 111-121). Both must stay in lockstep for the case-insensitive matching to work correctly end-to-end (per-head lookup normalization, sweep matching, and the nodeKey === key verification at lines 996-1001/1030-1034 all rely on consistent key semantics). If one gets tweaked later (e.g. trimming whitespace) without the other, matching silently breaks.

Consider extracting a single shared buildMatchKey(owner, repo, branch) helper (e.g. in types.ts or a small shared module) used by both files.

♻️ Suggested extraction
+// shared, e.g. in github-query/types.ts or a new key.ts
+export function buildMatchKey(
+	owner: string | null | undefined,
+	repo: string | null | undefined,
+	branch: string,
+): string | null {
+	if (!owner || !repo) return null;
+	return `${owner.toLowerCase()}/${repo.toLowerCase()}#${branch.toLowerCase()}`;
+}

Then replace both headKey (github-query.ts) and upstreamKey (pull-requests.ts) with calls to this shared helper.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/runtime/pull-requests/pull-requests.ts` around
lines 180 - 191, The case-insensitive key-building logic is duplicated between
upstreamKey and headKey, so they can drift and break matching semantics. Extract
a shared buildMatchKey(owner, repo, branch) helper in a common module and have
both pull-requests.ts::upstreamKey and github-query.ts::headKey call it, keeping
the normalization/concatenation behavior identical everywhere the key is
compared or verified.
🧹 Nitpick comments (1)
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts (1)

17-76: 🩺 Stability & Availability | 🔵 Trivial

Consider adding unit tests for the TTL/dedup logic.

The concurrency-sensitive parts here (in-flight dedup, TTL gating, failures consuming the TTL window) aren't covered by tests in this cohort. This logic is easy to regress silently (e.g., an accidental await reordering could reintroduce a double-fetch race). Worth adding tests for: TTL window skipping, in-flight dedup, and that fetch failures still set lastFetchStartedAt.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts` around
lines 17 - 76, Add unit tests around scheduleBaseRefFetch and resolveCommonDir
to cover the concurrency/TTL behavior that can regress silently. Verify that
repeated calls within BASE_REF_FETCH_TTL_MS skip a new fetch, that concurrent
calls dedupe via inFlightFetches for the same commonDir#remote/branch key, and
that a failed git.fetch still updates lastFetchStartedAt so the TTL window is
consumed. Use the existing symbols scheduleBaseRefFetch, resolveCommonDir,
lastFetchStartedAt, inFlightFetches, and commonDirByWorktree to locate the
logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/host-service/src/runtime/git/refs.ts`:
- Around line 55-89: The broad catch in listBranchShortNames is masking
unexpected git failures and returning empty branch lists, which can make
resolveRef silently miss existing refs. Update the error handling around git.raw
in listBranchShortNames to only treat the unborn/empty-repo case as expected,
and distinguish that from real failures by logging or surfacing unexpected
errors instead of swallowing them. Keep the local and remoteTracking parsing
logic intact, but ensure the fallback to empty arrays is limited to the no-refs
case.
- Around line 179-182: Tag detection in resolveRef is still relying on refExists
for refs/tags/${trimmed}, which can match a differently-cased loose ref on
case-insensitive filesystems and misclassify branches as tags. Update the tag
lookup in resolveRef to enumerate actual tags (or otherwise perform an
exact-only tag match) before returning kind: "tag", and ensure the branch
fallback in planBranchSource is still reachable when no exact tag exists.

---

Outside diff comments:
In `@packages/host-service/src/runtime/pull-requests/pull-requests.ts`:
- Around line 180-191: The case-insensitive key-building logic is duplicated
between upstreamKey and headKey, so they can drift and break matching semantics.
Extract a shared buildMatchKey(owner, repo, branch) helper in a common module
and have both pull-requests.ts::upstreamKey and github-query.ts::headKey call
it, keeping the normalization/concatenation behavior identical everywhere the
key is compared or verified.

---

Nitpick comments:
In `@packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts`:
- Around line 17-76: Add unit tests around scheduleBaseRefFetch and
resolveCommonDir to cover the concurrency/TTL behavior that can regress
silently. Verify that repeated calls within BASE_REF_FETCH_TTL_MS skip a new
fetch, that concurrent calls dedupe via inFlightFetches for the same
commonDir#remote/branch key, and that a failed git.fetch still updates
lastFetchStartedAt so the TTL window is consumed. Use the existing symbols
scheduleBaseRefFetch, resolveCommonDir, lastFetchStartedAt, inFlightFetches, and
commonDirByWorktree to locate the logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 912d9233-f59c-4823-874a-258d18ce40a3

📥 Commits

Reviewing files that changed from the base of the PR and between 21cd480 and 08840ca.

📒 Files selected for processing (13)
  • packages/host-service/src/runtime/git/refs.test.ts
  • packages/host-service/src/runtime/git/refs.ts
  • packages/host-service/src/runtime/pull-requests/pull-requests.test.ts
  • packages/host-service/src/runtime/pull-requests/pull-requests.ts
  • packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts
  • packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts
  • packages/host-service/src/runtime/pull-requests/utils/github-query/index.ts
  • packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts
  • packages/host-service/src/trpc/router/git/utils/git-helpers.integration.test.ts
  • packages/host-service/src/trpc/router/git/utils/git-helpers.ts
  • packages/host-service/src/trpc/router/git/utils/git-status.ts
  • packages/host-service/src/trpc/router/git/v2-diff-surfaces.integration.test.ts
  • packages/host-service/src/trpc/router/workspaces/workspaces.ts

Comment on lines 179 to 182
const tagRef: `refs/tags/${string}` = `refs/tags/${trimmed}`;
if (await refExists(git, tagRef)) {
return { kind: "tag", fullRef: tagRef, shortName: trimmed };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does git rev-parse --verify on a loose tag ref resolve case-insensitively on a case-insensitive filesystem (e.g. macOS APFS)?

💡 Result:

Yes, git rev-parse --verify can resolve loose refs (such as tags) case-insensitively when running on a case-insensitive filesystem like macOS APFS [1][2][3]. This occurs because Git's ref resolution mechanism relies on the underlying filesystem to locate loose ref files [1][2][3]. On case-insensitive filesystems, the operating system treats files with different casing as the same file, allowing Git to inadvertently "find" a ref even if the provided name does not match the actual casing of the file on disk [1][2][3]. This behavior is not a deliberate feature of Git's revision parsing logic, but rather an artifact of the interaction between Git's storage architecture and the filesystem [1][2]. Key technical consequences include: 1. Ambiguity and Misresolution: In complex scenarios—most notably with linked worktrees—this can lead to critical errors [2][4]. For example, if a user attempts to resolve a ref like "head" (lowercase) on a case-insensitive system, it may inadvertently resolve to the wrong ref (such as the main worktree's HEAD instead of a linked worktree's specific HEAD) because the OS successfully opens the file path for the main HEAD [2][4]. 2. Inconsistency: While Git generally treats refs as case-sensitive internally, the reliance on the filesystem for loose refs means that operations may behave differently depending on whether the ref is loose (on disk) or packed (in the packed-refs file) [1][2]. Packed-refs typically require exact, case-sensitive matching because Git performs the search against the contents of the packed-refs file rather than the filesystem [1][2]. 3. Recommended Practice: Because of these risks, it is widely recommended to avoid creating refs that differ only by case and to always use the exact casing (e.g., "HEAD" rather than "head") when referencing them [1][5][3]. Note that while some specific commands like git tag --list allow for explicit case-insensitive sorting or filtering [6][7], this is an application-level feature and distinct from the filesystem-induced behavior observed during general ref resolution [1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the relevant symbols and surrounding code.
rg -n "refExists|listBranchShortNames|planBranchSource|refs/tags|refs/heads" packages/host-service/src/runtime/git/refs.ts packages/host-service/src/runtime/git/workspaces.ts

echo
echo "---- refs.ts outline ----"
ast-grep outline packages/host-service/src/runtime/git/refs.ts --view expanded

echo
echo "---- workspaces.ts outline ----"
ast-grep outline packages/host-service/src/runtime/git/workspaces.ts --view expanded

Repository: superset-sh/superset

Length of output: 1820


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the specific implementations around the tag/branch probes.
sed -n '1,260p' packages/host-service/src/runtime/git/refs.ts
echo
sed -n '280,360p' packages/host-service/src/runtime/git/workspaces.ts

Repository: superset-sh/superset

Length of output: 7671


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the call site and tag handling paths in the current tree.
rg -n "BAD_REQUEST|kind: \"tag\"|resolveRef\\(|resolveBranch|resolve.*Ref|checkout" packages -g '*.ts' -g '*.tsx'

echo
echo "---- files mentioning resolveRef ----"
rg -n "resolveRef\\(" packages -g '*.ts' -g '*.tsx'

Repository: superset-sh/superset

Length of output: 27650


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the workspace call site and the ref tests for tag/branch edge cases.
sed -n '290,345p' packages/host-service/src/trpc/router/workspaces/workspaces.ts
echo
sed -n '1,240p' packages/host-service/src/runtime/git/refs.test.ts

Repository: superset-sh/superset

Length of output: 9015


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check whether tag enumeration is already used anywhere else and whether refs.md documents tags.
rg -n "for-each-ref|refs/tags/|tag" packages/host-service/src/runtime/git packages/host-service/src/trpc/router/workspaces -g '*.ts' -g '*.md'

Repository: superset-sh/superset

Length of output: 2484


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '290,345p' packages/host-service/src/trpc/router/workspaces/workspaces.ts
echo
sed -n '1,240p' packages/host-service/src/runtime/git/refs.test.ts

Repository: superset-sh/superset

Length of output: 9015


Tag lookup should avoid loose-ref probing

refExists(git, tagRef) can still resolve a differently-cased loose tag on case-insensitive filesystems, so resolveRef may classify a branch as kind: "tag" and hit the BAD_REQUEST path in planBranchSource before the branch fallback runs. Enumerate tags too, or document that tag lookup is intentionally exact-only.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/runtime/git/refs.ts` around lines 179 - 182, Tag
detection in resolveRef is still relying on refExists for refs/tags/${trimmed},
which can match a differently-cased loose ref on case-insensitive filesystems
and misclassify branches as tags. Update the tag lookup in resolveRef to
enumerate actual tags (or otherwise perform an exact-only tag match) before
returning kind: "tag", and ensure the branch fallback in planBranchSource is
still reachable when no exact tag exists.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

5 issues found across 13 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts">

<violation number="1" location="packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts:27">
P3: Unlike the fetch path which deduplicates via `inFlightFetches`, `resolveCommonDir` has no in-flight dedup — two concurrent first-time callers for the same `worktreePath` both issue `rev-parse --git-common-dir` before the cache is populated. Consider reusing the same in-flight-map pattern used below to avoid redundant git spawns if this path is hot.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Client
    participant WS as Workspace Router
    participant GS as GitStatus
    participant BF as BaseRefFetch
    participant GW as GitWatcher
    participant PRM as PullRequestRuntimeManager
    participant GH as GitHub API
    participant Git as Git (SimpleGit)
    participant Ref as ResolveRef

    Note over Client,Ref: **Status & Base‑Ref Fetch Flow** (new background fetch)

    Client->>WS: getStatus(worktreePath)
    WS->>GS: getGitStatusSnapshot()
    GS->>Git: resolveBaseComparison()
    Git-->>GS: { baseRef, fetchTarget }
    GS->>BF: CHANGED: scheduleBaseRefFetch(remote, branch)
    Note over BF: Fire‑and‑forget, TTL 5min, in‑flight deduped
    BF->>BF: Resolve commonDir (cached)
    BF->>Git: fetch <remote> <branch> --quiet --no-tags
    Git-->>BF: FETCH_HEAD updated
    BF-->>GW: Ref change detected
    GW->>GS: Re‑trigger status query

    GS->>Git: diff <baseRef>...HEAD
    Git-->>GS: Correct file count (no balloon)
    GS-->>WS: status snapshot
    WS-->>Client: status result

    Note over Client,Ref: **PR Linking Flow** (case‑insensitive matching + open‑PR sweep)

    WS->>PRM: refreshPullRequestsByWorkspaces(wsIds)
    loop For each workspace
        PRM->>GH: fetchPullRequestByHead(head=owner:branch)
        Note over PRM,GH: upstreamKey() now lowercases branch too
        alt Head lookup succeeds
            GH-->>PRM: PR node
            PRM->>PRM: Update pullRequestId
        else Head returns nothing (drifted branch)
            PRM->>GH: NEW: fetchOpenPullRequests(state=open, sorted by updated)
            Note over PRM,GH: Shallow sweep, no checks/statuses, TTL 1 min per repo
            alt Sweep succeeds
                GH-->>PRM: Open PR list
                PRM->>PRM: Match case‑insensitively via upstreamKey
                PRM->>PRM: Update pullRequestId
            else Sweep fails (transient error)
                PRM->>PRM: mark unmatched keys as failed → keep existing links
            end
        end
    end

    Note over Client,Ref: **Branch Resolution** (adopts canonical casing)

    WS->>Ref: resolveRef(inputBranch)
    Ref->>Git: CHANGED: for‑each‑ref (enumerates true refnames)
    Git-->>Ref: local + remote branch names
    alt Exact match in local branches
        Ref-->>WS: local ref with original shortName
    else Exact match in remote branches
        Ref-->>WS: remote‑tracking ref with original shortName
    else Case‑insensitive match in local branches
        Ref-->>WS: local ref *adopting canonical shortName*
    else Case‑insensitive match in remote branches
        Ref-->>WS: remote‑tracking ref *adopting canonical shortName*
    else Tag match
        Ref-->>WS: tag ref
    end
    WS->>WS: planBranchSource uses resolved.shortName (no case‑twin created)
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

git: SimpleGit,
worktreePath: string,
): Promise<string> {
const cached = commonDirByWorktree.get(worktreePath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: Unlike the fetch path which deduplicates via inFlightFetches, resolveCommonDir has no in-flight dedup — two concurrent first-time callers for the same worktreePath both issue rev-parse --git-common-dir before the cache is populated. Consider reusing the same in-flight-map pattern used below to avoid redundant git spawns if this path is hot.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts, line 27:

<comment>Unlike the fetch path which deduplicates via `inFlightFetches`, `resolveCommonDir` has no in-flight dedup — two concurrent first-time callers for the same `worktreePath` both issue `rev-parse --git-common-dir` before the cache is populated. Consider reusing the same in-flight-map pattern used below to avoid redundant git spawns if this path is hot.</comment>

<file context>
@@ -0,0 +1,76 @@
+	git: SimpleGit,
+	worktreePath: string,
+): Promise<string> {
+	const cached = commonDirByWorktree.get(worktreePath);
+	if (cached) return cached;
+	// `--git-common-dir` may print a path relative to the worktree root.
</file context>

…edges

Address PR review:

- upstreamKey and the per-head cache key are case-sensitive again. On a
  case-sensitive host, `feature` and `Feature` are distinct branches with
  distinct PRs; lowercasing the canonical identity/dedup key collapsed them
  and could mis-link a workspace or return the wrong PR from cache.
  Case-drift tolerance now lives only in the open-PR sweep fallback, keyed
  by a lowercased copy so latestByKey/link-assignment stay exact.
- github-query headKey is exact again (per-head filtering); drift recovery
  is the runtime sweep's job.
- base-ref-freshness: drop the unbounded worktreePath→commonDir cache;
  resolve fresh each call (a reused path could otherwise key the fetch
  dedup off a stale repo's common dir). scheduleBaseRefFetch returns its
  (never-rejecting) promise so it's awaitable in tests. Add unit tests.
- resolveRef: a real for-each-ref failure now propagates (logged) instead
  of silently degrading to "no branches", which would let a case-twin be
  created. Only caller is workspace creation, where loud failure is right.
@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@github-actions

github-actions Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) ✅ View Branch
Vercel API (Vercel) ✅ Open Preview
Vercel Web (Vercel) ✅ Open Preview
Vercel Marketing (Vercel) ✅ Open Preview
Vercel Admin (Vercel) ✅ Open Preview
Vercel Docs (Vercel) ✅ Open Preview

Preview updates automatically with new commits

@Kitenite

Kitenite commented Jul 5, 2026

Copy link
Copy Markdown
Member Author

Thanks for the reviews — addressed in 64f6fc6. Summary of each finding:

Fixed (valid):

  • cubic P1 — upstreamKey collapses case-variant branches (pull-requests.ts:190). Correct and the most important catch. On a case-sensitive host, feature/Feature are distinct branches with distinct PRs; lowercasing the canonical identity key could mis-link a workspace. Reverted upstreamKey to case-sensitive and moved case-drift tolerance into the open-PR sweep fallback only (keyed by a lowercased copy, so latestByKey/link-assignment stay exact).
  • cubic P2 — per-head cache key cross-branch poisoning (pull-requests.ts:908). Same root cause. Reverted the cache key to preserve branch case.
  • cubic/greptile — unbounded commonDirByWorktree + stale-on-path-reuse (base-ref-freshness.ts). Removed the path→commonDir cache entirely; it's now resolved fresh each call (rev-parse --git-common-dir is a near-instant local call, dwarfed by the fetch it precedes). That deletes the only unbounded map and the staleness footgun.
  • cubic/CodeRabbit — bare catch {} in resolveRef (refs.ts:85/89). A real for-each-ref failure now logs and propagates instead of degrading to "no branches" (which would let a case-twin be created). for-each-ref exits 0 with empty output on an empty repo, so this only fires on genuine failures; the sole caller is workspace creation, where loud failure is the right outcome.

Declined (with reasoning):

  • cubic P3 / greptile — no in-flight dedup on resolveCommonDir. Moot after removing the cache: every call resolves fresh by design, and a dedicated in-flight map for one cheap local rev-parse isn't worth the machinery.
  • CodeRabbit — tag lookup is case-insensitive on APFS (refs.ts:182). True (tags still use rev-parse), but far less harmful than the branch case — it only affects the "that's a tag, not a branch" rejection message, never branch creation. Left as-is to keep scope tight; can follow up if desired.

Also added a base-ref-freshness unit suite and a resolveRef for-each-ref-failure test. All host-service tests, typecheck, and lint green.

One thing I did not add: a two-workspace regression test for the P1 collision — the PR-manager test harness is currently single-workspace. The exact-upstreamKey design + the per-head exactness test guard it, but a multi-workspace harness test would be a stronger lock if reviewers want it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts (1)

35-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a TTL-expiry test.

Current coverage only verifies dedup within the TTL window. Nothing asserts that a fetch retriggers once BASE_REF_FETCH_TTL_MS has elapsed, which is the other half of the < boundary in the throttling check. Mocking Date.now() (not a real timer) would cover this without violating the repo's no-real-timers test convention.

🧪 Example addition
+	test("retries after the TTL window elapses", async () => {
+		const { git, fetchCalls } = createGit();
+		const target = { remote: "origin", branch: "expired-branch" };
+		const originalNow = Date.now;
+		let now = originalNow();
+		Date.now = () => now;
+		try {
+			await scheduleBaseRefFetch(git, "/repo/wt-expired", target);
+			now += BASE_REF_FETCH_TTL_MS + 1;
+			await scheduleBaseRefFetch(git, "/repo/wt-expired", target);
+		} finally {
+			Date.now = originalNow;
+		}
+		expect(fetchCalls).toHaveLength(2);
+	});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts`
around lines 35 - 42, Add a TTL-expiry test in the base ref freshness suite to
cover the other side of the throttle boundary. Extend the existing
scheduleBaseRefFetch coverage in base-ref-freshness.test.ts by mocking
Date.now() so you can advance time past BASE_REF_FETCH_TTL_MS, then call
scheduleBaseRefFetch again for the same repo/target and assert fetchCalls
increments after expiry. Keep using the existing createGit,
scheduleBaseRefFetch, and fetchCalls helpers so the new test stays consistent
with the current dedupe test.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts`:
- Around line 35-42: Add a TTL-expiry test in the base ref freshness suite to
cover the other side of the throttle boundary. Extend the existing
scheduleBaseRefFetch coverage in base-ref-freshness.test.ts by mocking
Date.now() so you can advance time past BASE_REF_FETCH_TTL_MS, then call
scheduleBaseRefFetch again for the same repo/target and assert fetchCalls
increments after expiry. Keep using the existing createGit,
scheduleBaseRefFetch, and fetchCalls helpers so the new test stays consistent
with the current dedupe test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a0f00d58-e92f-46db-abe3-594f09bbd6ae

📥 Commits

Reviewing files that changed from the base of the PR and between 08840ca and 64f6fc6.

📒 Files selected for processing (7)
  • packages/host-service/src/runtime/git/refs.test.ts
  • packages/host-service/src/runtime/git/refs.ts
  • packages/host-service/src/runtime/pull-requests/pull-requests.ts
  • packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.ts
  • packages/host-service/src/runtime/pull-requests/utils/github-query/github-query.ts
  • packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts
  • packages/host-service/src/trpc/router/git/utils/base-ref-freshness.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/host-service/src/runtime/git/refs.test.ts
  • packages/host-service/src/runtime/git/refs.ts

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 issue found across 7 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/host-service/src/runtime/pull-requests/pull-requests.ts">

<violation number="1" location="packages/host-service/src/runtime/pull-requests/pull-requests.ts:1047">
P2: Workspaces with a case-drifted branch can be linked to the wrong PR when the repo has two open case-variant branch names. The fallback index collapses all case variants and keeps the first result; consider detecting duplicate lowercased keys and preserving the existing link instead of assigning an arbitrary PR.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

if (!nodeKey) continue;
const lower = nodeKey.toLowerCase();
// Sweep is sorted by updated desc; first hit per key wins.
if (!openByLowerKey.has(lower)) openByLowerKey.set(lower, node);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2: Workspaces with a case-drifted branch can be linked to the wrong PR when the repo has two open case-variant branch names. The fallback index collapses all case variants and keeps the first result; consider detecting duplicate lowercased keys and preserving the existing link instead of assigning an arbitrary PR.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/runtime/pull-requests/pull-requests.ts, line 1047:

<comment>Workspaces with a case-drifted branch can be linked to the wrong PR when the repo has two open case-variant branch names. The fallback index collapses all case variants and keeps the first result; consider detecting duplicate lowercased keys and preserving the existing link instead of assigning an arbitrary PR.</comment>

<file context>
@@ -1025,18 +1030,24 @@ export class PullRequestRuntimeManager {
+					const lower = nodeKey.toLowerCase();
 					// Sweep is sorted by updated desc; first hit per key wins.
-					if (nodeKey && !openByKey.has(nodeKey)) openByKey.set(nodeKey, node);
+					if (!openByLowerKey.has(lower)) openByLowerKey.set(lower, node);
 				}
 				for (const key of unmatchedKeys) {
</file context>

…ase-isolation

The single-workspace fake DB couldn't express two workspaces at once, so the
case-variant collision bugs (distinct `feature`/`Feature` branches collapsing
onto one PR identity) were untestable — and every existing test asserted only
the positive "drift should link" direction, never the "distinct variants must
not cross-link" invariant. That gap is exactly where the review-found bugs lived.

Add a real, migrated, in-memory SQLite harness and two invariant tests:
- bypass path isolates the identity key (`upstreamKey`)
- non-bypass path exercises the per-head cache key

Both are mutation-verified: reverting `upstreamKey` to lowercased fails the
bypass test; reverting only the cache key fails only the cache test.
@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

Delete the hand-faked DB and migrate all tests onto the real, migrated,
in-memory SQLite harness introduced for the case-variant suite. The fake
ignored query predicates and held a single workspace — the exact blind spot
that let the case-collision bugs through — so removing it leaves one faithful
harness that exercises real drizzle predicates and wiring.

Line-count is roughly flat (seed+query replaces inline state mutation), but
there's now one mental model instead of two, and no footgun fake. All
mutation checks still hold: reverting upstreamKey, the cache key, or the
fallback lowering each fails its corresponding test.
@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/host-service/src/runtime/pull-requests/pull-requests.test.ts (1)

180-186: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid blanket async console.warn suppression.

This hides any unexpected warning emitted during the callback. Filter expected pull-request-runtime warnings and fail/pass through unexpected ones instead.

Suggested refactor
 async function withSilencedWarnings<T>(fn: () => Promise<T>): Promise<T> {
 	const original = console.warn;
-	console.warn = () => {};
+	const unexpected: Parameters<typeof console.warn>[] = [];
+	console.warn = (...args: Parameters<typeof console.warn>) => {
+		if (
+			typeof args[0] === "string" &&
+			args[0].startsWith("[host-service:pull-request-runtime]")
+		) {
+			return;
+		}
+		unexpected.push(args);
+		original(...args);
+	};
 	try {
-		return await fn();
+		const result = await fn();
+		if (unexpected.length > 0) {
+			throw new Error(`Unexpected console.warn call(s): ${unexpected.length}`);
+		}
+		return result;
 	} finally {
 		console.warn = original;
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/runtime/pull-requests/pull-requests.test.ts` around
lines 180 - 186, The helper withSilencedWarnings currently suppresses every
console.warn inside the callback, which can hide unexpected warnings. Update
withSilencedWarnings in pull-requests.test.ts to only ignore the known
pull-request-runtime warnings you expect, and let any other warning message pass
through or fail the test. Keep the filtering logic localized in that helper so
the pull-requests test cases still silence only the intended warnings.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/host-service/src/runtime/pull-requests/pull-requests.test.ts`:
- Around line 180-186: The helper withSilencedWarnings currently suppresses
every console.warn inside the callback, which can hide unexpected warnings.
Update withSilencedWarnings in pull-requests.test.ts to only ignore the known
pull-request-runtime warnings you expect, and let any other warning message pass
through or fail the test. Keep the filtering logic localized in that helper so
the pull-requests test cases still silence only the intended warnings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 975b9cc1-8b01-4903-935b-97f73f6ab260

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6db86 and 270a958.

📒 Files selected for processing (1)
  • packages/host-service/src/runtime/pull-requests/pull-requests.test.ts

Compress the verbose "why" comments added across the case-sensitivity and
base-ref-fetch changes to their load-bearing intent — no behavior change.
The reasoning (identity keys stay case-sensitive; enumerate refs instead of
probing; base ref refreshed in the background) is preserved, just terser.
@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@Kitenite
Kitenite merged commit b98580d into main Jul 5, 2026
16 checks passed

This branch was previously deployed

1 inactive deployment
preview — 2f719919 Deployed Jul 5, 2026 by Kitenite via Deploy API #6190
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.

1 participant