diff --git a/agents/hermes/mcp-config-transaction.py b/agents/hermes/mcp-config-transaction.py
index 5b5f8da01e6..d9875dce6b0 100755
--- a/agents/hermes/mcp-config-transaction.py
+++ b/agents/hermes/mcp-config-transaction.py
@@ -74,7 +74,6 @@
REVISIONED_ENV_PLACEHOLDER_RE = re.compile(
r"^Bearer openshell:resolve:env:(v[0-9]{1,20})_([A-Za-z_][A-Za-z0-9_]{0,127})$"
)
-OPENSHELL_CREDENTIAL_REVISION_RE = re.compile(r"^v[0-9]{1,20}$")
OPENSHELL_REVISIONED_CREDENTIAL_NAME_RE = re.compile(r"^v[0-9]+_[A-Za-z0-9_]+$")
BOUNDARY_MANIFEST_NAME = "openshell-child-visible-credentials.v0.0.106.json"
ANSI_ESCAPE_RE = re.compile(
@@ -365,8 +364,6 @@ def _validate_payload(action: str, payload: dict[str, object]) -> None:
raise ValueError("Unsupported MCP config action")
allowed = {"server", "url", "headers"}
allowed.add("replace_existing" if action == "add" else "force")
- if action == "add":
- allowed.update({"credential_name", "credential_revision"})
unexpected = sorted(set(payload) - allowed)
if unexpected:
raise ValueError(
@@ -459,38 +456,35 @@ def _validate_payload(action: str, payload: dict[str, object]) -> None:
if not isinstance(headers, dict) or set(headers) != {"Authorization"}:
raise ValueError("MCP mutation payload must contain one Authorization header")
authorization = headers.get("Authorization")
- declared_credential_name = payload.get("credential_name")
- credential_revision = payload.get("credential_revision")
- if credential_revision is not None and (
- not isinstance(credential_revision, str)
- or OPENSHELL_CREDENTIAL_REVISION_RE.fullmatch(credential_revision) is None
- ):
- raise ValueError("Hermes MCP credential revision is invalid")
- authorization_match = None
- credential_name = None
- if isinstance(authorization, str) and credential_revision is not None:
- authorization_match = REVISIONED_ENV_PLACEHOLDER_RE.fullmatch(authorization)
- if (
- authorization_match is not None
- and authorization_match.group(1) == credential_revision
- and isinstance(declared_credential_name, str)
- and authorization_match.group(2) == declared_credential_name
- ):
- credential_name = authorization_match.group(2)
- else:
- authorization_match = None
- elif isinstance(authorization, str) and declared_credential_name is None:
- authorization_match = ENV_PLACEHOLDER_RE.fullmatch(authorization)
- if authorization_match is not None:
- credential_name = authorization_match.group(1)
+ revisioned_authorization_match = (
+ REVISIONED_ENV_PLACEHOLDER_RE.fullmatch(authorization)
+ if isinstance(authorization, str)
+ else None
+ )
+ canonical_authorization_match = (
+ ENV_PLACEHOLDER_RE.fullmatch(authorization)
+ if isinstance(authorization, str)
+ else None
+ )
+ authorization_match = (
+ revisioned_authorization_match or canonical_authorization_match
+ )
if authorization_match is None:
raise ValueError(
"Hermes MCP Authorization must contain an OpenShell environment placeholder"
)
- if action == "add" and (
- not isinstance(credential_name, str)
- or _credential_name_is_reserved(credential_name)
- ):
+ credential_name = (
+ revisioned_authorization_match.group(2)
+ if revisioned_authorization_match is not None
+ else canonical_authorization_match.group(1)
+ )
+ if action == "add" and revisioned_authorization_match is not None:
+ expected_child_value = authorization.removeprefix("Bearer ")
+ if os.environ.get(credential_name) != expected_child_value:
+ raise ValueError(
+ "Hermes MCP Authorization revision does not match the OpenShell child environment"
+ )
+ if action == "add" and _credential_name_is_reserved(credential_name):
raise ValueError(
"Hermes MCP Authorization uses a reserved credential environment name"
)
@@ -515,6 +509,7 @@ def _managed_candidate(payload: dict[str, object]) -> dict[str, object]:
def _managed_candidate_matches(
actual: object, expected: dict[str, object], allow_revisioned: bool
) -> bool:
+ """Compare managed config with bounded revision equivalence when requested."""
if actual == expected:
return True
if not allow_revisioned or not isinstance(actual, dict):
diff --git a/agents/hermes/runtime-config-guard.py b/agents/hermes/runtime-config-guard.py
index fdb1222f0aa..40838de282c 100755
--- a/agents/hermes/runtime-config-guard.py
+++ b/agents/hermes/runtime-config-guard.py
@@ -1455,6 +1455,28 @@ def refresh_hashes(
source_hash_text, config_path, env_path
)
current_mcp, _ = _current_mcp_servers_digest(config_path)
+ # The transaction helper and the managed supervisor can both observe the
+ # same pending reload. The helper may commit it first while the supervisor
+ # still retains its earlier pending observation. Replacing an already-current
+ # anchor with byte-identical content needlessly changes its inode and can
+ # make a concurrent host reconciliation reject an otherwise coherent
+ # snapshot. Keep the repeated apply fail-closed, but make it validation-only:
+ # authenticate config, env, and every relevant anchor as one stable current
+ # snapshot before returning without an atomic replacement.
+ if mcp_transition == "apply" and secrets.compare_digest(
+ state.intended, state.applied
+ ):
+ integrity = inspect_mcp_integrity_snapshot(
+ hermes_dir,
+ state_path,
+ compat_hash if mode == "both" else None,
+ )
+ if integrity.state != "current":
+ raise UnsafePathError(
+ "Hermes MCP applied-state commit did not observe current state"
+ )
+ assert_mcp_integrity_snapshot_current(integrity)
+ return
if mcp_transition == "preserve":
if not secrets.compare_digest(current_mcp, state.intended):
raise UnsafePathError(
diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json
index 7fd7be0ebc3..4932787703a 100644
--- a/ci/source-architecture-budget.json
+++ b/ci/source-architecture-budget.json
@@ -11,7 +11,7 @@
"src/lib/adapters/openshell/runtime.ts": 55,
"src/lib/adapters/openshell/timeouts.ts": 39,
"src/lib/agent/defs.ts": 33,
- "src/lib/cli/branding.ts": 87,
+ "src/lib/cli/branding.ts": 86,
"src/lib/cli/nemoclaw-oclif-command.ts": 107,
"src/lib/cli/terminal-style.ts": 43,
"src/lib/core/json-types.ts": 37,
diff --git a/docs/deployment/set-up-mcp-bridge.mdx b/docs/deployment/set-up-mcp-bridge.mdx
index 22094db7162..123b227ba18 100644
--- a/docs/deployment/set-up-mcp-bridge.mdx
+++ b/docs/deployment/set-up-mcp-bridge.mdx
@@ -59,9 +59,14 @@ The decision record is tracked in [NVIDIA/NemoClaw#566](https://github.com/NVIDI
## Authenticated MCP Security Boundary
Authenticated MCP is the intended configuration.
-The agent stores only the `openshell:resolve:env:KEY` placeholder.
+The agent stores only an OpenShell resolver placeholder for the recorded credential key.
OpenShell keeps the raw credential in its provider store and combines credential replacement with generated MCP policy at egress.
+
+Hermes includes the credential revision from the readiness check in this placeholder.
+Registration, inspection, rollback, and lifecycle reconciliation preserve that revision while OpenShell still reports it.
+
+
For the normal MCP client path, OpenShell evaluates the effective policy for the destination host and port, adapter binary, literal endpoint path, and MCP method before replacing placeholders in allowed HTTP request headers.
The generated policy grants only the configured destination, path, adapter binaries, pinned addresses, explicit MCP method profile, and a 131,072-byte maximum request body.
@@ -134,9 +139,12 @@ mcp_servers:
resources: true
prompts: true
headers:
- Authorization: Bearer openshell:resolve:env:GITHUB_MCP_TOKEN
+ Authorization: Bearer openshell:resolve:env:v12_GITHUB_MCP_TOKEN
```
+The `v12_` prefix is an illustrative OpenShell credential revision.
+Hermes records the revision that the readiness check proves for the live provider.
+
### Prepare Hermes for Mutation
When Hermes shields are up, run `nemohermes shields down --timeout 15m --reason "MCP maintenance"` before `mcp add`, `mcp restart`, `mcp remove`, or destroy, then restore shields if the sandbox still exists.
diff --git a/docs/manage-sandboxes/add-mcp-server.mdx b/docs/manage-sandboxes/add-mcp-server.mdx
index 435945e1e1a..de0a7d4aef5 100644
--- a/docs/manage-sandboxes/add-mcp-server.mdx
+++ b/docs/manage-sandboxes/add-mcp-server.mdx
@@ -23,6 +23,8 @@ The early capability check identifies managed image version only; NemoClaw still
Hermes performs its managed runtime probe before an active add or restart changes a live provider or policy.
+Hermes stores the credential revision from the readiness check in the OpenShell resolver placeholder.
+Registration, inspection, rollback, and lifecycle reconciliation preserve that revision while it remains observable.
OpenClaw verifies the pinned `mcporter` during adapter registration and rolls back an incomplete add.
@@ -43,7 +45,8 @@ The assignment is illustrative.
Load real values from an approved secret manager or masked prompt so the credential is not recorded in shell history.
`--env KEY` reads the value from the host process environment and stores it in OpenShell's provider store.
-NemoClaw persists only the variable name, writes `openshell:resolve:env:KEY` into sandbox-side MCP config, and relies on OpenShell to resolve the placeholder at egress.
+NemoClaw persists only the variable name and writes an OpenShell resolver placeholder for that key into sandbox-side MCP configuration.
+OpenShell resolves the placeholder at egress.
After `mcp add` commits, NemoClaw performs a fresh status inspection and runs the gated credential-resolution probe once unless you pass `--no-probe`.
If readiness is inconclusive, the command reports a probe skip without failing the committed add.
@@ -103,7 +106,7 @@ The command records the resulting exact trust intent, so later lifecycle command
NemoClaw records the normalized trust intent and every validated address as exact policy pins.
The raw bearer value passes transiently to the OpenShell provider and remains absent from NemoClaw state, sandbox configuration, command arguments, and logs.
-The sandbox configuration contains only the `openshell:resolve:env:LOCAL_MCP_TOKEN` credential placeholder.
+The sandbox configuration contains only an OpenShell resolver placeholder for `LOCAL_MCP_TOKEN`, not the raw bearer value.
You can unset the host variable after `mcp add` returns because OpenShell retains the credential.
An exported replacement updates it during restart, and `mcp remove` or sandbox destroy deletes the registry-owned provider.
diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx
index 58eaf500db9..ddcbe60daca 100644
--- a/docs/manage-sandboxes/manage-mcp-servers.mdx
+++ b/docs/manage-sandboxes/manage-mcp-servers.mdx
@@ -84,7 +84,7 @@ Bounded partial results set `truncated` to `true` and include a redacted `detail
## Verify Credential Resolution
-Provider presence and metadata cannot prove that OpenShell rewrites `openshell:resolve:env:KEY` when a request leaves the sandbox.
+Provider presence and metadata cannot prove that OpenShell rewrites the recorded resolver placeholder when a request leaves the sandbox.
`mcp status ` requests a differential wire-level credential-resolution probe by default.
Before sending probe traffic, NemoClaw verifies exact generated policy, expected provider attachment, provider ID, `nemoclaw-mcp-v1` type, valid resource version, and exactly one matching credential key.
@@ -189,6 +189,11 @@ It never detaches the provider from other sandboxes.
`rebuild` preserves providers that match the recorded ID and credential-key metadata and the active `nemoclaw-mcp-v1` type.
It removes adapter entries and exact owned policies, then detaches providers before replacing the sandbox.
+Before changing each managed adapter, a fresh sandbox process must expose a revision-scoped OpenShell credential placeholder for that adapter.
+If an observation is absent, unscoped, or unavailable, NemoClaw leaves the affected adapter and every provider unchanged.
+It attempts to restore adapter entries prepared earlier in the operation and reports rollback failures.
+It does not substitute the provider resource version for the credential revision.
+Follow the reported [credential-revision recovery](../../reference/troubleshoot-mcp-servers#rebuild-or-destroy-cannot-prove-a-credential-revision), then retry rebuild.
Restoration applies the credential-free policy, reattaches each provider, applies the endpoint-bound policy, waits for credential readiness, and restores adapters.
For a trusted-private entry, the restored policy uses the recorded exact address pins and does not widen them from current DNS answers.
Public entries continue to resolve and validate their endpoint addresses during restoration.
@@ -209,6 +214,10 @@ A later `mcp restart` can retry an incomplete post-rebuild restore.
## Destroy a Sandbox with MCP State
Destroy removes adapter entries and exact owned policies, then detaches providers that match recorded metadata before asking OpenShell to delete the sandbox.
+Before changing each managed adapter, a fresh sandbox process must expose a revision-scoped OpenShell credential placeholder for that adapter.
+If an observation is absent, unscoped, or unavailable, NemoClaw leaves the affected adapter and every provider unchanged.
+It attempts to restore adapter entries prepared earlier in the operation and reports rollback failures.
+Follow the reported [credential-revision recovery](../../reference/troubleshoot-mcp-servers#rebuild-or-destroy-cannot-prove-a-credential-revision), then retry destroy.
If deletion is refused, NemoClaw attempts to restore previous MCP state, reports rollback failures, and preserves recovery state.
Provider deletion and registry cleanup happen only after OpenShell confirms the sandbox is gone.
diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx
index b8308c7243f..d8e8137fcf5 100644
--- a/docs/reference/commands.mdx
+++ b/docs/reference/commands.mdx
@@ -3183,7 +3183,7 @@ The declaration must equal the normalized host from `--url`.
For managed MCP, use a DNS hostname for an IPv6 unique local address because NemoClaw has not qualified direct IPv6-literal MCP URLs.
You can supply exact hosts through `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` instead, and NemoClaw combines the variable with command options.
NemoClaw records the resulting exact trust intent and address pins, so restart, rebuild, and restore do not depend on the ambient environment.
-NemoClaw registers that credential in an OpenShell provider, installs a generated OpenShell `protocol: mcp` policy for the target endpoint, attaches the provider to the running sandbox, and writes only an `openshell:resolve:env:KEY` placeholder into the agent config.
+NemoClaw registers that credential in an OpenShell provider, installs a generated OpenShell `protocol: mcp` policy for the target endpoint, attaches the provider to the running sandbox, and writes only an OpenShell resolver placeholder for the recorded key into the agent configuration.
Inline `--env KEY=VALUE` is rejected because it would expose the value in NemoClaw process arguments.
Load the variable from a secret manager or masked prompt, export it without recording the value in shell history, and pass only `--env KEY`.
All endpoints must use HTTPS.
@@ -3203,6 +3203,7 @@ For full setup details, see [Add an MCP Server](../manage-sandboxes/mcp-servers/
Hermes MCP add, restart, and remove mutate managed config and are refused while shields are up.
+Hermes includes the credential revision from the readiness check in the resolver placeholder and preserves it through inspection, rollback, and lifecycle reconciliation while OpenShell still reports it.
Run `$$nemoclaw shields down --timeout 15m --reason "MCP maintenance"` before the mutation, then run `$$nemoclaw shields up` after it; list and status remain read-only.
Allow at least 15 minutes per configured server for an all-server restart or destroy; rebuild opens its own crash-recoverable maintenance window.
Keep shields down until the command returns; a concurrent relock refuses the config commit and can leave an earlier policy/provider stage for the next retry to converge.
@@ -3242,7 +3243,7 @@ Text output reports `private address pins: match`, `drift`, or `unresolved`.
JSON output reports the same value in `trustedPrivateTarget.state` and includes the recorded pins.
When a single server is named, status requests a differential wire-level credential-resolution probe.
It sends no probe traffic unless the exact generated policy matches the effective gateway policy, the expected provider attachment is confirmed, and the live provider has the recorded ID, `nemoclaw-mcp-v1` type, a valid resource version, and exactly one credential key matching the recorded key; a readiness failure reports `unknown` with a `probe skipped` detail.
-When ready, the same MCP `initialize` is sent from inside the sandbox once with the `openshell:resolve:env:KEY` placeholder header and once with a deliberately-unresolvable control bearer.
+When ready, the same MCP `initialize` is sent from inside the sandbox once with the recorded resolver placeholder header and once with a deliberately-unresolvable control bearer.
Classification uses the two HTTP status codes plus curl exit codes for transport, timeout, and policy-denial outcomes; response bodies are never captured or printed.
A `verified` verdict requires the placeholder request to be accepted (HTTP 2xx) while the control is rejected — the only outcome that proves a valid credential was on the wire.
Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypotheses — the placeholder forwarded verbatim, an expired or revoked credential that resolved correctly, or (for HTTP 400) endpoint request validation — and tells you to verify the stored credential first.
diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx
index f1b1f22b30c..3e3f1716ce0 100644
--- a/docs/reference/troubleshoot-mcp-servers.mdx
+++ b/docs/reference/troubleshoot-mcp-servers.mdx
@@ -16,7 +16,7 @@ Use the reported status or lifecycle error to choose the matching remediation.
If `mcp status ` reports identical placeholder and control rejections, first confirm the stored credential is valid.
Rotate it with `mcp restart` when in doubt.
-For identical HTTP 401 or 403 responses, a confirmed-valid credential means the OpenShell gateway on this host is not rewriting `openshell:resolve:env:KEY` on egress.
+For identical HTTP 401 or 403 responses, a confirmed-valid credential means the OpenShell gateway on this host is not rewriting the recorded resolver placeholder on egress.
Every agent request receives the same authentication failure even when provider, attachment, readiness, and adapter checks report healthy.
This is a host-side OpenShell defect rather than a NemoClaw registration problem.
@@ -40,6 +40,31 @@ If restart reports a missing provider and the original credential is not registe
If restart or rebuild reports that the provider uses the profile-less legacy `generic` type, remove that server and add it again with the recorded credential variable exported.
OpenShell cannot bind that provider to an MCP endpoint, and NemoClaw accepts it only for exact cleanup.
+## Rebuild or Destroy Cannot Prove a Credential Revision
+
+If rebuild or destroy reports that it could not prove a revision-scoped credential, a fresh sandbox process did not expose the exact OpenShell credential identity required for adapter cleanup.
+NemoClaw leaves the affected adapter and every provider unchanged.
+It attempts to restore adapter entries prepared earlier in the operation and reports rollback failures.
+
+Inspect the managed server:
+
+```bash
+$$nemoclaw mcp status --json
+```
+
+If status cannot reach the sandbox, repair the reported gateway condition first.
+Export the recorded environment variable, then restart the server to publish and verify a fresh credential revision:
+
+```bash
+export ='replacement-value'
+$$nemoclaw mcp restart
+unset
+```
+
+Run status again.
+Retry rebuild or destroy only after `provider.credentialReady` and `adapter.registered` are both `true`.
+If restart still cannot prove the revision, repair the reported OpenShell provider, policy, or adapter condition before retrying teardown.
+
## Add Transaction Is Incomplete
If status reports an incomplete add transaction, rerun the original `mcp add` command with the same URL and environment-variable name.
diff --git a/src/commands/credentials/list.ts b/src/commands/credentials/list.ts
index abe8ed49929..705f86a2119 100644
--- a/src/commands/credentials/list.ts
+++ b/src/commands/credentials/list.ts
@@ -15,7 +15,7 @@ export default class CredentialsListCommand extends NemoClawCommand {
public async run(): Promise {
await this.parse(CredentialsListCommand);
- const result = await runCredentialsListAction();
+ const result = await runCredentialsListAction(this.config.bin);
if (result.exitCode !== 0) {
this.failWithLines(result.failureLines, result.exitCode);
return;
diff --git a/src/lib/actions/credentials/list.ts b/src/lib/actions/credentials/list.ts
index 2a77365f701..ee556edb696 100644
--- a/src/lib/actions/credentials/list.ts
+++ b/src/lib/actions/credentials/list.ts
@@ -3,7 +3,6 @@
import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command";
import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts";
-import { CLI_NAME } from "../../cli/branding";
import { recoverGatewayOrExit } from "../../credentials/command-support";
import { parseGatewayProviderNames } from "../../credentials/provider-list";
import { gatewayStartGuidance } from "../../gateway-start-guidance";
@@ -18,7 +17,7 @@ function fail(failureLines: readonly string[]): CredentialsListResult {
return { exitCode: 1, outputLines: [], failureLines };
}
-export async function runCredentialsListAction(): Promise {
+export async function runCredentialsListAction(cliName: string): Promise {
const recoveryFailureLines: string[] = [];
const recovered = await recoverGatewayOrExit("query", (lines) => {
recoveryFailureLines.push(...lines);
@@ -49,7 +48,7 @@ export async function runCredentialsListAction(): Promise
outputLines.push(
"",
` ${String(bridgeNames.length)} per-sandbox messaging bridge(s) are also registered.`,
- ` Manage those with \`${CLI_NAME} channels list/remove/stop\` — not this command.`,
+ ` Manage those with \`${cliName} channels list/remove/stop\` — not this command.`,
);
}
return { exitCode: 0, outputLines, failureLines: [] };
diff --git a/src/lib/actions/sandbox/gateway-failure-classifier.ts b/src/lib/actions/sandbox/gateway-failure-classifier.ts
index 9cc0b483fca..82ea9045920 100644
--- a/src/lib/actions/sandbox/gateway-failure-classifier.ts
+++ b/src/lib/actions/sandbox/gateway-failure-classifier.ts
@@ -19,6 +19,7 @@ import { getSandboxTargetGatewayName } from "./gateway-target";
const DOCKER_TIMEOUT_MS = 3000;
const PORT_PROBE_TIMEOUT_MS = 2000;
+
const portableRuntimeFailures = new Map<
string,
Extract
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes-branding.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes-branding.test.ts
new file mode 100644
index 00000000000..4b6b027af83
--- /dev/null
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes-branding.test.ts
@@ -0,0 +1,41 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ isShieldsDown: vi.fn(),
+ runOpenshellProviderCommand: vi.fn(),
+}));
+
+vi.mock("../../adapters/openshell/provider-command", () => ({
+ runOpenshellProviderCommand: mocks.runOpenshellProviderCommand,
+}));
+
+vi.mock("../../shields", () => ({
+ isShieldsDown: mocks.isShieldsDown,
+}));
+
+import { assertHermesMcpMutationRuntimeCapability } from "./mcp-bridge-adapter-hermes";
+
+describe("Hermes MCP recovery guidance", () => {
+ beforeEach(() => {
+ vi.stubEnv("NEMOCLAW_INVOKED_AS", "nemohermes");
+ mocks.isShieldsDown.mockReset().mockReturnValue(true);
+ mocks.runOpenshellProviderCommand.mockReset().mockReturnValue({
+ status: 1,
+ stdout: "",
+ stderr: "Hermes gateway is not running under the managed service lifecycle",
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("uses the invoked CLI name when the managed lifecycle is unavailable", () => {
+ expect(() => assertHermesMcpMutationRuntimeCapability("alpha")).toThrow(
+ "Run `nemohermes alpha recover` and retry.",
+ );
+ });
+});
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.test.ts
index 653ba1c8801..1438aef1398 100644
--- a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.test.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.test.ts
@@ -1,6 +1,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
import { describe, expect, it } from "vitest";
import type { McpBridgeEntry } from "../../state/registry";
@@ -9,6 +14,7 @@ import {
buildHermesMcpProbeCommand,
buildHermesMcpRegisterCommand,
} from "./mcp-bridge-adapter-hermes";
+import { buildHermesMcpStatusCommand } from "./mcp-bridge-adapter-status";
const baseEntry: McpBridgeEntry = {
server: "github",
@@ -65,7 +71,7 @@ describe("Hermes MCP config adapter", () => {
]);
});
- it("declares the readiness-proven credential revision for transaction validation (#10155)", () => {
+ it("projects the readiness-proven credential revision without helper-only metadata (#10155)", () => {
const command = buildHermesMcpRegisterCommand(baseEntry, false, "v12");
expect(JSON.parse(command[3] ?? "{}")).toEqual({
@@ -73,8 +79,55 @@ describe("Hermes MCP config adapter", () => {
url: "https://api.githubcopilot.com/mcp/",
headers: { Authorization: "Bearer openshell:resolve:env:v12_GITHUB_TOKEN" },
replace_existing: false,
- credential_name: "GITHUB_TOKEN",
- credential_revision: "v12",
});
});
+
+ it("accepts a revision on resumed inspection and rejects a stale exact revision (#10155)", () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-mcp-revision-"));
+ const configPath = path.join(temp, "config.yaml");
+ fs.writeFileSync(
+ configPath,
+ JSON.stringify({
+ mcp_servers: {
+ github: {
+ url: baseEntry.url,
+ enabled: true,
+ timeout: 120,
+ connect_timeout: 60,
+ tools: { resources: true, prompts: true },
+ headers: { Authorization: "Bearer openshell:resolve:env:v12_GITHUB_TOKEN" },
+ },
+ },
+ }),
+ );
+
+ const inspect = (credentialRevision?: "v11" | "v12") => {
+ const command = buildHermesMcpStatusCommand(baseEntry, credentialRevision);
+ const scriptStart = command.indexOf("\n") + 1;
+ const scriptEnd = command.lastIndexOf("\nPY");
+ expect(scriptStart, "Hermes status command Python start").toBeGreaterThan(0);
+ expect(scriptEnd, "Hermes status command Python end").toBeGreaterThanOrEqual(scriptStart);
+ const script = command
+ .slice(scriptStart, scriptEnd)
+ .replace("import json, pathlib, yaml", "import json, pathlib, sys, yaml")
+ .replace(
+ 'config_path = pathlib.Path("/sandbox/.hermes/config.yaml")',
+ "config_path = pathlib.Path(sys.argv[1])",
+ );
+ return spawnSync("python3", ["-", configPath], {
+ encoding: "utf8",
+ input: script,
+ killSignal: "SIGKILL",
+ timeout: 10_000,
+ });
+ };
+
+ try {
+ expect(inspect().stdout.trim()).toBe("registered");
+ expect(inspect("v12").stdout.trim()).toBe("registered");
+ expect(inspect("v11").stdout.trim()).toBe("mismatch");
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+ }
+ });
});
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts
index a5acb4d53cc..51dbd276644 100644
--- a/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-hermes.ts
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command";
+import { getAgentBranding } from "../../cli/branding";
import { waitUntil } from "../../core/wait";
import { isShieldsDown } from "../../shields";
import type { McpBridgeEntry } from "../../state/registry";
@@ -14,13 +15,16 @@ import {
type AdapterRegistrationInspection,
inspectAdapterRegistrationCommand,
} from "./mcp-bridge-adapter-inspection";
-import { buildHermesMcpStatusCommand, entryHeaders } from "./mcp-bridge-adapter-status";
+import {
+ buildHermesMcpStatusCommand,
+ entryHeaders,
+ HERMES_MCP_TRANSACTION_HELPER,
+} from "./mcp-bridge-adapter-status";
import { McpBridgeError } from "./mcp-bridge-contracts";
import { commandOutput, redactBridgeSecretsForDisplay } from "./mcp-bridge-output";
import type { McpAttachedCredentialRevision } from "./mcp-bridge-provider-readiness";
import { executeGatewaySupervisorAction } from "./process-recovery";
-const HERMES_MCP_TRANSACTION_HELPER = "/usr/local/lib/nemoclaw/hermes-mcp-config-transaction.py";
const HERMES_MCP_EXEC_TIMEOUT_SECONDS = 620;
const HERMES_MCP_PROBE_TIMEOUT_SECONDS = 30;
const HERMES_MCP_STARTUP_TIMEOUT_SECONDS = 90;
@@ -40,9 +44,6 @@ export function buildHermesMcpRegisterCommand(
url: entry.url,
headers: entryHeaders(entry, credentialRevision),
replace_existing: replaceExisting,
- ...(credentialRevision
- ? { credential_name: entry.env[0], credential_revision: credentialRevision }
- : {}),
};
return [HERMES_MCP_TRANSACTION_HELPER, "add", "--payload", JSON.stringify(payload)];
}
@@ -148,7 +149,7 @@ export function assertHermesMcpMutationRuntimeCapability(sandboxName: string): v
if (lastDetail === HERMES_MCP_GATEWAY_NOT_READY) return false;
if (lastDetail === HERMES_MCP_LIFECYCLE_NOT_READY) {
throw new McpBridgeError(
- `Hermes sandbox '${sandboxName}' is not running the managed service lifecycle required for authenticated MCP changes. Run \`nemoclaw ${sandboxName} recover\` and retry.`,
+ `Hermes sandbox '${sandboxName}' is not running the managed service lifecycle required for authenticated MCP changes. Run \`${getAgentBranding().cli} ${sandboxName} recover\` and retry.`,
);
}
throw new McpBridgeError(
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-status.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-status.ts
index 3f38bb00504..03518cab344 100644
--- a/src/lib/actions/sandbox/mcp-bridge-adapter-status.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-status.ts
@@ -17,6 +17,8 @@ import {
// state can never be layered over the validated registry projection.
export const DEEPAGENTS_MCP_CONFIG_PATH = "/sandbox/.deepagents/.nemoclaw-mcp.json";
export const DEFAULT_OPENCLAW_CONFIG_DIR = "/sandbox/.openclaw";
+export const HERMES_MCP_TRANSACTION_HELPER =
+ "/usr/local/lib/nemoclaw/hermes-mcp-config-transaction.py";
/** Resolve Mcporter's project root beneath an OpenClaw agent configuration directory. */
export function openClawMcporterRoot(configDir = DEFAULT_OPENCLAW_CONFIG_DIR): string {
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts
new file mode 100644
index 00000000000..dc6feb9d358
--- /dev/null
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.test.ts
@@ -0,0 +1,167 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { McpBridgeEntry, SandboxEntry } from "../../state/registry";
+
+const mocks = vi.hoisted(() => ({
+ assertMcpDestroyNotPending: vi.fn(),
+ bridgeState: vi.fn(),
+ discardSafeIncompleteMcpAdds: vi.fn(),
+ ensureSandboxGatewaySelected: vi.fn(),
+ getBridgeAdapter: vi.fn(),
+ getSandboxAgent: vi.fn(),
+ getSandboxOrThrow: vi.fn(),
+ inspectMcpProvider: vi.fn(),
+ observeMcpCredentialRevision: vi.fn(),
+ removeGeneratedPolicy: vi.fn(),
+ registerAgentAdapter: vi.fn(),
+ restoreExistingMcpBridgeRuntime: vi.fn(),
+ unregisterAgentAdapter: vi.fn(),
+}));
+
+vi.mock("../../state/registry", () => ({
+ getSandbox: vi.fn(),
+ updateSandbox: vi.fn(),
+}));
+
+vi.mock("./mcp-bridge-adapters", () => ({
+ registerAgentAdapter: mocks.registerAgentAdapter,
+ unregisterAgentAdapter: mocks.unregisterAgentAdapter,
+}));
+
+vi.mock("./mcp-bridge-provider-readiness", () => ({
+ observeMcpCredentialRevision: mocks.observeMcpCredentialRevision,
+}));
+
+vi.mock("./mcp-bridge-provider", () => ({
+ assertMcpProviderRecoverable: vi.fn(),
+ assertNoProviderCredentialCollisions: vi.fn(),
+ assertNoRegisteredProviderCredentialCollisions: vi.fn(),
+ detachProvider: vi.fn(),
+ inspectMcpProvider: mocks.inspectMcpProvider,
+ preflightMcpEntryTargets: vi.fn(),
+ waitForDetachedMcpCredential: vi.fn(),
+}));
+
+vi.mock("./mcp-bridge-destroy-preflight", () => ({
+ cloneMcpBridgeEntry: vi.fn((entry: McpBridgeEntry) => ({ ...entry, env: [...entry.env] })),
+ discardSafeIncompleteMcpAdds: mocks.discardSafeIncompleteMcpAdds,
+ inspectExactMcpDestroyProvider: vi.fn(),
+}));
+
+vi.mock("./mcp-bridge-policy", () => ({
+ assertGeneratedPolicyMutationSafe: vi.fn(),
+ assertGeneratedPolicyRegistrationMutationSafe: vi.fn(),
+ removeGeneratedPolicy: mocks.removeGeneratedPolicy,
+}));
+
+vi.mock("./mcp-bridge-restart", () => ({
+ restoreExistingMcpBridgeRuntime: mocks.restoreExistingMcpBridgeRuntime,
+}));
+
+vi.mock("./mcp-bridge-runtime-capabilities", () => ({
+ assertMcpAdapterConfigMutationsAllowed: vi.fn(),
+ assertMcpAdapterTeardownRuntimeCapabilities: vi.fn(),
+}));
+
+vi.mock("./mcp-bridge-state", () => ({
+ assertMcpDestroyNotPending: mocks.assertMcpDestroyNotPending,
+ bridgeState: mocks.bridgeState,
+ ensureSandboxGatewaySelected: mocks.ensureSandboxGatewaySelected,
+ getBridgeAdapter: mocks.getBridgeAdapter,
+ getSandboxAgent: mocks.getSandboxAgent,
+ getSandboxOrThrow: mocks.getSandboxOrThrow,
+ nowIso: vi.fn(() => new Date(0).toISOString()),
+ setBridgeState: vi.fn(),
+}));
+
+vi.mock("./mcp-bridge-validation", () => ({
+ assertAuthenticatedBridgeEntry: vi.fn(),
+ validateSandboxName: vi.fn(),
+}));
+
+import { prepareMcpBridgesForDestroy } from "./mcp-bridge-destroy";
+import { prepareMcpBridgesForRebuild } from "./mcp-bridge-rebuild";
+import { scrubManagedMcpAdapterOrThrow } from "./mcp-bridge-adapter-teardown";
+
+const sandbox = { agent: "hermes" } as SandboxEntry;
+const entry: McpBridgeEntry = {
+ server: "github",
+ agent: "hermes",
+ adapter: "hermes-config",
+ url: "https://api.githubcopilot.com/mcp/",
+ env: ["GITHUB_TOKEN"],
+ providerName: "alpha-mcp-github",
+ providerId: "11111111-2222-4333-8444-555555555555",
+ policyName: "mcp-bridge-github",
+ addedAt: new Date(0).toISOString(),
+};
+
+describe("MCP adapter teardown rollback", () => {
+ beforeEach(() => {
+ mocks.bridgeState.mockReset().mockReturnValue({ github: entry });
+ mocks.discardSafeIncompleteMcpAdds.mockReset().mockResolvedValue(sandbox);
+ mocks.ensureSandboxGatewaySelected.mockReset().mockResolvedValue(undefined);
+ mocks.getBridgeAdapter.mockReset().mockReturnValue("hermes-config");
+ mocks.getSandboxAgent.mockReset().mockReturnValue("hermes");
+ mocks.getSandboxOrThrow.mockReset().mockReturnValue(sandbox);
+ mocks.inspectMcpProvider.mockReset().mockReturnValue({ exists: false });
+ mocks.observeMcpCredentialRevision.mockReset().mockReturnValue("v12");
+ mocks.removeGeneratedPolicy.mockReset().mockImplementation(() => {
+ throw new Error("forced lifecycle failure after adapter scrub");
+ });
+ mocks.registerAgentAdapter.mockReset();
+ mocks.restoreExistingMcpBridgeRuntime.mockReset();
+ mocks.unregisterAgentAdapter.mockReset().mockReturnValue("removed");
+ });
+
+ it.each([
+ ["rebuild", prepareMcpBridgesForRebuild],
+ ["destroy", prepareMcpBridgesForDestroy],
+ ] as const)(
+ "restores the revision observed before a later %s step fails (#10155)",
+ async (_lifecycle, prepare) => {
+ mocks.observeMcpCredentialRevision
+ .mockReset()
+ .mockReturnValueOnce("v12")
+ .mockReturnValueOnce("absent");
+
+ await expect(prepare("alpha")).rejects.toThrow(
+ "forced lifecycle failure after adapter scrub",
+ );
+ expect(mocks.unregisterAgentAdapter).toHaveBeenCalledOnce();
+ expect(mocks.registerAgentAdapter).toHaveBeenCalledWith(
+ "alpha",
+ "hermes-config",
+ expect.objectContaining({ ...entry, credentialRevision: "v12" }),
+ {},
+ {
+ credentialRevision: "v12",
+ replaceExisting: true,
+ teardownRollback: true,
+ },
+ );
+ expect(mocks.restoreExistingMcpBridgeRuntime).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not derive a Hermes credential revision from an exact provider resource version", () => {
+ mocks.observeMcpCredentialRevision.mockReturnValue("absent");
+ mocks.inspectMcpProvider.mockReturnValue({
+ credentialKeys: ["GITHUB_TOKEN"],
+ exists: true,
+ id: entry.providerId,
+ resourceVersion: 12,
+ type: "nemoclaw-mcp-v1",
+ });
+
+ expect(() => scrubManagedMcpAdapterOrThrow("alpha", sandbox, entry)).toThrow(
+ "Could not prove a revision-scoped credential before removing the managed adapter entry for MCP server 'github'.",
+ );
+ expect(mocks.inspectMcpProvider).not.toHaveBeenCalled();
+ expect(mocks.unregisterAgentAdapter).not.toHaveBeenCalled();
+ expect(mocks.registerAgentAdapter).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts
index e7cd9f1fe23..76d143cedcf 100644
--- a/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-adapter-teardown.ts
@@ -9,7 +9,6 @@ import {
observeMcpCredentialRevision,
type McpAttachedCredentialRevision,
} from "./mcp-bridge-provider-readiness";
-import { inspectMcpProvider } from "./mcp-bridge-provider";
import { getBridgeAdapter, getSandboxAgent } from "./mcp-bridge-state";
export type McpScrubbedAdapterEntry = McpBridgeEntry & {
@@ -33,25 +32,12 @@ export function scrubManagedMcpAdapterOrThrow(
entry: McpBridgeEntry,
): McpScrubbedAdapterEntry {
const observation = observeMcpCredentialRevision(sandboxName, entry);
- let credentialRevision: McpAttachedCredentialRevision | undefined;
- if (observation !== "absent" && observation !== "canonical") {
- credentialRevision = observation;
- } else if (observation === "absent") {
- const provider = inspectMcpProvider(entry.providerName);
- if (
- provider.exists &&
- provider.id === entry.providerId &&
- provider.resourceVersion !== null &&
- provider.resourceVersion > 0
- ) {
- credentialRevision = `v${provider.resourceVersion}`;
- }
- }
- if (!credentialRevision) {
+ if (observation === "absent" || observation === "canonical") {
throw new McpBridgeError(
`Could not prove a revision-scoped credential before removing the managed adapter entry for MCP server '${entry.server}'.`,
);
}
+ const credentialRevision: McpAttachedCredentialRevision = observation;
const adapter = resolveManagedMcpAdapter(sandbox, entry);
const removal = unregisterAgentAdapter(sandboxName, adapter, entry, {
envValues: {},
diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts
index f8bcd7a5ff6..bfc6463f93f 100644
--- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts
@@ -435,11 +435,17 @@ async function addMcpBridgeUnlocked(
providerAttachAttempted = true;
attachProvider(sandboxName, entry);
applyGeneratedPolicy(sandboxName, entry, target);
- if (Object.hasOwn(adapterEnvValues, entry.env[0])) {
+ const hasHostCredential = Object.hasOwn(adapterEnvValues, entry.env[0]);
+ let synchronizationBaseline =
+ providerResult.action === "updated" ? previousCredentialRevision : undefined;
+ if (hasHostCredential) {
// OpenShell 0.0.106 can miss a credential update published before the
// bound policy generation. Republish while that policy is active and
- // before the first readiness exec; the exact provider identity is
- // rechecked before and after this update-only mutation.
+ // compare the opaque sandbox-wide credential revision observed
+ // immediately before that mutation with fresh execs afterward. Provider
+ // resource versions are unrelated to credential placeholder revisions,
+ // so this pre-mutation observation is the exact stale-revision barrier.
+ synchronizationBaseline = observeMcpCredentialRevision(sandboxName, entry);
upsertMcpProvider(entry.providerName ?? "", options.env, {
allowExisting: true,
expectedProviderId: entry.providerId,
@@ -447,34 +453,32 @@ async function addMcpBridgeUnlocked(
});
}
const credentialRevision = waitForAttachedMcpCredential(sandboxName, entry, {
- ...(providerResult.action === "updated"
+ ...(synchronizationBaseline !== undefined
+ ? { previousRevision: synchronizationBaseline }
+ : {}),
+ // A no-field provider update advances only the provider resource version.
+ // Hostless recovery has no post-policy credential-bearing mutation to
+ // wait for, so it advances the provider revision only after a fresh exec
+ // proves the credential absent. A host credential was already
+ // republished above and must be allowed to project without another
+ // update racing its opaque revision.
+ ...(!hasHostCredential
? {
- previousRevision: previousCredentialRevision,
+ refreshAfterObservedAbsence: () => {
+ // invalidState: OpenShell 0.0.106 can coalesce a no-field provider
+ // refresh without publishing the credential into fresh sandbox execs.
+ // sourceBoundary: OpenShell owns provider revision projection.
+ // whyNotSourceFix: NemoClaw can only observe absence after the bound
+ // policy is active. Hostless recovery retains the credential-free path.
+ // regressionTest: mcp-add-crash-consistency.test.ts covers hostless
+ // recovery; mcp-provider-ownership.test.ts covers loss of the
+ // persisted provider identity before refresh.
+ // removalCondition: remove this refresh when the supported OpenShell
+ // version guarantees bound credentials project into fresh execs.
+ refreshMcpProviderEnvironment(entry);
+ },
}
: {}),
- // A no-field provider update advances only the provider resource version.
- // If the credential remains available, republish it after observing an
- // absence; otherwise, a hostless recovery advances the provider revision.
- refreshAfterObservedAbsence: () => {
- // invalidState: OpenShell 0.0.106 can coalesce a no-field provider
- // refresh without publishing the credential into fresh sandbox execs.
- // sourceBoundary: OpenShell owns provider revision projection.
- // whyNotSourceFix: NemoClaw can only observe absence after the bound
- // policy is active, then republish when this process still has the host
- // credential value. Hostless recovery retains the credential-free path.
- // regressionTest: mcp-add-crash-consistency.test.ts covers republish
- // and hostless recovery; mcp-provider-ownership.test.ts covers loss of
- // the persisted provider identity before republish.
- // removalCondition: remove the credential-bearing republish when the
- // supported OpenShell version guarantees that a post-policy no-field
- // refresh projects the bound credential into fresh sandbox execs.
- const republished = upsertMcpProvider(entry.providerName ?? "", options.env, {
- allowExisting: true,
- expectedProviderId: entry.providerId,
- requireExisting: true,
- });
- if (republished.action !== "updated") refreshMcpProviderEnvironment(entry);
- },
});
// The adapter was proven absent above, so cleanup is safe even when a
// command commits config and then fails during its runtime reload.
diff --git a/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.ts b/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.ts
index e3b177c776a..901916878f6 100644
--- a/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-hermes-reconciliation.ts
@@ -5,13 +5,15 @@ import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-c
import { redactFull } from "../../security/redact";
import type { McpBridgeEntry, SandboxEntry } from "../../state/registry";
import * as registry from "../../state/registry";
-import { buildHermesMcpIntentPayload } from "./mcp-bridge-adapter-status";
+import {
+ buildHermesMcpIntentPayload,
+ HERMES_MCP_TRANSACTION_HELPER,
+} from "./mcp-bridge-adapter-status";
import { McpBridgeError } from "./mcp-bridge-contracts";
import { redactBridgeSecretsForDisplay } from "./mcp-bridge-output";
import type { McpAttachedCredentialRevision } from "./mcp-bridge-provider-readiness";
import { sleepMcpBridgeRetry } from "./mcp-bridge/timing";
-const HERMES_MCP_TRANSACTION_HELPER = "/usr/local/lib/nemoclaw/hermes-mcp-config-transaction.py";
const HERMES_MCP_INSPECT_TIMEOUT_SECONDS = 45;
const HERMES_MCP_INSPECT_TIMEOUT_MS = 60_000;
const HERMES_MCP_RECONCILIATION_FAILURE =
diff --git a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts
index c709c629d56..1af7a243d89 100644
--- a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts
@@ -195,8 +195,9 @@ replace(provider, "upsertMcpProvider", () => ({
},
}));
replace(provider, "attachProvider", () => {});
+replace(provider, "observeMcpCredentialRevision", () => "v-before-private-target-update");
replace(provider, "refreshMcpProviderEnvironment", () => {});
-replace(provider, "waitForAttachedMcpCredential", () => {});
+replace(provider, "waitForAttachedMcpCredential", () => "v-after-private-target-update");
registry.registerSandbox({ name: "alpha", agent: "openclaw" });
require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", {
server: "local",
diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts
index 60eeadb8e73..92c34d94270 100644
--- a/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-provider-readiness.ts
@@ -165,6 +165,7 @@ export function waitForAttachedMcpCredential(
);
let refreshedAfterObservedAbsence = false;
let lastAttempt: McpCredentialRevisionAttempt = { kind: "transport-unavailable" };
+ let candidateRevision: McpAttachedCredentialRevision | undefined;
let attachedRevision: McpAttachedCredentialRevision | undefined;
const ready = waitForMcpBridgeCondition(
() => {
@@ -194,8 +195,20 @@ export function waitForAttachedMcpCredential(
observation !== "absent" &&
observation !== "canonical" &&
(options.previousRevision === undefined || observation !== options.previousRevision);
- if (attached) attachedRevision = observation;
- return attached;
+ if (!attached) {
+ candidateRevision = undefined;
+ return false;
+ }
+ if (candidateRevision !== observation) {
+ candidateRevision = observation;
+ return false;
+ }
+ // OpenShell can briefly project the revision that preceded a post-policy
+ // provider refresh. Require the same revision from two consecutive fresh
+ // execs so the adapter cannot be committed with a placeholder that is
+ // already being replaced by the provider sidecar.
+ attachedRevision = observation;
+ return true;
},
Number.isFinite(timeoutSeconds) && timeoutSeconds > 0 ? timeoutSeconds : 30,
1_000,
diff --git a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts
index 5bbdc2af88c..098ed41883d 100644
--- a/src/lib/actions/sandbox/mcp-bridge-provider.test.ts
+++ b/src/lib/actions/sandbox/mcp-bridge-provider.test.ts
@@ -374,10 +374,58 @@ alpha-mcp-slack generic 1 0
expect(proofCommand).toContain("GITHUB_TOKEN");
expect(proofCommand).not.toContain("base64 -d");
expect(refreshAfterObservedAbsence).not.toHaveBeenCalled();
- expect(exec).toHaveBeenCalledTimes(2);
+ expect(exec).toHaveBeenCalledTimes(3);
expect(revision).toBe("v11");
});
+ it("waits for a post-policy credential revision to settle before returning", () => {
+ const entry: McpBridgeEntry = {
+ server: "github",
+ agent: "openclaw",
+ adapter: "mcporter",
+ url: "https://mcp.example.test/mcp",
+ env: ["GITHUB_TOKEN"],
+ providerName: "alpha-mcp-github-0123456789abcdef",
+ providerId: "11111111-2222-4333-8444-555555555555",
+ policyName: "mcp-bridge-github",
+ addedAt: "2026-06-01T00:00:00.000Z",
+ };
+ const exec = vi
+ .spyOn(processRecovery, "executeSandboxExecCommand")
+ .mockReturnValueOnce({ status: 0, stdout: "v11", stderr: "" })
+ .mockReturnValue({ status: 0, stdout: "v12", stderr: "" });
+
+ expect(waitForAttachedMcpCredential("alpha", entry)).toBe("v12");
+ expect(exec).toHaveBeenCalledTimes(3);
+ });
+
+ it("rejects a stable pre-update revision until the opaque provider mutation is projected", () => {
+ const entry: McpBridgeEntry = {
+ server: "github",
+ agent: "openclaw",
+ adapter: "mcporter",
+ url: "https://mcp.example.test/mcp",
+ env: ["GITHUB_TOKEN"],
+ providerName: "alpha-mcp-github-0123456789abcdef",
+ providerId: "11111111-2222-4333-8444-555555555555",
+ policyName: "mcp-bridge-github",
+ addedAt: "2026-06-01T00:00:00.000Z",
+ };
+ const exec = vi
+ .spyOn(processRecovery, "executeSandboxExecCommand")
+ .mockReturnValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" })
+ .mockReturnValueOnce({ status: 0, stdout: "v15566468742889590075", stderr: "" })
+ .mockReturnValueOnce({ status: 0, stdout: "v7480654703696766813", stderr: "" })
+ .mockReturnValue({ status: 0, stdout: "v7480654703696766813", stderr: "" });
+
+ expect(
+ waitForAttachedMcpCredential("alpha", entry, {
+ previousRevision: "v15566468742889590075",
+ }),
+ ).toBe("v7480654703696766813");
+ expect(exec).toHaveBeenCalledTimes(4);
+ });
+
it("does not accept an identityless placeholder as attachment readiness", () => {
vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1");
vi.spyOn(processRecovery, "executeSandboxExecCommand").mockReturnValue({
@@ -417,7 +465,7 @@ alpha-mcp-slack generic 1 0
const exec = vi
.spyOn(processRecovery, "executeSandboxExecCommand")
.mockReturnValueOnce({ status: 0, stdout: "absent", stderr: "" })
- .mockReturnValueOnce({ status: 0, stdout: "v12", stderr: "" });
+ .mockReturnValue({ status: 0, stdout: "v12", stderr: "" });
const refreshAfterObservedAbsence = vi.fn();
const revision = waitForAttachedMcpCredential("alpha", entry, {
@@ -425,7 +473,7 @@ alpha-mcp-slack generic 1 0
});
expect(refreshAfterObservedAbsence).toHaveBeenCalledTimes(1);
- expect(exec).toHaveBeenCalledTimes(2);
+ expect(exec).toHaveBeenCalledTimes(3);
expect(revision).toBe("v12");
});
@@ -604,7 +652,7 @@ alpha-mcp-slack generic 1 0
});
expect(waitForAttachedMcpCredential("alpha", entry, { previousRevision: "v11" })).toBe("v12");
- expect(exec).toHaveBeenCalledTimes(1);
+ expect(exec).toHaveBeenCalledTimes(2);
vi.stubEnv("NEMOCLAW_MCP_PROVIDER_SYNC_TIMEOUT_SECONDS", "1");
exec.mockClear();
diff --git a/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.test.ts b/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.test.ts
index bb7016825d3..3f3293f450d 100644
--- a/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.test.ts
+++ b/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.test.ts
@@ -13,6 +13,7 @@ describe("printHermesGatewayRestoreHint (#7312)", () => {
"hermes",
["runtime/state.db"],
[{ path: "runtime/state.db", strategy: "sqlite_backup" }],
+ "nemoclaw",
writeLine,
);
@@ -31,6 +32,7 @@ describe("printHermesGatewayRestoreHint (#7312)", () => {
{ path: "SOUL.md", strategy: "copy" },
{ path: "runtime/state.db", strategy: "sqlite_backup" },
],
+ "nemoclaw",
writeLine,
);
@@ -45,6 +47,7 @@ describe("printHermesGatewayRestoreHint (#7312)", () => {
"openclaw",
["openclaw.json"],
[{ path: "openclaw.json", strategy: "copy" }],
+ "nemoclaw",
writeLine,
);
printHermesGatewayRestoreHint(
@@ -52,6 +55,7 @@ describe("printHermesGatewayRestoreHint (#7312)", () => {
undefined,
["runtime/state.db"],
[{ path: "runtime/state.db", strategy: "sqlite_backup" }],
+ "nemoclaw",
writeLine,
);
diff --git a/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.ts b/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.ts
index 0aa018a7e91..cb426b277bf 100644
--- a/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.ts
+++ b/src/lib/actions/sandbox/snapshot-hermes-gateway-hint.ts
@@ -1,8 +1,6 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
-import { CLI_NAME } from "../../cli/branding";
-
interface SnapshotStateFile {
path: string;
strategy: "copy" | "sqlite_backup";
@@ -20,6 +18,7 @@ export function printHermesGatewayRestoreHint(
agentName: string | null | undefined,
restoredFiles: readonly string[],
snapshotStateFiles: readonly SnapshotStateFile[],
+ cliName: string,
writeLine: (message: string) => void = console.log,
): void {
if (agentName !== "hermes") return;
@@ -29,6 +28,6 @@ export function printHermesGatewayRestoreHint(
);
if (!restoredSqliteDatabase) return;
writeLine(
- ` Restart the gateway to open the restored state databases: run \`${CLI_NAME} ${sandboxName} gateway restart\``,
+ ` Restart the gateway to open the restored state databases: run \`${cliName} ${sandboxName} gateway restart\``,
);
}
diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts
index 4f780f920ef..54fe0fc1554 100644
--- a/src/lib/actions/sandbox/snapshot.ts
+++ b/src/lib/actions/sandbox/snapshot.ts
@@ -1820,6 +1820,7 @@ async function runSnapshotRestoreUnlocked(
registry.getSandbox(targetSandbox)?.agent,
result.restoredFiles,
resolvedSnapshot?.stateFiles ?? [],
+ CLI_NAME,
);
} else {
console.error(` Restore failed.`);
diff --git a/test/agents/hermes/hermes-mcp-credential-revision.test.ts b/test/agents/hermes/hermes-mcp-credential-revision.test.ts
index b6f33f29561..66e2ff25649 100644
--- a/test/agents/hermes/hermes-mcp-credential-revision.test.ts
+++ b/test/agents/hermes/hermes-mcp-credential-revision.test.ts
@@ -13,24 +13,23 @@ const TRANSACTION = path.resolve(
);
describe("Hermes MCP credential revision transaction", () => {
- it("accepts only the exact bounded revision declared by the host (#10155)", () => {
+ it("accepts a child-visible bounded revision and preserves exact comparison (#10155)", () => {
const result = spawnSync(
"python3",
[
"-c",
- `import importlib.util, json, sys
+ `import importlib.util, json, os, sys
spec = importlib.util.spec_from_file_location("mcp_tx", sys.argv[1])
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
+os.environ["FAKE_TOKEN"] = "openshell:resolve:env:v12_FAKE_TOKEN"
base = {
"server": "fake",
"url": "https://mcp.example.test/mcp",
"headers": {"Authorization": "Bearer openshell:resolve:env:v12_FAKE_TOKEN"},
"replace_existing": True,
- "credential_name": "FAKE_TOKEN",
- "credential_revision": "v12",
}
canonical = {
"server": "fake",
@@ -41,13 +40,32 @@ canonical = {
cases = {
"exact": base,
"canonical": canonical,
- "missingRevision": {key: value for key, value in base.items() if key != "credential_revision"},
- "missingName": {key: value for key, value in base.items() if key != "credential_name"},
- "mismatchedRevision": {**base, "credential_revision": "v11"},
- "malformedRevision": {**base, "credential_revision": "v"},
- "overlongRevision": {**base, "credential_revision": "v" + "1" * 21},
+ "malformedRevision": {
+ **base,
+ "headers": {"Authorization": "Bearer openshell:resolve:env:v-12_FAKE_TOKEN"},
+ },
+ "overlongRevision": {
+ **base,
+ "headers": {
+ "Authorization": "Bearer openshell:resolve:env:v" + "1" * 21 + "_FAKE_TOKEN"
+ },
+ },
"wrongName": {**base, "headers": {"Authorization": "Bearer openshell:resolve:env:v12_OTHER_TOKEN"}},
- "metadataOnRemove": {**base, "force": False},
+ "unobserved": {
+ **base,
+ "headers": {"Authorization": "Bearer openshell:resolve:env:v11_FAKE_TOKEN"},
+ },
+ "metadataOnAdd": {
+ **base,
+ "credential_name": "FAKE_TOKEN",
+ "credential_revision": "v12",
+ },
+ "metadataOnRemove": {
+ **base,
+ "credential_name": "FAKE_TOKEN",
+ "credential_revision": "v12",
+ "force": False,
+ },
}
cases["metadataOnRemove"].pop("replace_existing")
results = {}
@@ -57,7 +75,28 @@ for name, payload in cases.items():
results[name] = "accepted"
except ValueError:
results[name] = "rejected"
-print(json.dumps(results))`,
+
+canonical_candidate = module._managed_candidate(canonical)
+revisioned_candidate = module._managed_candidate(base)
+stale_candidate = module._managed_candidate({
+ **base,
+ "headers": {"Authorization": "Bearer openshell:resolve:env:v11_FAKE_TOKEN"},
+})
+comparison = {
+ "bounded": module._managed_candidate_matches(
+ revisioned_candidate, canonical_candidate, True
+ ),
+ "exactRejectsRevision": module._managed_candidate_matches(
+ revisioned_candidate, canonical_candidate, False
+ ),
+ "exactRejectsStale": module._managed_candidate_matches(
+ stale_candidate, revisioned_candidate, True
+ ),
+ "exactAcceptsCurrent": module._managed_candidate_matches(
+ revisioned_candidate, revisioned_candidate, False
+ ),
+}
+print(json.dumps({"validation": results, "comparison": comparison}))`,
TRANSACTION,
],
{ encoding: "utf8" },
@@ -65,15 +104,22 @@ print(json.dumps(results))`,
expect(result.status, result.stderr).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({
- exact: "accepted",
- canonical: "accepted",
- missingRevision: "rejected",
- missingName: "rejected",
- mismatchedRevision: "rejected",
- malformedRevision: "rejected",
- overlongRevision: "rejected",
- wrongName: "rejected",
- metadataOnRemove: "rejected",
+ validation: {
+ canonical: "accepted",
+ exact: "accepted",
+ malformedRevision: "rejected",
+ metadataOnAdd: "rejected",
+ metadataOnRemove: "rejected",
+ overlongRevision: "rejected",
+ unobserved: "rejected",
+ wrongName: "rejected",
+ },
+ comparison: {
+ bounded: true,
+ exactRejectsRevision: false,
+ exactRejectsStale: false,
+ exactAcceptsCurrent: true,
+ },
});
});
});
diff --git a/test/agents/hermes/hermes-mcp-integrity-state.test.ts b/test/agents/hermes/hermes-mcp-integrity-state.test.ts
index d8629b2672b..4eea68f4fff 100644
--- a/test/agents/hermes/hermes-mcp-integrity-state.test.ts
+++ b/test/agents/hermes/hermes-mcp-integrity-state.test.ts
@@ -313,6 +313,63 @@ print(json.dumps({
});
});
+ it("validates but does not replace already-current applied-state anchors", () => {
+ const result = spawnSync(
+ "python3",
+ [
+ "-I",
+ "-c",
+ String.raw`
+import importlib.util, json, os, sys, tempfile
+spec = importlib.util.spec_from_file_location("hermes_guard", sys.argv[1])
+guard = importlib.util.module_from_spec(spec)
+sys.modules[spec.name] = guard
+spec.loader.exec_module(guard)
+root = tempfile.mkdtemp(prefix="hermes-mcp-current-apply-")
+hermes = os.path.join(root, ".hermes")
+os.mkdir(hermes)
+config = os.path.join(hermes, "config.yaml")
+env = os.path.join(hermes, ".env")
+strict = os.path.join(root, "hermes.config-hash")
+compat = os.path.join(hermes, ".config-hash")
+open(config, "w", encoding="utf-8").write("model: test\n")
+open(env, "w", encoding="utf-8").write("SAFE=1\n")
+hash_text, _config_snapshot, _env_snapshot = guard._hash_text(config, env)
+guard._write_hash(strict, hash_text)
+guard._write_hash(compat, hash_text)
+before = {path: os.stat(path).st_ino for path in (strict, compat)}
+writes = []
+original_write_hash = guard._write_hash
+
+def captured_write_hash(path, text):
+ writes.append(path)
+ original_write_hash(path, text)
+
+guard._write_hash = captured_write_hash
+guard.refresh_hashes(hermes, strict, "both", mcp_transition="apply")
+guard.refresh_hashes(hermes, strict, "compat", mcp_transition="apply")
+after = {path: os.stat(path).st_ino for path in (strict, compat)}
+print(json.dumps({
+ "state": guard.inspect_mcp_integrity(hermes, strict),
+ "writes": writes,
+ "strict_inode_stable": before[strict] == after[strict],
+ "compat_inode_stable": before[compat] == after[compat],
+}))
+`,
+ GUARD,
+ ],
+ { encoding: "utf-8", timeout: 10_000 },
+ );
+
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({
+ state: "current",
+ writes: [],
+ strict_inode_stable: true,
+ compat_inode_stable: true,
+ });
+ });
+
it("runs startup-owned MCP inspection as a direct child", () => {
const source = fs.readFileSync(START, "utf-8");
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-mcp-parent-"));
diff --git a/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts b/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts
index 136fc3c5875..32aea9039f1 100644
--- a/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts
+++ b/test/e2e/support/mcp-bridge-hermes-lifecycle.test.ts
@@ -1,6 +1,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
import { describe, expect, it } from "vitest";
import { type CommandRunner, HostCliClient, SandboxClient } from "../fixtures/clients/index.ts";
@@ -55,6 +60,54 @@ class RecordingRunner implements CommandRunner {
}
}
+class HermesConfigAssertionRunner implements CommandRunner {
+ constructor(private readonly configPath: string) {}
+
+ async run(command: TrustedShellCommand): Promise {
+ const shellScript = command.args.at(-1) ?? "";
+ const marker = "/opt/hermes/.venv/bin/python - <<'PY'\n";
+ const scriptStart = shellScript.indexOf(marker) + marker.length;
+ const scriptEnd = shellScript.lastIndexOf("\nPY");
+ expect(scriptStart, "Hermes config assertion Python start").toBeGreaterThanOrEqual(
+ marker.length,
+ );
+ expect(scriptEnd, "Hermes config assertion Python end").toBeGreaterThanOrEqual(scriptStart);
+ const pythonScript = shellScript
+ .slice(scriptStart, scriptEnd)
+ .replace("import pathlib, re, yaml", "import pathlib, re, sys, yaml")
+ .replace(
+ "path = pathlib.Path('/sandbox/.hermes/config.yaml')",
+ "path = pathlib.Path(sys.argv[1])",
+ );
+ const result = spawnSync("python3", ["-", this.configPath], {
+ encoding: "utf8",
+ input: pythonScript,
+ killSignal: "SIGKILL",
+ timeout: 10_000,
+ });
+ const error = result.error?.message ?? "";
+ return shellResult(
+ result.status ?? 1,
+ result.stdout,
+ [result.stderr, error].filter(Boolean).join("\n"),
+ );
+ }
+}
+
+function writeHermesConfig(configPath: string, authorization: string): void {
+ fs.writeFileSync(
+ configPath,
+ JSON.stringify({
+ mcp_servers: {
+ fake: {
+ url: "https://mcp.example.test/mcp",
+ headers: { Authorization: authorization },
+ },
+ },
+ }),
+ );
+}
+
function sandboxWithInspectionState(state: string): SandboxClient {
return new SandboxClient({
run: async () => ({
@@ -99,15 +152,40 @@ describe("Hermes MCP live rollback inspection", () => {
});
describe("Hermes MCP managed configuration assertion", () => {
- it("requires the revision-scoped OpenShell credential placeholder (#10155)", async () => {
- const runner = new RecordingRunner();
- const sandbox = new SandboxClient(runner);
+ it("accepts a revision-scoped credential placeholder through the sandbox boundary (#10155)", async () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-config-assertion-"));
+ const configPath = path.join(temp, "config.yaml");
+ writeHermesConfig(configPath, "Bearer openshell:resolve:env:v12_FAKE_MCP_SECRET");
- await assertHermesConfig(sandbox, "hermes-e2e", "https://mcp.example.test/mcp");
+ try {
+ await expect(
+ assertHermesConfig(
+ new SandboxClient(new HermesConfigAssertionRunner(configPath)),
+ "hermes-e2e",
+ "https://mcp.example.test/mcp",
+ ),
+ ).resolves.toBeUndefined();
+ } finally {
+ fs.rmSync(temp, { force: true, recursive: true });
+ }
+ });
- const command = runner.calls[0]?.args.at(-1) ?? "";
- expect(command).toContain("Bearer openshell:resolve:env:v[0-9]{1,20}_FAKE_MCP_SECRET");
- expect(command).not.toContain("== 'Bearer openshell:resolve:env:FAKE_MCP_SECRET'");
+ it("rejects an unscoped credential placeholder through the sandbox boundary (#10155)", async () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-config-assertion-"));
+ const configPath = path.join(temp, "config.yaml");
+ writeHermesConfig(configPath, "Bearer openshell:resolve:env:FAKE_MCP_SECRET");
+
+ try {
+ await expect(
+ assertHermesConfig(
+ new SandboxClient(new HermesConfigAssertionRunner(configPath)),
+ "hermes-e2e",
+ "https://mcp.example.test/mcp",
+ ),
+ ).rejects.toThrow("Hermes MCP config contains placeholder and no raw host secret failed");
+ } finally {
+ fs.rmSync(temp, { force: true, recursive: true });
+ }
});
});
diff --git a/test/mcp/mcp-add-crash-consistency.test.ts b/test/mcp/mcp-add-crash-consistency.test.ts
index a9099784655..7f8006276b6 100644
--- a/test/mcp/mcp-add-crash-consistency.test.ts
+++ b/test/mcp/mcp-add-crash-consistency.test.ts
@@ -53,6 +53,10 @@ const marker = (name) => path.join(process.env.HOME, name + ".marker");
const mark = (name) => fs.writeFileSync(marker(name), "yes\n", { mode: 0o600 });
const marked = (name) => fs.existsSync(marker(name));
const providerVersion = () => Number.parseInt(marked("provider-version") ? fs.readFileSync(marker("provider-version"), "utf8") : "1", 10);
+// OpenShell provider resource versions and child credential revisions are
+// separate identities. Keep the fixture values unrelated so readiness cannot
+// derive one from the other.
+const childCredentialRevision = () => "v" + (4067750153477477213n + BigInt(providerVersion())).toString();
const setProviderVersion = (version) => fs.writeFileSync(marker("provider-version"), String(version), { mode: 0o600 });
const providerPresentAtStart = marked("provider");
const providerId = "11111111-2222-4333-8444-555555555555";
@@ -243,7 +247,7 @@ processRecovery.executeSandboxExecCommand = (_sandbox, command) => {
}
return {
status: 0,
- stdout: credentialRepublishBeforeObservationCountThisProcess > 0 ? "v" + providerVersion() : "absent",
+ stdout: credentialRepublishBeforeObservationCountThisProcess + credentialRepublishAfterAbsenceCountThisProcess > 0 ? childCredentialRevision() : "absent",
stderr: "",
};
}
@@ -254,13 +258,13 @@ processRecovery.executeSandboxExecCommand = (_sandbox, command) => {
}
return {
status: 0,
- stdout: credentialFreeRefreshAfterAbsenceCountThisProcess > 0 ? "v" + providerVersion() : "absent",
+ stdout: credentialFreeRefreshAfterAbsenceCountThisProcess > 0 ? childCredentialRevision() : "absent",
stderr: "",
};
}
return {
status: crashAfter === "preupdate-observation-forbidden" && isPreupdateObservation ? 1 : 0,
- stdout: isObservation ? (marked("updated") ? "v" + providerVersion() : marked("provider") ? "v1" : "absent") : "",
+ stdout: isObservation ? (marked("updated") || marked("provider") ? childCredentialRevision() : "absent") : "",
stderr: "",
};
};
@@ -631,11 +635,11 @@ describe("MCP add crash consistency", () => {
expect(results.map((result) => result.status).sort(), combinedOutput).toEqual([0, 2]);
expect(results.find((result) => result.status === 2)?.stderr).toContain("already exists");
expect(combinedOutput).not.toContain("host-only-secret");
- expect(fs.existsSync(path.join(home, "credential-observed-absent.marker"))).toBe(false);
- expect(fs.existsSync(path.join(home, "republish-before-observation.marker"))).toBe(true);
- expect(fs.existsSync(path.join(home, "republish-after-observed-absence.marker"))).toBe(false);
+ expect(fs.existsSync(path.join(home, "credential-observed-absent.marker"))).toBe(true);
+ expect(fs.existsSync(path.join(home, "republish-before-observation.marker"))).toBe(false);
+ expect(fs.existsSync(path.join(home, "republish-after-observed-absence.marker"))).toBe(true);
const credentialRepublishCount = fs
- .readFileSync(path.join(home, "republish-before-observation.marker"), "utf8")
+ .readFileSync(path.join(home, "republish-after-observed-absence.marker"), "utf8")
.split("\n")
.filter(Boolean).length;
expect(credentialRepublishCount).toBe(1);
diff --git a/test/mcp/mcp-destroy-lifecycle.test.ts b/test/mcp/mcp-destroy-lifecycle.test.ts
index b90dee5c37b..77161ed473e 100644
--- a/test/mcp/mcp-destroy-lifecycle.test.ts
+++ b/test/mcp/mcp-destroy-lifecycle.test.ts
@@ -1326,7 +1326,7 @@ describe("authenticated MCP sandbox destroy lifecycle", () => {
["destroy", "prepareMcpBridgesForDestroy"],
["rebuild", "prepareMcpBridgesForRebuild"],
] as const)(
- "reattaches an already-absent first provider when a later %s detach fails",
+ "fails closed before a later %s detach when an already-detached provider has no provable credential revision",
async (_label, prepareFunction) => {
registry.registerSandbox({
name: "alpha",
@@ -1343,19 +1343,21 @@ describe("authenticated MCP sandbox destroy lifecycle", () => {
const message = await captureMessage(() => bridge[prepareFunction]("alpha"));
- expect(message).toContain("provider detach failed");
- expect([...testState.attachedProviders].sort()).toEqual([
- "alpha-mcp-github",
- "alpha-mcp-slack",
- ]);
+ expect(message).toContain(
+ "Could not prove a revision-scoped credential before removing the managed adapter entry for MCP server 'github'.",
+ );
+ expect([...testState.attachedProviders]).toEqual(["alpha-mcp-slack"]);
expect(
testState.calls.some((call) => call === "sandbox provider attach alpha alpha-mcp-github"),
- ).toBe(true);
+ ).toBe(false);
+ expect(
+ testState.calls.some((call) => call === "sandbox provider detach alpha alpha-mcp-slack"),
+ ).toBe(false);
expect(testState.adapterRegistered).toBe(true);
},
);
- it("reattaches every desired provider when rebuild deletion aborts after a retry", async () => {
+ it("reattaches every desired provider when rebuild deletion aborts", async () => {
registry.registerSandbox({
name: "alpha",
agent: "openclaw",
@@ -1364,9 +1366,8 @@ describe("authenticated MCP sandbox destroy lifecycle", () => {
});
registry.addCustomPolicy("alpha", ownedPolicy("github"));
registry.addCustomPolicy("alpha", ownedPolicy("slack"));
- // The first rebuild process died after detaching github. A retry completes
- // preparation, then sandbox deletion is modeled as failed by invoking abort.
- testState.attachedProviders.delete("alpha-mcp-github");
+ // Preparation proves both credential revisions before detaching either
+ // provider, then sandbox deletion is modeled as failed by invoking abort.
const preparation = await bridge.prepareMcpBridgesForRebuild("alpha");
const detachedBeforeAbort = [...testState.attachedProviders].sort();
diff --git a/test/mcp/mcp-restart-policy-order.test.ts b/test/mcp/mcp-restart-policy-order.test.ts
index 5b91e847f2c..58cf661d4cb 100644
--- a/test/mcp/mcp-restart-policy-order.test.ts
+++ b/test/mcp/mcp-restart-policy-order.test.ts
@@ -302,13 +302,13 @@ bridge.restartMcpBridge("alpha", "example").then(
providerCalls: string[];
registeredProviderGets: number;
};
- expect(payload.observations).toEqual(["v1", "v3"]);
+ expect(payload.observations).toEqual(["v1", "v3", "v3"]);
expect(payload.providerCalls).toEqual([
"provider update alpha-mcp-example --credential MCP_TOKEN",
"provider update alpha-mcp-example",
]);
expect(payload.registeredProviderGets).toBe(1);
- expect(payload.proofScripts).toHaveLength(2);
+ expect(payload.proofScripts).toHaveLength(3);
expect(payload.proofScripts.join("\n")).not.toMatch(/\/tmp|snapshot/);
});
});
diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts
index bb08e8b1149..ba05c49c492 100644
--- a/test/repository/vitest-watch-triggers.test.ts
+++ b/test/repository/vitest-watch-triggers.test.ts
@@ -333,7 +333,6 @@ describe("Vitest opaque-input watch triggers", () => {
]);
expect(triggeredBy(".github/workflows/pr-review-advisor.yaml")).toEqual([
"test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts",
- "test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts",
]);
expect(triggeredBy("tools/pr-review-advisor/openshell-policy.yaml")).toEqual([
"test/automation/pull-requests/pr-review-advisor-workflow-boundary.test.ts",