From 633992427f10d236e513e4524590f7c5d7a3d12e Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:07:01 -0800 Subject: [PATCH 1/5] fix(e2e): verify native plugin tools through agent execution Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/README.md | 10 ++ test/e2e/fixtures/native-plugin-evidence.ts | 149 +++++++++++++++++ test/e2e/live/full-e2e.test.ts | 154 +++++++----------- .../support/native-plugin-evidence.test.ts | 140 ++++++++++++++++ 4 files changed, 355 insertions(+), 98 deletions(-) create mode 100644 test/e2e/fixtures/native-plugin-evidence.ts create mode 100644 test/e2e/support/native-plugin-evidence.test.ts diff --git a/test/e2e/README.md b/test/e2e/README.md index f763a78c52e..439feb8ec97 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1561,6 +1561,16 @@ run, restart survival, credential non-exposure, and removal in one sandbox. After replacing plugin v1 with v2, it restarts through the native gateway command and invokes the updated tool through the running gateway. A separate CLI inspection cannot prove that the gateway discarded its cached plugin code. +Each fixture version registers a distinct, no-argument local tool. A normal +agent turn exercises admission and execution; metadata-only audit records must +pair a successful completion with a start for the same run, tool, and call. +This avoids assertions on weather fields, tool arguments, or reply wording. +The audit read polls at most five times, one second apart, for asynchronous +persistence; it never repeats the agent turn. Existing admin approval grants +access to the audit command. Execution of each version's distinct tool proves +installation and replacement; JSON plugin inventory proves removal. Those +postconditions replace redundant install and uninstall exit checks. The same +checks run for source installs and baked Launchables. `rebuild-openclaw` proves a user-installed native plugin survives rebuild with no NemoClaw ownership metadata. On the pinned Docker runtime it then kills the exact test-owned container, observes `Error`, and requires a different container to restore both the workspace and diff --git a/test/e2e/fixtures/native-plugin-evidence.ts b/test/e2e/fixtures/native-plugin-evidence.ts new file mode 100644 index 00000000000..f3b02698ad3 --- /dev/null +++ b/test/e2e/fixtures/native-plugin-evidence.ts @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isObjectRecord } from "../../../src/lib/core/json-types.ts"; +import { shellQuote } from "../../../src/lib/core/shell-quote.ts"; +import { + openClawFinalAgentResponse, + parseOpenClawJsonDocuments, + projectOpenClawAgentCompletion, +} from "../../../src/lib/openclaw/agent-json-provenance.ts"; + +export type NativePluginVersion = "v1" | "v2"; +export const NATIVE_PLUGIN_ID = "nemoclaw-e2e-tool"; +export const nativeToolName = (version: NativePluginVersion) => `nemoclaw_e2e_check_${version}`; + +export function nativePluginWriteScript(version: NativePluginVersion): string { + const toolName = nativeToolName(version); + const packageJson = JSON.stringify({ + name: "@nemoclaw/e2e-native-tool", + version: version === "v1" ? "1.0.0" : "2.0.0", + type: "module", + main: "index.js", + files: ["index.js", "openclaw.plugin.json"], + openclaw: { extensions: ["./index.js"] }, + peerDependencies: { openclaw: ">=2026.7.1" }, + }); + const manifest = JSON.stringify({ + id: NATIVE_PLUGIN_ID, + name: "NemoClaw E2E Tool", + version: version === "v1" ? "1.0.0" : "2.0.0", + description: "Dependency-free native plugin lifecycle fixture", + activation: { onStartup: true }, + contracts: { tools: [toolName] }, + configSchema: { + type: "object", + properties: {}, + additionalProperties: false, + }, + }); + const entrypoint = `const plugin = { + id: ${JSON.stringify(NATIVE_PLUGIN_ID)}, + name: "NemoClaw E2E Tool", + version: ${JSON.stringify(version === "v1" ? "1.0.0" : "2.0.0")}, + description: "Dependency-free native plugin lifecycle fixture", + register(api) { + api.registerTool({ + name: ${JSON.stringify(toolName)}, + label: "Run Local Check", + description: "Complete a local check without accessing files or the network.", + parameters: { + type: "object", + properties: {}, + additionalProperties: false, + }, + async execute() { + return { content: [{ type: "text", text: "Local check completed." }] }; + }, + }); + }, +}; +export default plugin; +`; + return [ + "set -eu", + "source_dir=/sandbox/e2e-native-tool", + 'rm -rf -- "$source_dir"', + 'mkdir -p -- "$source_dir"', + `printf '%s' ${shellQuote(packageJson)} > "$source_dir/package.json"`, + `printf '%s' ${shellQuote(manifest)} > "$source_dir/openclaw.plugin.json"`, + `printf '%s' ${shellQuote(entrypoint)} > "$source_dir/index.js"`, + 'HOME=/sandbox openclaw plugins install --force --accept-capabilities "$source_dir"', + ].join("\n"); +} + +/** Read the gateway envelope, never a run identifier in model or tool output. */ +export function completedAgentRunId(raw: string): string { + const documents = parseOpenClawJsonDocuments(raw); + const final = openClawFinalAgentResponse(documents); + const completion = projectOpenClawAgentCompletion(documents); + const runId = final?.document.runId; + if ( + !completion.runCompleted || + completion.aborted || + completion.errorPresent || + typeof runId !== "string" || + !/^[a-zA-Z0-9_-]{1,128}$/u.test(runId) + ) { + throw new Error("Native plugin agent turn has no completed gateway run"); + } + return runId; +} + +export function nativePluginPresent(raw: string, pluginId: string): boolean { + const documents = parseOpenClawJsonDocuments(raw); + const document = documents.length === 1 ? documents[0] : undefined; + if ( + !isObjectRecord(document) || + !Array.isArray(document.plugins) || + !document.plugins.every((plugin) => isObjectRecord(plugin) && typeof plugin.id === "string") + ) + throw new Error("Native plugin inventory is invalid"); + return document.plugins.some((plugin) => isObjectRecord(plugin) && plugin.id === pluginId); +} + +/** Correlate metadata-only audit records from one run; tool payloads are irrelevant. */ +export function nativeToolCallOutcome( + raw: string, + runId: string, + toolName: string, +): "pending" | "succeeded" | "failed" { + const documents = parseOpenClawJsonDocuments(raw); + const document = documents.length === 1 ? documents[0] : undefined; + if ( + !isObjectRecord(document) || + !Array.isArray(document.events) || + document.events.length > 100 || + document.nextCursor !== undefined || + !document.events.every(isObjectRecord) + ) { + throw new Error("Native plugin audit page is invalid or incomplete"); + } + const calls = new Map(); + for (const event of document.events) { + if (event.runId !== runId || event.toolName !== toolName) continue; + if ( + event.kind !== "tool_action" || + typeof event.toolCallId !== "string" || + !event.toolCallId.trim() + ) { + return "failed"; + } + const call = calls.get(event.toolCallId) ?? { started: false, finished: false }; + if (event.action === "tool.action.started" && event.status === "started" && !call.started) { + call.started = true; + } else if ( + event.action === "tool.action.finished" && + event.status === "succeeded" && + !call.finished + ) { + call.finished = true; + } else { + return "failed"; + } + calls.set(event.toolCallId, call); + } + return calls.size > 0 && [...calls.values()].every((call) => call.started && call.finished) + ? "succeeded" + : "pending"; +} diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index f6453c33e8f..245f12a53eb 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -3,6 +3,7 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import fs from "node:fs"; +import { randomUUID } from "node:crypto"; import { buildSandboxInferenceChatCommand } from "../fixtures/inference-adapter.ts"; import os from "node:os"; import path from "node:path"; @@ -63,6 +64,15 @@ import { FULL_E2E_TEST_TIMEOUT_MS } from "../../../tools/e2e/full-e2e-timeout-co import { parseOpenClawJsonDocuments } from "../../../src/lib/openclaw/agent-json-provenance.ts"; import { fullE2eGateway, withOwnedFullE2eGateway } from "../fixtures/full-e2e-gateway.ts"; import { captureNativePluginFailureReadiness } from "../fixtures/native-plugin-failure-diagnostics.ts"; +import { + completedAgentRunId, + nativePluginPresent, + nativeToolCallOutcome, + NATIVE_PLUGIN_ID, + nativeToolName, + nativePluginWriteScript, + type NativePluginVersion, +} from "../fixtures/native-plugin-evidence.ts"; import { cleanupAcquiredResource, cleanupWhenOpenShellAvailable, @@ -219,99 +229,49 @@ async function waitForSandboxStatus(host: HostCliClient): Promise=2026.7.1" }, - }); - const manifest = JSON.stringify({ - id: "weather", - name: "NemoClaw Native Weather", - version: version === "v1" ? "1.0.0" : "2.0.0", - description: "Dependency-free native plugin lifecycle fixture", - activation: { onStartup: true }, - contracts: { tools: ["get_weather"] }, - configSchema: { - type: "object", - properties: {}, - additionalProperties: false, - }, - }); - const entrypoint = `const plugin = { - id: "weather", - name: "NemoClaw Native Weather", - version: ${JSON.stringify(version === "v1" ? "1.0.0" : "2.0.0")}, - description: "Dependency-free native plugin lifecycle fixture", - register(api) { - api.registerTool({ - name: "get_weather", - label: "Get Weather", - description: "Return deterministic weather data.", - parameters: { - type: "object", - properties: { location: { type: "string" } }, - required: ["location"], - additionalProperties: false, - }, - async execute(_toolCallId, params) { - const details = { - location: String(params.location), - condition: "clear", - fixtureVersion: ${JSON.stringify(version)}, - }; - return { content: [{ type: "text", text: JSON.stringify(details) }], details }; - }, - }); - }, -}; -export default plugin; -`; - return [ - "set -eu", - "source_dir=/sandbox/e2e-native-weather", - 'rm -rf -- "$source_dir"', - 'mkdir -p -- "$source_dir"', - `printf '%s' ${shellQuote(packageJson)} > "$source_dir/package.json"`, - `printf '%s' ${shellQuote(manifest)} > "$source_dir/openclaw.plugin.json"`, - `printf '%s' ${shellQuote(entrypoint)} > "$source_dir/index.js"`, - 'HOME=/sandbox openclaw plugins install --force --accept-capabilities "$source_dir"', - ].join("\n"); -} - -/** Invoke the installed native weather plugin and verify its versioned response. */ -async function invokeNativeWeatherPlugin( +/** Exercise the plugin through normal agent admission and inspect host-owned execution records. */ +async function invokeNativePlugin( sandbox: SandboxClient, version: NativePluginVersion, artifactName: string, ): Promise { - const result = await sandbox.execShell( + const toolName = nativeToolName(version); + const result = await sandbox.exec( SANDBOX_NAME, - trustedSandboxShellScript( - `. /tmp/nemoclaw-proxy-env.sh && printf 'header = "Authorization: Bearer %s"\\n' "$OPENCLAW_GATEWAY_TOKEN" | curl --noproxy '*' --max-time 30 --silent --show-error --fail-with-body --config - -H 'Content-Type: application/json' --data '{"agentId":"main","tool":"get_weather","args":{"location":"Santa Clara"}}' "http://127.0.0.1:\${OPENCLAW_GATEWAY_PORT:-18789}/tools/invoke"`, - ), - { artifactName, env: env(), timeoutMs: 60_000 }, + [ + "openclaw", + "agent", + "--agent", + "main", + "--json", + "--thinking", + "off", + "--session-id", + `e2e-plugin-${randomUUID()}`, + "-m", + `Run the local ${toolName} tool once with no arguments.`, + ], + { artifactName, env: env(), timeoutMs: FIRST_TURN_TIMEOUT_MS }, ); await captureNativePluginFailureReadiness(sandbox, result, SANDBOX_NAME, artifactName, env()); - const document = parseOpenClawJsonDocuments(result.stdout)[0] as - | { - ok?: boolean; - result?: { details?: { fixtureVersion?: string; location?: string } }; - } - | undefined; - expect( - result.exitCode === 0 && - document?.ok === true && - document.result?.details?.fixtureVersion === version && - document.result.details.location === "Santa Clara", - resultText(result), - ).toBe(true); + expect(result.exitCode, resultText(result)).toBe(0); + const runId = completedAgentRunId(result.stdout); + // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. + const audit = await pollUntil({ + artifactPrefix: `${artifactName}-audit`, + attempts: 5, + delayMs: 1_000, + probe: async (_attempt, auditArtifact) => { + const page = await sandbox.exec( + SANDBOX_NAME, + ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], + { artifactName: auditArtifact, env: env(), timeoutMs: 30_000 }, + ); + return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; + }, + accept: (outcome) => outcome !== "pending", + }); + expect(audit.value, "the plugin tool must start and succeed in this agent run").toBe("succeeded"); } async function exerciseNativeOpenClawPluginVersion( @@ -319,16 +279,16 @@ async function exerciseNativeOpenClawPluginVersion( sandbox: SandboxClient, version: NativePluginVersion, ): Promise { - const install = await sandbox.execShell( + await sandbox.execShell( SANDBOX_NAME, - trustedSandboxShellScript(nativeWeatherPluginWriteScript(version)), + trustedSandboxShellScript(nativePluginWriteScript(version)), { artifactName: `phase-4-native-plugin-install-${version}`, env: env(), timeoutMs: 120_000, }, ); - expect(install.exitCode, resultText(install)).toBe(0); + // Successful execution of this version's distinct tool proves installation. const restartArtifact = `phase-4-native-plugin-gateway-restart-${version}`; const restart = await repoNemoclaw( host, @@ -339,7 +299,7 @@ async function exerciseNativeOpenClawPluginVersion( ); await captureNativePluginFailureReadiness(sandbox, restart, SANDBOX_NAME, restartArtifact, env()); expect(restart.exitCode, resultText(restart)).toBe(0); - await invokeNativeWeatherPlugin(sandbox, version, `phase-4-native-plugin-invoke-${version}`); + await invokeNativePlugin(sandbox, version, `phase-4-native-plugin-invoke-${version}`); } async function exerciseNativeOpenClawPluginLifecycle( @@ -351,7 +311,7 @@ async function exerciseNativeOpenClawPluginLifecycle( const updateDryRun = await sandbox.exec( SANDBOX_NAME, - ["/usr/local/bin/openclaw", "plugins", "update", "weather", "--dry-run"], + ["/usr/local/bin/openclaw", "plugins", "update", NATIVE_PLUGIN_ID, "--dry-run"], { artifactName: "phase-4-native-plugin-update-dry-run", env: env(), @@ -379,28 +339,26 @@ async function exerciseNativeOpenClawPluginLifecycle( ); expect(selfUpdateDryRun.exitCode, resultText(selfUpdateDryRun)).toBe(0); - const uninstall = await sandbox.exec( + await sandbox.exec( SANDBOX_NAME, - ["/usr/local/bin/openclaw", "plugins", "uninstall", "weather", "--force"], + ["/usr/local/bin/openclaw", "plugins", "uninstall", NATIVE_PLUGIN_ID, "--force"], { artifactName: "phase-4-native-plugin-uninstall", env: env(), timeoutMs: 120_000, }, ); - expect(uninstall.exitCode, resultText(uninstall)).toBe(0); const absent = await sandbox.exec( SANDBOX_NAME, - ["/usr/local/bin/openclaw", "plugins", "inspect", "weather", "--json"], + ["/usr/local/bin/openclaw", "plugins", "list", "--json"], { artifactName: "phase-4-native-plugin-absent", env: env(), timeoutMs: 30_000, }, ); - expect(`exit=${absent.exitCode}\n${resultText(absent)}`).toMatch( - /^exit=1\n[\s\S]*(?:weather.*(?:not found|unknown)|(?:not found|unknown).*weather)/iu, - ); + expect(absent.exitCode, resultText(absent)).toBe(0); + expect(nativePluginPresent(absent.stdout, NATIVE_PLUGIN_ID)).toBe(false); } async function inspectNativeNetwork(sandbox: SandboxClient, artifactName: string) { diff --git a/test/e2e/support/native-plugin-evidence.test.ts b/test/e2e/support/native-plugin-evidence.test.ts new file mode 100644 index 00000000000..1dc44193da4 --- /dev/null +++ b/test/e2e/support/native-plugin-evidence.test.ts @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + completedAgentRunId, + nativePluginPresent, + nativeToolCallOutcome, +} from "../fixtures/native-plugin-evidence.ts"; + +const runId = "new-agent-run"; +const toolName = "arbitrary_fixture_tool"; +const event = (action: string, status: string, extra: Record = {}) => ({ + kind: "tool_action", + runId, + toolName, + toolCallId: "call-1", + action, + status, + ...extra, +}); +const started = event("tool.action.started", "started"); +const finished = event("tool.action.finished", "succeeded"); +const page = (events: unknown[]) => JSON.stringify({ events }); + +describe("native plugin execution evidence", () => { + it("accepts a matched successful execution without reading the tool payload", () => { + expect(nativeToolCallOutcome(page([started, finished]), runId, toolName)).toBe("succeeded"); + }); + + it("matches another fixture tool without a domain-specific response contract", () => { + const name = "different_tool"; + const events = [finished, started].map((entry) => ({ ...entry, toolName: name })); + expect(nativeToolCallOutcome(page(events), runId, name)).toBe("succeeded"); + }); + + it.each(["blocked", "failed", "cancelled", "timed_out", "unknown"])( + "rejects a terminal %s outcome even when another call succeeds", + (status) => { + const rejected = event("tool.action.finished", status, { toolCallId: "call-2" }); + expect(nativeToolCallOutcome(page([started, finished, rejected]), runId, toolName)).toBe( + "failed", + ); + }, + ); + + it.each([ + [], + [started], + [finished], + [started, { ...finished, toolCallId: "other-call" }], + [started, { ...finished, runId: "old-run" }], + [started, { ...finished, toolName: "unrelated-tool" }], + [ + { ...started, runId: "old-run" }, + { ...finished, runId: "old-run" }, + ], + ])("does not qualify missing or unmatched execution records: %j", (...events) => { + expect(nativeToolCallOutcome(page(events), runId, toolName)).toBe("pending"); + }); + + it.each([ + [started, started, finished], + [started, finished, finished], + [{ ...started, toolCallId: "" }, finished], + [started, { ...finished, kind: "agent_run" }], + [started, { ...finished, action: "unexpected" }], + ])("rejects inconsistent execution records: %j", (...events) => { + expect(nativeToolCallOutcome(page(events), runId, toolName)).toBe("failed"); + }); + + it.each([ + "not JSON", + "{}", + '{"events":[null]}', + JSON.stringify({ events: [started, finished], nextCursor: "more" }), + page(Array.from({ length: 101 }, () => started)), + ])("rejects invalid or incomplete audit pages: %s", (raw) => { + expect(() => nativeToolCallOutcome(raw, runId, toolName)).toThrow("invalid or incomplete"); + }); +}); + +describe("native plugin inventory", () => { + it("reports absence only from a valid inventory without the plugin", () => { + expect(nativePluginPresent('{"plugins":[]}', "fixture")).toBe(false); + expect(nativePluginPresent('{"plugins":[{"id":"other","version":"1"}]}', "fixture")).toBe( + false, + ); + }); + + it("does not mistake a disabled installed plugin for an uninstalled plugin", () => { + expect( + nativePluginPresent( + '{"plugins":[{"id":"fixture","version":"1","enabled":false}]}', + "fixture", + ), + ).toBe(true); + }); + + it.each(["{}", '{"plugins":[null]}', '{"plugins":[{}]}'])( + "rejects malformed plugin inventory: %s", + (raw) => { + expect(() => nativePluginPresent(raw, "fixture")).toThrow(); + }, + ); +}); + +describe("agent run correlation", () => { + const envelope = { + runId, + status: "ok", + summary: "completed", + result: { payloads: [], meta: {} }, + }; + it("uses the completed gateway envelope instead of model-provided run identifiers", () => { + expect( + completedAgentRunId( + JSON.stringify({ + ...envelope, + result: { + payloads: [{ text: '{"runId":"invented"}' }], + meta: {}, + }, + }), + ), + ).toBe(runId); + }); + + it.each([ + {}, + { ...envelope, runId: undefined }, + { ...envelope, status: "error" }, + { ...envelope, summary: "running" }, + { ...envelope, runId: "unbounded ".repeat(100) }, + { ...envelope, result: { payloads: [], meta: { aborted: true } } }, + { ...envelope, result: { payloads: [], meta: { error: "failed" } } }, + ])("rejects an incomplete or unidentified agent run: %j", (value) => { + expect(() => completedAgentRunId(JSON.stringify(value))).toThrow("no completed gateway run"); + }); +}); From c64b2256e402f6bd358c37971b1aca9b042125bd Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 3 Nov 2026 08:08:38 -0800 Subject: [PATCH 2/5] test(e2e): register native plugin evidence coverage Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- test/e2e/mock-parity.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 33cb0386043..68a1cf7f696 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -251,7 +251,8 @@ "test/e2e/live/sandbox-credential-boundary.ts", "test/e2e/live/openclaw-admin-scope.ts", "test/e2e/fixtures/admin-approval-connect.ts", - "test/e2e/fixtures/admin-approval-connect.sh" + "test/e2e/fixtures/admin-approval-connect.sh", + "test/e2e/fixtures/native-plugin-evidence.ts" ], "fast": [ "src/lib/onboard/gateway-host-runtime.test.ts", @@ -264,6 +265,7 @@ "test/e2e/support/full-e2e-inference-probe.test.ts", "test/e2e/support/full-e2e-native-model.test.ts", "test/e2e/support/full-e2e-gateway.test.ts", + "test/e2e/support/native-plugin-evidence.test.ts", "test/e2e/support/launch-agent-turn-provider-availability.test.ts", "test/e2e/support/launch-agent-turn-session-evidence.test.ts", "test/e2e/support/launch-agent-turn.test.ts", From 61776c5eac40294e19c7a4bbdf7829f31c723c36 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 3 Nov 2026 08:58:52 -0800 Subject: [PATCH 3/5] fix(e2e): run the survival plugin through an agent turn The OpenShell stop and start lane called the native plugin tool through the gateway tools/invoke endpoint. That direct call has no owned agent turn, so the web search guard now blocks it with tool_call_blocked, and the lane failed on main run 41581151938 after the restart had already preserved the sandbox state. Run the shared native plugin fixture through a normal agent turn after start and require host audit records that pair a start and a success for that run and tool. Approve the admin scope first so the audit read is allowed, and bound the agent turn inside the final validation budget. Drop the baseline echo probe, since the native readiness poll already needs a working sandbox exec, and lower the assertion budget to match. The search guard stays unchanged. Refs #13594 Signed-off-by: Deepak Jain --- ci/e2e-assertion-budget.json | 18 +-- test/e2e/live/sandbox-survival.test.ts | 151 +++++++----------- .../e2e/sandbox-survival-timeout-contract.mts | 1 + 3 files changed, 70 insertions(+), 100 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index db6d27a02f9..7b383b3c43f 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 189, "direct": { - "expectCalls": 1285, - "matcherAssertions": 1265, + "expectCalls": 1284, + "matcherAssertions": 1264, "nodeAssertions": 109, - "namedAssertionHelpers": 423, + "namedAssertionHelpers": 422, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2031, + "assertionPoints": 2029, "generatedProbeBlocks": 89, "generatedProbeConditions": 212 }, "unique": { - "expectCalls": 1715, - "matcherAssertions": 1690, + "expectCalls": 1714, + "matcherAssertions": 1689, "nodeAssertions": 132, - "namedAssertionHelpers": 669, + "namedAssertionHelpers": 668, "failCalls": 1, "throwGuards": 531, "objectFieldAssertions": 266, - "assertionPoints": 3289, + "assertionPoints": 3287, "generatedProbeBlocks": 218, "generatedProbeConditions": 724 }, @@ -112,7 +112,7 @@ "test/e2e/live/registry-targets.test.ts": [2,4,5,24,0], "test/e2e/live/sandbox-operations.test.ts": [2,11,9,50,6], "test/e2e/live/sandbox-rlimits-connect.test.ts": [1,1,1,1,0], - "test/e2e/live/sandbox-survival.test.ts": [4,11,4,11,0], + "test/e2e/live/sandbox-survival.test.ts": [3,9,4,10,0], "test/e2e/live/sessions-agents-cli.test.ts": [19,28,20,31,0], "test/e2e/live/skill-agent.test.ts": [7,9,8,10,0], "test/e2e/live/snapshot-commands.test.ts": [5,5,5,5,0], diff --git a/test/e2e/live/sandbox-survival.test.ts b/test/e2e/live/sandbox-survival.test.ts index 5045b497b34..9006d9cbd62 100644 --- a/test/e2e/live/sandbox-survival.test.ts +++ b/test/e2e/live/sandbox-survival.test.ts @@ -8,11 +8,10 @@ * arbitrary native home/workspace state. */ +import { randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; -import { shellQuote } from "../../../src/lib/core/shell-quote.ts"; -import { parseOpenClawJsonDocuments } from "../../../src/lib/openclaw/agent-json-provenance.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { SANDBOX_SURVIVAL_FINAL_DESTROY_TIMEOUT_MS, @@ -20,6 +19,7 @@ import { SANDBOX_SURVIVAL_INSTALL_TIMEOUT_MS, SANDBOX_SURVIVAL_LIFECYCLE_READINESS, SANDBOX_SURVIVAL_MARKER_PATHS, + SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, SANDBOX_SURVIVAL_NATIVE_READINESS, SANDBOX_SURVIVAL_OPENSHELL_DELETE_TIMEOUT_MS, SANDBOX_SURVIVAL_POST_DESTROY_LIST_TIMEOUT_MS, @@ -32,14 +32,22 @@ import { assertExitZero, outputContainsSandbox, resultText, + type SandboxClient, sandboxAccessEnv, } from "../fixtures/clients/index.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; +import { + completedAgentRunId, + nativePluginWriteScript, + nativeToolCallOutcome, + nativeToolName, +} from "../fixtures/native-plugin-evidence.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; import type { NemoClawInstance } from "../fixtures/phases/index.ts"; import type { SandboxMarker } from "../fixtures/phases/state-validation.ts"; import { pollUntil } from "../fixtures/polling.ts"; +import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-survival"; const DASHBOARD_PORT = Number(process.env.NEMOCLAW_DASHBOARD_PORT ?? "18789"); @@ -57,21 +65,6 @@ function installEnv(hostedEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv { }; } -async function expectSandboxExecAlive( - sandboxName: string, - exec: ( - script: string, - artifactName: string, - ) => Promise<{ stdout: string; stderr: string; exitCode: number | null }>, - artifactName: string, -): Promise { - const alive = await exec("echo alive", artifactName); - expect( - alive.exitCode === 0 && alive.stdout.trim() === "alive", - `${sandboxName} exec failed: ${resultText(alive)}`, - ).toBe(true); -} - async function waitForNativeAgentReady( exec: ( script: string, @@ -93,75 +86,47 @@ async function waitForNativeAgentReady( }); } -function nativeSurvivalPluginInstallScript(): string { - const packageJson = JSON.stringify({ - name: "@nemoclaw/e2e-survival-plugin", - version: "1.0.0", - type: "module", - main: "index.js", - files: ["index.js", "openclaw.plugin.json"], - openclaw: { extensions: ["./index.js"] }, - peerDependencies: { openclaw: ">=2026.7.1" }, - }); - const manifest = JSON.stringify({ - id: "e2e-survival-plugin", - name: "E2E Survival Plugin", - version: "1.0.0", - description: "Native stop/start persistence fixture", - activation: { onStartup: true }, - contracts: { tools: ["survival_probe"] }, - configSchema: { type: "object", properties: {}, additionalProperties: false }, - }); - const entrypoint = `const plugin = { - id: "e2e-survival-plugin", - name: "E2E Survival Plugin", - version: "1.0.0", - register(api) { - api.registerTool({ - name: "survival_probe", - label: "Survival Probe", - description: "Prove a native plugin remains executable after OpenShell stop/start.", - parameters: { type: "object", properties: {}, additionalProperties: false }, - async execute() { - const details = { survived: true }; - return { content: [{ type: "text", text: JSON.stringify(details) }], details }; - }, - }); - }, -}; -export default plugin; -`; - return [ - "set -eu", - "source_dir=/sandbox/e2e-survival-plugin-source", - 'rm -rf -- "$source_dir"', - 'mkdir -p -- "$source_dir"', - `printf '%s' ${shellQuote(packageJson)} > "$source_dir/package.json"`, - `printf '%s' ${shellQuote(manifest)} > "$source_dir/openclaw.plugin.json"`, - `printf '%s' ${shellQuote(entrypoint)} > "$source_dir/index.js"`, - 'HOME=/sandbox openclaw plugins install --force --accept-capabilities "$source_dir"', - ].join("\n"); -} - -async function expectNativeSurvivalPluginInvocation( - exec: ( - script: string, - artifactName: string, - ) => Promise<{ stdout: string; stderr: string; exitCode: number | null }>, -): Promise { - const invocation = await exec( - `. /tmp/nemoclaw-proxy-env.sh && printf 'header = "Authorization: Bearer %s"\\n' "$OPENCLAW_GATEWAY_TOKEN" | curl --noproxy '*' --max-time 30 --silent --show-error --fail-with-body --config - -H 'Content-Type: application/json' --data '{"agentId":"main","tool":"survival_probe","args":{}}' "http://127.0.0.1:\${OPENCLAW_GATEWAY_PORT:-18789}/tools/invoke"`, - "post-openshell-start-native-plugin-invoke", +/** Exercise the plugin through normal agent admission and inspect host-owned execution records. */ +async function expectNativeSurvivalPluginInvocation(sandbox: SandboxClient): Promise { + const toolName = nativeToolName("v1"); + const turn = await sandbox.exec( + SANDBOX_NAME, + [ + "openclaw", + "agent", + "--agent", + "main", + "--json", + "--thinking", + "off", + "--session-id", + `e2e-plugin-${randomUUID()}`, + "-m", + `Run the local ${toolName} tool once with no arguments.`, + ], + { + artifactName: "post-openshell-start-native-plugin-invoke", + env: sandboxAccessEnv(), + timeoutMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, + }, ); - const document = parseOpenClawJsonDocuments(invocation.stdout)[0] as - | { ok?: boolean; result?: { details?: { survived?: boolean } } } - | undefined; - expect( - invocation.exitCode === 0 && - document?.ok === true && - document.result?.details?.survived === true, - resultText(invocation), - ).toBe(true); + const runId = completedAgentRunId(turn.stdout); + // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. + const audit = await pollUntil({ + artifactPrefix: "post-openshell-start-native-plugin-invoke-audit", + attempts: 5, + delayMs: 1_000, + probe: async (_attempt, artifactName) => { + const page = await sandbox.exec( + SANDBOX_NAME, + ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], + { artifactName, env: sandboxAccessEnv(), timeoutMs: 30_000 }, + ); + return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; + }, + accept: (outcome) => outcome !== "pending", + }); + expect(audit.value, "the plugin tool must start and succeed in this agent run").toBe("succeeded"); } test( @@ -318,7 +283,6 @@ test( }); progress.phase("prove baseline sandbox access and native agent readiness"); - await expectSandboxExecAlive(SANDBOX_NAME, execShell, "baseline-sandbox-exec-alive"); await waitForNativeAgentReady(execShell, "baseline-native-agent-ready", DASHBOARD_PORT); progress.phase("write persistent OpenClaw markers"); @@ -330,10 +294,7 @@ test( await stateValidation.writeSandboxMarkers(instance, markers); await stateValidation.expectSandboxMarkers(instance, markers, "pre-restart-marker-read"); progress.phase("install a native OpenClaw plugin package"); - await execShell( - nativeSurvivalPluginInstallScript(), - "pre-openshell-stop-native-plugin-install", - ); + await execShell(nativePluginWriteScript("v1"), "pre-openshell-stop-native-plugin-install"); progress.phase("stop the sandbox through OpenShell"); const stop = await sandbox.openshell(["sandbox", "stop", "-g", "nemoclaw", SANDBOX_NAME], { @@ -364,7 +325,15 @@ test( markers, "post-openshell-start-marker-read", ); - await expectNativeSurvivalPluginInvocation(execShell); + await approveOpenClawAdminScope( + host, + sandbox, + SANDBOX_NAME, + { ...buildAvailabilityProbeEnv(), ...hosted.env }, + [apiKey], + false, + ); + await expectNativeSurvivalPluginInvocation(sandbox); progress.phase("destroy the sandbox"); await sandbox.cleanupSandbox(SANDBOX_NAME, { diff --git a/tools/e2e/sandbox-survival-timeout-contract.mts b/tools/e2e/sandbox-survival-timeout-contract.mts index 19b882dae15..e62b5188c0e 100644 --- a/tools/e2e/sandbox-survival-timeout-contract.mts +++ b/tools/e2e/sandbox-survival-timeout-contract.mts @@ -33,6 +33,7 @@ export const SANDBOX_SURVIVAL_PREREQUISITE_TIMEOUT_MS = 30_000; export const SANDBOX_SURVIVAL_SANDBOX_LIFECYCLE_TIMEOUT_MS = 2 * MINUTE_MS; export const SANDBOX_SURVIVAL_FINAL_DESTROY_TIMEOUT_MS = 2 * MINUTE_MS; export const SANDBOX_SURVIVAL_POST_DESTROY_LIST_TIMEOUT_MS = MINUTE_MS; +export const SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS = 2 * MINUTE_MS; export const SANDBOX_SURVIVAL_NATIVE_READINESS_POLLS = 2; export const SANDBOX_SURVIVAL_LIFECYCLE_READINESS_POLLS = 1; From 5057fd4fc11820f3632c5f81d6bc9e256098e828 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 3 Nov 2026 10:38:30 -0800 Subject: [PATCH 4/5] test(e2e): budget the survival plugin agent turn The final validation phase already used its whole 15 minute budget for marker reads and destroy. The admin approval, the agent turn and the audit polls added after start need their own ceilings, so name them in the timeout contract, raise the phase budget to 30 minutes, and check the sum in the contract test. Map that test to the survival lane. Refs #13594 Signed-off-by: Deepak Jain --- test/e2e/live/sandbox-survival.test.ts | 11 ++++++++--- test/e2e/mock-parity.json | 1 + .../support/sandbox-survival-timeout-contract.test.ts | 10 +++++++++- tools/e2e/sandbox-survival-timeout-contract.mts | 9 ++++++++- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/test/e2e/live/sandbox-survival.test.ts b/test/e2e/live/sandbox-survival.test.ts index 9006d9cbd62..225b390bfab 100644 --- a/test/e2e/live/sandbox-survival.test.ts +++ b/test/e2e/live/sandbox-survival.test.ts @@ -19,6 +19,7 @@ import { SANDBOX_SURVIVAL_INSTALL_TIMEOUT_MS, SANDBOX_SURVIVAL_LIFECYCLE_READINESS, SANDBOX_SURVIVAL_MARKER_PATHS, + SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT, SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, SANDBOX_SURVIVAL_NATIVE_READINESS, SANDBOX_SURVIVAL_OPENSHELL_DELETE_TIMEOUT_MS, @@ -114,13 +115,17 @@ async function expectNativeSurvivalPluginInvocation(sandbox: SandboxClient): Pro // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. const audit = await pollUntil({ artifactPrefix: "post-openshell-start-native-plugin-invoke-audit", - attempts: 5, - delayMs: 1_000, + attempts: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.attempts, + delayMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.delayMs, probe: async (_attempt, artifactName) => { const page = await sandbox.exec( SANDBOX_NAME, ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], - { artifactName, env: sandboxAccessEnv(), timeoutMs: 30_000 }, + { + artifactName, + env: sandboxAccessEnv(), + timeoutMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.timeoutMs, + }, ); return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; }, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 68a1cf7f696..8781c091689 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -1047,6 +1047,7 @@ { "live": "test/e2e/live/sandbox-survival.test.ts", "fast": [ + "test/e2e/support/sandbox-survival-timeout-contract.test.ts", "src/lib/onboard/machine/finalization-deps.test.ts", "src/lib/actions/sandbox/destroy-flow.test.ts", "test/agents/native-gateway-lifecycle.test.ts", diff --git a/test/e2e/support/sandbox-survival-timeout-contract.test.ts b/test/e2e/support/sandbox-survival-timeout-contract.test.ts index 10b12618734..f3dd4042636 100644 --- a/test/e2e/support/sandbox-survival-timeout-contract.test.ts +++ b/test/e2e/support/sandbox-survival-timeout-contract.test.ts @@ -4,12 +4,15 @@ import { describe, expect, it } from "vitest"; import { + SANDBOX_SURVIVAL_ADMIN_APPROVAL_TIMEOUT_MS, SANDBOX_SURVIVAL_FINAL_DESTROY_TIMEOUT_MS, SANDBOX_SURVIVAL_FINAL_VALIDATION_BUDGET_MS, SANDBOX_SURVIVAL_INSTALL_TIMEOUT_MS, SANDBOX_SURVIVAL_LIFECYCLE_BUDGET_MS, SANDBOX_SURVIVAL_LIFECYCLE_WORST_CASE_MS, SANDBOX_SURVIVAL_MARKER_PATHS, + SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT, + SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, SANDBOX_SURVIVAL_POST_DESTROY_LIST_TIMEOUT_MS, SANDBOX_SURVIVAL_POST_TEST_CLEANUP_BUDGET_MS, SANDBOX_SURVIVAL_PREPARATION_BUDGET_MS, @@ -47,7 +50,12 @@ describe("sandbox-survival timeout contract", () => { expect(SANDBOX_SURVIVAL_FINAL_VALIDATION_BUDGET_MS).toBeGreaterThanOrEqual( SANDBOX_SURVIVAL_FINAL_DESTROY_TIMEOUT_MS + SANDBOX_SURVIVAL_POST_DESTROY_LIST_TIMEOUT_MS + - SANDBOX_SURVIVAL_MARKER_PATHS.length * 3 * SANDBOX_MARKER_COMMAND_TIMEOUT_MS, + SANDBOX_SURVIVAL_MARKER_PATHS.length * 3 * SANDBOX_MARKER_COMMAND_TIMEOUT_MS + + SANDBOX_SURVIVAL_ADMIN_APPROVAL_TIMEOUT_MS + + SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS + + SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.attempts * + (SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.timeoutMs + + SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.delayMs), ); expect(SANDBOX_SURVIVAL_TEST_TIMEOUT_MS).toBe( SANDBOX_SURVIVAL_PREPARATION_BUDGET_MS + diff --git a/tools/e2e/sandbox-survival-timeout-contract.mts b/tools/e2e/sandbox-survival-timeout-contract.mts index e62b5188c0e..b2c0bfb48c0 100644 --- a/tools/e2e/sandbox-survival-timeout-contract.mts +++ b/tools/e2e/sandbox-survival-timeout-contract.mts @@ -33,7 +33,14 @@ export const SANDBOX_SURVIVAL_PREREQUISITE_TIMEOUT_MS = 30_000; export const SANDBOX_SURVIVAL_SANDBOX_LIFECYCLE_TIMEOUT_MS = 2 * MINUTE_MS; export const SANDBOX_SURVIVAL_FINAL_DESTROY_TIMEOUT_MS = 2 * MINUTE_MS; export const SANDBOX_SURVIVAL_POST_DESTROY_LIST_TIMEOUT_MS = MINUTE_MS; +// The shared admin approval waits up to 3 minutes for its trigger and 4 for approval. +export const SANDBOX_SURVIVAL_ADMIN_APPROVAL_TIMEOUT_MS = 7 * MINUTE_MS; export const SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS = 2 * MINUTE_MS; +export const SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT = { + attempts: 5, + delayMs: 1_000, + timeoutMs: 30_000, +} as const; export const SANDBOX_SURVIVAL_NATIVE_READINESS_POLLS = 2; export const SANDBOX_SURVIVAL_LIFECYCLE_READINESS_POLLS = 1; @@ -63,7 +70,7 @@ export const SANDBOX_SURVIVAL_LIFECYCLE_WORST_CASE_MS = export const SANDBOX_SURVIVAL_PREPARATION_BUDGET_MS = 30 * MINUTE_MS; export const SANDBOX_SURVIVAL_READINESS_BUDGET_MS = 15 * MINUTE_MS; export const SANDBOX_SURVIVAL_LIFECYCLE_BUDGET_MS = 10 * MINUTE_MS; -export const SANDBOX_SURVIVAL_FINAL_VALIDATION_BUDGET_MS = 15 * MINUTE_MS; +export const SANDBOX_SURVIVAL_FINAL_VALIDATION_BUDGET_MS = 30 * MINUTE_MS; export const SANDBOX_SURVIVAL_TEST_HEADROOM_MS = 5 * MINUTE_MS; export const SANDBOX_SURVIVAL_TEST_TIMEOUT_MS = From af654cd6640ff031e0f163acd16302dd83457aba Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 3 Nov 2026 14:04:58 -0800 Subject: [PATCH 5/5] test(e2e): share the native plugin agent turn and audit poll full-e2e and sandbox-survival each ran the same plugin agent turn, read the gateway run ID, and polled the same audit page. Move that sequence into the native plugin evidence fixture so both lanes use one contract. Each live test keeps its own assertion on the returned outcome. Signed-off-by: Deepak Jain --- ci/e2e-assertion-budget.json | 20 +++--- test/e2e/fixtures/native-plugin-evidence.ts | 59 +++++++++++++++++ test/e2e/live/full-e2e.test.ts | 50 +++----------- test/e2e/live/sandbox-survival.test.ts | 65 ++++--------------- test/e2e/mock-parity.json | 1 + .../support/native-plugin-evidence.test.ts | 60 +++++++++++++++++ 6 files changed, 151 insertions(+), 104 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 7b383b3c43f..534cd4e8a56 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 189, "direct": { - "expectCalls": 1284, - "matcherAssertions": 1264, + "expectCalls": 1283, + "matcherAssertions": 1263, "nodeAssertions": 109, - "namedAssertionHelpers": 422, + "namedAssertionHelpers": 421, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2029, + "assertionPoints": 2027, "generatedProbeBlocks": 89, "generatedProbeConditions": 212 }, "unique": { - "expectCalls": 1714, - "matcherAssertions": 1689, + "expectCalls": 1713, + "matcherAssertions": 1688, "nodeAssertions": 132, - "namedAssertionHelpers": 668, + "namedAssertionHelpers": 667, "failCalls": 1, "throwGuards": 531, "objectFieldAssertions": 266, - "assertionPoints": 3287, + "assertionPoints": 3285, "generatedProbeBlocks": 218, "generatedProbeConditions": 724 }, @@ -62,7 +62,7 @@ "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [46,51,46,51,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,8], + "test/e2e/live/full-e2e.test.ts": [26,29,27,59,8], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,27,1], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [9,19,16,58,12], @@ -112,7 +112,7 @@ "test/e2e/live/registry-targets.test.ts": [2,4,5,24,0], "test/e2e/live/sandbox-operations.test.ts": [2,11,9,50,6], "test/e2e/live/sandbox-rlimits-connect.test.ts": [1,1,1,1,0], - "test/e2e/live/sandbox-survival.test.ts": [3,9,4,10,0], + "test/e2e/live/sandbox-survival.test.ts": [3,8,4,9,0], "test/e2e/live/sessions-agents-cli.test.ts": [19,28,20,31,0], "test/e2e/live/skill-agent.test.ts": [7,9,8,10,0], "test/e2e/live/snapshot-commands.test.ts": [5,5,5,5,0], diff --git a/test/e2e/fixtures/native-plugin-evidence.ts b/test/e2e/fixtures/native-plugin-evidence.ts index f3b02698ad3..a5be2dc4c6c 100644 --- a/test/e2e/fixtures/native-plugin-evidence.ts +++ b/test/e2e/fixtures/native-plugin-evidence.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { randomUUID } from "node:crypto"; + import { isObjectRecord } from "../../../src/lib/core/json-types.ts"; import { shellQuote } from "../../../src/lib/core/shell-quote.ts"; import { @@ -8,6 +10,9 @@ import { parseOpenClawJsonDocuments, projectOpenClawAgentCompletion, } from "../../../src/lib/openclaw/agent-json-provenance.ts"; +import type { SandboxClient } from "./clients/sandbox.ts"; +import { captureNativePluginFailureReadiness } from "./native-plugin-failure-diagnostics.ts"; +import { pollUntil } from "./polling.ts"; export type NativePluginVersion = "v1" | "v2"; export const NATIVE_PLUGIN_ID = "nemoclaw-e2e-tool"; @@ -147,3 +152,57 @@ export function nativeToolCallOutcome( ? "succeeded" : "pending"; } + +export interface NativePluginInvocationOptions { + sandboxName: string; + version: NativePluginVersion; + artifactName: string; + env: NodeJS.ProcessEnv; + turnTimeoutMs: number; + audit: { attempts: number; delayMs: number; timeoutMs: number }; +} + +/** Exercise the plugin through normal agent admission and read host-owned execution records. */ +export async function nativePluginAgentInvocationOutcome( + sandbox: Pick, + options: NativePluginInvocationOptions, +): Promise<"pending" | "succeeded" | "failed"> { + const { sandboxName, artifactName, env } = options; + const toolName = nativeToolName(options.version); + const turn = await sandbox.exec( + sandboxName, + [ + "openclaw", + "agent", + "--agent", + "main", + "--json", + "--thinking", + "off", + "--session-id", + `e2e-plugin-${randomUUID()}`, + "-m", + `Run the local ${toolName} tool once with no arguments.`, + ], + { artifactName, env, timeoutMs: options.turnTimeoutMs }, + ); + await captureNativePluginFailureReadiness(sandbox, turn, sandboxName, artifactName, env); + if (turn.exitCode !== 0) return "failed"; + const runId = completedAgentRunId(turn.stdout); + // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. + const audit = await pollUntil({ + artifactPrefix: `${artifactName}-audit`, + attempts: options.audit.attempts, + delayMs: options.audit.delayMs, + probe: async (_attempt, auditArtifact) => { + const page = await sandbox.exec( + sandboxName, + ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], + { artifactName: auditArtifact, env, timeoutMs: options.audit.timeoutMs }, + ); + return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; + }, + accept: (outcome) => outcome !== "pending", + }); + return audit.value; +} diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 245f12a53eb..7302f81becd 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -3,7 +3,6 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import fs from "node:fs"; -import { randomUUID } from "node:crypto"; import { buildSandboxInferenceChatCommand } from "../fixtures/inference-adapter.ts"; import os from "node:os"; import path from "node:path"; @@ -65,11 +64,9 @@ import { parseOpenClawJsonDocuments } from "../../../src/lib/openclaw/agent-json import { fullE2eGateway, withOwnedFullE2eGateway } from "../fixtures/full-e2e-gateway.ts"; import { captureNativePluginFailureReadiness } from "../fixtures/native-plugin-failure-diagnostics.ts"; import { - completedAgentRunId, + nativePluginAgentInvocationOutcome, nativePluginPresent, - nativeToolCallOutcome, NATIVE_PLUGIN_ID, - nativeToolName, nativePluginWriteScript, type NativePluginVersion, } from "../fixtures/native-plugin-evidence.ts"; @@ -229,49 +226,20 @@ async function waitForSandboxStatus(host: HostCliClient): Promise { - const toolName = nativeToolName(version); - const result = await sandbox.exec( - SANDBOX_NAME, - [ - "openclaw", - "agent", - "--agent", - "main", - "--json", - "--thinking", - "off", - "--session-id", - `e2e-plugin-${randomUUID()}`, - "-m", - `Run the local ${toolName} tool once with no arguments.`, - ], - { artifactName, env: env(), timeoutMs: FIRST_TURN_TIMEOUT_MS }, - ); - await captureNativePluginFailureReadiness(sandbox, result, SANDBOX_NAME, artifactName, env()); - expect(result.exitCode, resultText(result)).toBe(0); - const runId = completedAgentRunId(result.stdout); - // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. - const audit = await pollUntil({ - artifactPrefix: `${artifactName}-audit`, - attempts: 5, - delayMs: 1_000, - probe: async (_attempt, auditArtifact) => { - const page = await sandbox.exec( - SANDBOX_NAME, - ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], - { artifactName: auditArtifact, env: env(), timeoutMs: 30_000 }, - ); - return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; - }, - accept: (outcome) => outcome !== "pending", + const outcome = await nativePluginAgentInvocationOutcome(sandbox, { + sandboxName: SANDBOX_NAME, + version, + artifactName, + env: env(), + turnTimeoutMs: FIRST_TURN_TIMEOUT_MS, + audit: { attempts: 5, delayMs: 1_000, timeoutMs: 30_000 }, }); - expect(audit.value, "the plugin tool must start and succeed in this agent run").toBe("succeeded"); + expect(outcome, "the plugin tool must start and succeed in this agent run").toBe("succeeded"); } async function exerciseNativeOpenClawPluginVersion( diff --git a/test/e2e/live/sandbox-survival.test.ts b/test/e2e/live/sandbox-survival.test.ts index 225b390bfab..b091494edce 100644 --- a/test/e2e/live/sandbox-survival.test.ts +++ b/test/e2e/live/sandbox-survival.test.ts @@ -8,7 +8,6 @@ * arbitrary native home/workspace state. */ -import { randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; @@ -33,16 +32,13 @@ import { assertExitZero, outputContainsSandbox, resultText, - type SandboxClient, sandboxAccessEnv, } from "../fixtures/clients/index.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { - completedAgentRunId, + nativePluginAgentInvocationOutcome, nativePluginWriteScript, - nativeToolCallOutcome, - nativeToolName, } from "../fixtures/native-plugin-evidence.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; import type { NemoClawInstance } from "../fixtures/phases/index.ts"; @@ -87,53 +83,6 @@ async function waitForNativeAgentReady( }); } -/** Exercise the plugin through normal agent admission and inspect host-owned execution records. */ -async function expectNativeSurvivalPluginInvocation(sandbox: SandboxClient): Promise { - const toolName = nativeToolName("v1"); - const turn = await sandbox.exec( - SANDBOX_NAME, - [ - "openclaw", - "agent", - "--agent", - "main", - "--json", - "--thinking", - "off", - "--session-id", - `e2e-plugin-${randomUUID()}`, - "-m", - `Run the local ${toolName} tool once with no arguments.`, - ], - { - artifactName: "post-openshell-start-native-plugin-invoke", - env: sandboxAccessEnv(), - timeoutMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, - }, - ); - const runId = completedAgentRunId(turn.stdout); - // Audit persistence is asynchronous. Poll only the read-only page, never replay the agent turn. - const audit = await pollUntil({ - artifactPrefix: "post-openshell-start-native-plugin-invoke-audit", - attempts: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.attempts, - delayMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.delayMs, - probe: async (_attempt, artifactName) => { - const page = await sandbox.exec( - SANDBOX_NAME, - ["openclaw", "audit", "--run", runId, "--kind", "tool_action", "--limit", "100", "--json"], - { - artifactName, - env: sandboxAccessEnv(), - timeoutMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT.timeoutMs, - }, - ); - return page.exitCode === 0 ? nativeToolCallOutcome(page.stdout, runId, toolName) : "failed"; - }, - accept: (outcome) => outcome !== "pending", - }); - expect(audit.value, "the plugin tool must start and succeed in this agent run").toBe("succeeded"); -} - test( "OpenShell stop/start preserves native agent state", { @@ -338,7 +287,17 @@ test( [apiKey], false, ); - await expectNativeSurvivalPluginInvocation(sandbox); + const pluginOutcome = await nativePluginAgentInvocationOutcome(sandbox, { + sandboxName: SANDBOX_NAME, + version: "v1", + artifactName: "post-openshell-start-native-plugin-invoke", + env: sandboxAccessEnv(), + turnTimeoutMs: SANDBOX_SURVIVAL_NATIVE_PLUGIN_TURN_TIMEOUT_MS, + audit: SANDBOX_SURVIVAL_NATIVE_PLUGIN_AUDIT, + }); + expect(pluginOutcome, "the plugin tool must start and succeed in this agent run").toBe( + "succeeded", + ); progress.phase("destroy the sandbox"); await sandbox.cleanupSandbox(SANDBOX_NAME, { diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 8781c091689..0e4f0b811ea 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -1048,6 +1048,7 @@ "live": "test/e2e/live/sandbox-survival.test.ts", "fast": [ "test/e2e/support/sandbox-survival-timeout-contract.test.ts", + "test/e2e/support/native-plugin-evidence.test.ts", "src/lib/onboard/machine/finalization-deps.test.ts", "src/lib/actions/sandbox/destroy-flow.test.ts", "test/agents/native-gateway-lifecycle.test.ts", diff --git a/test/e2e/support/native-plugin-evidence.test.ts b/test/e2e/support/native-plugin-evidence.test.ts index 1dc44193da4..99f11c82586 100644 --- a/test/e2e/support/native-plugin-evidence.test.ts +++ b/test/e2e/support/native-plugin-evidence.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { completedAgentRunId, + nativePluginAgentInvocationOutcome, nativePluginPresent, nativeToolCallOutcome, } from "../fixtures/native-plugin-evidence.ts"; @@ -138,3 +139,62 @@ describe("agent run correlation", () => { expect(() => completedAgentRunId(JSON.stringify(value))).toThrow("no completed gateway run"); }); }); + +describe("native plugin agent invocation", () => { + const pluginTool = "nemoclaw_e2e_check_v1"; + const turnOutput = JSON.stringify({ + runId, + status: "ok", + summary: "completed", + result: { payloads: [], meta: {} }, + }); + const auditPage = (events: Record[]) => + page(events.map((entry) => ({ ...entry, toolName: pluginTool }))); + type InvocationSandbox = Parameters[0]; + const fakeSandbox = (turn: { exitCode: number; stdout: string }, audits: string[]) => { + const calls: string[][] = []; + const shells: string[] = []; + const sandbox = { + exec: async (_name: string, argv: string[]) => { + calls.push(argv); + return argv[1] === "agent" + ? { ...turn, stderr: "" } + : { exitCode: 0, stdout: audits.shift() ?? auditPage([]), stderr: "" }; + }, + execShell: async (_name: string, script: string) => { + shells.push(script); + return { exitCode: 0, stdout: "", stderr: "" }; + }, + } as unknown as InvocationSandbox; + return { calls, shells, sandbox }; + }; + const options = { + sandboxName: "fixture", + version: "v1" as const, + artifactName: "invoke", + env: {}, + turnTimeoutMs: 1_000, + audit: { attempts: 3, delayMs: 0, timeoutMs: 1_000 }, + }; + + it("runs one agent turn and polls only the audit page until the call completes", async () => { + const fake = fakeSandbox({ exitCode: 0, stdout: turnOutput }, [ + auditPage([started]), + auditPage([started, finished]), + ]); + expect(await nativePluginAgentInvocationOutcome(fake.sandbox, options)).toBe("succeeded"); + expect(fake.calls.map((argv) => argv[1])).toEqual(["agent", "audit", "audit"]); + expect(fake.calls[0]).toContain(`Run the local ${pluginTool} tool once with no arguments.`); + expect(fake.calls[1]).toEqual( + expect.arrayContaining(["--run", runId, "--kind", "tool_action"]), + ); + expect(fake.shells).toEqual([]); + }); + + it("reports a failed turn without reading audit records and keeps readiness evidence", async () => { + const fake = fakeSandbox({ exitCode: 1, stdout: "" }, []); + expect(await nativePluginAgentInvocationOutcome(fake.sandbox, options)).toBe("failed"); + expect(fake.calls.map((argv) => argv[1])).toEqual(["agent"]); + expect(fake.shells).toHaveLength(1); + }); +});