diff --git a/adapters/python/openclaw/README.md b/adapters/python/openclaw/README.md index 5e71bc660..a5ac30531 100644 --- a/adapters/python/openclaw/README.md +++ b/adapters/python/openclaw/README.md @@ -30,12 +30,11 @@ Install the adapter in every NeMo Fabric environment: pip install "nemo-fabric[openclaw]" ``` -Managed runtimes and NeMo Fabric-owned services also require the pinned OpenClaw -version: +Install OpenClaw 2026.11.13 for managed runtimes and NeMo Fabric-owned services: ```bash # Requires Node.js >=24.22.1 <25 or >=26.12.1, and npm 11.16+. -npm install --global openclaw@2026.9.34 --allow-scripts=openclaw +npm install --global openclaw@2026.11.13 --allow-scripts=openclaw ``` An attachment to a caller-owned Gateway does not require a local OpenClaw @@ -45,16 +44,6 @@ prepared use, if `openclaw` is not in `PATH`, set bare command is resolved through `PATH`; a relative path containing a directory is resolved from the NeMo Fabric base directory. -### Upgrade a Gateway With Retained State - -When upgrading a caller-owned Gateway from OpenClaw 2026.9.4, stop the Gateway and run `openclaw backup create --verify` with the Gateway's existing `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH` before upgrading. The backup must include the active config, its include files, and all configured agent directories, including paths outside the state directory. Protect the archive because it can contain credentials. - -Before upgrading, check the backup result and manifest for the active config, its include files, and every configured agent directory. For paths marked `covered`, confirm that the archive contains the data under a parent directory. Fix missing required paths and rerun the backup. Continue with the upgrade after confirming that all required data is backed up. - -Before migration, copy every legacy session directory while the Gateway is stopped. Include `sessions.json`, `.jsonl` transcripts, and session directories outside `OPENCLAW_STATE_DIR`. The backup command excludes legacy `.jsonl` transcripts. Protect these copies and keep them with the verified archive for rollback. - -Run `openclaw doctor --fix` with the 2026.9.34 executable and the same path settings. The command imports legacy `sessions.json` files and JSONL session data into each agent's SQLite database. Restart the Gateway after the command succeeds. Keep the verified backup for rollback. - Managed runtimes and NeMo Fabric-owned services use temporary state by default. Set `runtime.keep_state=true` to retain the native Gateway home across restarts. ## Configuration @@ -169,9 +158,8 @@ The following settings are specific to the OpenClaw adapter: | `shutdown_timeout_seconds` | `15` | Graceful Gateway shutdown timeout. OpenClaw's descriptor allows 30 seconds for the complete adapter stop. Overrides must leave time for cleanup within that limit. Stop reports an error if the Gateway process is still running after cleanup. | | `connect_timeout_seconds` | `10` | Local HTTP connection timeout. | | `read_timeout_seconds` | None | Local HTTP response timeout. When unset, the invocation timeout bounds the response. | -| `agents.defaults.heartbeat.every` | OpenClaw native default | Recurring heartbeat interval with units, such as `30m`; `0m` disables the recurring cadence but not event-driven turns. | | `agents.defaults.compaction.memoryFlush.enabled` | OpenClaw native default | Pre-compaction memory flush turn. Compaction itself still runs. | -| `tools.exec.notifyOnExit` | OpenClaw native default | System event and heartbeat when a backgrounded `exec` process exits. | +| `tools.exec.notifyOnExit` | OpenClaw native default | Notification when a backgrounded `exec` process exits. | | `tools.toolSearch` | OpenClaw native default | Tool search for large tool catalogs. | | `tools.codeMode` | OpenClaw native default | Code Mode, which can take precedence over tool search and exposes only `exec` and `wait`; do not combine it with blocking `exec`. | | `tools.web.fetch.ssrfPolicy.allowRfc2544BenchmarkRange` | OpenClaw native default (blocked) | Lets `web_fetch`, `image`, and `pdf` connect to `198.18.0.0/15`; set it only behind a fake-IP proxy that owns the range and enforces its own destination policy. | @@ -181,11 +169,13 @@ The following settings are specific to the OpenClaw adapter: The `agents` and `tools` settings use OpenClaw's native structure, and `plugins` maps onto it. The adapter merges only the fields you set into the generated `openclaw.json` for managed runtimes and prepared services, beside the generated `agents.defaults`, `tools.allow`, `tools.deny`, and adapter-owned plugin entries, without replacing generated keys. Omitting a field preserves the current behavior. `harness.settings.tools` is separate from the normalized top-level `tools.enabled` and `tools.blocked` selectors. Attached Gateways reject these settings. These controls do not stop context compaction or correlate concurrent sessions, and they do not add NeMo Relay support; refer to [Native Gateway Controls](../../../docs/integrations/harness/openclaw/openclaw.mdx#native-gateway-controls). +Create and manage saved scheduled jobs with `openclaw automations`. + OpenClaw's [derived-port mapping](https://docs.openclaw.ai/gateway/multiple-gateways#port-mapping-derived) uses `base_port + 2` for browser control and allocates browser CDP ports from `base_port + 11` through `base_port + 110`. Set `port_range` when the consumer reserves a port range before configuring NeMo Fabric; the adapter selects a base whose complete derived footprint fits inside that range. The adapter verifies only that `base_port` and `base_port + 2` are available before startup. OpenClaw allocates the CDP ports on demand instead of reserving the complete range, so the adapter cannot guarantee that those ports will still be available when OpenClaw needs them. Keep the configured range reserved for the lifetime of the runtime when using OpenClaw browser features. With native interfaces enabled, one Gateway owns all four client paths. A small adapter-owned plugin adds the configured instruction for the selected agent through the public `before_prompt_build` hook while preserving OpenClaw's native prompt and tool guidance. SDK requests omit duplicate instruction injection in that mode; SDK-only and service behavior are preserved. The existing `replace` mode selects the Fabric instruction without replacing OpenClaw's internal prompt. Model, workspace, tools, MCP, and skill configuration are shared; native responses remain native. -Startup verifies the loaded hook through an authenticated, model-free probe before publishing connection files. Missing, blocked, or mismatched hooks fail with `openclaw_shared_configuration_unavailable`. The plugin requires both `allowConversationAccess` and `allowPromptInjection`: pinned OpenClaw gates `before_prompt_build` behind both permissions for external plugins. +Startup verifies the loaded hook through an authenticated, model-free probe before publishing connection files. Missing, blocked, or mismatched hooks fail with `openclaw_shared_configuration_unavailable`. On OpenClaw 2026.11.13, the plugin requires both `allowConversationAccess` and `allowPromptModification`. After readiness, private `interfaces/gateway.json` discovery references `dashboard.token` or `gateway.token`. Terminal selection adds an executable `interfaces/terminal` and `terminal.running` marker; the marker is removed first on stop. The launcher uses private client configuration and an environment SecretRef, not token arguments. Terminal attachment currently requires POSIX. Pinned TUI `/quit` can use a native exit-code-130 fallback while the Gateway stays usable. @@ -237,7 +227,7 @@ Gateway HTTP errors, provider failures, and request timeouts also require recove NeMo Fabric retains known unresolved tool calls in its completion record. A gap in the Gateway's recent history window also requires recovery acknowledgment. New work can confirm completion after acknowledgment when its history remains visible. -Keep native session resets separate from SDK invocations. The adapter checks the native session UUID around history reads and before dispatch. OpenClaw 2026.9.34 has no expected-UUID condition on Chat Completions requests, so a reset after the final check can still redirect a turn. The remaining dispatch race is tracked in [#638](https://github.com/NVIDIA/NeMo-Fabric/issues/638). +Keep native session resets separate from SDK invocations. The adapter checks the native session UUID around history reads and before dispatch. A reset after the final check can still redirect a turn. The remaining dispatch race is tracked in [#638](https://github.com/NVIDIA/NeMo-Fabric/issues/638). A prepared service keeps the Gateway and retained-state lock until release. Stopping a connected runtime closes that runtime's client. The service continues serving native chat channels. A retained namespace allows one connected runtime at a time. Failed Gateway cleanup retains ownership and can be retried before a replacement starts. Caller-owned attached services reject retained sessions because the current service reference cannot verify a native storage boundary. @@ -352,7 +342,7 @@ shows a sanitized service handle: "agent_id": "default" }, "metadata": { - "openclaw_version": "2026.9.34" + "openclaw_version": "2026.11.13" } } ``` @@ -522,3 +512,17 @@ workspace, as shown in the [calculator example](../../../examples/harbor/calculator/README.md#4-openclaw). Software evidence forwards the version returned by existing startup/service checks; it adds no request. Shared-service runtimes retain the service's original capture time when the reported version is unchanged. The reported service version describes OpenClaw only; it does not establish a complete remote installation inventory. Set `FabricConfig.provenance.enabled=false` before initialization to skip provenance collection. + +## OpenClaw 2026.9.34 + +The adapter also supports OpenClaw 2026.9.34. On this release, set `agents.defaults.heartbeat.every` to control recurring heartbeat turns. The interval requires units, such as `30m` or `1h30m`. Set `0m` to disable the recurring cadence; event-driven turns remain enabled. + +```yaml +harness: + adapter_id: nvidia.fabric.openclaw + settings: + agents: + defaults: + heartbeat: + every: 0m +``` diff --git a/adapters/python/openclaw/openclaw.fabric-adapter.json b/adapters/python/openclaw/openclaw.fabric-adapter.json index 46db03fe8..d4325fb4b 100644 --- a/adapters/python/openclaw/openclaw.fabric-adapter.json +++ b/adapters/python/openclaw/openclaw.fabric-adapter.json @@ -175,7 +175,7 @@ "every": { "type": "string", "pattern": "^(?:[0-9]+(?:\\.[0-9]+)?(?:ms|s|m|h|d))+$", - "description": "Native recurring heartbeat interval, such as 30m or 1h30m. Units are required; 0m disables the recurring cadence but not event-driven turns." + "description": "OpenClaw 2026.9.34 recurring heartbeat interval, such as 30m or 1h30m. Units are required; 0m disables recurring cadence but not event-driven turns. OpenClaw 2026.11.13 rejects this setting; use openclaw doctor --fix offline to convert an existing monitor into a saved scheduled job." } }, "additionalProperties": false diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py index 967cb2f7f..2723b6e03 100644 --- a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py @@ -60,7 +60,7 @@ OPENCLAW_SERVICE_TYPE = "openclaw_gateway" OPENCLAW_ADAPTER_ID = "nvidia.fabric.openclaw" OPENCLAW_USAGE_EVIDENCE = "nvidia.fabric.openclaw.usage_evidence.v1" -SUPPORTED_OPENCLAW_VERSIONS = frozenset({"2026.9.34"}) +SUPPORTED_OPENCLAW_VERSIONS = frozenset({"2026.9.34", "2026.11.13"}) MAX_PORT_ATTEMPTS = 20 MAX_DERIVED_PORT_OFFSET = 110 MAX_TCP_PORT = 65_535 @@ -841,6 +841,7 @@ def _openclaw_config( service_mode: bool = False, dashboard: bool = False, skill_plan: openclaw_skills.SkillPlan | None = None, + openclaw_version: str = "2026.9.34", ) -> dict[str, Any]: model = _selected_model(config) model_id = _model_id(model) @@ -1004,6 +1005,11 @@ def _openclaw_config( metadata={"field": "harness.settings.channel_config"}, ) result.update(channel_config) + if openclaw_version == "2026.11.13": + for entry in result.get("plugins", {}).get("entries", {}).values(): + hooks = entry.get("hooks", {}) + if "allowPromptInjection" in hooks: + hooks["allowPromptModification"] = hooks.pop("allowPromptInjection") return result @@ -1745,6 +1751,18 @@ def startup_remaining() -> float: command, "--version", env=child_env, timeout=startup_remaining() ) version = _validate_openclaw_version(version_output) + if version == "2026.11.13" and "heartbeat" in settings.get("agents", {}).get( + "defaults", {} + ): + raise lifecycle.LifecycleError( + "openclaw_unsupported_heartbeat", + "OpenClaw 2026.11.13 retired agents.defaults.heartbeat. Run " + "openclaw doctor --fix offline to convert an existing heartbeat " + "monitor into a saved scheduled job, then remove " + "harness.settings.agents.defaults.heartbeat and manage the job " + "through OpenClaw automations.", + metadata={"field": "harness.settings.agents.defaults.heartbeat"}, + ) from nemo_fabric_adapters.common.provenance import record_version record_version( @@ -1820,13 +1838,14 @@ def startup_remaining() -> float: service_mode=service is not None and service.get("operation") == "prepare", dashboard=dashboard_port is not None, skill_plan=skill_plan, + openclaw_version=version, ) plugin_section = generated.get("plugins", {}) if context.state_dir: # The agent's plugin commands write through the include. state_config = openclaw_plugins.state_folder(state_dir) plugin_section = openclaw_plugins.prepare( - state_config, generated.pop("plugins", {}) + state_config, generated.pop("plugins", {}), openclaw_version=version ) generated["plugins"] = dict(openclaw_plugins.INCLUDE) config_path = state_config / openclaw_plugins.CONFIG_FILE diff --git a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/plugins.py b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/plugins.py index 0acff977c..29d535010 100644 --- a/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/plugins.py +++ b/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/plugins.py @@ -257,11 +257,53 @@ def _digest(text: str) -> str: return hashlib.sha256(text.encode()).hexdigest() -def prepare(folder: Path, fabric: dict[str, Any]) -> dict[str, Any]: +def _prompt_permission(section: dict[str, Any], name: str) -> dict[str, Any]: + section = copy.deepcopy(section) + previous = ( + "allowPromptInjection" + if name == "allowPromptModification" + else "allowPromptModification" + ) + entries = section.get("entries") + if not isinstance(entries, dict): + return section + for entry in entries.values(): + if not isinstance(entry, dict): + continue + hooks = entry.get("hooks") + if not isinstance(hooks, dict) or previous not in hooks: + continue + if name in hooks and not _same(hooks[name], hooks[previous]): + raise ValueError( + "Conflicting allowPromptInjection and allowPromptModification; " + "resolve the plugin's prompt permission before restarting" + ) + hooks[name] = hooks.pop(previous) + return section + + +def prepare( + folder: Path, fabric: dict[str, Any], *, openclaw_version: str = "2026.9.34" +) -> dict[str, Any]: """Merge NeMo Fabric's plugin settings into ``plugins.json`` and return them.""" policy_path = folder / PLUGINS_FILE owned_path = folder / OWNED_FILE agent = _read_object(policy_path, kind="plugin settings") + entries = agent.get("entries") + if openclaw_version == "2026.9.34" and isinstance(entries, dict): + for entry in entries.values(): + hooks = entry.get("hooks") if isinstance(entry, dict) else None + if isinstance(hooks, dict) and "allowPromptModification" in hooks: + # Merging first could discard the record's shadowed values. + raise lifecycle.LifecycleError( + "openclaw_plugin_state_invalid", + "Retained plugin settings use the OpenClaw 2026.11.13 " + "permission format; OpenClaw 2026.9.34 cannot start with " + "them. Stop the Gateway and restore the matching " + "pre-upgrade state, workspace, and configuration backup " + "before restarting.", + metadata={"path": str(policy_path)}, + ) owned = _read_object(owned_path, kind="plugin ownership record") pending = owned.pop("pending", None) if isinstance(pending, dict): @@ -274,7 +316,16 @@ def prepare(folder: Path, fabric: dict[str, Any]) -> dict[str, Any]: raise _state_invalid( owned_path, "plugin ownership record", "unexpected record shape" ) + if openclaw_version == "2026.11.13": + # Keep the 0.7 ownership paths stable, including shadowed agent values. + try: + agent = _prompt_permission(agent, "allowPromptInjection") + fabric = _prompt_permission(fabric, "allowPromptInjection") + except ValueError as exc: + raise _state_invalid(policy_path, "plugin settings", str(exc)) from exc merged, record = merge_plugins(agent, fabric, owned) + if openclaw_version == "2026.11.13": + merged = _prompt_permission(merged, "allowPromptModification") text = json.dumps(merged, indent=2) + "\n" staged = {**owned, "pending": {**record, "sha256": _digest(text)}} for path, content in ( diff --git a/adapters/typescript/scripts/audit-dependencies.test.mjs b/adapters/typescript/scripts/audit-dependencies.test.mjs index 572326ad0..8d8769ed1 100644 --- a/adapters/typescript/scripts/audit-dependencies.test.mjs +++ b/adapters/typescript/scripts/audit-dependencies.test.mjs @@ -370,6 +370,27 @@ test("tar: allows the enumerated advisories and exact development parent paths b assert.equal(checkAudit(audit, lock, "adapters", tarDeadline - 1).high, 4); }); +for (const id of ["GHSA-xm6h-2993-3ch9", "GHSA-9hmx-4f52-v64x"]) { + test(`tar: allows reviewed ${id} only with the approved range and severity`, () => { + const { audit, lock } = tarFixture(); + const cause = { + ...tarAdvisory, + url: `https://github.com/advisories/${id}`, + }; + audit.vulnerabilities.tar.via.push(cause); + assert.equal(checkAudit(audit, lock, "adapters", tarNow).high, 4); + assert.throws( + () => checkAudit(audit, lock, "adapters", tarDeadline), + /expired/, + ); + cause.range = "*"; + assert.throws(() => checkAudit(audit, lock, "adapters", tarNow)); + cause.range = "<8.0.0"; + cause.severity = "critical"; + assert.throws(() => checkAudit(audit, lock, "adapters", tarNow)); + }); +} + for (const now of [tarDeadline, tarDeadline + 1, NaN]) { test(`tar: rejects an expired exception or invalid clock (${now})`, () => { const { audit, lock } = tarFixture(); diff --git a/docs/integrations/harness/openclaw/openclaw.mdx b/docs/integrations/harness/openclaw/openclaw.mdx index 1e051b85f..6cb7eaac9 100644 --- a/docs/integrations/harness/openclaw/openclaw.mdx +++ b/docs/integrations/harness/openclaw/openclaw.mdx @@ -49,23 +49,16 @@ To install OpenClaw from an npm package, then install the NeMo Fabric runtime an ```bash # Requires Node.js >=24.22.1 <25 or >=26.12.1, and npm 11.16+ -npm install --global openclaw@2026.9.34 --allow-scripts=openclaw +npm install --global openclaw@2026.11.13 --allow-scripts=openclaw pip install "nemo-fabric[openclaw]" ``` +The adapter supports OpenClaw 2026.11.13 for managed runtimes, +prepared services, and attachments to caller-owned Gateways. + To install the adapter without the NeMo Fabric runtime, use `nemo-fabric-adapters-openclaw`. The adapter package does not install OpenClaw. -### Upgrade a Gateway With Retained State - -When upgrading a caller-owned Gateway from OpenClaw 2026.9.4, stop the Gateway and run `openclaw backup create --verify` with the Gateway's existing `OPENCLAW_STATE_DIR` and `OPENCLAW_CONFIG_PATH` before upgrading. The backup must include the active config, its include files, and all configured agent directories, including paths outside the state directory. Protect the archive because it can contain credentials. - -Before upgrading, check the backup result and manifest for the active config, its include files, and every configured agent directory. For paths marked `covered`, confirm that the archive contains the data under a parent directory. Fix missing required paths and rerun the backup. Continue with the upgrade after confirming that all required data is backed up. - -Before migration, copy every legacy session directory while the Gateway is stopped. Include `sessions.json`, `.jsonl` transcripts, and session directories outside `OPENCLAW_STATE_DIR`. The backup command excludes legacy `.jsonl` transcripts. Protect these copies and keep them with the verified archive for rollback. - -Run `openclaw doctor --fix` with the 2026.9.34 executable and the same path settings. The command imports legacy `sessions.json` files and JSONL session data into each agent's SQLite database. Restart the Gateway after the command succeeds. Keep the verified backup for rollback. - Managed runtimes and NeMo Fabric-owned services use temporary state by default. Set `runtime.keep_state=true` to retain the native Gateway home across restarts. ## Resume a Retained Conversation @@ -124,7 +117,7 @@ This setting requires `base_url`. Attached services own their model configuratio ### Skills -[Configure Skills](../skills.mdx) describes the `skills` fields, the common setups, the start checks, and the run report. Its [Harness Differences](../skills.mdx#harness-differences) table compares OpenClaw with Hermes Agent. This section covers the rest of OpenClaw 2026.9.34's behavior. The adapter supports `skills.paths`, `skills.directories`, `skills.bundled`, and `skills.duplicates`. +[Configure Skills](../skills.mdx) describes the `skills` fields, the common setups, the start checks, and the run report. Its [Harness Differences](../skills.mdx#harness-differences) table compares OpenClaw with Hermes Agent. This section covers the rest of OpenClaw 2026.11.13's behavior. The adapter supports `skills.paths`, `skills.directories`, `skills.bundled`, and `skills.duplicates`. #### How the Adapter Reads Skills @@ -225,8 +218,6 @@ harness: settings: agents: defaults: - heartbeat: - every: 0m compaction: memoryFlush: enabled: false @@ -246,16 +237,17 @@ harness: | Setting | Values | Behavior | | --- | --- | --- | -| `agents.defaults.heartbeat.every` | Duration with units, such as `30m`, `1h30m`, or `500ms` | Recurring heartbeat interval. `0m` disables the recurring cadence; it does not stop event-driven turns. | | `agents.defaults.compaction.memoryFlush.enabled` | boolean | `false` turns off the pre-compaction memory flush turn. Compaction itself still runs. | -| `tools.exec.notifyOnExit` | boolean | `false` stops the system event and heartbeat when a backgrounded `exec` process exits. | +| `tools.exec.notifyOnExit` | boolean | `false` stops notifications when a backgrounded `exec` process exits. | | `tools.toolSearch` | boolean | `false` presents tool schemas directly instead of behind tool search. | | `tools.codeMode` | boolean | Code Mode. When enabled, it can take precedence over tool search and exposes only `exec` and `wait`, so do not combine it with blocking `exec` through `tools.blocked`. | | `tools.web.fetch.ssrfPolicy.allowRfc2544BenchmarkRange` | boolean | `true` lets `web_fetch`, `image`, and `pdf` connect to addresses in `198.18.0.0/15`, which a fake-IP proxy such as OpenShell's policy DNS answers for every name. OpenClaw blocks that range otherwise. Set it only when such a proxy owns the range and enforces its own destination policy. | | `tools.web.fetch.ssrfPolicy.allowIpv6UniqueLocalRange` | boolean | The same opt-in for `fc00::/7`. | | `plugins.bundled.entries.memory-core.config.dreaming.enabled` | boolean | `false` turns off scheduled dreaming in the `memory-core` plugin. | -The adapter merges only the fields you set into the generated `openclaw.json` before the Gateway starts. It adds them beside the generated `agents.defaults`, the `tools.allow` and `tools.deny` lists, and any adapter-owned plugin entry without replacing generated keys. Omitting a field preserves the current behavior. The closed descriptor schema rejects unknown fields and invalid values. Heartbeat durations require units. OpenClaw treats an unparseable value such as `30 minutes` as no heartbeat, so the schema rejects it, and it also rejects bare numbers such as `30` to avoid ambiguity. +The adapter merges only the fields you set into the generated `openclaw.json` before the Gateway starts. It adds them beside the generated `agents.defaults`, the `tools.allow` and `tools.deny` lists, and any adapter-owned plugin entry without replacing generated keys. Omitting a field preserves the current behavior. The closed descriptor schema rejects unknown fields and invalid values. + +Create and manage saved scheduled jobs with `openclaw automations`. - **Ownership:** Managed runtimes and NeMo Fabric-owned prepared services apply these controls, so they reach SDK invocations, every runtime connected to a prepared service, and the native API, dashboard, and terminal clients of a managed runtime. A caller-owned Gateway keeps its deployment-owned configuration: `attach_service()` rejects these fields with `openclaw_attach_configuration_unverifiable`. - **Tool selection:** `harness.settings.tools` is OpenClaw's native tools section. It is separate from NeMo Fabric's normalized top-level `tools.enabled` and `tools.blocked` selectors, which still generate `tools.allow` and `tools.deny`. @@ -286,7 +278,7 @@ harness: | `external.paths` | Plugin folders, each with its built code and `node_modules`, owned by the Gateway's Unix user. Relative paths resolve from the base directory. | | `external.entries.` | A plugin from those folders. A path alone doesn't enable it. | -Each entry takes OpenClaw's `enabled`, `config`, and `hooks` fields. A plugin id may appear in only one section, and `fabric-shared-config` is reserved. +Each entry accepts `enabled`, `config`, and `hooks`. A plugin ID may appear in only one section, and `fabric-shared-config` is reserved. With `runtime.keep_state=true`, the agent can install, enable, and disable plugins with OpenClaw's own commands, and they stay after a restart. The plugin settings live in `/fabric/plugins.json`; at each start the adapter merges its settings into that file, and the agent can still change them during a run. When a setting is removed from `harness.settings.plugins`, the agent's earlier value comes back, unless the agent changed it during a run. @@ -297,7 +289,7 @@ At start, the adapter asks the running Gateway which plugins it loaded. Every en | `openclaw_plugin_not_found` | An unknown plugin id, an `external.paths` folder that doesn't exist, or a plugin whose Gateway copy comes from another source; `metadata.origin` names that source. | | `openclaw_plugin_unavailable` | The plugin failed to load; `metadata.reason` has OpenClaw's error. | | `openclaw_invalid_configuration` | An id in both sections, a reserved id, or a plugin `config` that OpenClaw rejects. | -| `openclaw_plugin_state_invalid` | `plugins.json` can't be read. | +| `openclaw_plugin_state_invalid` | Retained plugin settings or their ownership record are invalid, or their permission format is incompatible with the OpenClaw release. | ## Select Native Interfaces @@ -321,3 +313,17 @@ After readiness, the adapter publishes private connection material under `=7.5.22 <8.0.0", "high"], + "GHSA-xm6h-2993-3ch9": ["<8.0.0", "high"], + "GHSA-9hmx-4f52-v64x": ["<8.0.0", "high"], }; const tarPackages = { tar: { "node_modules/tar": "7.5.24" }, diff --git a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json index 3a9ee88fc..be1e82efa 100644 --- a/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json +++ b/sdk/python/nemo-fabric-adapter-catalog/src/nemo_fabric_adapter_catalog/catalog.json @@ -2745,7 +2745,7 @@ "additionalProperties": false, "properties": { "every": { - "description": "Native recurring heartbeat interval, such as 30m or 1h30m. Units are required; 0m disables the recurring cadence but not event-driven turns.", + "description": "OpenClaw 2026.9.34 recurring heartbeat interval, such as 30m or 1h30m. Units are required; 0m disables recurring cadence but not event-driven turns. OpenClaw 2026.11.13 rejects this setting; use openclaw doctor --fix offline to convert an existing monitor into a saved scheduled job.", "pattern": "^(?:[0-9]+(?:\\.[0-9]+)?(?:ms|s|m|h|d))+$", "type": "string" } @@ -3070,7 +3070,7 @@ "name": "nemo-fabric-adapters-openclaw", "version": "0.7.0" }, - "sha256": "92c38d430d0b4d2beebcbd097f51ad92179761c77dc20cdae0dc2747fe836a9e", + "sha256": "3ddfca548e19e98c595d14819d85386f07aeaa6d20c46387a2cfa1565f8cd38f", "source": "adapters/python/openclaw/openclaw.fabric-adapter.json" }, "nvidia.fabric.opencode": { diff --git a/tests/_utils/mock_api_server.py b/tests/_utils/mock_api_server.py index 06c830cdb..f716bab40 100644 --- a/tests/_utils/mock_api_server.py +++ b/tests/_utils/mock_api_server.py @@ -101,7 +101,10 @@ def next_tool_call(payload: dict[str, object]) -> dict[str, object] | None: if index >= len(app.state.tool_calls): return None tool_call = app.state.tool_calls[index] - if not _payload_has_tool(payload, tool_call["name"]): + # A refusal probe can deliberately call a tool the model was not offered. + if not tool_call.get("force", False) and not _payload_has_tool( + payload, tool_call["name"] + ): return None app.state.tool_call_index += 1 return tool_call diff --git a/tests/_utils/mock_openclaw.py b/tests/_utils/mock_openclaw.py index 234aa036a..099d0fc68 100755 --- a/tests/_utils/mock_openclaw.py +++ b/tests/_utils/mock_openclaw.py @@ -22,10 +22,11 @@ args = sys.argv[1:] +version = os.environ.get("FAKE_OPENCLAW_VERSION", "2026.9.34") if args[:1] != ["gateway"] and (delay := os.environ.get("FAKE_OPENCLAW_COMMAND_DELAY")): time.sleep(float(delay)) if args == ["--version"]: - print("OpenClaw 2026.9.34 (fabric test)") + print(f"OpenClaw {version} (fabric test)") raise SystemExit(0) if args[:3] == ["config", "validate", "--json"]: with open(os.environ["OPENCLAW_CONFIG_PATH"], encoding="utf-8") as stream: @@ -301,7 +302,7 @@ def do_GET(self): return if self.path == "/startupz": body = json.dumps( - {"ok": True, "status": "started", "version": "2026.9.34"} + {"ok": True, "status": "started", "version": version} ).encode() self.send_response(200) self.send_header("Content-Type", "application/json") diff --git a/tests/adapter_contract/test_software_metadata.py b/tests/adapter_contract/test_software_metadata.py index 5245b374a..3cafc5650 100644 --- a/tests/adapter_contract/test_software_metadata.py +++ b/tests/adapter_contract/test_software_metadata.py @@ -84,7 +84,20 @@ def blocked(): pass -def test_target_bounds_are_explicit_without_scanning_all_packages(): +def test_target_bounds_are_explicit_without_scanning_all_packages(monkeypatch): + # Target-count bounds do not depend on filesystem latency or worker scheduling. + monkeypatch.setattr( + metadata, "bounded_collect", lambda participant, collect: collect() + ) + mock_version = MagicMock( + return_value=metadata.observation( + None, + "test:metadata", + metadata.observed_at(), + reason="distribution_not_found", + ) + ) + monkeypatch.setattr(metadata, "package_version", mock_version) report = metadata.collect_selected( "adapter", (("harness", f"missing-{i}", None) for i in range(1000)) ) @@ -92,9 +105,15 @@ def test_target_bounds_are_explicit_without_scanning_all_packages(): assert not env.complete assert env.reason assert len(env.entries) <= metadata.MAX_TARGETS + 1 + assert mock_version.call_count <= metadata.MAX_TARGETS def test_work_budget_preserves_partial_inventory_before_the_hard_wait(monkeypatch): + # Exercise the cooperative budget directly; the hung-worker test covers the + # separate hard wait. Do not race a previous lookup's daemon worker on Windows. + monkeypatch.setattr( + metadata, "bounded_collect", lambda participant, collect: collect() + ) monkeypatch.setattr( metadata.time, "monotonic", MagicMock(side_effect=[0.0, 0.0, 0.21]) ) diff --git a/tests/adapters/test_openclaw.py b/tests/adapters/test_openclaw.py index 6e9595401..63f5b9924 100644 --- a/tests/adapters/test_openclaw.py +++ b/tests/adapters/test_openclaw.py @@ -290,10 +290,10 @@ def respond(request): assert mock_record.call_args.args[1] == validated -def test_openclaw_accepts_supported_version(): +@pytest.mark.parametrize("version", ["2026.9.34", "2026.11.13"]) +def test_openclaw_accepts_supported_version(version): assert ( - adapter._validate_openclaw_version("OpenClaw 2026.9.34 (3a9d69d)") - == "2026.9.34" + adapter._validate_openclaw_version(f"OpenClaw {version} (3a9d69d)") == version ) @@ -305,7 +305,33 @@ def test_openclaw_rejects_unsupported_version(version: str): assert caught.value.code == "openclaw_unsupported_version" assert caught.value.metadata == { "detected_version": version, - "supported_versions": ["2026.9.34"], + "supported_versions": ["2026.11.13", "2026.9.34"], + } + + +@pytest.mark.parametrize( + ("version", "prompt_permission"), + [ + ("2026.9.34", "allowPromptInjection"), + ("2026.11.13", "allowPromptModification"), + ], +) +def test_native_instruction_hook_uses_the_installed_versions_permission( + tmp_path, mock_openclaw, version, prompt_permission +): + config = _config(mock_openclaw) + config.harness.settings["interfaces"] = {"terminal": {}} + generated = adapter._openclaw_config( + config, + _context(tmp_path), + base_dir=tmp_path, + port=18789, + token_env="OPENCLAW_GATEWAY_TOKEN", + openclaw_version=version, + ) + assert generated["plugins"]["entries"]["fabric-shared-config"]["hooks"] == { + "allowConversationAccess": True, + prompt_permission: True, } @@ -317,6 +343,60 @@ def test_openclaw_rejects_unrecognized_version_output(output: str): assert caught.value.code == "openclaw_version_check_failed" +@pytest.mark.parametrize( + ("version", "prompt_permission"), + [ + ("2026.9.34", "allowPromptInjection"), + ("2026.11.13", "allowPromptModification"), + ], +) +@pytest.mark.parametrize("section", ["bundled", "external"]) +@pytest.mark.parametrize("permitted", [False, True]) +def test_authored_plugin_prompt_policy_maps_to_the_native_version( + tmp_path, mock_openclaw, version, prompt_permission, section, permitted +): + config = _config(mock_openclaw) + authored = {"allowPromptInjection": permitted} + config.harness.settings["plugins"] = { + section: {"entries": {"example": {"hooks": authored}}} + } + generated = adapter._openclaw_config( + config, + _context(tmp_path), + base_dir=tmp_path, + port=18789, + token_env="OPENCLAW_GATEWAY_TOKEN", + openclaw_version=version, + ) + assert generated["plugins"]["entries"]["example"]["hooks"] == { + prompt_permission: permitted + } + assert authored == {"allowPromptInjection": permitted} + + +@pytest.mark.parametrize("every", ["0m", "30m"]) +async def test_retired_heartbeat_setting_has_offline_migration_guidance( + tmp_path, monkeypatch, every +): + version_probe = AsyncMock(return_value="OpenClaw 2026.11.13 (fabric test)") + monkeypatch.setattr(adapter, "_command_output", version_probe) + config = _config(Path(sys.executable)) + config.harness.settings["agents"] = {"defaults": {"heartbeat": {"every": every}}} + runtime = adapter.OpenClawRuntime() + try: + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await _start(runtime, tmp_path, config) + finally: + await runtime.stop() + assert caught.value.code == "openclaw_unsupported_heartbeat" + assert caught.value.metadata["field"] == ( + "harness.settings.agents.defaults.heartbeat" + ) + assert "openclaw doctor --fix" in str(caught.value) + assert "saved scheduled job" in str(caught.value) + version_probe.assert_awaited_once() + + _SETPRIV_RUNS = 'shift 3\nexec "$@"\n' _POSIX_SCRIPT = pytest.mark.skipif( sys.platform == "win32", reason="POSIX shell scripts stand in for setpriv" @@ -999,10 +1079,12 @@ def test_openclaw_service_connection_atomically_replaces_symlink(tmp_path: Path) @pytest.mark.skipif( sys.platform in {"darwin", "win32"}, reason="Requires POSIX process supervision" ) +@pytest.mark.parametrize("version", ["2026.9.34", "2026.11.13"]) async def test_openclaw_prepared_service_supports_multiple_runtime_sessions( mock_openclaw: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + version: str, ): capture = tmp_path / "config.json" request_capture = tmp_path / "request.json" @@ -1015,6 +1097,7 @@ async def test_openclaw_prepared_service_supports_multiple_runtime_sessions( "FAKE_OPENCLAW_REQUEST": str(request_capture), "FAKE_OPENCLAW_REQUESTS": str(requests_capture), "FAKE_OPENCLAW_STOPPED": str(stopped_capture), + "FAKE_OPENCLAW_VERSION": version, } ) service_context = _context(tmp_path, "service-1") @@ -1033,7 +1116,7 @@ async def test_openclaw_prepared_service_supports_multiple_runtime_sessions( assert info is not None assert info["adapter_id"] == "nvidia.fabric.openclaw" assert info["service_type"] == "openclaw_gateway" - assert info["metadata"] == {"openclaw_version": "2026.9.34"} + assert info["metadata"] == {"openclaw_version": version} assert "gateway_token" not in json.dumps(info) assert connection_path.parent.stat().st_mode & 0o777 == 0o700 assert connection_path.stat().st_mode & 0o777 == 0o600 @@ -1140,7 +1223,7 @@ async def test_openclaw_prepared_service_supports_multiple_runtime_sessions( } ) assert attached_info is not None - assert attached_info["metadata"] == {"openclaw_version": "2026.9.34"} + assert attached_info["metadata"] == {"openclaw_version": version} await attached.stop() assert not stopped_capture.exists() @@ -2859,7 +2942,9 @@ def generated_config(*args, **kwargs): if failure == "conversation-denied": shared["hooks"]["allowConversationAccess"] = False elif failure == "prompt-denied": - shared["hooks"]["allowPromptInjection"] = False + for key in ("allowPromptInjection", "allowPromptModification"): + if key in shared["hooks"]: + shared["hooks"][key] = False elif failure == "wrong-agent": shared["config"]["agentId"] = "other" return generated diff --git a/tests/adapters/test_openclaw_native.py b/tests/adapters/test_openclaw_native.py index 41dbd233f..07a008464 100644 --- a/tests/adapters/test_openclaw_native.py +++ b/tests/adapters/test_openclaw_native.py @@ -6,12 +6,14 @@ import asyncio import json import os +import subprocess import sys from pathlib import Path import httpx import pytest from nemo_fabric import Fabric, FabricConfig +from nemo_fabric.errors import FabricRuntimeError pytestmark = pytest.mark.skipif( not os.environ.get("FABRIC_OPENCLAW_TEST_COMMAND"), @@ -19,6 +21,23 @@ ) +@pytest.fixture(scope="module") +def native_version(): + from nemo_fabric_adapters.openclaw import adapter + + output = subprocess.check_output( + [os.environ["FABRIC_OPENCLAW_TEST_COMMAND"], "--version"], + text=True, + timeout=15, + ) + return adapter._validate_openclaw_version(output) + + +@pytest.fixture(scope="module") +def dispatch_tool(native_version): + return "dispatch_action" if native_version == "2026.11.13" else "tool_call" + + @pytest.fixture(name="native_config", params=["reviewer", "Reviewer"]) def native_config_fixture(tmp_path, api_server, unused_tcp_port, request): os.environ["ADAPTER_PYTHON"] = sys.executable @@ -78,8 +97,114 @@ def native_config_fixture(tmp_path, api_server, unused_tcp_port, request): return config +@pytest.mark.skipif( + not os.environ.get("FABRIC_OPENCLAW_UPGRADE_COMMAND"), + reason="Set FABRIC_OPENCLAW_UPGRADE_COMMAND to qualify a retained-state upgrade", +) +@pytest.mark.parametrize("native_config", ["reviewer"], indirect=True) +@pytest.mark.skipif(os.name != "posix", reason="Uses a stable executable symlink") +async def test_native_session_survives_openclaw_upgrade( + tmp_path, api_server, native_config, native_version +): + from uuid import uuid4 + + from nemo_fabric_adapters.openclaw import adapter + + assert native_version == "2026.9.34" + upgrade_version = subprocess.check_output( + [os.environ["FABRIC_OPENCLAW_UPGRADE_COMMAND"], "--version"], + text=True, + timeout=15, + ) + assert adapter._validate_openclaw_version(upgrade_version) == "2026.11.13" + + native_config.runtime.keep_state = True + native_config.runtime.artifacts = str(tmp_path / "retained") + # Match NemoClaw's sibling workspace and artifacts mounts. + workspace = tmp_path / "workspace" + workspace.mkdir() + native_config.environment.workspace = str(workspace) + native_config.harness.settings.pop("interfaces") + native_config.instructions = None + native_config.skills = None + native_config.mcp = None + native_config.tools.enabled = [] + command = tmp_path / "openclaw" + command.symlink_to(os.environ["FABRIC_OPENCLAW_TEST_COMMAND"]) + native_config.harness.settings["openclaw_command"] = str(command) + nonce = "upgrade-retained-" + uuid4().hex + fabric = Fabric() + async with await fabric.start_runtime(native_config, base_dir=tmp_path) as first: + reference = first.session_ref + assert reference is not None + result = await first.invoke(input="Remember " + nonce) + assert result.status == "succeeded" + config_path = next((tmp_path / "retained").rglob("fabric/openclaw.json")) + plugin_path = config_path.with_name("plugins.json") + retained_plugins = json.loads(plugin_path.read_text()) + retained_plugins.setdefault("entries", {})["memory-core"] = { + "enabled": False, + "hooks": {"allowPromptInjection": False}, + } + plugin_path.write_text(json.dumps(retained_plugins)) + maintenance_config = config_path.with_name("upgrade-maintenance.json") + maintenance = json.loads(config_path.read_text()) + # Doctor refuses to rewrite include-owned configuration. Flatten only + # this disposable maintenance copy, preserving retained plugin ownership. + maintenance["plugins"] = retained_plugins + maintenance_config.write_text(json.dumps(maintenance)) + maintenance_config.chmod(0o600) + + async with httpx.AsyncClient(trust_env=False) as client: + await client.post(api_server + "/_reset") + maintenance_env = { + **os.environ, + "OPENCLAW_CONFIG_PATH": str(maintenance_config), + "OPENCLAW_STATE_DIR": str(config_path.parent.parent), + "OPENCLAW_GATEWAY_TOKEN": "synthetic-offline-maintenance-token", + } + maintenance = await asyncio.to_thread( + subprocess.run, + [ + os.environ["FABRIC_OPENCLAW_UPGRADE_COMMAND"], + "doctor", + "--fix", + "--non-interactive", + ], + env=maintenance_env, + capture_output=True, + text=True, + timeout=60, + ) + assert maintenance.returncode == 0, maintenance.stdout + maintenance.stderr + command.unlink() + command.symlink_to(os.environ["FABRIC_OPENCLAW_UPGRADE_COMMAND"]) + async with await fabric.start_runtime( + native_config, base_dir=tmp_path, session_ref=reference + ) as upgraded: + assert upgraded.session_ref == reference + assert json.loads(plugin_path.read_text())["entries"]["memory-core"][ + "hooks" + ] == {"allowPromptModification": False} + result = await upgraded.invoke(input="Continue the retained conversation") + assert result.status == "succeeded" + requests = (await client.get(api_server + "/_requests")).json() + assert nonce in json.dumps(requests) + + policy_files = (plugin_path, plugin_path.with_name("plugins.owned.json")) + before_rollback = {path: path.read_bytes() for path in policy_files} + command.unlink() + command.symlink_to(os.environ["FABRIC_OPENCLAW_TEST_COMMAND"]) + with pytest.raises(FabricRuntimeError, match="pre-upgrade.*backup"): + async with await fabric.start_runtime( + native_config, base_dir=tmp_path, session_ref=reference + ): + pytest.fail("The older executable must not start on upgraded policy") + assert {path: path.read_bytes() for path in policy_files} == before_rollback + + async def test_native_and_sdk_share_gateway_configuration( - tmp_path, api_server, unused_tcp_port, native_config + tmp_path, api_server, unused_tcp_port, native_config, dispatch_tool ): from nemo_fabric import CheckRequest, EnvironmentHandle from playwright.async_api import async_playwright @@ -113,7 +238,11 @@ async def scenario(path, turn): if turn == 1 else [ { - "name": "tool_call", + "name": "tool_search", + "arguments": {"query": "fabricprobe authorization header"}, + }, + { + "name": dispatch_tool, "arguments": { "id": "mcp:fabricprobe:fabricprobe__get_authorization_header", "args": {}, @@ -138,10 +267,35 @@ async def scenario(path, turn): ) response.raise_for_status() + async def assert_native_tool_results(client_name): + payloads = (await client.get(f"{api_server}/_requests")).json() + messages = payloads[-1]["messages"] + turn = max( + index + for index, message in enumerate(messages) + if message["role"] == "user" + and f"{client_name} parity turn 2" in json.dumps(message["content"]) + ) + results = json.dumps( + [ + message["content"] + for message in messages[turn + 1 :] + if message["role"] == "tool" + ], + ensure_ascii=False, + ) + # The older native dispatcher redacts key-like tool results. + assert any( + receipt in results + for receipt in ("Bearer native-mcp-test-key", "Bearer native…-key") + ), client_name + assert "FABRIC_SKILL_98214" in results, client_name + for turn in (1, 2): await scenario("sdk", turn) result = await runtime.invoke(input=f"SDK parity turn {turn}") assert result.status == "succeeded", result.to_mapping() + await assert_native_tool_results("SDK") assert ( tmp_path / "sdk-result.txt" ).read_text() == "sdk configured workspace verified" @@ -160,6 +314,7 @@ async def scenario(path, turn): }, ) assert response.status_code == 200, response.text + await assert_native_tool_results("HTTP") assert ( tmp_path / "http-result.txt" ).read_text() == "http configured workspace verified" @@ -209,6 +364,7 @@ async def scenario(path, turn): ) ) await browser.close() + await assert_native_tool_results("Browser") assert ( tmp_path / "browser-result.txt" ).read_text() == "browser configured workspace verified" @@ -246,7 +402,13 @@ def terminal_turns(): if turn == 1 else [ { - "name": "tool_call", + "name": "tool_search", + "arguments": { + "query": "fabricprobe authorization header" + }, + }, + { + "name": dispatch_tool, "arguments": { "id": "mcp:fabricprobe:fabricprobe__get_authorization_header", "args": {}, @@ -283,6 +445,7 @@ def terminal_turns(): child.terminate(force=True) await asyncio.to_thread(terminal_turns) + await assert_native_tool_results("Terminal") assert ( tmp_path / "terminal-result.txt" ).read_text() == "terminal configured workspace verified" @@ -307,7 +470,7 @@ def terminal_turns(): (tmp_path / "captured-model-requests.json").write_text( json.dumps(payloads, indent=2) ) - assert len(payloads) == 25 + assert payloads for payload in payloads: assert payload["model"] == "fabric-echo" system = "\n".join( @@ -349,7 +512,7 @@ def terminal_turns(): async def test_native_mcp_and_skills_use_managed_configuration( - tmp_path, api_server, native_config + tmp_path, api_server, native_config, dispatch_tool ): from nemo_fabric_adapters.openclaw import terminal @@ -387,7 +550,7 @@ async def test_native_mcp_and_skills_use_managed_configuration( f"{api_server}/_scenario", json={ "tool_call": { - "name": "tool_call", + "name": dispatch_tool, "arguments": { "id": "mcp:fabricprobe:fabricprobe__get_authorization_header", "args": {}, @@ -400,12 +563,19 @@ async def test_native_mcp_and_skills_use_managed_configuration( assert ( await client.get(f"{api_server}/_mcp_authorization_headers") ).json()[-1] == "Bearer native-mcp-test-key" + payloads = (await client.get(f"{api_server}/_requests")).json() + assert any( + "Bearer native-mcp-test-key" in str(message["content"]) + for message in payloads[-1]["messages"] + if message["role"] == "tool" + ) forbidden = tmp_path / "forbidden-exec.txt" await client.post( f"{api_server}/_scenario", json={ "tool_call": { - "name": "tool_call", + "name": dispatch_tool, + "force": True, "arguments": { "id": "exec", "args": {"command": f"touch {forbidden}"}, @@ -611,7 +781,7 @@ async def test_native_selection_preserves_sdk_prompt_guidance( async def test_native_controls_apply_to_pinned_gateway( - tmp_path, api_server, native_config, monkeypatch + tmp_path, api_server, native_config, monkeypatch, native_version ): """The pinned Gateway accepts and applies the native harness controls.""" @@ -638,6 +808,13 @@ async def test_native_controls_apply_to_pinned_gateway( }, } ) + if native_version == "2026.11.13": + with pytest.raises(FabricRuntimeError, match="saved scheduled job"): + async with await Fabric().start_runtime( + FabricConfig.from_mapping(mapping), base_dir=tmp_path + ): + pytest.fail("Retired heartbeat configuration must be rejected") + del mapping["harness"]["settings"]["agents"]["defaults"]["heartbeat"] config = FabricConfig.from_mapping(mapping) temp_root = tmp_path / "tmp" temp_root.mkdir() @@ -649,7 +826,10 @@ async def test_native_controls_apply_to_pinned_gateway( (config_path,) = temp_root.glob("nemo-fabric-openclaw-*/openclaw.json") generated = json.loads(config_path.read_text()) defaults = generated["agents"]["defaults"] - assert defaults["heartbeat"] == {"every": "0m"} + if native_version == "2026.9.34": + assert defaults["heartbeat"] == {"every": "0m"} + else: + assert "heartbeat" not in defaults assert defaults["compaction"]["memoryFlush"] == {"enabled": False} assert generated["tools"]["exec"]["notifyOnExit"] is False assert generated["tools"]["toolSearch"] is False @@ -702,7 +882,12 @@ async def test_native_controls_apply_to_pinned_gateway( tools = {tool["function"]["name"] for tool in payloads[-1].get("tools", [])} # Tool search and Code Mode are off, so the MCP tool is presented directly. assert "fabricprobe__get_authorization_header" in tools, tools - assert not tools & {"tool_search", "tool_describe", "tool_call"}, tools + assert not tools & { + "tool_search", + "tool_describe", + "tool_call", + "dispatch_action", + }, tools @pytest.mark.skipif(os.name != "posix", reason="Uses POSIX Gateway signals") @@ -711,7 +896,6 @@ async def test_native_interrupted_session_resumes_after_acknowledgement( tmp_path, api_server, interruption ): import signal - from unittest.mock import AsyncMock from uuid import uuid4 from nemo_fabric_adapter_contract.models import ( @@ -802,7 +986,6 @@ async def test_native_interrupted_session_resumes_after_acknowledgement( session_id=started["session_id"], ) replacement = OpenClawRuntime() - replacement._session_call = AsyncMock(wraps=replacement._session_call) payload["runtime_context"] = context.to_mapping() try: reopened = await replacement.start(payload) @@ -810,11 +993,6 @@ async def test_native_interrupted_session_resumes_after_acknowledgement( assert ( reopened["recovery_warnings"][0]["code"] == "session_recovery_required" ) - if interruption == "crash": - assert any( - c.args[0] == "sessions.abort" - for c in replacement._session_call.call_args_list - ) blocked = await replacement.invoke( AgentRunRequest(input="Wait for inspection"), context ) diff --git a/tests/adapters/test_openclaw_plugins.py b/tests/adapters/test_openclaw_plugins.py index 3ea74688f..001bf5f73 100644 --- a/tests/adapters/test_openclaw_plugins.py +++ b/tests/adapters/test_openclaw_plugins.py @@ -1077,3 +1077,199 @@ async def test_keep_state_with_invalid_plugin_state_fails_start( assert (folder / "plugins.json").read_text() == "{broken" assert not (folder / "openclaw.json").exists() assert not (tmp_path / "gateway.pid").exists() + + +@posix_only +@pytest.mark.parametrize("origin", ["agent", "shadowed", "edited"]) +@pytest.mark.parametrize("permitted", [False, True]) +async def test_upgrade_preserves_retained_plugin_prompt_policy( + tmp_path, mock_openclaw, capture, origin, permitted +): + state_dir = tmp_path / "state" + state_dir.mkdir() + folder = openclaw_plugins.state_folder(state_dir) + policy_path = folder / openclaw_plugins.PLUGINS_FILE + policy = { + "entries": { + "memory-core": { + "enabled": False, + "hooks": {"allowPromptInjection": permitted}, + } + } + } + policy_path.write_text(json.dumps(policy)) + if origin != "agent": + openclaw_plugins.prepare( + folder, + { + "entries": { + "memory-core": {"hooks": {"allowPromptInjection": not permitted}} + } + }, + ) + if origin == "edited": + policy_path.write_text(json.dumps(policy)) + os.environ["FAKE_OPENCLAW_VERSION"] = "2026.11.13" + runtime = adapter.OpenClawRuntime() + try: + await _start(runtime, tmp_path, _config(mock_openclaw), state_dir=state_dir) + assert json.loads(policy_path.read_text())["entries"]["memory-core"][ + "hooks" + ] == {"allowPromptModification": permitted} + finally: + await runtime.stop() + + for authored, expected in [ + ( + _bundled( + { + "memory-core": { + "enabled": False, + "hooks": {"allowPromptInjection": not permitted}, + } + } + ), + not permitted, + ), + (None, permitted), + ]: + runtime = adapter.OpenClawRuntime() + try: + await _start( + runtime, tmp_path, _config(mock_openclaw, authored), state_dir=state_dir + ) + assert json.loads(policy_path.read_text())["entries"]["memory-core"][ + "hooks" + ] == {"allowPromptModification": expected} + finally: + await runtime.stop() + + +@pytest.mark.parametrize("permitted", [False, True]) +@pytest.mark.parametrize("keep_override", [False, True]) +def test_older_release_refuses_upgraded_policy_without_writing( + tmp_path, permitted, keep_override +): + folder = openclaw_plugins.state_folder(tmp_path) + policy_path = folder / openclaw_plugins.PLUGINS_FILE + owned_path = folder / openclaw_plugins.OWNED_FILE + policy_path.write_text( + json.dumps( + {"entries": {"example": {"hooks": {"allowPromptInjection": not permitted}}}} + ) + ) + authored = {"entries": {"example": {"hooks": {"allowPromptInjection": permitted}}}} + openclaw_plugins.prepare(folder, authored) + backup = {path: path.read_bytes() for path in (policy_path, owned_path)} + openclaw_plugins.prepare(folder, authored, openclaw_version="2026.11.13") + upgraded = {path: path.read_bytes() for path in (policy_path, owned_path)} + + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + openclaw_plugins.prepare(folder, authored if keep_override else {}) + + assert caught.value.code == "openclaw_plugin_state_invalid" + assert "2026.9.34" in str(caught.value) + assert "2026.11.13" in str(caught.value) + assert "backup" in str(caught.value) + assert caught.value.metadata["path"] == str(policy_path) + assert {path: path.read_bytes() for path in upgraded} == upgraded + + continued = openclaw_plugins.prepare( + folder, authored if keep_override else {}, openclaw_version="2026.11.13" + ) + assert continued["entries"]["example"]["hooks"] == { + "allowPromptModification": permitted if keep_override else not permitted + } + for path, content in backup.items(): + path.write_bytes(content) + restored = openclaw_plugins.prepare(folder, {}) + assert restored["entries"]["example"]["hooks"] == { + "allowPromptInjection": not permitted + } + + +@pytest.mark.parametrize("permitted", [False, True]) +@pytest.mark.parametrize("legacy_alias", [False, True]) +def test_older_release_refuses_new_permission_without_creating_ownership( + tmp_path, permitted, legacy_alias +): + folder = openclaw_plugins.state_folder(tmp_path) + policy_path = folder / openclaw_plugins.PLUGINS_FILE + hooks = {"allowPromptModification": permitted} + if legacy_alias: + hooks["allowPromptInjection"] = permitted + before = json.dumps({"entries": {"example": {"hooks": hooks}}}) + policy_path.write_text(before) + + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + openclaw_plugins.prepare(folder, {}) + + assert caught.value.code == "openclaw_plugin_state_invalid" + assert policy_path.read_text() == before + assert not (folder / openclaw_plugins.OWNED_FILE).exists() + + +@posix_only +@pytest.mark.parametrize("prepare_service", [False, True]) +async def test_older_managed_start_refuses_upgraded_policy( + tmp_path, mock_openclaw, capture, prepare_service +): + state = tmp_path / "state" + state.mkdir() + folder = openclaw_plugins.state_folder(state) + policy_path = folder / openclaw_plugins.PLUGINS_FILE + before = json.dumps( + {"entries": {"memory-core": {"hooks": {"allowPromptModification": False}}}} + ) + policy_path.write_text(before) + pid = tmp_path / "gateway.pid" + os.environ["FAKE_OPENCLAW_PID"] = str(pid) + payload = { + "config": _config(mock_openclaw), + "runtime_context": _context(tmp_path, state).to_mapping(), + "base_dir": str(tmp_path), + } + if prepare_service: + payload["service"] = { + "operation": "prepare", + "connection_path": str(tmp_path / "connection.json"), + } + runtime = adapter.OpenClawRuntime() + try: + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + await runtime.start(payload) + assert caught.value.code == "openclaw_plugin_state_invalid" + finally: + await runtime.stop() + + assert policy_path.read_text() == before + assert not (folder / openclaw_plugins.OWNED_FILE).exists() + assert not (folder / openclaw_plugins.CONFIG_FILE).exists() + assert not pid.exists() + assert not (tmp_path / "connection.json").exists() + + +@pytest.mark.parametrize("permitted", [False, True]) +def test_conflicting_retained_prompt_permissions_fail_without_writing( + tmp_path, permitted +): + folder = openclaw_plugins.state_folder(tmp_path) + policy_path = folder / openclaw_plugins.PLUGINS_FILE + before = json.dumps( + { + "entries": { + "example": { + "hooks": { + "allowPromptInjection": permitted, + "allowPromptModification": not permitted, + } + } + } + } + ) + policy_path.write_text(before) + with pytest.raises(adapter.lifecycle.LifecycleError) as caught: + openclaw_plugins.prepare(folder, {}, openclaw_version="2026.11.13") + assert caught.value.code == "openclaw_plugin_state_invalid" + assert policy_path.read_text() == before + assert not (folder / openclaw_plugins.OWNED_FILE).exists()