Skip to content
This repository was archived by the owner on Apr 7, 2026. It is now read-only.

sync: rebase on upstream (2026-03-28) - #9

Merged
TSavo merged 13 commits into
mainfrom
sync/upstream-2026-03-28
Mar 28, 2026
Merged

TSavo merged 13 commits into
mainfrom
sync/upstream-2026-03-28

Conversation

@AgentWOPR

@AgentWOPR AgentWOPR commented Mar 28, 2026 •

Copy link
Copy Markdown

Automated upstream sync

Rebased our WOPR sidecar commits onto upstream/main (NVIDIA/NemoClaw).

What this does

  • Pulls in latest upstream changes (security fixes, features, CI improvements)
  • Resolves any rebase conflicts (preserving wopr/ sidecar)
  • Verifies sidecar + Dockerfile integrity

Verify

  • Build passes
  • wopr/sidecar.js intact
  • Dockerfile includes sidecar setup

Open with Devin

Summary by CodeRabbit

  • New Features

    • Added resumable onboarding with --resume flag for interrupted sessions
    • Implemented automatic proxy environment configuration for sandbox connectivity
    • Enhanced sandbox/gateway recovery with intelligent error diagnosis and guided recovery steps
    • Added build context optimization to exclude unnecessary directories from deployment
  • Improvements

    • Better sandbox creation error reporting with specific recovery guidance
    • Improved credential management and secure credential handling
    • Enhanced installation detection and shell profile integration
    • Refined policy preset application logic
  • Bug Fixes

    • Fixed duplicate port-forward initialization during sandbox connection
    • Improved onboarding step persistence and status tracking

Note

Add resumable onboarding sessions with gateway reuse and credential sanitization in migration snapshots

  • The onboarding orchestrator in onboard.js now persists step state via a new onboard-session.js module, acquires a lock to prevent concurrent runs, and automatically skips completed steps on --resume
  • Gateway preflight now classifies reuse state (healthy, stale, foreign-active, etc.) and avoids tearing down a healthy named gateway; a new recoverGatewayRuntime utility restores runtime without full teardown
  • install.sh auto-detects an interrupted session and re-invokes nemoclaw onboard --resume --non-interactive; post-install messaging is now conditional on whether onboarding ran and whether the CLI is resolvable in the current shell
  • scripts/install.sh is replaced by a thin deprecation wrapper that delegates to the root install.sh
  • Migration snapshots in migration-state.ts now strip credential fields and the gateway section from openclaw.json using a new sanitizeConfigFile helper, with file permissions set to 0600
  • scripts/nemoclaw-start.sh now exports proxy environment variables and persists them to ~/.bashrc and ~/.profile inside the sandbox
  • Risk: nemoclaw connect no longer pre-starts a background port forward on 18789 before invoking openshell sandbox connect
📊 Macroscope summarized e32ccc6. 24 files reviewed, 8 issues evaluated, 3 issues filtered, 5 comments posted

🗂️ Filtered Issues

bin/lib/onboard.js — 3 comments posted, 4 evaluated, 1 filtered
  • line 1603: Line 1603 calls runOpenshell(["gateway", "destroy", "-g", GATEWAY_NAME], ...) directly instead of the new destroyGateway() helper. The destroyGateway() function (lines 1389-1394) was introduced specifically because openshell gateway destroy doesn't remove Docker volumes, leaving corrupted cluster state. The cleanup paths at lines 1620 and 1638 correctly use destroyGateway(), but the stale gateway cleanup at line 1603 does not, potentially leaving corrupted volumes that break the subsequent gateway start. [ Out of scope ]
bin/lib/runtime-recovery.js — 0 comments posted, 1 evaluated, 1 filtered
  • line 17: The regex /^(NAME|No sandboxes found\.?$)/i incorrectly skips any sandbox whose name starts with "name" (case-insensitive). For example, a sandbox named namesandbox would have its line start with "namesandbox" which matches ^NAME in the alternation, causing it to be silently excluded from the returned set. The fix should require whitespace after NAME to correctly identify only the header line, e.g., /^NAME\s|^No sandboxes found\.?$/i. [ Cross-file consolidated ]
test/install-preflight.test.js — 0 comments posted, 1 evaluated, 1 filtered
  • line 11: CURL_PIPE_INSTALLER now points to the same file as INSTALLER (../install.sh), but the "curl-pipe installer release-tag resolution" test suite (starting at line 1380) is intended to test scripts/install.sh. The suite's comment explicitly states "Build the full fakeBin environment needed to run scripts/install.sh" and notes behavioral differences ("Unlike install.sh, this script also requires docker, openshell..."). These tests no longer exercise the scripts/install.sh script at all, leaving its release-tag resolution behavior untested. [ Failed validation ]

kjw3 and others added 13 commits March 25, 2026 23:23
* fix: improve gateway lifecycle recovery

* docs: fix readme markdown list spacing

* fix: tighten gateway lifecycle review follow-ups

* fix: simplify tokenized control ui output

* fix: restore chat route in control ui urls

* refactor: simplify ansi stripping in onboard

* fix: shorten control ui url output

* fix: move control ui below cli next steps
* chore: add cyclomatic complexity rule (ratchet from 95)

Add ESLint complexity rule to bin/ and scripts/ to prevent new
functions from accumulating excessive branching. Starting threshold
is 95 (current worst offender: setupNim in onboard.js). Ratchet
plan: 95 → 40 → 25 → 15.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* chore: ratchet complexity to 20, suppress existing violations

Suppress 6 functions that exceed the threshold with eslint-disable
comments so we can start enforcing at 20 instead of 95:

- setupNim (95), setupPolicies (41), setupInference (22) in onboard.js
- deploy (22), main IIFE (27) in nemoclaw.js
- applyPreset (24) in policies.js

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* chore: suppress complexity for 3 missed functions

preflight (23), getReconciledSandboxGatewayState (25), sandboxStatus (27)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
…#913)

* chore: add tsconfig.cli.json, root execa, TS coverage ratchet

Foundation for the CLI TypeScript migration (PR 0 of the shell
consolidation plan). No runtime changes — config, tooling, and
dependency only.

- tsconfig.cli.json: strict TS type-checking for bin/ and scripts/
  (noEmit, module: preserve — tsx handles the runtime)
- scripts/check-coverage-ratchet.ts: pure TS replacement for the
  bash+python coverage ratchet script (same logic, same tolerance)
- execa ^9.6.1 added to root devDependencies (used by PR 1+)
- pr.yaml: coverage ratchet step now runs the TS version via tsx
- .pre-commit-config.yaml: SPDX headers cover scripts/*.ts,
  new tsc-check-cli pre-push hook
- CONTRIBUTING.md: document typecheck:cli task and CLI pre-push hook
- Delete scripts/check-coverage-ratchet.sh

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* Apply suggestion from @brandonpelfrey

* chore: address PR feedback — use types_or, add tsx devDep

- Use `types_or: [ts, tsx]` instead of file glob for tsc-check-cli
  hook per @brandonpelfrey's suggestion.
- Add `tsx` to devDependencies so CI doesn't re-fetch it on every run
  per CodeRabbit's suggestion.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix(ci): ignore GitHub "Apply suggestion" commits in commitlint

* fix(ci): lint only PR title since repo is squash-merge only

Reverts the commitlint ignores rule from the previous commit and
instead removes the per-commit lint step entirely.

Individual commit messages are discarded at merge time — only the
squash-merged PR title lands in main and drives changelog generation.
Drop the per-commit lint, keep the PR title check, and remove the
now-unnecessary fetch-depth: 0.

* Revert "fix(ci): lint only PR title since repo is squash-merge only"

This reverts commit 1257a47.

* Revert "fix(ci): ignore GitHub "Apply suggestion" commits in commitlint"

This reverts commit c395657.

* docs: fix markdownlint MD032 in README (blank line before list)

* refactor: make coverage ratchet script idiomatic TypeScript

- Wrap in main() with process.exitCode instead of scattered process.exit()
- Replace mutable flags with .map()/.some() over typed MetricResult[]
- Separate pure logic (checkMetrics) from formatting (formatReport)
- Throw with { cause } chaining instead of exit-in-helpers
- Derive CoverageThresholds from METRICS tuple (single source of truth)
- Exhaustive switch on CheckStatus discriminated union

* refactor: remove duplication in coverage ratchet script

- Drop STATUS_LABELS map; inline labels in exhaustive switch
- Extract common 'metric coverage is N%' preamble in formatResult
- Simplify ratchetedThresholds: use results directly (already in
  METRICS order) instead of re-scanning with .find() per metric
- Compute 'failed' once in main, pass into formatReport to avoid
  duplicate .some() scan

* refactor: simplify coverage ratchet with FP patterns

- Extract classify() as a named pure function (replaces nested ternary)
- loadJSON takes repo-relative paths, eliminating THRESHOLD_PATH and
  SUMMARY_PATH constants (DRY the join-with-REPO_ROOT pattern)
- Drop CoverageMetric/CoverageSummary interfaces (only pct is read);
  use structural type at the call site instead
- Inline ratchetedThresholds (one-liner, used once)
- formatReport derives fail/improved from results instead of taking
  a pre-computed boolean (let functions derive from data, don't
  thread derived state)
- sections.join("\n\n") replaces manual empty-string pushing
- Shorter type names (Thresholds, Status, Result) — no ambiguity
  in a single-purpose script

* refactor: strip coverage ratchet to failure-only output

prek hides output from commands that exit 0, so ok/improved
reporting was dead code. Remove Status, Result, classify,
formatResult, formatReport, and the ratcheted-thresholds
suggestion block. The script now just filters for regressions
and prints actionable errors on failure.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Brandon Pelfrey <[email protected]>
…ets (NVIDIA#438)

* fix: use CONNECT tunnel for WebSocket endpoints in Discord/Slack presets

The egress proxy's HTTP idle timeout (~2 min) kills long-lived WebSocket
connections when endpoints are configured with protocol:rest + tls:terminate.
Switch WebSocket endpoints to access:full (CONNECT tunnel) which bypasses
HTTP-level timeouts entirely.

Discord:
- gateway.discord.gg → access:full (WebSocket gateway)
- Add PUT/PATCH/DELETE methods for discord.com (message editing, reactions)
- Add media.discordapp.net for attachment access

Slack:
- Add wss-primary.slack.com and wss-backup.slack.com → access:full
  (Socket Mode WebSocket endpoints)

Partially addresses NVIDIA#409 — the policy-level fix enables WebSocket
connections to survive. The hardcoded 2-min timeout in openshell-sandbox
still affects any protocol:rest endpoints with long-lived connections.

Related: NVIDIA#361 (WhatsApp Web, same root cause)

* fix: correct comment wording for media endpoint and YAML formatting
* fix: remove unused RECOMMENDED_NODE_MAJOR from scripts/install.sh

Shellcheck flagged it as unused after the min/recommended merge.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: enforce full semver >=22.16.0 in installer scripts

The runtime checks only compared the major Node.js version, allowing
22.0–22.15 to pass despite package.json requiring >=22.16.0. Use the
version_gte() helper for full semver comparison in both installers.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: harden version_gte and align fallback message

Guard version_gte() against prerelease suffixes (e.g. "22.16.0-rc.1")
that would crash bash arithmetic. Also update the manual-install
fallback message to reference MIN_NODE_VERSION instead of hardcoded "22".

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: update test stubs for Node.js 22.16 minimum and add Node 20 rejection test

- Bump node stub in 'succeeds with acceptable Node.js' from v20.0.0 to v22.16.0
- Bump node stub in buildCurlPipeEnv from v22.14.0 to v22.16.0
- Add new test asserting Node.js 20 is rejected by ensure_supported_runtime

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
* fix: harden installer and onboard resiliency

* fix: address installer and debug review follow-ups

* fix: harden onboard resume across later setup steps

* test: simplify payload extraction in onboard tests

* test: keep onboard payload extraction target-compatible

* chore: align onboard session lint with complexity rule

* fix: harden onboard session safety and lock handling

* fix: tighten onboard session redaction and metadata handling
… blueprint digest (NVIDIA#769)

Reconciles NVIDIA#156 and NVIDIA#743 into a single comprehensive solution:

- Filter auth-profiles.json at copy time via cpSync filter (from NVIDIA#743)
- Recursive stripCredentials() with pattern-based field detection for
  deep config sanitization (from NVIDIA#156: CREDENTIAL_FIELDS set +
  CREDENTIAL_FIELD_PATTERN regex)
- Remove gateway config section (contains auth tokens) from sandbox
  openclaw.json
- Blueprint digest verification (SHA-256): recorded at snapshot time,
  validated on restore, empty/missing digest is a hard failure
- computeFileDigest() throws when blueprint file is missing instead of
  silently returning null
- Sanitize both snapshot-level and sandbox-bundle openclaw.json copies
- Backward compatible: old snapshots without blueprintDigest skip
  validation
- Bump SNAPSHOT_VERSION 2 → 3

Supersedes NVIDIA#156 and NVIDIA#743.
…ross reconnects (NVIDIA#1025)

* fix(sandbox): export proxy env vars with full NO_PROXY and persist across reconnects

OpenShell injects NO_PROXY=127.0.0.1,localhost,::1 into the sandbox, missing
inference.local and the gateway IP (10.200.0.1). This causes LLM inference
requests to route through the egress proxy instead of going direct, and the
proxy gateway IP itself gets proxied.

Add proxy configuration block to nemoclaw-start.sh that:
- Exports HTTP_PROXY, HTTPS_PROXY, and NO_PROXY with inference.local and
  the gateway IP included
- Persists via /etc/profile.d/nemoclaw-proxy.sh (root) or ~/.profile
  (non-root fallback) so values survive OpenShell reconnect injection
- Supports NEMOCLAW_PROXY_HOST / NEMOCLAW_PROXY_PORT overrides

The non-root fallback ensures the fix works in environments like Brev where
containers run without root privileges.

Tested on DGX Spark (ARM64) and Brev VM (x86_64). Verified NO_PROXY contains
inference.local and 10.200.0.1 inside the live sandbox after connect.

Ref: NVIDIA#626, NVIDIA#704
Ref: NVIDIA#704 (comment)

* fix(sandbox): write proxy config to ~/.bashrc for interactive reconnect sessions

OpenShell's `sandbox connect` spawns `/bin/bash -i` (interactive, non-login),
which sources ~/.bashrc — not ~/.profile or /etc/profile.d/*.  The previous
approach wrote to ~/.profile and /etc/profile.d/, neither of which is sourced
by `bash -i`, so the narrow OpenShell-injected NO_PROXY persisted in live
interactive sessions.

Changes:
- Write proxy snippet to ~/.bashrc (primary) and ~/.profile (login fallback)
- Export both uppercase and lowercase proxy variants (NO_PROXY + no_proxy,
  HTTP_PROXY + http_proxy, etc.) — Node.js undici prefers lowercase no_proxy
  over uppercase NO_PROXY when both are set
- Add idempotency guard to prevent duplicate blocks on container restart
- Update tests: verify .bashrc writing, idempotency, bash -i override
  behavior, and lowercase variant correctness

Tested on DGX Spark (ARM64) and Brev VM (x86_64) with full destroy +
re-onboard + live `env | grep proxy` verification inside the sandbox shell
via `openshell sandbox connect`.

Ref: NVIDIA#626

* fix(sandbox): replace stale proxy values on restart with begin/end markers

Use begin/end markers in .bashrc/.profile proxy snippet so
_write_proxy_snippet replaces the block when PROXY_HOST/PORT change
instead of silently keeping stale values. Adds test coverage for the
replacement path.

Addresses CodeRabbit review feedback on idempotency gap.

* fix(sandbox): resolve sandbox user home dynamically when running as root

When the entrypoint runs as root, $HOME is /root — the proxy snippet
was written to /root/.bashrc instead of the sandbox user's home.
Use getent passwd to look up the sandbox user's home when running as
UID 0; fall back to /sandbox if the user entry is missing.

Addresses CodeRabbit review feedback on _SANDBOX_HOME resolution.

---------

Co-authored-by: Carlos Villela <[email protected]>
…DIA#35) (NVIDIA#101)

* fix(policies): allow preset application for versionless policies (Fixes NVIDIA#35)

Fixes NVIDIA#35

Signed-off-by: Deepak Jain <[email protected]>

* fix: remove stale complexity suppression in policies

---------

Signed-off-by: Deepak Jain <[email protected]>
Co-authored-by: Kevin Jones <[email protected]>
* fix: restore routed inference and connect UX

* fix: simplify detected local inference hint

* fix: remove stale local inference hint

* test: relax connect forward assertion
Applied conflict resolution strategy:
1. TOOK all upstream features/bug fixes (new tests, install.sh refactor, policy merging)
2. KEPT wopr directory and specific additions intact
3. Removed port forward pre-start in sandboxConnect (upstream change)
4. Updated gateway lifecycle state checks to include 'missing_named' state
5. Simplified scripts/install.sh to delegate to root installer (wrapper pattern)

Conflicts resolved in:
- bin/lib/policies.js: Kept upstream's mergePresetIntoPolicy function
- bin/nemoclaw.js: Added 'missing_named' to gateway states, removed port forward pre-start
- scripts/install.sh: Simplified to wrapper pattern
- test/cli.test.js: Added upstream's new test for port forward handling
- test/install-preflight.test.js: Replaced tests with upstream's legacy wrapper tests
- test/onboard.test.js: Updated test cases to upstream's new format
- bin/lib/onboard.js: Took upstream's refactored version

All wopr-specific additions remain untouched and preserved.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry @AgentWOPR, your pull request is larger than the review limit of 150000 diff characters

@coderabbitai

coderabbitai Bot commented Mar 28, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces resumable onboarding and runtime recovery infrastructure. It adds session persistence to track onboard progress, enables interrupted installations to resume, implements gateway and sandbox recovery utilities, extends the CLI with --resume support, and enhances installation scripts with recovery path guidance and proxy configuration.

Changes

Cohort / File(s) Summary
Session Management
bin/lib/onboard-session.js, test/onboard-session.test.js
New module providing versioned JSON session persistence, atomic save/load with file permissions, process locking with stale-holder detection, step-level progress tracking with timestamps and sanitized failure messages, and credential/URL redaction utilities.
Onboarding Resume & Recovery
bin/lib/onboard.js, test/onboard.test.js
Refactored onboarding pipeline to support conditional step skipping based on session state; added gateway/sandbox reuse detection with classified states; integrated session lock acquisition/release; introduced helpers for build-context filtering, sandbox repair, policy preset resume, and inference/OpenClaw readiness checks; added recovery guidance and credential hydration.
Runtime Recovery Utilities
bin/lib/runtime-recovery.js, test/runtime-recovery.test.js
New module providing ANSI-stripping, sandbox/gateway status classification, live sandbox name parsing, and recovery command selection based on session resumability state.
Policy Merging
bin/lib/policies.js, test/policies.test.js
Extracted preset YAML merge logic into new mergePresetIntoPolicy function with version-header normalization and idempotent append of preset network policies.
Installation & Recovery
install.sh
Added install-time recovery state tracking, shell profile detection, and conditional onboard resume; enhanced verify_nemoclaw() to record recovery hints when CLI path is unresolved; updated print_done() messaging to guide PATH updates and resume flows.
Legacy Installer Wrapper
scripts/install.sh
Converted to deprecation wrapper that delegates to root install.sh and emits compatibility warnings.
Gateway & Proxy Management
scripts/nemoclaw-start.sh, bin/nemoclaw.js
Added proxy environment export with gateway IP exclusion and persistent ~/.bashrc/~/.profile configuration; extended CLI onboard parsing to accept --resume flag; updated gateway recovery state machine to include missing_named trigger; removed pre-sandbox connect port-forward.
Migration & Snapshot Security
nemoclaw/src/commands/migration-state.ts, nemoclaw/src/commands/migration-state.test.ts
Added credential sanitization during snapshot creation, replaced nullable digest with throwing error, integrated recursive credential-field stripping with [STRIPPED_BY_MIGRATION] redaction, and enhanced failure handling with try/catch.
E2E Test Suites
test/e2e/test-onboard-resume.sh, test/e2e/test-onboard-repair.sh
New comprehensive bash test scenarios validating interrupted onboard resumption with session persistence, resume with missing sandbox repair, conflict detection for sandbox name/provider/model mismatches, and cleanup validation.
Unit & Integration Tests
test/cli.test.js, test/install-preflight.test.js, test/onboard-selection.test.js, test/service-env.test.js, test/uninstall.test.js, test/nemoclaw-cli-recovery.test.js
Added tests for --resume CLI parsing, installer wrapper delegation, auto-resume on session presence, gateway recovery messaging, proxy persistence and override behavior, user-managed shim preservation, and onboard-session cleanup.
Diagnostics & Debugging
scripts/debug.sh
Added runtime script-location detection and new "Onboard Session" diagnostic section via summarizeForDebug() helper output.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI as bin/nemoclaw.js
    participant Session as onboard-session
    participant OnboardFlow as onboard.js
    participant Sandbox as openshell sandbox
    participant Gateway as openshell gateway

    User->>CLI: nemoclaw onboard --resume
    CLI->>Session: acquireOnboardLock()
    Session->>Session: Check lock file & PID
    Session-->>CLI: {acquired:true}
    
    CLI->>Session: loadSession()
    Session-->>CLI: session {status:failed, lastCompletedStep:N}
    
    CLI->>OnboardFlow: onboard({resume:true})
    OnboardFlow->>Session: Mark step resumed
    
    alt Resume Gateway
        OnboardFlow->>Gateway: Check existing gateway
        Gateway-->>OnboardFlow: healthy state
        OnboardFlow->>Session: markStepComplete("gateway")
    end
    
    alt Resume Sandbox
        OnboardFlow->>Sandbox: Get existing sandbox
        Sandbox-->>OnboardFlow: ready state
        OnboardFlow->>Session: markStepComplete("sandbox")
    end
    
    OnboardFlow->>OnboardFlow: Run remaining steps
    OnboardFlow->>Session: markStepComplete(...) per step
    OnboardFlow->>Session: completeSession()
    
    CLI->>Session: releaseOnboardLock()
    Session-->>CLI: lock removed
    User-->>CLI: Success
Loading
sequenceDiagram
    participant User
    participant CLI as bin/nemoclaw.js
    participant Install as install.sh
    participant Session as onboard-session
    participant OnboardFlow as onboard.js
    participant Node as Node.js
    participant Sandbox as openshell sandbox

    User->>Install: ./install.sh
    Install->>Install: Detect shell & PATH
    
    alt CLI not in PATH
        Install->>Install: Record recovery hints
        Install->>Install: NEMOCLAW_RECOVERY_PROFILE=~/.bashrc
    end
    
    Install->>Node: Check ~/.nemoclaw/onboard-session.json
    Node-->>Install: session {status:failed}
    
    Install->>Install: onboard_cmd=(nemoclaw onboard --resume)
    Install->>CLI: Run onboard --resume --non-interactive
    
    CLI->>Session: acquireOnboardLock()
    CLI->>Session: loadSession()
    Session-->>CLI: Prior incomplete session
    
    CLI->>OnboardFlow: onboard({resume:true, nonInteractive:true})
    OnboardFlow->>Sandbox: Check recorded sandbox
    Sandbox-->>OnboardFlow: missing (repairRecordedSandbox)
    OnboardFlow->>Sandbox: Recreate sandbox
    
    OnboardFlow->>Session: markStepComplete("sandbox", updates)
    OnboardFlow->>Session: completeSession()
    CLI->>Session: releaseOnboardLock()
    
    Install->>Install: print_done() recovery instructions
    Install->>User: CLI ready / PATH instructions
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes


Poem

A rabbit hops through resume gates,
Sessions dance in JSON fates,
No more restarts from the start,
This humble code's a work of art! 🐰

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.84% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'sync: rebase on upstream (2026-03-28)' is vague and generic, using non-descriptive terms that do not convey specific information about the actual changes in the changeset. Consider using a more descriptive title that indicates the primary feature or fix being brought in, such as 'feat: add session resumption and gateway recovery improvements' or referencing the main stability/security enhancements being synced.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 sync/upstream-2026-03-28

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Implement resumable onboarding with session tracking, runtime recovery, and credential sanitization

✨ Enhancement 🧪 Tests

Grey Divider

Walkthroughs

Description
• **Implement resumable onboarding with session tracking**: Added comprehensive session management
  for interrupted onboarding flows, including state persistence, conflict detection, and recovery
  logic
• **New session persistence module**: Created onboard-session.js for managing onboarding state in
  ~/.nemoclaw/onboard-session.json with sensitive data redaction and lock file mechanisms
• **Runtime recovery helpers**: Implemented runtime-recovery.js module for gateway and sandbox
  state classification to support automatic recovery from transient failures
• **Enhanced CLI with resume flag**: Added --resume flag to onboard command for resuming
  interrupted sessions
• **Improved installer with resume detection**: Enhanced install.sh to detect and auto-resume
  interrupted onboarding sessions with PATH recovery instructions
• **Proxy environment configuration**: Added proxy setup in nemoclaw-start.sh for sandbox gateway
  communication (HTTP_PROXY, HTTPS_PROXY, NO_PROXY)
• **Credential sanitization for migrations**: Implemented recursive credential stripping in
  migration snapshots to prevent sensitive data exposure
• **Policy merge refactoring**: Extracted mergePresetIntoPolicy as a pure testable function
• **Improved uninstall logic**: Enhanced symlink detection and user file preservation in shim
  directory
• **Comprehensive test coverage**: Added 10+ new test suites covering session management, resume
  scenarios, proxy configuration, runtime recovery, and credential sanitization
• **E2E test scenarios**: Added tests for onboard resume completion and repair workflows
Diagram
flowchart LR
  A["Interrupted Onboard"] -->|"Session Persisted"| B["onboard-session.js"]
  B -->|"State Tracked"| C["Resume Detection"]
  C -->|"Auto-Resume"| D["install.sh"]
  D -->|"Skip Cached Steps"| E["Complete Onboarding"]
  F["Runtime Failure"] -->|"Classify State"| G["runtime-recovery.js"]
  G -->|"Recovery Decision"| H["Attempt Recovery"]
  I["Migration Snapshot"] -->|"Sanitize"| J["stripCredentials"]
  J -->|"Remove Sensitive Data"| K["Safe Migration"]
  L["Sandbox Gateway"] -->|"Configure"| M["Proxy Settings"]
  M -->|"Persist"| N["bashrc/profile"]
Loading

Grey Divider

File Changes

1. bin/lib/onboard.js ✨ Enhancement +808/-107

Implement resumable onboarding with session tracking and state recovery

• Refactored gateway health checking with new state classification functions
 (getGatewayReuseState, isGatewayHealthy, hasStaleGateway) to support resume functionality
• Added session management integration via onboardSession module for tracking onboarding progress
 across interruptions
• Implemented resume logic with conflict detection for sandbox name, provider, and model mismatches
• Enhanced sandbox creation with build context filtering (shouldIncludeBuildContextPath,
 copyBuildContextDir) and failure classification (classifySandboxCreateFailure,
 printSandboxCreateRecoveryHints)
• Added helper functions for credential hydration, inference route verification, and policy preset
 application tracking
• Refactored main onboard() function to support resumable sessions with step-by-step progress
 tracking

bin/lib/onboard.js


2. bin/lib/onboard-session.js ✨ Enhancement +432/-0

New session persistence module for onboarding state tracking

• New module for managing onboarding session state persistence in ~/.nemoclaw/onboard-session.json
• Implements session lifecycle management with step tracking (preflight, gateway, sandbox,
 provider_selection, inference, openclaw, policies)
• Provides lock file mechanism to prevent concurrent onboarding runs
• Includes sensitive data redaction for credentials and URLs in persisted session data
• Exports functions for session creation, loading, updating, and step state management

bin/lib/onboard-session.js


3. test/onboard.test.js 🧪 Tests +520/-62

Comprehensive tests for resume and state management features

• Added comprehensive tests for new gateway state classification (getGatewayReuseState,
 isGatewayHealthy)
• Added tests for sandbox state detection and build context filtering
• Added tests for resume conflict detection (sandbox name, provider, model)
• Added tests for inference route readiness and OpenClaw configuration detection
• Added tests for policy preset application tracking
• Added tests for sandbox creation failure classification and recovery hints

test/onboard.test.js


View more (21)
4. test/install-preflight.test.js 🧪 Tests +196/-175

Update installer tests for resume and wrapper functionality

• Replaced legacy scripts/install.sh curl-pipe installer tests with compatibility wrapper tests
• Added test for auto-resume of interrupted onboarding sessions during installation
• Added test for PATH recovery instructions suppression when nemoclaw is already available
• Removed obsolete macOS runtime choice and stdin installer tests

test/install-preflight.test.js


5. test/service-env.test.js 🧪 Tests +236/-1

Add proxy environment variable configuration tests

• Added comprehensive test suite for proxy environment variable configuration (issue #626)
• Tests verify HTTP_PROXY, HTTPS_PROXY, NO_PROXY, and lowercase variants are correctly set
• Tests validate proxy configuration persistence to ~/.bashrc and ~/.profile
• Tests ensure idempotent and replaceable proxy configuration across repeated invocations

test/service-env.test.js


6. test/onboard-session.test.js 🧪 Tests +222/-0

Add onboard session management test suite

• New comprehensive test suite for onboard session management with 222 lines of test cases
• Tests session creation, persistence, credential redaction, step tracking, and lock file handling
• Validates that sensitive data (API keys, tokens, passwords) are redacted before persistence
• Covers session resumability, debug output sanitization, and metadata filtering

test/onboard-session.test.js


7. bin/lib/policies.js ✨ Enhancement +60/-51

Refactor policy merging into testable pure function

• Extracted mergePresetIntoPolicy as a pure function for testability and reusability
• Refactored applyPreset to use the new merge function, improving code organization
• Enhanced version header handling for versionless policies during preset merging
• Exported mergePresetIntoPolicy for external testing

bin/lib/policies.js


8. test/nemoclaw-cli-recovery.test.js 🧪 Tests +105/-0

Add CLI runtime recovery integration test

• New E2E test validating CLI runtime recovery when openshell is only available via fallback path
• Tests gateway status recovery and sandbox status retrieval after transient failures
• Simulates openshell CLI with mock script that fails on first call then succeeds
• Verifies recovery message output and successful sandbox status retrieval

test/nemoclaw-cli-recovery.test.js


9. test/cli.test.js 🧪 Tests +66/-0

Enhance CLI tests for onboard resume and connect

• Added test for onboard --resume CLI flag parsing
• Added assertion to verify "Onboard Session" appears in debug output
• Added test for connect command to prevent duplicate port forward pre-start
• Validates that sandbox get and connect are called but forward start is not

test/cli.test.js


10. test/uninstall.test.js 🧪 Tests +63/-1

Expand uninstall tests for shim and session cleanup

• Added createFakeNpmEnv helper function to mock npm in test environments
• Enhanced shim removal test to use symlinks and validate symlink detection
• Added test to preserve user-managed nemoclaw files in shim directory
• Added test to verify onboard session file removal during state cleanup

test/uninstall.test.js


11. test/runtime-recovery.test.js 🧪 Tests +74/-0

Add runtime recovery helper function tests

• New test suite for runtime recovery helper functions with 74 lines
• Tests sandbox name parsing, sandbox lookup classification, and gateway status classification
• Validates recovery decision logic based on sandbox and gateway states
• Covers ANSI stripping and error pattern matching

test/runtime-recovery.test.js


12. bin/lib/runtime-recovery.js ✨ Enhancement +81/-0

Implement runtime recovery classification helpers

• New module providing runtime recovery helpers for gateway and sandbox state classification
• Implements parseLiveSandboxNames, classifySandboxLookup, classifyGatewayStatus functions
• Includes shouldAttemptGatewayRecovery decision logic and getRecoveryCommand for session
 resumption
• Handles ANSI stripping and error pattern detection for robust state classification

bin/lib/runtime-recovery.js


13. bin/nemoclaw.js ✨ Enhancement +5/-6

Add onboard resume flag support to CLI

• Added missing_named to gateway recovery state detection
• Extended onboard command to accept --resume flag alongside --non-interactive
• Updated usage message to document both onboard flags
• Passes resume parameter to runOnboard function

bin/nemoclaw.js


14. test/policies.test.js 🧪 Tests +35/-0

Add policy merge function unit tests

• Added comprehensive test suite for mergePresetIntoPolicy function with 4 test cases
• Tests version header injection for versionless policies
• Validates preset entry merging with existing network_policies sections
• Covers edge cases like empty policies and version preservation

test/policies.test.js


15. scripts/install.sh ⚙️ Configuration changes +19/-515

Convert scripts/install.sh to legacy wrapper

• Replaced full installer implementation with lightweight compatibility wrapper
• Wrapper redirects to root-level install.sh with deprecation warning
• Maintains backward compatibility for legacy script paths
• Simplifies maintenance by centralizing installer logic

scripts/install.sh


16. test/e2e/test-onboard-repair.sh 🧪 Tests +331/-0

Add E2E test for onboard resume repair scenarios

• New E2E test script validating onboard resume repair behavior (331 lines)
• Tests missing sandbox recreation, conflicting sandbox name rejection, and provider/model conflict
 detection
• Validates that resume detects unavailable recorded sandbox and recreates it
• Ensures explicit provider/model changes are rejected during resume

test/e2e/test-onboard-repair.sh


17. test/e2e/test-onboard-resume.sh 🧪 Tests +339/-0

Add E2E test for onboard resume completion

• New E2E test script for interrupted onboard to resume completion flow (339 lines)
• Tests non-interactive onboard failure after sandbox creation with resumable state
• Validates resume skips cached preflight, gateway, and sandbox steps
• Verifies credential hydration from stored credentials during resume

test/e2e/test-onboard-resume.sh


18. install.sh ✨ Enhancement +105/-35

Improve installer onboard resume and PATH recovery

• Enhanced print_done to show context-aware next steps based on onboard execution
• Added detect_shell_profile function to identify user's shell configuration file
• Improved verify_nemoclaw to track recovery directory and profile for PATH updates
• Modified run_onboard to detect and resume interrupted onboard sessions
• Enhanced post-install messaging with PATH recovery instructions

install.sh


19. scripts/nemoclaw-start.sh ✨ Enhancement +76/-0

Add proxy environment configuration for sandbox

• Added proxy environment configuration for sandbox gateway communication
• Configures HTTP_PROXY, HTTPS_PROXY, NO_PROXY with gateway IP (10.200.0.1:3128)
• Writes proxy configuration to ~/.bashrc and ~/.profile with idempotent markers
• Ensures proxy settings persist across interactive and login shell sessions

scripts/nemoclaw-start.sh


20. uninstall.sh ✨ Enhancement +4/-2

Improve uninstall shim detection and preservation

• Updated documentation to mention onboard-session.json removal
• Modified shim removal logic to distinguish between symlinks and regular files
• Preserves user-managed nemoclaw files in shim directory (not installer-managed)
• Only removes installer-created symlinks, leaving user files intact

uninstall.sh


21. scripts/debug.sh ✨ Enhancement +28/-0

Add onboard session diagnostics to debug output

• Added onboard session state collection to debug diagnostics
• Implements summarizeForDebug helper to extract and display session information
• Includes error handling for missing onboard-session.js or Node.js
• Displays "No onboard session state found" when session file is absent

scripts/debug.sh


22. nemoclaw/src/commands/migration-state.test.ts 🧪 Tests +141/-4

Expand migration state credential sanitization tests

• Enhanced test to verify credential field stripping from sandbox openclaw.json
• Added test for pattern-matched credential fields (accessToken, privateKey, clientSecret, etc.)
• Added test for missing blueprint file error handling
• Added test to verify credential sanitization in snapshot directory itself

nemoclaw/src/commands/migration-state.test.ts


23. nemoclaw/src/commands/migration-state.ts Security +97/-25

Implement credential sanitization for migration snapshots

• Implemented stripCredentials recursive function to redact sensitive fields from config objects
• Added isCredentialField detection with explicit set and pattern-based matching
• Implemented sanitizeConfigFile to strip credentials and remove gateway config before migration
• Enhanced computeFileDigest to throw error for missing blueprint files
• Applied sanitization to both snapshot and prepared state directories

nemoclaw/src/commands/migration-state.ts


24. test/onboard-selection.test.js Additional files +0/-1

...

test/onboard-selection.test.js


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Mar 28, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Disconnected read as connected 🐞 Bug ✓ Correctness
Description
Gateway recovery/health checks use substring tests for "Connected" (e.g.,
status.includes("Connected")), which also match "Disconnected" and can incorrectly treat a
disconnected gateway as connected and set OPENSHELL_GATEWAY. This can cause NemoClaw to skip gateway
start/recovery and later fail when trying to use the gateway runtime.
Code

bin/lib/onboard.js[R1682-1684]

+  let status = runCaptureOpenshell(["status"], { ignoreError: true });
+  if (status.includes("Connected") && isSelectedGateway(status)) {
+    process.env.OPENSHELL_GATEWAY = GATEWAY_NAME;
Evidence
The PR adds/uses substring-based connection checks: isGatewayConnected() returns true if the
status output contains "Connected", and recoverGatewayRuntime() treats the gateway as connected
based on status.includes("Connected"). Because "Disconnected" contains the substring "Connected",
disconnected status outputs (which the tests explicitly model as realistic) can be misclassified as
connected, leading to incorrect OPENSHELL_GATEWAY selection and recovery behavior.

bin/lib/onboard.js[199-250]
bin/lib/onboard.js[1680-1705]
test/onboard.test.js[210-269]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Gateway connectivity checks treat any output containing the substring `"Connected"` as connected, which also matches `"Disconnected"`. This can incorrectly mark a disconnected gateway as healthy/connected and set `OPENSHELL_GATEWAY`, breaking subsequent gateway operations.

### Issue Context
`recoverGatewayRuntime()` and `isGatewayConnected()` are used to decide whether to reuse or recover the named gateway; a false-positive “connected” result can skip recovery and poison later steps.

### Fix
- Replace substring checks with a stricter parse, e.g.:
 - Use a regex that matches a full status token: `/\bStatus:\s*Connected\b/` or `/\bGateway status:\s*Connected\b/`.
 - Or explicitly reject `Disconnected` before accepting `Connected`.
- Apply the same stricter predicate everywhere `Connected` is checked (including `recoverGatewayRuntime()` loops and `isGatewayConnected()`).
- Add/adjust tests to include a status string that contains `Disconnected` alongside a `Gateway:` line to prevent regressions.

### Fix Focus Areas
- bin/lib/onboard.js[207-209]
- bin/lib/onboard.js[1680-1705]
- test/onboard.test.js[210-269]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Shell PATH hint invalid 🐞 Bug ⚙ Maintainability
Description
install.sh detects fish/csh/tcsh profiles but prints bash-specific export PATH=... guidance and
asks users to source those profiles, which will not work in fish/csh/tcsh. This can make the
post-install recovery steps fail for users whose current shell cannot resolve nemoclaw yet.
Code

install.sh[R653-654]

+  echo "    export PATH=\"${NEMOCLAW_RECOVERY_EXPORT_DIR}:\$PATH\""
+  echo "    source ${NEMOCLAW_RECOVERY_PROFILE}"
Evidence
The installer explicitly selects non-bash shell profile files (fish/tcsh/csh), but the recovery
instructions it prints are bash syntax (export PATH=...). These commands are not valid in
fish/csh/tcsh, so users following the printed instructions may still be unable to fix PATH in their
current shell.

install.sh[275-297]
install.sh[125-158]
install.sh[632-663]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The installer detects non-bash shells (fish/csh/tcsh) when choosing a profile file, but prints bash-only PATH instructions (`export PATH=...`) and generic `source` guidance. These instructions are incorrect for fish/csh/tcsh.

### Issue Context
This message is shown when the just-installed `nemoclaw` cannot be resolved in the current shell session, so the correctness of the remediation instructions matters.

### Fix
- Extend `detect_shell_profile()` (or add a `detect_shell_kind()` helper) to return both the profile path and shell type.
- Print shell-appropriate PATH update commands:
 - bash/zsh/sh: `export PATH="dir:$PATH"`
 - fish: `set -gx PATH dir $PATH` (and optionally `source ~/.config/fish/config.fish`)
 - csh/tcsh: `setenv PATH "dir:${PATH}"`
- Alternatively, for non-bash shells, avoid printing inline commands and instead instruct users to open a new terminal or manually update PATH in the detected profile.

### Fix Focus Areas
- install.sh[275-297]
- install.sh[125-158]
- install.sh[632-663]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

const now = new Date().toISOString();
return {
version: SESSION_VERSION,
sessionId: overrides.sessionId || `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
const config = parsed as Record<string, unknown>;
delete config["gateway"];
const sanitized = stripCredentials(config) as Record<string, unknown>;
writeFileSync(configPath, JSON.stringify(sanitized, null, 2));

Check failure

Code scanning / CodeQL

Potential file system race condition High

The file may have changed since it
was checked
.
expect(output).not.toMatch(/colima should not be started/);
expect(result.status).toBe(0);
expect(output).toMatch(/deprecated compatibility wrapper/);
expect(output).toMatch(/https:\/\/www\.nvidia\.com\/nemoclaw\.sh/);

Check failure

Code scanning / CodeQL

Missing regular expression anchor High test

When this is used as a regular expression on a URL, it may match anywhere, and arbitrary hosts may come before or after it.
expect(result.status).not.toBe(0);
expect(output).toMatch(/deprecated compatibility wrapper/);
expect(output).toMatch(/supported installer/);
expect(output).toMatch(/https:\/\/www\.nvidia\.com\/nemoclaw\.sh/);

Check failure

Code scanning / CodeQL

Missing regular expression anchor High test

When this is used as a regular expression on a URL, it may match anywhere, and arbitrary hosts may come before or after it.
Comment thread test/service-env.test.js
'export no_proxy="localhost,127.0.0.1,::1,10.200.0.1"',
"# nemoclaw-proxy-config end",
].join("\n");
writeFileSync(join(fakeHome, ".bashrc"), bashrcContent);

Check failure

Code scanning / CodeQL

Insecure temporary file High test

Insecure creation of file in
the os temp dir
.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 1 potential issue.

View 7 additional findings in Devin Review.

Open in Devin Review

Comment thread bin/lib/onboard.js
Comment on lines +2880 to +2883
if (resumeGateway) {
resumeStepMessage("gateway", "running");
} else if (!resume && canReuseHealthyGateway) {
note(" Reusing healthy NemoClaw gateway.");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Missing gateway selection and OPENSHELL_GATEWAY env var when reusing a healthy gateway

When the new onboard() function detects a healthy gateway, both the resume path (line 2880) and the non-resume path (line 2882) skip calling runOpenshell(["gateway", "select", GATEWAY_NAME]) and never set process.env.OPENSHELL_GATEWAY = GATEWAY_NAME. Since process.env.OPENSHELL_GATEWAY is explicitly deleted at bin/lib/onboard.js:2778, all subsequent openshell commands (sandbox create, inference set, etc.) may target the wrong gateway or no gateway at all.

The old code handled this in preflight() (lines 1266–1270 in the LEFT diff) by calling gateway select and setting the env var whenever a healthy gateway was found. The new startGatewayWithOptions() at bin/lib/onboard.js:1595-1598 also handles the healthy-gateway case correctly, but it's never invoked when the onboard() function shortcuts past the gateway step. The setupInference function at line 2290 does call gateway select, but if inference is also skipped on resume, no selection happens at all before sandbox creation or openclaw setup.

Suggested change
if (resumeGateway) {
resumeStepMessage("gateway", "running");
} else if (!resume && canReuseHealthyGateway) {
note(" Reusing healthy NemoClaw gateway.");
if (resumeGateway) {
resumeStepMessage("gateway", "running");
runOpenshell(["gateway", "select", GATEWAY_NAME], { ignoreError: true });
process.env.OPENSHELL_GATEWAY = GATEWAY_NAME;
} else if (!resume && canReuseHealthyGateway) {
note(" Reusing healthy NemoClaw gateway.");
runOpenshell(["gateway", "select", GATEWAY_NAME], { ignoreError: true });
process.env.OPENSHELL_GATEWAY = GATEWAY_NAME;
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread scripts/nemoclaw-start.sh
Comment on lines +264 to +277
_write_proxy_snippet() {
local target="$1"
if [ -f "$target" ] && grep -qF "$_PROXY_MARKER_BEGIN" "$target" 2>/dev/null; then
local tmp
tmp="$(mktemp)"
awk -v b="$_PROXY_MARKER_BEGIN" -v e="$_PROXY_MARKER_END" \
'$0==b{s=1;next} $0==e{s=0;next} !s' "$target" >"$tmp"
printf '%s\n' "$_PROXY_SNIPPET" >>"$tmp"
cat "$tmp" >"$target"
rm -f "$tmp"
return 0
fi
printf '\n%s\n' "$_PROXY_SNIPPET" >>"$target"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Low scripts/nemoclaw-start.sh:264

The awk filter in _write_proxy_snippet silently deletes everything from the begin marker to EOF when the end marker is missing. For example, if .bashrc contains user aliases after a corrupted proxy block, those aliases are permanently lost. The grep check only verifies the begin marker exists, not that both markers are present.

-_write_proxy_snippet() {
-  local target="$1"
-  if [ -f "$target" ] && grep -qF "$_PROXY_MARKER_BEGIN" "$target" 2>/dev/null; then
-    local tmp
-    tmp="$(mktemp)"
-    awk -v b="$_PROXY_MARKER_BEGIN" -v e="$_PROXY_MARKER_END" \
-      '$0==b{s=1;next} $0==e{s=0;next} !s' "$target" >"$tmp"
-    printf '%s\n' "$_PROXY_SNIPPET" >>"$tmp"
-    cat "$tmp" >"$target"
-    rm -f "$tmp"
-    return 0
-  fi
-  printf '\n%s\n' "$_PROXY_SNIPPET" >>"$target"
-}
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file scripts/nemoclaw-start.sh around lines 264-277:

The `awk` filter in `_write_proxy_snippet` silently deletes everything from the begin marker to EOF when the end marker is missing. For example, if `.bashrc` contains user aliases after a corrupted proxy block, those aliases are permanently lost. The `grep` check only verifies the begin marker exists, not that both markers are present.

Comment thread bin/lib/policies.js
Comment on lines 113 to +114
let merged;
if (currentPolicy && currentPolicy.includes("network_policies:")) {
// Find the network_policies: line and append the new entries after it
// We need to insert before the next top-level key or end of file
if (/^network_policies\s*:/m.test(currentPolicy)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Low lib/policies.js:113

The regex /^network_policies\s*:/ in mergePresetIntoPolicy matches inline values like network_policies: [] or network_policies: {}, then appends indented preset entries after them. This produces syntactically invalid YAML where block-style entries follow an inline collection, causing openshell policy set to fail when the current policy has an empty inline array.

-  if (/^network_policies\s*:/m.test(currentPolicy)) {
+  if (/^network_policies:\s*$/m.test(currentPolicy)) {
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file bin/lib/policies.js around lines 113-114:

The regex `/^network_policies\s*:/` in `mergePresetIntoPolicy` matches inline values like `network_policies: []` or `network_policies: {}`, then appends indented preset entries after them. This produces syntactically invalid YAML where block-style entries follow an inline collection, causing `openshell policy set` to fail when the current policy has an empty inline array.

Evidence trail:
bin/lib/policies.js lines 113-140 at REVIEWED_COMMIT - The regex `/^network_policies\s*:/` at line 124 matches inline values. When matched, line 125 pushes the original line (e.g., `network_policies: []`) to result, then lines 138-140 append `presetEntries` (indented block entries) after. This produces invalid YAML where block-style entries follow an inline collection.

Comment thread bin/lib/onboard.js
Comment on lines +207 to +209
function isGatewayConnected(statusOutput = "") {
return typeof statusOutput === "string" && statusOutput.includes("Connected");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High lib/onboard.js:207

isGatewayConnected returns true when statusOutput contains the substring "Connected", including for values like "Disconnected" or "Not Connected". This causes getGatewayReuseState to misclassify a disconnected gateway as connected or "healthy".

-function isGatewayConnected(statusOutput = "") {
-  return typeof statusOutput === "string" && statusOutput.includes("Connected");
+function isGatewayConnected(statusOutput = "") {
+  return typeof statusOutput === "string" && statusOutput.trim() === "Connected";
}
Also found in 1 other location(s)

bin/lib/runtime-recovery.js:17

The regex /^(NAME|No sandboxes found\.?$)/i incorrectly skips any sandbox whose name starts with "name" (case-insensitive). For example, a sandbox named namesandbox would have its line start with "namesandbox" which matches ^NAME in the alternation, causing it to be silently excluded from the returned set. The fix should require whitespace after NAME to correctly identify only the header line, e.g., /^NAME\s|^No sandboxes found\.?$/i.

🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file bin/lib/onboard.js around lines 207-209:

`isGatewayConnected` returns `true` when `statusOutput` contains the substring "Connected", including for values like "Disconnected" or "Not Connected". This causes `getGatewayReuseState` to misclassify a disconnected gateway as connected or "healthy".

Evidence trail:
bin/lib/onboard.js lines 207-208 (isGatewayConnected function using .includes("Connected")), lines 222-229 (isGatewayHealthy using isGatewayConnected), lines 231-250 (getGatewayReuseState using both functions). Test file test/onboard.test.js lines 249-253 shows expected behavior with "Disconnected" input expecting "stale" result.

Also found in 1 other location(s):
- bin/lib/runtime-recovery.js:17 -- The regex `/^(NAME|No sandboxes found\.?$)/i` incorrectly skips any sandbox whose name starts with "name" (case-insensitive). For example, a sandbox named `namesandbox` would have its line start with "namesandbox" which matches `^NAME` in the alternation, causing it to be silently excluded from the returned set. The fix should require whitespace after NAME to correctly identify only the header line, e.g., `/^NAME\s|^No sandboxes found\.?$/i`.

Comment thread bin/lib/onboard.js
Comment on lines +2534 to +2546
if (chosen && chosen.length > 0) {
if (onSelection) onSelection(chosen);
if (!waitForSandboxReady(sandboxName)) {
console.error(` Sandbox '${sandboxName}' was not ready for policy application.`);
process.exit(1);
}
note(` [resume] Reapplying policy presets: ${chosen.join(", ")}`);
for (const name of chosen) {
if (applied.includes(name)) continue;
policies.applyPreset(sandboxName, name);
}
return chosen;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Low lib/onboard.js:2534

The resume path (lines 2534-2545) passes selectedPresets directly to policies.applyPreset() without validating against allPresets. If a preset was valid in a prior session but has since been removed or renamed, the call fails with an unclear error from deep in the policy stack instead of the helpful "Unknown policy preset(s)" message shown in other paths. Consider adding the same validation and early exit used in the non-interactive (2574-2579) and interactive (2631-2636) branches.

  if (chosen && chosen.length > 0) {
+    const knownPresets = new Set(allPresets.map((p) => p.name));
+    const invalidPresets = chosen.filter((name) => !knownPresets.has(name));
+    if (invalidPresets.length > 0) {
+      console.error(`  Unknown policy preset(s): ${invalidPresets.join(", ")}`);
+      process.exit(1);
+    }
+
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file bin/lib/onboard.js around lines 2534-2546:

The resume path (lines 2534-2545) passes `selectedPresets` directly to `policies.applyPreset()` without validating against `allPresets`. If a preset was valid in a prior session but has since been removed or renamed, the call fails with an unclear error from deep in the policy stack instead of the helpful "Unknown policy preset(s)" message shown in other paths. Consider adding the same validation and early exit used in the non-interactive (2574-2579) and interactive (2631-2636) branches.

Evidence trail:
bin/lib/onboard.js lines 2520-2650 (viewed at REVIEWED_COMMIT): Resume path at lines ~2534-2545 calls `policies.applyPreset(sandboxName, name)` without validation. Non-interactive path at lines ~2574-2579 validates with `knownPresets` and `invalidPresets` check. Interactive path at lines ~2631-2636 uses same validation pattern.

Comment thread bin/lib/onboard.js
const resumeInference =
resume &&
typeof provider === "string" &&
typeof model === "string" &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium lib/onboard.js:2940

registry.updateSandbox(sandboxName, { nimContainer }) at lines 2945 and 2953 is called before sandboxName is assigned a value (it remains null from line 2901 until lines 2974-2976). When resuming after provider_selection with nim-local or during fresh runs with a NIM container, this passes null to the registry, creating invalid state or causing errors.

🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file bin/lib/onboard.js around line 2940:

`registry.updateSandbox(sandboxName, { nimContainer })` at lines 2945 and 2953 is called before `sandboxName` is assigned a value (it remains `null` from line 2901 until lines 2974-2976). When resuming after `provider_selection` with `nim-local` or during fresh runs with a NIM container, this passes `null` to the registry, creating invalid state or causing errors.

Evidence trail:
bin/lib/onboard.js lines 2901-2980 (REVIEWED_COMMIT): Shows sandboxName initialized to `session?.sandboxName || null` at line 2901, `registry.updateSandbox(sandboxName, { nimContainer })` calls at lines 2945 and 2953 (inference step), and sandboxName assignment at lines 2974-2976 (sandbox step, which runs after inference step). bin/lib/registry.js lines 58-64: `updateSandbox(name, updates)` returns false if `data.sandboxes[name]` doesn't exist, meaning passing `null` causes the update to silently fail.

Comment thread bin/lib/onboard.js
Comment on lines +1682 to +1684
let status = runCaptureOpenshell(["status"], { ignoreError: true });
if (status.includes("Connected") && isSelectedGateway(status)) {
process.env.OPENSHELL_GATEWAY = GATEWAY_NAME;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Disconnected read as connected 🐞 Bug ✓ Correctness

Gateway recovery/health checks use substring tests for "Connected" (e.g.,
status.includes("Connected")), which also match "Disconnected" and can incorrectly treat a
disconnected gateway as connected and set OPENSHELL_GATEWAY. This can cause NemoClaw to skip gateway
start/recovery and later fail when trying to use the gateway runtime.
Agent Prompt
### Issue description
Gateway connectivity checks treat any output containing the substring `"Connected"` as connected, which also matches `"Disconnected"`. This can incorrectly mark a disconnected gateway as healthy/connected and set `OPENSHELL_GATEWAY`, breaking subsequent gateway operations.

### Issue Context
`recoverGatewayRuntime()` and `isGatewayConnected()` are used to decide whether to reuse or recover the named gateway; a false-positive “connected” result can skip recovery and poison later steps.

### Fix
- Replace substring checks with a stricter parse, e.g.:
  - Use a regex that matches a full status token: `/\bStatus:\s*Connected\b/` or `/\bGateway status:\s*Connected\b/`.
  - Or explicitly reject `Disconnected` before accepting `Connected`.
- Apply the same stricter predicate everywhere `Connected` is checked (including `recoverGatewayRuntime()` loops and `isGatewayConnected()`).
- Add/adjust tests to include a status string that contains `Disconnected` alongside a `Gateway:` line to prevent regressions.

### Fix Focus Areas
- bin/lib/onboard.js[207-209]
- bin/lib/onboard.js[1680-1705]
- test/onboard.test.js[210-269]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@greptile-apps

greptile-apps Bot commented Mar 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This upstream sync (2026-03-28) layers significant new capability onto the NemoClaw CLI: a persistent, resumable onboarding session (bin/lib/onboard-session.js), a nemoclaw onboard --resume command, improved gateway-state classification, proxy-environment injection in sandbox shells, and recursive credential sanitization before config files enter sandbox bundles. The WOPR sidecar (wopr/sidecar.js) is untouched, and the CI workflow correctly uses [self-hosted, Linux, X64] runners.

Key changes and findings:

  • Resumable onboarding — onboard-session.js implements atomic file-based sessions with O_EXCL locking, TOCTOU-mitigated stale-lock eviction, and per-step state tracking. Solid overall; one edge-case where stale: true is returned when the lock is actually contested by a live process.
  • Credential cleanup regression (P1) — When both resumeProviderSelection and resumeInference are true, hydrateCredentialEnv loads the API key into process.env but delete process.env.NVIDIA_API_KEY is never called (it only runs in the non-resume inference branch). The key persists in the environment for all subsequent child processes.
  • Spurious sandbox deletion (P2) — getSandboxStateFromOutputs returns \"not_ready\" when openshell sandbox list returns empty output (transient failure), even though openshell sandbox get confirmed the sandbox exists. During resume this triggers repairRecordedSandbox → sandbox delete, destroying a healthy sandbox unnecessarily.
  • Credential sanitization — migration-state.ts adds recursive stripCredentials and sanitizeConfigFile applied to both the sandbox bundle and the snapshot-level copy of openclaw.json; well-tested and a clear security improvement.
  • scripts/install.sh simplification — The 500-line standalone installer is replaced by a 31-line compatibility wrapper that delegates to the root install.sh, with a clear deprecation warning.
  • Proxy config — scripts/nemoclaw-start.sh correctly sets both HTTP_PROXY/http_proxy and avoids bypassing inference.local, with idempotent marker-delimited shell profile injection.

Confidence Score: 4/5

Safe to merge after resolving the credential-cleanup regression and the sandbox misclassification on transient list failures.

One clear P1 defect (API key not deleted from process.env in the full-resume path) reduces the score from 5. The P2 sandbox misclassification issue can cause unintended sandbox deletion on transient errors, compounding the risk slightly. All other changes are well-implemented and tested.

bin/lib/onboard.js — credential cleanup missing in resumeInference branch, and getSandboxStateFromOutputs misclassification on empty listOutput.

Important Files Changed

Filename Overview
bin/lib/onboard.js Major refactor introducing --resume flow: two issues — API key not cleared when inference step is skipped on resume, and getSandboxStateFromOutputs can trigger spurious sandbox deletion on transient list failures.
bin/lib/onboard-session.js New file: atomic session persistence, lock acquisition, and per-step state tracking for resumable onboarding; well-structured with TOCTOU mitigations and sensitive-data redaction, but spurious stale: true on contested lock.
bin/lib/runtime-recovery.js New file: pure classification helpers for gateway/sandbox state used by recovery paths; clean, well-tested, no issues found.
bin/lib/policies.js Refactors applyPreset to extract a pure mergePresetIntoPolicy helper; logic is equivalent to the original, version-header guard is correct, and the extracted function improves testability.
nemoclaw/src/commands/migration-state.ts Adds recursive stripCredentials and sanitizeConfigFile to scrub API keys/tokens from snapshot bundles before sandbox delivery; computeFileDigest now throws instead of returning null, relying on an implicit outer catch for the missing-blueprint case.
scripts/install.sh Replaced ~500-line standalone installer with a thin 31-line wrapper that delegates to the canonical root install.sh; leaves a clear deprecation warning and fails fast outside a repo checkout.
scripts/nemoclaw-start.sh Adds idempotent proxy-environment setup (HTTP_PROXY/HTTPS_PROXY/NO_PROXY) with marker-delimited bashrc/profile injection; correctly avoids bypassing inference.local through the proxy.
bin/nemoclaw.js Adds --resume flag to CLI dispatch and expands recoverNamedGatewayRuntime to handle the missing_named gateway state; removes the pre-connect port-forward call.
install.sh Improves post-install messaging for three states (onboarded, PATH-ready, PATH-not-yet-updated); adds detect_shell_profile for fish/tcsh/csh; adds session-resume detection in run_onboard.
nemoclaw/src/commands/migration-state.test.ts Adds test coverage for pattern-matched credential stripping, snapshot-level sanitization, and missing-blueprint failure; tests are comprehensive and match the new implementation.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A([nemoclaw onboard --resume]) --> B{Load session}
    B -- not found --> ERR1([exit 1])
    B -- found --> C{Config conflicts?}
    C -- conflicts --> ERR2([exit 1])
    C -- none --> D[preflight cached?]
    D --> E{gateway healthy?}
    E -- healthy --> F[Skip gateway]
    E -- stale/missing --> G[startGateway]
    F --> H
    G --> H
    H{provider_selection cached?} -- yes --> I[hydrateCredentialEnv
key in process.env]
    H -- no --> J[setupNim]
    I --> K
    J --> K
    K{inference route ready?} -- yes resume --> L[⚠ key NOT deleted
stays in env]
    K -- no --> M[setupInference
delete process.env.KEY]
    L --> N
    M --> N
    N{sandbox state?} -- ready --> O[Skip sandbox]
    N -- not_ready
⚠ also on list failure --> P[repairRecordedSandbox
delete + recreate]
    N -- missing --> Q[createSandbox]
    O --> R
    P --> R
    Q --> R
    R{openclaw ready?} -- yes --> S[Skip]
    R -- no --> T[setupOpenclaw]
    S --> U
    T --> U
    U{policies applied?} -- yes --> V[Skip]
    U -- no --> W[setupPolicies]
    V --> X
    W --> X
    X[completeSession / printDashboard]
    style L fill:#ff9999
    style P fill:#ffcc99
Loading

Comments Outside Diff (3)

  1. bin/lib/onboard.js, line 1457-1464 (link)

    P1 Credential not cleared when inference step is skipped on resume

    When resumeProviderSelection is true, hydrateCredentialEnv(credentialEnv) loads the API key (e.g., NVIDIA_API_KEY) into process.env. When resumeInference is subsequently also true, the inference step is skipped and delete process.env.NVIDIA_API_KEY is never called. In contrast, the non-resume inference branch explicitly removes the key:

    // non-resume path (below, in the else branch)
    await setupInference(GATEWAY_NAME, model, provider, endpointUrl, credentialEnv);
    delete process.env.NVIDIA_API_KEY;

    This means that for a full-resume run (all steps cached), the API key stays in process.env and is inherited by every child process spawned during sandbox creation, openclaw setup, and policy application. The fix is to apply the same cleanup in the resumeInference branch:

    if (resumeInference) {
      resumeStepMessage("inference", `${provider} / ${model}`);
      delete process.env[credentialEnv || "NVIDIA_API_KEY"]; // mirror the non-resume cleanup
      if (nimContainer) {
        registry.updateSandbox(sandboxName, { nimContainer });
      }
      onboardSession.markStepComplete("inference", { sandboxName, provider, model, nimContainer });
    }
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: bin/lib/onboard.js
    Line: 1457-1464
    
    Comment:
    **Credential not cleared when inference step is skipped on resume**
    
    When `resumeProviderSelection` is `true`, `hydrateCredentialEnv(credentialEnv)` loads the API key (e.g., `NVIDIA_API_KEY`) into `process.env`. When `resumeInference` is subsequently also `true`, the inference step is skipped and `delete process.env.NVIDIA_API_KEY` is never called. In contrast, the non-resume inference branch explicitly removes the key:
    
    ```js
    // non-resume path (below, in the else branch)
    await setupInference(GATEWAY_NAME, model, provider, endpointUrl, credentialEnv);
    delete process.env.NVIDIA_API_KEY;
    ```
    
    This means that for a full-resume run (all steps cached), the API key stays in `process.env` and is inherited by every child process spawned during sandbox creation, openclaw setup, and policy application. The fix is to apply the same cleanup in the `resumeInference` branch:
    
    ```js
    if (resumeInference) {
      resumeStepMessage("inference", `${provider} / ${model}`);
      delete process.env[credentialEnv || "NVIDIA_API_KEY"]; // mirror the non-resume cleanup
      if (nimContainer) {
        registry.updateSandbox(sandboxName, { nimContainer });
      }
      onboardSession.markStepComplete("inference", { sandboxName, provider, model, nimContainer });
    }
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

  2. bin/lib/onboard.js, line 553-556 (link)

    P2 Transient openshell sandbox list failure misclassifies a healthy sandbox as not_ready

    getSandboxStateFromOutputs trusts getOutput to determine existence but relies entirely on listOutput for readiness:

    function getSandboxStateFromOutputs(sandboxName, getOutput = "", listOutput = "") {
      if (!sandboxName) return "missing";
      if (!getOutput) return "missing";
      return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
    }

    If openshell sandbox list has a transient failure and returns empty output (while openshell sandbox get <name> succeeds), the sandbox is classified as "not_ready". During resume, "not_ready" triggers repairRecordedSandbox → openshell sandbox delete, destroying a perfectly healthy sandbox. Consider treating an empty listOutput conservatively:

    if (!listOutput) {
      return "ready"; // preserve existing sandbox when list is unavailable
    }
    return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: bin/lib/onboard.js
    Line: 553-556
    
    Comment:
    **Transient `openshell sandbox list` failure misclassifies a healthy sandbox as `not_ready`**
    
    `getSandboxStateFromOutputs` trusts `getOutput` to determine existence but relies entirely on `listOutput` for readiness:
    
    ```js
    function getSandboxStateFromOutputs(sandboxName, getOutput = "", listOutput = "") {
      if (!sandboxName) return "missing";
      if (!getOutput) return "missing";
      return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
    }
    ```
    
    If `openshell sandbox list` has a transient failure and returns empty output (while `openshell sandbox get <name>` succeeds), the sandbox is classified as `"not_ready"`. During resume, `"not_ready"` triggers `repairRecordedSandbox` → `openshell sandbox delete`, destroying a perfectly healthy sandbox. Consider treating an empty `listOutput` conservatively:
    
    ```js
    if (!listOutput) {
      return "ready"; // preserve existing sandbox when list is unavailable
    }
    return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

  3. nemoclaw/src/commands/migration-state.ts, line 2385-2391 (link)

    P2 computeFileDigest now throws; call-site in createSnapshotBundle is unguarded

    The refactored function throws on a missing file instead of returning null:

    function computeFileDigest(filePath: string): string {
      if (!existsSync(filePath)) {
        throw new Error(`Blueprint file not found: ${filePath}`);
      }
      ...
    }

    The call in createSnapshotBundle has no local try/catch; correctness relies on the outer catch in the function converting the throw to a null return + logger.error. This works but is implicit — consider adding a brief comment at the call-site noting that throws from computeFileDigest are handled by the surrounding try/catch.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: nemoclaw/src/commands/migration-state.ts
    Line: 2385-2391
    
    Comment:
    **`computeFileDigest` now throws; call-site in `createSnapshotBundle` is unguarded**
    
    The refactored function throws on a missing file instead of returning `null`:
    
    ```ts
    function computeFileDigest(filePath: string): string {
      if (!existsSync(filePath)) {
        throw new Error(`Blueprint file not found: ${filePath}`);
      }
      ...
    }
    ```
    
    The call in `createSnapshotBundle` has no local try/catch; correctness relies on the outer catch in the function converting the throw to a `null` return + `logger.error`. This works but is implicit — consider adding a brief comment at the call-site noting that throws from `computeFileDigest` are handled by the surrounding try/catch.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

Fix All in Claude Code

Prompt To Fix All With AI
This is a comment left during a code review.
Path: bin/lib/onboard.js
Line: 1457-1464

Comment:
**Credential not cleared when inference step is skipped on resume**

When `resumeProviderSelection` is `true`, `hydrateCredentialEnv(credentialEnv)` loads the API key (e.g., `NVIDIA_API_KEY`) into `process.env`. When `resumeInference` is subsequently also `true`, the inference step is skipped and `delete process.env.NVIDIA_API_KEY` is never called. In contrast, the non-resume inference branch explicitly removes the key:

```js
// non-resume path (below, in the else branch)
await setupInference(GATEWAY_NAME, model, provider, endpointUrl, credentialEnv);
delete process.env.NVIDIA_API_KEY;
```

This means that for a full-resume run (all steps cached), the API key stays in `process.env` and is inherited by every child process spawned during sandbox creation, openclaw setup, and policy application. The fix is to apply the same cleanup in the `resumeInference` branch:

```js
if (resumeInference) {
  resumeStepMessage("inference", `${provider} / ${model}`);
  delete process.env[credentialEnv || "NVIDIA_API_KEY"]; // mirror the non-resume cleanup
  if (nimContainer) {
    registry.updateSandbox(sandboxName, { nimContainer });
  }
  onboardSession.markStepComplete("inference", { sandboxName, provider, model, nimContainer });
}
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: bin/lib/onboard.js
Line: 553-556

Comment:
**Transient `openshell sandbox list` failure misclassifies a healthy sandbox as `not_ready`**

`getSandboxStateFromOutputs` trusts `getOutput` to determine existence but relies entirely on `listOutput` for readiness:

```js
function getSandboxStateFromOutputs(sandboxName, getOutput = "", listOutput = "") {
  if (!sandboxName) return "missing";
  if (!getOutput) return "missing";
  return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
}
```

If `openshell sandbox list` has a transient failure and returns empty output (while `openshell sandbox get <name>` succeeds), the sandbox is classified as `"not_ready"`. During resume, `"not_ready"` triggers `repairRecordedSandbox` → `openshell sandbox delete`, destroying a perfectly healthy sandbox. Consider treating an empty `listOutput` conservatively:

```js
if (!listOutput) {
  return "ready"; // preserve existing sandbox when list is unavailable
}
return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready";
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: bin/lib/onboard-session.js
Line: 234-278

Comment:
**`acquireOnboardLock` returns `stale: true` even when the lock is being contested**

The fallback at the end of the two-attempt loop:

```js
return { acquired: false, lockFile: LOCK_FILE, stale: true };
```

This is reached when both attempts discovered a stale lock (process not alive), deleted it, and still failed to claim it on retry. In a race between two concurrent `nemoclaw onboard` invocations, the loser reports `stale: true` even though another live process now holds the lock. The caller only checks `lockResult.acquired` so this is benign today, but the misleading flag could confuse future consumers. Consider returning `stale: false` in the fallback.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: nemoclaw/src/commands/migration-state.ts
Line: 2385-2391

Comment:
**`computeFileDigest` now throws; call-site in `createSnapshotBundle` is unguarded**

The refactored function throws on a missing file instead of returning `null`:

```ts
function computeFileDigest(filePath: string): string {
  if (!existsSync(filePath)) {
    throw new Error(`Blueprint file not found: ${filePath}`);
  }
  ...
}
```

The call in `createSnapshotBundle` has no local try/catch; correctness relies on the outer catch in the function converting the throw to a `null` return + `logger.error`. This works but is implicit — consider adding a brief comment at the call-site noting that throws from `computeFileDigest` are handled by the surrounding try/catch.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Resolve merge conflicts with upstream/ma..." | Re-trigger Greptile

Comment on lines +234 to +278
} catch (error) {
if (error?.code !== "EEXIST") {
throw error;
}

let existing;
try {
existing = parseLockFile(fs.readFileSync(LOCK_FILE, "utf8"));
} catch (readError) {
if (readError?.code === "ENOENT") {
continue;
}
throw readError;
}
if (!existing) {
continue;
}
if (existing && isProcessAlive(existing.pid)) {
return {
acquired: false,
lockFile: LOCK_FILE,
stale: false,
holderPid: existing.pid,
holderStartedAt: existing.startedAt,
holderCommand: existing.command,
};
}

try {
fs.unlinkSync(LOCK_FILE);
} catch (unlinkError) {
if (unlinkError?.code !== "ENOENT") {
throw unlinkError;
}
}
}
}

return { acquired: false, lockFile: LOCK_FILE, stale: true };
}

function releaseOnboardLock() {
try {
if (!fs.existsSync(LOCK_FILE)) return;
let existing = null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 acquireOnboardLock returns stale: true even when the lock is being contested

The fallback at the end of the two-attempt loop:

return { acquired: false, lockFile: LOCK_FILE, stale: true };

This is reached when both attempts discovered a stale lock (process not alive), deleted it, and still failed to claim it on retry. In a race between two concurrent nemoclaw onboard invocations, the loser reports stale: true even though another live process now holds the lock. The caller only checks lockResult.acquired so this is benign today, but the misleading flag could confuse future consumers. Consider returning stale: false in the fallback.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bin/lib/onboard-session.js
Line: 234-278

Comment:
**`acquireOnboardLock` returns `stale: true` even when the lock is being contested**

The fallback at the end of the two-attempt loop:

```js
return { acquired: false, lockFile: LOCK_FILE, stale: true };
```

This is reached when both attempts discovered a stale lock (process not alive), deleted it, and still failed to claim it on retry. In a race between two concurrent `nemoclaw onboard` invocations, the loser reports `stale: true` even though another live process now holds the lock. The caller only checks `lockResult.acquired` so this is benign today, but the misleading flag could confuse future consumers. Consider returning `stale: false` in the fallback.

How can I resolve this? If you propose a fix, please make it concise.

Fix in Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (1)
bin/lib/runtime-recovery.js (1)

6-9: Consider extracting shared stripAnsi utility.

The stripAnsi function is duplicated between this module and bin/nemoclaw.js (line 86-89). Consider extracting it to a shared utility module to reduce duplication.

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

In `@bin/lib/runtime-recovery.js` around lines 6 - 9, The stripAnsi function is
duplicated; extract it into a shared utility (e.g., export function
stripAnsi(text) from a new module) and replace the inline implementations in
runtime-recovery.js and nemoclaw.js with imports from that module; update both
files to require/import the new utility and remove the duplicated regex
implementation so both modules call the shared stripAnsi function (ensure the
exported name matches the call sites).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bin/lib/onboard.js`:
- Around line 1277-1292: The getEffectiveProviderName function normalizes
provider keys inconsistently: it maps "nim-local" to "nvidia-nim" while the code
persists the local NIM selection as "vllm-local", causing resume conflicts;
update getEffectiveProviderName so that the "nim-local" case returns the same
persisted string ("vllm-local") (or otherwise align the persisted value to the
normalization) to ensure getEffectiveProviderName("nim-local") matches the value
stored when selecting local NIM; change the switch case for "nim-local" in
getEffectiveProviderName to return "vllm-local" (or update the persistence site
to use "nvidia-nim") so both sides use the same identifier.
- Around line 2847-2855: The exit handler currently reads
onboardSession.loadSession() and unconditionally calls
onboardSession.markStepFailed(lastStepStarted) which can revert an already
completed step; change it to check the session state for the step referenced by
current.lastStepStarted and only call onboardSession.markStepFailed(...) if that
step's status is still "in_progress" (or equivalent in the session object).
Locate the exit handler using process.once("exit", ...) and use
onboardSession.loadSession(), current.lastStepStarted, and
onboardSession.markStepFailed(...) to implement the guard so completed steps are
not re-marked failed.
- Around line 441-448: The helper hydrateCredentialEnv currently mutates global
process.env (function hydrateCredentialEnv), which can leak stored API keys into
child sandboxes because createSandbox clones process.env and only strips
NVIDIA_API_KEY; change hydrateCredentialEnv to stop writing to process.env and
only return the credential value (or null), then update callers (places that
call hydrateCredentialEnv before spawning commands/sandboxes) to inject the
returned value into a per-command/env object passed to createSandbox or
child_process.spawn rather than relying on global process.env so sensitive keys
are never globally mutated or inherited by unrelated child processes.

In `@install.sh`:
- Around line 151-156: The recovery printout uses bash-only syntax for
NEMOCLAW_RECOVERY_EXPORT_DIR and NEMOCLAW_RECOVERY_PROFILE; update the logic
that formats those lines (use detect_shell_profile() or inspect the profile
path) to emit shell-appropriate commands: for bash/zsh print export
PATH="...:$PATH" and source <file>, for fish print set -gx PATH "<dir>" $PATH
and source <file>, and for csh/tcsh print setenv PATH "<dir>:$PATH" and source
<file>; apply this change to both places that print those recovery lines so
non-bash users get valid instructions, or as a fallback print a neutral message
like "update your profile and open a new terminal" if the shell cannot be
determined.

In `@nemoclaw/src/commands/migration-state.ts`:
- Around line 691-699: The snapshot creation is currently calling
sanitizeConfigFile which removes full "gateway" settings and causes
restoreSnapshotToHost() to lose non-secret gateway fields; instead, preserve
gateway keys except for credential fields when creating host-restorable
snapshots. Update the calls that sanitize the snapshot copy (the call after
copyDirectory for snapshotStateDir and the call after copyFileSync for
configSnapshotPath) to use a lighter sanitizer (e.g., a new
sanitizeConfigStripCredentials function or an option to sanitizeConfigFile like
{ stripCredentials: true, stripGatewayKeys: ['apiKey','secret'] } ) that only
strips credential-bearing fields from gateway while leaving other gateway
settings (such as gateway.inferenceProvider) intact; leave full
sanitizeConfigFile usage limited to prepareSandboxState() where completely
removing gateway is intended. Ensure references: copyDirectory,
sanitizeConfigFile (or new sanitizer), restoreSnapshotToHost,
prepareSandboxState, snapshotStateDir, hostState.configPath.
- Around line 540-549: The sanitizeConfigFile function currently reads/writes
configPath directly; update it to first use lstatSync(configPath) to ensure the
path exists, is a regular file (not a directory) and is not a symbolic link
(reject if stats.isSymbolicLink() or !stats.isFile()), then perform JSON5.parse
and stripCredentials as before but write the sanitized JSON to a temp file in
the same directory (e.g., `${configPath}.tmp`), set the temp file mode with
chmodSync, and atomically replace the original by renameSync(tempPath,
configPath) instead of writing directly with writeFileSync; keep existing calls
to existsSync, readFileSync, stripCredentials, and chmodSync semantics but move
chmodSync to the temp file before rename and ensure errors are thrown/reported
on non-regular or symlink targets.

In `@scripts/nemoclaw-start.sh`:
- Around line 264-281: The current _write_proxy_snippet function can follow
symlinks and append into arbitrary root-owned files; update it to first verify
the target is a regular file or a non-existent path (reject and skip if it's a
symlink, device, or other non-regular file) and when writing, write into a
secure temporary file (e.g. via mktemp) and atomically replace the target with
mv (not cat >>), ensuring you preserve permissions/ownership as needed;
reference _write_proxy_snippet, $_PROXY_MARKER_BEGIN/END and $_PROXY_SNIPPET for
where to read/insert the snippet and use $_SANDBOX_HOME invocations that call
_write_proxy_snippet to ensure dotfiles are never followed if symlinked.

---

Nitpick comments:
In `@bin/lib/runtime-recovery.js`:
- Around line 6-9: The stripAnsi function is duplicated; extract it into a
shared utility (e.g., export function stripAnsi(text) from a new module) and
replace the inline implementations in runtime-recovery.js and nemoclaw.js with
imports from that module; update both files to require/import the new utility
and remove the duplicated regex implementation so both modules call the shared
stripAnsi function (ensure the exported name matches the call sites).
🪄 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: Pro

Run ID: f6db4825-5b87-4987-a7a9-6ea34b689b10

📥 Commits

Reviewing files that changed from the base of the PR and between 4cfa2c4 and e32ccc6.

📒 Files selected for processing (24)
  • bin/lib/onboard-session.js
  • bin/lib/onboard.js
  • bin/lib/policies.js
  • bin/lib/runtime-recovery.js
  • bin/nemoclaw.js
  • install.sh
  • nemoclaw/src/commands/migration-state.test.ts
  • nemoclaw/src/commands/migration-state.ts
  • scripts/debug.sh
  • scripts/install.sh
  • scripts/nemoclaw-start.sh
  • test/cli.test.js
  • test/e2e/test-onboard-repair.sh
  • test/e2e/test-onboard-resume.sh
  • test/install-preflight.test.js
  • test/nemoclaw-cli-recovery.test.js
  • test/onboard-selection.test.js
  • test/onboard-session.test.js
  • test/onboard.test.js
  • test/policies.test.js
  • test/runtime-recovery.test.js
  • test/service-env.test.js
  • test/uninstall.test.js
  • uninstall.sh
💤 Files with no reviewable changes (1)
  • test/onboard-selection.test.js

Comment thread bin/lib/onboard.js
Comment on lines +441 to +448
function hydrateCredentialEnv(envName) {
if (!envName) return null;
const value = getCredential(envName);
if (value) {
process.env[envName] = value;
}
return value || null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid hydrating stored credentials into global process.env.

This helper mutates process-global state, and later createSandbox() clones that object while only stripping NVIDIA_API_KEY. After a resumed OpenAI/Anthropic/Gemini/custom flow, the stored API key can leak into unrelated child processes even though sandbox creation is supposed to run with non-sensitive env only.

🔒 Suggested fix
 function hydrateCredentialEnv(envName) {
   if (!envName) return null;
-  const value = getCredential(envName);
-  if (value) {
-    process.env[envName] = value;
-  }
-  return value || null;
+  return getCredential(envName) || process.env[envName] || null;
 }

Keep using the returned value via per-command env objects instead of mutating global process state.

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

In `@bin/lib/onboard.js` around lines 441 - 448, The helper hydrateCredentialEnv
currently mutates global process.env (function hydrateCredentialEnv), which can
leak stored API keys into child sandboxes because createSandbox clones
process.env and only strips NVIDIA_API_KEY; change hydrateCredentialEnv to stop
writing to process.env and only return the credential value (or null), then
update callers (places that call hydrateCredentialEnv before spawning
commands/sandboxes) to inject the returned value into a per-command/env object
passed to createSandbox or child_process.spawn rather than relying on global
process.env so sensitive keys are never globally mutated or inherited by
unrelated child processes.

Comment thread bin/lib/onboard.js
Comment on lines +1277 to +1292
function getEffectiveProviderName(providerKey) {
if (!providerKey) return null;
if (REMOTE_PROVIDER_CONFIG[providerKey]) {
return REMOTE_PROVIDER_CONFIG[providerKey].providerName;
}

switch (providerKey) {
case "nim-local":
return "nvidia-nim";
case "ollama":
return "ollama-local";
case "vllm":
return "vllm-local";
default:
return providerKey;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Normalize nim-local to the same provider name you persist.

getEffectiveProviderName("nim-local") returns nvidia-nim, but Line 2149 stores the successful local-NIM selection as vllm-local. That makes non-interactive --resume report a provider conflict even when the user reruns with the same NEMOCLAW_PROVIDER=nim setting.

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

In `@bin/lib/onboard.js` around lines 1277 - 1292, The getEffectiveProviderName
function normalizes provider keys inconsistently: it maps "nim-local" to
"nvidia-nim" while the code persists the local NIM selection as "vllm-local",
causing resume conflicts; update getEffectiveProviderName so that the
"nim-local" case returns the same persisted string ("vllm-local") (or otherwise
align the persisted value to the normalization) to ensure
getEffectiveProviderName("nim-local") matches the value stored when selecting
local NIM; change the switch case for "nim-local" in getEffectiveProviderName to
return "vllm-local" (or update the persistence site to use "nvidia-nim") so both
sides use the same identifier.

Comment thread bin/lib/onboard.js
Comment on lines +2512 to +2515
function arePolicyPresetsApplied(sandboxName, selectedPresets = []) {
if (!Array.isArray(selectedPresets) || selectedPresets.length === 0) return false;
const applied = new Set(policies.getAppliedPresets(sandboxName));
return selectedPresets.every((preset) => applied.has(preset));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Preserve an explicit “skip all presets” choice across --resume.

[] is a valid recorded selection here, but the helper treats it as “not applied” and the resume caller drops it because of the length > 0 gate. If an interrupted session had already recorded policyPresets: [], resume falls back to current defaults/prompting and can apply presets the user explicitly skipped.

💡 Suggested fix
-function arePolicyPresetsApplied(sandboxName, selectedPresets = []) {
-  if (!Array.isArray(selectedPresets) || selectedPresets.length === 0) return false;
+function arePolicyPresetsApplied(sandboxName, selectedPresets = null) {
+  if (!Array.isArray(selectedPresets)) return false;
+  if (selectedPresets.length === 0) return true;
   const applied = new Set(policies.getAppliedPresets(sandboxName));
   return selectedPresets.every((preset) => applied.has(preset));
 }
         selectedPresets:
           resume &&
           session?.steps?.policies?.status !== "complete" &&
-          Array.isArray(recordedPolicyPresets) &&
-          recordedPolicyPresets.length > 0
+          Array.isArray(recordedPolicyPresets)
             ? recordedPolicyPresets
             : null,

Also applies to: 2519-2546, 2991-3012

Comment thread bin/lib/onboard.js
Comment on lines +2847 to +2855
process.once("exit", (code) => {
if (!completed && code !== 0) {
const current = onboardSession.loadSession();
const failedStep = current?.lastStepStarted;
if (failedStep) {
onboardSession.markStepFailed(failedStep, "Onboarding exited before the step completed.");
}
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Only mark the last step failed if it is still in_progress.

This hook keys only off lastStepStarted. Because bin/lib/onboard-session.js leaves that field untouched after markStepComplete(), a crash between steps can flip an already completed step back to failed and break the next --resume.

🩹 Suggested fix
     process.once("exit", (code) => {
       if (!completed && code !== 0) {
         const current = onboardSession.loadSession();
         const failedStep = current?.lastStepStarted;
-        if (failedStep) {
+        if (failedStep && current?.steps?.[failedStep]?.status === "in_progress") {
           onboardSession.markStepFailed(failedStep, "Onboarding exited before the step completed.");
         }
       }
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bin/lib/onboard.js` around lines 2847 - 2855, The exit handler currently
reads onboardSession.loadSession() and unconditionally calls
onboardSession.markStepFailed(lastStepStarted) which can revert an already
completed step; change it to check the session state for the step referenced by
current.lastStepStarted and only call onboardSession.markStepFailed(...) if that
step's status is still "in_progress" (or equivalent in the session object).
Locate the exit handler using process.once("exit", ...) and use
onboardSession.loadSession(), current.lastStepStarted, and
onboardSession.markStepFailed(...) to implement the guard so completed steps are
not re-marked failed.

Comment thread install.sh
Comment on lines +151 to +156
if [[ -n "$NEMOCLAW_RECOVERY_EXPORT_DIR" ]]; then
printf " %s$%s export PATH=\"%s:\$PATH\"\n" "$C_GREEN" "$C_RESET" "$NEMOCLAW_RECOVERY_EXPORT_DIR"
fi
if [[ -n "$NEMOCLAW_RECOVERY_PROFILE" ]]; then
printf " %s$%s source %s\n" "$C_GREEN" "$C_RESET" "$NEMOCLAW_RECOVERY_PROFILE"
fi

Copy link
Copy Markdown

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

🏁 Script executed:

# First, let me check the file structure and size
wc -l install.sh

Repository: wopr-network/nemoclaw

Length of output: 79


🏁 Script executed:

# Find the detect_shell_profile function definition
grep -n "detect_shell_profile" install.sh | head -20

Repository: wopr-network/nemoclaw

Length of output: 213


🏁 Script executed:

# Read the detect_shell_profile function (around line 275)
sed -n '275,320p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 1230


🏁 Script executed:

# Read lines 151-156 (first recovery output section)
sed -n '151,156p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 374


🏁 Script executed:

# Read lines 653-654 and surrounding context
sed -n '650,660p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 395


🏁 Script executed:

# Search for all places where recovery commands are printed
grep -n "export PATH\|source" install.sh | grep -E "(printf|echo)" | head -20

Repository: wopr-network/nemoclaw

Length of output: 388


🏁 Script executed:

# Check the broader context around lines 145-165 to see if there's any shell detection around recovery output
sed -n '140,170p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 1533


🏁 Script executed:

# Check if there's any shell-specific logic around the recovery output generation
grep -B 10 -A 2 "NEMOCLAW_RECOVERY" install.sh | head -60

Repository: wopr-network/nemoclaw

Length of output: 2202


🏁 Script executed:

# Let me verify the exact syntax requirements for each shell
# Check what happens in fish, tcsh, and csh with bash commands

cat > /tmp/test_shells.txt << 'EOF'
Fish shell:
- export PATH=... → NOT valid. Use: set -gx PATH ... or set -U fish_user_paths ...
- source file → Works, but fish uses different syntax in some contexts

Tcsh/Csh:
- export PATH=... → NOT valid. Use: setenv PATH ... or set path = (...)
- source file → Works

Zsh:
- export PATH=... → Valid (compatible with bash)
- source file → Valid
EOF

cat /tmp/test_shells.txt

Repository: wopr-network/nemoclaw

Length of output: 412


🏁 Script executed:

# Search for any references to the shell type in recovery output generation
grep -n "SHELL\|shell\|fish\|tcsh\|csh" install.sh | grep -A 2 -B 2 "151\|155\|653\|654"

Repository: wopr-network/nemoclaw

Length of output: 47


🏁 Script executed:

# Check if there's any condition checking the shell type around the recovery output generation
sed -n '570,590p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 819


🏁 Script executed:

# Double-check by looking at the full context of where recovery output is printed (post_install_message function)
sed -n '138,165p' install.sh

Repository: wopr-network/nemoclaw

Length of output: 1388


The printed recovery commands are invalid for fish/csh users.

detect_shell_profile() can return ~/.config/fish/config.fish or ~/.tcshrc/~/.cshrc, but both output paths emit bash-only syntax (export PATH=..., source ...). For fish, export is invalid; for tcsh/csh, export is also invalid. This leaves users with non-bash shells unable to follow the recovery instructions, making the installer unusable without a working next step. Emit shell-specific commands for each detected shell, or fall back to "open a new terminal after updating your profile."

This applies to all recovery output locations: lines 152–155 and 653–654.

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

In `@install.sh` around lines 151 - 156, The recovery printout uses bash-only
syntax for NEMOCLAW_RECOVERY_EXPORT_DIR and NEMOCLAW_RECOVERY_PROFILE; update
the logic that formats those lines (use detect_shell_profile() or inspect the
profile path) to emit shell-appropriate commands: for bash/zsh print export
PATH="...:$PATH" and source <file>, for fish print set -gx PATH "<dir>" $PATH
and source <file>, and for csh/tcsh print setenv PATH "<dir>:$PATH" and source
<file>; apply this change to both places that print those recovery lines so
non-bash users get valid instructions, or as a fallback print a neutral message
like "update your profile and open a new terminal" if the shell cannot be
determined.

Comment on lines +540 to +549
function sanitizeConfigFile(configPath: string): void {
if (!existsSync(configPath)) return;
const raw = readFileSync(configPath, "utf-8");
const parsed: unknown = JSON5.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
const config = parsed as Record<string, unknown>;
delete config["gateway"];
const sanitized = stripCredentials(config) as Record<string, unknown>;
writeFileSync(configPath, JSON.stringify(sanitized, null, 2));
chmodSync(configPath, 0o600);

Copy link
Copy Markdown

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:

# Locate and examine the target file
fd -t f 'migration-state.ts' --exec wc -l {} \;

Repository: wopr-network/nemoclaw

Length of output: 111


🏁 Script executed:

# Read the sanitizeConfigFile function at lines 540-549
sed -n '540,549p' nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 580


🏁 Script executed:

# Get more context around the function to understand its usage
sed -n '535,560p' nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 1050


🏁 Script executed:

# Search for where sanitizeConfigFile is called
rg 'sanitizeConfigFile' nemoclaw/src/commands/migration-state.ts -A 2 -B 2

Repository: wopr-network/nemoclaw

Length of output: 938


🏁 Script executed:

# Check the snapshot bundle creation context
rg 'createSnapshotBundle|restoreSnapshotToHost' nemoclaw/src/commands/migration-state.ts -A 5 -B 2

Repository: wopr-network/nemoclaw

Length of output: 495


🏁 Script executed:

# Look at wopr/sidecar.js line 93-94 for gateway context
sed -n '85,105p' wopr/sidecar.js 2>/dev/null || echo "File not found, searching for sidecar.js"

Repository: wopr-network/nemoclaw

Length of output: 780


🏁 Script executed:

# Locate sidecar.js if not in wopr/
fd -t f 'sidecar.js' --exec sed -n '85,105p' {} \;

Repository: wopr-network/nemoclaw

Length of output: 780


🏁 Script executed:

# Find all calls to sanitizeConfigFile
rg 'sanitizeConfigFile' nemoclaw/src --type ts -B 3 -A 1

Repository: wopr-network/nemoclaw

Length of output: 1872


🏁 Script executed:

# Look at the restoreSnapshotToHost function to see if it handles gateway restoration
sed -n '600,700p' nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 3846


🏁 Script executed:

# Check if gateway field is recreated/initialized elsewhere
rg 'gateway' nemoclaw/src/commands/migration-state.ts -B 2 -A 2

Repository: wopr-network/nemoclaw

Length of output: 737


🏁 Script executed:

# Verify Node.js fs symlink behavior in documentation
web_search
Does Node.js readFileSync and writeFileSync follow symlinks by default?

Repository: wopr-network/nemoclaw

Length of output: 158


🌐 Web query:

Node.js readFileSync writeFileSync follow symlinks

💡 Result:

By default, both fs.readFileSync and fs.writeFileSync in Node.js follow (dereference) symbolic links. They open the target file that the symlink points to, rather than operating on the symlink itself. For fs.readFileSync(path, options): It internally calls fs.openSync(path, 'r') or equivalent, which uses POSIX open(2) with flag 'r' (O_RDONLY). This follows symlinks to read the contents of the target file. Source code shows it opens the path and reads from the file descriptor, treating symlinks transparently. For fs.writeFileSync(path, data, options): It opens the path for writing (typically 'w' flag, O_TRUNC | O_CREAT | O_WRONLY), which also follows symlinks, overwriting or creating the target file. To avoid following symlinks: - Use fs.lstatSync(path).isSymbolicLink to detect symlinks first. - For no-follow on open, use the 'O_NOFOLLOW' flag: fs.openSync(path, 'r' + constants.O_NOFOLLOW), but this is low-level and throws ELOOP if path is a symlink. - Node.js fs.readFileSync/writeFileSync do not expose a direct no-follow option; they always dereference. This behavior matches POSIX standards where open(2), read(2), write(2) follow symlinks unless O_NOFOLLOW is specified. Confirmed in Node.js source (lib/fs.js) and docs.

Citations:


🏁 Script executed:

# Check if gateway is mentioned in entrypoint/sandbox initialization
rg 'regenerates|entrypoint|gateway' nemoclaw/src --type ts -B 2 -A 2 | head -50

Repository: wopr-network/nemoclaw

Length of output: 3811


🏁 Script executed:

# Check the stripCredentials function to understand its scope
rg -A 15 'function stripCredentials' nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 566


🏁 Script executed:

# Verify if lstatSync is already imported or used elsewhere
rg 'lstatSync|O_NOFOLLOW' nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 165


🏁 Script executed:

# Check imports at the top of the file
head -30 nemoclaw/src/commands/migration-state.ts

Repository: wopr-network/nemoclaw

Length of output: 831


Validate that configPath is not a symlink before reading or writing.

Lines 541-549 read and overwrite the file at configPath without checking if it's a symlink. Since Node.js readFileSync() and writeFileSync() dereference symlinks by default, a malicious or misconfigured path could cause the sanitization to overwrite a file outside the snapshot tree. Check the target with lstatSync() before reading, reject non-regular files, and use renameSync() to atomically replace the file (by writing to a temp file first).

🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 548-548: Potential file system race condition
The file may have changed since it was checked.

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

In `@nemoclaw/src/commands/migration-state.ts` around lines 540 - 549, The
sanitizeConfigFile function currently reads/writes configPath directly; update
it to first use lstatSync(configPath) to ensure the path exists, is a regular
file (not a directory) and is not a symbolic link (reject if
stats.isSymbolicLink() or !stats.isFile()), then perform JSON5.parse and
stripCredentials as before but write the sanitized JSON to a temp file in the
same directory (e.g., `${configPath}.tmp`), set the temp file mode with
chmodSync, and atomically replace the original by renameSync(tempPath,
configPath) instead of writing directly with writeFileSync; keep existing calls
to existsSync, readFileSync, stripCredentials, and chmodSync semantics but move
chmodSync to the temp file before rename and ensure errors are thrown/reported
on non-regular or symlink targets.

Comment on lines 691 to +699
copyDirectory(hostState.stateDir, snapshotStateDir, { stripCredentials: true });
sanitizeConfigFile(path.join(snapshotStateDir, "openclaw.json"));

if (hostState.configPath && hostState.hasExternalConfig) {
const configSnapshotDir = path.join(parentDir, "config");
mkdirSync(configSnapshotDir, { recursive: true });
const configSnapshotPath = path.join(configSnapshotDir, "openclaw.json");
copyFileSync(hostState.configPath, configSnapshotPath);
chmodSync(configSnapshotPath, 0o600);
sanitizeConfigFile(configSnapshotPath);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep gateway settings in the host-restorable snapshot.

Lines 692 and 699 run the same sanitizer used for the sandbox bundle, but restoreSnapshotToHost() later copies these files back verbatim. That permanently deletes non-secret gateway.* settings from the host config. In WOPR, wopr/sidecar.js Line 93-94 stores gateway.inferenceProvider there, so a restore loses the active provider selection. Limit full gateway removal to prepareSandboxState() and only strip credential-bearing fields in the snapshot copy.

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

In `@nemoclaw/src/commands/migration-state.ts` around lines 691 - 699, The
snapshot creation is currently calling sanitizeConfigFile which removes full
"gateway" settings and causes restoreSnapshotToHost() to lose non-secret gateway
fields; instead, preserve gateway keys except for credential fields when
creating host-restorable snapshots. Update the calls that sanitize the snapshot
copy (the call after copyDirectory for snapshotStateDir and the call after
copyFileSync for configSnapshotPath) to use a lighter sanitizer (e.g., a new
sanitizeConfigStripCredentials function or an option to sanitizeConfigFile like
{ stripCredentials: true, stripGatewayKeys: ['apiKey','secret'] } ) that only
strips credential-bearing fields from gateway while leaving other gateway
settings (such as gateway.inferenceProvider) intact; leave full
sanitizeConfigFile usage limited to prepareSandboxState() where completely
removing gateway is intended. Ensure references: copyDirectory,
sanitizeConfigFile (or new sanitizer), restoreSnapshotToHost,
prepareSandboxState, snapshotStateDir, hostState.configPath.

Comment thread scripts/nemoclaw-start.sh
Comment on lines +264 to +281
_write_proxy_snippet() {
local target="$1"
if [ -f "$target" ] && grep -qF "$_PROXY_MARKER_BEGIN" "$target" 2>/dev/null; then
local tmp
tmp="$(mktemp)"
awk -v b="$_PROXY_MARKER_BEGIN" -v e="$_PROXY_MARKER_END" \
'$0==b{s=1;next} $0==e{s=0;next} !s' "$target" >"$tmp"
printf '%s\n' "$_PROXY_SNIPPET" >>"$tmp"
cat "$tmp" >"$target"
rm -f "$tmp"
return 0
fi
printf '\n%s\n' "$_PROXY_SNIPPET" >>"$target"
}

if [ -w "$_SANDBOX_HOME" ]; then
_write_proxy_snippet "${_SANDBOX_HOME}/.bashrc"
_write_proxy_snippet "${_SANDBOX_HOME}/.profile"

Copy link
Copy Markdown

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:

wc -l scripts/nemoclaw-start.sh

Repository: wopr-network/nemoclaw

Length of output: 94


🏁 Script executed:

# Find the _write_proxy_snippet function and surrounding context
sed -n '250,290p' scripts/nemoclaw-start.sh

Repository: wopr-network/nemoclaw

Length of output: 1301


🏁 Script executed:

# Search for where _SANDBOX_HOME is set and how privileges are managed
rg "_SANDBOX_HOME|privilege|setuid|su |sudo" scripts/nemoclaw-start.sh -n

Repository: wopr-network/nemoclaw

Length of output: 1131


🏁 Script executed:

# Look for any existing symlink checks or protections
rg "\-L|\-h|symlink" scripts/nemoclaw-start.sh -n

Repository: wopr-network/nemoclaw

Length of output: 516


Don't append to sandbox-controlled dotfiles as root.

This block rewrites ${_SANDBOX_HOME}/.bashrc and .profile before dropping privileges. If the sandbox user makes either path a symlink, the next startup follows it and writes the proxy snippet into an arbitrary root-owned file inside the container. Reject symlinks/non-regular files and write a temp file + mv so the path itself is replaced instead of following it.

🔒 Suggested hardening
 _write_proxy_snippet() {
   local target="$1"
-  if [ -f "$target" ] && grep -qF "$_PROXY_MARKER_BEGIN" "$target" 2>/dev/null; then
-    local tmp
-    tmp="$(mktemp)"
+  local tmp
+  if [ -L "$target" ] || { [ -e "$target" ] && [ ! -f "$target" ]; }; then
+    echo "[SECURITY] Refusing to update non-regular profile: $target" >&2
+    return 1
+  fi
+  tmp="$(mktemp "${target}.XXXXXX")"
+  if [ -f "$target" ] && grep -qF "$_PROXY_MARKER_BEGIN" "$target" 2>/dev/null; then
     awk -v b="$_PROXY_MARKER_BEGIN" -v e="$_PROXY_MARKER_END" \
       '$0==b{s=1;next} $0==e{s=0;next} !s' "$target" >"$tmp"
-    printf '%s\n' "$_PROXY_SNIPPET" >>"$tmp"
-    cat "$tmp" >"$target"
-    rm -f "$tmp"
-    return 0
+  elif [ -f "$target" ]; then
+    cat "$target" >"$tmp"
   fi
-  printf '\n%s\n' "$_PROXY_SNIPPET" >>"$target"
+  printf '\n%s\n' "$_PROXY_SNIPPET" >>"$tmp"
+  mv -f "$tmp" "$target"
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/nemoclaw-start.sh` around lines 264 - 281, The current
_write_proxy_snippet function can follow symlinks and append into arbitrary
root-owned files; update it to first verify the target is a regular file or a
non-existent path (reject and skip if it's a symlink, device, or other
non-regular file) and when writing, write into a secure temporary file (e.g. via
mktemp) and atomically replace the target with mv (not cat >>), ensuring you
preserve permissions/ownership as needed; reference _write_proxy_snippet,
$_PROXY_MARKER_BEGIN/END and $_PROXY_SNIPPET for where to read/insert the
snippet and use $_SANDBOX_HOME invocations that call _write_proxy_snippet to
ensure dotfiles are never followed if symlinked.

@TSavo
TSavo merged commit fb35f29 into main Mar 28, 2026
14 of 22 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Mar 30, 2026
3 tasks
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.