Skip to content

refactor(cli): extract sandbox rebuild action - #2896

Merged
cv merged 10 commits into
mainfrom
refactor/oclif-extract-sandbox-rebuild-action
May 4, 2026
Merged

refactor(cli): extract sandbox rebuild action#2896
cv merged 10 commits into
mainfrom
refactor/oclif-extract-sandbox-rebuild-action

Conversation

@cv

@cv cv commented May 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Extract sandbox rebuild orchestration from src/nemoclaw.ts into a dedicated action module. This removes sandboxRebuild from the transitional runtime bridge while preserving rebuild preflight, backup, recreate, restore, policy preset restore, and post-upgrade checks.

Stack Navigation

Changes

  • Added src/lib/sandbox-rebuild-action.ts for rebuild confirmation, credential preflight, backup, delete/recreate, restore, policy preset replay, and post-restore checks.
  • Updated src/lib/sandbox-runtime-actions.ts to call the extracted rebuild action.
  • Updated upgrade-sandboxes to call the extracted rebuild action directly.
  • Removed sandboxRebuild from src/nemoclaw.ts and NemoClawRuntimeBridge.

Type of Change

  • Code change (feature, bug fix, or refactor)
  • Code change with doc updates
  • Doc only (prose changes, no code sample modifications)
  • Doc only (includes code sample changes)

Verification

  • npx prek run --all-files passes
  • npm test passes
  • Tests added or updated for new or changed behavior
  • No secrets, API keys, or credentials committed
  • Docs updated for user-facing behavior changes
  • make docs builds without warnings (doc changes only)
  • Doc pages follow the style guide (doc changes only)
  • New doc pages include SPDX header and frontmatter (new pages only)

Signed-off-by: Carlos Villela cvillela@nvidia.com

Summary by CodeRabbit

  • New Features

    • Safer, user-facing sandbox rebuild flow with interactive confirmations, SSH-session warnings, credential preflight, workspace backup/restore, and clear completion/recovery messages.
  • Refactor

    • Moved sandbox rebuild responsibilities to a dedicated action; runtime bridge no longer exposes a direct rebuild method.

@cv cv self-assigned this May 3, 2026
@copy-pr-bot

copy-pr-bot Bot commented May 3, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented May 3, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e38ecf08-5f6e-4963-a3a5-c7f66f38d9d4

📥 Commits

Reviewing files that changed from the base of the PR and between af8b9fc and 668c999.

📒 Files selected for processing (1)
  • src/lib/sandbox-rebuild-action.ts

📝 Walkthrough

Walkthrough

The PR removes sandboxRebuild from the NemoClawRuntimeBridge interface and from the top-level runtime bridge export, and extracts the sandbox rebuild workflow into a new src/lib/sandbox-rebuild-action.ts module; runtime actions now delegate to that module via dynamic require.

Changes

Sandbox Rebuild Extraction

Layer / File(s) Summary
Bridge Interface Update
src/lib/nemoclaw-runtime-bridge.ts
NemoClawRuntimeBridge drops sandboxRebuild(sandboxName: string, args?: string[]), leaving upgradeSandboxes(args?: string[]).
Delegation Wiring
src/lib/sandbox-runtime-actions.ts
rebuildSandbox(sandboxName, args) now dynamically requires and delegates to src/lib/sandbox-rebuild-action.ts instead of calling the runtime bridge.
Core Rebuild Implementation
src/lib/sandbox-rebuild-action.ts
New, self-contained rebuild workflow implementing: verbose/confirm flags, active-session detection, registry checks (block multi-agent), version reporting, credential preflight and legacy migration, live-sandbox verification, backup with manifest validation, NIM stop and openshell sandbox delete, onboard-based recreation with process.exit interception, backup restoration, gateway policy preset re-application, OpenClaw post-restore fix, and registry update of agent version.
Top-level Integration
src/nemoclaw.ts
Removes sandboxRebuild from exports.runtimeBridge and updates destructured imports from ./lib/sandbox-destroy-action (removing removeSandboxRegistryEntry).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI as NemoClaw CLI
    participant Onboard
    participant Openshell
    participant Registry
    participant SandboxState
    participant Policies

    User->>CLI: run rebuildSandbox(sandboxName, args)
    CLI->>Registry: load sandbox entry
    CLI->>Onboard: detect active onboard sessions
    CLI->>Openshell: check sandbox liveness (sandbox list)
    CLI->>SandboxState: backupSandboxState()
    CLI->>Openshell: stop NIM container / delete sandbox
    CLI->>Registry: remove registry entry
    CLI->>Onboard: onboard(resume, recreateSandbox, nonInteractive)
    Onboard-->>CLI: success / failure
    CLI->>SandboxState: restoreSandboxState()
    CLI->>Policies: applyPreset(...) for each saved preset
    CLI->>Registry: update agentVersion
    CLI->>User: print completion status
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • NVIDIA/NemoClaw#2895: Performs a similar refactor pattern extracting sandbox destroy into an action module and removing the bridge method.
  • NVIDIA/NemoClaw#2892: Similar refactor pattern extracting sandbox-related logic into a dedicated module and updating runtime-action delegation.

Suggested reviewers

  • prekshivyas

Poem

🐰 I dug a tunnel through the bridge and land,
Backed up my burrow with a careful hand.
I stop the box, then build it new,
Restore the carrots and the dew.
Hop—recreated, safe and grand!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: extracting sandbox rebuild action from the main module into a dedicated file.
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.

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

✨ 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 refactor/oclif-extract-sandbox-rebuild-action

Review rate limit: 9/10 reviews remaining, refill in 6 minutes.

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

@cv cv added the v0.0.34 label May 4, 2026
cv added a commit that referenced this pull request May 4, 2026
## Summary
Extract sandbox destroy and image cleanup helpers from `src/nemoclaw.ts`
into a dedicated action module. This removes `sandboxDestroy` from the
transitional runtime bridge while preserving sandbox deletion, messaging
provider cleanup, gateway teardown, and Docker image cleanup behavior.

## Stack Navigation
- Position: 6 of 60
- Previous PR: [#2893 — refactor(cli): extract sandbox doctor
action](#2893)
- Next PR: [#2896 — refactor(cli): extract sandbox rebuild
action](#2896)

## Changes
- Added `src/lib/sandbox-destroy-action.ts` for sandbox destroy
orchestration, delete-result classification, gateway cleanup, service
cleanup, and image cleanup helpers.
- Updated `src/lib/sandbox-runtime-actions.ts` to call the extracted
destroy action.
- Removed `sandboxDestroy` and destroy-specific helpers from
`src/nemoclaw.ts` and `NemoClawRuntimeBridge`.
- Updated rebuild to use the extracted image/registry removal helper.
- Reworked image cleanup tests to cover helper behavior instead of
source-shape assertions against `src/nemoclaw.ts`.

## Type of Change
- [x] Code change (feature, bug fix, or refactor)
- [ ] Code change with doc updates
- [ ] Doc only (prose changes, no code sample modifications)
- [ ] Doc only (includes code sample changes)

## Verification
- [x] `npx prek run --all-files` passes
- [x] `npm test` passes
- [x] Tests added or updated for new or changed behavior
- [x] No secrets, API keys, or credentials committed
- [ ] Docs updated for user-facing behavior changes
- [ ] `make docs` builds without warnings (doc changes only)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

---
Signed-off-by: Carlos Villela <cvillela@nvidia.com>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved handling for sandbox deletion when the sandbox has already
been removed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv
cv changed the base branch from refactor/oclif-extract-sandbox-destroy-action to main May 4, 2026 19:11
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv
cv marked this pull request as ready for review May 4, 2026 19:15

@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: 3

🤖 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 `@src/lib/sandbox-rebuild-action.ts`:
- Around line 83-84: The code captures agent with
agentRuntime.getSessionAgent(sandboxName) into agent/agentName early, but later
logic that loads agentDef (used for post-restore migrations/version updates)
still uses that stale agent; after the session rewrite (the rebuild of the
sandbox session), re-fetch the current agent and display name (call
agentRuntime.getSessionAgent(sandboxName) and
agentRuntime.getAgentDisplayName(...) again) or replace uses of the original
agent/agentName with the rebuilt-session agent variable so agentDef is derived
from the up-to-date agent; update the code paths that load agentDef (the block
currently around where agentDef is used for migrations/version updates) to use
the fresh agent reference.
- Around line 127-143: The current branch in sandbox-rebuild-action.ts skips
credential preflight when onboardSession.loadSession() points to a different
sandbox, which allows destructive operations without checking credentials;
instead, when session.sandboxName !== sandboxName, fall back to resolving the
credential environment for the target sandbox and set rebuildCredentialEnv
accordingly rather than skipping preflight: keep using
onboardSession.loadSession() to read the existing session, but replace the skip
block that logs the warning with logic that calls the registry-backed provider
resolution used elsewhere (i.e., the same provider selection/onboard resume
path) to obtain the credential env for sandboxName and assign it to
rebuildCredentialEnv (preserving the existing null fallback behavior if none
found), ensuring the preflight uses rebuildCredentialEnv for subsequent checks.
- Around line 48-52: The bailout handler declaration for bail currently defines
a second parameter named code that is unused in the throwing branch, violating
the unused-variable rule; update the throwing branch's parameter name to _code
(i.e., change (msg: string, code = 1) => { throw new Error(msg); } to use (msg:
string, _code = 1) => { throw new Error(msg); }) while leaving the non-throwing
branch unchanged so opts.throwOnError and bail semantics remain the same.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 9ce940f5-911a-4452-9237-41fbfcc8e960

📥 Commits

Reviewing files that changed from the base of the PR and between 9471322 and af8b9fc.

📒 Files selected for processing (4)
  • src/lib/nemoclaw-runtime-bridge.ts
  • src/lib/sandbox-rebuild-action.ts
  • src/lib/sandbox-runtime-actions.ts
  • src/nemoclaw.ts
💤 Files with no reviewable changes (1)
  • src/lib/nemoclaw-runtime-bridge.ts

Comment thread src/lib/sandbox-rebuild-action.ts
Comment thread src/lib/sandbox-rebuild-action.ts
Comment thread src/lib/sandbox-rebuild-action.ts

@prekshivyas prekshivyas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Clean extraction of sandboxRebuild + _rebuildLog into src/lib/sandbox-rebuild-action.ts. Public surface preserved (--yes/--force/--verbose/-v, NEMOCLAW_REBUILD_VERBOSE=1, all log/confirm strings byte-identical, exit codes unchanged). The throwOnError opt for upgradeSandboxes's batch loop is preserved. The RD as _RD re-aliasing is inconsistent with #2891/#2892/#2893 (which dropped the underscore) but resolves to the same color — no behavior change.

Nit / follow-up:

Six new orphan imports introduced in src/nemoclaw.ts (last consumer was sandboxRebuild):

  • hydrateCredentialEnv (line 38, in destructure with the still-used isNonInteractive)
  • getActiveSandboxSessions (line 81)
  • createSessionDeps / createSystemDeps (line 82)
  • sandboxState and parseRestoreArgs (lines 78–79)
  • policies (line 45)

These plus the carryover from #2891/#2893/#2895 (~10 imports + 2 stale sandboxDestroy() comments) bring the total to ~16. Tracked for the separate cleanup PR.

@cv
cv merged commit 92f4cd3 into main May 4, 2026
17 checks passed
@prekshivyas
prekshivyas deleted the refactor/oclif-extract-sandbox-rebuild-action branch May 4, 2026 20:44
cv added a commit that referenced this pull request May 4, 2026
## Summary
Extract upgrade-sandboxes orchestration from `src/nemoclaw.ts` into a
dedicated action module. This removes the final command action from the
transitional runtime bridge while preserving stale-version detection and
rebuild-loop behavior.

## Stack Navigation
- Position: 8 of 60
- Previous PR: [#2896 — refactor(cli): extract sandbox rebuild
action](#2896)
- Next PR: [#2898 — refactor(cli): remove runtime
bridge](#2898)

## Changes
- Added `src/lib/upgrade-sandboxes-action.ts` for stale/unknown version
classification and optional rebuild orchestration.
- Updated `src/lib/global-cli-actions.ts` to call the extracted upgrade
action.
- Removed `upgradeSandboxes` from `src/nemoclaw.ts` and emptied the
`NemoClawRuntimeBridge` action surface.
- Removed the remaining runtime-bridge dependency from
`src/lib/sandbox-runtime-actions.ts`.

## Type of Change
- [x] Code change (feature, bug fix, or refactor)
- [ ] Code change with doc updates
- [ ] Doc only (prose changes, no code sample modifications)
- [ ] Doc only (includes code sample changes)

## Verification
- [x] `npx prek run --all-files` passes
- [x] `npm test` passes
- [ ] Tests added or updated for new or changed behavior
- [x] No secrets, API keys, or credentials committed
- [ ] Docs updated for user-facing behavior changes
- [ ] `make docs` builds without warnings (doc changes only)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

---
Signed-off-by: Carlos Villela <cvillela@nvidia.com>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactor**
* Internal reorganization of the sandbox upgrade system to improve code
modularity and maintainability. The upgrade functionality, including
sandbox stale detection and batch rebuild operations with `--check`,
`--auto`, and `--yes` flag support, remains available as before.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@wscurran wscurran added the refactor PR restructures code without intended behavior change label Jun 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactor PR restructures code without intended behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants