Skip to content

perf(test): reduce CommonJS loader churn - #6299

Merged
cv merged 8 commits into
mainfrom
codex/perf-reduce-create-require
Jul 6, 2026
Merged

perf(test): reduce CommonJS loader churn#6299
cv merged 8 commits into
mainfrom
codex/perf-reduce-create-require

Conversation

@cv

@cv cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Summary

This removes repeated createRequire use and CommonJS cache manipulation from the policy-channel, gateway-runtime, and rebuild suites, replaces native-safe seams with typed imports, and keeps heavyweight provider/rebuild dependencies late-bound. It reduces CLI test files using createRequire from 44 to 32 and adds exact path guardrails so the remaining seams can only decrease.

Related Issue

Refs #6245

Changes

  • Convert six policy/channel suites plus runner and status tests to native imports and typed dependency seams.
  • Load policy conflict detection from its leaf module while deferring provider and rebuild graphs until their runtime paths execute.
  • Replace the gateway-runtime suite's per-test onboard graph load and cache invalidation with a native, late-bound dependency seam.
  • Move rebuild-to-onboard calls behind one lazy typed boundary and replace two coverage-timeout rebuild suites with native, phase-focused tests.
  • Centralize source-loader NODE_OPTIONS quoting/removal, preserving unrelated options and limiting bypass to the explicit compiled-artifact test.
  • Enforce exact createRequire allowlists for 32 CLI tests and 8 support files across .ts, .mts, .cts, and .tsx; production TypeScript remains prohibited and the scanner skips symlinks.
  • Expand the repository-check hook matcher to cover every TypeScript module extension.
  • Give the compiled CLI dispatch contract enough polling time under CI contention while retaining cleanup headroom.

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: Internal test loading, dependency injection, and repository guardrails only; no user-facing behavior or interface changes.
  • 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: Independent read-only reviews found no remaining runtime, test-isolation, TypeScript, guardrail, or documentation findings after follow-up.
  • 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
  • Normal pre-commit, commit-msg, and pre-push hooks passed, or npm run check:diff passed when hooks were skipped or unavailable
  • Targeted behavior tests pass for the current change set, or tests are marked not applicable above — 13 focused source/integration suites passed 147/147; the parser/guard review batch passed 16/16; all 41 rebuild suites passed 311/311, 13 credential integration tests passed, all 10 shared-harness consumer suites passed 105/105, and the three formerly timing-out suites passed 17/17 from a cold source cache with V8 coverage (67–264 ms per file); all 17 package-contract files passed 290/290; the CLI type-check and 32-CLI/8-support budget passed.
  • Applicable broad gate passed — CI-equivalent five-shard CLI/integration coverage merge passed 11,496 tests with zero failures; coverage passed at 71.48% lines, 72.76% functions, 64.01% branches, and 70.86% statements.
  • 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: Carlos Villela cvillela@nvidia.com

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv cv self-assigned this Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 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 a createRequire budget check, shared NODE_OPTIONS helpers, injectable runtime seams for sandbox and gateway actions, and test migrations from CommonJS loading to direct ESM imports.

Changes

CreateRequire budget and ESM migration

Layer / File(s) Summary
Budget check implementation
scripts/checks/test-create-require-budget.ts, scripts/checks/run.ts, .pre-commit-config.yaml
Adds the createRequire budget script, registers it in repository checks, and broadens pre-commit matching for TypeScript module extensions.
Shared source-loader helper
test/helpers/source-loader-options.ts, test/cli/helpers.test.ts, test/gateway-drift-preflight.test.ts, vitest.config.ts
Adds shared NODE_OPTIONS helper functions for appending and removing the source-loader hook, and applies the helper in Vitest config and the gateway drift preflight test.
Policy-channel dependency boundary
src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/policy-channel.ts
Introduces policyChannelDependencies, replaces direct onboarding and rebuild calls, and switches non-interactive detection and conflict lookup to local/imported sources.
Gateway runtime dependency boundary
src/lib/gateway-runtime-action.ts, src/lib/gateway-runtime-action.test.ts
Introduces gatewayRuntimeDependencies, routes lifecycle capture and recovery through it, and updates the corresponding test to spy on the new boundary.
Rebuild onboarding boundary
src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/actions/sandbox/rebuild-credential-preflight.ts, src/lib/actions/sandbox/rebuild-recreate-phase.ts, src/lib/actions/sandbox/rebuild-target-runtime.ts, src/lib/actions/sandbox/rebuild-resume-snapshot.test.ts, src/lib/actions/sandbox/rebuild-shields-finally.test.ts
Adds rebuildOnboardDependencies and switches rebuild preflight, recreate, resume-snapshot, shields, and target-runtime paths to use it.
Sandbox and runner test migrations
src/lib/actions/sandbox/policy-channel-*.test.ts, src/lib/runner-argv.test.ts, src/lib/status-command-deps.test.ts
Moves sandbox policy-channel tests and related runner/status tests to ESM imports, updates fixtures and session mocks, and retargets spies to the new dependency seams.

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

Possibly related PRs

  • NVIDIA/NemoClaw#2584: Related runner test changes around argv-only execution and the same legacy string-input guard assertions.

Suggested labels: refactor

Suggested reviewers: ericksoa, cjagwani

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main test-focused change: reducing CommonJS loader churn.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/perf-reduce-create-require

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

@github-code-quality

github-code-quality Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Code Coverage Overview

Languages: TypeScript

TypeScript / code-coverage/plugin

The overall coverage in the codex/perf-reduce-cr... 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 codex/perf-reduce-cr... f262eb0 +/-
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 codex/perf-reduce-cr... branch is 73%. Coverage data for the main branch is not yet available.

Show a code coverage summary of the most covered files.
File main codex/perf-reduce-cr... f262eb0 +/-
src/lib/shields...nsition-lock.ts 87%
src/lib/onboard/preflight.ts 83%
src/lib/actions...all/run-plan.ts 81%
src/lib/state/o...oard-session.ts 81%
src/lib/state/sandbox.ts 71%
src/lib/onboard...er-gpu-patch.ts 69%
src/lib/shields/index.ts 68%
src/lib/policy/index.ts 66%
src/lib/actions...licy-channel.ts 63%
src/lib/onboard.ts 24%

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

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

PR Review Advisor (Nemotron Ultra) — Informational

Merge posture: Informational / low confidence
Primary next action: Resolve or justify PRA-1: PR review advisor unavailable.
Open items: 0 required · 1 warning · 0 suggestions · 1 test follow-up
Top item: PR review advisor unavailable

Action checklist

  • PRA-1 Resolve or justify: PR review advisor unavailable
  • PRA-T1 Add or justify test follow-up: Runtime validation

Findings index

ID Severity Category Location Required action
PRA-1 Resolve/justify correctness Re-run the PR Review Advisor or perform a manual review.
Review findings by urgency: 0 required fixes, 1 item 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 — PR review advisor unavailable

  • Location: not file-specific
  • Category: correctness
  • Problem: The automated advisor could not complete: Could not parse JSON from PR review advisor output; see /home/runner/work/NemoClaw/NemoClaw/artifacts/pr-review-advisor-nemotron-ultra/pr-review-advisor-retry-raw-output.txt
  • Impact: Automated review evidence is incomplete, so human review must cover the changed code manually.
  • Recommended action: Re-run the PR Review Advisor or perform a manual review.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Inspect the workflow logs and raw advisor artifact for the execution failure.
  • Missing regression test: No regression test recommendation is available because the advisor did not complete.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Inspect the workflow logs and raw advisor artifact for the execution failure.
  • Evidence: Could not parse JSON from PR review advisor output; see /home/runner/work/NemoClaw/NemoClaw/artifacts/pr-review-advisor-nemotron-ultra/pr-review-advisor-retry-raw-output.txt

💡 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 — Add or identify targeted runtime/integration validation for the changed behavior; do not report external E2E job pass/fail here.. Runtime/sandbox/infrastructure paths need behavioral runtime validation: .pre-commit-config.yaml, scripts/checks/run.ts, scripts/checks/test-create-require-budget.ts, src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/policy-channel.ts, src/lib/actions/sandbox/rebuild-credential-preflight.ts, src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/actions/sandbox/rebuild-recreate-phase.ts.

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 6, 2026

Copy link
Copy Markdown
Contributor

E2E Advisor Recommendation

Required E2E: channels-add-remove, channels-stop-start, network-policy, sandbox-rebuild, gateway-drift-preflight-e2e
Optional E2E: rebuild-openclaw, cloud-onboard, token-rotation

Dispatch hint: channels-add-remove,channels-stop-start,network-policy,sandbox-rebuild

Workflow run

Full advisor summary

E2E Recommendation Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E

  • channels-add-remove (high): Required because policy-channel production code changed the real channel add/remove path: provider upsert is now late-bound, rebuild is invoked through a dependency boundary, channel conflict detection import changed, and registry/policy/gateway side effects are in scope. This E2E onboards a real sandbox, adds Telegram, rebuilds, verifies registry/gateway/policy/in-sandbox state, removes Telegram, and rebuilds back clean.
  • channels-stop-start (high): Required because policy-channel start/stop/disabled-plan paths and rebuild invocation are affected by the same production dependency-boundary change. This validates live channel pause/resume behavior across supported agents, policy mutation, registry state, and rebuild application.
  • network-policy (high): Required because policy-channel.ts owns policy-add/remove, preset application, session policy synchronization, and policy context refresh. The live network-policy job exercises real NemoClaw CLI policy mutation against a sandbox and verifies allow/deny egress boundaries from inside the sandbox.
  • sandbox-rebuild (high): Required because rebuild credential preflight, recreate phase, target runtime, and late-bound onboard dependency code changed. This E2E runs a real onboard plus nemoclaw <sandbox> rebuild --yes, verifies state preservation, registry metadata refresh, and backup credential hygiene.
  • gateway-drift-preflight-e2e (medium): Required because gateway-runtime-action.ts changed and gateway drift preflight coverage was touched. This regression E2E validates that stale or incompatible OpenShell gateway state fails closed instead of being trusted or misclassified.

Optional E2E

  • rebuild-openclaw (high): Useful additional confidence for the rebuild dependency-boundary changes because it exercises an older OpenClaw base, seeded policy/gateway-token state, real rebuild, state preservation, and credential/token rotation behavior beyond the standard sandbox-rebuild path.
  • cloud-onboard (high): Useful smoke coverage for full hosted onboarding if reviewers want extra confidence that the rebuild/onboard dependency boundary and gateway-runtime changes did not regress the normal hosted OpenClaw onboarding journey.
  • token-rotation (medium): Adjacent confidence for messaging credential handling after policy-channel/provider-boundary changes, especially if the PR is expected to affect credential hash/conflict or provider update semantics.

New E2E recommendations

  • messaging credential conflict handling (medium): Existing unit tests cover cross-sandbox channel credential conflict prompts, but there is no focused live E2E that creates two real sandboxes and validates channels add fail/continue behavior against gateway-backed providers after the new lazy dependency boundary.
    • Suggested test: Add a selective live E2E for cross-sandbox messaging credential conflict detection using fake/local channel credentials and real registry/gateway provider state.

Dispatch hint

  • Workflow: .github/workflows/e2e.yaml
  • jobs input: channels-add-remove,channels-stop-start,network-policy,sandbox-rebuild

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

E2E Target Recommendation

Required E2E targets: channels-add-remove, channels-stop-start, network-policy, sandbox-rebuild, onboard-resume, onboard-repair
Optional E2E targets: rebuild-openclaw

Dispatch required E2E targets:

  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=channels-add-remove
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=channels-stop-start
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=network-policy
  • gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild
  • 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

Workflow run

Full E2E target advisor summary

E2E Target Advisor

Base: origin/main
Head: HEAD
Confidence: high

Required E2E targets

  • channels-add-remove: policy-channel provider registration and rebuild handoff were refactored behind policyChannelDependencies; this live job exercises real OpenClaw channels add, rebuild, gateway credential reuse, policy-list, and remove cleanup.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=channels-add-remove
  • channels-stop-start: policy-channel start/stop paths share the changed rebuild/provider dependency boundary and need the live OpenClaw/Hermes stop-start, rebuild, provider reuse, registry, and in-sandbox config contract.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=channels-stop-start
  • network-policy: policy-channel policy add/remove imports and non-interactive/session behavior changed; this job exercises the real network policy allow/deny and interactive policy-add boundary.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=network-policy
  • sandbox-rebuild: rebuild credential preflight, target runtime, and recreate-phase onboarding handoff now route through rebuildOnboardDependencies; this job runs a real onboard plus nemoclaw rebuild and validates registry/state preservation and backup hygiene.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=sandbox-rebuild
  • onboard-resume: the rebuild recreate path changes the late-bound onboard({ resume: true, nonInteractive: true, recreateSandbox: true }) handoff, which is a resume-state path and must be guarded by the live onboard resume contract.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-resume
  • onboard-repair: the same persisted-session resume boundary can affect repair/backstop behavior from saved onboarding state, so onboard-repair is required alongside onboard-resume for these resume-path changes.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=onboard-repair

Optional E2E targets

  • rebuild-openclaw: Adjacent higher-cost rebuild coverage for an older OpenClaw base image with policy/gateway-token state; useful if maintainers want extra confidence beyond the primary sandbox-rebuild lane.
    • Dispatch: gh workflow run e2e.yaml --ref <pr-head-ref> --field jobs=rebuild-openclaw

Relevant changed files

  • src/lib/actions/sandbox/policy-channel-dependencies.ts
  • src/lib/actions/sandbox/policy-channel.ts
  • src/lib/actions/sandbox/rebuild-credential-preflight.ts
  • src/lib/actions/sandbox/rebuild-onboard-dependencies.ts
  • src/lib/actions/sandbox/rebuild-recreate-phase.ts
  • src/lib/actions/sandbox/rebuild-target-runtime.ts
  • src/lib/gateway-runtime-action.ts

@github-actions

github-actions Bot commented Jul 6, 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: Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams.
Open items: 0 required · 2 warnings · 0 suggestions · 5 test follow-ups
Since last review: 0 prior items resolved · 2 still apply · 0 new items found

Action checklist

  • PRA-1 Resolve or justify: Source-of-truth review needed: Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams
  • PRA-2 Resolve or justify: Add direct contract tests for late-bound runtime seams in src/lib/actions/sandbox/policy-channel-dependencies.ts:35
  • 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: Acceptance clause
  • PRA-T5 Add or justify test follow-up: Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams

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/actions/sandbox/policy-channel-dependencies.ts:35 Add small direct tests for the seam implementations in this PR, or identify existing tests that explicitly assert these exact delegation and no-eager-import contracts. Keep the late-bound validation seams; do not simplify away this trust-boundary separation.
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: Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams

  • 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: Broad caller suites were converted to native imports, and scripts/checks/test-create-require-budget.ts prevents new createRequire test seams, but direct seam delegation and no-eager-onboard-import tests are still missing.
  • 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/actions/sandbox/policy-channel-dependencies.ts and src/lib/actions/sandbox/rebuild-onboard-dependencies.ts document late-bound boundaries; src/lib/gateway-runtime-action.ts defers ./onboard to startGatewayForRecovery. This needs-followup item is covered by the security finding.

PRA-2 Resolve/justify — Add direct contract tests for late-bound runtime seams

  • Location: src/lib/actions/sandbox/policy-channel-dependencies.ts:35
  • Category: security
  • Problem: This PR introduces late-bound dependency objects around messaging provider registration, rebuild orchestration, onboarding calls, and gateway recovery. The changed caller suites spy on these seam objects, and the new createRequire budget prevents additional CommonJS test seams, but I did not find direct callee tests that pin the seam contracts themselves: provider upsert should delegate the original token definitions, the real runOpenshell function, and options unchanged; rebuild should delegate sandbox name and argv unchanged; gateway runtime should not load ./onboard during module import, lifecycle probing, or a healthy/no-start recovery path.
  • Impact: These seams sit on credential-provider registration, sandbox rebuild, and gateway lifecycle trust boundaries. A future refactor could silently alter credential registration inputs, rebuild argv, or reintroduce eager trusted onboarding graph execution during gateway probes without the broad caller tests failing clearly.
  • Recommended action: Add small direct tests for the seam implementations in this PR, or identify existing tests that explicitly assert these exact delegation and no-eager-import contracts. Keep the late-bound validation seams; do not simplify away this trust-boundary separation.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Read src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/gateway-runtime-action.ts, and src/lib/gateway-runtime-action.test.ts; then grep changed tests for direct assertions on upsertMessagingProviders(tokenDefs, runOpenshell, options), rebuildSandbox(sandboxName, argv), and absence of ./onboard loading before gatewayRuntimeDependencies.startGatewayForRecovery.
  • Missing regression test: Add tests named like: policyChannelDependencies.upsertMessagingProviders delegates tokenDefs, runOpenshell, and options unchanged; policyChannelDependencies.rebuildSandbox delegates sandbox name and argv unchanged; gatewayRuntimeDependencies does not import onboard during module import, getNamedGatewayLifecycleState, or healthy recoverNamedGatewayRuntime.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Read src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/gateway-runtime-action.ts, and src/lib/gateway-runtime-action.test.ts; then grep changed tests for direct assertions on upsertMessagingProviders(tokenDefs, runOpenshell, options), rebuildSandbox(sandboxName, argv), and absence of ./onboard loading before gatewayRuntimeDependencies.startGatewayForRecovery.
  • Evidence: policy-channel-dependencies.ts calls require("../../onboard/providers") and require("./rebuild") inside the new seam; gateway-runtime-action.ts dynamically imports ./onboard only in startGatewayForRecovery. Grep/read inspection found caller tests spying on policyChannelDependencies and gatewayRuntimeDependencies, plus the new createRequire budget tests, but no direct seam-delegation or no-eager-import contract tests.

💡 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 — policyChannelDependencies.upsertMessagingProviders delegates tokenDefs, runOpenshell, and options unchanged. Changed code touches sandbox lifecycle, credential-provider registration, onboarding, gateway recovery, and test loader boundaries. Existing caller suites and parser/budget tests are broad and useful, but direct runtime seam tests would pin the new trusted boundaries without relying on external E2E state.
  • PRA-T2 Runtime validation — policyChannelDependencies.rebuildSandbox delegates sandbox name and argv unchanged. Changed code touches sandbox lifecycle, credential-provider registration, onboarding, gateway recovery, and test loader boundaries. Existing caller suites and parser/budget tests are broad and useful, but direct runtime seam tests would pin the new trusted boundaries without relying on external E2E state.
  • PRA-T3 Runtime validation — gatewayRuntimeDependencies does not import onboard during module import, getNamedGatewayLifecycleState, or healthy recoverNamedGatewayRuntime. Changed code touches sandbox lifecycle, credential-provider registration, onboarding, gateway recovery, and test loader boundaries. Existing caller suites and parser/budget tests are broad and useful, but direct runtime seam tests would pin the new trusted boundaries without relying on external E2E state.
  • PRA-T4 Acceptance clause — No trusted linked issue acceptance clauses were available in the deterministic context. — add test evidence or identify existing coverage. The validation context reported linkedIssues: []; the PR body references Refs perf(test): reduce test I/O to restore 2–5 minute full-suite runs #6245, but PR-provided text is untrusted evidence and no issue body/comments were available to extract literal clauses.
  • PRA-T5 Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams — Broad caller suites were converted to native imports, and scripts/checks/test-create-require-budget.ts prevents new createRequire test seams, but direct seam delegation and no-eager-onboard-import tests are still missing.. src/lib/actions/sandbox/policy-channel-dependencies.ts and src/lib/actions/sandbox/rebuild-onboard-dependencies.ts document late-bound boundaries; src/lib/gateway-runtime-action.ts defers ./onboard to startGatewayForRecovery. This needs-followup item is covered by the security finding.
Since last review details

Current findings, using the urgency labels above:

PRA-1 Resolve/justify — Source-of-truth review needed: Late-bound policy-channel, rebuild-onboard, and gateway-runtime dependency seams

  • 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: Broad caller suites were converted to native imports, and scripts/checks/test-create-require-budget.ts prevents new createRequire test seams, but direct seam delegation and no-eager-onboard-import tests are still missing.
  • 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/actions/sandbox/policy-channel-dependencies.ts and src/lib/actions/sandbox/rebuild-onboard-dependencies.ts document late-bound boundaries; src/lib/gateway-runtime-action.ts defers ./onboard to startGatewayForRecovery. This needs-followup item is covered by the security finding.

PRA-2 Resolve/justify — Add direct contract tests for late-bound runtime seams

  • Location: src/lib/actions/sandbox/policy-channel-dependencies.ts:35
  • Category: security
  • Problem: This PR introduces late-bound dependency objects around messaging provider registration, rebuild orchestration, onboarding calls, and gateway recovery. The changed caller suites spy on these seam objects, and the new createRequire budget prevents additional CommonJS test seams, but I did not find direct callee tests that pin the seam contracts themselves: provider upsert should delegate the original token definitions, the real runOpenshell function, and options unchanged; rebuild should delegate sandbox name and argv unchanged; gateway runtime should not load ./onboard during module import, lifecycle probing, or a healthy/no-start recovery path.
  • Impact: These seams sit on credential-provider registration, sandbox rebuild, and gateway lifecycle trust boundaries. A future refactor could silently alter credential registration inputs, rebuild argv, or reintroduce eager trusted onboarding graph execution during gateway probes without the broad caller tests failing clearly.
  • Recommended action: Add small direct tests for the seam implementations in this PR, or identify existing tests that explicitly assert these exact delegation and no-eager-import contracts. Keep the late-bound validation seams; do not simplify away this trust-boundary separation.
  • Expected follow-up: Resolve in this PR or explain why the risk is acceptable.
  • Verification: Read src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/gateway-runtime-action.ts, and src/lib/gateway-runtime-action.test.ts; then grep changed tests for direct assertions on upsertMessagingProviders(tokenDefs, runOpenshell, options), rebuildSandbox(sandboxName, argv), and absence of ./onboard loading before gatewayRuntimeDependencies.startGatewayForRecovery.
  • Missing regression test: Add tests named like: policyChannelDependencies.upsertMessagingProviders delegates tokenDefs, runOpenshell, and options unchanged; policyChannelDependencies.rebuildSandbox delegates sandbox name and argv unchanged; gatewayRuntimeDependencies does not import onboard during module import, getNamedGatewayLifecycleState, or healthy recoverNamedGatewayRuntime.
  • Done when: The risk is fixed or explicitly justified in the PR. Verification: Read src/lib/actions/sandbox/policy-channel-dependencies.ts, src/lib/actions/sandbox/rebuild-onboard-dependencies.ts, src/lib/gateway-runtime-action.ts, and src/lib/gateway-runtime-action.test.ts; then grep changed tests for direct assertions on upsertMessagingProviders(tokenDefs, runOpenshell, options), rebuildSandbox(sandboxName, argv), and absence of ./onboard loading before gatewayRuntimeDependencies.startGatewayForRecovery.
  • Evidence: policy-channel-dependencies.ts calls require("../../onboard/providers") and require("./rebuild") inside the new seam; gateway-runtime-action.ts dynamically imports ./onboard only in startGatewayForRecovery. Grep/read inspection found caller tests spying on policyChannelDependencies and gatewayRuntimeDependencies, plus the new createRequire budget tests, but no direct seam-delegation or no-eager-import contract tests.

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.

@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 (4)
scripts/checks/test-create-require-budget.ts (1)

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

Duplicate collector logic between production and test-support collectors.

collectProductionCreateRequireSources and collectTestSupportCreateRequireSources are byte-identical apart from their default root argument and name. As per path instructions for scripts/checks/**, "Derive inventories and limits from a canonical source where possible; flag duplicated lists that can silently drift" — extracting a shared helper avoids the two implementations drifting apart under future edits.

♻️ Proposed refactor: extract shared helper
+function collectNonTestCreateRequireSources(root: string): string[] {
+  return [...walkTypeScriptFiles(root)]
+    .filter((absolutePath) => !TEST_FILE_PATTERN.test(absolutePath))
+    .filter((absolutePath) =>
+      containsCreateRequireIdentifier(readFileSync(absolutePath, "utf8"), absolutePath),
+    )
+    .map((absolutePath) => path.relative(REPO_ROOT, absolutePath).split(path.sep).join("/"))
+    .sort();
+}
+
 export function collectProductionCreateRequireSources(root = CLI_TEST_ROOT): string[] {
-  return [...walkTypeScriptFiles(root)]
-    .filter((absolutePath) => !TEST_FILE_PATTERN.test(absolutePath))
-    .filter((absolutePath) =>
-      containsCreateRequireIdentifier(readFileSync(absolutePath, "utf8"), absolutePath),
-    )
-    .map((absolutePath) => path.relative(REPO_ROOT, absolutePath).split(path.sep).join("/"))
-    .sort();
+  return collectNonTestCreateRequireSources(root);
 }

 export function collectTestSupportCreateRequireSources(root = TEST_SUPPORT_ROOT): string[] {
-  return [...walkTypeScriptFiles(root)]
-    .filter((absolutePath) => !TEST_FILE_PATTERN.test(absolutePath))
-    .filter((absolutePath) =>
-      containsCreateRequireIdentifier(readFileSync(absolutePath, "utf8"), absolutePath),
-    )
-    .map((absolutePath) => path.relative(REPO_ROOT, absolutePath).split(path.sep).join("/"))
-    .sort();
+  return collectNonTestCreateRequireSources(root);
 }
🤖 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 `@scripts/checks/test-create-require-budget.ts` around lines 119 - 137, The two
collectors, collectProductionCreateRequireSources and
collectTestSupportCreateRequireSources, duplicate the same walk/filter/map/sort
pipeline and can drift over time. Extract the shared logic into a single helper
that accepts the root and reuse it from both functions, keeping only the
differing default roots and exported names.

Source: Path instructions

test/test-create-require-budget.test.ts (1)

50-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing coverage for real JSX content in .tsx fixtures.

This scan test only writes plain import statements into .mts/.cts/.tsx fixtures. It doesn't exercise a .tsx file containing actual JSX syntax alongside createRequire, so a scriptKind-related parsing regression (see companion comment on scripts/checks/test-create-require-budget.ts lines 83-107) would go undetected here.

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

In `@test/test-create-require-budget.test.ts` around lines 50 - 72, The scan test
currently covers only plain import statements, so it misses JSX parsing behavior
in .tsx files. Update the test around collectProductionCreateRequireSources and
collectTestCreateRequireSources to write a real .tsx fixture containing actual
JSX syntax plus createRequire, and keep the existing .mts/.cts assertions so
scriptKind-related regressions are exercised.

Source: Path instructions

src/lib/actions/sandbox/policy-channel-agent-gate.test.ts (1)

19-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract duplicated test fixture helpers to a shared module.

agentFixture and successfulOpenshellResult are duplicated verbatim in policy-channel-cleanup.test.ts and policy-channel-conflict.test.ts. This PR already establishes the pattern of extracting shared test scaffolding (see test/helpers/source-loader-options.ts); doing the same here (e.g. a sandbox/test-helpers.ts) would prevent the three copies from silently diverging.

Also note agentFixture casts { name } as defs.AgentDefinition, bypassing the type checker for the many required fields on AgentDefinition — fine as long as tests only touch .name, but worth keeping in mind if a future test exercises another field via this fixture.

🤖 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/policy-channel-agent-gate.test.ts` around lines 19 -
32, The duplicated test fixture helpers should be moved into a shared sandbox
test helper module so the copies in these policy-channel tests do not drift
apart. Extract `agentFixture` and `successfulOpenshellResult` into a common
helper (for example alongside the existing test scaffolding pattern used by
`test/helpers/source-loader-options.ts`), then update
`policy-channel-agent-gate.test.ts`, `policy-channel-cleanup.test.ts`, and
`policy-channel-conflict.test.ts` to import and use those shared helpers. Keep
the `agentFixture` shape intentional and confined to the `.name` usage in these
tests.
src/lib/actions/sandbox/policy-channel.ts (1)

106-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Lift the non-interactive check into one shared helper The same NEMOCLAW_NON_INTERACTIVE check is repeated in destroy.ts and other boundary modules; centralize it if these paths need to stay aligned.

🤖 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/policy-channel.ts` around lines 106 - 108, The
NEMOCLAW_NON_INTERACTIVE environment check is duplicated across multiple
boundary modules, so centralize it into one shared helper and reuse it
everywhere instead of keeping separate copies. Move the logic currently in
isNonInteractive in policy-channel.ts into a common utility, then update
destroy.ts and any other callers to use that shared helper so the behavior stays
aligned in one place.

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 `@test/test-create-require-budget.test.ts`:
- Around line 25-90: The test suite in containsCreateRequireIdentifier,
collectProductionCreateRequireSources, collectTestSupportCreateRequireSources,
and createRequireBudgetFailure uses behavior-oriented titles but is missing the
required local issue-reference suffix. Update each it(...) title in this file to
end with a matching `(`#1234`)`-style suffix per the test naming guideline,
keeping the existing behavior-focused wording and adding the appropriate issue
ref for each case.

---

Nitpick comments:
In `@scripts/checks/test-create-require-budget.ts`:
- Around line 119-137: The two collectors, collectProductionCreateRequireSources
and collectTestSupportCreateRequireSources, duplicate the same
walk/filter/map/sort pipeline and can drift over time. Extract the shared logic
into a single helper that accepts the root and reuse it from both functions,
keeping only the differing default roots and exported names.

In `@src/lib/actions/sandbox/policy-channel-agent-gate.test.ts`:
- Around line 19-32: The duplicated test fixture helpers should be moved into a
shared sandbox test helper module so the copies in these policy-channel tests do
not drift apart. Extract `agentFixture` and `successfulOpenshellResult` into a
common helper (for example alongside the existing test scaffolding pattern used
by `test/helpers/source-loader-options.ts`), then update
`policy-channel-agent-gate.test.ts`, `policy-channel-cleanup.test.ts`, and
`policy-channel-conflict.test.ts` to import and use those shared helpers. Keep
the `agentFixture` shape intentional and confined to the `.name` usage in these
tests.

In `@src/lib/actions/sandbox/policy-channel.ts`:
- Around line 106-108: The NEMOCLAW_NON_INTERACTIVE environment check is
duplicated across multiple boundary modules, so centralize it into one shared
helper and reuse it everywhere instead of keeping separate copies. Move the
logic currently in isNonInteractive in policy-channel.ts into a common utility,
then update destroy.ts and any other callers to use that shared helper so the
behavior stays aligned in one place.

In `@test/test-create-require-budget.test.ts`:
- Around line 50-72: The scan test currently covers only plain import
statements, so it misses JSX parsing behavior in .tsx files. Update the test
around collectProductionCreateRequireSources and collectTestCreateRequireSources
to write a real .tsx fixture containing actual JSX syntax plus createRequire,
and keep the existing .mts/.cts assertions so scriptKind-related regressions are
exercised.
🪄 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: 14d76473-927c-4d95-a778-efa750ee46f3

📥 Commits

Reviewing files that changed from the base of the PR and between f0d2549 and 1b33745.

📒 Files selected for processing (17)
  • .pre-commit-config.yaml
  • scripts/checks/run.ts
  • scripts/checks/test-create-require-budget.ts
  • src/lib/actions/sandbox/policy-channel-agent-gate.test.ts
  • src/lib/actions/sandbox/policy-channel-cleanup.test.ts
  • src/lib/actions/sandbox/policy-channel-conflict.test.ts
  • src/lib/actions/sandbox/policy-channel-policy.test.ts
  • src/lib/actions/sandbox/policy-channel-refresh.test.ts
  • src/lib/actions/sandbox/policy-channel-remove-flow.test.ts
  • src/lib/actions/sandbox/policy-channel.ts
  • src/lib/runner-argv.test.ts
  • src/lib/status-command-deps.test.ts
  • test/cli/helpers.test.ts
  • test/gateway-drift-preflight.test.ts
  • test/helpers/source-loader-options.ts
  • test/test-create-require-budget.test.ts
  • vitest.config.ts

Comment thread test/test-create-require-budget.test.ts Outdated
cv added 2 commits July 6, 2026 00:13
Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Signed-off-by: Carlos Villela <cvillela@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)
test/test-create-require-budget.test.ts (1)

87-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant assertion doesn't exercise the production/test-support distinction.

Both collectProductionCreateRequireSources and collectTestSupportCreateRequireSources are called with the same directory and checked against the identical expected array. Per the graph context, these functions only differ in their default root (CLI_TEST_ROOT vs TEST_SUPPORT_ROOT), which isn't exercised here since both calls override the root explicitly. As written, the second assertion re-verifies the same shared filtering/traversal logic rather than the distinguishing behavior the test title implies ("production and non-test support files").

Consider dropping the duplicate assertion (or asserting on the respective default roots) to keep the test focused on what it claims to cover.

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

In `@test/test-create-require-budget.test.ts` around lines 87 - 93, The test is
redundantly asserting the same behavior for both
collectProductionCreateRequireSources and collectTestSupportCreateRequireSources
by passing the same directory and expecting the same result, so it does not
verify their different default roots. Update the test to either keep only one
assertion if the shared traversal/filtering is what’s being covered, or call
each function in a way that exercises its default root behavior (CLI_TEST_ROOT
vs TEST_SUPPORT_ROOT). Keep the focus on the production/create-require source
distinction in test/test-create-require-budget.test.ts.

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.

Nitpick comments:
In `@test/test-create-require-budget.test.ts`:
- Around line 87-93: The test is redundantly asserting the same behavior for
both collectProductionCreateRequireSources and
collectTestSupportCreateRequireSources by passing the same directory and
expecting the same result, so it does not verify their different default roots.
Update the test to either keep only one assertion if the shared
traversal/filtering is what’s being covered, or call each function in a way that
exercises its default root behavior (CLI_TEST_ROOT vs TEST_SUPPORT_ROOT). Keep
the focus on the production/create-require source distinction in
test/test-create-require-budget.test.ts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 3c696edb-90a0-4719-8de6-93daf724a4d8

📥 Commits

Reviewing files that changed from the base of the PR and between 41a4d4e and ccc251e.

📒 Files selected for processing (4)
  • scripts/checks/test-create-require-budget.ts
  • test/cli/helpers.test.ts
  • test/helpers/source-loader-options.ts
  • test/test-create-require-budget.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/cli/helpers.test.ts
  • test/helpers/source-loader-options.ts
  • scripts/checks/test-create-require-budget.ts

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Automated-review follow-up for 314ee9b50:

  • PRA-6 / PRA-T6 is now covered with the exact malformed --require forms requested (unclosed single quote, unclosed double quote, and mixed quotes), plus removal of an unquoted Windows-style assignment with escaped backslashes.
  • PRA-1, PRA-4, PRA-10, and PRA-12: source-loader removal is intentionally atomic. The helper tokenizes the complete external NODE_OPTIONS value before changing it; any incomplete quote or escape preserves the original bytes so it cannot partially remove the hook or alter unrelated flags. That contract is now documented and tested. This is test-only source-hook plumbing, and its removal condition is elimination of that hook.
  • PRA-2, PRA-5, and PRA-8: the policy dependency object is a narrow late-bound boundary that avoids eagerly importing the onboarding/rebuild graphs. Its methods directly return the underlying calls with no catch or translation, so errors propagate unchanged; existing policy-flow tests verify the consumer arguments and ordering. A direct mocked-require test would recreate the cache-loader seam this PR is removing. The boundary's removal condition is now documented.
  • PRA-3, PRA-7, and PRA-11: exact path allowlists are the intentional ratchet—retiring a path cannot create capacity for another file. The AST scan counts executable identifiers, including property access, while ignoring inert literal text; this intent and both outcomes are documented and tested. Source markers would weaken that exact-path invariant.
  • PRA-9 and the remaining runtime test follow-ups: the spaced-path case executes a real Node child, which is stronger than a string-only quoting assertion. The gateway and policy suites exercise the runtime seams without reintroducing createRequire or cache invalidation, and the tests tagged #6245 cover the issue's loader-removal and ratchet behavior.

Focused verification on this head: 16/16 tests passed, Biome passed, the CLI type-check passed in the normal pre-push hook, and the loader budget remains 35 CLI test files / 8 support files.

@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

PRA-4 follow-up: this PR intentionally takes the finding's documented-and-tested fallback alternative, not the throw alternative.

Preserving malformed input is the accepted contract here; attempting to surgically remove a token from a string whose boundaries cannot be established would be the unsafe behavior. No further code change is planned for this non-binding finding.

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI follow-up in 494f24bc2:

The first final-head run and a failed-job-only rerun both reproduced 10-second beforeEach timeouts in rebuild-resume-snapshot.test.ts and rebuild-shields-finally.test.ts. These were loader-pressure failures, not assertion failures: each hook synchronously loaded more than 600 source modules through createRequire while its shard was collecting V8 coverage.

The fix moves the four rebuild-to-onboard calls behind one lazy typed boundary, converts the snapshot suite to native imports/seam spies, and narrows the shields suite to the pipeline finally contract with phase-boundary mocks. Both suites now contain no createRequire or cache invalidation, reducing the exact CLI allowlist from 35 to 33 paths (44 at the start of this PR).

Verification on the new head:

  • Both former timeout suites with V8 coverage: 2/2 passed, 60 ms combined test time, 4.63 s total including transform/import/coverage.
  • All rebuild source suites: 41 files, 311/311 tests passed.
  • Credential rebuild integration: 13/13 tests passed.
  • Independent direct-spy compatibility review: 11 files, 109/109 tests passed.
  • CLI type-check, Biome, diff check, normal hooks, and the 33-CLI/8-support budget all passed.

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

PRA-1 / PRA-2 seam rationale for the final head:

  • Invalid state and source boundary: eager import of the broad CommonJS onboarding/rebuild graphs made focused test setup synchronously instrument 600+ modules. Under shard coverage pressure, two independent suites exceeded Vitest's hook timeout on both the initial run and a failed-job-only rerun.
  • Why the source cannot be removed here: eliminating the boundary entirely requires converting the monolithic onboarding/rebuild graphs into side-effect-free named imports. This PR localizes the legacy boundary and keeps production calls transparent while that larger migration proceeds incrementally.
  • Regression evidence: the two former timeout suites pass with V8 coverage; all 41 rebuild suites pass 311/311; and an independent compatibility run passed 11 direct-spy-dependent suites / 109 tests. Those tests spy the real underlying ../../onboard CommonJS exports, so their success proves the lazy wrappers perform call-time lookup and preserve delegation/error behavior. Policy-channel caller suites also assert the token definitions, options, sandbox name, argv, ordering, and failure paths passed into the narrow boundary. The wrappers contain no catch, coercion, fallback, or argument transformation.
  • Why no loader-introspection test: directly mocking require() or inspecting require.cache would recreate the exact CommonJS loader/cache seam this PR removes. The gateway healthy/probe paths are covered through the injectable runtime object; source inspection and the dynamic import location pin onboarding to the recovery-only method without loader mutation.
  • Removal condition: both dependency-boundary comments identify removal when the underlying onboarding/rebuild APIs can be imported as side-effect-free named exports. The exact 33-path guard prevents the retired test seams from returning in the meantime.

On that basis, the requested direct seam tests would add a weaker implementation-coupled loader test and are intentionally not added. The existing behavior, direct-spy compatibility, coverage reproduction, and exact-path ratchet are the accepted validation for these two non-blocking warnings.

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Additional CI root-cause follow-up in 0a62b329b:

After the production rebuild boundary became lazy, two legacy shared harnesses still called require("../../onboard") inside createRebuildFlowHarness(). Before this PR that barrel had already been warmed indirectly by rebuild.js; after the cleanup, it became a cold 218-TypeScript-module load inside each file's first 5-second test. That explains why the next run moved the timeout to three previously unchanged harness consumers.

Both harnesses now spy rebuildOnboardDependencies directly and retain the leaf credential-env fallback. This keeps the full onboard barrel out of the timed test body while preserving the harness APIs and production call path.

Validation on 0a62b329b:

  • All consumers of both harnesses: 10 files, 105/105 tests passed.
  • Coverage-mode reproduction of the initially exposed harness suites: 4/4 tests passed, with 87–102 ms test bodies.
  • Independent review confirmed mock restoration and that a cold rebuild import no longer places src/lib/onboard.ts in require.cache.
  • Biome, diff check, normal hooks, and the 33-CLI/8-support loader budget passed.

No timeout was raised and no behavior was bypassed; this removes the cold loader work that the timeout was identifying.

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
@cv

cv commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Final-head cold-cache fix: f262eb0a6

The remaining shard failures all had the same cause. The main shared rebuild harness mocked onboard, but not rebuildOnboardDependencies.hydrateCredentialEnv, so the first compatible-endpoint rebuild still lazily loaded the full onboarding graph (279 modules). The failed shard recorded that first test at 8.114 seconds; the following cases were 49 ms and 12 ms.

This commit:

  • delegates credential hydration to the narrow onboard/credential-env leaf;
  • loads stable harness dependency modules once instead of resolving them in every createRebuildFlowHarness() call;
  • preserves fresh spies and the existing rebuild.js reload boundary; and
  • removes one now-redundant test-local createRequire/cache deletion, lowering the guard to 32 CLI test files (from 44 at baseline).

Verification on a genuinely cold source-transpile cache with V8 coverage:

  • all three formerly failing suites: 17/17 passed;
  • file test times: 67 ms, 167 ms, and 264 ms;
  • all shared-harness consumers: 10 files / 105 tests passed;
  • CLI typecheck, Biome, normal hooks, and the 32-CLI/8-support loader guard passed.

The commit is DCO-signed and GitHub-verified.

@cv
cv merged commit 7d3aada into main Jul 6, 2026
45 of 46 checks passed
@cv
cv deleted the codex/perf-reduce-create-require branch July 6, 2026 16:26
@wscurran wscurran added area: ci CI workflows, checks, release automation, or GitHub Actions chore Build, CI, dependency, or tooling maintenance area: e2e End-to-end tests, nightly failures, or validation infrastructure labels Jul 7, 2026
cv added a commit that referenced this pull request Jul 7, 2026
<!-- markdownlint-disable MD041 -->
## Summary
Run the integration project as a bounded four-worker phase during the
canonical local `npm test`, while keeping CI, coverage, focused
integration, and direct Vitest runs serialized. Isolate two onboarding
fixtures from host-global dashboard ports so the parallel suite remains
deterministic. This is the final cumulative #6245 step after the named
onboarding conversions, representative process-contract work, and
sequenced loader cleanup already merged; the final clean-build Node 22
suite passes in 3:52.03.

## Related Issue
Closes #6245.

## Changes
- Replace the dashboard-exhaustion fixture's real host listeners with a
fake `lsof` while retaining the real CLI, preflight, diagnostic, and
non-zero exit contract.
- Give the restore-intent fixture an explicit existing dashboard forward
so unrelated host port occupancy cannot divert the behavior under test.
- Resolve integration scheduling from npm lifecycle, CI, coverage, and
worker-cap inputs: local `npm test` uses at most four workers in group
1, while every safety-sensitive route stays serial.
- Add a behavior matrix covering local, CI, coverage, focused, direct,
and explicit worker-throttle modes.
- Complete the cumulative #6245 acceptance path after #6276/#6336/#6383
converted the named onboarding hotspots, #6285/#6417 retained
representative process contracts, and #6286/#6299/#6388/#6415 sequenced
loader cleanup after process removal.
- Record the final host-specific timings, hotspot disposition, and
retained process-contract inventory in `test/README.md` as an advisory
acceptance snapshot rather than a permanent CI budget.

## 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
<!-- Check exactly one tests line and one docs line. Check other lines
when applicable. Add every requested justification or approval
reference. -->
- [x] Tests added or updated for changed behavior
- [ ] Existing tests cover changed behavior — justification:
- [ ] Tests not applicable — justification:
- [ ] Docs updated for user-facing behavior changes
- [x] Docs not applicable — justification: Test fixtures and local
test-runner scheduling changed; NemoClaw commands, configuration,
runtime behavior, and CI/coverage workflows are unchanged.
- [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: Independent final-diff
review confirmed that the fake `lsof` preserves the real
CLI/preflight/exit contract, the restore-intent assertions remain
intact, and resolved CI/coverage configurations remain serialized.
- [ ] Non-success, skipped, or missing CI check accepted by maintainer —
check name, approval link, and follow-up issue:

## Verification
<!-- Check each applicable item only when supported by the requested
evidence. Run targeted tests once per relevant change set and rerun
after later edits or hook autofixes that can affect the tested behavior.
Do not rerun hook-covered checks. -->
- [x] PR description includes the DCO sign-off declaration and every
commit appears as `Verified` in GitHub
- [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or
`npm run check:diff` passed when hooks were skipped or unavailable
- [x] Targeted behavior tests pass for the current change set, or tests
are marked not applicable above — command/result or justification: Real
CLI exhaustion contract passed; restore-intent passed with all 11
dashboard ports deliberately occupied; scheduling matrix passed 14/14
through the lifecycle-triggered config; `npm run test:projects:check`
reported 1,327 files disjoint across 8 projects.
- [x] Applicable broad gate passed — `npm test` for broad
runtime/test-harness changes; `npm run check` for repo-wide
validation/coverage changes — command/result: Clean-build Node 22 `npm
test -- --reporter=blob` under the normal `umask 022` passed 1,251 files
and 13,879 tests with 39 skipped, 1 todo, and zero failures in 3:52.03,
down 73% from the issue's 14:19.65 baseline despite a larger suite. The
matching diff-scoped routine pre-commit stage passed in 13.95s. #6270
separately removed full coverage from routine pre-commit while
preserving manual and authoritative CI gates.
- [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)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

---
<!-- DCO sign-off is required in this PR description, and every commit
must appear as Verified in GitHub. Run: git config user.name && git
config user.email -->
Signed-off-by: Carlos Villela <cvillela@nvidia.com>


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

## Summary by CodeRabbit

* **New Features**
* Integration test runs now use adaptive scheduling to speed up local
execution while keeping CI/focused runs serialized.

* **Bug Fixes**
* Improved reliability of onboarding regression coverage by simulating
dashboard port exhaustion in a hermetic way.
* Updated onboarding-related fixtures to better match the intended
readiness/exit behavior.

* **Tests**
* Added coverage for integration scheduling behavior (local caps,
invalid inputs, and CI/coverage scenarios).

* **Documentation**
* Added test-suite documentation with a local performance snapshot and
key test hotspots.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Hadar301 pushed a commit to Hadar301/NemoClaw-OpenShift that referenced this pull request Jul 12, 2026
<!-- markdownlint-disable MD041 -->
## Summary
This removes repeated `createRequire` use and CommonJS cache
manipulation from the policy-channel, gateway-runtime, and rebuild
suites, replaces native-safe seams with typed imports, and keeps
heavyweight provider/rebuild dependencies late-bound. It reduces CLI
test files using `createRequire` from 44 to 32 and adds exact path
guardrails so the remaining seams can only decrease.

## Related Issue
Refs NVIDIA#6245

## Changes
- Convert six policy/channel suites plus runner and status tests to
native imports and typed dependency seams.
- Load policy conflict detection from its leaf module while deferring
provider and rebuild graphs until their runtime paths execute.
- Replace the gateway-runtime suite's per-test onboard graph load and
cache invalidation with a native, late-bound dependency seam.
- Move rebuild-to-onboard calls behind one lazy typed boundary and
replace two coverage-timeout rebuild suites with native, phase-focused
tests.
- Centralize source-loader `NODE_OPTIONS` quoting/removal, preserving
unrelated options and limiting bypass to the explicit compiled-artifact
test.
- Enforce exact `createRequire` allowlists for 32 CLI tests and 8
support files across `.ts`, `.mts`, `.cts`, and `.tsx`; production
TypeScript remains prohibited and the scanner skips symlinks.
- Expand the repository-check hook matcher to cover every TypeScript
module extension.
- Give the compiled CLI dispatch contract enough polling time under CI
contention while retaining cleanup headroom.

## Type of Change

- [x] 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
- [x] Tests added or updated for changed behavior
- [ ] Existing tests cover changed behavior — justification:
- [ ] Tests not applicable — justification:
- [ ] Docs updated for user-facing behavior changes
- [x] Docs not applicable — justification: Internal test loading,
dependency injection, and repository guardrails only; no user-facing
behavior or interface changes.
- [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: Independent read-only
reviews found no remaining runtime, test-isolation, TypeScript,
guardrail, or documentation findings after follow-up.
- [ ] 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] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or
`npm run check:diff` passed when hooks were skipped or unavailable
- [x] Targeted behavior tests pass for the current change set, or tests
are marked not applicable above — 13 focused source/integration suites
passed 147/147; the parser/guard review batch passed 16/16; all 41
rebuild suites passed 311/311, 13 credential integration tests passed,
all 10 shared-harness consumer suites passed 105/105, and the three
formerly timing-out suites passed 17/17 from a cold source cache with V8
coverage (67–264 ms per file); all 17 package-contract files passed
290/290; the CLI type-check and 32-CLI/8-support budget passed.
- [x] Applicable broad gate passed — CI-equivalent five-shard
CLI/integration coverage merge passed 11,496 tests with zero failures;
coverage passed at 71.48% lines, 72.76% functions, 64.01% branches, and
70.86% statements.
- [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)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

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

---------

Signed-off-by: Carlos Villela <cvillela@nvidia.com>
Hadar301 pushed a commit to Hadar301/NemoClaw-OpenShift that referenced this pull request Jul 12, 2026
<!-- markdownlint-disable MD041 -->
## Summary
Run the integration project as a bounded four-worker phase during the
canonical local `npm test`, while keeping CI, coverage, focused
integration, and direct Vitest runs serialized. Isolate two onboarding
fixtures from host-global dashboard ports so the parallel suite remains
deterministic. This is the final cumulative NVIDIA#6245 step after the named
onboarding conversions, representative process-contract work, and
sequenced loader cleanup already merged; the final clean-build Node 22
suite passes in 3:52.03.

## Related Issue
Closes NVIDIA#6245.

## Changes
- Replace the dashboard-exhaustion fixture's real host listeners with a
fake `lsof` while retaining the real CLI, preflight, diagnostic, and
non-zero exit contract.
- Give the restore-intent fixture an explicit existing dashboard forward
so unrelated host port occupancy cannot divert the behavior under test.
- Resolve integration scheduling from npm lifecycle, CI, coverage, and
worker-cap inputs: local `npm test` uses at most four workers in group
1, while every safety-sensitive route stays serial.
- Add a behavior matrix covering local, CI, coverage, focused, direct,
and explicit worker-throttle modes.
- Complete the cumulative NVIDIA#6245 acceptance path after NVIDIA#6276/NVIDIA#6336/NVIDIA#6383
converted the named onboarding hotspots, NVIDIA#6285/NVIDIA#6417 retained
representative process contracts, and NVIDIA#6286/NVIDIA#6299/NVIDIA#6388/NVIDIA#6415 sequenced
loader cleanup after process removal.
- Record the final host-specific timings, hotspot disposition, and
retained process-contract inventory in `test/README.md` as an advisory
acceptance snapshot rather than a permanent CI budget.

## 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
<!-- Check exactly one tests line and one docs line. Check other lines
when applicable. Add every requested justification or approval
reference. -->
- [x] Tests added or updated for changed behavior
- [ ] Existing tests cover changed behavior — justification:
- [ ] Tests not applicable — justification:
- [ ] Docs updated for user-facing behavior changes
- [x] Docs not applicable — justification: Test fixtures and local
test-runner scheduling changed; NemoClaw commands, configuration,
runtime behavior, and CI/coverage workflows are unchanged.
- [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: Independent final-diff
review confirmed that the fake `lsof` preserves the real
CLI/preflight/exit contract, the restore-intent assertions remain
intact, and resolved CI/coverage configurations remain serialized.
- [ ] Non-success, skipped, or missing CI check accepted by maintainer —
check name, approval link, and follow-up issue:

## Verification
<!-- Check each applicable item only when supported by the requested
evidence. Run targeted tests once per relevant change set and rerun
after later edits or hook autofixes that can affect the tested behavior.
Do not rerun hook-covered checks. -->
- [x] PR description includes the DCO sign-off declaration and every
commit appears as `Verified` in GitHub
- [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or
`npm run check:diff` passed when hooks were skipped or unavailable
- [x] Targeted behavior tests pass for the current change set, or tests
are marked not applicable above — command/result or justification: Real
CLI exhaustion contract passed; restore-intent passed with all 11
dashboard ports deliberately occupied; scheduling matrix passed 14/14
through the lifecycle-triggered config; `npm run test:projects:check`
reported 1,327 files disjoint across 8 projects.
- [x] Applicable broad gate passed — `npm test` for broad
runtime/test-harness changes; `npm run check` for repo-wide
validation/coverage changes — command/result: Clean-build Node 22 `npm
test -- --reporter=blob` under the normal `umask 022` passed 1,251 files
and 13,879 tests with 39 skipped, 1 todo, and zero failures in 3:52.03,
down 73% from the issue's 14:19.65 baseline despite a larger suite. The
matching diff-scoped routine pre-commit stage passed in 13.95s. NVIDIA#6270
separately removed full coverage from routine pre-commit while
preserving manual and authoritative CI gates.
- [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)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

---
<!-- DCO sign-off is required in this PR description, and every commit
must appear as Verified in GitHub. Run: git config user.name && git
config user.email -->
Signed-off-by: Carlos Villela <cvillela@nvidia.com>


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

## Summary by CodeRabbit

* **New Features**
* Integration test runs now use adaptive scheduling to speed up local
execution while keeping CI/focused runs serialized.

* **Bug Fixes**
* Improved reliability of onboarding regression coverage by simulating
dashboard port exhaustion in a hermetic way.
* Updated onboarding-related fixtures to better match the intended
readiness/exit behavior.

* **Tests**
* Added coverage for integration scheduling behavior (local caps,
invalid inputs, and CI/coverage scenarios).

* **Documentation**
* Added test-suite documentation with a local performance snapshot and
key test hotspots.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ci CI workflows, checks, release automation, or GitHub Actions area: e2e End-to-end tests, nightly failures, or validation infrastructure chore Build, CI, dependency, or tooling maintenance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants