Skip to content

feat: choose which tools are deferred behind Tool Search - #170071

Merged
roboclaw-bot merged 11 commits into
openclaw:mainfrom
ificator:feat/tool-search-selectors
Oct 23, 2026
Merged

roboclaw-bot merged 11 commits into
openclaw:mainfrom
ificator:feat/tool-search-selectors

Conversation

@ificator

@ificator ificator commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #170058

What Problem This Solves

Operators cannot defer only MCP tools behind Tool Search while keeping core, non-MCP plugin, client, and frequently used MCP tools directly available.

User Impact

User impact: operators can choose which authorized tools need discovery without removing execution permission or exposing every MCP schema.

{
  "tools": {
    "toolSearch": {
      "mode": "tools",
      "include": [{ "source": "mcp" }],
      "exclude": [{ "source": "mcp", "name": "github_read_*" }]
    }
  }
}

Existing defaults are unchanged; no threshold or migration is introduced. These are presentation controls, not authorization. Direct-only and runtime-required trusted tools retain their existing guarantees. Directory mode still keeps client tools direct; the Copilot harness retains its existing directory-to-tools mapping. Independent Code Mode and Codex-native search are unchanged.

Maintainer direction: Patrick-Erichsen requested landing after configuration/security discussion. Canonical review is complete; an additional direct/deferred-name ambiguity was repaired and independently re-reviewed. Hosted CI, security and enforced review requirements still apply.

Why This Change Was Made

The existing policy-filtered compactor and dispatcher now accept include/exclude selectors. Each selector has a source, registered name, or both; names reuse policy normalization and * matching without regex support or implicit tool-group expansion. Fields are ANDed, lists are ORed, and exclusion wins. Omitted inclusion retains existing eligibility; empty inclusion defers nothing.

Source qualification prevents unintended name-only matches across origins. Client registration, prompt allowlists, registry ownership, and worker presentation follow the selected surface without granting tools through a same-named tool from another owner. Public documentation and schema/help/labels are included. No MCP activation, connection, deployment, or dependency changes are part of the PR diff.

Prior art: #118335 proposed a name-only alwaysVisibleTools option and was closed unmerged. Its closure reason is unverified; this implementation does not infer Code Mode from Tool Search mode or promote tools through a name-only trusted-tool rule.

Evidence

October 23 reviewed correction

Final candidate edab183, tree d6bda2053a82d6c35051abdcd11573dec9a192b4, preserves contributor ancestry and incorporates main1532cce3. Config metadata was regenerated; the merged fixture retains selector and upstream deny-all cases.

Independent composed review found a direct/deferred-name ambiguity. The production regression failed before repair; deferred namesakes now consistently require exact catalog IDs across directory guidance, dispatch, recovery and cache/inventory changes. Normal initial MCP registration ordinarily deconflicts names; this is not claimed as an initial-registration exploit.

Passed on edab183: 47 selector/run-plan tests, single-worker wall95.76s including46.14s cold compilation; affected test types47.70s wrapper wall and core types8.91s; config metadata, lint, format and whitespace. Complete final-feature canonical review is scoped-clean. Prior91b repair scope passed166 tests. Whole-run CI span: 793s; 11880 summed job-seconds (not added-test-only cost).

Installed upgrade (prior reviewed91b): npm-latest stable2026.10.6 upgraded itself to exact signed91b1485/tree13b6 in one invocation, exit0, without recovery. This is not an edab package-build claim; the refresh preserves selector/config code, adds generated metadata and merges fixture coverage with main. Actual installed CLI/agent turns preserved Tool Search settings, workspace and prior conversation input; selectors persisted and loaded in a new process. Private runtime-only package SHA-256: 0301ac307cdf91e3357faeaebdc679dec15f059b21adae828de70f44b706246c. This is not a release or full-declaration-build claim. The installed isolated Gateway became ready and stopped cleanly.

Limits: deterministic survival checks used a test-owned provider. An extra commercial-model file-read smoke failed in protected-egress upstream transport (HTTP 502); no successful live read is claimed. That transport is unchanged by this PR. Current-head hosted CI/security remain required. On old run 39646002382, the UI failure was inherited and repaired in incorporated main; Android exhausted its 20-minute job budget with the underlying slowness/stall unknown. Historical receipts below do not establish current-head green CI.

Current CI qualification: Run 39908731999, attempt 1 completed all 90 jobs. Its sole root failure is a stale sessions_send options assertion (job 120266922474), reproduced on exact main baseline e40d9f7: 1 failed, 63 skipped, 53.38s. Ten relevant test/runtime/config inputs are unchanged in the PR merge. Security cleared; other planned jobs passed or were skipped. The native inherited-failure exception is selected; CI remains failed, not green.

Historical merge refreshes

October 21 integration: merged upstream b5aa29b1ed0fcef44ec2367dd03eb2239e55511f as 6db38b3d866782652ee4aee99d1761a47b4c9570. All merge conflicts are resolved. Partial-client projections now live in upstream's inlined catalog owner; descriptor-based catalog reuse retains direct-tool metadata, and removed diagnostic/planner modules remain removed. Source-qualified registry and catalog authorization are preserved. Affected tests and explicit production/test type graphs pass, along with lint, formatting, mock-export ratchet and config metadata. Independent source review found no significant issues.

Verification gaps: the changed-graph boundary checker reports oversized all-tree test partitions (722/729/749 roots versus 720); the explicit affected compiler graphs pass, but that boundary check is not claimed green. Canonical review was attempted and could not launch because codex is missing; the independent review does not substitute for canonical success. No new-head full build or installed upgrade is claimed. Exact commands and merge receipts. Product acceptance and the installed-upgrade request remain open.

Prior green CI head: Broad CI passed on 4a7845762024d075c88bf3e623171c496d05c2ca, including both Android Access lanes; this is not new-head CI evidence. Maintainer security approval remains required for the current revision.

Earlier refresh: 4a7845762024d075c88bf3e623171c496d05c2ca, incorporating upstream 82b8f59a3ec944adafb05fe802928e353761f4c1.

The evening /check resolved newly conflicting generated schema metadata and retained upstream control-hook/result-projection changes. On the merged tree, 130 focused tests, core production types, both affected test type graphs, mock-export ratchet, lint/format and config metadata checks passed. Selector policy owners are unchanged. The previous head's hosted ratchet job now passes; its CI aggregator failed solely on a cancelled 4-KiB Android native job, not a recorded test assertion. Maintainer security approval, product acceptance and the v2026.10.3 installed-upgrade request remain open. Current per-finding receipts and exact commands. No new-head full build or installed-package proof is claimed.

Previous check on 505ca678b46:

The latest /check fixed CI's new mock-export ratchet failure: the workspace test mock now spreads the real adapter exports before retaining its existing override. The obsolete grandfathered exception was removed, tightening the baseline by one entry. The failing checker now passes, as do the 25-test context-engine consumer suite, both affected test type graphs, lint, formatting and whitespace checks. Runtime code is unchanged. Failure reproduction, exact commands and per-finding receipts. No fresh broad-CI success is claimed.

The October 13 /check regenerated the two conflicting metadata files and aligned three selector tests with upstream's dispatch_action name, retaining its dispatcher and provenance changes. Passed: 155 focused tests across seven files, core production types, three affected test type graphs, targeted lint/format, generated config metadata, and whitespace checks. Per-finding receipts and exact commands.

GitHub reports this head mergeable, but openclaw/ci-gate and openclaw/security-sensitive-review fail because a maintainer must approve the current revision. Product acceptance and an installed upgrade exercise from stable 2026.10.3 remain unresolved. No new full build or installed-package proof is claimed for this head, and no formal change-request reviews existed to dismiss.

Earlier refresh: 59be7f106ac57a09cec36079fff6c3f7a329dfe8, incorporating upstream c07481adc5abd354e89e17e21c36b924f95b3268.

Upstream advanced during the first refresh's 73-minute build. The follow-up merge regenerates the two config metadata files, preserves upstream's deletion of obsolete description-observer tests, retains both selector client regressions, and updates the selector test to upstream's catalogPrompt argument name. Upstream's Code Mode prompt/lifecycle changes are retained. The final feature diff is 35 files, +1088/-59.

Follow-up merge passed: 162 tests across six affected files (four shards, 459.29s); the corrected selector test then passed separately (22 tests, 63.58s). Core production types and the agents-other, agents-tools, and config-cli test graphs passed, as did targeted lint/format, regenerated config metadata and whitespace checks. The first test-type run caught the stale toolSearchPrompt argument; it was corrected and the affected type graphs were rerun successfully.

Build provenance: the complete build passed on the immediately preceding merge c0740aa9e9a, not on 59be7f106ac. No second full build or installed-package run is claimed for the follow-up merge; its overlapping code and test contracts were checked with the targeted commands below.

Latest follow-up merge checks — commands and results

Passed:

corepack pnpm install --frozen-lockfile
corepack pnpm config:docs:gen
corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/agents/harness/tool-surface-bridge.test.ts src/config/schema.test.ts --maxWorkers=1 --reporter=dot
corepack pnpm tsgo:core
corepack pnpm test src/agents/tool-search-selection.test.ts --maxWorkers=1 --reporter=dot
node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/config/schema.test.ts"]'
git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1
corepack pnpm exec oxfmt --check --threads=1 src/agents/tool-search-selection.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/tool-search-selection.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts
corepack pnpm config:docs:check
git diff upstream/main --check

The initial graph selection below passed agents-other before reporting the stale test argument in agents-tools. The corrected agents-tools and config-cli graphs passed in the rerun above:

node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts","src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts","src/config/schema.test.ts"]'

The first refresh was c0740aa9e9a128d116fe5516573fb69c1477a9c2, incorporating upstream 20d12e8a4dce7af751315e08494467d38d14d35f.

Only the generated config baseline counts and hashes conflicted. They were regenerated with the merged schema, preserving the eight selector paths and all upstream fields. Upstream runtime-config setup/cleanup in the shared harness test and unrelated help/label changes were retained. The feature diff remains 35 files, +1087/-59; selector production code is unchanged from the earlier evidence candidate.

Passed on the merged tree: 214 focused tests across 10 files (six Vitest shards, 691.10 seconds), core production types, all five affected test type graphs, targeted lint/format, config metadata consistency, and feature-diff whitespace checks.

Exact-head build passed: corepack pnpm build completed successfully on c0740aa9e9a in 4419.59 seconds wall time (73m 39.6s). Most time was native package declaration generation; advisory UI/bundler warnings did not fail the build.

Current merge verification commands and results

All commands below passed with Node 24.21.0 and pnpm 12.9.0:

corepack pnpm install --frozen-lockfile
corepack pnpm config:docs:gen
corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search-config.test.ts src/agents/tool-search.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts src/agents/embedded-agent-runner/run/attempt.tool-search-run-plan.test.ts src/agents/harness/tool-surface-bridge.test.ts src/config/schema.test.ts packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts --maxWorkers=1 --reporter=dot
corepack pnpm tsgo:core
node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts","src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts","src/agents/embedded-agent-runner/run/attempt-prompt-admission.test-support.ts","src/agents/embedded-agent-runner/run/attempt-spawn-workspace.test-support.ts","src/config/schema.test.ts","packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts"]'
git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1
corepack pnpm config:docs:check
git diff upstream/main --check
corepack pnpm build

Evidence provenance: the installed-Gateway, MCP/client final-effect, and recovered-upgrade receipts below remain pinned to f142599; they were not rerun on either merge refresh. The later checks above do not relabel those historical receipts. Maintainer direction and the documented canonical-review availability gap remain unresolved.

Historical evidence candidate: f1425991727896e20378f690fddd044a64fee77a, incorporating upstream a640fff46b1. Validation used Linux, Node v24.21.0, and pnpm 12.9.0 through Corepack. The earlier post-merge checks exercised the resolved tree committed unchanged as that candidate.

Installed-package execution and upgrade proof — October 12

Passed on f142599: a fresh candidate installation and 15 real Gateway HTTP turns / nine scenario groups. Configuration/history survival and selector persistence also pass after the published updater installs the candidate and supported recovery completes. The fixture drives the installed CLI/Gateway and actual MCP stdio server; it does not import or mock the compactor, prompt policy, session registry, or dispatcher.

Upgrade limitation: the first published-updater invocation exceeded the harness's 900-second overall deadline and exited 143. It had published f142599; its recovery status reported publication-complete. The follow-up openclaw update repair --yes --no-restart --json --timeout 600 succeeded, followed by the state-survival checks below. This is not a clean one-shot upgrade pass and is not attributed to this feature without baseline evidence. The original failure is retained here rather than hidden by the recovery result.

Contract exercised Observed result
MCP-only inclusion plus a source-qualified frequent-tool exception Provider request schemas keep core, non-MCP plugin, client, and the exception direct; selected MCP schemas are absent.
MCP discovery and execution Successful search metadata, described parameter schema, and dispatcher result reach the provider; the MCP process records the invocation.
Direct execution Core file contents reach the provider; plugin and excepted MCP executors record effects; a client receives and executes its returned function call.
Same-name direct client/plugin collision The unrestricted client call produces an effect. A real opted-in before_prompt_build hook returning an acme-qualified cap removes the client winner, emits no client dispatch, and produces zero denied effects.
Source-qualified MCP denial and plugin lookalike MCP calls that succeeded before the cap are rejected afterward, while the authorized plugin still executes. Normal registration renames the colliding MCP tool to fixture__blocked-2; the test uses that actual identity rather than forging metadata.
Same-session permission/client inventory refresh Restrictions remain effective after the caller supplies an updated client inventory; removing the cap restores the permitted client dispatch.
Live MCP inventory refresh The server disables its old tool and adds a new tool through its SDK, notifying tools/list_changed. In the same Gateway session, the old name produces no effect and the new tool is searchable/callable.
Partial client deferral after persisted configuration/restart One client remains directly declared while another is deferred; search, describe, and call return the correct client dispatch.
Same-name deferred client/plugin collision An explicit client catalog ID works without the cap, then is rejected under the plugin-qualified cap after an inventory change; the permitted plugin still executes.
Published stable → candidate upgrade, then recovery The installed stable CLI's own update --tag file:/proof/openclaw-candidate.tgz --yes --no-restart --json --timeout 600 publishes f142599 but hits the harness deadline. Supported repair succeeds; existing Tool Search settings, workspace content, and prior conversation in the next model request survive without reseeding.
New selector persistence after upgrade The installed CLI accepts the selector configuration; validation and a new agent process succeed, with the exact selector arrays retained.

Final-effect recorders observed 4 plugin, 6 MCP, and 5 client effects, with zero forbidden effects. The core read result is independently checked in the provider request. Successful calls to each recorder precede the corresponding denial tests.

Scope: deterministic local model responses, actual installed OpenClaw runtime, and a test-owned MCP server/client. This is not live commercial-provider or production MCP-service evidence. Runtime demonstrations use structured tools mode; directory, independent Code Mode, and other selector semantics retain the focused test evidence below. Refresh proof covers real MCP notifications and subsequent turns in the same session, not a simulated mid-instruction revocation. The compatibility check is a focused published-driver/state-survival run, not a full Package Acceptance release matrix.

Package SHA-256: e169735bedbcbe71f39f639e3ff8d07053bb7d92dc65ed3a1b2fc9e973d67c9b. Baseline: OpenClaw 2026.10.2 (b8952d4); candidate: OpenClaw 2026.10.2 (f142599). Docker image: node@sha256:d6aa754f16b3197301076f047b5def2f02ea1dbbc2ca920407d46d7ec7f87b20 (Node 24.21.0). No operator state, real credentials, or production services were mounted; the product checkout stayed unchanged.

Exact installed-package commands, results, and receipts

PROOF_DIR is the external fixture/artifact directory containing the scripts below. /harness is a read-only mount of f1425991727896e20378f690fddd044a64fee77a for this historical run; /proof is its separate writable fixture/artifact mount. The previously successful build was reused.

# Passed: canonical package creation, inventory and tarball checks.
node scripts/package-openclaw-for-docker.mjs --skip-build --allow-unreleased-changelog --output-dir "$PROOF_DIR" --output-name openclaw-candidate.tgz

# Passed inside the isolated container.
npm install --prefix /opt/candidate --no-audit --no-fund /proof/openclaw-candidate.tgz
npm install --global --prefix /opt/upgrade-global --no-audit --no-fund [email protected]
node /proof/runtime-proof.mjs > /proof/runtime-run.log 2>&1
node /proof/verify-receipts.mjs
# First attempt failed: updater exceeded the harness deadline and exited 143.
node /proof/upgrade-proof.mjs
# Passed: supported repair and all remaining checks, preserving original state.
node /proof/upgrade-proof.mjs --resume

The upgrade harness invokes the published updater, not an out-of-band replacement install. It checks the changed build commit even though baseline and candidate both report package version 2026.10.2. The resume path neither rewrites the baseline config nor recreates the workspace sentinel.

{
  "candidate": "f1425991727896e20378f690fddd044a64fee77a",
  "packageSha256": "e169735bedbcbe71f39f639e3ff8d07053bb7d92dc65ed3a1b2fc9e973d67c9b",
  "runtimeScenarioGroups": 9,
  "gatewayTurns": 15,
  "finalEffectsBySource": {
    "plugin": 4,
    "mcp": 6,
    "client": 5
  },
  "forbiddenEffects": 0,
  "searchAndDescribePayloadsVerified": [
    "mcp",
    "client"
  ],
  "sameNameClientCases": [
    "direct",
    "deferred"
  ],
  "refreshCases": [
    "client inventory and prompt cap",
    "MCP tools/list_changed with removed and added tools"
  ],
  "externalModelProvider": false
}
{
  "status": "passed-after-recovery",
  "baseline": "OpenClaw 2026.10.2 (b8952d4)",
  "candidate": "OpenClaw 2026.10.2 (f142599)",
  "initialUpdateExitCode": 143,
  "harnessDeadlineSeconds": 900,
  "cleanOneShotUpgrade": false,
  "recoveryPassed": true,
  "publishedUpdater": true,
  "preserved": [
    "toolSearch settings",
    "workspace",
    "session history"
  ],
  "selectorsPersistedAndLoadedInNewProcess": true
}
Original interrupted-update diagnostics (exit 143; stdout was empty)
Warning: canvas migration declares no data resources; its private state is not in the recovery set
Warning: crabbox migration declares no data resources; its private state is not in the recovery set
Warning: memory-core migration declares no data resources; its private state is not in the recovery set
Warning: workboard migration declares no data resources; its private state is not in the recovery set
candidate-state-snapshot: Preparing update checks
[sqlite/transaction] slow SQLite transaction hold async=false database=/tmp/selector-upgrade-home/.openclaw/state/openclaw.sqlite operation=update.run elapsedMs=1224 isMainThread=false mode=immediate pid=1061 threadId=5 thresholdMs=1000
candidate-state-snapshot: shared database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: copying, attempt 1, 0/0 pages, 0.000 seconds.
candidate-state-snapshot: shared database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: copying, attempt 1, 360/360 pages, 0.049 seconds.
candidate-state-snapshot: shared database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: completed, attempt 1, 360/360 pages, 1,474,560 bytes, 0.086 seconds.
[sqlite/transaction] slow SQLite transaction hold async=false database=/tmp/selector-upgrade-home/.openclaw/state/openclaw.sqlite operation=update.run elapsedMs=3121 isMainThread=false mode=immediate pid=1061 threadId=5 thresholdMs=1000
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/agents/main/agent/openclaw-agent.sqlite: copying, attempt 1, 0/0 pages, 0.000 seconds.
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/agents/main/agent/openclaw-agent.sqlite: copying, attempt 1, 179/179 pages, 0.048 seconds.
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/agents/main/agent/openclaw-agent.sqlite: completed, attempt 1, 179/179 pages, 733,184 bytes, 0.181 seconds.
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: copying, attempt 1, 0/0 pages, 0.000 seconds.
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: copying, attempt 1, 360/360 pages, 0.043 seconds.
candidate-state-snapshot: database snapshot $OPENCLAW_STATE_DIR/state/openclaw.sqlite: completed, attempt 1, 360/360 pages, 1,474,560 bytes, 0.228 seconds.
candidate-state-cleanup: Temporary-copy cleanup /tmp/selector-upgrade-home/.openclaw.update-captures/openclaw-update-canary-KNBDXk; waiting for filesystem removal; budget=300000ms (5 minutes for large copies on slow disks); deadline=2026-10-12T21:39:40.571Z.
candidate-state-cleanup: Temporary-copy cleanup /tmp/selector-upgrade-home/.openclaw.update-captures/openclaw-update-canary-KNBDXk; removed disposable temporary copy; budget=300000ms (5 minutes for large copies on slow disks); deadline=2026-10-12T21:39:40.571Z.
Package publication recovery: /usr/local/bin/node /opt/upgrade-global/lib/node_modules/.openclaw.package-activation-2e4bcc8001531aafa6672b9c.control/recovery.mjs --anchor /opt/upgrade-global/lib/node_modules/.openclaw.package-activation-2e4bcc8001531aafa6672b9c --operation 8b4d7f3f-faaa-4e7b-ae26-3ea09df5b862 status
Keep other package managers stopped; repair may republish a missing installation. Recovery does not restart or verify the Gateway.
[infra:temp-artifacts] Runtime retained at /opt/upgrade-global/lib/openclaw-update-runtime-oQcfsN: worker generation settled; cleanup deferred to the next eligible update or openclaw doctor --fix

Reproducible installed-runtime harness (runtime-proof.mjs)
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs/promises";
import { createWriteStream } from "node:fs";
import { createRequire } from "node:module";
import http from "node:http";
import { setTimeout as delay } from "node:timers/promises";
import { applyMockOpenAiModelConfig } from "/harness/scripts/e2e/lib/fixtures/mock-openai-config.mjs";

const root = "/proof";
const cli = "/opt/candidate/node_modules/.bin/openclaw";
const home = `/tmp/selector-proof-home-${Date.now()}`;
const state = `${home}/.openclaw`;
const plugin = `${home}/acme`;
const modelPort = 44080;
const gatewayPort = 18791;
const token = "synthetic-selector-proof-token";
const children = [];
const env = {
  ...process.env,
  HOME: home,
  OPENCLAW_HOME: home,
  OPENCLAW_STATE_DIR: state,
  OPENCLAW_CONFIG_PATH: `${state}/openclaw.json`,
  OPENAI_API_KEY: "synthetic-local-model-key",
  OPENCLAW_GATEWAY_TOKEN: token,
  OPENCLAW_DISABLE_BONJOUR: "1",
  OPENCLAW_SKIP_STARTUP_MODEL_PREWARM: "1",
  OPENCLAW_SKIP_CHANNELS: "1",
  OPENCLAW_SKIP_CRON: "1",
};
const schema = { type: "object", properties: { marker: { type: "string" } }, required: ["marker"] };
const require = createRequire("/opt/candidate/node_modules/openclaw/package.json");
const receipts = [];
let proxy;
async function json(file, value) {
  await fs.writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
}
async function lines(file) {
  try {
    return (await fs.readFile(file, "utf8")).trim().split("\n").filter(Boolean).map(JSON.parse);
  } catch (error) {
    if (error.code === "ENOENT") return [];
    throw error;
  }
}
function start(command, args, name, extraEnv = {}) {
  const log = createWriteStream(`${root}/${name}.log`);
  const child = spawn(command, args, { env: { ...env, ...extraEnv }, stdio: ["ignore", "pipe", "pipe"] });
  child.stdout.pipe(log);
  child.stderr.pipe(log);
  children.push(child);
  return child;
}
async function stop(child) {
  if (child.exitCode !== null || child.signalCode !== null) return;
  child.kill("SIGTERM");
  await Promise.race([once(child, "exit"), delay(10000)]);
  if (child.exitCode === null && child.signalCode === null) {
    child.kill("SIGKILL");
    await once(child, "exit");
    throw new Error("Gateway failed to shut down cleanly");
  }
}
async function ready(url, child) {
  for (let i = 0; i < 180; i++) {
    assert.equal(child.exitCode, null, `${url}: child exited ${child.exitCode}`);
    try {
      const response = await fetch(url, { signal: AbortSignal.timeout(1000) });
      if (response.ok) return;
    } catch (error) {
      if (!(error instanceof TypeError) && error.name !== "TimeoutError") throw error;
    }
    await delay(1000);
  }
  throw new Error(`Readiness timeout: ${url}`);
}
function events(name, args, index) {
  const id = `call_proof_${index}`;
  const item = { type: "function_call", id: `fc_${id}`, call_id: id, name, arguments: JSON.stringify(args) };
  return { events: [
    { type: "response.output_item.added", output_index: 0, item: { ...item, arguments: "" } },
    { type: "response.function_call_arguments.delta", output_index: 0, item_id: item.id, delta: item.arguments },
    { type: "response.output_item.done", output_index: 0, item },
    { type: "response.completed", response: { id: `resp_${id}`, status: "completed", output: [item],
      usage: { input_tokens: 10, output_tokens: 10, total_tokens: 20, input_tokens_details: { cached_tokens: 0 } } } },
  ] };
}
async function turn(label, calls = [], clientNames = [], session = label) {
  const previous = (await lines(`${root}/model-requests.jsonl`)).length;
  await json(`${root}/model-control.json`, {
    scriptVersion: label,
    responses: [...calls.map(([name, args], index) => events(name, args, `${label}_${index}`)), { text: `PROOF_DONE_${label}` }],
  });
  const response = await fetch(`http://127.0.0.1:${gatewayPort}/v1/responses`, {
    method: "POST",
    headers: { authorization: `Bearer ${token}`, "content-type": "application/json",
      "x-openclaw-agent": "main", "x-openclaw-session-key": `agent:main:openresponses:proof-${session}` },
    body: JSON.stringify({ model: "openclaw/main", input: `Execute the fixture sequence for ${label}.`,
      tools: clientNames.map((name) => ({ type: "function", name, description: "Test-owned client effect recorder", parameters: schema })),
      stream: false }),
    signal: AbortSignal.timeout(180000),
  });
  const body = await response.json();
  await json(`${root}/${label}-response.json`, body);
  assert.equal(response.status, 200, `${label}: ${JSON.stringify(body)}`);
  const requests = (await lines(`${root}/model-requests.jsonl`)).slice(previous);
  await json(`${root}/${label}-requests.json`, requests);
  const clientCalls = (body.output ?? []).filter((item) => item.type === "function_call");
  for (const call of clientCalls) {
    assert(clientNames.includes(call.name), `Unregistered client call ${call.name}`);
    await fs.appendFile(`${root}/effects.jsonl`, `${JSON.stringify({ source: "client", name: call.name, args: JSON.parse(call.arguments) })}\n`);
  }
  console.log(JSON.stringify({ label, status: response.status, requestCount: requests.length, clientCalls }));
  return { body, requests, clientCalls };
}
async function main() {
  await fs.mkdir(`${state}/workspace`, { recursive: true });
  await fs.mkdir(plugin, { recursive: true });
  await fs.writeFile(`${state}/workspace/proof.txt`, "CORE_READ_PROOF\n");
  await json(`${root}/policy.json`, {});
  await json(`${root}/model-control.json`, { text: "PROOF_READY" });
  await fs.writeFile(`${root}/effects.jsonl`, "");
  await fs.writeFile(`${root}/hooks.jsonl`, "");
  await fs.writeFile(`${root}/model-requests.jsonl`, "");
  await json(`${plugin}/package.json`, { name: "selector-proof-acme", version: "0.0.0", type: "module", openclaw: { extensions: ["./index.mjs"] } });
  await json(`${plugin}/openclaw.plugin.json`, { id: "acme", name: "Selector proof", activation: { onStartup: true },
    contracts: { tools: ["acme_status", "acme_lookup", "fixture__blocked"] },
    configSchema: { type: "object", properties: {}, additionalProperties: false } });
  await fs.writeFile(`${plugin}/index.mjs`, `
import fs from "node:fs";
export default { id: "acme", name: "Selector proof", register(api) {
  for (const name of ["acme_status", "acme_lookup", "fixture__blocked"]) {
    api.registerTool({name, label: name, description: "Local proof plugin tool " + name,
      parameters: ${JSON.stringify(schema)},
      async execute(_id, args) {
        fs.appendFileSync("/proof/effects.jsonl", JSON.stringify({source:"plugin", name, args})+"\\n");
        return {content:[{type:"text", text:"PLUGIN_EFFECT_"+name}],details:{owner:"acme"}};
      }}, {name});
  }
  api.on("before_prompt_build", () => {
    const policy = JSON.parse(fs.readFileSync("/proof/policy.json","utf8"));
    fs.appendFileSync("/proof/hooks.jsonl", JSON.stringify({hook:"before_prompt_build",policy})+"\\n");
    return policy;
  });
}};
`);
  await fs.writeFile(`${home}/mcp.mjs`, `
import fs from "node:fs";
import { McpServer } from ${JSON.stringify(require.resolve("@modelcontextprotocol/sdk/server/mcp.js"))};
import { StdioServerTransport } from ${JSON.stringify(require.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
import { z } from ${JSON.stringify(require.resolve("zod"))};
const server = new McpServer({name:"selector-proof",version:"1.0.0"});
let writeTool;
let added = false;
for (const name of ["read_frequent","write_note","blocked"]) {
  const registered = server.tool(name, "Fixture MCP "+name, {marker:z.string()}, async (args) => {
    fs.appendFileSync("/proof/effects.jsonl", JSON.stringify({source:"mcp",name,args})+"\\n");
    if (args.marker === "refresh-inventory" && !added) {
      added = true;
      writeTool.disable();
      server.tool("added_note", "Fixture MCP added tool", {marker:z.string()}, async (input) => {
        fs.appendFileSync("/proof/effects.jsonl", JSON.stringify({source:"mcp",name:"added_note",args:input})+"\\n");
        return {content:[{type:"text",text:"MCP_EFFECT_added_note"}]};
      });
    }
    return {content:[{type:"text",text:"MCP_EFFECT_"+name}]};
  });
  if (name === "write_note") writeTool = registered;
}
await server.connect(new StdioServerTransport());
`);
  const config = {
    gateway: { mode: "local", auth: { mode: "token", token }, controlUi: { enabled: false },
      http: { endpoints: { responses: { enabled: true } } } },
    agents: { defaults: { workspace: `${state}/workspace`, heartbeat: { every: "0m" } } },
    memory: { search: { enabled: false } },
    plugins: { allow: ["acme"], slots: { memory: "none" }, load: { paths: [plugin] },
      entries: { acme: { enabled: true, hooks: { allowConversationAccess: true } } } },
    tools: { allow: ["*"], codeMode: false,
      toolSearch: { enabled: true, mode: "tools", include: [{ source: "mcp" }], exclude: [{ source: "mcp", name: "fixture__read_*" }] } },
    mcp: { servers: { fixture: { command: "node", args: [`${home}/mcp.mjs`], cwd: home, connectionTimeoutMs: 30000 } } },
  };
  applyMockOpenAiModelConfig(config, { mockPort: modelPort, modelRef: "openai/gpt-5.5" });
  config.models.providers.openai.baseUrl = `http://127.0.0.1:${modelPort + 1}/v1`;
  await json(env.OPENCLAW_CONFIG_PATH, config);
  await json(`${root}/initial-config.json`, config);
  const mock = start("node", ["/harness/scripts/e2e/mock-openai-server.mjs"], "model", {
    MOCK_PORT: String(modelPort), MOCK_RESPONSE_CONTROL: `${root}/model-control.json`, MOCK_REQUEST_LOG: `${root}/model-requests.jsonl`,
  });
  await ready(`http://127.0.0.1:${modelPort}/health`, mock);
  proxy = http.createServer(async (req, res) => {
    try {
      const chunks = [];
      for await (const chunk of req) chunks.push(chunk);
      const body = Buffer.concat(chunks);
      const payload = JSON.parse(body);
      if (payload.model !== "gpt-5.5") {
        const item = { type: "message", id: "utility_msg", role: "assistant", status: "completed",
          content: [{ type: "output_text", text: "Synthetic activity recap", annotations: [] }] };
        const event = { type: "response.completed", response: { id: "utility_resp", status: "completed",
          output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } };
        res.writeHead(200, { "content-type": "text/event-stream" });
        res.end(`data: ${JSON.stringify(event)}\n\ndata: [DONE]\n\n`);
        return;
      }
      const response = await fetch(`http://127.0.0.1:${modelPort}${req.url}`, {
        method: "POST", headers: { "content-type": "application/json" }, body,
      });
      res.writeHead(response.status, { "content-type": response.headers.get("content-type") });
      res.end(Buffer.from(await response.arrayBuffer()));
    } catch (error) {
      console.error(error);
      res.writeHead(500);
      res.end(JSON.stringify({ error: String(error) }));
    }
  });
  proxy.listen(modelPort + 1, "127.0.0.1");
  await once(proxy, "listening");
  let gateway = start(cli, ["gateway", "run", "--port", String(gatewayPort), "--bind", "loopback", "--allow-unconfigured"], "gateway");
  await ready(`http://127.0.0.1:${gatewayPort}/healthz`, gateway);
  const discover = await turn("discover", [], ["client_ping"]);
  await json(`${root}/discovery.json`, discover);
  const declared = JSON.parse(discover.requests[0].body).tools.map((tool) => tool.name);
  for (const name of ["read", "acme_status", "client_ping", "fixture__read_frequent", "tool_search", "tool_describe", "tool_call"]) {
    assert(declared.includes(name), `Missing direct tool ${name}`);
  }
  assert(!declared.includes("fixture__write_note"), "MCP write schema must be deferred");
  assert((await lines(`${root}/hooks.jsonl`)).length > 0, "Prompt policy hook must actually execute");
  receipts.push({ scenario: "mcp-only-selection-and-exception", status: "passed", declared });
  const direct = await turn("direct", [
    ["read", { path: `${state}/workspace/proof.txt` }],
    ["acme_status", { marker: "direct-plugin" }],
    ["fixture__blocked", { marker: "direct-plugin-mcp-lookalike" }],
    ["fixture__read_frequent", { marker: "direct-mcp-exception" }],
  ], ["client_ping"]);
  assert(JSON.stringify(direct.requests).includes("CORE_READ_PROOF"), "Core read must reach the model");
  assert((await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker === "direct-plugin"));
  assert((await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker === "direct-mcp-exception"));
  receipts.push({ scenario: "direct-core-plugin-mcp-exception-execution", status: "passed" });
  const deferred = await turn("deferred", [
    ["tool_search", { query: "write_note" }],
    ["tool_describe", { id: "fixture__write_note" }],
    ["tool_call", { id: "fixture__write_note", args: { marker: "deferred-mcp" } }],
    ["tool_call", { id: "fixture__blocked-2", args: { marker: "mcp-lookalike-positive" } }],
  ], ["client_ping"]);
  assert((await lines(`${root}/effects.jsonl`)).some((entry) => entry.source === "mcp" && entry.args.marker === "deferred-mcp"));
  assert(JSON.stringify(deferred.requests).includes("MCP_EFFECT_write_note"));
  assert((await lines(`${root}/effects.jsonl`)).some((entry) => entry.source === "mcp" && entry.args.marker === "mcp-lookalike-positive"));
  receipts.push({ scenario: "mcp-search-describe-call", status: "passed" });
  const directClient = await turn("direct-client", [["client_ping", { marker: "direct-client" }]], ["client_ping"]);
  assert.equal(directClient.clientCalls.length, 1);
  receipts.push({ scenario: "direct-client-dispatch-and-effect", status: "passed" });
  const clientPositive = await turn("client-collision-positive", [["acme_lookup", { marker: "client-positive" }]], ["acme_lookup"], "collision");
  assert.equal(clientPositive.clientCalls.length, 1);
  await json(`${root}/policy.json`, { toolsAllow: ["acme", "tool_search", "tool_describe", "tool_call"] });
  const restricted = await turn("restricted-client", [["acme_lookup", { marker: "forbidden-client" }]], ["acme_lookup"], "collision");
  assert.equal(restricted.clientCalls.length, 0);
  assert(!JSON.parse(restricted.requests[0].body).tools.some((tool) => tool.name === "acme_lookup"));
  const beforeDenial = (await lines(`${root}/effects.jsonl`)).length;
  const mcpDenied = await turn("restricted-mcp", [
    ["tool_call", { id: "fixture__write_note", args: { marker: "forbidden-mcp" } }],
    ["tool_call", { id: "fixture__blocked-2", args: { marker: "forbidden-mcp-lookalike" } }],
    ["acme_status", { marker: "authorized-plugin-under-cap" }],
  ], ["acme_lookup"], "collision");
  const newEffects = (await lines(`${root}/effects.jsonl`)).slice(beforeDenial);
  assert.deepEqual(newEffects.map((entry) => entry.source), ["plugin"]);
  assert(JSON.stringify(mcpDenied.requests).includes("Unknown tool"));
  receipts.push({ scenario: "source-qualified-cap-client-collision-and-mcp-denial", status: "passed" });
  const refreshed = await turn("restricted-client-refresh", [["acme_lookup", { marker: "forbidden-after-refresh" }]], ["acme_lookup", "client_new"], "collision");
  assert.equal(refreshed.clientCalls.length, 0);
  await json(`${root}/policy.json`, {});
  const restored = await turn("restored-client", [["acme_lookup", { marker: "restored-client" }]], ["acme_lookup", "client_new"], "collision");
  assert.equal(restored.clientCalls.length, 1);
  assert(!(await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker.startsWith("forbidden")));
  receipts.push({ scenario: "same-session-client-inventory-refresh-and-policy-restoration", status: "passed" });
  await turn("mcp-refresh-positive", [
    ["tool_call", { id: "fixture__write_note", args: { marker: "before-mcp-refresh" } }],
    ["fixture__read_frequent", { marker: "refresh-inventory" }],
  ], [], "mcp-refresh");
  const afterRefresh = await turn("mcp-refresh-negative", [
    ["tool_search", { query: "added_note" }],
    ["tool_call", { id: "fixture__write_note", args: { marker: "forbidden-stale-mcp" } }],
    ["tool_call", { id: "fixture__added_note", args: { marker: "after-mcp-refresh" } }],
  ], [], "mcp-refresh");
  assert(!(await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker === "forbidden-stale-mcp"));
  assert((await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker === "after-mcp-refresh"));
  assert(JSON.stringify(afterRefresh.requests).includes("MCP_EFFECT_added_note"));
  receipts.push({ scenario: "same-session-mcp-inventory-refresh-no-stale-effect", status: "passed" });
  await stop(gateway);
  config.tools.toolSearch.include.push({ source: "client", name: "client_deferred" }, { source: "client", name: "acme_lookup" });
  await json(env.OPENCLAW_CONFIG_PATH, config);
  gateway = start(cli, ["gateway", "run", "--port", String(gatewayPort), "--bind", "loopback", "--allow-unconfigured"], "gateway-partial-clients");
  await ready(`http://127.0.0.1:${gatewayPort}/healthz`, gateway);
  const partial = await turn("partial-clients", [], ["client_ping", "client_deferred", "acme_lookup"]);
  const partialNames = JSON.parse(partial.requests[0].body).tools.map((tool) => tool.name);
  assert(partialNames.includes("client_ping"));
  assert(!partialNames.includes("client_deferred"));
  const deferredClient = await turn("deferred-client", [
    ["tool_search", { query: "client_deferred" }],
    ["tool_describe", { id: "client_deferred" }],
    ["tool_call", { id: "client_deferred", args: { marker: "deferred-client" } }],
  ], ["client_ping", "client_deferred", "acme_lookup"], "partial");
  assert.equal(deferredClient.clientCalls.length, 1);
  assert.equal(deferredClient.clientCalls[0].name, "client_deferred");
  receipts.push({ scenario: "persisted-partial-client-deferral-search-describe-dispatch", status: "passed" });
  const deferredShadow = await turn("deferred-client-shadow-positive", [
    ["tool_call", { id: "client:client:acme_lookup", args: { marker: "deferred-shadow-positive" } }],
  ], ["acme_lookup"], "deferred-collision");
  assert.equal(deferredShadow.clientCalls.length, 1);
  await json(`${root}/policy.json`, { toolsAllow: ["acme", "tool_search", "tool_describe", "tool_call"] });
  const deferredDenied = await turn("deferred-client-shadow-denied", [
    ["tool_call", { id: "client:client:acme_lookup", args: { marker: "forbidden-deferred-shadow" } }],
    ["acme_status", { marker: "authorized-plugin-deferred-cap" }],
  ], ["acme_lookup", "client_new"], "deferred-collision");
  assert.equal(deferredDenied.clientCalls.length, 0);
  assert(!(await lines(`${root}/effects.jsonl`)).some((entry) => entry.args.marker.startsWith("forbidden")));
  assert(JSON.stringify(deferredDenied.requests).includes("Unknown tool"));
  receipts.push({ scenario: "deferred-client-same-name-source-cap-after-refresh", status: "passed" });
  await json(`${root}/policy.json`, {});
  await json(`${root}/runtime-summary.json`, receipts);
}
try {
  await main();
} finally {
  if (proxy) await new Promise((resolve) => proxy.close(resolve));
  for (const child of children.reverse()) {
    await stop(child);
  }
}
Independent captured-result assertions (verify-receipts.mjs)
import assert from "node:assert/strict";
import fs from "node:fs/promises";
const root = new URL("./", import.meta.url);
const load = async (name) => JSON.parse(await fs.readFile(new URL(name, root), "utf8"));
const records = (await fs.readFile(new URL("effects.jsonl", root), "utf8")).trim().split("\n").map(JSON.parse);
const runtime = await load("runtime-summary.json");
assert.equal(runtime.length, 9);
assert(runtime.every((entry) => entry.status === "passed"));
const denied = records.filter((entry) => entry.args.marker.startsWith("forbidden"));
assert.equal(denied.length, 0);
for (const [marker, source] of [
  ["direct-plugin", "plugin"], ["direct-plugin-mcp-lookalike", "plugin"],
  ["direct-mcp-exception", "mcp"], ["deferred-mcp", "mcp"], ["mcp-lookalike-positive", "mcp"],
  ["direct-client", "client"], ["client-positive", "client"], ["restored-client", "client"],
  ["after-mcp-refresh", "mcp"], ["deferred-client", "client"], ["deferred-shadow-positive", "client"],
  ["authorized-plugin-under-cap", "plugin"], ["authorized-plugin-deferred-cap", "plugin"],
]) {
  assert.equal(records.filter((entry) => entry.args.marker === marker && entry.source === source).length, 1, marker);
}
for (const [label, name, source] of [
  ["deferred", "fixture__write_note", "mcp"], ["deferred-client", "client_deferred", "client"],
]) {
  const payload = JSON.parse((await load(`${label}-requests.json`)).at(-1).body);
  const outputs = payload.input.filter((item) => item.type === "function_call_output").map((item) => {
    const text = item.output;
    const inner = text.includes("<<<EXTERNAL_UNTRUSTED_CONTENT")
      ? text.slice(text.indexOf("---\n") + 4, text.lastIndexOf("\n<<<END_EXTERNAL_UNTRUSTED_CONTENT"))
      : text;
    return JSON.parse(inner);
  });
  assert(outputs.some((output) => Array.isArray(output) && output.some((tool) => tool.name === name && tool.source === source)));
  assert(outputs.some((output) => output.name === name && output.source === source && output.parameters.required.includes("marker")));
}
for (const label of ["restricted-client", "restricted-client-refresh", "deferred-client-shadow-denied"]) {
  const response = await load(`${label}-response.json`);
  assert.equal(response.output.filter((item) => item.type === "function_call").length, 0, label);
}
const summary = {
  candidate: "f1425991727896e20378f690fddd044a64fee77a",
  packageSha256: "e169735bedbcbe71f39f639e3ff8d07053bb7d92dc65ed3a1b2fc9e973d67c9b",
  runtimeScenarioGroups: runtime.length,
  gatewayTurns: (await fs.readFile(new URL("runtime-run.log", root), "utf8")).trim().split("\n").length,
  finalEffectsBySource: Object.fromEntries(["plugin", "mcp", "client"].map((source) => [source, records.filter((entry) => entry.source === source).length])),
  forbiddenEffects: denied.length,
  searchAndDescribePayloadsVerified: ["mcp", "client"],
  sameNameClientCases: ["direct", "deferred"],
  refreshCases: ["client inventory and prompt cap", "MCP tools/list_changed with removed and added tools"],
  externalModelProvider: false,
};
await fs.writeFile(new URL("verified-runtime-receipt.json", root), `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify(summary, null, 2));
Published-driver upgrade harness (upgrade-proof.mjs)
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs/promises";
import { createWriteStream } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { applyMockOpenAiModelConfig } from "/harness/scripts/e2e/lib/fixtures/mock-openai-config.mjs";

const root = "/proof";
const home = "/tmp/selector-upgrade-home";
const state = `${home}/.openclaw`;
const cli = "/opt/upgrade-global/bin/openclaw";
const resume = process.argv.includes("--resume");
const env = {
  ...process.env, HOME: home, OPENCLAW_HOME: home, OPENCLAW_STATE_DIR: state,
  OPENCLAW_CONFIG_PATH: `${state}/openclaw.json`, OPENAI_API_KEY: "synthetic-upgrade-model-key",
  PATH: `/opt/upgrade-global/bin:${process.env.PATH}`, NPM_CONFIG_PREFIX: "/opt/upgrade-global",
  npm_config_prefix: "/opt/upgrade-global", OPENCLAW_DISABLE_BONJOUR: "1",
  OPENCLAW_SKIP_STARTUP_MODEL_PREWARM: "1", OPENCLAW_SKIP_CHANNELS: "1", OPENCLAW_SKIP_CRON: "1",
};
async function json(path, value) {
  await fs.writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
}
async function run(label, args, executable = cli) {
  const child = spawn(executable, args, { cwd: "/tmp", env, stdio: ["ignore", "pipe", "pipe"] });
  let stdout = "";
  let stderr = "";
  child.stdout.on("data", (data) => { stdout += data; });
  child.stderr.on("data", (data) => { stderr += data; });
  const timeout = setTimeout(() => child.kill("SIGTERM"), 900000);
  const [code, signal] = await once(child, "exit");
  clearTimeout(timeout);
  await fs.writeFile(`${root}/${label}.stdout`, stdout);
  await fs.writeFile(`${root}/${label}.stderr`, stderr);
  console.log(JSON.stringify({ label, code, signal }));
  assert.equal(code, 0, `${label} failed: ${stderr.slice(-3000)} ${stdout.slice(-3000)}`);
  return stdout;
}
let mock;
try {
  await fs.mkdir(`${state}/workspace`, { recursive: true });
  if (!resume) await fs.writeFile(`${state}/workspace/preserved.txt`, "UPGRADE_WORKSPACE_SENTINEL\n");
  const config = {
    gateway: { mode: "local", controlUi: { enabled: false } },
    agents: { defaults: { workspace: `${state}/workspace`, heartbeat: { every: "0m" } } },
    memory: { search: { enabled: false } },
    plugins: { slots: { memory: "none" } },
    tools: { codeMode: false, toolSearch: { enabled: false, mode: "tools", searchDefaultLimit: 7, maxSearchLimit: 13 } },
  };
  applyMockOpenAiModelConfig(config, { mockPort: 44180, modelRef: "openai/gpt-5.5" });
  if (!resume) await json(env.OPENCLAW_CONFIG_PATH, config);
  const log = createWriteStream(`${root}/upgrade-model.log`);
  mock = spawn("node", ["/harness/scripts/e2e/mock-openai-server.mjs"], {
    env: { ...env, MOCK_PORT: "44180", SUCCESS_MARKER: "UPGRADE_AGENT_OK", MOCK_REQUEST_LOG: `${root}/upgrade-model-requests.jsonl` },
    stdio: ["ignore", "pipe", "pipe"],
  });
  mock.stdout.pipe(log);
  mock.stderr.pipe(log);
  let ready = false;
  for (let i = 0; i < 30; i++) {
    assert.equal(mock.exitCode, null);
    try {
      if ((await fetch("http://127.0.0.1:44180/health", { signal: AbortSignal.timeout(1000) })).ok) { ready = true; break; }
    } catch (error) {
      if (!(error instanceof TypeError) && error.name !== "TimeoutError") throw error;
    }
    await delay(1000);
  }
  assert(ready, "Mock provider did not start");
  const baseline = resume
    ? await fs.readFile(`${root}/upgrade-baseline-version.stdout`, "utf8")
    : await run("upgrade-baseline-version", ["--version"]);
  assert(baseline.includes("b8952d4"), "Baseline must be the resolved published stable package");
  let beforeConfig;
  if (resume) {
    beforeConfig = JSON.parse(await fs.readFile(`${root}/upgrade-before-config.json`, "utf8"));
    await run("upgrade-repair", ["update", "repair", "--yes", "--no-restart", "--json", "--timeout", "600"]);
  } else {
    await run("upgrade-baseline-config", ["config", "validate"]);
    const before = await run("upgrade-baseline-turn", [
      "agent", "--local", "--agent", "main", "--session-key", "agent:main:upgrade-proof",
      "--message", "UPGRADE_HISTORY_SENTINEL before installing the candidate.", "--json",
    ]);
    assert(before.includes("UPGRADE_AGENT_OK"));
    beforeConfig = JSON.parse(await fs.readFile(env.OPENCLAW_CONFIG_PATH, "utf8"));
    await json(`${root}/upgrade-before-config.json`, beforeConfig);
    await run("upgrade-published-driver", ["update", "--tag", "file:/proof/openclaw-candidate.tgz", "--yes", "--no-restart", "--json", "--timeout", "600"]);
  }
  const candidate = await run("upgrade-candidate-version", ["--version"]);
  assert(candidate.includes("f142599"), "Updater must activate the exact candidate build");
  await run("upgrade-candidate-config", ["config", "validate"]);
  const afterConfig = JSON.parse(await fs.readFile(env.OPENCLAW_CONFIG_PATH, "utf8"));
  assert.deepEqual(afterConfig.tools, beforeConfig.tools);
  assert.equal(afterConfig.agents.defaults.workspace, beforeConfig.agents.defaults.workspace);
  assert.equal(await fs.readFile(`${state}/workspace/preserved.txt`, "utf8"), "UPGRADE_WORKSPACE_SENTINEL\n");
  const beforeRequests = (await fs.readFile(`${root}/upgrade-model-requests.jsonl`, "utf8")).split("\n").filter(Boolean).length;
  const after = await run("upgrade-candidate-turn", [
    "agent", "--local", "--agent", "main", "--session-key", "agent:main:upgrade-proof",
    "--message", "Confirm the upgraded session still works.", "--json",
  ]);
  assert(after.includes("UPGRADE_AGENT_OK"));
  const newRequests = (await fs.readFile(`${root}/upgrade-model-requests.jsonl`, "utf8")).split("\n").filter(Boolean).slice(beforeRequests).map(JSON.parse);
  assert(newRequests.some((entry) => entry.body.includes("UPGRADE_HISTORY_SENTINEL")), "Prior conversation must be present in candidate model input");
  const selectors = { ...afterConfig.tools.toolSearch, enabled: true, include: [{ source: "mcp" }], exclude: [{ source: "mcp", name: "github_read_*" }] };
  await run("upgrade-set-selectors", ["config", "set", "tools.toolSearch", JSON.stringify(selectors), "--strict-json"]);
  await run("upgrade-selector-config-valid", ["config", "validate"]);
  const persisted = JSON.parse(await fs.readFile(env.OPENCLAW_CONFIG_PATH, "utf8"));
  assert.deepEqual(persisted.tools.toolSearch, selectors);
  const restarted = await run("upgrade-selector-turn", [
    "agent", "--local", "--agent", "main", "--session-key", "agent:main:upgrade-proof",
    "--message", "Confirm the persisted selectors load after a new process starts.", "--json",
  ]);
  assert(restarted.includes("UPGRADE_AGENT_OK"));
  await json(`${root}/upgrade-summary.json`, {
    status: resume ? "passed-after-recovery" : "passed", baseline: baseline.trim(), candidate: candidate.trim(),
    initialUpdateExitCode: resume ? 143 : 0, harnessDeadlineSeconds: 900,
    cleanOneShotUpgrade: !resume, recoveryPassed: resume,
    publishedUpdater: true, preserved: ["toolSearch settings", "workspace", "session history"],
    selectorsPersistedAndLoadedInNewProcess: true,
  });
} finally {
  if (mock && mock.exitCode === null && mock.signalCode === null) {
    mock.kill("SIGTERM");
    await once(mock, "exit");
  }
}
  • Build passed: corepack pnpm build completed in 12m 29.8s. It emitted bundler/advisory warnings in untouched UI and third-party code, but no build errors.
  • Post-merge focused tests passed: 207 tests in 9 files, six routed Vitest shards, 467.39s wrapper wall time.
  • Production and test types passed: core production plus agents-other, agents-tools, config-cli, packages, and services-cron.
  • Targeted lint, formatting, config documentation metadata, and feature-diff whitespace checks passed.
  • Runtime boundary proof: synthetic MCP tools remain searchable, describable, and callable through the real tool_search/tool_describe/tool_call controls; unselected tools retain direct schemas and execution. The real client/session registry exercises partial deferral, ownership, hook caps, restoration, and refresh.
  • Negative controls: before the repairs, same-name deferred client/MCP calls and direct client-shadow calls executed despite a plugin-specific prompt cap. The regressions now reject those calls while preserving authorized direct tools, explicit name grants, and restoration. These are synthetic local boundary tests, not live MCP/provider evidence.

Evidence gaps: no live commercial-provider/production-MCP-service E2E, full local pnpm check, or full local pnpm test was run. Installed-runtime and focused upgrade proof is supplied above. Earlier draft checks included a passing PR context and evidence check; broad CI was skipped while draft, and no broad-CI success or CI timing evidence is claimed. There is no visual UI change requiring screenshots. Maintainer edits are enabled. The October 13 conflict repair is published; current-revision maintainer security approval, broad CI, product acceptance, and the current-stable upgrade evidence request remain outstanding.

Canonical autoreview blocker: the shared openclaw/agent-skills helper was invoked against upstream/main at P0–P2 scope with committed caller context. Codex could not launch because its executable was missing. The permitted Claude fallback initially required a newer CLI; after installing supported Claude Code 2.1.170 in a task-local directory, review startup failed with 400 Not a valid API key for this workspace before any assessment. This is an unavailable review, not a clean result. Independently requested Fable 5.1 and Sol 6.1 source reviews of the feature before the upstream merge reported no actionable findings after both authorization repairs; they do not substitute for a successful canonical review of this merged head. This review gap and maintainer direction remain unresolved after publication.

Exact post-merge validation commands and results

Passed — 207 tests:

corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search-config.test.ts src/agents/tool-search.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts src/agents/harness/tool-surface-bridge.test.ts src/config/schema.test.ts packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts --maxWorkers=2 --reporter=dot

Passed — production types:

corepack pnpm tsgo:core

Passed — all five selected test graphs:

node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts","src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts","src/agents/embedded-agent-runner/run/attempt-prompt-admission.test-support.ts","src/agents/embedded-agent-runner/run/attempt-spawn-workspace.test-support.ts","src/config/schema.test.ts","packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts"]'

Passed — targeted lint and formatting:

git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1

Passed — generated config metadata and feature-diff whitespace:

corepack pnpm config:docs:gen
corepack pnpm config:docs:check
git diff upstream/main --check

The generated core count increases by eight paths; unrelated upstream schema changes are retained. Upstream test deletions/refactors were preserved when resolving the merge, and our session-fixture method was moved to the new shared type owner.

Single-worker cost evidence for new or materially changed test files

Each row was separately executed on the candidate as:

corepack pnpm test <file> --maxWorkers=1 --reporter=dot

All rows passed. Wall time includes repository orchestration, import/transformation, and cleanup; it is not a claim about test-body duration or CI runtime.

File Local wall time Result
src/agents/tool-search-selection.test.ts 84s Passed
src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts 51s Passed
src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts 44s Passed
src/agents/harness/tool-surface-bridge.test.ts 46s Passed
src/agents/embedded-agent-runner/run/attempt.tool-search-run-plan.test.ts 36s Passed
src/agents/tool-search-config.test.ts 5s Passed
src/config/schema.test.ts 33s Passed
packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts 8s Passed

The source-selection unit cases cover independent selector semantics. The integration proof intentionally uses the real session registry and adapter to detect last-write-wins ownership errors that a name-only mock missed. MCP calls use real controls with synthetic executors; no live service, Gateway process, or real provider request is required by these new regressions. CI seconds are not yet available.

ificator and others added 2 commits October 12, 2026 10:00
Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
Resolve upstream test refactors while retaining Tool Search selector and authorization regression coverage. Regenerate merged config documentation metadata.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Adds source-qualified include/exclude selectors for choosing which authorized tools are deferred behind Tool Search.

Example: Configure include: [{source: "mcp"}] and exclude: [{source: "mcp", name: "github_read_*"}].

  • Before: Eligible plugin and MCP tools are deferred together, including github_read_issue.
  • After: github_read_issue and non-MCP plugin tools remain direct, while eligible MCP tools such as github_write_issue require discovery.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation has meaningful shipped-entry-point evidence and no actionable code finding, but latest-stable compatibility proof and product acceptance remain unresolved.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Operators must choose between deferring all eligible tools and exposing all schemas, even when only MCP tools need discovery.
Reason: The implementation addresses the requested presentation distinction, but approval for the additional core configuration surface is explicitly outstanding.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this PR provides a distinct capability absent from main, with no concrete introduced defect found; the new core settings still need an area-owner decision.

Priority: P3
Reviewed head: 4a7845762024d075c88bf3e623171c496d05c2ca
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should Tool Search support the proposed include/exclude configuration contract for mixed native, MCP, and client inventories?
  • Recommendation: Sponsor the bounded selector design: Accept presentation-only selectors within the existing Tool Search owner, preserving source qualification and current defaults.
  • Why: The capability is missing, but two new core settings incur ongoing support cost, and neither the PR nor its linked request records area-owner approval.

Before merge

  • Add real behavior proof - Installed CLI/Gateway receipts on f142599 exercise the real selector, registry, MCP transport, and client-dispatch owners through successful calls, source-qualified denials, restoration, and inventory refresh with zero forbidden effects; later inspected changes retain those semantics. The remaining gap is the required installed upgrade from latest stable v2026.10.3, preserving settings and data and loading persisted selectors afterward; provide redacted terminal output or logs, removing IPs, keys, phone numbers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Supply an installed upgrade from v2026.10.3 preserving existing settings, workspace content, and conversation history, then demonstrate persisted selectors after restart.
Agent review details

How this fits together

The tool-surface planner passes authorized native, MCP, and client tools through catalog compaction, producing direct model schemas and a deferred catalog served by the existing search and dispatcher owners.

flowchart LR
  A[Authorized tool inventory] --> B[Tool surface planner]
  B --> C[Tool Search selectors]
  C --> D[Direct model schemas]
  C --> E[Deferred catalog]
  E --> F[Search and dispatcher]
  F --> G[Existing tool executors]
Loading

Technical review

Best possible solution:

If sponsored, retain source-qualified selection in the existing Tool Search owner with unchanged authorization, defaults, and independent Code Mode behavior.

Do we have a high-confidence way to reproduce the issue?

This is a feature request: current-main configuration and compaction lack source-qualified selection, while the supplied installed-runtime receipts demonstrate the proposed behavior.

Is this the best way to solve the issue?

The implementation uses the existing catalog and policy owners, and source qualification addresses the earlier name-only proposal's ambiguity; whether the added configuration is worthwhile remains an owner decision.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 525a7cd755d3.

Provenance checked

  • Stable directory and trusted direct visibility keeps the original intent (17ed69e: Keep a deterministic capability directory and stable provider prompt prefixes while preserving trusted coding, delivery, direct-only, and client contracts.)
  • Run-owned catalog lifetime keeps the original intent (76cc412: Make the existing run-owned catalog reference the single authority and remove process-global fallback registries.)
  • Prompt-time direct and deferred policy filtering keeps the original intent (b34eb16: Apply prompt restrictions atomically to direct tools and hidden catalogs so guidance matches callable capabilities.)
  • Availability across direct and catalog tools keeps the original intent (af9ba2a: Finalize affordances from genuine callable dependencies after filtering and registration, with client definitions winning exact-name shadows.)
  • Capability guidance versus execution allowlists keeps the original intent (f0cc57d: Retain cataloged native capabilities in stable guidance without widening execution allowlists or including foreign/client tools.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit f405852 adds src/agents/tool-search-catalog.ts:292 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f4058528e5db; files: src/agents/tool-search-catalog.ts)

PR surface

Source +189, Tests +780, Docs +50, Generated 0, Other -1. Total +1018 across 36 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 17 235 46 +189
Tests 15 795 15 +780
Docs 1 55 5 +50
Config 0 0 0 0
Generated 2 3 3 0
Other 1 0 1 -1
Total 36 1088 70 +1018

Review metrics

Metric Value Why it matters
Operator configuration 2 optional selector arrays; 0 changed defaults The permanent include/exclude contract is the substantive product decision.

Root-cause cluster

Relationship: same_root_cause
Canonical: #170058
Summary: This PR implements the same author's source-qualified selection request; the closed name-only proposal is related prior art rather than an existing implementation.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This improves advanced tool-presentation ergonomics without repairing an outage or established broken behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (8 earlier review cycles)
  • reviewed 2026-10-12T18:24:15.265Z sha f142599 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-12T21:57:56.831Z sha f142599 :: blocked before merge. :: none
  • reviewed 2026-10-12T22:08:29.616Z sha f142599 :: blocked before merge. :: none
  • reviewed 2026-10-12T23:49:00.350Z sha c0740aa :: blocked before merge. :: none
  • reviewed 2026-10-13T00:09:43.924Z sha 59be7f1 :: blocked before merge. :: none
  • reviewed 2026-10-13T15:34:12.477Z sha 59be7f1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-13T18:22:49.782Z sha a4e6807 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-13T20:14:49.593Z sha 505ca67 :: needs real behavior proof before merge. :: none

Reviewed October 14, 2026, 12:04 AM ET / 04:04 UTC (Revision 9).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
ificator and others added 2 commits October 12, 2026 15:24
Regenerate config schema metadata for upstream 20d12e8 while retaining the Tool Search selectors and upstream runtime-config test preparation.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
Preserve upstream's stable Code Mode prompt lifecycle and removed observer tests. Keep partial-client selector regressions, adopt catalogPrompt in the policy fixture, and regenerate schema metadata.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 13, 2026
@ificator
ificator marked this pull request as ready for review October 13, 2026 15:22
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Oct 13, 2026
Regenerate config metadata and retain upstream dispatcher and provenance changes without changing selector semantics.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
@ificator

ificator commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Integration receipts — latest head 6db38b3d866782652ee4aee99d1761a47b4c9570

October 21 upstream merge — completed

At the author's explicit direction, merged upstream b5aa29b1ed0fcef44ec2367dd03eb2239e55511f and resolved all conflicts in 6db38b3d866. GitHub reports the new head mergeable. The feature diff is 32 files, +1078/-46.

  • Kept upstream's removed planner and diagnostic modules removed. Migrated partial-client visible/live/replay and capability projections into prepareEmbeddedAttemptToolCatalog; its real entry-point fixture now covers the selector contracts.
  • Retained upstream's descriptor-based catalog reuse and prompt cache. Carried the feature's direct-native/direct-client metadata through both catalog replacement and reuse so availability and cleanup remain correct.
  • Reused upstream's metadata-owned source classification, Gateway tool-policy application, hook wrapping and source-execution guards. Retained actual-session-winner authorization and separately authorized catalog entries.
  • Preserved upstream test consolidations; adapted selector tests for the renamed harness factory and new array allocation. No execution-policy relaxation, migration, or new configuration was added beyond the original feature.

Validation commands and results:

corepack pnpm install --frozen-lockfile
corepack pnpm config:docs:gen
corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search-config.test.ts src/agents/tool-search.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.test.ts src/agents/embedded-agent-runner/run/attempt.tool-search-run-plan.test.ts src/agents/embedded-agent-runner/run/attempt-tool-search-prompt.test.ts src/agents/harness/tool-surface-bridge.test.ts --maxWorkers=1 --reporter=dot

Dependency installation and config generation passed. The grouped test run first passed the 56-test fast group, six prompt-parity tests, and the 51-test Tool Search owner suite, then failed two selector assertions about array object identity. Upstream legitimately allocates a new array; the assertions now compare the retained tools, not the container identity. The following rerun passed all 68 tests, including those selectors and all remaining client/policy/planner files:

corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.test.ts src/agents/embedded-agent-runner/run/attempt.tool-search-run-plan.test.ts --maxWorkers=1 --reporter=dot
# Passed: 68 tests, 135.22s.
corepack pnpm test src/config/schema.test.ts packages/gateway-protocol/src/schema/worker-gateway-tool.test.ts src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts --maxWorkers=1 --reporter=dot
# Passed: 57 tests, 103.59s.
node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core","core-test-agents-tools","core-test-agents-other","core-test-services-cron"]'
# Passed: all four canonical graphs.
git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1
corepack pnpm check:test-mock-exports --base upstream/main
corepack pnpm config:docs:check
git diff upstream/main --check
# All passed.

Unresolved validation: the automatic changed-graph selector reports oversized all-tree partitions (agents-root 722, gateway-root 729, infra 749 versus 720). Explicit affected production/test graphs pass, but the boundary gate is not relabeled as passing or suppressed. Canonical review was attempted through the shared helper and failed to launch: executable not found: codex; the installed Claude CLI remains below its minimum. A separate independent source review found no significant issues, but is not canonical review success. No full build or installed upgrade was rerun for this head.

Historical CI and installed-runtime evidence below remains pinned to its original heads. Maintainer product/security approval and the installed-upgrade evidence request remain unresolved.

October 21 check — head unchanged

  • Broad CI — passed. Run 38508694499 completed successfully on exactly 4a7845762024d075c88bf3e623171c496d05c2ca. The mock-export ratchet, both 4-KiB and 16-KiB Android Access lanes, and the CI workflow's openclaw/ci-gate check all passed. The earlier Android cancellation is no longer the current-head CI outcome.
  • Remaining red statuses — maintainer approval. The separate commit-status contexts openclaw/ci-gate and openclaw/security-sensitive-review from Security Review still state “A maintainer must approve the current PR revision.” These statuses are distinct from the successful CI check with the same name. Dependency review passed. No approval bypass or self-approval was attempted.
  • Conflict check — upstream integration remains unresolved. Fetched fork origin/main at 06056926a099dfcd9758205e30c536aa447ca887 merges without conflicts. Read-only git merge-tree --write-tree HEAD upstream/main against 44a7ac39e656afef4679e4d9b94fab8b3976636a reports 14 conflicting paths. Unlike earlier refreshes, these include adapter/catalog/config conflicts, runtime test conflicts, and upstream deletion of attempt-tool-search-run-plan.ts and attempt-decision-diagnostics.test.ts. Upstream folded single-consumer runtime owners and refactored tool handling. Reconciling this requires migrating the feature to current owners rather than resurrecting deleted modules. No working-tree merge was started and no source was changed during this check; green head CI does not establish compatibility with that newer base.
  • Comments — no new concrete code finding. Product acceptance and installed v2026.10.3 upgrade evidence remain open. The generic data-compatibility warning still has no demonstrated failing record or scenario; the previous evidence-based rejection of speculative storage changes stands. Existing recovered v2026.10.2 proof is not relabeled as v2026.10.3 proof.
  • Change-request dismissal audit — none applicable. GitHub's reviews endpoint returned an empty list. There are no human or bot CHANGES_REQUESTED reviews to dismiss. Existing bot issue comments and security-approval notices are not reviews. No unresolved request was dismissed.

October 13 evening check

  • Mock-export CI failure — resolved in hosted CI. The ratchet job on 505ca678b46 passed. The earlier repair is now supported by hosted evidence, not only a local replay.
  • Remaining CI check failure — cancelled Android lane. The CI aggregator failed because selected android-access-native was cancelled. The 4-KiB Android job was cancelled during compilePlayDebugKotlin; its logs contain no failing test assertion before “The operation was canceled.” The 16-KiB sibling passed. The initiating reason for cancellation is unverified; this is not proof of an OpenClaw code defect or a passing Android lane. No unrelated Android changes or blind rerun were made. Other selected groups reported success in that aggregator, including build artifacts, ratchets, core tests/types/lint, docs and UI.
  • Security approval — unresolved. The separate commit-status openclaw/ci-gate and openclaw/security-sensitive-review both still require maintainer approval of the current revision. These approval statuses are distinct from the cancelled-lane CI check above; no bypass or self-approval is attempted.
  • Conflicts — repaired. The fork's fetched origin/main remained conflict-free. The actual upstream base had advanced and conflicted in only the two generated config metadata files. 4a784576202 merges upstream 82b8f59a3ec944adafb05fe802928e353761f4c1 and regenerates those files, retaining the eight selector paths. Upstream's control-hook wrapping and model-result projection changes are preserved. Selector matching/resolution and source-qualified prompt-policy owners are unchanged from the previously reviewed head.
  • Comments — no new concrete finding. Product acceptance and the installed v2026.10.3 upgrade request remain open. The earlier recovered v2026.10.2 proof is not relabeled as current-stable proof. The generic storage warning still identifies no failing example, so it does not justify speculative storage changes.
  • Dismissals — none applicable. The GitHub reviews API contains no formal reviews, including no CHANGES_REQUESTED reviews. Bot issue comments and approval notices cannot be dismissed as reviews.

Passed on the final merged tree:

corepack pnpm install --frozen-lockfile
corepack pnpm config:docs:gen
corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search.test.ts src/agents/harness/tool-surface-bridge.test.ts src/config/schema.test.ts --maxWorkers=1 --reporter=dot
# 130 tests across four files; 236.74s wrapper time.
corepack pnpm tsgo:core
node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/agents/tool-search.test.ts","src/agents/harness/tool-surface-bridge.test.ts","src/config/schema.test.ts"]'
# agents-tools and config-cli passed.
corepack pnpm check:test-mock-exports --base upstream/main
git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1
corepack pnpm config:docs:check
git diff upstream/main --check

No final-head full build, installed upgrade, or completed broad CI run is claimed. The new push is a conflict repair, not a replay solely to obtain green CI.

October 13 follow-up: CI mock-export ratchet — fixed

The failed ratchet job rejected the first-party mock in attempt-spawn-workspace.tools-mock.test-support.ts. CI classified this as new, and the same checker failed locally before the fix.

505ca678b46 spreads the already-loaded real adapter module before applying the existing toToolDefinitions override. This preserves current and future real exports without changing runtime code or adding module imports. The checker then required removal of the now-obsolete grandfathered exception; its --prune command removed exactly that one entry (9692 → 9691). No new allowance, ignore, or isolation suppression was added.

Verification:

corepack pnpm check:test-mock-exports --base 400cc5df5b6bed84d3ab8f7e1d968c7ed8299718
# Failed before; passed after repair and removal of the stale exception.
corepack pnpm check:test-mock-exports --base 400cc5df5b6bed84d3ab8f7e1d968c7ed8299718 --prune
# Passed; removed only the repaired mock's exception.
corepack pnpm test src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts --maxWorkers=1 --reporter=dot
# Passed: 25 tests, 119.34s wrapper time.
node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/embedded-agent-runner/run/attempt-spawn-workspace.tools-mock.test-support.ts","src/agents/embedded-agent-runner/run/attempt.spawn-workspace.context-engine.test.ts"]'
# Passed: agents-other and services-cron.
corepack pnpm exec oxfmt --check --threads=1 src/agents/embedded-agent-runner/run/attempt-spawn-workspace.tools-mock.test-support.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/embedded-agent-runner/run/attempt-spawn-workspace.tools-mock.test-support.ts
git diff --check
# Formatting, lint and whitespace checks passed.

The fork's origin/main is still conflict-free; GitHub reports 505ca678b46 mergeable. No formal CHANGES_REQUESTED reviews exist, so no dismissal is applicable. The prior maintainer-security approval, product decision, and current-stable upgrade proof requests below remain unresolved. A local checker pass is not a claim that a new broad CI run has completed.

Previous receipts on a4e68073dc809dc10972ef93174c8c5959cd14e0

  1. Merge conflict — fixed. Merged upstream 400cc5df5b6bed84d3ab8f7e1d968c7ed8299718 in a4e68073dc8. The two generated config metadata files were regenerated. Upstream dispatcher/provenance changes are retained; three selector tests now expect the upstream dispatch_action name. No selector semantics were changed. The fork's origin/main (06056926a099dfcd9758205e30c536aa447ca887) had no merge conflicts; the conflicts were against this PR's actual upstream base.

  2. Failing checks — maintainer approval still required. On the checked head 59be7f106ac, both openclaw/ci-gate and openclaw/security-sensitive-review reported: “A maintainer must approve the current PR revision.” The Security Review workflow itself succeeded; its enforcement step reported that it was awaiting maintainer approval. The same two gate failures are now verified on a4e68073dc8 against the new-head workflow. Dependency review passed. These are real policy-gate failures, not a failing build/test command to repair. Approval must cover the new head; no policy bypass or self-approval was attempted.

  3. Compatibility comment — no demonstrated data defect; latest-stable proof remains open. The generic assertion that stored data may not work is not accompanied by a failing example or a review finding. The selector patch adds optional configuration arrays (schema); it does not introduce a storage migration. I therefore do not treat that assertion as an established bug or make speculative storage changes. This does not resolve the separate request for an installed upgrade from stable 2026.10.3: that exact exercise was not run. The existing installed-runtime and recovered 2026.10.2 upgrade evidence remains historical evidence on f142599, not fresh proof for this head.

  4. Product decision — unresolved. Maintainer acceptance of the additional operator-facing configuration contract is still needed; it is not inferred from bot recommendations or passing tests.

  5. Review dismissal audit. The GitHub reviews API returned no formal reviews, including no CHANGES_REQUESTED reviews. The ClawSweeper assessment and security-approval notice are issue comments, not dismissible reviews. No review was dismissed, and no dismissal was deferred pending CI or re-review.

Verification

Passed on the merged source subsequently committed unchanged as a4e68073dc8:

corepack pnpm install --frozen-lockfile
corepack pnpm config:docs:gen
corepack pnpm test src/agents/tool-search-selection.test.ts src/agents/tool-search.test.ts src/agents/harness/tool-surface-bridge.test.ts src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts src/agents/embedded-agent-runner/run/attempt-prompt-tool-policy.integration.test.ts src/config/schema.test.ts --maxWorkers=1 --reporter=dot
# Passed: 148 tests across six files; 344.89s wrapper time.
corepack pnpm test src/agents/embedded-agent-runner/run/attempt.tool-search-run-plan.test.ts --maxWorkers=1 --reporter=dot
# Passed: 7 tests; 36.88s wrapper time.
corepack pnpm tsgo:core
node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/tool-search-selection.test.ts","src/agents/harness/tool-surface-bridge.test.ts","src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts","src/config/schema.test.ts"]'
# Passed: agents-other, agents-tools, config-cli.
git diff upstream/main --name-only -z -- '*.ts' | xargs -0 node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json
git diff upstream/main --name-only -z -- '*.ts' '*.md' | xargs -0 corepack pnpm exec oxfmt --check --threads=1
corepack pnpm config:docs:check
git diff upstream/main --check

No new full build, installed-package run, or broad-CI success is claimed for this head. Prior full-build and package receipts remain pinned to their documented commits. This check does not authorize merging or waive maintainer approval.

ificator and others added 3 commits October 13, 2026 13:02
Spread the already-loaded real module before overriding toToolDefinitions, then remove the resolved grandfathered mock exception.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
Retain upstream control-hook and model-result projection changes; regenerate the eight additional selector schema paths.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
Retain inlined catalog planning, descriptor-based reuse, current tool guards and deleted diagnostic paths. Preserve partial client deferral and source-qualified authorization coverage.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: ea584bec-8136-4fa7-86af-96d0d8953157
@giodl73-repo giodl73-repo self-assigned this Oct 21, 2026
@giodl73-repo

Copy link
Copy Markdown
Contributor

Review follow-up for head 6db38b3d866782652ee4aee99d1761a47b4c9570:

Full source review of all 32 changed files and relevant callers, plus a separate Codex review, found no confirmed introduced implementation defects. Both were static reviews; this is not new runtime or installed-upgrade proof, nor a maintainer security approval.

To make the remaining merge path concrete:

  1. Area-owner decision: Please confirm acceptance of the optional tools.toolSearch.include / exclude configuration contract proposed in [Feature]: Select which tools are deferred behind Tool Search #170058. The design selects presentation, not additional tool permissions.
  2. Current-revision security review: The security gate still requests maintainer approval of this exact revision. Our source-review result does not substitute for that approval.
  3. Validation closeout: Current-head CI passes build, types, lint and boundary checks, but the UI recovery shard has two Retry now timeouts and android-test-play was cancelled. Please resolve these or establish their cause with evidence; we have not established that they are unrelated. Also close the existing installed-upgrade request on the candidate head, showing preserved settings, workspace/history and persisted selectors after restart, with the stable source version stated explicitly. Earlier recovered v2026.10.2 evidence is not that current-head proof.

Positive on the implementation based on review. The remaining CI/upgrade items are technical validation gaps, not just process, and do not establish a storage defect or justify speculative migration changes. No merge or gate waiver is requested by this comment.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@giodl73-repo: Patrick-Erichsen requested landing follow-through after discussing the selector design and security boundaries. I am retaining your assignment and source-review findings, and investigating the remaining exact-head CI and installed-upgrade gaps before native merge admission. No security approval or CI waiver is being inferred from the landing request.

roboclaw-bot and others added 3 commits October 23, 2026 04:49
Merge current main without rewriting contributor ancestry and regenerate the two config metadata files. The selector feature remains unchanged; 199 focused tests, prefix stability, lint, formatting, and config metadata checks pass.

Co-authored-by: Patrick-Erichsen <[email protected]>
Carry selected-out direct-name collisions on catalog descriptors so directory guidance, fallback lookup, dispatch, and recovery use the same identity decision. Preserve exact-ID dispatch and direct execution while invalidating cached guidance after inventory and prompt-policy changes. The production-owner regression fails before the repair and passes afterward; selector and sibling suites, core/test types, lint, and formatting pass.

Co-authored-by: Patrick-Erichsen <[email protected]>
Baseline-Refresh: e803cbe6940e2dc39c757320da01321729e4d193
Co-authored-by: Patrick-Erichsen <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

/allow-security-sensitive-change

@roboclaw-bot
roboclaw-bot merged commit 3ff4a6c into openclaw:main Oct 23, 2026
153 of 156 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

@ificator
ificator deleted the feat/tool-search-selectors branch October 23, 2026 20:29
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
…0071)

Allow operators to choose which authorized tools are deferred behind Tool Search using source-qualified include/exclude selectors, preserving existing defaults and execution permissions.

Keep direct/deferred name collisions unambiguous: deferred tools with a direct namesake require their exact catalog ID, and cached guidance follows inventory and prompt-policy changes.

Co-authored-by: Brad Cleaver <[email protected]>
Co-authored-by: Patrick-Erichsen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants