Repository navigation
fix(host-service): stop workspace↔PR/diff state drifting from GitHub - #5455
Conversation
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).
|
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. |
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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. ChangesIntegrated git and pull-request flow
Estimated code review effort: 4 (Complex) | ~60 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
Ready to review this PR? Stage has broken it down into 6 individual chapters for you: Chapters generated by Stage for commit 2f71991 on Jul 5, 2026 8:14am UTC. |
Greptile SummaryThis PR fixes three distinct causes of workspace↔PR/diff state drift in the v2 host-service: case-sensitive branch matching in
Confidence Score: 4/5Safe 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
|
| 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"
%%{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"
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
| const commonDirByWorktree = new Map<string, string>(); | ||
| const lastFetchStartedAt = new Map<string, number>(); | ||
| const inFlightFetches = new Map<string, Promise<void>>(); |
There was a problem hiding this 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.
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.| 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; |
There was a problem hiding this 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.
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!
There was a problem hiding this comment.
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 winDuplicate case-insensitive key logic across files.
upstreamKeyhere duplicates the exact same lowercasing/concatenation logic asheadKeyingithub-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 thenodeKey === keyverification 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. intypes.tsor 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) andupstreamKey(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 | 🔵 TrivialConsider 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
📒 Files selected for processing (13)
packages/host-service/src/runtime/git/refs.test.tspackages/host-service/src/runtime/git/refs.tspackages/host-service/src/runtime/pull-requests/pull-requests.test.tspackages/host-service/src/runtime/pull-requests/pull-requests.tspackages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.tspackages/host-service/src/runtime/pull-requests/utils/github-query/github-query.tspackages/host-service/src/runtime/pull-requests/utils/github-query/index.tspackages/host-service/src/trpc/router/git/utils/base-ref-freshness.tspackages/host-service/src/trpc/router/git/utils/git-helpers.integration.test.tspackages/host-service/src/trpc/router/git/utils/git-helpers.tspackages/host-service/src/trpc/router/git/utils/git-status.tspackages/host-service/src/trpc/router/git/v2-diff-surfaces.integration.test.tspackages/host-service/src/trpc/router/workspaces/workspaces.ts
| const tagRef: `refs/tags/${string}` = `refs/tags/${trimmed}`; | ||
| if (await refExists(git, tagRef)) { | ||
| return { kind: "tag", fullRef: tagRef, shortName: trimmed }; | ||
| } |
There was a problem hiding this comment.
🎯 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:
- 1: http://public-inbox.org/git/20240701182824.GE3199@coredump.intra.peff.net/T/
- 2: http://public-inbox.org/git/CALnO6CAZ+Z_ZzkqXHu45A3cwZTZD4=MEz-vx0PEoD05bJ=0bzw@mail.gmail.com/T/
- 3: https://github.com/MicrosoftDocs/azure-devops-docs/blob/main/docs/repos/git/os-compatibility.md
- 4: http://public-inbox.org/git/a77695ea-ae24-45ca-8c14-966e25bb90ba@web.de/
- 5: http://public-inbox.org/git/A72DCB1B-8D81-4DD7-93AD-BF37E88E9D63@jvns.ca/T/
- 6: https://git-scm.com/docs/git-tag
- 7: https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-tag.html
🏁 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 expandedRepository: 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.tsRepository: 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.tsRepository: 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.tsRepository: 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.
There was a problem hiding this comment.
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)
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| git: SimpleGit, | ||
| worktreePath: string, | ||
| ): Promise<string> { | ||
| const cached = commonDirByWorktree.get(worktreePath); |
There was a problem hiding this comment.
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.
|
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. |
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
|
Thanks for the reviews — addressed in 64f6fc6. Summary of each finding: Fixed (valid):
Declined (with reasoning):
Also added a 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- |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.ts (1)
35-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider 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_MShas elapsed, which is the other half of the<boundary in the throttling check. MockingDate.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
📒 Files selected for processing (7)
packages/host-service/src/runtime/git/refs.test.tspackages/host-service/src/runtime/git/refs.tspackages/host-service/src/runtime/pull-requests/pull-requests.tspackages/host-service/src/runtime/pull-requests/utils/github-query/github-query.test.tspackages/host-service/src/runtime/pull-requests/utils/github-query/github-query.tspackages/host-service/src/trpc/router/git/utils/base-ref-freshness.test.tspackages/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
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
|
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.
|
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. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/host-service/src/runtime/pull-requests/pull-requests.test.ts (1)
180-186: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid blanket async
console.warnsuppression.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
📒 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.
|
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. |
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/headKeylowercased owner/repo but kept the branch verbatim, so a localroshvan/mcp-1525-…never matched a PR headRoshvan/mcp-1525-…, and every sync actively re-wrotepullRequestId = null. Now the branch is compared case-insensitively. Because GitHub'shead=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/foohappily resolves therefs/heads/Foofile, soresolveRef's exact-case probe couldn't distinguish an exact match from case drift — andgit worktree add -bwould create a second branch sharing the existing one's loose-ref file (the mechanism that corrupts HEAD underneath the workspace).resolveRefnow enumerates real refnames viafor-each-ref: exact matches keep prior precedence (local > remote > tag); a case-insensitive match adopts the existing branch's canonical casing, whichplanBranchSource/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 fetchedorigin/<base>— so after a rebase onto a newer upstream, every replayed upstream commit was counted as a workspace change, ballooning the file count.getGitStatusSnapshotnow 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
resolveRefadopts canonical casing for local/remote/origin/-prefixed drift; diff balloons 4→heals to 1 file after the background fetch.getStatusballoon (4 files) → heal (1 file), background fetch fires (FETCH_HEAD+origin/mainsha advance confirmed independently), TTL dedup holds on rapid calls.Notes / prior art
(headSha, baseSha)+ a short failure-only backoff would remove the arbitrary interval and make the heal immediate after a rebase. Left out of this PR to keep it focused.pr-resolution.ts) has the same case-sensitivity bug but is left untouched pending the v1 sunset.🤖 Generated with Claude Code
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.
upstreamKeyand per-head cache keys case-sensitive to isolate case-variant branches; add a shallowstate=opensweep (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.for-each-refand adopt canonical casing; prevent case-twin creation on case-insensitive filesystems; propagate the canonical name during workspace creation; surface realfor-each-reffailures instead of degrading to “no branches.”origin/<base>...HEADdiffs don’t balloon after a rebase.Written for commit 2f71991. Summary will update on new commits.
Summary by CodeRabbit
New Features
Bug Fixes
Tests