diff --git a/src/lib/messaging/applier/plan-filter.ts b/src/lib/messaging/applier/plan-filter.ts index 93953963327..6bfdec9a422 100644 --- a/src/lib/messaging/applier/plan-filter.ts +++ b/src/lib/messaging/applier/plan-filter.ts @@ -1,31 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { - MessagingChannelId, - SandboxMessagingChannelPlan, - SandboxMessagingPlan, -} from "../manifest"; - -export function enabledPlanChannels(plan: SandboxMessagingPlan): SandboxMessagingChannelPlan[] { - const disabled = disabledPlanChannelIds(plan); - return plan.channels.filter( - (channel) => channel.active && !channel.disabled && !disabled.has(channel.channelId), - ); -} - -export function enabledPlanChannelIds(plan: SandboxMessagingPlan): Set { - return new Set(enabledPlanChannels(plan).map((channel) => channel.channelId)); -} - -export function filterEnabledPlanEntries( - plan: SandboxMessagingPlan, - entries: readonly T[], -): T[] { - const enabled = enabledPlanChannelIds(plan); - return entries.filter((entry) => enabled.has(entry.channelId)); -} - -function disabledPlanChannelIds(plan: SandboxMessagingPlan): Set { - return new Set(plan.disabledChannels); -} +export { + type EnabledPlanChannel, + type EnabledPlanSelection, + enabledPlanChannelIds, + enabledPlanChannels, + filterEnabledPlanEntries, + normalizeMessagingChannelId, +} from "../post-agent-install-selection"; diff --git a/src/lib/messaging/plan-validation.test.ts b/src/lib/messaging/plan-validation.test.ts index a0993887ad6..3879b920dea 100644 --- a/src/lib/messaging/plan-validation.test.ts +++ b/src/lib/messaging/plan-validation.test.ts @@ -237,6 +237,108 @@ describe("parseSandboxMessagingPlan", () => { makePlan({ channels: [makePlan().channels[0], makePlan().channels[0]] }), ), ).toBeNull(); + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [ + makePlan().channels[0], + { ...makePlan().channels[0], channelId: " TELEGRAM " }, + ], + }), + ), + ).toBeNull(); + }); + + it("rejects a lone noncanonical channel id even when related ids are canonical", () => { + const source = makePlan(); + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [{ ...source.channels[0], channelId: " Telegram " }], + disabledChannels: ["telegram"], + credentialBindings: [ + { + channelId: "telegram", + credentialId: "telegramBotToken", + sourceInput: "botToken", + providerName: "sb-telegram-bridge", + providerEnvKey: "TELEGRAM_BOT_TOKEN", + placeholder: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + credentialAvailable: true, + }, + ], + }), + ), + ).toBeNull(); + }); + + it.each([ + ["disabledChannels", { disabledChannels: [" Telegram "] }], + ["credentialBindings", { credentialBindings: [{ channelId: "Telegram" }] }], + [ + "networkPolicy.entries", + { networkPolicy: { presets: [], entries: [{ channelId: "Telegram" }] } }, + ], + ["agentRender", { agentRender: [{ channelId: "Telegram" }] }], + ["buildSteps", { buildSteps: [{ channelId: "Telegram" }] }], + ["stateUpdates", { stateUpdates: [{ channelId: "Telegram" }] }], + ["healthChecks", { healthChecks: [{ channelId: "Telegram" }] }], + [ + "runtimeSetup.nodePreloads", + { + runtimeSetup: { + nodePreloads: [{ channelId: "Telegram" }], + envAliases: [], + secretScans: [], + }, + }, + ], + [ + "runtimeSetup.envAliases", + { + runtimeSetup: { + nodePreloads: [], + envAliases: [{ channelId: "Telegram" }], + secretScans: [], + }, + }, + ], + [ + "runtimeSetup.secretScans", + { + runtimeSetup: { + nodePreloads: [], + envAliases: [], + secretScans: [{ channelId: "Telegram" }], + }, + }, + ], + ])("rejects noncanonical channel references in %s", (_field, overrides) => { + expect(parseSandboxMessagingPlan({ ...makePlan(), ...overrides })).toBeNull(); + }); + + it.each([ + ["input", { inputs: [{ inputId: "token", channelId: "Telegram" }] }], + ["hook", { hooks: [{ channelId: "Telegram" }] }], + [ + "host forward", + { + hostForward: { + channelId: "Telegram", + port: 3978, + label: "Telegram webhook", + }, + }, + ], + ])("rejects a noncanonical nested %s channel reference", (_field, channelOverrides) => { + const channel = makePlan().channels[0]; + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [{ ...channel, ...channelOverrides }] as SandboxMessagingPlan["channels"], + }), + ), + ).toBeNull(); }); it("rejects any persisted channel when supportedChannelIds: [] is passed (deny-all)", () => { diff --git a/src/lib/messaging/plan-validation.ts b/src/lib/messaging/plan-validation.ts index 6b59cf31f87..422d0a61ae3 100644 --- a/src/lib/messaging/plan-validation.ts +++ b/src/lib/messaging/plan-validation.ts @@ -13,6 +13,7 @@ import { type MaybeCompactMessagingPlan, normalizePersistedSandboxMessagingPlanShape, } from "./persistence"; +import { normalizeMessagingChannelId } from "./post-agent-install-selection"; export interface SandboxMessagingPlanParseOptions { sandboxName?: string | null; @@ -49,8 +50,17 @@ export function parseSandboxMessagingPlan( const supported = Array.isArray(options.supportedChannelIds) ? new Set(options.supportedChannelIds) : null; - for (const [index, channel] of value.channels.entries()) { + const normalizedChannelIds = new Set(); + for (const channel of value.channels) { if (!isObjectRecord(channel) || typeof channel.channelId !== "string") return null; + const normalizedChannelId = normalizeMessagingChannelId(channel.channelId); + if ( + !normalizedChannelId || + normalizedChannelId !== channel.channelId || + normalizedChannelIds.has(normalizedChannelId) + ) { + return null; + } if (Object.hasOwn(channel, "configured") && typeof channel.configured !== "boolean") { return null; } @@ -61,23 +71,47 @@ export function parseSandboxMessagingPlan( if (Object.hasOwn(channel, "hooks") && !Array.isArray(channel.hooks)) return null; if ( Array.isArray(channel.inputs) && - channel.inputs.some((input) => !isObjectRecord(input) || typeof input.inputId !== "string") + channel.inputs.some( + (input) => + !isObjectRecord(input) || + typeof input.inputId !== "string" || + (Object.hasOwn(input, "channelId") && input.channelId !== normalizedChannelId), + ) ) { return null; } - if (Array.isArray(channel.hooks) && channel.hooks.some((hook) => !isObjectRecord(hook))) { + if ( + Array.isArray(channel.hooks) && + channel.hooks.some( + (hook) => + !isObjectRecord(hook) || + (Object.hasOwn(hook, "channelId") && hook.channelId !== normalizedChannelId), + ) + ) { return null; } - if (supported && !supported.has(channel.channelId)) return null; if ( - value.channels.findIndex( - (candidate) => isObjectRecord(candidate) && candidate.channelId === channel.channelId, - ) !== index + Object.hasOwn(channel, "hostForward") && + isObjectRecord(channel.hostForward) && + channel.hostForward.channelId !== normalizedChannelId ) { return null; } + if (supported && !supported.has(channel.channelId)) return null; + normalizedChannelIds.add(normalizedChannelId); + } + if (!value.disabledChannels.every(isCanonicalMessagingChannelId)) return null; + if ( + !hasCanonicalChannelReferences(value.credentialBindings) || + !hasCanonicalChannelReferences(value.agentRender) || + !hasCanonicalChannelReferences(value.buildSteps) || + !hasCanonicalChannelReferences(value.stateUpdates) || + !hasCanonicalChannelReferences(value.healthChecks) || + !hasCanonicalNetworkPolicyReferences(value.networkPolicy) || + !hasCanonicalRuntimeSetupReferences(value.runtimeSetup) + ) { + return null; } - if (!value.disabledChannels.every((channelId) => typeof channelId === "string")) return null; return cloneSandboxMessagingPlan( normalizePersistedSandboxMessagingPlanShape(value as MaybeCompactMessagingPlan), @@ -192,3 +226,32 @@ function isRuntimeSetup(value: unknown): boolean { value.secretScans.every(isObjectRecord) ); } + +function isCanonicalMessagingChannelId(value: unknown): value is string { + return ( + typeof value === "string" && value.length > 0 && normalizeMessagingChannelId(value) === value + ); +} + +function hasCanonicalChannelReferences(value: unknown): boolean { + return ( + value === undefined || + (Array.isArray(value) && + value.every( + (entry) => isObjectRecord(entry) && isCanonicalMessagingChannelId(entry.channelId), + )) + ); +} + +function hasCanonicalNetworkPolicyReferences(value: unknown): boolean { + if (!isObjectRecord(value) || !Object.hasOwn(value, "entries")) return true; + return hasCanonicalChannelReferences(value.entries); +} + +function hasCanonicalRuntimeSetupReferences(value: unknown): boolean { + if (value === undefined) return true; + if (!isObjectRecord(value)) return false; + return ["nodePreloads", "envAliases", "secretScans"].every((field) => + hasCanonicalChannelReferences(value[field]), + ); +} diff --git a/src/lib/messaging/post-agent-install-selection.test.ts b/src/lib/messaging/post-agent-install-selection.test.ts new file mode 100644 index 00000000000..34e8c3b23f9 --- /dev/null +++ b/src/lib/messaging/post-agent-install-selection.test.ts @@ -0,0 +1,191 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; + +import { describe, expect, it } from "vitest"; +import { filterEnabledPlanEntries } from "./applier/plan-filter"; +import type { + SandboxMessagingAgentRenderPlan, + SandboxMessagingBuildStepPlan, + SandboxMessagingChannelPlan, + SandboxMessagingPlan, +} from "./manifest"; +import { + selectActiveMessagingChannelIds, + selectEnabledMessagingAgentRender, + selectEnabledPostAgentInstallBuildFiles, +} from "./post-agent-install-selection"; + +function channel( + channelId: string, + hooks: SandboxMessagingChannelPlan["hooks"] = [], +): SandboxMessagingChannelPlan { + return { + channelId, + displayName: channelId, + authMode: "none", + active: true, + selected: true, + configured: true, + disabled: false, + inputs: [], + hooks, + }; +} + +function plan(overrides: Partial = {}): SandboxMessagingPlan { + return { + schemaVersion: 1, + sandboxName: "selection-test", + agent: "openclaw", + workflow: "onboard", + channels: [], + disabledChannels: [], + credentialBindings: [], + networkPolicy: { presets: [], entries: [] }, + agentRender: [], + buildSteps: [], + stateUpdates: [], + healthChecks: [], + ...overrides, + }; +} + +function render(channelId: string): SandboxMessagingAgentRenderPlan { + return { + channelId, + kind: "json-fragment", + agent: "openclaw", + target: "/sandbox/.openclaw/openclaw.json", + path: "channels.telegram.enabled", + value: true, + templateRefs: [], + }; +} + +function buildFile( + channelId: string, + outputId: string, + hookId?: string, +): SandboxMessagingBuildStepPlan { + return { + channelId, + kind: "build-file", + hookId, + outputId, + required: true, + value: "fixture", + }; +} + +describe("post-agent-install messaging selection", () => { + it("loads through Node's direct TypeScript ESM path used by image builds", () => { + const moduleUrl = new URL("./post-agent-install-selection.ts", import.meta.url).href; + const result = spawnSync( + process.execPath, + [ + "--experimental-strip-types", + "--input-type=module", + "--eval", + `import(${JSON.stringify(moduleUrl)})`, + ], + { encoding: "utf8" }, + ); + + expect({ status: result.status, signal: result.signal }).toEqual({ status: 0, signal: null }); + }); + + it("uses the shared enabled-channel contract and preserves canonical ordering", () => { + const selection = plan({ + channels: [channel(" Discord "), channel(" TeLeGrAm "), channel("DISCORD")], + disabledChannels: [" telegram "], + }); + + expect(selectActiveMessagingChannelIds(selection)).toEqual(["discord"]); + expect( + filterEnabledPlanEntries(selection, [ + { channelId: "DISCORD", value: "kept" }, + { channelId: "telegram", value: "disabled" }, + ]), + ).toEqual([{ channelId: "DISCORD", value: "kept" }]); + }); + + it("matches normalized channel ids across channels, render entries, and build steps", () => { + const selection = plan({ + channels: [ + channel(" Telegram ", [ + { + channelId: " Telegram ", + id: "post-install", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + { + channelId: " Telegram ", + id: "render-only", + phase: "render", + handler: "telegram.render", + }, + ]), + ], + agentRender: [render("TELEGRAM"), render("discord")], + buildSteps: [ + buildFile("telegram", "post-install-file", "post-install"), + buildFile(" TELEGRAM ", "render-file", "render-only"), + buildFile("discord", "unrelated-file"), + ], + }); + + expect(selectEnabledMessagingAgentRender(selection).map(({ channelId }) => channelId)).toEqual([ + "TELEGRAM", + ]); + expect( + selectEnabledPostAgentInstallBuildFiles(selection).map(({ outputId }) => outputId), + ).toEqual(["post-install-file"]); + }); + + it("fails closed instead of selecting a hook phase from ambiguous normalized ids", () => { + const selection = plan({ + channels: [ + channel("telegram", [ + { + channelId: "telegram", + id: "shared-hook", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + ]), + channel(" TELEGRAM ", [ + { + channelId: " TELEGRAM ", + id: "shared-hook", + phase: "render", + handler: "telegram.render", + }, + ]), + ], + buildSteps: [buildFile("TELEGRAM", "ambiguous-file", "shared-hook")], + }); + + expect(selectEnabledPostAgentInstallBuildFiles(selection)).toEqual([]); + }); + + it("fails closed when a build step references a missing hook", () => { + const selection = plan({ + channels: [ + channel("telegram", [ + { + channelId: "telegram", + id: "post-install", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + ]), + ], + buildSteps: [buildFile("telegram", "stale-hook-file", "missing-hook")], + }); + + expect(selectEnabledPostAgentInstallBuildFiles(selection)).toEqual([]); + }); +}); diff --git a/src/lib/messaging/post-agent-install-selection.ts b/src/lib/messaging/post-agent-install-selection.ts index 63c9afb380c..8c88f212fc5 100644 --- a/src/lib/messaging/post-agent-install-selection.ts +++ b/src/lib/messaging/post-agent-install-selection.ts @@ -1,77 +1,112 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -interface SelectionHook { - readonly id: string; - readonly phase: string; +import type { + MessagingChannelId, + SandboxMessagingAgentRenderPlan, + SandboxMessagingBuildStepPlan, + SandboxMessagingChannelPlan, + SandboxMessagingHookReferencePlan, +} from "./manifest"; + +export type EnabledPlanChannel = Pick & + Partial>; + +export interface EnabledPlanSelection { + readonly channels: readonly Channel[]; + readonly disabledChannels?: readonly MessagingChannelId[]; +} + +export function normalizeMessagingChannelId(channelId: MessagingChannelId): MessagingChannelId { + return channelId.trim().toLowerCase(); +} + +export function enabledPlanChannels( + plan: EnabledPlanSelection, +): Channel[] { + const disabled = new Set( + (plan.disabledChannels ?? []).map(normalizeMessagingChannelId).filter(Boolean), + ); + return plan.channels.filter((channel) => { + const channelId = normalizeMessagingChannelId(channel.channelId); + return channelId.length > 0 && channel.active && !channel.disabled && !disabled.has(channelId); + }); } -interface SelectionChannel { - readonly channelId: string; - readonly active?: boolean; - readonly disabled?: boolean; - readonly hooks?: readonly SelectionHook[]; +export function enabledPlanChannelIds(plan: EnabledPlanSelection): Set { + return new Set( + enabledPlanChannels(plan).map((channel) => normalizeMessagingChannelId(channel.channelId)), + ); } -interface SelectionPlanBase { - readonly channels: readonly SelectionChannel[]; +export function filterEnabledPlanEntries( + plan: EnabledPlanSelection, + entries: readonly T[], +): T[] { + const enabled = enabledPlanChannelIds(plan); + return entries.filter((entry) => enabled.has(normalizeMessagingChannelId(entry.channelId))); } +type SelectionChannel = EnabledPlanChannel & { + readonly hooks?: readonly (Pick & { + readonly phase: string; + })[]; +}; + +type SelectionRender = Pick; + +type SelectionBuildStep = Pick; + /** * Canonical active-channel selection for the image applier. Each selection * consumer must resolve the same active channels and mutable outputs. */ -export function selectActiveMessagingChannelIds(plan: SelectionPlanBase): string[] { +export function selectActiveMessagingChannelIds( + plan: EnabledPlanSelection, +): MessagingChannelId[] { const seen = new Set(); const channels: string[] = []; - for (const item of plan.channels) { - const channel = String(item.channelId || "") - .trim() - .toLowerCase(); + for (const item of enabledPlanChannels(plan)) { + const channel = normalizeMessagingChannelId(item.channelId); if (!channel || seen.has(channel)) continue; - if (item.active === true && item.disabled !== true) { - seen.add(channel); - channels.push(channel); - } + seen.add(channel); + channels.push(channel); } return channels; } -export function selectEnabledMessagingAgentRender< - Render extends { - readonly agent: string; - readonly channelId: string; - }, ->( - plan: SelectionPlanBase & { +export function selectEnabledMessagingAgentRender( + plan: EnabledPlanSelection & { readonly agent: string; readonly agentRender: readonly Render[]; }, ): Render[] { const active = new Set(selectActiveMessagingChannelIds(plan)); return plan.agentRender.filter( - (render) => render.agent === plan.agent && active.has(render.channelId), + (render) => + render.agent === plan.agent && active.has(normalizeMessagingChannelId(render.channelId)), ); } export function selectEnabledPostAgentInstallBuildFiles< - Step extends { - readonly channelId: string; - readonly kind: string; - readonly hookId?: string; - }, + Channel extends SelectionChannel, + Step extends SelectionBuildStep, >( - plan: SelectionPlanBase & { + plan: EnabledPlanSelection & { readonly buildSteps: readonly Step[]; }, -): Step[] { +): Array { const active = new Set(selectActiveMessagingChannelIds(plan)); - return plan.buildSteps.filter((step) => { - if (!active.has(step.channelId) || step.kind !== "build-file") return false; + const channels = enabledPlanChannels(plan); + return plan.buildSteps.filter((step): step is Step & { readonly kind: "build-file" } => { + const channelId = normalizeMessagingChannelId(step.channelId); + if (!active.has(channelId) || step.kind !== "build-file") return false; if (!step.hookId) return true; - const hookPhase = plan.channels - .find((channel) => channel.channelId === step.channelId) - ?.hooks?.find((hook) => hook.id === step.hookId)?.phase; - return hookPhase === undefined || hookPhase === "post-agent-install"; + const matchingChannels = channels.filter( + (channel) => normalizeMessagingChannelId(channel.channelId) === channelId, + ); + if (matchingChannels.length !== 1) return false; + const matchedHook = matchingChannels[0]?.hooks?.find((hook) => hook.id === step.hookId); + return matchedHook !== undefined && matchedHook.phase === "post-agent-install"; }); } diff --git a/src/lib/onboard/managed-startup/image-runtime.ts b/src/lib/onboard/managed-startup/image-runtime.ts index 2aac60603b5..f8e5c7f4edd 100644 --- a/src/lib/onboard/managed-startup/image-runtime.ts +++ b/src/lib/onboard/managed-startup/image-runtime.ts @@ -1631,7 +1631,7 @@ export async function main(argv: readonly string[] = process.argv.slice(2)): Pro ); } -if (require.main === module) { +if (typeof require !== "undefined" && typeof module !== "undefined" && require.main === module) { main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/test/e2e/docs/README.md b/test/e2e/docs/README.md index a6388b30fb1..b889fbba258 100644 --- a/test/e2e/docs/README.md +++ b/test/e2e/docs/README.md @@ -67,6 +67,48 @@ harness or runner. Vitest remains the only test harness. `suiteIds` remain metadata for reporting and migration planning. They do not dispatch shell validation suites. +## Cross-Runtime Foundation + +The registry contains an inert foundation for describing the same behavior on +more than one execution provider: + +- `scenario.ts` owns provider-neutral desired state and explicit support + obligations, an ordered semantic user journey, and normalized assertions. +- `execution-profile.ts` describes provider, host platform and architecture, + root mode, acceleration, capabilities, and bounded runner capacity. Provider + IDs are open; adding one does not require editing a central union. +- `runtime-matrix.ts` binds every scenario obligation to a registered callable + fixture adapter, rejects incompatible capabilities, keeps full-profile + preparation batches atomic, schedules those batches within a host-wide shard + ceiling, and derives isolated resource identities. +- `fixtures/runtime-provider.ts` is the provider-command boundary for + readiness, exact workload identity, obligation execution, lifecycle evidence, + and cleanup. Its fixture-only executor exercises compiled cases without + crossing the legacy Docker phase-fixture path. +- `parity-evidence.ts` compares normalized lifecycle traces, desired-state + fingerprints, terminal outcomes, and user-visible projections. It retains + exact head/base, engine, architecture, workload, managed-image, capability, + and opaque provider receipt evidence without comparing provider internals. + +Compile one registry-wide `RuntimeMatrixDefinition`, then attach only a +`scenarioId`/`profileId` reference with `TargetBuilder.runtimeCase(...)` in fast +compiler tests today. The existing target compiler resolves the reference but +does not dispatch its adapter IDs. Support tests execute the same compiled case +through Docker-shaped and fake-MXC providers; no canonical target, workflow +selector, live scenario, or production runtime registration consumes this +metadata yet. The shared fixture context exposes optional `executionProfile` +and `runtimeProvider` injection points, both defaulting to `undefined`. Existing +legacy Docker command fixtures, their ordering, and their output contracts are +unchanged. +Execution evidence must be published with +`ArtifactSink.writeExecutionEvidence(...)` so normal artifact redaction still +applies. + +When extending the foundation, keep product intent in the scenario, runtime +mechanics in obligation bindings, and support facts in capabilities. A binding +must cover every obligation explicitly; a missing adapter or capability is a +compile error rather than a skip. + ## How To Run ```bash diff --git a/test/e2e/fixtures/artifacts.ts b/test/e2e/fixtures/artifacts.ts index 833f4f823d3..f8c2735d637 100644 --- a/test/e2e/fixtures/artifacts.ts +++ b/test/e2e/fixtures/artifacts.ts @@ -5,6 +5,7 @@ import fsSync from "node:fs"; import fs from "node:fs/promises"; import path from "node:path"; +import type { ExecutionEvidence } from "../registry/parity-evidence.ts"; import { redactString } from "./redaction.ts"; export type TargetContract = string | readonly string[]; @@ -138,6 +139,18 @@ export class ArtifactSink { async writeJson(relativePath: string, value: unknown): Promise { return this.writeText(relativePath, `${JSON.stringify(value, null, 2)}\n`); } + + async writeExecutionEvidence(resultId: string, evidence: ExecutionEvidence): Promise { + if (!/^[a-z0-9][a-z0-9-]{0,127}$/u.test(resultId)) { + throw new Error(`execution result id is not artifact-safe: ${resultId}`); + } + if (resultId !== evidence.resultId) { + throw new Error( + `execution result id '${resultId}' does not match evidence result '${evidence.resultId}'`, + ); + } + return this.writeJson(path.join("execution", `${resultId}.json`), evidence); + } } export function slugifyArtifactName(name: string): string { diff --git a/test/e2e/fixtures/e2e-test.ts b/test/e2e/fixtures/e2e-test.ts index b036689d3da..550c1c0fbab 100644 --- a/test/e2e/fixtures/e2e-test.ts +++ b/test/e2e/fixtures/e2e-test.ts @@ -11,6 +11,7 @@ import { collectResourceSnapshot, } from "../../../tools/e2e/runner-pressure.mts"; import { renderSnapshotLine } from "../../../tools/e2e/runner-pressure-core.mts"; +import type { ExecutionProfile } from "../registry/execution-profile.ts"; import { type ArtifactSink, createArtifactSink } from "./artifacts.ts"; import { assertCleanupPassed, CleanupRegistry } from "./cleanup.ts"; @@ -37,6 +38,7 @@ import { type TestProgress, type TestProgressOptions, } from "./progress.ts"; +import type { RuntimeProviderFixture } from "./runtime-provider.ts"; import { SecretStore } from "./secrets.ts"; import { ShellProbe } from "./shell-probe.ts"; @@ -63,6 +65,9 @@ export interface E2ETargetFixtures { lifecycle: LifecyclePhaseFixture; runtime: RuntimePhaseFixture; stateValidation: StateValidationPhaseFixture; + /** Inert injection points for a future compiled cross-runtime target. */ + executionProfile: ExecutionProfile | undefined; + runtimeProvider: RuntimeProviderFixture | undefined; progress: TestProgress; } @@ -292,6 +297,12 @@ export const test = base.extend({ stateValidation: async ({ artifacts, host, gateway, sandbox }, use) => { await use(new StateValidationPhaseFixture(host, gateway, sandbox, {}, artifacts)); }, + executionProfile: async ({}, use) => { + await use(undefined); + }, + runtimeProvider: async ({}, use) => { + await use(undefined); + }, }); export { expect }; diff --git a/test/e2e/fixtures/runtime-provider.ts b/test/e2e/fixtures/runtime-provider.ts new file mode 100644 index 00000000000..98827c329ed --- /dev/null +++ b/test/e2e/fixtures/runtime-provider.ts @@ -0,0 +1,172 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { ExecutionCapability, ExecutionProfile } from "../registry/execution-profile.ts"; +import { + buildExecutionEvidence, + type ExecutionEvidence, + type ManagedImageEvidence, + type NonEmptyProviderReceipts, +} from "../registry/parity-evidence.ts"; +import { + executionPreparationKey, + type ResolvedRuntimeCase, + type RuntimeAdapterRequest, + type RuntimeAdapterRuntime, +} from "../registry/runtime-matrix.ts"; +import type { FsmTransition, JsonValue, TerminalOutcome } from "../registry/scenario.ts"; + +export interface RuntimeReadinessEvidence { + profileId: string; + ready: true; + engineName: string; + engineVersion: string; + capabilities: readonly ExecutionCapability[]; +} + +export interface ExactWorkloadIdentity { + logicalId: string; + providerResourceId: string; + managedImages: readonly ManagedImageEvidence[]; +} + +export interface RuntimeLifecycleRequest { + caseId: string; + workload: ExactWorkloadIdentity; +} + +export interface RuntimeLifecycleEvidence { + desiredState: JsonValue; + fsmTrace: readonly FsmTransition[]; + terminalOutcome: TerminalOutcome; + userVisibleState: JsonValue; + providerReceipts: NonEmptyProviderReceipts; +} + +/** + * Provider commands stop at this seam. Scenario, matrix, and parity code use + * only normalized evidence and exact workload identities. + */ +export interface RuntimeProviderEnvironment { + prepare(): Promise; +} + +export interface RuntimeProviderLifecycle { + executeAdapter(adapterId: string, request: RuntimeAdapterRequest): Promise; + cleanup(identity: ExactWorkloadIdentity): Promise; +} + +export interface RuntimeProviderState { + inspectWorkload(request: { logicalId: string }): Promise; + observe(request: RuntimeLifecycleRequest): Promise; +} + +export interface RuntimeProviderFixture extends RuntimeAdapterRuntime { + readonly profile: ExecutionProfile; + readonly environment: RuntimeProviderEnvironment; + readonly lifecycle: RuntimeProviderLifecycle; + readonly state: RuntimeProviderState; +} + +export interface RuntimeExecutionRequest { + resolved: ResolvedRuntimeCase; + provider: RuntimeProviderFixture; + source: { + headSha: string; + baseSha: string; + }; +} + +async function cleanupAfterExecutionFailure( + provider: RuntimeProviderFixture, + workload: ExactWorkloadIdentity, + executionError: unknown, +): Promise { + try { + await provider.lifecycle.cleanup(workload); + } catch (cleanupError) { + throw new AggregateError( + [executionError, cleanupError], + "Runtime case execution failed and provider cleanup also failed", + { cause: executionError }, + ); + } + throw executionError; +} + +/** + * The only executable cross-runtime path in this foundation. It does not use + * the legacy Docker-shaped environment/lifecycle/state fixtures and is not + * selected by any canonical target or workflow. + */ +export async function executeRuntimeCaseThroughProvider( + request: RuntimeExecutionRequest, +): Promise { + const { case: runtimeCase } = request.resolved; + const provider = request.provider; + if ( + provider.profile.id !== runtimeCase.profile.id || + executionPreparationKey(provider.profile) !== runtimeCase.preparationKey + ) { + throw new Error( + `Runtime provider profile '${provider.profile.id}' does not match case '${runtimeCase.id}'`, + ); + } + const readiness = await provider.environment.prepare(); + if (readiness.profileId !== runtimeCase.profile.id) { + throw new Error( + `Runtime readiness profile '${readiness.profileId}' does not match '${runtimeCase.profile.id}'`, + ); + } + const missingCapabilities = runtimeCase.profile.capabilities.filter( + (capability) => !readiness.capabilities.includes(capability), + ); + if (missingCapabilities.length > 0) { + throw new Error( + `Runtime readiness for '${runtimeCase.profile.id}' is missing capabilities: ${missingCapabilities.join(", ")}`, + ); + } + + const workload = await provider.state.inspectWorkload({ + logicalId: runtimeCase.identities.sandbox, + }); + let lifecycle: RuntimeLifecycleEvidence; + try { + if (workload.logicalId !== runtimeCase.identities.sandbox) { + throw new Error( + `workload.logicalId '${workload.logicalId}' does not match case sandbox identity '${runtimeCase.identities.sandbox}'`, + ); + } + for (const binding of runtimeCase.obligationBindings) { + await binding.adapter.execute(provider, { + caseId: runtimeCase.id, + obligationId: binding.obligationId, + workloadId: workload.logicalId, + }); + } + lifecycle = await provider.state.observe({ + caseId: runtimeCase.id, + workload, + }); + } catch (executionError) { + return cleanupAfterExecutionFailure(provider, workload, executionError); + } + const cleanupReceipts = await provider.lifecycle.cleanup(workload); + + return buildExecutionEvidence({ + resolved: request.resolved, + source: request.source, + engine: { + name: readiness.engineName, + version: readiness.engineVersion, + }, + workload, + observed: { + desiredState: lifecycle.desiredState, + fsmTrace: lifecycle.fsmTrace, + terminalOutcome: lifecycle.terminalOutcome, + userVisibleState: lifecycle.userVisibleState, + }, + providerReceipts: [...lifecycle.providerReceipts, ...cleanupReceipts], + }); +} diff --git a/test/e2e/live/run-plan.ts b/test/e2e/live/run-plan.ts index 21e1af9c9ef..a56f58c4ce9 100644 --- a/test/e2e/live/run-plan.ts +++ b/test/e2e/live/run-plan.ts @@ -1,8 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { cloudExperimentalChecksForOnboarding } from "./cloud-experimental-check-list.ts"; +import { + type CompiledRuntimeMatrix, + type ResolvedRuntimeCase, + resolveRuntimeCase, +} from "../registry/runtime-matrix.ts"; import type { TargetDefinition } from "../registry/types.ts"; +import { cloudExperimentalChecksForOnboarding } from "./cloud-experimental-check-list.ts"; export interface LiveTargetRunPlan { targetId: string; @@ -10,10 +15,14 @@ export interface LiveTargetRunPlan { expectedStateId: string | undefined; suiteIds: string[]; phases: string[]; + runtimeCase?: ResolvedRuntimeCase; e2eCloudExperimentalChecks?: string[]; } -export function buildLiveTargetRunPlan(target: TargetDefinition): LiveTargetRunPlan { +export function buildLiveTargetRunPlan( + target: TargetDefinition, + runtimeMatrix?: CompiledRuntimeMatrix, +): LiveTargetRunPlan { const plan: LiveTargetRunPlan = { targetId: target.id, manifestPath: target.manifestPath ?? null, @@ -32,5 +41,13 @@ export function buildLiveTargetRunPlan(target: TargetDefinition): LiveTargetRunP if (cloudExperimentalChecks.length > 0) { plan.e2eCloudExperimentalChecks = [...cloudExperimentalChecks]; } + if (target.runtimeCase) { + if (!runtimeMatrix) { + throw new Error( + `Target '${target.id}' references a runtime case without a compiled runtime matrix`, + ); + } + plan.runtimeCase = resolveRuntimeCase(runtimeMatrix, target.runtimeCase); + } return plan; } diff --git a/test/e2e/registry/builder.ts b/test/e2e/registry/builder.ts index d884f301277..402fb7b7c46 100644 --- a/test/e2e/registry/builder.ts +++ b/test/e2e/registry/builder.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { RuntimeCaseReference } from "./runtime-matrix.ts"; import type { AssertionGroup, TargetDefinition, TargetEnvironment } from "./types.ts"; export class TargetBuilder { @@ -25,6 +26,11 @@ export class TargetBuilder { return this; } + runtimeCase(runtimeCase: RuntimeCaseReference): TargetBuilder { + this.definition.runtimeCase = runtimeCase; + return this; + } + expectedState(expectedStateId: string): TargetBuilder { this.definition.expectedStateId = expectedStateId; return this; @@ -68,6 +74,7 @@ export class TargetBuilder { build(): TargetDefinition { return { ...this.definition, + ...(this.definition.runtimeCase ? { runtimeCase: { ...this.definition.runtimeCase } } : {}), assertionGroups: [...this.definition.assertionGroups], suiteIds: [...(this.definition.suiteIds ?? [])], onboardingAssertionIds: [...(this.definition.onboardingAssertionIds ?? [])], diff --git a/test/e2e/registry/execution-profile.ts b/test/e2e/registry/execution-profile.ts new file mode 100644 index 00000000000..1601cb38a12 --- /dev/null +++ b/test/e2e/registry/execution-profile.ts @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const EXECUTION_FOUNDATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/u; +export const MAX_HOST_SHARDS = 32; + +declare const executionProviderIdBrand: unique symbol; + +/** + * Open provider identity. A provider becomes executable only when its adapter + * is present in a RuntimeAdapterCatalog; naming one here is not registration or + * a support claim. + */ +export type ExecutionProviderId = string & { + readonly [executionProviderIdBrand]: true; +}; +export type ExecutionPlatform = "linux" | "macos" | "windows"; +export type ExecutionArchitecture = "amd64" | "arm64"; +export type ExecutionRootMode = "rootful" | "rootless"; +export type ExecutionAcceleration = "cpu" | "nvidia-gpu"; + +export type ExecutionCapability = + | "agent.configure" + | "agent.turn" + | "evidence.collect" + | "sandbox.lifecycle" + | "state.observe" + | "transport.docker-socket" + | "transport.socket-free"; + +export interface ExecutionRunner { + /** Stable physical or virtual host identity used to bound shard lanes. */ + hostId: string; + /** Runner label for future consumers. This foundation does not select it. */ + label: string; + /** Maximum serial shard lanes that may be assigned on this host. */ + maxShards: number; +} + +export interface ExecutionProfile { + id: string; + provider: ExecutionProviderId; + platform: ExecutionPlatform; + architecture: ExecutionArchitecture; + rootMode: ExecutionRootMode; + acceleration: ExecutionAcceleration; + capabilities: readonly ExecutionCapability[]; + runner: Readonly; +} + +const PLATFORMS = new Set(["linux", "macos", "windows"]); +const ARCHITECTURES = new Set(["amd64", "arm64"]); +const ROOT_MODES = new Set(["rootful", "rootless"]); +const ACCELERATIONS = new Set(["cpu", "nvidia-gpu"]); +const CAPABILITIES = new Set([ + "agent.configure", + "agent.turn", + "evidence.collect", + "sandbox.lifecycle", + "state.observe", + "transport.docker-socket", + "transport.socket-free", +]); + +export function assertExecutionFoundationId(value: string, label: string): void { + if (!EXECUTION_FOUNDATION_ID_PATTERN.test(value)) { + throw new Error( + `${label} '${value}' must start with a lowercase letter and contain only lowercase letters, digits, dots, or hyphens`, + ); + } +} + +export function executionProviderId(value: string): ExecutionProviderId { + assertExecutionFoundationId(value, "Execution provider id"); + return value as ExecutionProviderId; +} + +function assertEnumValue(values: ReadonlySet, value: T, label: string): void { + if (!values.has(value)) { + throw new Error(`${label} '${value}' is not recognized`); + } +} + +export function defineExecutionProfile(input: ExecutionProfile): ExecutionProfile { + assertExecutionFoundationId(input.id, "Execution profile id"); + const provider = executionProviderId(input.provider); + assertEnumValue(PLATFORMS, input.platform, "Execution platform"); + assertEnumValue(ARCHITECTURES, input.architecture, "Execution architecture"); + assertEnumValue(ROOT_MODES, input.rootMode, "Execution root mode"); + assertEnumValue(ACCELERATIONS, input.acceleration, "Execution acceleration"); + + if (input.capabilities.length === 0) { + throw new Error(`Execution profile '${input.id}' must declare capabilities`); + } + const capabilities = [...input.capabilities]; + for (const capability of capabilities) { + assertEnumValue(CAPABILITIES, capability, "Execution capability"); + } + if (new Set(capabilities).size !== capabilities.length) { + throw new Error(`Execution profile '${input.id}' declares duplicate capabilities`); + } + + assertExecutionFoundationId(input.runner.hostId, "Execution runner host id"); + const runnerLabel = input.runner.label.trim(); + if (!runnerLabel || /[\r\n]/u.test(runnerLabel)) { + throw new Error(`Execution profile '${input.id}' must declare a single-line runner label`); + } + if ( + !Number.isSafeInteger(input.runner.maxShards) || + input.runner.maxShards < 1 || + input.runner.maxShards > MAX_HOST_SHARDS + ) { + throw new Error( + `Execution profile '${input.id}' runner maxShards must be between 1 and ${MAX_HOST_SHARDS}`, + ); + } + + return Object.freeze({ + ...input, + provider, + capabilities: Object.freeze([...capabilities].sort()), + runner: Object.freeze({ ...input.runner, label: runnerLabel }), + }); +} diff --git a/test/e2e/registry/parity-evidence.ts b/test/e2e/registry/parity-evidence.ts new file mode 100644 index 00000000000..eb222d643b6 --- /dev/null +++ b/test/e2e/registry/parity-evidence.ts @@ -0,0 +1,312 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; + +import { + defineExecutionProfile, + type ExecutionAcceleration, + type ExecutionArchitecture, + type ExecutionCapability, + type ExecutionPlatform, + type ExecutionProviderId, + type ExecutionRootMode, +} from "./execution-profile.ts"; +import { assertResolvedRuntimeCase, type ResolvedRuntimeCase } from "./runtime-matrix.ts"; +import { + assertTerminalMatchesTrace, + compareCodeUnits, + type FsmTransition, + freezeJsonValue, + type JsonValue, + normalizeFsmTrace, + normalizeJsonValue, + normalizeTerminalOutcome, + type TerminalOutcome, +} from "./scenario.ts"; + +export interface ManagedImageEvidence { + role: string; + digest: string; +} + +export interface ProviderReceipt { + kind: string; + operationId: string; + /** Provider-defined diagnostic payload; parity comparison never interprets it. */ + value: JsonValue; +} + +export type NonEmptyProviderReceipts = readonly [ProviderReceipt, ...ProviderReceipt[]]; + +type NormalizedProviderReceipts = readonly [ + Readonly, + ...Readonly[], +]; + +export interface NormalizedParityEvidence { + desiredStateFingerprint: string; + fsmTrace: readonly Readonly[]; + terminalOutcome: Readonly; + userVisibleState: JsonValue; +} + +export interface ExecutionEvidence { + schemaVersion: 1; + caseId: string; + resultId: string; + shardId: string; + scenarioId: string; + profileId: string; + source: Readonly<{ + headSha: string; + baseSha: string; + }>; + runtime: Readonly<{ + provider: ExecutionProviderId; + engineName: string; + engineVersion: string; + platform: ExecutionPlatform; + architecture: ExecutionArchitecture; + rootMode: ExecutionRootMode; + acceleration: ExecutionAcceleration; + capabilities: readonly ExecutionCapability[]; + }>; + workload: Readonly<{ + logicalId: string; + providerResourceId: string; + managedImages: readonly Readonly[]; + }>; + parity: Readonly; + providerReceipts: NormalizedProviderReceipts; +} + +export interface ExecutionEvidenceInput { + resolved: ResolvedRuntimeCase; + source: { + headSha: string; + baseSha: string; + }; + engine: { + name: string; + version: string; + }; + workload: { + logicalId: string; + providerResourceId: string; + managedImages: readonly ManagedImageEvidence[]; + }; + observed: { + desiredState: JsonValue; + fsmTrace: readonly FsmTransition[]; + terminalOutcome: TerminalOutcome; + userVisibleState: JsonValue; + }; + providerReceipts: NonEmptyProviderReceipts; +} + +export interface ParityMismatch { + field: + | "scenarioId" + | "desiredStateFingerprint" + | "fsmTrace" + | "terminalOutcome" + | "userVisibleState"; + expected: unknown; + actual: unknown; +} + +const SHA_PATTERN = /^[a-f0-9]{40}$/u; +const IMAGE_DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/u; +const RECEIPT_ID_PATTERN = /^[a-z][a-z0-9]*(?:[./_-][a-z0-9]+)*$/u; + +function normalizeSingleLine(value: string, fieldPath: string): string { + const normalized = value.trim(); + if (!normalized || /[\r\n]/u.test(normalized)) { + throw new Error(`${fieldPath} must be a non-empty single-line string`); + } + return normalized; +} + +function stableJson(value: JsonValue): string { + return JSON.stringify(normalizeJsonValue(value)); +} + +export function fingerprintDesiredState(desiredState: JsonValue): string { + return createHash("sha256").update(stableJson(desiredState)).digest("hex"); +} + +function normalizeSha(value: string, fieldPath: string): string { + const normalized = value.toLowerCase(); + if (!SHA_PATTERN.test(normalized)) { + throw new Error(`${fieldPath} must be a 40-character commit SHA`); + } + return normalized; +} + +function normalizeManagedImages( + images: readonly ManagedImageEvidence[], +): readonly Readonly[] { + if (images.length === 0) { + throw new Error("workload.managedImages must contain at least one exact image digest"); + } + const roles = new Set(); + return Object.freeze( + images + .map((image) => { + const role = normalizeSingleLine(image.role, "workload.managedImages.role"); + if (roles.has(role)) { + throw new Error(`workload.managedImages repeats role '${role}'`); + } + roles.add(role); + const digest = image.digest.toLowerCase(); + if (!IMAGE_DIGEST_PATTERN.test(digest)) { + throw new Error(`workload.managedImages '${role}' must use an exact sha256 digest`); + } + return Object.freeze({ role, digest }); + }) + .sort((left, right) => compareCodeUnits(left.role, right.role)), + ); +} + +function normalizeProviderReceipts(receipts: NonEmptyProviderReceipts): NormalizedProviderReceipts { + if (receipts.length === 0) { + throw new Error("providerReceipts must contain at least one provider receipt"); + } + const operationIds = new Set(); + const normalizeReceipt = (receipt: ProviderReceipt): Readonly => { + if (typeof receipt.kind !== "string") { + throw new Error("provider receipt kind must be a string"); + } + if (typeof receipt.operationId !== "string") { + throw new Error("provider receipt operationId must be a string"); + } + if (!RECEIPT_ID_PATTERN.test(receipt.kind)) { + throw new Error(`provider receipt kind '${receipt.kind}' is invalid`); + } + if (!RECEIPT_ID_PATTERN.test(receipt.operationId)) { + throw new Error(`provider receipt operationId '${receipt.operationId}' is invalid`); + } + if (operationIds.has(receipt.operationId)) { + throw new Error(`provider receipt operationId '${receipt.operationId}' is duplicated`); + } + operationIds.add(receipt.operationId); + return Object.freeze({ + kind: receipt.kind, + operationId: receipt.operationId, + value: freezeJsonValue( + normalizeJsonValue(receipt.value, `providerReceipts.${receipt.operationId}.value`), + ), + }); + }; + return Object.freeze([normalizeReceipt(receipts[0]), ...receipts.slice(1).map(normalizeReceipt)]); +} + +export function buildExecutionEvidence(input: ExecutionEvidenceInput): ExecutionEvidence { + assertResolvedRuntimeCase(input.resolved); + const { case: runtimeCase, shard } = input.resolved; + const profile = defineExecutionProfile(runtimeCase.profile); + const logicalId = normalizeSingleLine(input.workload.logicalId, "workload.logicalId"); + if (logicalId !== runtimeCase.identities.sandbox) { + throw new Error( + `workload.logicalId '${logicalId}' does not match case sandbox identity '${runtimeCase.identities.sandbox}'`, + ); + } + const providerResourceId = normalizeSingleLine( + input.workload.providerResourceId, + "workload.providerResourceId", + ); + const fsmTrace = normalizeFsmTrace(input.observed.fsmTrace); + const terminalOutcome = normalizeTerminalOutcome(input.observed.terminalOutcome); + assertTerminalMatchesTrace(fsmTrace, terminalOutcome, "observed.terminalOutcome"); + const desiredState = normalizeJsonValue(input.observed.desiredState, "observed.desiredState"); + const userVisibleState = normalizeJsonValue( + input.observed.userVisibleState, + "observed.userVisibleState", + ); + const assertions = runtimeCase.scenario.assertions; + const observedContract = { + desiredState, + fsmTrace, + terminalOutcome, + userVisibleState, + }; + for (const field of Object.keys(observedContract) as Array) { + if (!sameJson(observedContract[field], assertions[field])) { + throw new Error( + `Runtime case '${runtimeCase.id}' observed ${field} does not satisfy its scenario assertion`, + ); + } + } + + return Object.freeze({ + schemaVersion: 1, + caseId: runtimeCase.id, + resultId: runtimeCase.identities.result, + shardId: shard.id, + scenarioId: runtimeCase.scenario.id, + profileId: profile.id, + source: Object.freeze({ + headSha: normalizeSha(input.source.headSha, "source.headSha"), + baseSha: normalizeSha(input.source.baseSha, "source.baseSha"), + }), + runtime: Object.freeze({ + provider: profile.provider, + engineName: normalizeSingleLine(input.engine.name, "engine.name"), + engineVersion: normalizeSingleLine(input.engine.version, "engine.version"), + platform: profile.platform, + architecture: profile.architecture, + rootMode: profile.rootMode, + acceleration: profile.acceleration, + capabilities: profile.capabilities, + }), + workload: Object.freeze({ + logicalId, + providerResourceId, + managedImages: normalizeManagedImages(input.workload.managedImages), + }), + parity: Object.freeze({ + desiredStateFingerprint: fingerprintDesiredState(desiredState), + fsmTrace, + terminalOutcome, + userVisibleState: freezeJsonValue(userVisibleState), + }), + providerReceipts: normalizeProviderReceipts(input.providerReceipts), + }); +} + +function sameJson(left: unknown, right: unknown): boolean { + return JSON.stringify(left) === JSON.stringify(right); +} + +export function compareParityEvidence( + expected: ExecutionEvidence, + actual: ExecutionEvidence, +): ParityMismatch[] { + const comparable = { + scenarioId: [expected.scenarioId, actual.scenarioId], + desiredStateFingerprint: [ + expected.parity.desiredStateFingerprint, + actual.parity.desiredStateFingerprint, + ], + fsmTrace: [expected.parity.fsmTrace, actual.parity.fsmTrace], + terminalOutcome: [expected.parity.terminalOutcome, actual.parity.terminalOutcome], + userVisibleState: [expected.parity.userVisibleState, actual.parity.userVisibleState], + } satisfies Record; + + return (Object.keys(comparable) as ParityMismatch["field"][]).flatMap((field) => { + const [expectedValue, actualValue] = comparable[field]; + return sameJson(expectedValue, actualValue) + ? [] + : [{ field, expected: expectedValue, actual: actualValue }]; + }); +} + +export function assertParityEvidence(expected: ExecutionEvidence, actual: ExecutionEvidence): void { + const mismatches = compareParityEvidence(expected, actual); + if (mismatches.length > 0) { + throw new Error( + `Runtime parity mismatch in: ${mismatches.map((mismatch) => mismatch.field).join(", ")}`, + ); + } +} diff --git a/test/e2e/registry/registry.ts b/test/e2e/registry/registry.ts index 4fbfa9e939b..3ae6c43b9ea 100644 --- a/test/e2e/registry/registry.ts +++ b/test/e2e/registry/registry.ts @@ -43,6 +43,10 @@ export function listTargets(): TargetDefinition[] { return [...registry.targets].sort((a, b) => a.id.localeCompare(b.id)); } +export function hasRegisteredRuntimeProfile(profileId: string): boolean { + return registry.targets.some((target) => target.runtimeCase?.profileId === profileId); +} + export function getTarget(id: string): TargetDefinition | undefined { return registry.byId.get(id); } diff --git a/test/e2e/registry/runtime-matrix.ts b/test/e2e/registry/runtime-matrix.ts new file mode 100644 index 00000000000..36ea682444c --- /dev/null +++ b/test/e2e/registry/runtime-matrix.ts @@ -0,0 +1,474 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; + +import { + assertExecutionFoundationId, + defineExecutionProfile, + type ExecutionProfile, + type ExecutionProviderId, + executionProviderId, +} from "./execution-profile.ts"; +import { + compareCodeUnits, + defineRuntimeScenario, + type RuntimeNeutralScenario, + type ScenarioSupportObligation, +} from "./scenario.ts"; + +export interface ObligationBinding { + obligationId: string; + /** Registry-local executable adapter identity. */ + adapterId: string; +} + +export interface RuntimeBindingSpec { + scenarioId: string; + profileId: string; + obligationBindings: readonly ObligationBinding[]; +} + +export interface RuntimeAdapterRequest { + caseId: string; + obligationId: string; + workloadId: string; +} + +export interface RuntimeAdapterRuntime { + readonly profile: ExecutionProfile; + readonly lifecycle: { + executeAdapter(adapterId: string, request: RuntimeAdapterRequest): Promise; + }; +} + +export interface RuntimeAdapterRegistration { + id: string; + provider: ExecutionProviderId; + scenarioId: string; + obligationId: string; + execute(runtime: RuntimeAdapterRuntime, request: RuntimeAdapterRequest): Promise; +} + +export interface RuntimeCaseReference { + scenarioId: string; + profileId: string; +} + +export interface RuntimeMatrixDefinition { + scenarios: readonly RuntimeNeutralScenario[]; + profiles: readonly ExecutionProfile[]; + adapterCatalog: readonly RuntimeAdapterRegistration[]; + bindings: readonly RuntimeBindingSpec[]; +} + +export interface RuntimeResourceIdentities { + sandbox: string; + artifact: string; + cleanup: string; + result: string; +} + +export interface RuntimeMatrixCase { + id: string; + preparationKey: string; + scenario: RuntimeNeutralScenario; + profile: ExecutionProfile; + obligationBindings: readonly Readonly[]; + identities: Readonly; +} + +export interface CompiledObligationBinding extends ObligationBinding { + adapter: Readonly; +} + +export interface RuntimePreparationBatch { + preparationKey: string; + profile: ExecutionProfile; + cases: readonly RuntimeMatrixCase[]; +} + +export interface RuntimeHostShard { + id: string; + runner: ExecutionProfile["runner"]; + index: number; + count: number; + preparations: readonly Readonly[]; + cases: readonly RuntimeMatrixCase[]; +} + +declare const compiledRuntimeMatrixBrand: unique symbol; +declare const resolvedRuntimeCaseBrand: unique symbol; + +export interface CompiledRuntimeMatrix { + readonly [compiledRuntimeMatrixBrand]: true; + cases: readonly RuntimeMatrixCase[]; + shards: readonly Readonly[]; +} + +export interface ResolvedRuntimeCase { + readonly [resolvedRuntimeCaseBrand]: true; + case: RuntimeMatrixCase; + shard: Readonly; +} + +const ADAPTER_ID_PATTERN = /^[a-z][a-z0-9]*(?:[./_-][a-z0-9]+)*$/u; +const compiledRuntimeMatrices = new WeakSet(); +const resolvedRuntimeCases = new WeakSet(); + +function indexById(values: readonly T[], label: string): Map { + const index = new Map(); + for (const value of values) { + if (index.has(value.id)) { + throw new Error(`Duplicate ${label} id '${value.id}'`); + } + index.set(value.id, value); + } + return index; +} + +function assertConsistentHosts(profiles: readonly ExecutionProfile[]): void { + const runnersByHost = new Map(); + for (const profile of profiles) { + const existing = runnersByHost.get(profile.runner.hostId); + if ( + existing && + (existing.maxShards !== profile.runner.maxShards || existing.label !== profile.runner.label) + ) { + throw new Error( + `Execution host '${profile.runner.hostId}' has conflicting runner label or maxShards`, + ); + } + runnersByHost.set(profile.runner.hostId, profile.runner); + } +} + +function compileObligationBindings( + scenario: RuntimeNeutralScenario, + profile: ExecutionProfile, + bindings: readonly ObligationBinding[], + adapterCatalog: ReadonlyMap>, +): readonly Readonly[] { + const declared = new Map(); + for (const binding of bindings) { + assertExecutionFoundationId(binding.obligationId, "Bound obligation id"); + if (!ADAPTER_ID_PATTERN.test(binding.adapterId)) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' has invalid adapter id '${binding.adapterId}'`, + ); + } + const adapter = adapterCatalog.get(binding.adapterId); + if (!adapter) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' references unregistered adapter '${binding.adapterId}'`, + ); + } + if (adapter.provider !== profile.provider) { + throw new Error( + `Runtime adapter '${binding.adapterId}' belongs to provider '${adapter.provider}', not '${profile.provider}'`, + ); + } + if (adapter.scenarioId !== scenario.id) { + throw new Error( + `Runtime adapter '${binding.adapterId}' belongs to scenario '${adapter.scenarioId}', not '${scenario.id}'`, + ); + } + if (adapter.obligationId !== binding.obligationId) { + throw new Error( + `Runtime adapter '${binding.adapterId}' implements obligation '${adapter.obligationId}', not '${binding.obligationId}'`, + ); + } + if (declared.has(binding.obligationId)) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' repeats obligation '${binding.obligationId}'`, + ); + } + declared.set(binding.obligationId, binding); + } + + const expected = new Map( + scenario.supportObligations.map((obligation) => [obligation.id, obligation]), + ); + const missing = [...expected.keys()].filter((id) => !declared.has(id)).sort(); + if (missing.length > 0) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' is missing obligations: ${missing.join(", ")}`, + ); + } + const unknown = [...declared.keys()].filter((id) => !expected.has(id)).sort(); + if (unknown.length > 0) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' has unknown obligations: ${unknown.join(", ")}`, + ); + } + + const capabilities = new Set(profile.capabilities); + for (const obligation of expected.values()) { + assertCompatibleObligation(scenario, profile, obligation, capabilities); + } + return Object.freeze( + scenario.supportObligations.map((obligation) => { + const binding = declared.get(obligation.id) as ObligationBinding; + return Object.freeze({ + ...binding, + adapter: adapterCatalog.get(binding.adapterId) as Readonly, + }); + }), + ); +} + +function compileAdapterCatalog( + registrations: readonly RuntimeAdapterRegistration[], +): ReadonlyMap> { + const catalog = new Map>(); + for (const registration of registrations) { + if (!ADAPTER_ID_PATTERN.test(registration.id)) { + throw new Error(`Runtime adapter id '${registration.id}' is invalid`); + } + const provider = executionProviderId(registration.provider); + assertExecutionFoundationId(registration.scenarioId, "Runtime adapter scenario id"); + assertExecutionFoundationId(registration.obligationId, "Runtime adapter obligation id"); + if (typeof registration.execute !== "function") { + throw new Error(`Runtime adapter '${registration.id}' has no executable implementation`); + } + if (catalog.has(registration.id)) { + throw new Error(`Duplicate runtime adapter id '${registration.id}'`); + } + catalog.set( + registration.id, + Object.freeze({ + ...registration, + provider, + }), + ); + } + return catalog; +} + +function assertCompatibleObligation( + scenario: RuntimeNeutralScenario, + profile: ExecutionProfile, + obligation: ScenarioSupportObligation, + capabilities: ReadonlySet, +): void { + const missing = obligation.requiredCapabilities.filter( + (capability) => !capabilities.has(capability), + ); + if (missing.length > 0) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' cannot satisfy obligation '${obligation.id}'; missing capabilities: ${missing.join(", ")}`, + ); + } +} + +function digest(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function resourceIdentities(bindingId: string): RuntimeResourceIdentities { + const token = digest(`nemoclaw-runtime-binding-v1\0${bindingId}`).slice(0, 16); + const readable = bindingId + .replaceAll(".", "-") + .replaceAll("--", "-") + .slice(0, 28) + .replace(/-+$/u, ""); + return Object.freeze({ + sandbox: `e2e-${readable}-${token}`, + artifact: `runtime-artifact-${token}`, + cleanup: `runtime-cleanup-${token}`, + result: `runtime-result-${token}`, + }); +} + +export function executionPreparationKey(profile: ExecutionProfile): string { + const serialized = JSON.stringify({ + id: profile.id, + provider: profile.provider, + platform: profile.platform, + architecture: profile.architecture, + rootMode: profile.rootMode, + acceleration: profile.acceleration, + capabilities: profile.capabilities, + runner: { + hostId: profile.runner.hostId, + label: profile.runner.label, + maxShards: profile.runner.maxShards, + }, + }); + return `runtime-preparation-${digest(serialized).slice(0, 16)}`; +} + +function assertUniqueResourceIdentities(cases: readonly RuntimeMatrixCase[]): void { + const identities = cases.flatMap((entry) => Object.values(entry.identities)); + if (new Set(identities).size !== identities.length) { + throw new Error("Runtime matrix generated colliding resource identities"); + } +} + +function compileHostShards( + profiles: readonly ExecutionProfile[], + cases: readonly RuntimeMatrixCase[], +): readonly Readonly[] { + const shards: RuntimeHostShard[] = []; + const preparationsByHost = new Map(); + for (const profile of [...profiles].sort((left, right) => compareCodeUnits(left.id, right.id))) { + const profileCases = cases.filter((entry) => entry.profile.id === profile.id); + if (profileCases.length === 0) continue; + const preparations = preparationsByHost.get(profile.runner.hostId) ?? []; + preparations.push({ + preparationKey: executionPreparationKey(profile), + profile, + cases: Object.freeze(profileCases), + }); + preparationsByHost.set(profile.runner.hostId, preparations); + } + + for (const [hostId, preparations] of [...preparationsByHost.entries()].sort(([left], [right]) => + compareCodeUnits(left, right), + )) { + preparations.sort((left, right) => compareCodeUnits(left.preparationKey, right.preparationKey)); + const maxShards = preparations[0]?.profile.runner.maxShards ?? 0; + const count = Math.min(maxShards, preparations.length); + const lanes = Array.from({ length: count }, (): RuntimePreparationBatch[] => []); + preparations.forEach((preparation, index) => lanes[index % count]?.push(preparation)); + lanes.forEach((lane, index) => { + const shardIndex = index + 1; + const preparationKeys = lane.map((entry) => entry.preparationKey); + const laneIdentity = digest(JSON.stringify(preparationKeys)).slice(0, 16); + const runner = lane[0]?.profile.runner as ExecutionProfile["runner"]; + shards.push( + Object.freeze({ + id: `${hostId}-runtime-lane-${laneIdentity}-${shardIndex}-of-${count}`, + runner, + index: shardIndex, + count, + preparations: Object.freeze( + lane.map((entry) => + Object.freeze({ + ...entry, + }), + ), + ), + cases: Object.freeze(lane.flatMap((entry) => entry.cases)), + }), + ); + }); + } + if (new Set(shards.map((shard) => shard.id)).size !== shards.length) { + throw new Error("Runtime matrix generated colliding shard identities"); + } + return Object.freeze(shards); +} + +/** + * Compiles inert registry metadata. It selects no runner and executes no + * fixture; a future live consumer must opt in explicitly. + */ +export function compileRuntimeMatrix(definition: RuntimeMatrixDefinition): CompiledRuntimeMatrix { + if (definition.scenarios.length === 0) { + throw new Error("Runtime matrix must declare at least one scenario"); + } + if (definition.profiles.length === 0) { + throw new Error("Runtime matrix must declare at least one execution profile"); + } + + const scenarios = definition.scenarios.map(defineRuntimeScenario); + const profiles = definition.profiles.map(defineExecutionProfile); + const adapterCatalog = compileAdapterCatalog(definition.adapterCatalog); + const scenariosById = indexById(scenarios, "runtime scenario"); + const profilesById = indexById(profiles, "execution profile"); + assertConsistentHosts(profiles); + + const boundScenarios = new Set(); + const bindingIds = new Set(); + const cases = [...definition.bindings] + .sort( + (left, right) => + compareCodeUnits(left.scenarioId, right.scenarioId) || + compareCodeUnits(left.profileId, right.profileId), + ) + .map((binding): RuntimeMatrixCase => { + const scenario = scenariosById.get(binding.scenarioId); + if (!scenario) { + throw new Error(`Runtime binding references unknown scenario '${binding.scenarioId}'`); + } + const profile = profilesById.get(binding.profileId); + if (!profile) { + throw new Error(`Runtime binding references unknown profile '${binding.profileId}'`); + } + const id = `${scenario.id}--${profile.id}`; + if (bindingIds.has(id)) { + throw new Error(`Duplicate runtime binding '${id}'`); + } + bindingIds.add(id); + boundScenarios.add(scenario.id); + const missingScenarioCapabilities = scenario.requiredCapabilities.filter( + (capability) => !profile.capabilities.includes(capability), + ); + if (missingScenarioCapabilities.length > 0) { + throw new Error( + `Runtime binding '${scenario.id}' -> '${profile.id}' is incompatible; missing scenario capabilities: ${missingScenarioCapabilities.join(", ")}`, + ); + } + return Object.freeze({ + id, + preparationKey: executionPreparationKey(profile), + scenario, + profile, + obligationBindings: compileObligationBindings( + scenario, + profile, + binding.obligationBindings, + adapterCatalog, + ), + identities: resourceIdentities(id), + }); + }); + + const unboundScenarios = scenarios + .map((scenario) => scenario.id) + .filter((id) => !boundScenarios.has(id)); + if (unboundScenarios.length > 0) { + throw new Error( + `Runtime scenarios have no explicit binding: ${unboundScenarios.sort().join(", ")}`, + ); + } + assertUniqueResourceIdentities(cases); + const matrix = Object.freeze({ + cases: Object.freeze(cases), + shards: compileHostShards(profiles, cases), + }) as CompiledRuntimeMatrix; + compiledRuntimeMatrices.add(matrix); + return matrix; +} + +export function resolveRuntimeCase( + matrix: CompiledRuntimeMatrix, + reference: RuntimeCaseReference, +): ResolvedRuntimeCase { + if (!compiledRuntimeMatrices.has(matrix)) { + throw new Error("Runtime matrix was not issued by compileRuntimeMatrix"); + } + const id = `${reference.scenarioId}--${reference.profileId}`; + const runtimeCase = matrix.cases.find((entry) => entry.id === id); + if (!runtimeCase) { + throw new Error(`Runtime case '${id}' is not present in the compiled matrix`); + } + const shard = matrix.shards.find((entry) => + entry.cases.some((candidate) => candidate.id === runtimeCase.id), + ); + if (!shard) { + throw new Error(`Runtime case '${id}' has no compiled host shard`); + } + const resolved = Object.freeze({ case: runtimeCase, shard }) as ResolvedRuntimeCase; + resolvedRuntimeCases.add(resolved); + return resolved; +} + +export function assertResolvedRuntimeCase( + resolved: ResolvedRuntimeCase, +): asserts resolved is ResolvedRuntimeCase { + if (!resolvedRuntimeCases.has(resolved)) { + throw new Error("Runtime case resolution was not issued by resolveRuntimeCase"); + } +} diff --git a/test/e2e/registry/scenario.ts b/test/e2e/registry/scenario.ts new file mode 100644 index 00000000000..b6b284b7129 --- /dev/null +++ b/test/e2e/registry/scenario.ts @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { assertExecutionFoundationId, type ExecutionCapability } from "./execution-profile.ts"; + +export type RuntimeAgent = "openclaw" | "hermes" | "dcode"; + +export type JsonPrimitive = boolean | number | string | null; +export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }; + +export interface FsmTransition { + from: string; + event: string; + to: string; +} + +export interface TerminalOutcome { + status: "succeeded" | "failed"; + state: string; + failureClass?: string; +} + +export interface ScenarioJourneyStep { + id: string; + /** Stable semantic action. Never a provider command or shell fragment. */ + action: string; +} + +export interface ScenarioAssertionContract { + desiredState: JsonValue; + fsmTrace: readonly FsmTransition[]; + terminalOutcome: TerminalOutcome; + userVisibleState: JsonValue; +} + +export interface ScenarioSupportObligation { + id: string; + description: string; + requiredCapabilities: readonly ExecutionCapability[]; +} + +/** + * Product intent shared by runtime providers. Provider-specific setup and + * evidence adapters belong to RuntimeBindingSpec, never in the scenario. + */ +export interface RuntimeNeutralScenario { + id: string; + agent: RuntimeAgent; + description: string; + journey: readonly Readonly[]; + requiredCapabilities: readonly ExecutionCapability[]; + assertions: Readonly; + supportObligations: readonly Readonly[]; +} + +const AGENTS = new Set(["openclaw", "hermes", "dcode"]); + +/** Locale-independent ordering for canonical evidence and registry identities. */ +export function compareCodeUnits(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +export function normalizeJsonValue( + value: unknown, + fieldPath = "$", + ancestors = new Set(), +): JsonValue { + if (value === null || typeof value === "string" || typeof value === "boolean") { + return value; + } + if (typeof value === "number") { + if (!Number.isFinite(value)) { + throw new Error(`${fieldPath} must contain only finite JSON numbers`); + } + return Object.is(value, -0) ? 0 : value; + } + if (!value || typeof value !== "object") { + throw new Error(`${fieldPath} must be JSON-serializable`); + } + if (ancestors.has(value)) { + throw new Error(`${fieldPath} must not contain cyclic values`); + } + + ancestors.add(value); + try { + if (Array.isArray(value)) { + return value.map((entry, index) => + normalizeJsonValue(entry, `${fieldPath}[${index}]`, ancestors), + ); + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) { + throw new Error(`${fieldPath} must contain only plain JSON objects`); + } + return Object.fromEntries( + Object.entries(value) + .sort(([left], [right]) => compareCodeUnits(left, right)) + .map(([key, entry]) => [key, normalizeJsonValue(entry, `${fieldPath}.${key}`, ancestors)]), + ); + } finally { + ancestors.delete(value); + } +} + +export function freezeJsonValue(value: JsonValue): JsonValue { + if (Array.isArray(value)) { + return Object.freeze(value.map(freezeJsonValue)) as unknown as JsonValue; + } + if (value && typeof value === "object") { + return Object.freeze( + Object.fromEntries( + Object.entries(value).map(([key, entry]) => [key, freezeJsonValue(entry)]), + ), + ); + } + return value; +} + +function normalizeLabel(value: string, fieldPath: string): string { + const normalized = value.trim().replace(/\s+/gu, " "); + if (!normalized) { + throw new Error(`${fieldPath} must be a non-empty string`); + } + return normalized; +} + +export function normalizeFsmTrace( + transitions: readonly FsmTransition[], +): readonly Readonly[] { + if (transitions.length === 0) { + throw new Error("FSM trace must contain at least one transition"); + } + const normalized = transitions.map((transition, index) => + Object.freeze({ + from: normalizeLabel(transition.from, `fsmTrace[${index}].from`), + event: normalizeLabel(transition.event, `fsmTrace[${index}].event`), + to: normalizeLabel(transition.to, `fsmTrace[${index}].to`), + }), + ); + for (let index = 1; index < normalized.length; index += 1) { + if (normalized[index - 1]?.to !== normalized[index]?.from) { + throw new Error(`FSM trace is discontinuous between transitions ${index - 1} and ${index}`); + } + } + return Object.freeze(normalized); +} + +export function normalizeTerminalOutcome(outcome: TerminalOutcome): Readonly { + const state = normalizeLabel(outcome.state, "terminalOutcome.state"); + if (outcome.status === "succeeded") { + if (outcome.failureClass !== undefined) { + throw new Error("Successful terminal outcome must not declare failureClass"); + } + return Object.freeze({ status: outcome.status, state }); + } + if (outcome.status !== "failed") { + throw new Error(`Terminal outcome status '${String(outcome.status)}' is not recognized`); + } + if (outcome.failureClass === undefined) { + throw new Error("Failed terminal outcome must declare failureClass"); + } + return Object.freeze({ + status: outcome.status, + state, + failureClass: normalizeLabel(outcome.failureClass, "terminalOutcome.failureClass"), + }); +} + +export function assertTerminalMatchesTrace( + trace: readonly Readonly[], + outcome: Readonly, + fieldPath = "terminalOutcome", +): void { + const terminalState = trace.at(-1)?.to; + if (terminalState !== outcome.state) { + throw new Error( + `${fieldPath}.state '${outcome.state}' does not match FSM terminal state '${terminalState ?? ""}'`, + ); + } +} + +function normalizeDescription(value: string, fieldPath: string): string { + const description = value.trim(); + if (!description || /[\r\n]/u.test(description)) { + throw new Error(`${fieldPath} must be a single-line description`); + } + return description; +} + +function normalizeCapabilities( + values: readonly ExecutionCapability[], + fieldPath: string, +): readonly ExecutionCapability[] { + if (values.length === 0) { + throw new Error(`${fieldPath} must declare capabilities`); + } + if (new Set(values).size !== values.length) { + throw new Error(`${fieldPath} repeats a capability`); + } + return Object.freeze([...values].sort()); +} + +function assertUniqueIds( + values: readonly { id: string }[], + scenarioId: string, + label: string, +): void { + const ids = new Set(); + for (const value of values) { + assertExecutionFoundationId(value.id, `${label} id`); + if (ids.has(value.id)) { + throw new Error(`Runtime scenario '${scenarioId}' declares duplicate ${label} '${value.id}'`); + } + ids.add(value.id); + } +} + +export function defineRuntimeScenario(input: RuntimeNeutralScenario): RuntimeNeutralScenario { + assertExecutionFoundationId(input.id, "Runtime scenario id"); + if (!AGENTS.has(input.agent)) { + throw new Error(`Runtime scenario '${input.id}' agent '${input.agent}' is not recognized`); + } + const description = normalizeDescription(input.description, `Runtime scenario '${input.id}'`); + if (input.journey.length === 0) { + throw new Error(`Runtime scenario '${input.id}' must declare a user journey`); + } + if (!input.assertions) { + throw new Error(`Runtime scenario '${input.id}' must declare normalized assertions`); + } + if (input.supportObligations.length === 0) { + throw new Error(`Runtime scenario '${input.id}' must declare support obligations`); + } + + assertUniqueIds(input.journey, input.id, "journey step"); + const journey = input.journey.map((step) => { + assertExecutionFoundationId(step.action, "Journey action"); + return Object.freeze({ id: step.id, action: step.action }); + }); + + assertUniqueIds(input.supportObligations, input.id, "obligation"); + const supportObligations = input.supportObligations.map((obligation) => + Object.freeze({ + id: obligation.id, + description: normalizeDescription( + obligation.description, + `Runtime scenario '${input.id}' obligation '${obligation.id}'`, + ), + requiredCapabilities: normalizeCapabilities( + obligation.requiredCapabilities, + `Runtime scenario '${input.id}' obligation '${obligation.id}'`, + ), + }), + ); + const fsmTrace = normalizeFsmTrace(input.assertions.fsmTrace); + const terminalOutcome = normalizeTerminalOutcome(input.assertions.terminalOutcome); + assertTerminalMatchesTrace(fsmTrace, terminalOutcome, "assertions.terminalOutcome"); + + return Object.freeze({ + id: input.id, + agent: input.agent, + description, + journey: Object.freeze(journey), + requiredCapabilities: normalizeCapabilities( + input.requiredCapabilities, + `Runtime scenario '${input.id}'`, + ), + assertions: Object.freeze({ + desiredState: freezeJsonValue( + normalizeJsonValue(input.assertions.desiredState, "assertions.desiredState"), + ), + fsmTrace, + terminalOutcome, + userVisibleState: freezeJsonValue( + normalizeJsonValue(input.assertions.userVisibleState, "assertions.userVisibleState"), + ), + }), + supportObligations: Object.freeze(supportObligations), + }); +} diff --git a/test/e2e/registry/types.ts b/test/e2e/registry/types.ts index 4761ec3f393..dd10bd3d626 100644 --- a/test/e2e/registry/types.ts +++ b/test/e2e/registry/types.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { RuntimeCaseReference } from "./runtime-matrix.ts"; + export type PhaseName = "environment" | "onboarding" | "state-validation" | "lifecycle" | "runtime"; // Synthetic phase appended by the target runner when a target @@ -196,6 +198,12 @@ export interface TargetDefinition { description?: string; manifestPath?: string; environment?: TargetEnvironment; + /** + * Optional reference into the registry-wide cross-runtime catalog. Canonical + * targets do not declare this until a live consumer and support policy land + * separately. + */ + runtimeCase?: RuntimeCaseReference; assertionGroups: AssertionGroup[]; expectedStateId?: string; suiteIds?: string[]; diff --git a/test/e2e/support/cross-runtime-foundation-fixtures.ts b/test/e2e/support/cross-runtime-foundation-fixtures.ts new file mode 100644 index 00000000000..756f026eb5d --- /dev/null +++ b/test/e2e/support/cross-runtime-foundation-fixtures.ts @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + defineExecutionProfile, + type ExecutionCapability, + type ExecutionProfile, + executionProviderId, +} from "../registry/execution-profile.ts"; +import type { + RuntimeAdapterRegistration, + RuntimeBindingSpec, + RuntimeMatrixDefinition, +} from "../registry/runtime-matrix.ts"; +import { + defineRuntimeScenario, + type RuntimeAgent, + type RuntimeNeutralScenario, +} from "../registry/scenario.ts"; + +const COMMON_CAPABILITIES = [ + "agent.configure", + "agent.turn", + "evidence.collect", + "sandbox.lifecycle", + "state.observe", +] as const satisfies readonly ExecutionCapability[]; + +export function foundationScenarios(): RuntimeNeutralScenario[] { + return (["openclaw", "hermes", "dcode"] as const).map((agent) => + defineRuntimeScenario({ + id: `${agent}-smoke`, + agent, + description: `Runtime-neutral ${agent} lifecycle and turn`, + journey: [ + { id: "provision", action: "sandbox.provision" }, + { id: "configure", action: "agent.configure" }, + { id: "turn", action: "agent.turn" }, + { id: "observe", action: "state.observe" }, + ], + requiredCapabilities: [...COMMON_CAPABILITIES], + assertions: { + desiredState: { + agent, + inference: { model: "fixture-model", provider: "fixture-inference" }, + }, + fsmTrace: [ + { from: "requested", event: "provision", to: "ready" }, + { from: "ready", event: "complete turn", to: "completed" }, + ], + terminalOutcome: { status: "succeeded", state: "completed" }, + userVisibleState: { status: "ready", response: "fixture response" }, + }, + supportObligations: [ + { + id: "provision", + description: "Create and own the isolated sandbox", + requiredCapabilities: ["sandbox.lifecycle"], + }, + { + id: "configure", + description: "Apply the requested agent configuration", + requiredCapabilities: ["agent.configure"], + }, + { + id: "turn", + description: "Complete one agent turn", + requiredCapabilities: ["agent.turn"], + }, + { + id: "observe", + description: "Observe final state and collect evidence", + requiredCapabilities: ["state.observe", "evidence.collect"], + }, + ], + }), + ); +} + +export function foundationProfiles(): ExecutionProfile[] { + return [ + defineExecutionProfile({ + id: "docker-linux-amd64", + provider: executionProviderId("docker"), + platform: "linux", + architecture: "amd64", + rootMode: "rootful", + acceleration: "cpu", + capabilities: [...COMMON_CAPABILITIES, "transport.docker-socket"], + runner: { + hostId: "fixture-host", + label: "fixture-linux", + maxShards: 2, + }, + }), + defineExecutionProfile({ + id: "test-mxc-linux-arm64", + provider: executionProviderId("test-mxc"), + platform: "linux", + architecture: "arm64", + rootMode: "rootless", + acceleration: "cpu", + capabilities: [...COMMON_CAPABILITIES, "transport.socket-free"], + runner: { + hostId: "fixture-host", + label: "fixture-linux", + maxShards: 2, + }, + }), + ]; +} + +export function obligationBindings( + scenario: RuntimeNeutralScenario, + profile: ExecutionProfile, +): RuntimeBindingSpec["obligationBindings"] { + return scenario.supportObligations.map((obligation) => ({ + obligationId: obligation.id, + adapterId: `${profile.provider}.${scenario.agent}.${obligation.id}`, + })); +} + +export function foundationBindings( + scenarios: readonly RuntimeNeutralScenario[], + profiles: readonly ExecutionProfile[], +): RuntimeBindingSpec[] { + return scenarios.flatMap((scenario) => + profiles.map((profile) => ({ + scenarioId: scenario.id, + profileId: profile.id, + obligationBindings: obligationBindings(scenario, profile), + })), + ); +} + +export function foundationAdapterCatalog( + scenarios: readonly RuntimeNeutralScenario[], + profiles: readonly ExecutionProfile[], +): RuntimeAdapterRegistration[] { + const adapters = new Map(); + for (const scenario of scenarios) { + for (const profile of profiles) { + for (const binding of obligationBindings(scenario, profile)) { + const adapterId = binding.adapterId; + adapters.set(binding.adapterId, { + id: adapterId, + provider: profile.provider, + scenarioId: scenario.id, + obligationId: binding.obligationId, + execute(runtime, request) { + return runtime.lifecycle.executeAdapter(adapterId, request); + }, + }); + } + } + } + return [...adapters.values()]; +} + +export function foundationDefinition(): RuntimeMatrixDefinition { + const scenarios = foundationScenarios(); + const profiles = foundationProfiles(); + return { + scenarios, + profiles, + adapterCatalog: foundationAdapterCatalog(scenarios, profiles), + bindings: foundationBindings(scenarios, profiles), + }; +} + +export function scenarioFor(agent: RuntimeAgent): RuntimeNeutralScenario { + const scenario = foundationScenarios().find((entry) => entry.agent === agent); + if (!scenario) throw new Error(`Missing fixture scenario for ${agent}`); + return scenario; +} diff --git a/test/e2e/support/e2e-cross-runtime-compatibility.test.ts b/test/e2e/support/e2e-cross-runtime-compatibility.test.ts new file mode 100644 index 00000000000..ced45f0d2e2 --- /dev/null +++ b/test/e2e/support/e2e-cross-runtime-compatibility.test.ts @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; + +import { describe, expect, it } from "vitest"; + +import { buildRiskPlan } from "../../../tools/advisors/risk-plan.mts"; +import { buildE2eWorkflowPlan } from "../../../tools/e2e/workflow-plan.mts"; +import { buildLiveTargetMatrix } from "../registry/run.ts"; + +function digestOutput(value: unknown): string { + return createHash("sha256") + .update(`${JSON.stringify(value)}\n`) + .digest("hex"); +} + +describe("cross-runtime foundation compatibility", () => { + it("preserves the exact canonical Docker live matrix output", () => { + expect(digestOutput(buildLiveTargetMatrix())).toBe( + "1e9b8aa3f3435e32398f8a6e13b8daf97e6fa89be263d9b9f99d13694c143f1b", + ); + expect( + digestOutput( + buildLiveTargetMatrix([ + "ubuntu-repo-cloud-langchain-deepagents-code", + "ubuntu-repo-docker-post-reboot-recovery", + ]), + ), + ).toBe("6272aab16cf4b9555bdc4b3f4c0cdd24b5faa55118cbd61cbb4b30a3d418a63a"); + expect(digestOutput(buildE2eWorkflowPlan())).toBe( + "9c391dfd06884da3898cc5590e7b8d4f43f1a2ad5ebb0c141da5f6383021aeb5", + ); + }); + + it("preserves exact risk-plan outputs for established policy cases", () => { + const headSha = "0123456789abcdef0123456789abcdef01234567"; + const cases = [ + { headSha, changedFiles: [] }, + { headSha, changedFiles: ["test/e2e/registry/run.ts"] }, + { + headSha, + changedFiles: ["src/lib/onboard.ts", "src/lib/inference/foo.ts"], + }, + ]; + + expect(digestOutput(cases.map(buildRiskPlan))).toBe( + "70fdce2f30eaf736c7cb54638ec617412580751710a058da545af841bef5ccbe", + ); + }); +}); diff --git a/test/e2e/support/e2e-parity-evidence.test.ts b/test/e2e/support/e2e-parity-evidence.test.ts new file mode 100644 index 00000000000..0025deaac4a --- /dev/null +++ b/test/e2e/support/e2e-parity-evidence.test.ts @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { + assertParityEvidence, + buildExecutionEvidence, + compareParityEvidence, + type ExecutionEvidenceInput, + fingerprintDesiredState, + type NonEmptyProviderReceipts, + type ProviderReceipt, +} from "../registry/parity-evidence.ts"; +import { + compileRuntimeMatrix, + type ResolvedRuntimeCase, + resolveRuntimeCase, +} from "../registry/runtime-matrix.ts"; +import { foundationDefinition } from "./cross-runtime-foundation-fixtures.ts"; + +const HEAD_SHA = "0123456789abcdef0123456789abcdef01234567"; +const BASE_SHA = "89abcdef0123456789abcdef0123456789abcdef"; +const IMAGE_DIGEST = `sha256:${"a".repeat(64)}`; + +function evidenceInput(provider: "docker" | "test-mxc"): ExecutionEvidenceInput { + const matrix = compileRuntimeMatrix(foundationDefinition()); + const runtimeCase = matrix.cases.find( + (entry) => entry.scenario.agent === "openclaw" && entry.profile.provider === provider, + ); + assert.ok(runtimeCase, `Missing fixture runtime case for ${provider}`); + const resolved = resolveRuntimeCase(matrix, { + scenarioId: runtimeCase.scenario.id, + profileId: runtimeCase.profile.id, + }); + + return { + resolved, + source: { headSha: HEAD_SHA, baseSha: BASE_SHA }, + engine: { + name: provider === "docker" ? "docker-engine" : "fake-mxc-engine", + version: provider === "docker" ? "29.1.0" : "0.0.0-fixture", + }, + workload: { + logicalId: runtimeCase.identities.sandbox, + providerResourceId: `${provider}://fixture/${runtimeCase.identities.sandbox}`, + managedImages: [{ role: "agent", digest: IMAGE_DIGEST }], + }, + observed: { + desiredState: runtimeCase.scenario.assertions.desiredState, + fsmTrace: runtimeCase.scenario.assertions.fsmTrace, + terminalOutcome: runtimeCase.scenario.assertions.terminalOutcome, + userVisibleState: runtimeCase.scenario.assertions.userVisibleState, + }, + providerReceipts: [ + { + kind: "prepare", + operationId: `${provider}.prepare`, + value: { diagnostic: `${provider}-private` }, + }, + ], + }; +} + +describe("cross-runtime parity evidence", () => { + it("normalizes desired-state fingerprints and exact execution evidence", () => { + expect(fingerprintDesiredState({ b: 2, a: { y: 2, x: 1 } })).toBe( + fingerprintDesiredState({ a: { x: 1, y: 2 }, b: 2 }), + ); + + const evidence = buildExecutionEvidence(evidenceInput("docker")); + expect(evidence).toMatchObject({ + source: { headSha: HEAD_SHA, baseSha: BASE_SHA }, + runtime: { + provider: "docker", + architecture: "amd64", + capabilities: expect.arrayContaining(["transport.docker-socket"]), + }, + workload: { + logicalId: expect.stringMatching(/^e2e-/), + providerResourceId: expect.stringMatching(/^docker:/), + managedImages: [{ role: "agent", digest: IMAGE_DIGEST }], + }, + parity: { + terminalOutcome: { status: "succeeded", state: "completed" }, + }, + }); + }); + + it("ignores provider runtime identity and opaque receipts when comparing parity", () => { + const docker = buildExecutionEvidence(evidenceInput("docker")); + const mxc = buildExecutionEvidence(evidenceInput("test-mxc")); + + expect(compareParityEvidence(docker, mxc)).toEqual([]); + expect(() => assertParityEvidence(docker, mxc)).not.toThrow(); + }); + + it("rejects executions that do not satisfy the scenario before parity comparison", () => { + const mismatchInput = evidenceInput("test-mxc"); + mismatchInput.observed.userVisibleState = { + status: "degraded", + response: "fixture response", + }; + expect(() => buildExecutionEvidence(mismatchInput)).toThrow( + /observed userVisibleState does not satisfy its scenario assertion/, + ); + + const wrongTrace = evidenceInput("docker"); + wrongTrace.observed.fsmTrace = [ + { from: "requested", event: "skip provision", to: "ready" }, + { from: "ready", event: "complete turn", to: "completed" }, + ]; + expect(() => buildExecutionEvidence(wrongTrace)).toThrow( + /observed fsmTrace does not satisfy its scenario assertion/, + ); + }); + + it("rejects incomplete source, image, and provider receipt evidence", () => { + const badSource = evidenceInput("docker"); + badSource.source.headSha = "not-a-sha"; + expect(() => buildExecutionEvidence(badSource)).toThrow(/40-character commit SHA/); + + const badImage = evidenceInput("docker"); + badImage.workload.managedImages = [{ role: "agent", digest: "latest" }]; + expect(() => buildExecutionEvidence(badImage)).toThrow(/exact sha256 digest/); + + const missingReceipt = evidenceInput("docker"); + missingReceipt.providerReceipts = [] as unknown as NonEmptyProviderReceipts; + expect(() => buildExecutionEvidence(missingReceipt)).toThrow(/provider receipt/); + + const wrongWorkload = evidenceInput("docker"); + wrongWorkload.workload.logicalId = "some-other-sandbox"; + expect(() => buildExecutionEvidence(wrongWorkload)).toThrow( + /does not match case sandbox identity/, + ); + + const wrongTerminal = evidenceInput("docker"); + wrongTerminal.observed.terminalOutcome = { + status: "succeeded", + state: "not-the-trace-terminal", + }; + expect(() => buildExecutionEvidence(wrongTerminal)).toThrow( + /does not match FSM terminal state/, + ); + + const wrongDesiredState = evidenceInput("docker"); + wrongDesiredState.observed.desiredState = { configured: false }; + expect(() => buildExecutionEvidence(wrongDesiredState)).toThrow( + /observed desiredState does not satisfy its scenario assertion/, + ); + + const forgedResolution = evidenceInput("docker"); + forgedResolution.resolved = { + case: forgedResolution.resolved.case, + shard: { + ...forgedResolution.resolved.shard, + id: "attacker-chosen-shard-id", + }, + } as unknown as ResolvedRuntimeCase; + expect(() => buildExecutionEvidence(forgedResolution)).toThrow( + /resolution was not issued by resolveRuntimeCase/, + ); + }); + + it("rejects non-string receipt identities and omits unknown receipt fields", () => { + const missingKind = evidenceInput("docker"); + missingKind.providerReceipts = [ + { + kind: undefined, + operationId: "docker.prepare", + value: {}, + } as unknown as ProviderReceipt, + ]; + expect(() => buildExecutionEvidence(missingKind)).toThrow( + /provider receipt kind must be a string/, + ); + + const missingOperationId = evidenceInput("docker"); + missingOperationId.providerReceipts = [ + { + kind: "prepare", + operationId: undefined, + value: {}, + } as unknown as ProviderReceipt, + ]; + expect(() => buildExecutionEvidence(missingOperationId)).toThrow( + /provider receipt operationId must be a string/, + ); + + const extraField = evidenceInput("docker"); + extraField.providerReceipts = [ + { + kind: "prepare", + operationId: "docker.prepare", + value: { fixture: true }, + providerPrivateField: "must-not-persist", + } as ProviderReceipt, + ]; + const evidence = buildExecutionEvidence(extraField); + expect(evidence.providerReceipts).toEqual([ + { + kind: "prepare", + operationId: "docker.prepare", + value: { fixture: true }, + }, + ]); + expect(evidence.providerReceipts[0]).not.toHaveProperty("providerPrivateField"); + }); + + it("publishes provider receipts through the redacting artifact boundary", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-execution-evidence-")); + try { + const secret = "provider-private-secret"; + const input = evidenceInput("test-mxc"); + input.providerReceipts = [ + { + kind: "prepare", + operationId: "test-mxc.prepare", + value: { diagnostic: secret }, + }, + ]; + const sink = new ArtifactSink(root, [secret]); + const evidence = buildExecutionEvidence(input); + const file = await sink.writeExecutionEvidence( + input.resolved.case.identities.result, + evidence, + ); + + expect(file).toBe( + path.join(sink.rootDir, "execution", `${input.resolved.case.identities.result}.json`), + ); + const published = fs.readFileSync(file, "utf8"); + expect(published).toContain("[REDACTED]"); + expect(published).not.toContain(secret); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/e2e/support/e2e-runtime-foundation-types.test.ts b/test/e2e/support/e2e-runtime-foundation-types.test.ts new file mode 100644 index 00000000000..45f7e73ff72 --- /dev/null +++ b/test/e2e/support/e2e-runtime-foundation-types.test.ts @@ -0,0 +1,174 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, expectTypeOf, it } from "vitest"; + +import { test as e2eFixtureTest } from "../fixtures/e2e-test.ts"; +import { + EnvironmentPhaseFixture, + LifecyclePhaseFixture, + StateValidationPhaseFixture, +} from "../fixtures/phases/index.ts"; +import type { + RuntimeLifecycleEvidence, + RuntimeProviderLifecycle, +} from "../fixtures/runtime-provider.ts"; +import { defineExecutionProfile, executionProviderId } from "../registry/execution-profile.ts"; +import type { + ExecutionEvidenceInput, + NonEmptyProviderReceipts, +} from "../registry/parity-evidence.ts"; +import { hasRegisteredRuntimeProfile } from "../registry/registry.ts"; +import { buildLiveTargetMatrix } from "../registry/run.ts"; +import { defineRuntimeScenario, type RuntimeNeutralScenario } from "../registry/scenario.ts"; +import { foundationProfiles, foundationScenarios } from "./cross-runtime-foundation-fixtures.ts"; + +describe("cross-runtime foundation types", () => { + it("models Docker and socket-free fake MXC profiles without registering either", () => { + const liveMatrixBefore = buildLiveTargetMatrix(); + const profiles = foundationProfiles(); + const [docker, mxc] = profiles; + + expect(docker).toMatchObject({ + provider: "docker", + architecture: "amd64", + rootMode: "rootful", + acceleration: "cpu", + }); + expect(docker?.capabilities).toContain("transport.docker-socket"); + expect(mxc).toMatchObject({ + provider: "test-mxc", + architecture: "arm64", + rootMode: "rootless", + acceleration: "cpu", + }); + expect(mxc?.capabilities).toContain("transport.socket-free"); + expect(mxc?.capabilities).not.toContain("transport.docker-socket"); + expect(buildLiveTargetMatrix()).toEqual(liveMatrixBefore); + for (const profile of profiles) { + expect(hasRegisteredRuntimeProfile(profile.id)).toBe(false); + } + }); + + it("keeps OpenClaw, Hermes, and DCode scenarios provider-neutral and obligation-explicit", () => { + const scenarios = foundationScenarios(); + + expect(scenarios.map((scenario) => scenario.agent)).toEqual(["openclaw", "hermes", "dcode"]); + for (const scenario of scenarios) { + expect(scenario).not.toHaveProperty("provider"); + expect(scenario.journey.map((step) => step.action)).toEqual([ + "sandbox.provision", + "agent.configure", + "agent.turn", + "state.observe", + ]); + expect(scenario.assertions.terminalOutcome).toEqual({ + status: "succeeded", + state: "completed", + }); + expect(scenario.supportObligations.map((obligation) => obligation.id)).toEqual([ + "provision", + "configure", + "turn", + "observe", + ]); + } + }); + + it("omits undeclared provider fields from normalized scenarios", () => { + const base = foundationScenarios()[0]!; + const input = { + ...base, + provider: "docker", + journey: base.journey.map((step) => ({ ...step, provider: "docker" })), + assertions: { ...base.assertions, provider: "docker" }, + supportObligations: base.supportObligations.map((obligation) => ({ + ...obligation, + provider: "docker", + })), + } as unknown as RuntimeNeutralScenario; + + const scenario = defineRuntimeScenario(input); + + expect(scenario).not.toHaveProperty("provider"); + expect(scenario.journey[0]).not.toHaveProperty("provider"); + expect(scenario.assertions).not.toHaveProperty("provider"); + expect(scenario.supportObligations[0]).not.toHaveProperty("provider"); + }); + + it("requires provider receipt evidence from lifecycle and cleanup contracts", () => { + expectTypeOf< + RuntimeLifecycleEvidence["providerReceipts"] + >().toEqualTypeOf(); + expectTypeOf< + Awaited> + >().toEqualTypeOf(); + expectTypeOf< + ExecutionEvidenceInput["providerReceipts"] + >().toEqualTypeOf(); + }); + + it("keeps provider ids open while rejecting invalid profiles", () => { + const valid = foundationProfiles()[0]!; + expect( + defineExecutionProfile({ + ...valid, + id: "future-provider-profile", + provider: executionProviderId("future-provider"), + }).provider, + ).toBe("future-provider"); + expect(() => executionProviderId("../unsafe")).toThrow(/provider id/); + expect(() => + defineExecutionProfile({ + ...valid, + runner: { ...valid.runner, maxShards: 0 }, + }), + ).toThrow(/maxShards must be between/); + expect(() => + defineExecutionProfile({ + ...valid, + capabilities: [...valid.capabilities, valid.capabilities[0]!], + }), + ).toThrow(/duplicate capabilities/); + }); + + it("rejects missing and duplicate support obligations", () => { + const valid = foundationScenarios()[0]!; + expect(() => + defineRuntimeScenario({ + ...valid, + supportObligations: [], + }), + ).toThrow(/must declare support obligations/); + expect(() => + defineRuntimeScenario({ + ...valid, + supportObligations: [valid.supportObligations[0]!, valid.supportObligations[0]!], + }), + ).toThrow(/duplicate obligation/); + }); + + it("rejects scenarios without a user journey or normalized assertions", () => { + const valid = foundationScenarios()[0]!; + expect(() => defineRuntimeScenario({ ...valid, journey: [] })).toThrow( + /must declare a user journey/, + ); + expect(() => + defineRuntimeScenario({ + ...valid, + assertions: undefined, + } as unknown as typeof valid), + ).toThrow(/must declare normalized assertions/); + }); +}); + +e2eFixtureTest( + "keeps cross-runtime injection inert beside the existing Docker phase fixtures", + async ({ environment, executionProfile, lifecycle, runtimeProvider, stateValidation }) => { + expect(executionProfile).toBeUndefined(); + expect(runtimeProvider).toBeUndefined(); + expect(environment).toBeInstanceOf(EnvironmentPhaseFixture); + expect(lifecycle).toBeInstanceOf(LifecyclePhaseFixture); + expect(stateValidation).toBeInstanceOf(StateValidationPhaseFixture); + }, +); diff --git a/test/e2e/support/e2e-runtime-matrix.test.ts b/test/e2e/support/e2e-runtime-matrix.test.ts new file mode 100644 index 00000000000..46e640cec52 --- /dev/null +++ b/test/e2e/support/e2e-runtime-matrix.test.ts @@ -0,0 +1,445 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; + +import { describe, expect, it } from "vitest"; + +import { + type ExactWorkloadIdentity, + executeRuntimeCaseThroughProvider, + type RuntimeProviderFixture, +} from "../fixtures/runtime-provider.ts"; +import { buildLiveTargetRunPlan } from "../live/run-plan.ts"; +import { target } from "../registry/builder.ts"; +import { + defineExecutionProfile, + type ExecutionProfile, + executionProviderId, +} from "../registry/execution-profile.ts"; +import { + compileRuntimeMatrix, + executionPreparationKey, + type RuntimeMatrixDefinition, + resolveRuntimeCase, +} from "../registry/runtime-matrix.ts"; +import { + foundationDefinition, + foundationProfiles, + obligationBindings, +} from "./cross-runtime-foundation-fixtures.ts"; + +function fakeRuntimeProvider( + profile: ExecutionProfile, + adapterCalls: string[] = [], +): RuntimeProviderFixture { + const imageDigest = `sha256:${"b".repeat(64)}`; + return { + profile, + environment: { + async prepare() { + return { + profileId: profile.id, + ready: true, + engineName: `${profile.provider}-fixture`, + engineVersion: "0.0.0-fixture", + capabilities: profile.capabilities, + }; + }, + }, + lifecycle: { + async executeAdapter(adapterId, request) { + assert.ok( + adapterId.startsWith(`${profile.provider}.`) && + adapterId.endsWith(`.${request.obligationId}`), + `Fixture provider cannot execute ${adapterId}`, + ); + adapterCalls.push(adapterId); + }, + async cleanup() { + return [ + { + kind: "cleanup", + operationId: `${profile.provider}.cleanup`, + value: { fixture: true }, + }, + ]; + }, + }, + state: { + async inspectWorkload({ logicalId }) { + return { + logicalId, + providerResourceId: `${profile.provider}://fixture/${logicalId}`, + managedImages: [{ role: "agent", digest: imageDigest }], + }; + }, + async observe({ caseId }) { + const agent = caseId.split("-smoke--", 1)[0]!; + return { + desiredState: { + agent, + inference: { model: "fixture-model", provider: "fixture-inference" }, + }, + fsmTrace: [ + { from: "requested", event: "provision", to: "ready" }, + { from: "ready", event: "complete turn", to: "completed" }, + ], + terminalOutcome: { status: "succeeded", state: "completed" }, + userVisibleState: { status: "ready", response: "fixture response" }, + providerReceipts: [ + { + kind: "lifecycle", + operationId: `${profile.provider}.lifecycle`, + value: { fixture: true }, + }, + ], + }; + }, + }, + }; +} + +describe("cross-runtime E2E matrix compiler", () => { + it("binds OpenClaw, Hermes, and DCode explicitly on Docker and fake MXC", () => { + const { cases, shards } = compileRuntimeMatrix(foundationDefinition()); + + expect(cases).toHaveLength(6); + expect(cases.map((entry) => `${entry.scenario.agent}:${entry.profile.provider}`)).toEqual([ + "dcode:docker", + "dcode:test-mxc", + "hermes:docker", + "hermes:test-mxc", + "openclaw:docker", + "openclaw:test-mxc", + ]); + for (const entry of cases) { + expect(entry.obligationBindings).toHaveLength(entry.scenario.supportObligations.length); + } + expect(shards).toHaveLength(2); + expect(shards.some((shard) => shard.cases.length > 1)).toBe(true); + for (const shard of shards) { + expect(shard.preparations).toHaveLength(1); + expect(shard.cases).toEqual(shard.preparations.flatMap((entry) => entry.cases)); + } + }); + + it("fails incompatible profile bindings before producing a matrix", () => { + const definition = foundationDefinition(); + const scenario = definition.scenarios[0]!; + const baseProfile = definition.profiles[0]!; + const incompatible = defineExecutionProfile({ + ...baseProfile, + id: "docker-without-turn", + capabilities: baseProfile.capabilities.filter((capability) => capability !== "agent.turn"), + }); + + expect(() => + compileRuntimeMatrix({ + scenarios: [scenario], + profiles: [incompatible], + adapterCatalog: definition.adapterCatalog, + bindings: [ + { + scenarioId: scenario.id, + profileId: incompatible.id, + obligationBindings: obligationBindings(scenario, incompatible), + }, + ], + }), + ).toThrow(/incompatible.*agent\.turn/); + }); + + it("fails bindings that omit a scenario support obligation", () => { + const definition = foundationDefinition(); + const scenario = definition.scenarios[0]!; + const profile = definition.profiles[0]!; + + expect(() => + compileRuntimeMatrix({ + scenarios: [scenario], + profiles: [profile], + adapterCatalog: definition.adapterCatalog, + bindings: [ + { + scenarioId: scenario.id, + profileId: profile.id, + obligationBindings: obligationBindings(scenario, profile).slice(1), + }, + ], + }), + ).toThrow(/missing obligations: provision/); + }); + + it("assigns deterministic bounded host shards and isolated resource identities", () => { + const definition = foundationDefinition(); + const first = compileRuntimeMatrix(definition); + const reversed: RuntimeMatrixDefinition = { + scenarios: [...definition.scenarios].reverse(), + profiles: [...definition.profiles].reverse(), + adapterCatalog: [...definition.adapterCatalog].reverse(), + bindings: [...definition.bindings].reverse(), + }; + const second = compileRuntimeMatrix(reversed); + + expect(second).toEqual(first); + expect(first.shards).toHaveLength(2); + expect(new Set(first.shards.map((shard) => shard.runner.hostId))).toEqual( + new Set(["fixture-host"]), + ); + const preparationKeys = first.shards.flatMap((shard) => + shard.preparations.map((preparation) => preparation.preparationKey), + ); + expect(new Set(preparationKeys).size).toBe(2); + for (const shard of first.shards) { + expect(shard.index).toBeGreaterThanOrEqual(1); + expect(shard.index).toBeLessThanOrEqual(shard.count); + expect(shard.count).toBeLessThanOrEqual(shard.runner.maxShards); + expect(shard.id).toContain("runtime-lane"); + expect(shard.cases).toHaveLength(3); + for (const preparation of shard.preparations) { + expect(new Set(preparation.cases.map((entry) => entry.preparationKey))).toEqual( + new Set([preparation.preparationKey]), + ); + } + } + const allIdentities = first.cases.flatMap((entry) => Object.values(entry.identities)); + expect(new Set(allIdentities).size).toBe(first.cases.length * 4); + }); + + it("derives preparation identity from every profile and runner dimension", () => { + const profile = foundationProfiles()[0]!; + const variants = [ + { ...profile, id: "docker-linux-amd64-second" }, + { ...profile, provider: executionProviderId("future-provider") }, + { ...profile, platform: "macos" as const }, + { ...profile, architecture: "arm64" as const }, + { ...profile, rootMode: "rootless" as const }, + { ...profile, acceleration: "nvidia-gpu" as const }, + { ...profile, capabilities: [...profile.capabilities, "transport.socket-free" as const] }, + { ...profile, runner: { ...profile.runner, hostId: "fixture-host-second" } }, + { ...profile, runner: { ...profile.runner, label: "fixture-linux-second" } }, + { ...profile, runner: { ...profile.runner, maxShards: 1 } }, + ].map(defineExecutionProfile); + + expect(new Set([profile, ...variants].map(executionPreparationKey)).size).toBe( + variants.length + 1, + ); + }); + + it("rejects obligation bindings whose adapter is not registered", () => { + const definition = foundationDefinition(); + const binding = definition.bindings[0]!; + expect(() => + compileRuntimeMatrix({ + ...definition, + bindings: [ + { + ...binding, + obligationBindings: binding.obligationBindings.map((entry, index) => + index === 0 ? { ...entry, adapterId: "docker.missing.adapter" } : entry, + ), + }, + ...definition.bindings.slice(1), + ], + }), + ).toThrow(/unregistered adapter/); + }); + + it("schedules preparation-atomic work within the shared host maxShards ceiling", () => { + const definition = foundationDefinition(); + const scenario = definition.scenarios[0]!; + const docker = definition.profiles[0]!; + const mxc = definition.profiles[1]!; + const secondDockerPreparation = defineExecutionProfile({ + ...docker, + id: "docker-linux-amd64-rootless", + rootMode: "rootless", + }); + + const compiled = compileRuntimeMatrix({ + scenarios: [scenario], + profiles: [docker, mxc, secondDockerPreparation], + adapterCatalog: definition.adapterCatalog, + bindings: [docker, mxc, secondDockerPreparation].map((profile) => ({ + scenarioId: scenario.id, + profileId: profile.id, + obligationBindings: obligationBindings(scenario, profile), + })), + }); + + expect(compiled.shards).toHaveLength(2); + expect(compiled.shards.flatMap((shard) => shard.preparations)).toHaveLength(3); + expect(compiled.shards.some((shard) => shard.preparations.length === 2)).toBe(true); + expect( + new Set( + compiled.shards.flatMap((shard) => + shard.preparations.map((preparation) => preparation.preparationKey), + ), + ).size, + ).toBe(3); + }); + + it("keeps Docker and socket-free fake MXC commands behind one provider fixture seam", async () => { + const providers = foundationProfiles().map((profile) => fakeRuntimeProvider(profile)); + + for (const provider of providers) { + const ready = await provider.environment.prepare(); + const workload = await provider.state.inspectWorkload({ logicalId: "fixture-workload" }); + await provider.lifecycle.executeAdapter(`${provider.profile.provider}.openclaw.provision`, { + caseId: "fixture-case", + obligationId: "provision", + workloadId: workload.logicalId, + }); + const lifecycle = await provider.state.observe({ + caseId: "fixture-case", + workload, + }); + const cleanup = await provider.lifecycle.cleanup(workload); + + expect(ready.profileId).toBe(provider.profile.id); + expect(workload.providerResourceId).toMatch(new RegExp(`^${provider.profile.provider}:`)); + expect(lifecycle.terminalOutcome.status).toBe("succeeded"); + expect(cleanup).toHaveLength(1); + } + expect(providers[1]?.profile.capabilities).toContain("transport.socket-free"); + expect(providers[1]?.profile.capabilities).not.toContain("transport.docker-socket"); + }); + + it("executes compiled cases only through the provider-neutral seam", async () => { + const matrix = compileRuntimeMatrix(foundationDefinition()); + for (const runtimeCase of matrix.cases.filter((entry) => entry.scenario.agent === "openclaw")) { + const shard = matrix.shards.find((entry) => entry.cases.includes(runtimeCase)); + assert.ok(shard, `Missing shard for ${runtimeCase.id}`); + const adapterCalls: string[] = []; + const resolved = resolveRuntimeCase(matrix, { + scenarioId: runtimeCase.scenario.id, + profileId: runtimeCase.profile.id, + }); + expect(resolved.shard).toBe(shard); + const evidence = await executeRuntimeCaseThroughProvider({ + resolved, + provider: fakeRuntimeProvider(runtimeCase.profile, adapterCalls), + source: { + headSha: "0123456789abcdef0123456789abcdef01234567", + baseSha: "89abcdef0123456789abcdef0123456789abcdef", + }, + }); + expect(evidence.caseId).toBe(runtimeCase.id); + expect(evidence.runtime.provider).toBe(runtimeCase.profile.provider); + expect(evidence.providerReceipts.map((receipt) => receipt.kind)).toEqual([ + "lifecycle", + "cleanup", + ]); + expect(adapterCalls).toEqual( + ["provision", "configure", "turn", "observe"].map( + (obligation) => + `${runtimeCase.profile.provider}.${runtimeCase.scenario.agent}.${obligation}`, + ), + ); + } + }); + + it("rejects an inspected workload mismatch before executing obligations and still cleans it", async () => { + const matrix = compileRuntimeMatrix(foundationDefinition()); + const runtimeCase = matrix.cases.find( + (entry) => entry.scenario.agent === "openclaw" && entry.profile.provider === "docker", + ); + assert.ok(runtimeCase, "Missing Docker OpenClaw fixture case"); + const resolved = resolveRuntimeCase(matrix, { + scenarioId: runtimeCase.scenario.id, + profileId: runtimeCase.profile.id, + }); + const adapterCalls: string[] = []; + const cleanedWorkloads: ExactWorkloadIdentity[] = []; + const provider = fakeRuntimeProvider(runtimeCase.profile, adapterCalls); + const inspectedWorkload = { + logicalId: "provider-returned-wrong-sandbox", + providerResourceId: "docker://fixture/provider-returned-wrong-sandbox", + managedImages: [{ role: "agent", digest: `sha256:${"b".repeat(64)}` }], + }; + provider.state.inspectWorkload = async () => inspectedWorkload; + provider.lifecycle.cleanup = async (workload) => { + cleanedWorkloads.push(workload); + return [ + { + kind: "cleanup", + operationId: "docker.cleanup-mismatched-workload", + value: { fixture: true }, + }, + ]; + }; + + await expect( + executeRuntimeCaseThroughProvider({ + resolved, + provider, + source: { + headSha: "0123456789abcdef0123456789abcdef01234567", + baseSha: "89abcdef0123456789abcdef0123456789abcdef", + }, + }), + ).rejects.toThrow(/does not match case sandbox identity/); + expect(adapterCalls).toEqual([]); + expect(cleanedWorkloads).toEqual([inspectedWorkload]); + }); + + it("keeps the execution failure as the cause when cleanup also fails", async () => { + const matrix = compileRuntimeMatrix(foundationDefinition()); + const runtimeCase = matrix.cases.find( + (entry) => entry.scenario.agent === "openclaw" && entry.profile.provider === "docker", + ); + assert.ok(runtimeCase, "Missing Docker OpenClaw fixture case"); + const resolved = resolveRuntimeCase(matrix, { + scenarioId: runtimeCase.scenario.id, + profileId: runtimeCase.profile.id, + }); + const executionError = new Error("adapter execution failed"); + const cleanupError = new Error("provider cleanup failed"); + const provider = fakeRuntimeProvider(runtimeCase.profile); + provider.lifecycle.executeAdapter = async () => { + throw executionError; + }; + provider.lifecycle.cleanup = async () => { + throw cleanupError; + }; + + await expect( + executeRuntimeCaseThroughProvider({ + resolved, + provider, + source: { + headSha: "0123456789abcdef0123456789abcdef01234567", + baseSha: "89abcdef0123456789abcdef0123456789abcdef", + }, + }), + ).rejects.toMatchObject({ + cause: executionError, + errors: [executionError, cleanupError], + }); + }); + + it("compiles optional runtime metadata through the existing target run-plan path", () => { + const runtimeMatrix = foundationDefinition(); + const compiled = compileRuntimeMatrix(runtimeMatrix); + const registered = target("synthetic-cross-runtime") + .manifest("test/e2e/manifests/openclaw-nvidia.yaml") + .environment({ + platform: "ubuntu-local", + install: "repo-current", + runtime: "docker-running", + onboarding: "cloud-openclaw", + }) + .expectedState("cloud-openclaw-ready") + .runtimeCase({ + scenarioId: "openclaw-smoke", + profileId: "docker-linux-amd64", + }) + .build(); + + const plan = buildLiveTargetRunPlan(registered, compiled); + expect(plan.runtimeCase?.case.id).toBe("openclaw-smoke--docker-linux-amd64"); + expect(plan.runtimeCase?.shard.cases).toContain(plan.runtimeCase?.case); + expect(plan.phases).toEqual(["environment", "onboarding", "state-validation"]); + }); +}); diff --git a/test/entrypoint-env-wrapper.test.ts b/test/entrypoint-env-wrapper.test.ts index 8bd74015681..5e58805d17f 100644 --- a/test/entrypoint-env-wrapper.test.ts +++ b/test/entrypoint-env-wrapper.test.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { sliceBlock } from "./helpers/corporate-ca-support"; const HELPER = path.join(import.meta.dirname, "..", "scripts", "lib", "entrypoint-env-wrapper.sh"); @@ -134,8 +134,10 @@ describe("OCI entrypoint env-wrapper normalization", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-wrapper-")); const fakeBin = path.join(tmpDir, "bin"); const scriptPath = path.join(tmpDir, "run.sh"); - function runScenario(setArgs: string, extraEnv: Record = {}) { + const baseEnv = { ...process.env }; + delete baseEnv.NEMOCLAW_DASHBOARD_PORT; + delete baseEnv.CHAT_UI_URL; const script = [ "#!/usr/bin/env bash", "set -euo pipefail", @@ -156,10 +158,13 @@ describe("OCI entrypoint env-wrapper normalization", () => { return spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000, - env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH || ""}`, ...extraEnv }, + env: { ...baseEnv, PATH: `${fakeBin}:${process.env.PATH || ""}`, ...extraEnv }, }); } + vi.stubEnv("NEMOCLAW_DASHBOARD_PORT", "19999"); + vi.stubEnv("CHAT_UI_URL", "https://ambient.example.test/ui"); + try { fs.mkdirSync(fakeBin); fs.writeFileSync(path.join(fakeBin, "openclaw"), "#!/usr/bin/env bash\nexit 0\n", { @@ -205,6 +210,11 @@ describe("OCI entrypoint env-wrapper normalization", () => { expect(baked.stdout).toContain("OPENCLAW_STATE_DIR=/sandbox/.openclaw"); expect(baked.stdout).toContain("CMD=openclaw agent"); + const defaults = runScenario("set -- nemoclaw-start openclaw agent"); + expect(defaults.status).toBe(0); + expect(defaults.stdout).toContain("CHAT_UI_URL=http://127.0.0.1:18789"); + expect(defaults.stdout).toContain("PUBLIC_PORT=18789"); + const invalidHighPort = runScenario("set -- nemoclaw-start openclaw agent", { NEMOCLAW_DASHBOARD_PORT: "70000", }); @@ -212,6 +222,7 @@ describe("OCI entrypoint env-wrapper normalization", () => { expect(invalidHighPort.stderr).toContain("Invalid NEMOCLAW_DASHBOARD_PORT='70000'"); expect(invalidHighPort.stderr).toContain("must be an integer between 1024 and 65535"); } finally { + vi.unstubAllEnvs(); fs.rmSync(tmpDir, { recursive: true, force: true }); } });