Skip to content

fix: verify sandbox git remote matches expected repo#82

Open
sweetmantech wants to merge 11 commits intomainfrom
fix/sandbox-remote-mismatch
Open

fix: verify sandbox git remote matches expected repo#82
sweetmantech wants to merge 11 commits intomainfrom
fix/sandbox-remote-mismatch

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Mar 12, 2026

Summary

  • When restoring from a snapshot, verify that the git remote origin matches the expected githubRepo URL
  • If mismatched (e.g., snapshot was from a different account's sandbox), update the remote before proceeding
  • Add remoteUrl to push logs for easier debugging

Root cause

Snapshots carry .git/config with the remote URL from when the snapshot was taken. If an account's sandbox was created from a snapshot belonging to a different account (e.g., the org root account), the remote points to the wrong repo. ensureGithubRepo previously trusted the existing .git directory without verifying the remote, causing pushes to land in the wrong repo.

Test plan

  • All 141 tasks tests passing
  • Deploy and trigger a sandbox command for an account that previously had the wrong remote
  • Verify push logs show remoteUrl matching the expected repo
  • Verify commits land in the correct GitHub repo

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Added verification for GitHub repository configuration to ensure the correct repository is being used before pushing code
    • Automatically corrects mismatched repository URLs when detected
  • Improvements

    • Enhanced push operation logging to display remote repository URL information for better visibility

Recoup Agent and others added 10 commits March 11, 2026 22:44
…shot

Snapshots can carry a stale git remote from a different account's
sandbox. When .git already exists, check that origin matches the
expected githubRepo and update it if not.

Also adds remoteUrl to push logs for easier debugging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 12, 2026

📝 Walkthrough

Walkthrough

The PR adds remote URL verification to the GitHub repository setup process within sandboxes and enhances logging in the push operation. When a repository is already cloned, the remote origin URL is fetched, normalized, and compared against the expected GitHub repository. If mismatched, the origin is automatically rewritten to the authenticated repository URL. Push operations now log the actual remote URL being used.

Changes

Cohort / File(s) Summary
Remote Verification
src/sandboxes/ensureGithubRepo.ts
Adds verification step when repository is already cloned: fetches and normalizes origin URL, compares to expected githubRepo, rewrites origin if mismatched, and applies git remote update.
Push Operation Logging
src/sandboxes/pushSandboxToGithub.ts
Reads current Git remote URL for origin and includes it in push initiation and completion log messages instead of generic text.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

Poem

🐰 A rabbit checks each remote with care,
Normalizing URLs floating through the air,
Origin verified, authenticated right,
Git remotes rewritten—all pushing bright! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: verifying that the sandbox git remote matches the expected repository, which is the primary fix described in the PR objectives.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/sandbox-remote-mismatch
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
src/sandboxes/pushSandboxToGithub.ts (1)

22-26: Consider checking exitCode before using stdout for robustness.

The remote URL is read without verifying that the command succeeded. If git remote get-url origin fails (e.g., no remote configured), remoteUrl will be empty or misleading. While ensureGithubRepo runs before this function (per context snippet 4), adding defensive error handling would be consistent with the pattern in runGitCommand.ts.

🔧 Proposed fix
   const remoteCheck = await sandbox.runCommand({
     cmd: "git",
     args: ["remote", "get-url", "origin"],
   });
-  const remoteUrl = ((await remoteCheck.stdout()) || "").trim();
+  const remoteUrl =
+    remoteCheck.exitCode === 0
+      ? ((await remoteCheck.stdout()) || "").trim()
+      : "<unknown>";
   logger.log("Pushing sandbox files to GitHub", { remoteUrl });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/sandboxes/pushSandboxToGithub.ts` around lines 22 - 26, Check the git
command's exit code before using stdout: after calling sandbox.runCommand
(remoteCheck) verify remoteCheck.exitCode (or equivalent) indicates success and
only then use remoteCheck.stdout() to set remoteUrl; if the command failed,
handle it consistently (e.g., log or throw a descriptive error and treat
remoteUrl as missing) similar to patterns in runGitCommand.ts and in callers
like ensureGithubRepo so you don't proceed with an empty/misleading remoteUrl.
src/sandboxes/ensureGithubRepo.ts (2)

72-76: Consider checking exitCode before using stdout.

Similar to the pattern in pushSandboxToGithub.ts, the remote URL is read without verifying command success. While this is inside the .git directory check block, if the origin remote somehow doesn't exist, currentRemote would be empty. The current behavior would still work (empty string won't match githubRepo, triggering the update), but explicit error handling would be cleaner.

🔧 Proposed fix
     const remoteResult = await sandbox.runCommand({
       cmd: "git",
       args: ["remote", "get-url", "origin"],
     });
-    const currentRemote = ((await remoteResult.stdout()) || "").trim();
+    const currentRemote =
+      remoteResult.exitCode === 0
+        ? ((await remoteResult.stdout()) || "").trim()
+        : "";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/sandboxes/ensureGithubRepo.ts` around lines 72 - 76, In
ensureGithubRepo.ts, before reading remoteResult.stdout() from the
sandbox.runCommand call that fetches "git remote get-url origin", check
remoteResult.exitCode (or the equivalent success indicator) and handle non-zero
exit by logging or treating currentRemote as empty; update the code around the
remoteResult variable to mirror the pattern used in pushSandboxToGithub.ts
(verify exitCode, capture stderr for diagnostics, and only use stdout when
exitCode === 0) so you don't rely on stdout when the git command failed or the
origin remote is missing.

89-93: The return value of runGitCommand is not checked.

If the remote update fails, the function continues and returns githubRepo as if successful. The subsequent push would fail, but with a less specific error. Consider checking the result and either logging a warning or returning undefined on failure.

🔧 Proposed fix to handle failure
-      await runGitCommand(
+      const updated = await runGitCommand(
         sandbox,
         ["remote", "set-url", "origin", repoUrl],
         "update remote to correct repo"
       );
+      if (!updated) {
+        logger.error("Failed to update sandbox remote", { expected: githubRepo });
+        return undefined;
+      }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/sandboxes/ensureGithubRepo.ts` around lines 89 - 93, In ensureGithubRepo,
the call to runGitCommand([... "remote", "set-url", "origin", repoUrl]) isn't
checked so failures are ignored; change ensureGithubRepo to capture the return
value of runGitCommand, and if it indicates failure (falsy/false), log a warning
via the existing logger or processLogger and return undefined (or throw) instead
of proceeding to push; ensure any subsequent code that uses githubRepo only runs
when the remote update succeeded so the function doesn't erroneously return
githubRepo after a failed runGitCommand.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/sandboxes/ensureGithubRepo.ts`:
- Around line 72-76: In ensureGithubRepo.ts, before reading
remoteResult.stdout() from the sandbox.runCommand call that fetches "git remote
get-url origin", check remoteResult.exitCode (or the equivalent success
indicator) and handle non-zero exit by logging or treating currentRemote as
empty; update the code around the remoteResult variable to mirror the pattern
used in pushSandboxToGithub.ts (verify exitCode, capture stderr for diagnostics,
and only use stdout when exitCode === 0) so you don't rely on stdout when the
git command failed or the origin remote is missing.
- Around line 89-93: In ensureGithubRepo, the call to runGitCommand([...
"remote", "set-url", "origin", repoUrl]) isn't checked so failures are ignored;
change ensureGithubRepo to capture the return value of runGitCommand, and if it
indicates failure (falsy/false), log a warning via the existing logger or
processLogger and return undefined (or throw) instead of proceeding to push;
ensure any subsequent code that uses githubRepo only runs when the remote update
succeeded so the function doesn't erroneously return githubRepo after a failed
runGitCommand.

In `@src/sandboxes/pushSandboxToGithub.ts`:
- Around line 22-26: Check the git command's exit code before using stdout:
after calling sandbox.runCommand (remoteCheck) verify remoteCheck.exitCode (or
equivalent) indicates success and only then use remoteCheck.stdout() to set
remoteUrl; if the command failed, handle it consistently (e.g., log or throw a
descriptive error and treat remoteUrl as missing) similar to patterns in
runGitCommand.ts and in callers like ensureGithubRepo so you don't proceed with
an empty/misleading remoteUrl.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f38f1e50-a8f0-4ff6-ba7c-4e620c253f65

📥 Commits

Reviewing files that changed from the base of the PR and between f7dc49a and bccb1c4.

📒 Files selected for processing (2)
  • src/sandboxes/ensureGithubRepo.ts
  • src/sandboxes/pushSandboxToGithub.ts

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