Repository navigation
Switch repo sessions to source branches - #558
Conversation
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
|
Warning Review limit reached
More reviews will be available in 19 minutes and 17 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits. 🚦 How do rate limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (9)
📝 WalkthroughWalkthroughRepo sessions now use branch-based identity and source repos, scheduled cleanup removes abandoned session branches, and artifact/job cleanup paths no longer depend on repo-session-derived repository names. ChangesSession branch and artifact cleanup
Estimated code review effort🎯 5 (Critical) | ⏱️ ~90+ minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 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 |
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
|
🔎 Preview deployed: https://kody-pr-558.kentcdodds.workers.dev Worker: Mocks:
|
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/worker/src/jobs/service.ts (1)
622-640: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDon’t drop the source row when repo cleanup fails.
cleanupArtifactReposForSourcereturns0when Artifacts access is unavailable or deletion fails. These paths still delete published artifacts/snapshots and theentity_sourcesrow, losing therepo_idneeded for retry/manual cleanup and orphaning the artifact repo.Proposed fix
- await cleanupArtifactReposForSource({ + const deletedRepoCount = await cleanupArtifactReposForSource({ env: input.env, userId: artifact.userId, sourceId: source.id, }) + if (source.repo_id.trim() && deletedRepoCount === 0) { + throw new Error(`Artifact repo cleanup failed for source ${source.id}`) + }- await cleanupArtifactReposForSource({ + const deletedRepoCount = await cleanupArtifactReposForSource({ env: input.env, userId: input.userId, sourceId: source.id, }) + if (source.repo_id.trim() && deletedRepoCount === 0) { + throw new Error(`Artifact repo cleanup failed for source ${source.id}`) + }Also applies to: 686-704
🤖 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/worker/src/jobs/service.ts` around lines 622 - 640, The cleanup flow in service.ts should not continue deleting published artifacts, snapshots, or the entity_sources row when cleanupArtifactReposForSource returns 0. Update the logic around cleanupArtifactReposForSource, deletePublishedArtifactsForSource, deletePublishedSourceSnapshot, and deleteEntitySource so repo cleanup failures/unavailable access short-circuit the rest of the deletion path, preserving repo_id for retry or manual cleanup. Apply the same guard in the other affected cleanup block as well.packages/worker/src/repo/repo-session-do.ts (2)
795-820: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winRollback the remote branch when session-row creation fails.
The branch is pushed before
insertRepoSession(). Any transient DB failure after Line 795 leaves an untrackedsessions/...branch behind, and cleanup can never discover it because no row was written.Suggested direction
await this.git.push({ dir: repoSessionWorkspacePrefix, remote: 'origin', ref: sessionBranch, ...buildArtifactsGitAuth({ token: sourceAccess.token }), }) - const now = nowIso() - const newSessionRow: RepoSessionRow = { - id: input.sessionId, - user_id: input.userId, - source_id: input.sourceId, - session_branch: sessionBranch, - base_commit: baseCommit ?? '', - source_root: input.sourceRoot ?? source.source_root, - conversation_id: input.conversationId ?? null, - status: 'active', - expires_at: null, - last_checkpoint_at: null, - last_checkpoint_commit: baseCommit, - last_check_run_id: null, - last_check_tree_hash: null, - created_at: now, - updated_at: now, - } - await insertRepoSession(this.env.APP_DB, newSessionRow) - sessionRow = newSessionRow + try { + const now = nowIso() + const newSessionRow: RepoSessionRow = { + id: input.sessionId, + user_id: input.userId, + source_id: input.sourceId, + session_branch: sessionBranch, + base_commit: baseCommit ?? '', + source_root: input.sourceRoot ?? source.source_root, + conversation_id: input.conversationId ?? null, + status: 'active', + expires_at: null, + last_checkpoint_at: null, + last_checkpoint_commit: baseCommit, + last_check_run_id: null, + last_check_tree_hash: null, + created_at: now, + updated_at: now, + } + await insertRepoSession(this.env.APP_DB, newSessionRow) + sessionRow = newSessionRow + } catch (error) { + await this.deleteRemoteBranch({ + branch: sessionBranch, + token: sourceAccess.token, + }).catch(() => {}) + throw error + }🤖 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/worker/src/repo/repo-session-do.ts` around lines 795 - 820, The branch push in `RepoSessionDo` happens before `insertRepoSession`, so if session-row creation fails the remote `sessionBranch` is left behind with no DB record to clean it up. Wrap the push-and-insert flow in error handling, and if `insertRepoSession(this.env.APP_DB, newSessionRow)` throws, immediately delete/rollback the pushed branch from `origin` using the same auth/token path before rethrowing. Keep the fix localized to the `RepoSessionDo` session creation flow and reuse the existing `git.push`/`buildArtifactsGitAuth` setup for the cleanup path.
739-780: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftPersist the caller-selected upstream branch.
defaultBranchis still accepted on open, but Line 779 always usessourceInfo?.defaultBranch, and later rebase/publish recompute the repo default again. A session opened against a non-default branch will resume and publish against the wrong upstream ref because that choice is never stored inrepo_sessions.Also applies to: 1612-1617, 1709-1713
🤖 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/worker/src/repo/repo-session-do.ts` around lines 739 - 780, The session open flow is ignoring the caller’s selected upstream branch and always falling back to the repo default, so the chosen branch is lost after open. In the repo session create/open logic in RepoSessionDo, persist the effective branch from the open input (defaultBranch or sourceInfo default) into repo_sessions when the session is created. Then update the resume/rebase/publish paths in the same repo session class to read and reuse that stored branch instead of recomputing the repo default.
🧹 Nitpick comments (1)
packages/worker/src/repo/repo-session-do.node.test.ts (1)
936-936: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep this insert assertion checking the new branch contract.
expect.objectContaining({})is effectively a no-op now, so this path stops validating that the persisted session carries the newsession_branchstate.Suggested assertion
- expect.objectContaining({}), + expect.objectContaining({ + session_branch: expect.stringMatching(/^sessions\//), + }),🤖 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/worker/src/repo/repo-session-do.node.test.ts` at line 936, The insert assertion in the repo session test is currently a no-op, so it no longer verifies the new branch contract. Update the assertion in repo-session-do.node.test.ts to explicitly check that the persisted session includes the expected session_branch state, using the existing insert path and related session fixture/expectation objects so the test continues validating the new branch behavior.
🤖 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/worker/src/index.ts`:
- Around line 419-422: The scheduled maintenance flow in the worker still lets
an unhandled failure from reconcileArtifactsPushes block
cleanupRepoSessionBranches, so the branch cleanup can be skipped for the whole
run. Update the maintenance sequence in index.ts to isolate these jobs by
handling each step independently, ideally around the reconcileArtifactsPushes
and cleanupRepoSessionBranches calls in the scheduled handler, so a transient
failure in one does not prevent the other from executing.
In `@packages/worker/src/jobs/service.ts`:
- Around line 617-621: The source cleanup guard in service.ts is missing the
ownership check, so it can act on a source that does not belong to the current
user. Update the conditional around the source cleanup block in the cleanup flow
to also verify source.user_id matches the same user constraint used in
cleanupAdHocJobSource, alongside the existing source.entity_kind and
source.entity_id checks. This ensures the source-scoped snapshot deletion only
runs for the correct owner.
In `@packages/worker/src/mcp/capabilities/repo/repo-workflow.node.test.ts`:
- Around line 261-262: Remove the duplicated session_branch entries in the
repo-workflow.node.test.ts fixtures so each object only defines that field once.
Update the affected fixture objects in the repo workflow test data to keep a
single session_branch property per object, using the existing value, and check
the repeated fixture blocks referenced by the duplicate occurrences so Biome
validation passes cleanly.
In `@packages/worker/src/repo/artifact-inventory-planner.ts`:
- Around line 95-96: The artifact inventory planner is combining user-scoped
`entity_sources` with a namespace-wide `binding.list()` result, which can
surface other users’ repos in `samples` and misclassify them as
`deleteCandidate`. Update `repo_artifacts_inventory`/`ArtifactInventoryPlanner`
so the `listEntitySourcesByUser` + `sourceRepoNames` check is only used for
operator/admin flows, or otherwise ensure the namespace passed into
`binding.list()` is already isolated per user. Keep the classification logic in
`artifact-inventory-planner.ts` from comparing shared-namespace repos against a
single caller’s metadata.
In `@packages/worker/src/repo/repo-session-cleanup.ts`:
- Around line 41-50: The repo session cleanup warning is logging raw user-owned
identifiers in the JSON payload. Update the repoSessionCleanup flow in
repo-session-cleanup.ts so the console.warn output no longer includes userId,
sessionId, sourceId, or branch, and keep only non-sensitive error context such
as the reason and error message. Use the existing cleanup failure logging block
to remove those fields from the payload while preserving the warning message.
In `@packages/worker/src/repo/repo-session-do.ts`:
- Around line 1071-1079: Stop emitting raw user/session metadata in the cleanup
log from repo-session-do.ts. Update the console.info payload in the
branch-deletion path to remove or redact userId, sessionId, sourceId, and the
full sessionBranch while keeping only non-sensitive operational context in the
“repo session branch deleted” message.
---
Outside diff comments:
In `@packages/worker/src/jobs/service.ts`:
- Around line 622-640: The cleanup flow in service.ts should not continue
deleting published artifacts, snapshots, or the entity_sources row when
cleanupArtifactReposForSource returns 0. Update the logic around
cleanupArtifactReposForSource, deletePublishedArtifactsForSource,
deletePublishedSourceSnapshot, and deleteEntitySource so repo cleanup
failures/unavailable access short-circuit the rest of the deletion path,
preserving repo_id for retry or manual cleanup. Apply the same guard in the
other affected cleanup block as well.
In `@packages/worker/src/repo/repo-session-do.ts`:
- Around line 795-820: The branch push in `RepoSessionDo` happens before
`insertRepoSession`, so if session-row creation fails the remote `sessionBranch`
is left behind with no DB record to clean it up. Wrap the push-and-insert flow
in error handling, and if `insertRepoSession(this.env.APP_DB, newSessionRow)`
throws, immediately delete/rollback the pushed branch from `origin` using the
same auth/token path before rethrowing. Keep the fix localized to the
`RepoSessionDo` session creation flow and reuse the existing
`git.push`/`buildArtifactsGitAuth` setup for the cleanup path.
- Around line 739-780: The session open flow is ignoring the caller’s selected
upstream branch and always falling back to the repo default, so the chosen
branch is lost after open. In the repo session create/open logic in
RepoSessionDo, persist the effective branch from the open input (defaultBranch
or sourceInfo default) into repo_sessions when the session is created. Then
update the resume/rebase/publish paths in the same repo session class to read
and reuse that stored branch instead of recomputing the repo default.
---
Nitpick comments:
In `@packages/worker/src/repo/repo-session-do.node.test.ts`:
- Line 936: The insert assertion in the repo session test is currently a no-op,
so it no longer verifies the new branch contract. Update the assertion in
repo-session-do.node.test.ts to explicitly check that the persisted session
includes the expected session_branch state, using the existing insert path and
related session fixture/expectation objects so the test continues validating the
new branch behavior.
🪄 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 Plus
Run ID: 1001f440-5fe4-42e3-af6a-4a385ece8e23
📒 Files selected for processing (28)
packages/shared/src/chat.tspackages/worker/migrations/0041-repo-session-branches.sqlpackages/worker/src/index.tspackages/worker/src/jobs/service.node.test.tspackages/worker/src/jobs/service.tspackages/worker/src/mcp/capabilities/repo/domain.tspackages/worker/src/mcp/capabilities/repo/repo-artifacts-inventory.tspackages/worker/src/mcp/capabilities/repo/repo-open-session.tspackages/worker/src/mcp/capabilities/repo/repo-shared.tspackages/worker/src/mcp/capabilities/repo/repo-workflow.node.test.tspackages/worker/src/mcp/observability.workers.test.tspackages/worker/src/package-invocations/service.tspackages/worker/src/package-retrievers/service.tspackages/worker/src/repo/artifact-inventory-planner.node.test.tspackages/worker/src/repo/artifact-inventory-planner.tspackages/worker/src/repo/artifact-repo-cleanup.node.test.tspackages/worker/src/repo/artifact-repo-cleanup.tspackages/worker/src/repo/artifacts-mock-cloudflare.node.test.tspackages/worker/src/repo/artifacts.node.test.tspackages/worker/src/repo/artifacts.tspackages/worker/src/repo/repo-session-cleanup.node.test.tspackages/worker/src/repo/repo-session-cleanup.tspackages/worker/src/repo/repo-session-do.node.test.tspackages/worker/src/repo/repo-session-do.tspackages/worker/src/repo/repo-session-rpc.tspackages/worker/src/repo/repo-session-tree.tspackages/worker/src/repo/repo-sessions.tspackages/worker/src/repo/types.ts
💤 Files with no reviewable changes (4)
- packages/shared/src/chat.ts
- packages/worker/src/package-retrievers/service.ts
- packages/worker/src/mcp/observability.workers.test.ts
- packages/worker/src/package-invocations/service.ts
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit ab13a8d. Configure here.
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>

Summary
sessions/<id>branches on the source repo.repo_sessionsinto the branch-only schema; old fork-backed session metadata is not migrated forward.session_repo_*/sessionRepoIdAPI and caller-context surface.repo.fork()REST abstraction, session repo resolver, and fork-specific tests.Validation
npm run validateSummary by CodeRabbit
session_branch/source_branchinstead of legacy repo identifiers.