diff --git a/docs/index.yml b/docs/index.yml index 6ab295d9d8e..54731b70094 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -381,6 +381,9 @@ navigation: - page: "Troubleshoot MCP Servers" path: _build/agent-variants/reference/troubleshoot-mcp-servers.openclaw.generated.mdx slug: troubleshoot-mcp-servers + - page: "System Readiness" + path: _build/agent-variants/reference/system-readiness.openclaw.generated.mdx + slug: system-readiness - page: "Troubleshooting" path: _build/agent-variants/reference/troubleshooting.openclaw.generated.mdx slug: troubleshooting @@ -682,6 +685,9 @@ navigation: - page: "Troubleshoot MCP Servers" path: _build/agent-variants/reference/troubleshoot-mcp-servers.deepagents.generated.mdx slug: troubleshoot-mcp-servers + - page: "System Readiness" + path: _build/agent-variants/reference/system-readiness.deepagents.generated.mdx + slug: system-readiness - page: "Troubleshooting" path: _build/agent-variants/reference/troubleshooting.deepagents.generated.mdx slug: troubleshooting @@ -1052,6 +1058,9 @@ navigation: - page: "Troubleshoot MCP Servers" path: _build/agent-variants/reference/troubleshoot-mcp-servers.hermes.generated.mdx slug: troubleshoot-mcp-servers + - page: "System Readiness" + path: _build/agent-variants/reference/system-readiness.hermes.generated.mdx + slug: system-readiness - page: "Troubleshooting" path: _build/agent-variants/reference/troubleshooting.hermes.generated.mdx slug: troubleshooting diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index a4ab2dafd92..9f2836d3ba1 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -170,6 +170,18 @@ $$nemoclaw resources [--json] If the gateway is not running, Kubernetes allocatable fields are omitted and host CPU/RAM totals are still shown. +### `$$nemoclaw host probe` + +Inspect host readiness before onboarding without changing host, Docker, gateway, credential, policy, or sandbox state. +Use `--json` for the schema-versioned report. +The command exits with `0` for `supported`, `2` for `incompatible`, and `3` for `inconclusive`. + +```bash +$$nemoclaw host probe [--json] +``` + +For capability IDs, evidence bounds, and compatibility guidance, refer to [System Readiness](system-readiness). + ### `$$nemoclaw agents list` List the installed agent runtimes that can be selected with `$$nemoclaw onboard --agent `. diff --git a/docs/reference/system-readiness.mdx b/docs/reference/system-readiness.mdx new file mode 100644 index 00000000000..5b681266690 --- /dev/null +++ b/docs/reference/system-readiness.mdx @@ -0,0 +1,64 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "System Readiness" +sidebar-title: "System Readiness" +description: "Check host readiness before NemoClaw onboarding without changing system state." +description-agent: "Documents the read-only host readiness command, JSON contract, exit codes, redaction boundary, and mutation guarantees. Use when checking a host before onboarding or consuming readiness JSON." +keywords: ["nemoclaw host probe", "system readiness", "readiness json", "pre-onboarding check"] +content: + type: "reference" +--- + +Use the system readiness report to inspect a host before you run onboarding. +The command works without a registered gateway or sandbox. + +## Run the readiness check + +Run the human-readable check from the host: + +```bash +$$nemoclaw host probe +``` + +Use JSON when another tool consumes the result: + +```bash +$$nemoclaw host probe --json +``` + +Both presentations use the same structured report. +The JSON report includes its `schemaVersion`, `status`, `exitCode`, `observations`, `capabilities`, `qualifications`, `findings`, `evidence`, and `provenance`. +It also includes `mutated: false`. + +## Interpret exit codes + +The command uses deterministic exit codes: + +| Exit code | Status | Meaning | +| --- | --- | --- | +| `0` | `supported` | Required readiness checks passed. | +| `2` | `incompatible` | A blocking or fatal finding prevents onboarding. | +| `3` | `inconclusive` | NemoClaw could not determine a required capability. | + +The command writes a schema-valid JSON report for all three results. +Read the report before you handle a nonzero exit. + +## Use the compatibility contract + +The `schemaVersion` field uses `major.minor.patch` format. +Consumers must reject an unknown major version. +Consumers can ignore fields that they do not recognize within major version 1. +Use stable capability and finding IDs instead of parsing human summaries. +Treat bounded evidence as diagnostic context unless an observation, capability, or finding references that evidence ID. + +## Understand the read-only boundary + +`host probe` observes the host and does not run remediation. +Repeated runs do not change filesystem, service, Docker image or container, gateway, provider, credential, policy, or sandbox state. +A future command that changes the host must use a separate mutating mode. +That mode cannot run with `--json` probing. + +The public report removes process environments and unrecognized fields from internal probe results. +It redacts token-shaped values and credential-bearing URLs. +It also limits finding summaries and command evidence before either presentation receives the report. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 7528844e8fb..789b2337f3a 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -72,6 +72,16 @@ If you cannot add memory, configure at least 8 GB of swap to work around the iss ### Docker is not running +Check the host before onboarding: + +```bash +$$nemoclaw host probe +``` + +The command does not start Docker or apply a repair. +A `host.docker.daemon_unreachable` finding means Docker is installed but NemoClaw cannot reach the daemon. +For JSON output and exit-code details, refer to [System Readiness](system-readiness). + The installer and onboard wizard require Docker to be running. If you see a Docker connection error, start the Docker daemon: diff --git a/src/commands/host/probe.test.ts b/src/commands/host/probe.test.ts new file mode 100644 index 00000000000..8fbe21cb582 --- /dev/null +++ b/src/commands/host/probe.test.ts @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import Ajv2020, { type AnySchema } from "ajv/dist/2020.js"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import systemReadinessSchema from "../../../schemas/system-readiness.schema.json" with { + type: "json", +}; +import type { SystemReadinessReport } from "../../lib/readiness/types"; + +const mocks = vi.hoisted(() => ({ + createHostReadinessReport: vi.fn(), + createPublicReadinessReport: vi.fn(), + renderReadinessReport: vi.fn(), +})); + +vi.mock("../../lib/readiness/index", () => ({ + createHostReadinessReport: mocks.createHostReadinessReport, + createPublicReadinessReport: mocks.createPublicReadinessReport, + renderReadinessReport: mocks.renderReadinessReport, +})); + +import HostProbeCommand from "./probe"; + +type ReadinessOutcome = + | { status: "supported"; exitCode: 0 } + | { status: "incompatible"; exitCode: 2 } + | { status: "inconclusive"; exitCode: 3 }; + +const READINESS_OUTCOMES = [ + { status: "supported", exitCode: 0 }, + { status: "incompatible", exitCode: 2 }, + { status: "inconclusive", exitCode: 3 }, +] as const satisfies readonly ReadinessOutcome[]; + +function throwSchemaErrors(errors: unknown): never { + throw new Error(JSON.stringify(errors)); +} + +function assertSchemaValid(value: unknown): void { + const ajv = new Ajv2020({ allErrors: true, strict: true }); + ajv.addFormat("date-time", true); + const validate = ajv.compile(systemReadinessSchema as AnySchema); + validate(value) || throwSchemaErrors(validate.errors); +} + +function report(outcome: ReadinessOutcome): SystemReadinessReport { + return { + schemaVersion: "1.0.0", + ...outcome, + mutated: false, + provenance: { nemoclawVersion: "0.1.0", observedAt: "2026-06-01T12:00:00.000Z" }, + observations: [], + capabilities: [], + qualifications: [], + findings: [], + evidence: [], + }; +} + +describe("host probe command (#7412)", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.createHostReadinessReport.mockReturnValue(report(READINESS_OUTCOMES[0])); + mocks.createPublicReadinessReport.mockImplementation((value) => value); + mocks.renderReadinessReport.mockReturnValue("System readiness: supported"); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it.each(READINESS_OUTCOMES)("returns the deterministic $status exit code", async (outcome) => { + const previousExitCode = process.exitCode; + process.exitCode = undefined; + mocks.createHostReadinessReport.mockReturnValueOnce(report(outcome)); + + try { + await HostProbeCommand.run([], process.cwd()); + expect(process.exitCode).toBe(outcome.exitCode); + } finally { + process.exitCode = previousExitCode; + } + }); + + it.each(READINESS_OUTCOMES)("emits schema-valid JSON for $status hosts", async (outcome) => { + const expectedReport = report(outcome); + mocks.createHostReadinessReport.mockReturnValueOnce(expectedReport); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const previousExitCode = process.exitCode; + process.exitCode = undefined; + + try { + await HostProbeCommand.run(["--json"], process.cwd()); + const output = JSON.parse(String(log.mock.calls.at(-1)?.[0])); + + assertSchemaValid(output); + expect(output).toEqual(expectedReport); + expect(process.exitCode).toBe(outcome.exitCode); + expect(mocks.renderReadinessReport).not.toHaveBeenCalled(); + } finally { + process.exitCode = previousExitCode; + } + }); + + it("uses one readiness report for human output (#7412)", async () => { + const publicReport = report(READINESS_OUTCOMES[0]); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + mocks.createPublicReadinessReport.mockReturnValueOnce(publicReport); + + await HostProbeCommand.run([], process.cwd()); + + expect(mocks.createHostReadinessReport).toHaveBeenCalledWith({ nemoclawVersion: "0.1.0" }); + expect(mocks.createPublicReadinessReport).toHaveBeenCalledWith( + mocks.createHostReadinessReport.mock.results[0]?.value, + ); + expect(mocks.renderReadinessReport).toHaveBeenCalledWith(publicReport); + expect(log).toHaveBeenCalledWith("System readiness: supported"); + }); + + it("repeats through the observation-only dependency graph", async () => { + vi.spyOn(console, "log").mockImplementation(() => undefined); + + await HostProbeCommand.run([], process.cwd()); + await HostProbeCommand.run(["--json"], process.cwd()); + + expect(mocks.createHostReadinessReport).toHaveBeenCalledTimes(2); + expect(mocks.createPublicReadinessReport).toHaveBeenCalledTimes(2); + expect(mocks.renderReadinessReport).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/commands/host/probe.ts b/src/commands/host/probe.ts new file mode 100644 index 00000000000..10232a63567 --- /dev/null +++ b/src/commands/host/probe.ts @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { NemoClawCommand } from "../../lib/cli/nemoclaw-oclif-command"; +import { + createHostReadinessReport, + createPublicReadinessReport, + renderReadinessReport, +} from "../../lib/readiness"; + +export default class HostProbeCommand extends NemoClawCommand { + static id = "host:probe"; + static strict = true; + static enableJsonFlag = true; + static summary = "Report host readiness without changing the system"; + static description = + "Inspect host capabilities before onboarding. The command does not remediate findings or change host, Docker, gateway, credential, policy, or sandbox state."; + static usage = ["host probe [--json]"]; + static examples = ["<%= config.bin %> host probe", "<%= config.bin %> host probe --json"]; + static flags = {}; + static publicDisplay = [ + { + usage: "nemoclaw host probe", + description: "Report host readiness without changing the system", + flags: "[--json]", + group: "Troubleshooting", + scope: "global", + order: 37.5, + }, + ] as const; + + public async run(): Promise { + await this.parse(HostProbeCommand); + const report = createPublicReadinessReport( + createHostReadinessReport({ nemoclawVersion: this.config.version }), + ); + this.setExitCode(report.exitCode); + if (this.jsonEnabled()) return report; + this.log(renderReadinessReport(report)); + } +} diff --git a/src/lib/readiness/effects.test.ts b/src/lib/readiness/effects.test.ts new file mode 100644 index 00000000000..e6f52c75342 --- /dev/null +++ b/src/lib/readiness/effects.test.ts @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { assessHost } from "../onboard/preflight"; +import { createHostReadinessReport } from "./host"; + +const NOW = new Date("2026-06-01T12:00:00Z"); +const DOCKER_INFO = JSON.stringify({ + CgroupVersion: "2", + Driver: "overlay2", + DriverStatus: [], + NCPU: 8, + MemTotal: 16 * 1024 ** 3, + OperatingSystem: "Docker Engine", +}); +const COMMAND_OUTPUTS: Record = { + 'sh -c command -v "$1" -- docker': "/usr/bin/docker", + 'sh -c command -v "$1" -- node': "/usr/bin/node", + 'sh -c command -v "$1" -- openshell': "/usr/bin/openshell", + 'sh -c command -v "$1" -- nvidia-ctk': "/usr/bin/nvidia-ctk", + 'sh -c command -v "$1" -- apt-get': "", + 'sh -c command -v "$1" -- dnf': "", + 'sh -c command -v "$1" -- yum': "", + 'sh -c command -v "$1" -- brew': "", + 'sh -c command -v "$1" -- pacman': "", + 'sh -c command -v "$1" -- systemctl': "/usr/bin/systemctl", + "docker info --format {{json .}}": DOCKER_INFO, + "systemctl is-active docker": "active", + "systemctl is-enabled docker": "enabled", +}; +const FILE_CONTENTS: Record = { + "/proc/version": "Linux version 6.8", + "/etc/docker/daemon.json": "{}", + "/home/rootless/.config/docker/daemon.json": "{}", +}; + +describe("readiness process effects (#7412)", () => { + it("repeats the host probe without invoking a mutating dependency", () => { + const commands: string[][] = []; + const reads: string[] = []; + const directories: string[] = []; + const runCaptureImpl = vi.fn((command: readonly string[]) => { + commands.push([...command]); + return COMMAND_OUTPUTS[command.join(" ")] ?? ""; + }); + const readFileImpl = vi.fn((path: string) => { + reads.push(path); + return FILE_CONTENTS[path] ?? ""; + }); + const readdirImpl = vi.fn((path: string) => { + directories.push(path); + return []; + }); + const assess = vi.fn(() => + assessHost({ + gpuProbeImpl: () => false, + platform: "linux", + readFileImpl, + readdirImpl, + runCaptureImpl, + }), + ); + const options = { nemoclawVersion: "0.1.0", now: () => NOW }; + const collectionOptions = { assess, now: () => NOW }; + + const first = createHostReadinessReport(options, collectionOptions); + const second = createHostReadinessReport(options, collectionOptions); + + expect(first).toEqual(second); + expect(first.mutated).toBe(false); + expect(assess).toHaveBeenCalledTimes(2); + expect(commands.length).toBeGreaterThan(0); + expect(commands.every((command) => Object.hasOwn(COMMAND_OUTPUTS, command.join(" ")))).toBe( + true, + ); + expect( + commands + .filter(([command]) => command === "systemctl") + .every(([, operation]) => operation === "is-active" || operation === "is-enabled"), + ).toBe(true); + expect( + commands + .filter(([command]) => command === "docker") + .every(([, operation]) => operation === "info"), + ).toBe(true); + expect( + reads.every((path) => + [ + "/proc/version", + "/etc/docker/daemon.json", + "/home/rootless/.config/docker/daemon.json", + ].includes(path), + ), + ).toBe(true); + expect(directories.every((path) => path === "/etc/cdi" || path === "/var/run/cdi")).toBe(true); + }); +}); diff --git a/src/lib/readiness/index.ts b/src/lib/readiness/index.ts index c29cd83256d..247025f6f3c 100644 --- a/src/lib/readiness/index.ts +++ b/src/lib/readiness/index.ts @@ -15,6 +15,7 @@ export type { HostObservationSnapshot, HostObservations, } from "./host.js"; +export { createPublicReadinessReport, renderReadinessReport } from "./presentation.js"; export { SUPPORTED_SYSTEM_READINESS_SCHEMA_MAJOR, SYSTEM_READINESS_SCHEMA_VERSION, diff --git a/src/lib/readiness/presentation.test.ts b/src/lib/readiness/presentation.test.ts new file mode 100644 index 00000000000..bc56cd0af38 --- /dev/null +++ b/src/lib/readiness/presentation.test.ts @@ -0,0 +1,325 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { createPublicReadinessReport, renderReadinessReport } from "./presentation"; +import type { SystemReadinessReport } from "./types"; + +type ReadinessOutcome = + | { status: "supported"; exitCode: 0 } + | { status: "incompatible"; exitCode: 2 } + | { status: "inconclusive"; exitCode: 3 }; + +type ReportOverrides = Partial< + Omit, "status" | "exitCode"> +>; + +const NON_SUPPORTED_OUTCOMES = [ + { status: "incompatible", exitCode: 2 }, + { status: "inconclusive", exitCode: 3 }, +] as const satisfies readonly ReadinessOutcome[]; + +function report( + overrides: ReportOverrides = {}, + outcome: ReadinessOutcome = { status: "supported", exitCode: 0 }, +): SystemReadinessReport { + return { + schemaVersion: "1.0.0", + ...outcome, + mutated: false, + provenance: { + nemoclawVersion: "0.1.0", + observedAt: "2026-06-01T12:00:00.000Z", + }, + observations: [], + capabilities: [], + qualifications: [], + findings: [], + evidence: [], + ...overrides, + }; +} + +describe("public readiness presentation (#7412)", () => { + it("rejects reports that claim host mutation", () => { + const mutatedReport = { ...report(), mutated: true } as unknown as SystemReadinessReport; + + expect(() => createPublicReadinessReport(mutatedReport)).toThrow( + "Readiness reports must be observation-only.", + ); + }); + + it.each(NON_SUPPORTED_OUTCOMES)("preserves $status status and exit code $exitCode", (outcome) => { + const publicReport = createPublicReadinessReport(report({}, outcome)); + + expect(publicReport).toMatchObject({ ...outcome, mutated: false }); + }); + + it.each([ + [`nvapi-${"a".repeat(24)}`, undefined], + ["not-a-source-revision", undefined], + ["a".repeat(40), "a".repeat(40)], + ])("publishes only immutable source revisions", (sourceRevision, expected) => { + const publicReport = createPublicReadinessReport( + report({ + provenance: { + nemoclawVersion: "0.1.0", + observedAt: "2026-06-01T12:00:00.000Z", + sourceRevision, + }, + }), + ); + + expect(publicReport.provenance.sourceRevision).toBe(expected); + }); + + it("renders human output from the same public report used for JSON", () => { + const publicReport = createPublicReadinessReport( + report( + { + findings: [ + { + id: "host.docker.unavailable", + severity: "blocking", + summary: "Docker is not installed.", + }, + ], + }, + { status: "incompatible", exitCode: 2 }, + ), + ); + + expect(renderReadinessReport(publicReport)).toContain("System readiness: incompatible"); + expect(renderReadinessReport(publicReport)).toContain( + "[blocking] host.docker.unavailable: Docker is not installed.", + ); + }); + + it("redacts secrets and excludes process environments at the public boundary", () => { + const token = `nvapi-${"a".repeat(24)}`; + const publicReport = createPublicReadinessReport( + report({ + findings: [ + { + id: "host.probe.failure", + severity: "warning", + summary: `token=${token}`, + processEnv: { NVIDIA_API_KEY: token }, + }, + ], + evidence: [ + { + id: "host.probe.output", + summary: `https://user:${token}@example.test/path?token=${token}${"x".repeat(1200)}`, + details: { + stderr: `${token}${"x".repeat(1200)}`, + processEnv: `NVIDIA_API_KEY=${token}`, + "processEnv.PATH": "/usr/bin", + environmentDump: "HOME=/home/user", + envVars: `NVIDIA_API_KEY=${token}`, + }, + }, + ], + }), + ); + const serialized = JSON.stringify(publicReport); + + expect(serialized).not.toContain(token); + expect(serialized).not.toContain("user:"); + expect(serialized).not.toContain("NVIDIA_API_KEY"); + expect(serialized).not.toContain("processEnv"); + expect(serialized).not.toContain("environmentDump"); + expect(serialized).not.toContain("envVars"); + expect(publicReport.evidence[0]?.summary.length).toBeLessThanOrEqual(1024); + expect(String(publicReport.evidence[0]?.details?.stderr).length).toBeLessThanOrEqual(1024); + }); + + it("excludes camel-cased and suffixed process environment keys", () => { + const publicReport = createPublicReadinessReport( + report({ + evidence: [ + { + id: "host.probe.output", + summary: "Probe output", + details: { + processEnvironmentVariables: "HOME=/private/home PATH=/private/bin", + processEnvDumpV2: "USER=private-user", + stderr: "Docker is unavailable.", + }, + }, + ], + }), + ); + + expect(publicReport.evidence[0]?.details).toEqual({ stderr: "Docker is unavailable." }); + }); + + it("retains a final required finding at the public boundary", () => { + const warnings = Array.from({ length: 256 }, (_, index) => ({ + id: `host.boundary.${index}`, + severity: "warning" as const, + summary: `Warning ${index}`, + })); + const blocker = { + id: "host.boundary.blocker", + severity: "fatal" as const, + summary: "A final required finding.", + }; + + const publicReport = createPublicReadinessReport( + report({ findings: [...warnings, blocker] }, { status: "incompatible", exitCode: 2 }), + ); + + expect(publicReport.findings).toHaveLength(256); + expect(publicReport.findings).toContainEqual(blocker); + expect(publicReport.findings).not.toContainEqual(warnings.at(-1)); + }); + + it("retains evidence referenced by a finding beyond the initial evidence boundary", () => { + const evidence = Array.from({ length: 257 }, (_, index) => ({ + id: `host.boundary.evidence.${index}`, + summary: `Evidence ${index}`, + })); + const blocker = { + id: "host.boundary.blocker", + severity: "blocking" as const, + summary: "A blocker with late evidence.", + evidenceIds: [evidence.at(-1)?.id ?? ""], + }; + + const publicReport = createPublicReadinessReport( + report({ evidence, findings: [blocker] }, { status: "incompatible", exitCode: 2 }), + ); + + expect(publicReport.evidence).toHaveLength(256); + expect(publicReport.evidence.map(({ id }) => id)).toContain(evidence.at(-1)?.id); + expect(publicReport.evidence.map(({ id }) => id)).not.toContain(evidence.at(-2)?.id); + }); + + it("retains capabilities referenced by a qualification beyond the initial boundary", () => { + const capabilities = Array.from({ length: 257 }, (_, index) => ({ + id: `host.boundary.capability.${index}`, + state: "present" as const, + })); + const qualification = { + id: "host.boundary.qualification", + status: "qualified" as const, + capabilityIds: [capabilities.at(-1)?.id ?? ""], + }; + + const publicReport = createPublicReadinessReport( + report({ capabilities, qualifications: [qualification] }), + ); + + expect(publicReport.capabilities).toHaveLength(256); + expect(publicReport.capabilities.map(({ id }) => id)).toContain(capabilities.at(-1)?.id); + expect(publicReport.capabilities.map(({ id }) => id)).not.toContain(capabilities.at(-2)?.id); + }); + + it("fails closed when required findings exceed the public boundary", () => { + const blockers = Array.from({ length: 257 }, (_, index) => ({ + id: `host.blocker.${index}`, + severity: "blocking" as const, + summary: `Blocker ${index}`, + })); + + expect(() => + createPublicReadinessReport( + report({ findings: blockers }, { status: "incompatible", exitCode: 2 }), + ), + ).toThrow("Readiness report exceeds the public boundary for required findings."); + }); + + it("fails closed when a finding exceeds its capability-reference boundary", () => { + const capabilities = Array.from({ length: 65 }, (_, index) => ({ + id: `host.capability.${index}`, + state: "present" as const, + })); + const blocker = { + id: "host.boundary.blocker", + severity: "blocking" as const, + summary: "A blocker with too many capability references.", + capabilityIds: capabilities.map(({ id }) => id), + }; + + expect(() => + createPublicReadinessReport( + report({ capabilities, findings: [blocker] }, { status: "incompatible", exitCode: 2 }), + ), + ).toThrow("Readiness report exceeds the public boundary for finding capability references."); + }); + + it("fails closed when an observation exceeds its evidence-reference boundary", () => { + const evidence = Array.from({ length: 33 }, (_, index) => ({ + id: `host.evidence.${index}`, + summary: `Evidence ${index}`, + })); + const observation = { + id: "host.observation", + state: "present" as const, + evidenceIds: evidence.map(({ id }) => id), + }; + + expect(() => + createPublicReadinessReport(report({ evidence, observations: [observation] })), + ).toThrow("Readiness report exceeds the public boundary for observation evidence references."); + }); + + it("fails closed when a retained reference array contains duplicate IDs", () => { + const evidence = [{ id: "host.evidence", summary: "Evidence" }]; + const observation = { + id: "host.observation", + state: "present" as const, + evidenceIds: [evidence[0].id, evidence[0].id], + }; + + expect(() => + createPublicReadinessReport(report({ evidence, observations: [observation] })), + ).toThrow("Readiness report contains duplicate observation evidence references."); + }); + + it("fails closed when required capability references exceed the collection boundary", () => { + const capabilities = Array.from({ length: 257 }, (_, index) => ({ + id: `host.capability.${index}`, + state: "present" as const, + })); + const blockers = Array.from({ length: 5 }, (_, index) => ({ + id: `host.boundary.blocker.${index}`, + severity: "blocking" as const, + summary: "A blocker with required capabilities.", + capabilityIds: capabilities.slice(index * 64, (index + 1) * 64).map(({ id }) => id), + })); + + expect(() => + createPublicReadinessReport( + report({ capabilities, findings: blockers }, { status: "incompatible", exitCode: 2 }), + ), + ).toThrow("Readiness report exceeds the public boundary for referenced capability entries."); + }); + + it("fails closed when a required capability reference does not resolve", () => { + const blocker = { + id: "host.boundary.blocker", + severity: "blocking" as const, + summary: "A blocker with a missing capability.", + capabilityIds: ["host.capability.missing"], + }; + + expect(() => + createPublicReadinessReport( + report({ findings: [blocker] }, { status: "incompatible", exitCode: 2 }), + ), + ).toThrow("Readiness report contains unresolved capability references."); + }); + + it("rejects conflicting capabilities that use the same stable ID", () => { + const capabilities = [ + { id: "host.capability", state: "present" as const }, + { id: "host.capability", state: "absent" as const }, + ]; + + expect(() => createPublicReadinessReport(report({ capabilities }))).toThrow( + "Readiness report contains duplicate capability IDs.", + ); + }); +}); diff --git a/src/lib/readiness/presentation.ts b/src/lib/readiness/presentation.ts new file mode 100644 index 00000000000..a1208a4dd66 --- /dev/null +++ b/src/lib/readiness/presentation.ts @@ -0,0 +1,297 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { redactForLog } from "../security/redact.js"; +import type { + EvidenceScalar, + ReadinessCapability, + ReadinessEvidence, + ReadinessFinding, + ReadinessObservation, + ReadinessQualification, + SystemReadinessReport, +} from "./types.js"; + +const MAX_SUMMARY_LENGTH = 512; +const MAX_EVIDENCE_LENGTH = 1024; +const MAX_OBSERVATIONS = 256; +const MAX_CAPABILITIES = 256; +const MAX_QUALIFICATIONS = 128; +const MAX_FINDINGS = 256; +const MAX_EVIDENCE = 256; +const MAX_CAPABILITY_REFERENCES = 64; +const MAX_EVIDENCE_REFERENCES = 32; +const SOURCE_REVISION_PATTERN = /^[0-9a-f]{40,64}$/; +const ENVIRONMENT_DETAIL_KEYS = new Set([ + "env", + "environment", + "environmentdump", + "environmentvariables", + "envvars", + "processenv", + "processenvironment", +]); + +function bounded(value: string, maxLength: number): string { + return String(redactForLog(value)) + .replace(/([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi, "$1@") + .slice(0, maxLength); +} + +function scalar(value: EvidenceScalar): EvidenceScalar { + return typeof value === "string" ? bounded(value, MAX_EVIDENCE_LENGTH) : value; +} + +function isEnvironmentDetail(key: string): boolean { + const segments = key + .replace(/([a-z0-9])([A-Z])/g, "$1.$2") + .replace(/([A-Za-z])([0-9])/g, "$1.$2") + .replace(/([0-9])([A-Za-z])/g, "$1.$2") + .split(/[._-]/) + .filter(Boolean); + return segments.some((segment) => ENVIRONMENT_DETAIL_KEYS.has(segment.toLowerCase())); +} + +function boundedReferences( + references: readonly string[] | undefined, + maxReferences: number, + referenceName: string, +): readonly string[] | undefined { + if (!references) return undefined; + if (references.length > maxReferences) { + throw new Error(`Readiness report exceeds the public boundary for ${referenceName}.`); + } + if (new Set(references).size !== references.length) { + throw new Error(`Readiness report contains duplicate ${referenceName}.`); + } + return [...references]; +} + +function observation(entry: ReadinessObservation): ReadinessObservation { + const evidenceIds = boundedReferences( + entry.evidenceIds, + MAX_EVIDENCE_REFERENCES, + "observation evidence references", + ); + return { + id: entry.id, + state: entry.state, + ...(entry.value !== undefined ? { value: scalar(entry.value) } : {}), + ...(evidenceIds ? { evidenceIds } : {}), + }; +} + +function capability(entry: ReadinessCapability): ReadinessCapability { + const evidenceIds = boundedReferences( + entry.evidenceIds, + MAX_EVIDENCE_REFERENCES, + "capability evidence references", + ); + return { + id: entry.id, + state: entry.state, + ...(evidenceIds ? { evidenceIds } : {}), + }; +} + +function qualification(entry: ReadinessQualification): ReadinessQualification { + const capabilityIds = boundedReferences( + entry.capabilityIds, + MAX_CAPABILITY_REFERENCES, + "qualification capability references", + ); + return { + id: entry.id, + status: entry.status, + ...(capabilityIds ? { capabilityIds } : {}), + }; +} + +function finding(entry: ReadinessFinding): ReadinessFinding { + const capabilityIds = boundedReferences( + entry.capabilityIds, + MAX_CAPABILITY_REFERENCES, + "finding capability references", + ); + const evidenceIds = boundedReferences( + entry.evidenceIds, + MAX_EVIDENCE_REFERENCES, + "finding evidence references", + ); + return { + id: entry.id, + severity: entry.severity, + summary: bounded(entry.summary, MAX_SUMMARY_LENGTH), + ...(capabilityIds ? { capabilityIds } : {}), + ...(evidenceIds ? { evidenceIds } : {}), + }; +} + +function boundedFindings(entries: readonly ReadinessFinding[]): readonly ReadinessFinding[] { + const required = entries.filter( + ({ severity }) => severity === "blocking" || severity === "fatal", + ); + if (required.length > MAX_FINDINGS) { + throw new Error("Readiness report exceeds the public boundary for required findings."); + } + + const selected = new Set(required); + for (const entry of entries) { + if (selected.size >= MAX_FINDINGS) break; + selected.add(entry); + } + return entries.filter((entry) => selected.has(entry)); +} + +function addReferences(target: Set, references: readonly string[] | undefined): void { + for (const id of references ?? []) target.add(id); +} + +function assertUniqueIds( + entries: readonly T[], + entityName: string, +): void { + const ids = new Set(); + for (const entry of entries) { + if (ids.has(entry.id)) { + throw new Error(`Readiness report contains duplicate ${entityName} IDs.`); + } + ids.add(entry.id); + } +} + +function boundedReferencedEntries( + entries: readonly T[], + requiredIds: ReadonlySet, + maxEntries: number, + entityName: string, +): readonly T[] { + if (requiredIds.size > maxEntries) { + throw new Error( + `Readiness report exceeds the public boundary for referenced ${entityName} entries.`, + ); + } + + const entriesById = new Map(entries.map((entry) => [entry.id, entry])); + const missingIds = [...requiredIds].filter((id) => !entriesById.has(id)); + if (missingIds.length > 0) { + throw new Error(`Readiness report contains unresolved ${entityName} references.`); + } + + const selected = new Set([...requiredIds].map((id) => entriesById.get(id) as T)); + for (const entry of entries) { + if (selected.size >= maxEntries) break; + selected.add(entry); + } + return entries.filter((entry) => selected.has(entry)); +} + +function evidence(entry: ReadinessEvidence): ReadinessEvidence { + const redactedDetails = entry.details + ? (redactForLog(entry.details) as Record) + : undefined; + return { + id: entry.id, + summary: bounded(entry.summary, MAX_EVIDENCE_LENGTH), + ...(redactedDetails + ? { + details: Object.fromEntries( + Object.entries(redactedDetails) + .filter(([key]) => !isEnvironmentDetail(key)) + .slice(0, 16) + .map(([key, value]) => [key, scalar(value)]), + ), + } + : {}), + }; +} + +export function createPublicReadinessReport( + report: Readonly, +): SystemReadinessReport { + if (report.mutated !== false) { + throw new Error("Readiness reports must be observation-only."); + } + assertUniqueIds(report.observations, "observation"); + assertUniqueIds(report.capabilities, "capability"); + assertUniqueIds(report.qualifications, "qualification"); + assertUniqueIds(report.findings, "finding"); + assertUniqueIds(report.evidence, "evidence"); + // Keep these branches so TypeScript preserves the correlation between status and exitCode. + const outcome = + report.status === "supported" + ? ({ status: report.status, exitCode: report.exitCode } as const) + : report.status === "incompatible" + ? ({ status: report.status, exitCode: report.exitCode } as const) + : ({ status: report.status, exitCode: report.exitCode } as const); + const selectedObservations = report.observations.slice(0, MAX_OBSERVATIONS); + const selectedQualifications = report.qualifications.slice(0, MAX_QUALIFICATIONS); + const selectedFindings = boundedFindings(report.findings); + const requiredCapabilityIds = new Set(); + for (const entry of selectedQualifications) { + addReferences(requiredCapabilityIds, entry.capabilityIds); + } + for (const entry of selectedFindings) { + addReferences(requiredCapabilityIds, entry.capabilityIds); + } + const selectedCapabilities = boundedReferencedEntries( + report.capabilities, + requiredCapabilityIds, + MAX_CAPABILITIES, + "capability", + ); + const requiredEvidenceIds = new Set(); + for (const entry of selectedObservations) { + addReferences(requiredEvidenceIds, entry.evidenceIds); + } + for (const entry of selectedCapabilities) { + addReferences(requiredEvidenceIds, entry.evidenceIds); + } + for (const entry of selectedFindings) { + addReferences(requiredEvidenceIds, entry.evidenceIds); + } + const selectedEvidence = boundedReferencedEntries( + report.evidence, + requiredEvidenceIds, + MAX_EVIDENCE, + "evidence", + ); + return { + schemaVersion: report.schemaVersion, + ...outcome, + mutated: false, + provenance: { + nemoclawVersion: bounded(report.provenance.nemoclawVersion, 128), + ...(report.provenance.sourceRevision && + SOURCE_REVISION_PATTERN.test(report.provenance.sourceRevision) + ? { sourceRevision: report.provenance.sourceRevision } + : {}), + observedAt: report.provenance.observedAt, + }, + observations: selectedObservations.map(observation), + capabilities: selectedCapabilities.map(capability), + qualifications: selectedQualifications.map(qualification), + findings: selectedFindings.map(finding), + evidence: selectedEvidence.map(evidence), + }; +} + +export function renderReadinessReport(report: Readonly): string { + const lines = [ + `System readiness: ${report.status}`, + `Schema: ${report.schemaVersion}`, + `Observed: ${report.provenance.observedAt}`, + "Mutation performed: no", + ]; + + if (report.findings.length === 0) { + lines.push("Findings: none"); + } else { + lines.push("Findings:"); + for (const entry of report.findings) { + lines.push(`- [${entry.severity}] ${entry.id}: ${entry.summary}`); + } + } + + return lines.join("\n"); +} diff --git a/test/package-contract/cli/command-registry.test.ts b/test/package-contract/cli/command-registry.test.ts index 787e929ba27..a1f19adff2c 100644 --- a/test/package-contract/cli/command-registry.test.ts +++ b/test/package-contract/cli/command-registry.test.ts @@ -189,11 +189,12 @@ describe("command-registry", () => { }); describe("globalCommandTokens()", () => { - it("returns the exact set of 27 tokens matching the global dispatch commands", () => { + it("returns the exact set of 28 tokens matching the global dispatch commands", () => { const tokens = globalCommandTokens(); const expected = new Set([ "agents", "completion", + "host", "onboard", "update", "list",