Repository navigation
sync: rebase on upstream (2026-03-28) - #9
Conversation
* 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
Fixes NVIDIA#949 Co-authored-by: KJ <[email protected]>
* 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]>
…#903) Signed-off-by: peteryuqin <[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]>
There was a problem hiding this comment.
Sorry @AgentWOPR, your pull request is larger than the review limit of 150000 diff characters
📝 WalkthroughWalkthroughThis 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 Changes
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
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
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Review Summary by QodoImplement resumable onboarding with session tracking, runtime recovery, and credential sanitization
WalkthroughsDescription• **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 Diagramflowchart 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"]
File Changes1. bin/lib/onboard.js
|
Code Review by Qodo
1. Disconnected read as connected
|
| 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
| 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
| 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
| 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
| '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
| if (resumeGateway) { | ||
| resumeStepMessage("gateway", "running"); | ||
| } else if (!resume && canReuseHealthyGateway) { | ||
| note(" Reusing healthy NemoClaw gateway."); |
There was a problem hiding this comment.
🔴 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.
| 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; |
Was this helpful? React with 👍 or 👎 to provide feedback.
| _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" | ||
| } |
There was a problem hiding this comment.
🟢 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.
| 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)) { |
There was a problem hiding this comment.
🟢 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.
| function isGatewayConnected(statusOutput = "") { | ||
| return typeof statusOutput === "string" && statusOutput.includes("Connected"); | ||
| } |
There was a problem hiding this comment.
🟠 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\.?$)/iincorrectly skips any sandbox whose name starts with "name" (case-insensitive). For example, a sandbox namednamesandboxwould have its line start with "namesandbox" which matches^NAMEin 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`.
| 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; | ||
| } |
There was a problem hiding this comment.
🟢 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.
| const resumeInference = | ||
| resume && | ||
| typeof provider === "string" && | ||
| typeof model === "string" && |
There was a problem hiding this comment.
🟡 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.
| let status = runCaptureOpenshell(["status"], { ignoreError: true }); | ||
| if (status.includes("Connected") && isSelectedGateway(status)) { | ||
| process.env.OPENSHELL_GATEWAY = GATEWAY_NAME; |
There was a problem hiding this comment.
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 SummaryThis upstream sync (2026-03-28) layers significant new capability onto the NemoClaw CLI: a persistent, resumable onboarding session ( Key changes and findings:
Confidence Score: 4/5Safe 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.
|
| 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
Comments Outside Diff (3)
-
bin/lib/onboard.js, line 1457-1464 (link)Credential not cleared when inference step is skipped on resume
When
resumeProviderSelectionistrue,hydrateCredentialEnv(credentialEnv)loads the API key (e.g.,NVIDIA_API_KEY) intoprocess.env. WhenresumeInferenceis subsequently alsotrue, the inference step is skipped anddelete process.env.NVIDIA_API_KEYis 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.envand is inherited by every child process spawned during sandbox creation, openclaw setup, and policy application. The fix is to apply the same cleanup in theresumeInferencebranch: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.
-
bin/lib/onboard.js, line 553-556 (link)Transient
openshell sandbox listfailure misclassifies a healthy sandbox asnot_readygetSandboxStateFromOutputstrustsgetOutputto determine existence but relies entirely onlistOutputfor readiness:function getSandboxStateFromOutputs(sandboxName, getOutput = "", listOutput = "") { if (!sandboxName) return "missing"; if (!getOutput) return "missing"; return isSandboxReady(listOutput, sandboxName) ? "ready" : "not_ready"; }
If
openshell sandbox listhas a transient failure and returns empty output (whileopenshell sandbox get <name>succeeds), the sandbox is classified as"not_ready". During resume,"not_ready"triggersrepairRecordedSandbox→openshell sandbox delete, destroying a perfectly healthy sandbox. Consider treating an emptylistOutputconservatively: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.
-
nemoclaw/src/commands/migration-state.ts, line 2385-2391 (link)computeFileDigestnow throws; call-site increateSnapshotBundleis unguardedThe 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
createSnapshotBundlehas no local try/catch; correctness relies on the outer catch in the function converting the throw to anullreturn +logger.error. This works but is implicit — consider adding a brief comment at the call-site noting that throws fromcomputeFileDigestare 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.
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
| } 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; |
There was a problem hiding this comment.
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.There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (1)
bin/lib/runtime-recovery.js (1)
6-9: Consider extracting sharedstripAnsiutility.The
stripAnsifunction is duplicated between this module andbin/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
📒 Files selected for processing (24)
bin/lib/onboard-session.jsbin/lib/onboard.jsbin/lib/policies.jsbin/lib/runtime-recovery.jsbin/nemoclaw.jsinstall.shnemoclaw/src/commands/migration-state.test.tsnemoclaw/src/commands/migration-state.tsscripts/debug.shscripts/install.shscripts/nemoclaw-start.shtest/cli.test.jstest/e2e/test-onboard-repair.shtest/e2e/test-onboard-resume.shtest/install-preflight.test.jstest/nemoclaw-cli-recovery.test.jstest/onboard-selection.test.jstest/onboard-session.test.jstest/onboard.test.jstest/policies.test.jstest/runtime-recovery.test.jstest/service-env.test.jstest/uninstall.test.jsuninstall.sh
💤 Files with no reviewable changes (1)
- test/onboard-selection.test.js
| function hydrateCredentialEnv(envName) { | ||
| if (!envName) return null; | ||
| const value = getCredential(envName); | ||
| if (value) { | ||
| process.env[envName] = value; | ||
| } | ||
| return value || null; | ||
| } |
There was a problem hiding this comment.
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.
| 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; | ||
| } |
There was a problem hiding this comment.
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.
| 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)); |
There was a problem hiding this comment.
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
| 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."); | ||
| } | ||
| } | ||
| }); |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let me check the file structure and size
wc -l install.shRepository: wopr-network/nemoclaw
Length of output: 79
🏁 Script executed:
# Find the detect_shell_profile function definition
grep -n "detect_shell_profile" install.sh | head -20Repository: wopr-network/nemoclaw
Length of output: 213
🏁 Script executed:
# Read the detect_shell_profile function (around line 275)
sed -n '275,320p' install.shRepository: wopr-network/nemoclaw
Length of output: 1230
🏁 Script executed:
# Read lines 151-156 (first recovery output section)
sed -n '151,156p' install.shRepository: wopr-network/nemoclaw
Length of output: 374
🏁 Script executed:
# Read lines 653-654 and surrounding context
sed -n '650,660p' install.shRepository: 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 -20Repository: 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.shRepository: 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 -60Repository: 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.txtRepository: 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.shRepository: 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.shRepository: 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.
| 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); |
There was a problem hiding this comment.
🧩 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.tsRepository: 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.tsRepository: 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 2Repository: 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 2Repository: 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 1Repository: 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.tsRepository: 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 2Repository: 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:
- 1: https://nodejs.org/api/fs.html
- 2: https://nodejs.org/docs/latest-v24.x/api/fs.html
- 3: https://nodejs.org/docs/latest/api/fs.html
- 4: https://github.com/nodejs/node/blob/main/lib/fs.js
- 5: https://docs.deno.com/api/node/fs/~/constants
🏁 Script executed:
# Check if gateway is mentioned in entrypoint/sandbox initialization
rg 'regenerates|entrypoint|gateway' nemoclaw/src --type ts -B 2 -A 2 | head -50Repository: 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.tsRepository: 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.tsRepository: wopr-network/nemoclaw
Length of output: 165
🏁 Script executed:
# Check imports at the top of the file
head -30 nemoclaw/src/commands/migration-state.tsRepository: 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.
| 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); |
There was a problem hiding this comment.
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.
| _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" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
wc -l scripts/nemoclaw-start.shRepository: 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.shRepository: 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 -nRepository: 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 -nRepository: 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.
Automated upstream sync
Rebased our WOPR sidecar commits onto upstream/main (NVIDIA/NemoClaw).
What this does
Verify
Summary by CodeRabbit
New Features
--resumeflag for interrupted sessionsImprovements
Bug Fixes
Note
Add resumable onboarding sessions with gateway reuse and credential sanitization in migration snapshots
--resumehealthy,stale,foreign-active, etc.) and avoids tearing down a healthy named gateway; a newrecoverGatewayRuntimeutility restores runtime without full teardownnemoclaw onboard --resume --non-interactive; post-install messaging is now conditional on whether onboarding ran and whether the CLI is resolvable in the current shellopenclaw.jsonusing a newsanitizeConfigFilehelper, with file permissions set to0600~/.bashrcand~/.profileinside the sandboxnemoclaw connectno longer pre-starts a background port forward on 18789 before invokingopenshell 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
runOpenshell(["gateway", "destroy", "-g", GATEWAY_NAME], ...)directly instead of the newdestroyGateway()helper. ThedestroyGateway()function (lines 1389-1394) was introduced specifically becauseopenshell gateway destroydoesn't remove Docker volumes, leaving corrupted cluster state. The cleanup paths at lines 1620 and 1638 correctly usedestroyGateway(), but the stale gateway cleanup at line 1603 does not, potentially leaving corrupted volumes that break the subsequentgateway start. [ Out of scope ]bin/lib/runtime-recovery.js — 0 comments posted, 1 evaluated, 1 filtered
/^(NAME|No sandboxes found\.?$)/iincorrectly skips any sandbox whose name starts with "name" (case-insensitive). For example, a sandbox namednamesandboxwould have its line start with "namesandbox" which matches^NAMEin 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
CURL_PIPE_INSTALLERnow points to the same file asINSTALLER(../install.sh), but the "curl-pipe installer release-tag resolution" test suite (starting at line 1380) is intended to testscripts/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 thescripts/install.shscript at all, leaving its release-tag resolution behavior untested. [ Failed validation ]