Repository navigation
fix(gateway): run CLI bridge tool calls in their own run's request scope - #157144
Leit-motif wants to merge 2 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Thanks for the context here. I did a careful shell check against current This PR’s implementation was incorporated into a formally linked merged PR, and current main fixes the requested behavior with stronger authority coverage. I found the merged PR that appears to have closed this: #165432: fix(gateway): claude-cli session tools fail after the turn that started the MCP loopback ends. Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. So I’m closing this as already implemented rather than keeping a duplicate issue open. Review detailsBest possible solution: Retain the merged implementation and close this absorbed branch. Do we have a high-confidence way to reproduce the issue? The contributor supplied live before/after reproduction through an isolated Gateway and Claude CLI; current-main source and regression coverage repair that path, and this read-only review ran no code. Is this the best way to solve the issue? The merged solution is more complete because it clears all starter-local async stores while retaining Gateway resources and restoring each grant’s own authority. Security review: Security review cleared: Recorded live proof and merged HTTP coverage preserve caller ceilings and reject closed or revoked authority before dispatch. AGENTS.md: found and applied where relevant. What I checked:
Codex review notes: model internal, reasoning medium; reviewed against e3604e876c8f; fix evidence: merged PR #165432, release v2026.10.5-beta.1, commit fdcbcf5c2ebd. |
The listener no longer inherits its starter's scope, so each CLI grant now carries the Gateway request scope it was minted in. Bridge tool calls re-enter that scope, as in-process runtimes do, so a write-only restart-recovery run stays capped and a run whose client authority closed is still refused.
|
Independent confirmation on a Linux Docker gateway: this branch cherry-picked onto main at 1e9f0d0 (2026.9.6), claude-cli backend, Claude Code 2.1.280, Telegram forum topics that reply through the message tool. Before, on main without this PR: after a deploy, the first claude-cli turn was a short-lived shell After, with this PR:
On current main the branch applies cleanly: |
|
Confirmed on a systemd Gateway with
One more listener gap on current Our regression test for this is in the patch below, on top of this PR rebased onto
It fails on Patch: operator-authority exit + regression test (on top of this PR rebased onto main)diff --git a/src/gateway/mcp-http.async-scope.test.ts b/src/gateway/mcp-http.async-scope.test.ts
index 1ecc5194980..3e65ea7ac82 100644
--- a/src/gateway/mcp-http.async-scope.test.ts
+++ b/src/gateway/mcp-http.async-scope.test.ts
@@ -18,6 +18,17 @@ import {
tryBeginGatewayRootWorkAdmission,
} from "../process/gateway-work-admission.js";
import { AsyncWorkScope, getAsyncWorkSignal, trackAsyncWork } from "../shared/async-work-scope.js";
+import {
+ activateMcpLoopbackClientGrantCapture,
+ mintMcpLoopbackClientGrant,
+ revokeMcpLoopbackClientGrant,
+} from "./mcp-grant-store.js";
+import { createGatewayMethodRegistry } from "./methods/registry.js";
+import { createDirectChatContext } from "./server-chat.agent-events.test-helpers.js";
+import type { GatewayRequestHandlerOptions } from "./server-methods/types.js";
+import { withOperatorToolGatewayAuthority } from "./server-plugin-in-process-authority.js";
+import { dispatchGatewayMethodInProcessRaw } from "./server-plugin-in-process-dispatch.js";
+import { createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client.js";
const { execute, resolveTools } = vi.hoisted(() => ({ execute: vi.fn(), resolveTools: vi.fn() }));
vi.mock("../config/io.js", () => {
@@ -29,16 +40,13 @@ vi.mock("../agents/agent-tools.before-tool-call.js", () => ({
}));
vi.mock("./tool-resolution.js", () => ({ resolveGatewayScopedTools: resolveTools }));
-import {
- activateMcpLoopbackClientGrantCapture,
- mintMcpLoopbackClientGrant,
-} from "./mcp-grant-store.js";
import { closeMcpLoopbackServer, ensureMcpLoopbackServer } from "./mcp-http.js";
import { getActiveMcpLoopbackRuntime } from "./mcp-http.loopback-runtime.js";
const completed = { content: [{ type: "text", text: "tracked tool completed" }] };
const executionScopes: Array<AbortSignal | undefined> = [];
const constructionScopes: Array<AbortSignal | undefined> = [];
+const admissions: PreparedAgentRunAdmission[] = [];
beforeEach(() => {
executionScopes.length = 0;
@@ -67,8 +75,6 @@ beforeEach(() => {
});
});
-const admissions: PreparedAgentRunAdmission[] = [];
-
afterEach(async () => {
await closeMcpLoopbackServer();
for (const admission of admissions.splice(0)) {
@@ -114,7 +120,136 @@ async function startFromCaller() {
}
}
+async function callBoundTool(token: string, captureKey: string) {
+ const runtime = getActiveMcpLoopbackRuntime();
+ if (!runtime) {
+ throw new Error("MCP runtime missing");
+ }
+ const response = await fetch(`http://127.0.0.1:${runtime.port}/mcp`, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ "x-openclaw-cli-capture-key": captureKey,
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "scope_probe", arguments: {} },
+ }),
+ });
+ return { status: response.status, body: await response.json() };
+}
+
describe("MCP HTTP work ownership", () => {
+ it("uses each admitted CLI run's scope for an admin dispatch after a write-only starter", async () => {
+ const adminDispatch = vi.fn(({ respond }: GatewayRequestHandlerOptions) => {
+ respond(true, { allowed: true });
+ });
+ const registry = createGatewayMethodRegistry([
+ {
+ name: "scope.probe",
+ owner: { kind: "core", area: "scope-proof" },
+ scope: "operator.admin",
+ handler: adminDispatch,
+ },
+ ]);
+ const context = createDirectChatContext({
+ getRuntimeConfig: () => ({}),
+ getGatewayMethodRegistry: () => registry,
+ });
+ const scopeFor = (
+ client: ReturnType<typeof createSyntheticPluginRuntimeClient>,
+ isCurrent: () => boolean,
+ ) => ({
+ client,
+ isWebchatConnect: () => false,
+ resolveGatewayContext: () => context,
+ hasCurrentClientAuthority: isCurrent,
+ });
+ const writeOnly = createSyntheticPluginRuntimeClient({ scopes: ["operator.write"] });
+ const admin = createSyntheticPluginRuntimeClient({ scopes: ["operator.admin"] });
+ let ownerCurrent = true;
+ execute.mockImplementation(async () => {
+ const result = await dispatchGatewayMethodInProcessRaw(
+ "scope.probe",
+ {},
+ {
+ resolveGatewayContext: () => context,
+ },
+ );
+ return {
+ content: [{ type: "text", text: result.ok ? "admin-dispatched" : result.error?.message }],
+ };
+ });
+ await withPluginRuntimeGatewayRequestScope(
+ scopeFor(writeOnly, () => true),
+ () =>
+ withOperatorToolGatewayAuthority({ scopes: ["operator.write"] }, () =>
+ ensureMcpLoopbackServer(),
+ ),
+ );
+ const runtime = getActiveMcpLoopbackRuntime();
+ if (!runtime) {
+ throw new Error("MCP runtime missing");
+ }
+ const admit = async (runId: string, client: typeof admin, isCurrent: () => boolean) => {
+ const admission = prepareAgentRunAdmission({
+ cfg: {},
+ facts: {
+ runId,
+ agentId: "main",
+ ingress: { kind: "system", boundary: "mcp-scope-proof", state: "present" },
+ },
+ operationalRunInstance: createOperationalRunInstanceRef(runId),
+ });
+ admissions.push(admission);
+ const admittedRunContext = await admission.admit("gateway", `gateway-${runId}`);
+ const grant = withPluginRuntimeGatewayRequestScope(scopeFor(client, isCurrent), () =>
+ mintMcpLoopbackClientGrant({
+ context: { sessionKey: "agent:main:scope-proof", senderIsOwner: true },
+ runtimeOwnerToken: runtime.ownerToken,
+ admittedRunContext,
+ }),
+ );
+ const captureKey = `capture-${runId}`;
+ expect(
+ activateMcpLoopbackClientGrantCapture({
+ token: grant.token,
+ runtimeOwnerToken: runtime.ownerToken,
+ captureKey,
+ }),
+ ).toBeTruthy();
+ return { token: grant.token, captureKey };
+ };
+ const ownerGrant = await admit("mcp-owner", admin, () => ownerCurrent);
+ const recoveryGrant = await admit("mcp-recovery", writeOnly, () => true);
+
+ expect(await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).toMatchObject({
+ status: 200,
+ body: { result: { content: [{ text: "admin-dispatched" }], isError: false } },
+ });
+ expect(await callBoundTool(recoveryGrant.token, recoveryGrant.captureKey)).toMatchObject({
+ status: 200,
+ body: { result: { content: [{ text: "missing scope: operator.admin" }], isError: false } },
+ });
+ expect(adminDispatch).toHaveBeenCalledTimes(1);
+
+ ownerCurrent = false;
+ expect(await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).toMatchObject({
+ status: 200,
+ body: {
+ result: {
+ content: [{ text: "Gateway client authority closed before dispatching scope.probe." }],
+ },
+ },
+ });
+ expect(adminDispatch).toHaveBeenCalledTimes(1);
+ expect(revokeMcpLoopbackClientGrant(ownerGrant.token)).toBe(true);
+ expect((await callBoundTool(ownerGrant.token, ownerGrant.captureKey)).status).toBe(401);
+ });
+
it.each([false, true])(
"serves fresh request scopes after its creator closes (replacement=%s)",
async (replace) => {
diff --git a/src/gateway/mcp-http.ts b/src/gateway/mcp-http.ts
index 27cd85a8840..7f9b21d9978 100644
--- a/src/gateway/mcp-http.ts
+++ b/src/gateway/mcp-http.ts
@@ -58,6 +58,7 @@ import {
resolveMcpRequestContext,
validateMcpLoopbackRequest,
} from "./mcp-http.request.js";
+import { runOutsideOperatorToolGatewayAuthority } from "./operator-tool-gateway-authority.js";
// Loopback MCP server exposes gateway-scoped tools to local MCP clients over a
// bearer-token HTTP endpoint bound to 127.0.0.1. Only one active server/runtime
@@ -571,16 +572,18 @@ export async function ensureMcpLoopbackServer(port = 0): Promise<void> {
// restart-recovery run would otherwise cap every later turn's bridge calls.
const work = new AsyncWorkScope();
const resolveGatewayContext = getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
- activeMcpLoopbackServerPromise = withoutGatewayToolCallerIdentity(() =>
- withPluginRuntimeGatewayContextResolver(
- resolveGatewayContext,
- () =>
- runOutsidePluginRuntimeGenerationScope(() =>
- runOutsideGatewayRootWorkAdmission(() =>
- work.run(() => startMcpLoopbackServer(port, work)),
+ activeMcpLoopbackServerPromise = runOutsideOperatorToolGatewayAuthority(() =>
+ withoutGatewayToolCallerIdentity(() =>
+ withPluginRuntimeGatewayContextResolver(
+ resolveGatewayContext,
+ () =>
+ runOutsidePluginRuntimeGenerationScope(() =>
+ runOutsideGatewayRootWorkAdmission(() =>
+ work.run(() => startMcpLoopbackServer(port, work)),
+ ),
),
- ),
- { inheritRequestScope: false },
+ { inheritRequestScope: false },
+ ),
),
)
.then((close) => {The listener also inherits its starter's Cron creator authority store. A runId check stops it from being used today, but it could be exited in the same place. |
|
Another affected deployment, with one more way to trigger it that is easy to hit by accident. Setup: OpenClaw 2026.9.6 (eb377ac), Linux, npm global install, gateway as a systemd user unit, Trigger here: after a gateway restart, the first CLI turn was not a user message but a short-lived
Impact: about one hour (one morning, 08:16–09:12 local) in which the agent produced answers and could not deliver any of them to Telegram. Only a gateway restart cleared it. Two things that may be useful for review:
If it helps to get this merged: we can cherry-pick this branch onto 2026.9.6, replay the exact sequence (fresh start → |
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. This implementation was incorporated into #165432 (fdcbcf5c2ebd). Current main starts the shared MCP listener outside the starter’s request context, restores each grant’s own request scope, and retains Gateway resources. HTTP regressions cover owner access, the write-only ceiling, closed callers, and revoked grants. Thanks @Leit-motif (Amrit Chana) for the fix and proof, and @Grynn for the authority regression. Closing this absorbed branch unmerged. The release-pinned follow-up, separate Cron-management report, and cross-agent authority report in #185303 are outside this closeout. Please reopen with current-main reproduction details if this specific caller-scope leak persists. |
…tomations (#162237) Related: #147614, #157126, #157144 ## What Problem This Solves Fixes: admitted owners using CLI-backed agents cannot see or manage existing ownerless automations because the later MCP request constructs the tool outside the owner's automation-management scope. ## User Impact Authorized owners regain Gateway-wide list/get/update of existing automations through CLI MCP. Removing owner membership or revoking the grant still denies access, and later callers without management authority remain caller-scoped. Ownerless jobs remain ownerless. No configuration or stored-data migration is required. ## Why This Change Was Made Automation tools bind management authority when constructed, before their later execution. The host-only CLI grant now retains the exact live construction scope, and tool resolution enters it under the admitted caller identity and stored request scope. The construction identity deliberately omits execution's requester-grant issuer. Actual execution retains the existing one-use, method-bound grant and final-effect checks. The retained callback rechecks the exact grant row, active run, abort/currentness and current channel-owner membership. Stale scope exits any ambient management scope rather than inheriting it. The implementation builds on current requester-origin and detached-listener ownership; it does not restore superseded listener or ambient-authority code. ## Evidence - **Live Claude CLI proof:** new QA scenario `cron-claude-cli-owner-management` (live-frontier, `claude-cli/claude-sonnet-4-6`, subscription auth). A configured channel owner asks the Claude CLI agent to `get` and then disable an automation owned by another account. On this branch the agent replies with the success marker; the job is disabled and keeps its original owner. With the four source files reverted to `main`, the same live turn fails with `cron job not found: <id> ... For cross-session management, use a fresh authenticated configured channel owner ...`, which is the production report in #186696. - **Production:** on 2026.10.8, a configured channel owner on a `claude-cli` agent got `cron job not found` for a job owned by the same conversation, with no `cron: admin management` log line; the same owner on the embedded runtime is granted management. - **Real boundary regression:** `src/gateway/server-methods/mcp-cron-management.integration.test.ts` drives the actual detached loopback HTTP MCP listener, production tool resolution and isolated durable Cron persistence. On the unchanged owner it fails with `expected 'caller' to be 'gateway'`; with this repair it lists, reads and updates the ownerless job without assigning an owner. - The same scenario then removes the configured owner and observes update refusal; revokes the grant and observes HTTP401; starts a later unentitled run on the same listener and observes caller scope with no access to the job. The only mocked boundary is unrelated attached-node inventory. - **Construction/execution separation:** a real HTTP regression proves the admitted identity cannot mint a requester grant during construction, while execution can mint and redeem its one-use grant. It failed before the construction identity was narrowed and passes afterward. - Final affected command: `OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts src/gateway/server-methods/mcp-cron-management.integration.test.ts src/agents/tools/cron-tool.management.test.ts --maxWorkers=1`: **21/21 pass** (7 HTTP-scope, 1 durable Cron integration, 13 management controls). Wrapper wall **65.13s**, including compiler/bootstrap work; the integrated owner scenario took **6.772s**. These are test costs, not production-latency benchmarks. - Earlier broader affected runs cover **85 distinct tests across the runs**, including grant-store, grant construction, authority and requester-continuation consumers. Core/gateway test types, touched type-aware lint, formatting, scoped line-cap and diff checks pass. - Simplification keeps the existing grant row and Cron authority owner; no second authority registry, wire credential, database schema or permission option is added. Construction and execution share one identity builder with an explicit phase. Necessary patch growth is the retained host callback and separate real authority/revocation regressions. Co-authored-by: Ayaan Zaidi <[email protected]>
…tomations (openclaw#162237) Related: openclaw#147614, openclaw#157126, openclaw#157144 ## What Problem This Solves Fixes: admitted owners using CLI-backed agents cannot see or manage existing ownerless automations because the later MCP request constructs the tool outside the owner's automation-management scope. ## User Impact Authorized owners regain Gateway-wide list/get/update of existing automations through CLI MCP. Removing owner membership or revoking the grant still denies access, and later callers without management authority remain caller-scoped. Ownerless jobs remain ownerless. No configuration or stored-data migration is required. ## Why This Change Was Made Automation tools bind management authority when constructed, before their later execution. The host-only CLI grant now retains the exact live construction scope, and tool resolution enters it under the admitted caller identity and stored request scope. The construction identity deliberately omits execution's requester-grant issuer. Actual execution retains the existing one-use, method-bound grant and final-effect checks. The retained callback rechecks the exact grant row, active run, abort/currentness and current channel-owner membership. Stale scope exits any ambient management scope rather than inheriting it. The implementation builds on current requester-origin and detached-listener ownership; it does not restore superseded listener or ambient-authority code. ## Evidence - **Live Claude CLI proof:** new QA scenario `cron-claude-cli-owner-management` (live-frontier, `claude-cli/claude-sonnet-4-6`, subscription auth). A configured channel owner asks the Claude CLI agent to `get` and then disable an automation owned by another account. On this branch the agent replies with the success marker; the job is disabled and keeps its original owner. With the four source files reverted to `main`, the same live turn fails with `cron job not found: <id> ... For cross-session management, use a fresh authenticated configured channel owner ...`, which is the production report in openclaw#186696. - **Production:** on 2026.10.8, a configured channel owner on a `claude-cli` agent got `cron job not found` for a job owned by the same conversation, with no `cron: admin management` log line; the same owner on the embedded runtime is granted management. - **Real boundary regression:** `src/gateway/server-methods/mcp-cron-management.integration.test.ts` drives the actual detached loopback HTTP MCP listener, production tool resolution and isolated durable Cron persistence. On the unchanged owner it fails with `expected 'caller' to be 'gateway'`; with this repair it lists, reads and updates the ownerless job without assigning an owner. - The same scenario then removes the configured owner and observes update refusal; revokes the grant and observes HTTP401; starts a later unentitled run on the same listener and observes caller scope with no access to the job. The only mocked boundary is unrelated attached-node inventory. - **Construction/execution separation:** a real HTTP regression proves the admitted identity cannot mint a requester grant during construction, while execution can mint and redeem its one-use grant. It failed before the construction identity was narrowed and passes afterward. - Final affected command: `OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts src/gateway/server-methods/mcp-cron-management.integration.test.ts src/agents/tools/cron-tool.management.test.ts --maxWorkers=1`: **21/21 pass** (7 HTTP-scope, 1 durable Cron integration, 13 management controls). Wrapper wall **65.13s**, including compiler/bootstrap work; the integrated owner scenario took **6.772s**. These are test costs, not production-latency benchmarks. - Earlier broader affected runs cover **85 distinct tests across the runs**, including grant-store, grant construction, authority and requester-continuation consumers. Core/gateway test types, touched type-aware lint, formatting, scoped line-cap and diff checks pass. - Simplification keeps the existing grant row and Cron authority owner; no second authority registry, wire credential, database schema or permission option is added. Construction and execution share one identity builder with an explicit phase. Necessary patch growth is the retained host callback and separate real authority/revocation regressions. Co-authored-by: Ayaan Zaidi <[email protected]>
Current disposition — October 11, 2026
The implementation in this PR has been incorporated into main by #165432, commit
fdcbcf5c2ebd83316f411d406315f08225949c59, which credits Amrit Chana and adapts this PR's authority-chain regression. There is no remaining production fix to merge from this branch.Current main uses a detached process context for listener startup, retains the Gateway's worker resources, records each grant's minting request scope, and restores that scope for its tool calls. Its HTTP coverage checks starter isolation, fresh replacement scopes, allowed owner dispatch, the write-only ceiling, closed requester refusal, and revoked-grant rejection.
Fresh verification on main
cbe0b272883c68210aee33b67e4bdf66d9106587:node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.tspassed 6/6 tests on macOS/Node 24.16.0. Vitest reported 221.45 s, including cold transformation. This was HTTP/in-process authority boundary proof, not a new live Claude or channel test. No production or test changes were needed.The v2026.10.1 tag predates the merged detached-context implementation, so the release-pinned follow-up remains relevant to that tag. The original branch's old CI/conflict state is historical; rebasing it would duplicate the implementation and weaker coverage already on main. This PR remains open and non-draft for maintainer disposition; no merge or closure was requested or performed.
Original contributor proposal and historical evidence
Closes #157126
What Problem This Solves
Fixes: after a Gateway restart that resumes an in-flight CLI-runtime turn (for example
claude-cli), the owner's later chat turns fail admin-only tools withmissing scope: operator.adminuntil the Gateway restarts again. The same leak also breaks a second owner turn once the first turn's connection has closed (Gateway client authority closed before dispatching ...).User Impact
User impact: owners of CLI-runtime agents keep their normal tool authority after a restart. Admin-only tools (automations with triggers, secrets, system and config tools) work from chat again. Lower-authority runs keep their own ceiling: the write-only restart-recovery run is still refused admin tools, and a run whose device was revoked mid-turn is still refused before its action. No configuration or migration is required.
Why This Change Was Made
The loopback MCP listener is process-owned but starts lazily inside whichever Gateway request first needs it. Its handlers kept that request's scope and tool-caller identity. So every bridge tool call ran with the authority of whichever run started the listener, not the run making the call. If the restart-recovery continuation (a write-only system caller) started it, every later owner call was capped at
operator.write.The fix has two parts:
withoutGatewayToolCallerIdentity) and outside the request scope (withPluginRuntimeGatewayContextResolver(..., { inheritRequestScope: false })), keeping only the Gateway context resolver. This matches the rule already applied to follow-up and scheduled runs.mintMcpLoopbackClientGrant, called while the run's request is active), and the handler re-enters that scope for the grant's tool calls. That is what in-process runtimes already get implicitly, so dispatch sees the calling run's own client: its scopes stay the ceiling, and itshasCurrentClientAuthorityliveness still applies.Part 1 alone would have removed the accidental ceiling without restoring the intended one. With no scope, a write-only recovery run and a revoked run both completed an admin-only call in live testing. Part 2 is why those runs are still refused (see the proof below).
Evidence
Real behavior proof
Setup. This PR's branch at
3ff6fbe1d78, built, running as an isolated foreground Gateway (openclaw --profile <test> gateway run, loopback, its own state dir, clean environment). macOS arm64, Node v26.8.2, OpenClaw2026.9.6 (3ff6fbe). Agentmainrunsclaude-cli/claude-sonnet-5. Owner turns come fromopenclaw agent --agent mainon a local CLI device paired withoperator.admin(senderIsOwner: true). The admin-only action is thesecretstool withaction: "list"(secrets.store.list, needsoperator.admin). Heartbeat, Bonjour, and dreaming are off, so no other system run can start the bridge first.Steps:
secretslist.secretslist. Mid-probe the Gateway is restarted (gateway restart --wait 5s). The drain runs out, the turn is marked for recovery, and the restart-recovery continuation (a write-only system caller) is the first CLI run after startup, so it starts the bridge. It then callssecretslist itself.secretslist.devices revoke --role operator, connection closed4001 device removed). After the probe, the run callssecretslist.Results are the exact tool results the agent received, from the Claude Code stream in the Gateway log and
chat.history. The "unpatched" column is the same checkout withsrc/gateway/mcp-http.tsreverted to6907f58b136(upstream main) and rebuilt. "Part 1 only" is this PR's first commit,3b3536613b4.The secret store is empty.The secret store is empty.The secret store is empty.Gateway client authority closed before dispatching secrets.store.list.The secret store is empty.The secret store is empty.missing scope: operator.adminThe secret store is empty.missing scope: operator.adminmissing scope: operator.adminThe secret store is empty.The secret store is empty.Gateway client authority closed before dispatching secrets.store.list.The secret store is empty.Gateway client authority closed before dispatching secrets.store.list.On unpatched main, step1 and step3 are refused only because each of those runs happened to start the bridge itself. On this PR they are refused by their own run's scope, whichever run started the listener.
Restart and recovery on this PR (Gateway log, local time, redacted):
secretstool results on this PR, in order (step0, step0b, recovery, step2):The refused call belongs to the recovery turn: in
chat.historyit follows the[System] Your previous turn was interrupted by a gateway restart ...continuation message, and step2's owner turn after it succeeds.step3 on this PR (device revoked mid-run):
Differences from the issue's scenario. Owner turns come from the local CLI (
openclaw agent, a device withoperator.admin), not Control UI webchat. The restart is the supported foreground restart (gateway restart --wait 5s, in-process SIGUSR2 with a 5 s drain), not a LaunchAgent handoff. The admin-only tool issecretslist only.Tests
src/gateway/mcp-http.async-scope.test.ts:[owner, recovery, undefined]). Fails without part 2 ([undefined, undefined, undefined]).pnpm vitest run src/gateway/mcp-http src/gateway/mcp-grant-store src/agents/cli-runner/prepare: 275 of 276 pass. The one failure,mcp-http.keepalive.test.ts› "keeps a GET notification stream alive and releases it during shutdown", fails identically on unmodifiedorigin/mainat6907f58.pnpm check:changed: passes (exit 0).--mode branch --base origin/main --max-priority P2:scoped-clean, "patch is correct" (0.78). Its sandbox could not read unchanged files or run tests; the tests above ran locally.