Skip to content

refactor: call destroyGateway() after diagnostic logs on final gateway failure - #2280

Closed
Sayeem3051 wants to merge 12 commits into
NVIDIA:mainfrom
Sayeem3051:fix/issue-17-gateway-volume-cleanup-v2
Closed

Sayeem3051 wants to merge 12 commits into
NVIDIA:mainfrom
Sayeem3051:fix/issue-17-gateway-volume-cleanup-v2

Conversation

@Sayeem3051

@Sayeem3051 Sayeem3051 commented Apr 22, 2026 •

Copy link
Copy Markdown

Summary

When gateway start fails after all retries are exhausted, the gateway volumes were not being cleaned up, leaving stale Docker volumes behind. This PR ensures destroyGateway() is called in the catch block after diagnostic logs are collected, preventing volume corruption on reruns.

Related Issue

Fixes #17

Changes

  • Restored err.retriesLeft > 0 guard in onFailedAttempt so intermediate failures still clean up while preserving the gateway for diagnostic log collection
  • Added destroyGateway() call in the catch block, after doctor logs are collected and right before process.exit(1)
  • Added src/lib/onboard.test.ts with a test verifying destroyGateway() is called when retries are exhausted

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update

Verification

  • Code follows project coding standards
  • Self-reviewed code
  • Added tests for new/changed functionality
    Signed-off-by: Abkari Mohammed Sayeem [email protected]

Summary by CodeRabbit

  • Bug Fixes

    • Ensures gateway cleanup runs and reports success/failure when startup exhausts retries; prints manual recovery commands if automatic cleanup fails and exits with failure.
    • Removes preserved-state diagnostic message and updates troubleshooting guidance to recommend using the onboard CLI command.
  • Tests

    • Added test coverage to validate cleanup behavior when gateway initialization fails after retry exhaustion.

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

startGatewayWithOptions now ensures destroyGateway() is invoked on retry/final failure when exitOnFailure: true; failure handling attempts automatic Docker-volume cleanup (reporting success/failure) and prints a manual recovery command set before rejecting/exiting. destroyGateway explicitly returns boolean after cleanup.

Changes

Cohort / File(s) Summary
Gateway cleanup & failure path
src/lib/onboard.ts
Added explicit (): boolean return for destroyGateway; adjusted onFailedAttempt/retry control flow so destroyGateway() runs in the intended failure branch; final failure handler now tries destroyGateway() and reports success/failure, replaces prior diagnostic message with nemoclau onboard guidance and prints manual recovery commands before exiting.
Tests for gateway cleanup
src/lib/onboard.test.ts
New Vitest test that mocks destroyGateway (via importActual), stubs p-retry to trigger onFailedAttempt across attempts then throw, calls startGatewayWithOptions({ exitOnFailure: true }), expects rejection/exit, and asserts destroyGateway was invoked.

Sequence Diagram(s)

sequenceDiagram
  participant Caller as Caller
  participant Onboard as startGatewayWithOptions
  participant PRetry as p-retry
  participant Gateway as destroyGateway

  Caller->>Onboard: startGatewayWithOptions({ exitOnFailure: true })
  Onboard->>PRetry: initiate retry loop
  PRetry->>Onboard: attempt fails (onFailedAttempt)
  Onboard->>Gateway: destroyGateway()  /* rgba(255,0,0,0.5) */
  PRetry->>Onboard: retry next attempt
  PRetry->>Onboard: final attempt fails
  Onboard->>Gateway: destroyGateway()  /* rgba(255,0,0,0.5) */
  Onboard-->>Caller: reject / exit with error + troubleshooting (suggest `nemoclau onboard`)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇
I hopped through retries, swept the docked-away,
Cleared every volume so new runs play,
I closed the gate, then gave a cheer,
If cleanup fails, I print the gear,
A tidy burrow for your next relay. 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% 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 accurately describes the main change: calling destroyGateway() after diagnostic logs on final gateway failure, which directly addresses the PR's objective of ensuring cleanup on exhausted retries.
Linked Issues check ✅ Passed The PR implements all acceptance criteria: prevents cluster state from blocking reruns [#17], ensures cleanup removes Docker volumes [#17], adds error handling with recovery commands [#17], and includes a unit test for the cleanup behavior [#17].
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing issue #17: modifications to destroyGateway() return type, conditional adjustments in onFailedAttempt, failure handling in catch block, and test coverage—no extraneous changes detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

@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.

Caution

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

⚠️ Outside diff range comments (1)
src/lib/onboard.ts (1)

3096-3133: ⚠️ Potential issue | 🟡 Minor

Update failure diagnostics text to match cleanup-on-every-failure behavior.

At Line 3100, cleanup now runs on every failed attempt, but Lines 3109-3133 still report that gateway state is preserved and then suggest diagnostics against state that may already be removed. Please align the failure messaging (or capture diagnostics before final cleanup).

Suggested patch
   } catch {
     if (exitOnFailure) {
       console.error(`  Gateway failed to start after ${retries + 1} attempts.`);
-      console.error("  Gateway state preserved for diagnostics.");
+      console.error("  Gateway cleanup completed after failed startup.");
       console.error("");
       try {
         const logs = redact(
           runCaptureOpenshell(["doctor", "logs", "--name", GATEWAY_NAME], {
             ignoreError: true,
           }),
         );
@@
       } catch {
         // doctor logs unavailable — fall through to manual instructions
       }
       console.error("  Troubleshooting:");
-      console.error("    openshell doctor logs --name nemoclaw");
       console.error("    openshell doctor check");
+      console.error("    nemoclaw onboard");
       process.exit(1);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` around lines 3096 - 3133, The failure messaging still
states "Gateway state preserved" and prints saved logs even though cleanup now
runs on every failed attempt via destroyGateway when exitOnFailure is true;
update the catch block around runCaptureOpenshell/redact/GATEWAY_NAME to either
capture and log diagnostics before destroyGateway is called or change the
printed text and troubleshooting steps to reflect that gateway state may have
been removed (e.g., remove "state preserved" line and adjust suggested
commands). Locate the relevant symbols exitOnFailure, destroyGateway,
runCaptureOpenshell, redact, GATEWAY_NAME, and ANSI_RE and either move the
runCaptureOpenshell call to occur before destroyGateway is invoked on failures
or alter the console.error lines to warn that logs may be unavailable because
cleanup ran and provide appropriate doctor/check commands.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/lib/onboard.ts`:
- Around line 3096-3133: The failure messaging still states "Gateway state
preserved" and prints saved logs even though cleanup now runs on every failed
attempt via destroyGateway when exitOnFailure is true; update the catch block
around runCaptureOpenshell/redact/GATEWAY_NAME to either capture and log
diagnostics before destroyGateway is called or change the printed text and
troubleshooting steps to reflect that gateway state may have been removed (e.g.,
remove "state preserved" line and adjust suggested commands). Locate the
relevant symbols exitOnFailure, destroyGateway, runCaptureOpenshell, redact,
GATEWAY_NAME, and ANSI_RE and either move the runCaptureOpenshell call to occur
before destroyGateway is invoked on failures or alter the console.error lines to
warn that logs may be unavailable because cleanup ran and provide appropriate
doctor/check commands.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 296574f4-1e5a-436e-b089-9032fb634771

📥 Commits

Reviewing files that changed from the base of the PR and between d50452a and 9fdb7d2.

📒 Files selected for processing (1)
  • src/lib/onboard.ts

@wscurran wscurran added refactor PR restructures code without intended behavior change fix labels Apr 22, 2026
@wscurran

Copy link
Copy Markdown
Contributor

✨ Thanks for submitting this PR that proposes a way to improve the gateway startup process. Please note that issue #17 has been fixed. Please respond if you still think this PR is valid.


Related open issues:

@Sayeem3051

Copy link
Copy Markdown
Author

Thanks for the heads up, @wscurran!

I've reviewed PR #337 and the current state of main. While PR #337 added the destroyGateway() function and calls it in the onFailedAttempt handler, the current code at line 3100 in src/lib/onboard.ts still has this condition:

if (err.retriesLeft > 0 && exitOnFailure) {
    destroyGateway();
}

This means destroyGateway() is only called when there are retries remaining (err.retriesLeft > 0). On the final failed attempt (when retries are exhausted and err.retriesLeft === 0), the cleanup is skipped, leaving behind a stale openshell-cluster-nemoclaw Docker volume.

PR #2280 removes the err.retriesLeft > 0 guard so destroyGateway() runs on every failed attempt, including the last one. This ensures the environment is left in a clean, rerunnable state regardless of how many retries were configured.

Happy to adjust if there's a preferred approach!

@brandonpelfrey

Copy link
Copy Markdown
Contributor

@Sayeem3051

Thanks for the PR — you've correctly identified a real issue. Stale Docker volumes from exhausted retries are a legit cleanup gap, and the one-line fix is easy to follow. Nice catch tracing the pattern across install.sh too.

One concern before merging: the current err.retriesLeft > 0 guard looks intentional. When the final attempt fails, the catch block right below (lines ~2693–2715) deliberately says "Gateway state preserved for diagnostics" and then collects openshell doctor logs from the still-running gateway. With this change, destroyGateway() fires in onFailedAttempt before the catch block runs, so by the time we try to grab those diagnostic logs the gateway is already torn down — they'll likely come back empty.

A cleaner approach might be to keep the existing guard as-is and instead call destroyGateway() inside the catch block after the diagnostic logs have been collected (right before process.exit(1)). That way you get both: useful logs on final failure and volume cleanup.

Would you also be able to add a test covering the cleanup-on-final-failure path? The plugin tests are co-located in src/ as *.test.ts files — even a simple mock verifying destroyGateway gets called when retriesLeft === 0 would be great.

@Sayeem3051

Copy link
Copy Markdown
Author

Thanks for the detailed feedback, @brandonpelfrey!

You're absolutely right about the diagnostic logs — I hadn't considered that destroyGateway() tearing down the gateway before the catch block runs would leave the doctor logs empty. Moving the call into the catch block after log collection is the right approach.

Here's the plan:

  1. Revert the onFailedAttempt change (restore the err.retriesLeft > 0 guard) so intermediate failures still clean up as intended.
  2. Add destroyGateway() inside the catch block, after the doctor logs are collected and right before process.exit(1).
  3. Add a test in src/ verifying that destroyGateway() is called when retries are exhausted.

I'll push these changes shortly. Appreciate the guidance!

Per @brandonpelfrey's feedback:
- Restore err.retriesLeft > 0 guard in onFailedAttempt so intermediate
  failures still clean up while preserving gateway for diagnostics
- Add destroyGateway() in catch block after doctor logs are collected,
  ensuring volumes are cleaned on final failure without losing diagnostic info
@copy-pr-bot

copy-pr-bot Bot commented Apr 29, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

Per @brandonpelfrey's request: add a test verifying that destroyGateway()
is called when retries are exhausted and the catch block is reached.
@Sayeem3051 Sayeem3051 changed the title fix: call destroyGateway() on all gateway start failures refactor: call destroyGateway() after diagnostic logs on final gateway failure Apr 29, 2026

@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.

Caution

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

⚠️ Outside diff range comments (1)
src/lib/onboard.ts (1)

3107-3134: ⚠️ Potential issue | 🟠 Major

Surface cleanup failure explicitly and stop claiming the gateway state is preserved.

destroyGateway() is still best-effort, so this path cannot tell whether the stale volume cleanup actually succeeded. If cleanup fails, the user exits with the original corrupted state still present, but the only follow-up guidance shown is diagnostic commands. Also, after Line 3133, openshell doctor logs --name nemoclaw is no longer a valid post-exit recovery step because the gateway has already been torn down. Please make cleanup report success/failure and print the exact manual recovery command when it fails; otherwise the issue’s fallback acceptance criteria is still unmet.

Suggested direction
-      console.error(`  Gateway failed to start after ${retries + 1} attempts.`);
-      console.error("  Gateway state preserved for diagnostics.");
+      console.error(`  Gateway failed to start after ${retries + 1} attempts.`);
+      console.error("  Gateway diagnostics collected above.");
       console.error("");
@@
       console.error("  Troubleshooting:");
-      console.error("    openshell doctor logs --name nemoclaw");
       console.error("    openshell doctor check");
-              destroyGateway();
+      const cleanup = destroyGateway();
+      if (!cleanup?.ok) {
+        console.error("");
+        console.error("  Automatic cleanup failed. Run:");
+        console.error("    openshell gateway destroy -g nemoclaw");
+        console.error(
+          '    docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | grep . && docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs docker volume rm || true',
+        );
+      }
       process.exit(1);
// `destroyGateway()` should return enough status for the caller to decide
// whether it needs to print the manual recovery command.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 83f23132-c8f8-41d9-803a-875b8bfb808e

📥 Commits

Reviewing files that changed from the base of the PR and between 9fdb7d2 and 89991d7.

📒 Files selected for processing (1)
  • src/lib/onboard.ts

vi.mock must be at the top level of the file, not inside beforeEach.
Moved the mock factory to module scope and create vi.fn() mocks
directly in the factory instead of referencing beforeEach variables.

@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 the current code and only fix it if needed.

Inline comments:
In `@src/lib/onboard.test.ts`:
- Around line 48-52: The test currently only asserts inside a catch block which
can silently pass if startGatewayWithOptions stops throwing; change it to
explicitly assert the promise rejects and then verify cleanup: use an explicit
rejection assertion against onboardModule.startGatewayWithOptions(gpu, {
exitOnFailure: true }) (e.g.,
expect(...).rejects.toThrow()/rejects.toBeDefined()) and after that assertion
verify destroyGatewaySpy was called; keep references to
onboardModule.startGatewayWithOptions and destroyGatewaySpy so the test both
asserts failure and that cleanup ran.
- Around line 11-25: Replace the hoisted vi.mock call in the beforeEach with
vi.doMock so the mock executes at runtime and can access the locally defined
spies; keep vi.resetModules() at the start of the beforeEach, define
destroyGatewaySpy, runOpenshellSpy, and runSpy there, and then call
vi.doMock(...) returning the actual module merged with overrides for
destroyGateway, runOpenshell, and run so the spies are used during tests.
- Around line 33-36: Add the missing export and correct the p-retry spy target:
export the function startGatewayWithOptions from the onboard module by adding it
to module.exports alongside startGateway and startGatewayForRecovery (so tests
can call onboardModule.startGatewayWithOptions), and change the spy setup in the
test to target the actual p-retry function (remove the erroneous extra
.default)—i.e., spy on originalPRetry.default (or use vi.spyOn(originalPRetry,
"default")) instead of originalPRetry.default.default so the mock wraps the real
p-retry function.
🪄 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: 6c584ae4-e1ab-4d60-b531-f3962044e400

📥 Commits

Reviewing files that changed from the base of the PR and between 89991d7 and ffb3021.

📒 Files selected for processing (1)
  • src/lib/onboard.test.ts

Comment thread src/lib/onboard.test.ts Outdated
Comment on lines +11 to +25
beforeEach(async () => {
vi.resetModules();
destroyGatewaySpy = vi.fn();
runOpenshellSpy = vi.fn().mockReturnValue({ status: 0 });
runSpy = vi.fn();

vi.mock("../../dist/lib/onboard", async () => {
const actual = await vi.importActual<typeof import("../../dist/lib/onboard")>("../../dist/lib/onboard");
return {
...actual,
destroyGateway: destroyGatewaySpy,
runOpenshell: runOpenshellSpy,
run: runSpy,
};
});

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

cat -n src/lib/onboard.test.ts | head -60

Repository: NVIDIA/NemoClaw

Length of output: 2525


🌐 Web query:

vitest vi.mock hoisting beforeEach vi.doMock

💡 Result:

In Vitest, vi.mock is hoisted to the top of the test file, executing before all imports regardless of where it's called (e.g., inside beforeEach). This ensures the mock applies to static imports but prevents referencing variables defined later in the file scope within the mock factory, as those variables aren't available at hoisting time. To use variables from the test file scope (like counters or test-specific values) in a mock factory, use vi.doMock instead. vi.doMock is not hoisted—it runs when called (e.g., in beforeEach). It only mocks subsequent dynamic imports (await import), not prior static imports. For modules already imported (e.g., static imports at top or cached), call vi.resetModules in beforeEach before vi.doMock to clear caches. vi.hoisted runs code before imports and vi.mock calls, useful for defining shared mocks or values accessible in hoisted vi.mock factories. Example from official docs: import { beforeEach, test, expect } from 'vitest' import { increment } from './increment.js' // Static import: NOT mocked initially let mockedIncrement = 100 beforeEach( => { vi.doMock('./increment.js', => ({ increment: => ++mockedIncrement })) }) test('dynamic import gets mocked version', async => { // Static import remains original expect(increment(1)).toBe(2) // Dynamic import after doMock gets mocked const { increment: mockedIncrement } = await import('./increment.js') expect(mockedIncrement).toBe(101) // Uses outer mockedIncrement }) If mocking affects already-imported modules (e.g., via components), combine with vi.resetModules: beforeEach( => { vi.resetModules // Clears caches vi.doMock('./module', factory) }) vi.mock suits file-wide mocks; vi.doMock for dynamic, scope-aware mocks in hooks like beforeEach. Always use dynamic imports after vi.doMock for the mock to apply.

Citations:


Use vi.doMock instead of vi.mock in beforeEach—vi.mock is hoisted and cannot access the spy variables.

In Vitest, vi.mock() is hoisted to the top of the test file before the beforeEach hook runs, so it cannot reference destroyGatewaySpy, runOpenshellSpy, or runSpy defined in the hook. This causes the ReferenceError: destroyGatewaySpy is not defined error. Use vi.doMock() instead—it executes when called in beforeEach and can safely access hook-scoped variables. The pattern with vi.resetModules() on line 12 is already in place, which is correct for this approach.

Suggested fix
-    vi.mock("../../dist/lib/onboard", async () => {
+    vi.doMock("../../dist/lib/onboard", async () => {
       const actual = await vi.importActual<typeof import("../../dist/lib/onboard")>("../../dist/lib/onboard");
       return {
         ...actual,
         destroyGateway: destroyGatewaySpy,
         runOpenshell: runOpenshellSpy,
         run: runSpy,
       };
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
beforeEach(async () => {
vi.resetModules();
destroyGatewaySpy = vi.fn();
runOpenshellSpy = vi.fn().mockReturnValue({ status: 0 });
runSpy = vi.fn();
vi.mock("../../dist/lib/onboard", async () => {
const actual = await vi.importActual<typeof import("../../dist/lib/onboard")>("../../dist/lib/onboard");
return {
...actual,
destroyGateway: destroyGatewaySpy,
runOpenshell: runOpenshellSpy,
run: runSpy,
};
});
beforeEach(async () => {
vi.resetModules();
destroyGatewaySpy = vi.fn();
runOpenshellSpy = vi.fn().mockReturnValue({ status: 0 });
runSpy = vi.fn();
vi.doMock("../../dist/lib/onboard", async () => {
const actual = await vi.importActual<typeof import("../../dist/lib/onboard")>("../../dist/lib/onboard");
return {
...actual,
destroyGateway: destroyGatewaySpy,
runOpenshell: runOpenshellSpy,
run: runSpy,
};
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 11 - 25, Replace the hoisted vi.mock
call in the beforeEach with vi.doMock so the mock executes at runtime and can
access the locally defined spies; keep vi.resetModules() at the start of the
beforeEach, define destroyGatewaySpy, runOpenshellSpy, and runSpy there, and
then call vi.doMock(...) returning the actual module merged with overrides for
destroyGateway, runOpenshell, and run so the spies are used during tests.

Comment thread src/lib/onboard.test.ts Outdated
Comment on lines +33 to +36
const onboardModule = await import("../../dist/lib/onboard");
const originalPRetry = await vi.importActual<{ default: typeof import("p-retry") }>("p-retry");

const pRetrySpy = vi.spyOn(originalPRetry.default, "default").mockImplementation(async (fn, opts) => {

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the test file at the relevant lines
cat -n src/lib/onboard.test.ts | sed -n '30,55p'

Repository: NVIDIA/NemoClaw

Length of output: 1350


🏁 Script executed:

# Check if dist directory exists and what onboard exports
if [ -d "dist/lib" ]; then
  cat -n dist/lib/onboard.js | head -30
else
  echo "dist not found, checking source instead"
  cat -n src/lib/onboard.ts | head -50
fi

Repository: NVIDIA/NemoClaw

Length of output: 2167


🏁 Script executed:

# Let's check the imports/exports in the source onboard.ts
grep -n "export" src/lib/onboard.ts | head -20

Repository: NVIDIA/NemoClaw

Length of output: 504


🏁 Script executed:

# Check the p-retry module structure in package.json or node_modules
if [ -f "package.json" ]; then
  grep -A2 "p-retry" package.json
fi

Repository: NVIDIA/NemoClaw

Length of output: 145


🏁 Script executed:

# Find the exports in onboard.ts
rg -n "module\.exports|^export\s+" src/lib/onboard.ts | head -20

Repository: NVIDIA/NemoClaw

Length of output: 181


🏁 Script executed:

# Check for a tsconfig.cli.json to see type-checking config
if [ -f "tsconfig.cli.json" ]; then
  echo "=== tsconfig.cli.json ===" 
  cat tsconfig.cli.json
fi

Repository: NVIDIA/NemoClaw

Length of output: 616


🏁 Script executed:

# Let's also check what's in the test file to understand the full context
cat -n src/lib/onboard.test.ts | sed -n '1,70p'

Repository: NVIDIA/NemoClaw

Length of output: 2525


🏁 Script executed:

# Look for p-retry type definitions or how it's used elsewhere
rg -n "p-retry" src/ -A 3 -B 1 | head -40

Repository: NVIDIA/NemoClaw

Length of output: 831


🏁 Script executed:

# Get the full module.exports statement
sed -n '6817,6850p' src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 960


🏁 Script executed:

# Check what properties are exported
rg -n "startGatewayWithOptions" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 283


🏁 Script executed:

# Run type-checking on the test file
cd . && npm run typecheck:cli 2>&1 | grep -A 10 "onboard.test.ts" | head -50

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Check p-retry export structure - look at node_modules types or search online patterns
if [ -f "node_modules/p-retry/package.json" ]; then
  cat node_modules/p-retry/package.json | jq '.exports, .main, .types'
fi

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Continue viewing the full module.exports
sed -n '6817,6900p' src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 2237


🏁 Script executed:

# Verify if startGatewayWithOptions is in the exports list
grep "startGatewayWithOptions" src/lib/onboard.ts | grep -E "module\.exports|^export"

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Let's check how p-retry is actually used in onboard.ts
rg -n "pRetry" src/lib/onboard.ts | head -10

Repository: NVIDIA/NemoClaw

Length of output: 120


🏁 Script executed:

# Try running type-checking directly with a better filter
npx tsc --noEmit --project tsconfig.cli.json 2>&1 | grep "onboard.test" || echo "No errors found for onboard.test.ts"

Repository: NVIDIA/NemoClaw

Length of output: 95


🏁 Script executed:

# Check if startGatewayWithOptions is anywhere in the exports section
grep -n "startGatewayWithOptions" src/lib/onboard.ts | grep -v "^[0-9]*:async function" | grep -v "^[0-9]*:  return"

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Let's verify what the full exports list includes - search for all exports
sed -n '6817,7000p' src/lib/onboard.ts | grep -E "^  [a-zA-Z]"

Repository: NVIDIA/NemoClaw

Length of output: 2378


🏁 Script executed:

# Check the mock setup in the test more carefully - does it export startGatewayWithOptions?
cat -n src/lib/onboard.test.ts | sed -n '17,25p'

Repository: NVIDIA/NemoClaw

Length of output: 439


🏁 Script executed:

# Check p-retry actual export structure - look at its index file
if [ -f "node_modules/p-retry/index.d.ts" ]; then
  head -20 node_modules/p-retry/index.d.ts
elif [ -f "node_modules/p-retry/index.js" ]; then
  head -20 node_modules/p-retry/index.js
fi

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Look at actual p-retry exports more carefully
find node_modules/p-retry -name "*.d.ts" -o -name "index.js" | xargs head -30 2>/dev/null | head -40

Repository: NVIDIA/NemoClaw

Length of output: 115


🏁 Script executed:

# Specifically search for startGatewayWithOptions in exports section
awk '/^module\.exports = \{/,/^\};/' src/lib/onboard.ts | grep -i "startGateway"

Repository: NVIDIA/NemoClaw

Length of output: 102


🏁 Script executed:

# Check if startGatewayWithOptions is actually exported at all
grep -E "^\s+startGatewayWithOptions," src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Check the complete exports list to see if it includes startGatewayWithOptions
sed -n '6817,7100p' src/lib/onboard.ts | tail -50

Repository: NVIDIA/NemoClaw

Length of output: 1317


🏁 Script executed:

# Let's look at how the test will actually work - check the mock behavior
cat -n src/lib/onboard.test.ts | sed -n '15,30p'

Repository: NVIDIA/NemoClaw

Length of output: 570


🏁 Script executed:

# Check what p-retry looks like without node_modules - check package.json for export info
python3 << 'EOF'
import json
with open('package.json') as f:
    data = json.load(f)
    if 'p-retry' in str(data.get('dependencies', {})):
        print("p-retry is a dependency")
        print("Version:", data.get('dependencies', {}).get('p-retry'))
EOF

Repository: NVIDIA/NemoClaw

Length of output: 99


🏁 Script executed:

# Check if startGatewayWithOptions is explicitly NOT in the exports
sed -n '6817,7100p' src/lib/onboard.ts | grep -c "startGatewayWithOptions"

Repository: NVIDIA/NemoClaw

Length of output: 61


🏁 Script executed:

# Verify what happens when we access startGatewayWithOptions - is it even exported?
rg "^\s+startGatewayWithOptions" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Let's check the complete mock - what does it return?
cat -n src/lib/onboard.test.ts | sed -n '17,50p'

Repository: NVIDIA/NemoClaw

Length of output: 1682


🏁 Script executed:

# Check if there's a build script or dist output
ls -la dist/ 2>/dev/null || echo "dist directory does not exist"
npm run build 2>&1 | head -5 || echo "Build script not available"

Repository: NVIDIA/NemoClaw

Length of output: 311


🏁 Script executed:

# Let's verify the exact type-checking output for the test file
npx tsc --noEmit --project tsconfig.cli.json src/lib/onboard.test.ts 2>&1 || echo "Type-check completed"

Repository: NVIDIA/NemoClaw

Length of output: 164


🏁 Script executed:

# Let's check the npm scripts to understand the build/test setup
npm run 2>&1 | head -30

Repository: NVIDIA/NemoClaw

Length of output: 1372


🏁 Script executed:

# Check if there are any type errors in the test file at all - let's be more explicit
npx tsc --noEmit --project tsconfig.cli.json 2>&1 | grep -E "error|warning" | head -20

Repository: NVIDIA/NemoClaw

Length of output: 118


🏁 Script executed:

# Let's manually check the type resolution for onboardModule - what shape does it have?
npx tsc --noEmit --project tsconfig.cli.json --listFilesOnly 2>&1 | grep onboard || echo "No onboard files listed"

Repository: NVIDIA/NemoClaw

Length of output: 718


🏁 Script executed:

# Check p-retry types - what does the import resolve to?
python3 << 'EOF'
import json
import subprocess
import sys

# Try to understand p-retry's export structure from package.json
try:
    result = subprocess.run(['npm', 'ls', 'p-retry', '--depth=0', '--json'], 
                          capture_output=True, text=True, timeout=10)
    if result.returncode == 0:
        data = json.loads(result.stdout)
        print("p-retry location:", data.get('dependencies', {}).get('p-retry', {}).get('resolved'))
except Exception as e:
    print(f"Could not check p-retry: {e}")
    
# Also check if there's a .d.ts that we can examine
import os
for root, dirs, files in os.walk('node_modules/.pnpm' if os.path.exists('node_modules/.pnpm') else 'node_modules'):
    if 'p-retry' in root:
        print(f"Found p-retry at: {root}")
        for f in files[:5]:
            print(f"  - {f}")
        break
EOF

Repository: NVIDIA/NemoClaw

Length of output: 41


🏁 Script executed:

# Key question: is startGatewayWithOptions a function that exists but isn't exported?
grep -n "^async function startGatewayWithOptions\|^function startGatewayWithOptions" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 142


🏁 Script executed:

# Check if startGatewayWithOptions is actually supposed to be exported
# Let's look for any recent additions or patterns
grep -B5 -A5 "startGatewayWithOptions" src/lib/onboard.ts | head -30

Repository: NVIDIA/NemoClaw

Length of output: 987


🏁 Script executed:

# Verify the p-retry export pattern by checking TypeScript definitions
# Since node_modules doesn't exist in sandbox, let's search for how p-retry is used
rg -B2 -A2 "pRetry\(" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 200


🏁 Script executed:

# Let's check what the actual interface signature should be - look at imports in test
cat -n src/lib/onboard.test.ts | head -10

Repository: NVIDIA/NemoClaw

Length of output: 552


🏁 Script executed:

# The critical question: when the test runs, will it have access to startGatewayWithOptions?
# Let's trace through the mock - what does the mock actually provide?
cat src/lib/onboard.test.ts | grep -A 20 "vi.mock"

Repository: NVIDIA/NemoClaw

Length of output: 851


🏁 Script executed:

# Check if perhaps the test is new and startGatewayWithOptions was recently added to exports
git log --oneline -n 20 -- src/lib/onboard.ts 2>/dev/null | head -10 || echo "Git history not available"

Repository: NVIDIA/NemoClaw

Length of output: 114


🏁 Script executed:

# Double-check: is startGatewayWithOptions in the complete module.exports?
sed -n '6817,7200p' src/lib/onboard.ts | grep -i "startGateway"

Repository: NVIDIA/NemoClaw

Length of output: 102


🏁 Script executed:

# Check what the mock actually returns - trace through carefully
cat src/lib/onboard.test.ts | grep -A 30 "vi.mock"

Repository: NVIDIA/NemoClaw

Length of output: 1339


🏁 Script executed:

# Now verify p-retry type structure - how is it actually meant to be used?
web_search "p-retry npm javascript export structure named vs default"

Repository: NVIDIA/NemoClaw

Length of output: 110


🌐 Web query:

p-retry npm export structure default named export CommonJS ESM

💡 Result:

For p-retry (the main package, not the cjs fork), the export shape is: 1) It is ESM-only (package sets "type": "module"). 2) It uses the package.json "exports" map with a named key "default" pointing to ./index.js. 3) Therefore, the intended import is a default import in ESM: import pRetry, {AbortError} from 'p-retry'; 4) In CommonJS, require('p-retry') will fail because the package is ESM-only; you must use dynamic import: const {default: pRetry, AbortError} = await import('p-retry'); // or: const pRetry = (await import('p-retry')).default Notes on “named export default vs named exports”: - The “default” mentioned in package.json exports is the ESM default export, so it supports importing the default binding (pRetry) with import pRetry from 'p-retry'. - p-retry also provides named exports like AbortError, so import {AbortError} from 'p-retry' is valid. If you specifically need CommonJS without dynamic import, there is a separate fork/package published as p-retry-cjs described as a CommonJS fork of p-retry.

Citations:


Export startGatewayWithOptions and fix the p-retry spy target.

Line 49 calls onboardModule.startGatewayWithOptions, but this function is not in the module exports—only startGateway and startGatewayForRecovery are exported. Line 36 spies on originalPRetry.default.default, which is incorrect because originalPRetry.default is already the pRetry function (ESM default export); there is no .default property on the function itself.

Suggested fix
  1. Add startGatewayWithOptions to the module.exports in src/lib/onboard.ts (around line 6817).
  2. Fix the p-retry spy:
-    const originalPRetry = await vi.importActual<{ default: typeof import("p-retry") }>("p-retry");
-    const pRetrySpy = vi.spyOn(originalPRetry.default, "default").mockImplementation(async (fn, opts) => {
+    const pRetryModule = await vi.importActual<typeof import("p-retry")>("p-retry");
+    const pRetrySpy = vi.spyOn(pRetryModule, "default").mockImplementation(async (fn, opts) => {
🧰 Tools
🪛 GitHub Actions: macos-e2e

[error] 33-35: [vitest] There was an error when mocking a module (vi.mock hoisting). Caused by ReferenceError: destroyGatewaySpy is not defined.

🪛 GitHub Check: macos-e2e

[failure] 33-33: [cli] src/lib/onboard.test.ts > lib/onboard — gateway cleanup on final failure > calls destroyGateway() when gateway start fails after exhausting retries
Error: [vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock
❯ src/lib/onboard.test.ts:33:27

Caused by: Caused by: ReferenceError: destroyGatewaySpy is not defined
❯ src/lib/onboard.test.ts:21:25
❯ src/lib/onboard.test.ts:33:27

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 33 - 36, Add the missing export and
correct the p-retry spy target: export the function startGatewayWithOptions from
the onboard module by adding it to module.exports alongside startGateway and
startGatewayForRecovery (so tests can call
onboardModule.startGatewayWithOptions), and change the spy setup in the test to
target the actual p-retry function (remove the erroneous extra .default)—i.e.,
spy on originalPRetry.default (or use vi.spyOn(originalPRetry, "default"))
instead of originalPRetry.default.default so the mock wraps the real p-retry
function.

Comment thread src/lib/onboard.test.ts
Comment on lines +48 to +52
try {
await onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true });
} catch {
expect(destroyGatewaySpy).toHaveBeenCalled();
}

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.

⚠️ Potential issue | 🟠 Major

Avoid assertion-only-in-catch; this can pass without validating behavior.

If Line 49 stops throwing, this test can pass without any assertion. Assert rejection explicitly, then assert destroyGatewaySpy call.

Suggested fix
-    try {
-      await onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true });
-    } catch {
-      expect(destroyGatewaySpy).toHaveBeenCalled();
-    }
+    await expect(
+      onboardModule.default.startGatewayWithOptions(gpu, { exitOnFailure: true }),
+    ).rejects.toThrow();
+    expect(destroyGatewaySpy).toHaveBeenCalled();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
await onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true });
} catch {
expect(destroyGatewaySpy).toHaveBeenCalled();
}
await expect(
onboardModule.default.startGatewayWithOptions(gpu, { exitOnFailure: true }),
).rejects.toThrow();
expect(destroyGatewaySpy).toHaveBeenCalled();
🧰 Tools
🪛 GitHub Check: checks

[failure] 49-49:
Property 'startGatewayWithOptions' does not exist on type '{ default: typeof import("/home/runner/work/NemoClaw/NemoClaw/dist/lib/onboard"); }'.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 48 - 52, The test currently only
asserts inside a catch block which can silently pass if startGatewayWithOptions
stops throwing; change it to explicitly assert the promise rejects and then
verify cleanup: use an explicit rejection assertion against
onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true }) (e.g.,
expect(...).rejects.toThrow()/rejects.toBeDefined()) and after that assertion
verify destroyGatewaySpy was called; keep references to
onboardModule.startGatewayWithOptions and destroyGatewaySpy so the test both
asserts failure and that cleanup ran.

@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.

♻️ Duplicate comments (2)
src/lib/onboard.test.ts (2)

46-50: ⚠️ Potential issue | 🟠 Major

Avoid assertion-only-in-catch; enforce rejection explicitly.

Lines 46-50 can pass without asserting anything if the call stops throwing. Assert the rejection first, then assert cleanup.

Suggested patch
-    try {
-      await onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true });
-    } catch {
-      expect(destroyGatewayMock).toHaveBeenCalled();
-    }
+    await expect(
+      onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true }),
+    ).rejects.toThrow();
+    expect(destroyGatewayMock).toHaveBeenCalled();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 46 - 50, The test currently only
asserts inside the catch block which can falsely pass if no error is thrown;
change it to explicitly assert the promise rejects by using Jest's await
expect(onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true
})).rejects.toThrow() (or .rejects.toBeDefined()/match specific error) and after
that assertion verify destroyGatewayMock was called; ensure references to
startGatewayWithOptions and destroyGatewayMock (and the gpu fixture) are used so
the test both enforces rejection and checks cleanup.

32-35: ⚠️ Potential issue | 🔴 Critical

Fix the p-retry spy target (default.default is incorrect).

Line 34 currently spies on a nested default property, which can fail at runtime and prevent this test from validating retry cleanup behavior.

Suggested patch
-    const originalPRetry = await vi.importActual<{ default: typeof import("p-retry") }>("p-retry");
+    const pRetryModule = await vi.importActual<typeof import("p-retry")>("p-retry");

-    const pRetrySpy = vi.spyOn(originalPRetry.default, "default").mockImplementation(async (fn, opts) => {
+    const pRetrySpy = vi.spyOn(pRetryModule, "default").mockImplementation(async (_fn, opts) => {

As per coding guidelines **/*.{js,ts,tsx}: Unused variables must be prefixed with underscore (_) to indicate intentional non-use.

For Vitest 4.1.0 and p-retry 4.6.2, what is the correct `vi.spyOn` target after `await vi.importActual("p-retry")`? Please include the module export shape and whether `module.default.default` is valid.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 32 - 35, The test is spying on the
wrong property (using originalPRetry.default.default); after await
vi.importActual("p-retry") the module object exposes the default export as
module.default (a function), so change the spy to vi.spyOn(originalPRetry,
"default") instead of vi.spyOn(originalPRetry.default, "default") and adjust the
mockImplementation target accordingly (update the pRetrySpy reference and any
type annotations around originalPRetry/importActual); also rename any
intentionally unused variables to start with an underscore per the lint rule.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/lib/onboard.test.ts`:
- Around line 46-50: The test currently only asserts inside the catch block
which can falsely pass if no error is thrown; change it to explicitly assert the
promise rejects by using Jest's await
expect(onboardModule.startGatewayWithOptions(gpu, { exitOnFailure: true
})).rejects.toThrow() (or .rejects.toBeDefined()/match specific error) and after
that assertion verify destroyGatewayMock was called; ensure references to
startGatewayWithOptions and destroyGatewayMock (and the gpu fixture) are used so
the test both enforces rejection and checks cleanup.
- Around line 32-35: The test is spying on the wrong property (using
originalPRetry.default.default); after await vi.importActual("p-retry") the
module object exposes the default export as module.default (a function), so
change the spy to vi.spyOn(originalPRetry, "default") instead of
vi.spyOn(originalPRetry.default, "default") and adjust the mockImplementation
target accordingly (update the pRetrySpy reference and any type annotations
around originalPRetry/importActual); also rename any intentionally unused
variables to start with an underscore per the lint rule.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: df5a97f4-3578-4f9c-b982-1992f1650960

📥 Commits

Reviewing files that changed from the base of the PR and between ffb3021 and 7d80df6.

📒 Files selected for processing (1)
  • src/lib/onboard.test.ts

CodeRabbit flagged the test for having assertions only inside catch.
Added a 'threw' flag to verify the function throws, then assert
destroyGateway was called — both assertions are now outside catch.

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

♻️ Duplicate comments (1)
src/lib/onboard.test.ts (1)

34-34: ⚠️ Potential issue | 🔴 Critical

Fix p-retry spy target — current spyOn target is incorrect.

On Line 34, vi.spyOn(originalPRetry.default, "default") tries to spy on a default property of the default export value. Spy the module namespace’s default export instead.

Suggested fix
-    const originalPRetry = await vi.importActual<{ default: typeof import("p-retry") }>("p-retry");
+    const pRetryModule = await vi.importActual<typeof import("p-retry")>("p-retry");

-    const pRetrySpy = vi.spyOn(originalPRetry.default, "default").mockImplementation(async (fn, opts) => {
+    const pRetrySpy = vi.spyOn(pRetryModule, "default").mockImplementation(async (fn, opts) => {
In Vitest, when using `const mod = await vi.importActual<typeof import("p-retry")>("p-retry")`, what is the correct `vi.spyOn` target to mock the default export?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` at line 34, The p-retry spy is targeting the wrong
property; change the spy target from the nested "default" property to the module
namespace's default export by calling vi.spyOn on originalPRetry (not
originalPRetry.default) — i.e., replace vi.spyOn(originalPRetry.default,
"default") with vi.spyOn(originalPRetry, "default") and keep the
mockImplementation used for pRetrySpy so the default export is properly mocked;
locate the change where pRetrySpy is declared in src/lib/onboard.test.ts
referencing originalPRetry.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/onboard.test.ts`:
- Around line 37-39: The mock p-retry in the onboard.test.ts should await the
onFailedAttempt callback to mirror real p-retry behavior; update the mock where
it invokes onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0,
(opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" }) to use
await so async handlers are supported and the mock matches the library contract
(reference the onFailedAttempt identifier and the surrounding
attempt/opts?.retries logic in the test).

---

Duplicate comments:
In `@src/lib/onboard.test.ts`:
- Line 34: The p-retry spy is targeting the wrong property; change the spy
target from the nested "default" property to the module namespace's default
export by calling vi.spyOn on originalPRetry (not originalPRetry.default) —
i.e., replace vi.spyOn(originalPRetry.default, "default") with
vi.spyOn(originalPRetry, "default") and keep the mockImplementation used for
pRetrySpy so the default export is properly mocked; locate the change where
pRetrySpy is declared in src/lib/onboard.test.ts referencing originalPRetry.
🪄 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: 08711c56-4c6c-4a35-8f68-93383002ea08

📥 Commits

Reviewing files that changed from the base of the PR and between 7d80df6 and d10a813.

📒 Files selected for processing (1)
  • src/lib/onboard.test.ts

Comment thread src/lib/onboard.test.ts Outdated
Comment on lines +37 to +39
if (onFailedAttempt) {
onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
}

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Does p-retrysupport asynconFailedAttempt handlers, and should callers await it in custom retry mocks?

💡 Result:

Yes, p-retry supports async onFailedAttempt handlers. The official documentation explicitly states that the onFailedAttempt function can return a promise, and provides an example using an async function with await delay(1000). p-retry awaits the promise returned by onFailedAttempt before proceeding to the next retry attempt, as confirmed in the GitHub README and resolved discussions around async support (e.g., historical issues confirming promise awaiting behavior). For custom retry mocks imitating p-retry, callers should await the onFailedAttempt handler if it returns a promise. This ensures sequential execution matching p-retry's behavior, where the handler completes (including any async operations like delays or token refreshes) before the retry logic continues. Non-awaiting could lead to parallel or premature retries, as noted in early GitHub issues.

Citations:


🏁 Script executed:

cat -n src/lib/onboard.test.ts | head -60

Repository: NVIDIA/NemoClaw

Length of output: 2572


🏁 Script executed:

rg -A 5 -B 5 "onFailedAttempt" src/lib/onboard.test.ts

Repository: NVIDIA/NemoClaw

Length of output: 821


🏁 Script executed:

grep -r "p-retry\|p-retries" --include="*.ts" --include="*.js" src/ | head -20

Repository: NVIDIA/NemoClaw

Length of output: 237


🏁 Script executed:

cat -n src/lib/onboard.ts | head -100

Repository: NVIDIA/NemoClaw

Length of output: 4060


🏁 Script executed:

rg -A 10 "onFailedAttempt" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 365


🏁 Script executed:

rg -B 5 -A 10 "function destroyGateway|const destroyGateway|exports.destroyGateway" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 626


🏁 Script executed:

rg -B 2 -A 8 "destroyGateway()" src/lib/onboard.ts | head -30

Repository: NVIDIA/NemoClaw

Length of output: 1105


🏁 Script executed:

rg -B 3 -A 8 "function runOpenshell|const runOpenshell|exports.runOpenshell" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 355


🏁 Script executed:

grep -r "function runOpenshell\|const runOpenshell\|exports.runOpenshell" src/ --include="*.ts" --include="*.js"

Repository: NVIDIA/NemoClaw

Length of output: 234


🏁 Script executed:

cat -n src/lib/runner.ts | head -50

Repository: NVIDIA/NemoClaw

Length of output: 2035


🏁 Script executed:

rg -B 2 -A 8 "^function run\(|^const run = |^exports.run" src/lib/runner.ts | head -30

Repository: NVIDIA/NemoClaw

Length of output: 353


Mock p-retry implementation should await onFailedAttempt to match actual library behavior.

The test mock on lines 37–39 calls onFailedAttempt without await. While the current production handler is synchronous, the real p-retry library awaits this callback, and the mock should replicate that behavior to ensure correctness if handlers become async in future versions or to properly simulate the library's contract.

Suggested fix
-        if (onFailedAttempt) {
-          onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
-        }
+        if (onFailedAttempt) {
+          await onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (onFailedAttempt) {
onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
}
if (onFailedAttempt) {
await onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 37 - 39, The mock p-retry in the
onboard.test.ts should await the onFailedAttempt callback to mirror real p-retry
behavior; update the mock where it invokes onFailedAttempt({ attemptNumber:
attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message:
"Gateway start failed" }) to use await so async handlers are supported and the
mock matches the library contract (reference the onFailedAttempt identifier and
the surrounding attempt/opts?.retries logic in the test).

…mock to match library behaviorentation in tests

Fix syntax error in onFailedAttempt callback
… to match cleanup-on-every-failure behaviory startup

Removed unnecessary error message and updated troubleshooting instructions.
@Sayeem3051

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
src/lib/onboard.ts (1)

3108-3133: ⚠️ Potential issue | 🟠 Major

Don't report cleanup success before cleanup has actually succeeded.

This branch prints Gateway cleanup completed after failed start. before calling destroyGateway(), but destroyGateway() currently swallows gateway destroy / Docker-volume cleanup failures and does not report whether cleanup worked. That can tell users the stale-volume fix succeeded even when the next rerun will still fail for the same reason. Please either move the success message behind a verified cleanup result, or print the exact manual recovery commands when cleanup cannot be confirmed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` around lines 3108 - 3133, The code currently logs
"Gateway cleanup completed after failed start." before calling destroyGateway(),
which may hide cleanup failures; change destroyGateway() (or wrap its call here)
to return or throw a boolean/success result and only print the "cleanup
completed" message after successful completion, otherwise print explicit manual
recovery commands (e.g., the Docker/volume removal steps) and the failure
details; update the block that references GATEWAY_NAME, retries and ANSI_RE to
call await destroyGateway() (or check its return) and conditionally log success
vs. the manual instructions/runCaptureOpenshell output so users see accurate
cleanup status.
♻️ Duplicate comments (2)
src/lib/onboard.test.ts (2)

47-47: ⚠️ Potential issue | 🔴 Critical

Call an exported entry point here.

src/lib/onboard.ts does not export startGatewayWithOptions, so onboardModule.startGatewayWithOptions(...) does not match the imported module shape. Either exercise the public startGateway() wrapper here or add the helper to module.exports before testing it directly. As per coding guidelines, src/**/*.ts: CLI type-checking must pass via tsconfig.cli.json (run npm run typecheck:cli).

#!/bin/bash
rg -n "async function startGatewayWithOptions|module\\.exports|startGateway,|startGatewayForRecovery," src/lib/onboard.ts src/lib/onboard.test.ts -A2 -B2
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` at line 47, The test calls startGatewayWithOptions
which isn't exported; either change the test to call the public exported wrapper
startGateway (so replace onboardModule.startGatewayWithOptions(...) with
onboardModule.startGateway(...)) or export the helper by adding
startGatewayWithOptions to the module's exports/exports object (ensuring the
symbol name matches the implementation) so the import shape is correct; after
the change run the CLI type-check (npm run typecheck:cli) to ensure
tsconfig.cli.json passes.

32-42: ⚠️ Potential issue | 🔴 Critical

Fix the p-retry mock syntax and spy target.

This block does not parse (const { onFailedAttempt({ } ..., if (onFailedAttempt({)), and vi.spyOn(originalPRetry.default, "default") is aiming at a property on the retry function instead of the module namespace. The test will not type-check or run until both are corrected. As per coding guidelines, src/**/*.ts: CLI type-checking must pass via tsconfig.cli.json (run npm run typecheck:cli).

Suggested fix
-    const originalPRetry = await vi.importActual<{ default: typeof import("p-retry") }>("p-retry");
-
-    const pRetrySpy = vi.spyOn(originalPRetry.default, "default").mockImplementation(async (fn, opts) => {
-      const { onFailedAttempt({ } = opts || {};
+    const pRetryModule = await vi.importActual<typeof import("p-retry")>("p-retry");
+
+    const pRetrySpy = vi.spyOn(pRetryModule, "default").mockImplementation(async (_fn, opts) => {
+      const { onFailedAttempt } = opts ?? {};
       for (let attempt = 1; attempt <= (opts?.retries ?? 2) + 1; attempt++) {
-        if (onFailedAttempt({) {
-    await       onFailedAttempt({ attemptNumber: attempt, retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt), message: "Gateway start failed" } as Error & { attemptNumber: number; retriesLeft: number });
+        if (onFailedAttempt) {
+          await onFailedAttempt({
+            attemptNumber: attempt,
+            retriesLeft: Math.max(0, (opts?.retries ?? 2) + 1 - attempt),
+            message: "Gateway start failed",
+          } as Error & { attemptNumber: number; retriesLeft: number });
         }
       }
       throw new Error("Gateway failed to start");
     });
#!/bin/bash
sed -n '32,42p' src/lib/onboard.test.ts
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 32 - 42, The p-retry mock has broken
syntax and the spy targets the wrong object: replace the malformed destructuring
and conditionals with "const { onFailedAttempt } = opts || {};" and "if
(onFailedAttempt) { await onFailedAttempt({...}) }", and change the spy target
from vi.spyOn(originalPRetry.default, 'default') to vi.spyOn(originalPRetry,
'default') so you spy the module's default export; keep the mockImplementation
body that loops attempts and throws the final error, referencing pRetrySpy and
onFailedAttempt exactly as shown.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/onboard.test.ts`:
- Around line 6-14: The test is mocking exported properties on
../../dist/lib/onboard but startGatewayWithOptions uses local bindings, so
replacing exports doesn't change what it calls, and startGatewayWithOptions
isn't exported; to fix, either (A) change the test to import the source module
(src/lib/onboard) and refactor the module under test to export
startGatewayWithOptions so the test can import and stub or spy on its internals
(destroyGateway, runOpenshell, run) with vi.spyOn/vi.fn, or (B) refactor
startGatewayWithOptions to accept the three functions (destroyGateway,
runOpenshell, run) as injectable parameters or move those calls into separate
exported helpers you can mock; additionally fix the malformed TypeScript in the
test file (unclosed/mismatched braces around the block at lines 34–42) so it
type-checks. Ensure references to startGatewayWithOptions, destroyGateway,
runOpenshell, run, startGateway, and startGatewayForRecovery are used to locate
the correct symbols.

In `@src/lib/onboard.ts`:
- Line 3131: Replace the misspelled recovery command string in the console.error
call: change the literal "  nemoclau onboard" to the correct command " 
nemoclaus onboard" in the console.error invocation so copy-pasting the
troubleshooting command works (locate the console.error call in onboard.ts and
update the string).

---

Outside diff comments:
In `@src/lib/onboard.ts`:
- Around line 3108-3133: The code currently logs "Gateway cleanup completed
after failed start." before calling destroyGateway(), which may hide cleanup
failures; change destroyGateway() (or wrap its call here) to return or throw a
boolean/success result and only print the "cleanup completed" message after
successful completion, otherwise print explicit manual recovery commands (e.g.,
the Docker/volume removal steps) and the failure details; update the block that
references GATEWAY_NAME, retries and ANSI_RE to call await destroyGateway() (or
check its return) and conditionally log success vs. the manual
instructions/runCaptureOpenshell output so users see accurate cleanup status.

---

Duplicate comments:
In `@src/lib/onboard.test.ts`:
- Line 47: The test calls startGatewayWithOptions which isn't exported; either
change the test to call the public exported wrapper startGateway (so replace
onboardModule.startGatewayWithOptions(...) with onboardModule.startGateway(...))
or export the helper by adding startGatewayWithOptions to the module's
exports/exports object (ensuring the symbol name matches the implementation) so
the import shape is correct; after the change run the CLI type-check (npm run
typecheck:cli) to ensure tsconfig.cli.json passes.
- Around line 32-42: The p-retry mock has broken syntax and the spy targets the
wrong object: replace the malformed destructuring and conditionals with "const {
onFailedAttempt } = opts || {};" and "if (onFailedAttempt) { await
onFailedAttempt({...}) }", and change the spy target from
vi.spyOn(originalPRetry.default, 'default') to vi.spyOn(originalPRetry,
'default') so you spy the module's default export; keep the mockImplementation
body that loops attempts and throws the final error, referencing pRetrySpy and
onFailedAttempt exactly as shown.
🪄 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: 1f304ad0-1d49-418f-942a-e94b402e9c90

📥 Commits

Reviewing files that changed from the base of the PR and between 7d80df6 and 7e54688.

📒 Files selected for processing (2)
  • src/lib/onboard.test.ts
  • src/lib/onboard.ts

Comment thread src/lib/onboard.test.ts
Comment on lines +6 to +14
vi.mock("../../dist/lib/onboard", async () => {
const actual = await vi.importActual<typeof import("../../dist/lib/onboard")>("../../dist/lib/onboard");
return {
...actual,
destroyGateway: vi.fn(),
runOpenshell: vi.fn().mockReturnValue({ status: 0 }),
run: vi.fn(),
};
});

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n "function destroyGateway|function runOpenshell|async function startGatewayWithOptions|destroyGateway\\(|runOpenshell\\(|run\\(" src/lib/onboard.ts -A3 -B2

Repository: NVIDIA/NemoClaw

Length of output: 14478


🏁 Script executed:

#!/bin/bash
# Check what is exported from src/lib/onboard.ts and look at the test file
cat -n src/lib/onboard.test.ts | head -100

Repository: NVIDIA/NemoClaw

Length of output: 2582


🏁 Script executed:

#!/bin/bash
# Check export statements in src/lib/onboard.ts
rg -n "^export" src/lib/onboard.ts | head -20

Repository: NVIDIA/NemoClaw

Length of output: 157


🏁 Script executed:

#!/bin/bash
# Check if startGatewayWithOptions is exported
rg -n "startGatewayWithOptions" src/lib/onboard.ts

Repository: NVIDIA/NemoClaw

Length of output: 283


🏁 Script executed:

#!/bin/bash
# Look for all export/module.exports statements in src/lib/onboard.ts
rg -n "export|module\.exports" src/lib/onboard.ts | tail -30

Repository: NVIDIA/NemoClaw

Length of output: 504


🏁 Script executed:

#!/bin/bash
# Check the end of src/lib/onboard.ts to see what is exported
tail -100 src/lib/onboard.ts | cat -n

Repository: NVIDIA/NemoClaw

Length of output: 3311


🏁 Script executed:

#!/bin/bash
# Look for export statements around startGateway
rg -n "startGateway" src/lib/onboard.ts | grep -E "export|function startGateway"

Repository: NVIDIA/NemoClaw

Length of output: 235


Mocking ../../dist/lib/onboard won't intercept this cleanup path, and startGatewayWithOptions() is not exported.

startGatewayWithOptions() calls local destroyGateway, runOpenshell, and run bindings from src/lib/onboard.ts. Replacing those names on the exported module object does not change what the function under test executes. Additionally, startGatewayWithOptions is not in the module exports (only startGateway and startGatewayForRecovery are exported), so this test will fail at runtime.

Lines 34–42 also contain malformed TypeScript syntax that will prevent the file from type-checking via tsconfig.cli.json (e.g., line 35 has an unclosed brace, line 37 has unmatched braces).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.test.ts` around lines 6 - 14, The test is mocking exported
properties on ../../dist/lib/onboard but startGatewayWithOptions uses local
bindings, so replacing exports doesn't change what it calls, and
startGatewayWithOptions isn't exported; to fix, either (A) change the test to
import the source module (src/lib/onboard) and refactor the module under test to
export startGatewayWithOptions so the test can import and stub or spy on its
internals (destroyGateway, runOpenshell, run) with vi.spyOn/vi.fn, or (B)
refactor startGatewayWithOptions to accept the three functions (destroyGateway,
runOpenshell, run) as injectable parameters or move those calls into separate
exported helpers you can mock; additionally fix the malformed TypeScript in the
test file (unclosed/mismatched braces around the block at lines 34–42) so it
type-checks. Ensure references to startGatewayWithOptions, destroyGateway,
runOpenshell, run, startGateway, and startGatewayForRecovery are used to locate
the correct symbols.

Comment thread src/lib/onboard.ts Outdated
console.error(" Troubleshooting:");
console.error(" openshell doctor logs --name nemoclaw");
console.error(" openshell doctor check");
console.error(" nemoclau onboard");

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.

⚠️ Potential issue | 🟡 Minor

Fix the recovery command typo.

nemoclau onboard is misspelled here, so copy-pasting the troubleshooting command will fail.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` at line 3131, Replace the misspelled recovery command
string in the console.error call: change the literal "  nemoclau onboard" to the
correct command "  nemoclaus onboard" in the console.error invocation so
copy-pasting the troubleshooting command works (locate the console.error call in
onboard.ts and update the string).

…very command troubleshooting textn onboard.ts
…after destroyGateway() callor message

Remove duplicate error message for gateway cleanup.
@Sayeem3051

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

♻️ Duplicate comments (1)
src/lib/onboard.ts (1)

3131-3131: ⚠️ Potential issue | 🟡 Minor

Fix the recovery command typo.

nemoclau onboard is still misspelled, so the one troubleshooting command shown here cannot be copy-pasted successfully.

✏️ Proposed fix
-              console.error("  nemoclau onboard");
+              console.error("  nemoclaw onboard");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` at line 3131, The printed recovery/troubleshooting string
is misspelled—update the console.error call that currently prints "  nemoclau
onboard" in src/lib/onboard.ts to the correct command string ("  nemoclave
onboard"); locate the console.error invocation (search for the literal "nemoclau
onboard") and replace the typo so the message is copy-pasteable and accurate.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/onboard.ts`:
- Around line 3132-3133: The console message "Gateway cleanup completed after
failed start." claims success unconditionally even though destroyGateway() is
best-effort and may fail; change the flow so destroyGateway() returns a
boolean/enum indicating whether gateway destroy and volume cleanup both
succeeded, have the caller check that result, and log either a success message
or a failure message that includes the exact manual recovery command suggested
in the acceptance criteria; update the destroyGateway() signature and its call
site to act on the returned status and include the manual recovery instructions
when cleanup failed.

---

Duplicate comments:
In `@src/lib/onboard.ts`:
- Line 3131: The printed recovery/troubleshooting string is misspelled—update
the console.error call that currently prints "  nemoclau onboard" in
src/lib/onboard.ts to the correct command string ("  nemoclave onboard"); locate
the console.error invocation (search for the literal "nemoclau onboard") and
replace the typo so the message is copy-pasteable and accurate.
🪄 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: ab2256c6-7cc4-4bc2-99b5-16cf9d21cf09

📥 Commits

Reviewing files that changed from the base of the PR and between 7e54688 and 005fa20.

📒 Files selected for processing (1)
  • src/lib/onboard.ts

Comment thread src/lib/onboard.ts Outdated
Comment on lines +3132 to +3133
destroyGateway();
console.error(" Gateway cleanup completed after failed start.");

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.

⚠️ Potential issue | 🟠 Major

Don't claim cleanup succeeded unconditionally.

destroyGateway() is best-effort and currently swallows failures, so this branch can report success even when the stale gateway volumes are still present. That also misses the exact manual recovery command the issue acceptance calls for.

🛠 Suggested direction
-              destroyGateway();
-              console.error(" Gateway cleanup completed after failed start.");
+              const cleanupOk = destroyGateway();
+              if (cleanupOk) {
+                console.error("  Gateway cleanup completed after failed start.");
+              } else {
+                console.error("  Automatic gateway cleanup failed.");
+                console.error("  Recovery:");
+                console.error("    openshell gateway destroy -g nemoclaw");
+                console.error(
+                  '    docker volume ls -q --filter "name=openshell-cluster-nemoclaw" | xargs -r docker volume rm',
+                );
+              }

And update destroyGateway() to return whether both the gateway destroy and volume cleanup succeeded.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` around lines 3132 - 3133, The console message "Gateway
cleanup completed after failed start." claims success unconditionally even
though destroyGateway() is best-effort and may fail; change the flow so
destroyGateway() returns a boolean/enum indicating whether gateway destroy and
volume cleanup both succeeded, have the caller check that result, and log either
a success message or a failure message that includes the exact manual recovery
command suggested in the acceptance criteria; update the destroyGateway()
signature and its call site to act on the returned status and include the manual
recovery instructions when cleanup failed.

… print recovery commands on failure boolean status

Change destroyGateway function to return a boolean indicating success or failure. Update error handling to reflect the new return value.
@Sayeem3051

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Sayeem3051

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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.

♻️ Duplicate comments (2)
src/lib/onboard.ts (2)

2101-2114: ⚠️ Potential issue | 🟠 Major

Return the real cleanup status from destroyGateway().

The new caller branches on cleanupOk, but this implementation always returns true. If openshell gateway destroy or the volume cleanup fails, the code will still report success and skip the manual recovery path.

🛠 Suggested direction
 function destroyGateway(): boolean {
   const destroyResult = runOpenshell(["gateway", "destroy", "-g", GATEWAY_NAME], {
     ignoreError: true,
   });
   // Clear the local registry so `nemoclaw list` stays consistent with OpenShell state. (`#532`)
   if (destroyResult.status === 0) {
     registry.clearAll();
   }
   // openshell gateway destroy doesn't remove Docker volumes, which leaves
   // corrupted cluster state that breaks the next gateway start. Clean them up.
-  dockerRemoveVolumesByPrefix(`openshell-cluster-${GATEWAY_NAME}`, { ignoreError: true });
-    
-    return true;
+  const volumeCleanupResult = dockerRemoveVolumesByPrefix(
+    `openshell-cluster-${GATEWAY_NAME}`,
+    { ignoreError: true },
+  );
+
+  return destroyResult.status === 0 && volumeCleanupResult.status === 0;
 
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` around lines 2101 - 2114, destroyGateway() currently
always returns true even when runOpenshell(["gateway","destroy"...]) or
dockerRemoveVolumesByPrefix fails; update it to return the real cleanup status
by checking the return values of runOpenshell (inspect destroyResult.status) and
dockerRemoveVolumesByPrefix (capture its result/throw) and return true only if
both succeeded (and still call registry.clearAll() only when
destroyResult.status === 0). If dockerRemoveVolumesByPrefix returns a result
object, treat non-zero/failure as failure; if it throws on error, catch it and
treat as failure, then return false so callers can handle the cleanupOk branch
correctly.

3049-3058: ⚠️ Potential issue | 🟠 Major

Fix the recovery commands before release.

These are the commands users will copy-paste on failure, but they currently point at nemoclau / openshell-cluster-nemoclau, and the Docker command only lists volumes instead of removing them. That breaks the fallback path this PR is adding.

🛠 Suggested fix
       console.error("  Troubleshooting:");
-              console.error("  nemoclau onboard");
-                      const cleanupOk = destroyGateway();
+      console.error("    nemoclaw onboard");
+      const cleanupOk = destroyGateway();
       if (cleanupOk) {
-            console.error(" Gateway cleanup completed after failed start.");
+        console.error("  Gateway cleanup completed after failed start.");
       } else {
-            console.error("  Automatic gateway cleanup failed.");
-            console.error("  Recovery:");
-            console.error("    openshell gateway destroy -g nemoclau");
-            console.error("    docker volume ls -q --filter \"name=openshell-cluster-nemoclau\"");
+        console.error("  Automatic gateway cleanup failed.");
+        console.error("  Recovery:");
+        console.error(`    openshell gateway destroy -g ${GATEWAY_NAME}`);
+        console.error(
+          `    docker volume ls -q --filter "name=openshell-cluster-${GATEWAY_NAME}" | xargs -r docker volume rm`,
+        );
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/onboard.ts` around lines 3049 - 3058, The recovery messages after the
failed start hard-code "nemoclau" and only list Docker volumes instead of
removing them; update the strings in the error block that follows
destroyGateway() to interpolate the actual gateway identifier (use the existing
gatewayName/clusterName variable used to create the gateway) instead of
"nemoclau" and change the Docker command from listing to removing volumes, e.g.
suggest: "openshell gateway destroy -g <gatewayName>" and "docker volume rm
$(docker volume ls -q --filter \"name=openshell-cluster-<gatewayName>\")" so
users can copy/paste a working cleanup sequence.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/lib/onboard.ts`:
- Around line 2101-2114: destroyGateway() currently always returns true even
when runOpenshell(["gateway","destroy"...]) or dockerRemoveVolumesByPrefix
fails; update it to return the real cleanup status by checking the return values
of runOpenshell (inspect destroyResult.status) and dockerRemoveVolumesByPrefix
(capture its result/throw) and return true only if both succeeded (and still
call registry.clearAll() only when destroyResult.status === 0). If
dockerRemoveVolumesByPrefix returns a result object, treat non-zero/failure as
failure; if it throws on error, catch it and treat as failure, then return false
so callers can handle the cleanupOk branch correctly.
- Around line 3049-3058: The recovery messages after the failed start hard-code
"nemoclau" and only list Docker volumes instead of removing them; update the
strings in the error block that follows destroyGateway() to interpolate the
actual gateway identifier (use the existing gatewayName/clusterName variable
used to create the gateway) instead of "nemoclau" and change the Docker command
from listing to removing volumes, e.g. suggest: "openshell gateway destroy -g
<gatewayName>" and "docker volume rm $(docker volume ls -q --filter
\"name=openshell-cluster-<gatewayName>\")" so users can copy/paste a working
cleanup sequence.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 13aa8e48-0d30-45f7-9e2b-bfa051d79156

📥 Commits

Reviewing files that changed from the base of the PR and between 005fa20 and 2805233.

📒 Files selected for processing (1)
  • src/lib/onboard.ts

ericksoa added a commit that referenced this pull request May 6, 2026
## Summary
- Preserve final gateway-start diagnostics first, then run
`destroyGateway()` before exiting the exhausted-retry path.
- Keep intermediate retry cleanup behavior unchanged.
- Print accurate best-effort manual recovery commands for the `nemoclaw`
gateway if cleanup still needs help.
- Add focused regression coverage for diagnostics-before-cleanup
ordering.

## Tests
- `npm run build:cli`
- `npm run typecheck:cli`
- `npx vitest run test/gateway-final-failure-cleanup.test.ts
test/gateway-cleanup.test.ts`

Supersedes #2280. Addresses the remaining cleanup gap from #17.

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

* **Bug Fixes**
* Improved gateway startup failure handling with clearer multi-attempt
messaging, automated diagnostic collection (with sensitive data
redaction), and standardized cleanup and manual remediation guidance.

* **Tests**
* Added tests covering gateway startup failure flows, diagnostic
collection (including fallback when diagnostics fail), cleanup
execution, and verification of error output and remediation
instructions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Aaron Erickson <[email protected]>
@wscurran

wscurran commented May 6, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded — #3018 has now merged and explicitly supersedes this PR while preserving the diagnostics-before-cleanup behavior. Thanks for the contribution.

@wscurran wscurran closed this May 6, 2026
@wscurran wscurran added bug-fix PR fixes a bug or regression needs: info Waiting on author for missing details and removed status: needs-info bug-fix PR fixes a bug or regression labels Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs: info Waiting on author for missing details refactor PR restructures code without intended behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ensure failed gateway startup is fully cleaned up so reruns do not require manual Docker volume deletion

3 participants