Skip to content

refactor(rebuild): lower cognitive complexity ratchet to 244 - #5421

Merged
cv merged 13 commits into
mainfrom
ratchet/244-rebuild-cognitive-complexity
Jun 15, 2026
Merged

refactor(rebuild): lower cognitive complexity ratchet to 244#5421
cv merged 13 commits into
mainfrom
ratchet/244-rebuild-cognitive-complexity

Conversation

@cv

@cv cv commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator

Summary

Continue the cognitive-complexity ratchet by lowering the threshold from 245 to 244. This addresses the next offender with a small rebuild refactor and keeps the stack free of per-file exceptions or suppressions.

Changes

  • Lowered complexity/noExcessiveCognitiveComplexity from 245 to 244 in biome.json.
  • Extracted active-session counting in src/lib/actions/sandbox/rebuild.ts into countActiveSandboxSessionsForRebuild.
  • Documented the fail-open source boundary for active-session detection when OpenShell/process detection is unavailable.
  • Added caller-level rebuild prompt coverage for detected active SSH sessions and unavailable detection.
  • Preserved rebuild prompt behavior while reducing rebuildSandbox cognitive complexity below the new ceiling.

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 @biomejs/biome lint --only=complexity/noExcessiveCognitiveComplexity --max-diagnostics=none .

  • npm run typecheck:cli

  • npx vitest run --project cli src/lib/actions/sandbox/rebuild-gpu-opt-out.test.ts src/lib/actions/sandbox/rebuild-shields-finally.test.ts src/lib/actions/sandbox/rebuild-gateway-drift.test.ts src/lib/actions/sandbox/rebuild-config-hash.test.ts src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts test/rebuild-credential-preflight.test.ts test/rebuild-credential-hydration.test.ts test/rebuild-policy-presets.test.ts test/rebuild-shields-window.test.ts test/rebuild-stale-recovery.test.ts

  • npx vitest run --project cli test/rebuild-credential-preflight.test.ts

  • Git hooks passed during commit and push, or npx prek run --from-ref main --to-ref HEAD passes

  • Targeted tests pass for changed behavior

  • Tests added or updated for new or changed behavior

  • Full npm test passes (broad runtime changes only)

  • No secrets, API keys, or credentials committed

  • Docs updated for user-facing behavior changes

  • npm run 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

Release Notes

  • Bug Fixes

    • Improved active SSH session detection during sandbox rebuild operations
    • Session warnings now display before confirmation prompts in interactive mode
    • Enhanced error handling when session detection is unavailable
  • Tests

    • Added comprehensive test coverage for interactive rebuild confirmation flow

cv added 2 commits June 14, 2026 11:27
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
(cherry picked from commit 41fcd6a)
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv cv self-assigned this Jun 14, 2026
@copy-pr-bot

copy-pr-bot Bot commented Jun 14, 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 Jun 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

countActiveSandboxSessionsForRebuild is extracted from inline logic in rebuildSandbox, encapsulating OpenShell resolution and getActiveSandboxSessions with a fail-open 0 return. biome.json decrements maxAllowedComplexity by one. Tests add a configurable fake ps script, interactive runRebuild options, and two new SSH-warning prompt test cases.

Changes

Active SSH session detection refactor and tests

Layer / File(s) Summary
Extract countActiveSandboxSessionsForRebuild helper
src/lib/actions/sandbox/rebuild.ts, biome.json
Moves OpenShell resolution and getActiveSandboxSessions call out of rebuildSandbox into a local helper returning 0 on unavailability or error. rebuildSandbox is updated to call the helper. maxAllowedComplexity in biome.json is decremented from 245 to 244.
Test fixture: fake ps script and interactive runRebuild
test/rebuild-credential-preflight.test.ts
createFixture gains activeSessionCount?: number | null; the fixture writes a fake ps that emits SSH lines or exits non-zero. runRebuild is refactored to accept { yes?, input? } to support interactive prompt testing.
New tests: SSH warning and cancellation behavior
test/rebuild-credential-preflight.test.ts
Two new Layer 2 tests assert that the active-SSH warning appears before Proceed? [y/N] and that canceling skips backup, and that the warning is absent when detection is unavailable.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • NVIDIA/NemoClaw#5419: Both PRs modify biome.json to adjust the linter's maxAllowedComplexity threshold.

Poem

🐇 A helper was born, small and neat,
To count SSH sessions with feet so fleet.
The biome threshold dropped by one,
The tests now ask "y/N?" for fun.
When OpenShell's gone, we fail open wide —
This rabbit hops forward with nothing to hide! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the primary change: lowering the cognitive complexity threshold in biome.json from 245 to 244, which is the main driver for all refactoring in the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 ratchet/244-rebuild-cognitive-complexity

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

@github-code-quality

github-code-quality Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Code Coverage Overview

Languages: TypeScript

TypeScript / code-coverage/plugin

The overall coverage in the ratchet/244-rebuild-... branch is 96%. Coverage data for the main branch is not yet available.

Show a code coverage summary of the most covered files.
File main ratchet/244-rebuild-... eb2aadf +/-
nemoclaw/src/se...cret-scanner.ts 100%
nemoclaw/src/commands/slash.ts 100%
nemoclaw/src/li...bprocess-env.ts 100%
nemoclaw/src/bl...eprint/state.ts 98%
nemoclaw/src/onboard/config.ts 98%
nemoclaw/src/bl...int/snapshot.ts 97%
nemoclaw/src/bl...print/runner.ts 95%
nemoclaw/src/co...ration-state.ts 94%
nemoclaw/src/bl...ate-networks.ts 94%
nemoclaw/src/index.ts 94%

TypeScript / code-coverage/cli

The overall coverage in the ratchet/244-rebuild-... branch is 44%. Coverage data for the main branch is not yet available.

Show a code coverage summary of the most covered files.
File main ratchet/244-rebuild-... eb2aadf +/-
src/lib/state/o...oard-session.ts 90%
src/lib/inference/local.ts 77%
src/lib/sandbox/config.ts 72%
src/lib/inference/nim.ts 72%
src/lib/onboard/preflight.ts 64%
src/lib/state/sandbox.ts 55%
src/lib/actions...licy-channel.ts 52%
src/lib/onboard...er-gpu-patch.ts 50%
src/lib/policy/index.ts 49%
src/lib/onboard.ts 17%

Updated June 15, 2026 19:31 UTC
Code Coverage is in Public Preview. Learn more and provide us with your feedback.

@github-actions

github-actions Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

PR Review Advisor

Findings: 0 needs attention, 0 worth checking, 0 nice ideas
Since last review: 0 prior items resolved, 0 still apply, 0 new items found

Consider writing more tests for
  • **Runtime validation** — rebuildSandbox prints the singular `Active SSH session detected (1 connection)` and `terminate the active session` warning when exactly one SSH session is detected before confirmation.. The changed production surface is a sandbox rebuild lifecycle prompt before destructive work. The PR adds useful runtime-style CLI coverage for the main plural active-session path and unavailable process-detector path; a few branch-specific cases would further increase confidence in wording and fallback behavior.
  • **Runtime validation** — rebuildSandbox still shows the normal confirmation prompt and omits the Active SSH warning when `resolveOpenshell()` returns null.. The changed production surface is a sandbox rebuild lifecycle prompt before destructive work. The PR adds useful runtime-style CLI coverage for the main plural active-session path and unavailable process-detector path; a few branch-specific cases would further increase confidence in wording and fallback behavior.
  • **Runtime validation** — rebuildSandbox still shows the normal confirmation prompt and omits the Active SSH warning when active-session detection throws.. The changed production surface is a sandbox rebuild lifecycle prompt before destructive work. The PR adds useful runtime-style CLI coverage for the main plural active-session path and unavailable process-detector path; a few branch-specific cases would further increase confidence in wording and fallback behavior.

Workflow run details

This is an automated advisory review. A human maintainer must make the final merge decision.

@github-actions

github-actions Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

E2E Advisor Recommendation

Required E2E: sandbox-rebuild-vitest
Optional E2E: rebuild-openclaw-vitest, rebuild-hermes-e2e

Dispatch hint: sandbox-rebuild-vitest

Workflow run

Full advisor summary

E2E Recommendation Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E

  • sandbox-rebuild-vitest (high): Runs the real NemoClaw/OpenShell sandbox rebuild lifecycle, including onboarding a sandbox, writing and preserving state, invoking nemoclaw <sandbox> rebuild --yes, verifying the sandbox is ready afterward, refreshing registry metadata, and checking rebuild backup credential hygiene. This is the closest existing PR-safe E2E coverage for changes in src/lib/actions/sandbox/rebuild.ts.

Optional E2E

  • rebuild-openclaw-vitest (very high): Provides deeper OpenClaw-specific rebuild coverage by rebuilding an older OpenClaw sandbox image, preserving workspace/policy state, rotating gateway secrets, and validating post-rebuild behavior. Useful extra confidence for common rebuild code, but heavier than the focused sandbox rebuild lane.
  • rebuild-hermes-e2e (high): Exercises the legacy Hermes rebuild path from nightly E2E, including Hermes state preservation and messaging-related rebuild behavior. Useful if maintainers want agent-specific confidence, though this PR's change is generic active-session detection rather than Hermes-specific logic.

New E2E recommendations

  • interactive rebuild active-session warning (high): Existing live rebuild E2E jobs appear to use --yes and therefore do not verify the interactive warning/cancel path for active SSH sessions. The PR specifically changes active-session detection and warning behavior.
    • Suggested test: Add a live or hermetic E2E scenario that creates or fakes an active openshell-<sandbox> SSH session, runs nemoclaw <sandbox> rebuild without --yes, answers n, and asserts the active-session warning is printed and no backup/delete/rebuild work starts.

Dispatch hint

  • Workflow: .github/workflows/e2e-vitest-scenarios.yaml
  • jobs input: sandbox-rebuild-vitest

@github-actions

github-actions Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Vitest E2E Scenario Recommendation

Required Vitest E2E scenarios: sandbox-rebuild-vitest
Optional Vitest E2E scenarios: rebuild-openclaw-vitest

Dispatch required Vitest E2E scenarios:

  • gh workflow run e2e-vitest-scenarios.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild-vitest

Workflow run

Full Vitest E2E advisor summary

Vitest E2E Scenario Advisor

Base: origin/main
Head: HEAD
Confidence: medium

Required Vitest E2E scenarios

  • sandbox-rebuild-vitest: The PR changes the real nemoclaw rebuild implementation, specifically active-session detection before rebuild confirmation. The wired free-standing sandbox rebuild Vitest job is the smallest live Vitest path that runs the rebuild CLI through Docker/OpenShell and validates rebuild behavior.
    • Dispatch: gh workflow run e2e-vitest-scenarios.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild-vitest

Optional Vitest E2E scenarios

  • rebuild-openclaw-vitest: Adjacent live rebuild coverage for an OpenClaw rebuild/state-preservation path. Useful if reviewers want extra confidence that the rebuild helper refactor does not regress the older OpenClaw rebuild flow.
    • Dispatch: gh workflow run e2e-vitest-scenarios.yaml --ref <pr-head-ref> --field jobs=rebuild-openclaw-vitest

Relevant changed files

  • src/lib/actions/sandbox/rebuild.ts

Base automatically changed from ratchet/245-setup-nim-cognitive-complexity to main June 15, 2026 18:06
…ognitive-complexity

# Conflicts:
#	biome.json
@copy-pr-bot

copy-pr-bot Bot commented Jun 15, 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.

cv added 2 commits June 15, 2026 11:18
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv
cv marked this pull request as ready for review June 15, 2026 19:27

@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

🤖 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 `@test/rebuild-credential-preflight.test.ts`:
- Around line 369-372: The test assertions on lines 369-372 in
test/rebuild-credential-preflight.test.ts use multiple toContain() checks that
only verify string presence but not their ordering. To ensure the warning
messages appear before the confirmation prompt as intended, replace the
individual toContain() assertions with a single assertion that verifies the
substring order—for example, check that the index of "Active SSH sessions
detected (2 connections)" and "terminate all active sessions with a Broken pipe
error" appear before the index of "Proceed? [y/N]:" in the output string, or use
a regex or index-based approach to enforce the correct sequence.
🪄 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: e1c0e611-471e-457b-a440-ef6a74fb8e39

📥 Commits

Reviewing files that changed from the base of the PR and between 999a6a8 and eb2aadf.

📒 Files selected for processing (3)
  • biome.json
  • src/lib/actions/sandbox/rebuild.ts
  • test/rebuild-credential-preflight.test.ts

Comment on lines +369 to +372
expect(output).toContain("Active SSH sessions detected (2 connections)");
expect(output).toContain("terminate all active sessions with a Broken pipe error");
expect(output).toContain("Proceed? [y/N]:");
expect(output).toContain("Cancelled.");

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 | ⚡ Quick win

Assert output ordering, not just presence, for warning vs confirmation prompt.

On Lines 369-372, the test checks both strings exist but does not verify the warning appears before Proceed? [y/N]:, so the intended sequencing can regress undetected.

Suggested test assertion update
       expect(output).toContain("Active SSH sessions detected (2 connections)");
       expect(output).toContain("terminate all active sessions with a Broken pipe error");
       expect(output).toContain("Proceed? [y/N]:");
+      expect(output.indexOf("Active SSH sessions detected (2 connections)")).toBeLessThan(
+        output.indexOf("Proceed? [y/N]:"),
+      );
📝 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
expect(output).toContain("Active SSH sessions detected (2 connections)");
expect(output).toContain("terminate all active sessions with a Broken pipe error");
expect(output).toContain("Proceed? [y/N]:");
expect(output).toContain("Cancelled.");
expect(output).toContain("Active SSH sessions detected (2 connections)");
expect(output).toContain("terminate all active sessions with a Broken pipe error");
expect(output).toContain("Proceed? [y/N]:");
expect(output.indexOf("Active SSH sessions detected (2 connections)")).toBeLessThan(
output.indexOf("Proceed? [y/N]:"),
);
expect(output).toContain("Cancelled.");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/rebuild-credential-preflight.test.ts` around lines 369 - 372, The test
assertions on lines 369-372 in test/rebuild-credential-preflight.test.ts use
multiple toContain() checks that only verify string presence but not their
ordering. To ensure the warning messages appear before the confirmation prompt
as intended, replace the individual toContain() assertions with a single
assertion that verifies the substring order—for example, check that the index of
"Active SSH sessions detected (2 connections)" and "terminate all active
sessions with a Broken pipe error" appear before the index of "Proceed? [y/N]:"
in the output string, or use a regex or index-based approach to enforce the
correct sequence.

@cv
cv merged commit a57d508 into main Jun 15, 2026
37 checks passed
@cv
cv deleted the ratchet/244-rebuild-cognitive-complexity branch June 15, 2026 19:46
@cv cv added the v0.0.65 label Jun 15, 2026
@wscurran wscurran added the area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery label Aug 1, 2026
@wscurran wscurran added the refactor PR restructures code without intended behavior change label Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery refactor PR restructures code without intended behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants