Skip to content

fix: schedule local continuations with unauthenticated MCP integrations - #160793

Draft
roboclaw-bot wants to merge 2 commits into
mainfrom
openclaw/fix-156379-mcp-continuation-capture
Draft

roboclaw-bot wants to merge 2 commits into
mainfrom
openclaw/fix-156379-mcp-continuation-capture

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #156379

What Problem This Solves

Fixes continuation scheduling being blocked when an unrelated configured MCP integration is not authenticated.

User Impact

Agent-created continuations capture the currently executable, authorized subset and report excluded integrations in warnings. Explicit unavailable or unknown tool selectors fail before saving instead of silently disappearing. Trusted runtime aliases retain their canonical executable identities. Later login does not expand a saved tool ceiling; current permissions and approvals still apply. No configuration, storage schema, or protocol version changes.

Intentional upgrade behavior: older finite lists could silently drop unavailable names. New creates and explicit tool-policy edits reject those names, including named requirements alongside *; remove unavailable selectors or restore access. Existing stored caps are not rewritten.

This authority-sensitive PR remains a draft for owner/security review. Required CI/review gates are not waived; no merge or deployment is requested.

Why This Change Was Made

Use the existing creator-authority snapshot and cap owners. Keep the materializer's policy/approval-filtered tools, carry its exclusions into scheduling results, and replace earlier interactive configured-tool bindings with the fresh scheduled snapshot. Unexpected discovery failures and exact-run grant/lifecycle checks still fail closed. Host-issued shell aliases keep their existing executable identity and lifetime checks when provider normalization wraps them.

Thanks @jalehman for the report and the requested bounded-subset behavior.

Work sessions

Evidence

  • Verified real-Gateway proof and inline reproducibility artifact. Baseline fb503c9e1f25d8c3877881e55e83d4378eda3676 rejects local continuation creation for unrelated OAuth. Exact head 685ddfc5f86d242c115c96b988975421ad962d2c passes all 16 cases: bounded save + warning, real shell/file effects, finite aliases, unknown/required selectors, healthy MCP, read-only caller, creator revocation, and unchanged saved ceilings after OAuth plus fresh discovery. Both snapshots use isolated built Gateways and managed Codex 0.158.0. Model/MCP peers are synthetic; Gateway, auth, storage, dispatch and effects are real.
  • 341 targeted and sibling tests pass across 13 files (137 feature-focused tests plus 204 normalizer/host/plugin-lifetime controls). Core and extension production types, relevant agent/plugin/extension test types, changed-file lint/formatting, line-growth and assertion-safety ratchets, and diff checks pass. The current environment budget passes 476/476, without a budget edit in this PR.
  • Full exact-head candidate build passed in Crabbox. Fresh independent autoreview found no actionable P0–P2 findings. Current PR is draft; openclaw/ci-gate is skipped, not asserted green. Owner/security review remains before merge.

Proof limit: post-login ceiling checks explicitly restart only the owned Gateway to force fresh authenticated discovery and verify persistence. This does not claim immediate warm-cache invalidation or live-vendor inference. The saved job’s attempted excluded MCP call is verified against the native unsupported-call response and zero peer tool calls, with a successful authenticated new-job control.

Measured test cost and implementation scope

Canonical node scripts/run-vitest.mjs run <file> --maxWorkers=1, measured on the final head; wall time includes runner/cache/import overhead. CI seconds are unavailable while the PR is draft.

Changed test file Tests Wall seconds
cron-tool-creator-cap.test.ts 17 1.80
cron-tool.test.ts 71 13.16
cron-tool.authority-exclusions.test.ts 8 24.19
cron-tool.output-contract.test.ts 7 28.09
cron-creator-authority-context.test.ts 12 13.32
run-attempt.configured-mcp-authority.test.ts 9 42.16
tools.scheduled-projection.test.ts 7 11.68

The attempt-level tests exercise the actual capture composition and stale-binding replacement; the alias suite exercises real normalization and plugin admission, including nested/retired views and replaced executors. Pure name-matching tests would miss those boundaries. Upstream test pruning was preserved during conflict resolution.

Against rebase base d4be6500114cff6fcbf72f323fc520861a06c6c9: production +150/-40 (net +110); tests +422/-50 (net +372); docs +16. Growth is the returned exclusions, explicit selector validation, fresh finite-MCP capture and admission-preserving alias metadata transfer. The blanket diagnostic rejection, stale interactive-MCP union and duplicate output-schema shape are removed. Existing cap/grant/lifecycle owners remain authoritative; no storage/config/protocol change or budget increase.


View the OpenClaw team session

@clawsweeper

clawsweeper Bot commented Sep 28, 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 agents Agent runtime and tooling extensions: codex size: M labels Sep 28, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 10:06 PM ET / September 29, 2026, 02:06 UTC (Revision 4).

ClawSweeper review

What this changes

The branch lets Codex-backed agents schedule continuations with available authorized tools, reports excluded MCP integrations, validates requested tool names, and preserves executable shell aliases.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep open. Current main still blocks inherited scheduling when unrelated MCP authentication is missing, and the pinned real-Gateway proof supports the proposed repair. The branch also makes mixed finite tool requests fail where the latest release saves their available intersection; no owner acceptance of that upgrade change is recorded.

Priority: P2
Reviewed head: 685ddfc5f86d242c115c96b988975421ad962d2c
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-boundary proof supports the core fix, while an unresolved shipped-behavior break limits merge readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The exact-head terminal trace exercises the production Gateway, managed Codex adapter, automation save, and scheduled shell/file effects with unrelated MCP OAuth unavailable; it records a saved bounded cap, warnings, denied unauthorized and revoked callers, and no old-job MCP call after login. Synthetic inference and MCP peers bound the scenario. Stored cap shape is unchanged, so data-model migration is not applicable.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The exact-head terminal trace exercises the production Gateway, managed Codex adapter, automation save, and scheduled shell/file effects with unrelated MCP OAuth unavailable; it records a saved bounded cap, warnings, denied unauthorized and revoked callers, and no old-job MCP call after login. Synthetic inference and MCP peers bound the scenario. Stored cap shape is unchanged, so data-model migration is not applicable.
Evidence reviewed 10 items Introduced finite-list rejection: The pinned PR head throws before saving when any explicitly requested selector is unavailable, including a named selector beside a wildcard.
Current-main behavior: Current main still intersects a finite request with available creator tools and retains the separate rejection of incomplete configured-MCP discovery.
Unfixed central bug on main: The current-main Codex integration throws when configured MCP materialization returns an authentication diagnostic.
Findings 1 actionable finding [P1] Preserve shipped finite-list scheduling compatibility
Security None None.

How this fits together

An agent asks OpenClaw to save a future continuation using tools discovered through its Codex runtime and configured MCP integrations. OpenClaw captures a tool ceiling at creation, then the Gateway applies that ceiling and current authority when the job runs.

flowchart LR
A[Agent requests continuation] --> B[Codex tool discovery]
B --> C[Creator authority snapshot]
C --> D[Requested tool validation]
D --> E[Saved job tool ceiling]
E --> F[Scheduled run authority checks]
C --> G[Excluded integration warnings]
Loading

Decision needed

Question Recommendation
Should agent-created continuations use bounded partial MCP capture while retaining the shipped finite-list intersection, or should mixed explicit lists become atomic failures? Preserve finite-list compatibility: Approve bounded partial capture, save the available finite intersection, and warn about omitted requested tools.

Why: The branch changes an intentional capture policy and a shipped create/edit behavior, so proof of correct execution cannot authorize the upgrade semantics.

Before merge

  • Preserve shipped finite-list scheduling compatibility (P1) - In v2026.9.6, a request such as toolsAllow: ["read", "temporarily_unavailable"] saves the available read cap. This new throw rejects the entire add or explicit tool edit, so an existing request can stop working after upgrade when one integration is unavailable. This finding remains from the prior review of the same head. Preserve the shipped default with a warning, or obtain explicit owner acceptance and fresh-create and upgrade-recovery proof for atomic rejection.
  • Resolve merge risk (P1) - Existing create or explicit tool-edit requests with a mixed finite list can fail entirely after upgrade where v2026.9.6 saved the available subset.
  • Resolve merge risk (P1) - The policy choice to save a durable partial MCP authority snapshot still needs owner review; the positive real-Gateway controls do not themselves record product or security-boundary acceptance.
  • Complete next step (P2) - Resolve the shipped finite-list compatibility finding and obtain owner review of the partial-authority scheduling policy before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Preserve shipped finite-list scheduling compatibility — src/agents/tools/cron-tool-creator-cap.ts:327-332
Agent review details

Security

None.

PR surface

Source +110, Tests +372, Docs +16. Total +498 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 11 150 40 +110
Tests 7 422 50 +372
Docs 1 16 0 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 588 90 +498

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #156379
Summary: This PR is the candidate repair for the reported inherited-scheduling failure; the finite-request scope issue is related but distinct.

Members:

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

Merge-risk options

Maintainer options:

  1. Keep the shipped finite default (recommended)
    Save the available intersection and report omitted selectors without blocking existing mixed-list requests.
  2. Own atomic rejection
    Approve the new failure mode only with an explicit upgrade decision and proof of recovery for existing requests.
  3. Pause authority-policy change
    Leave the draft open while the owner decides whether partial capture should replace the current complete-capture rule.

Technical review

Best possible solution:

Capture the authorized executable subset with visible exclusions while preserving finite-list intersection as the default; offer atomic required-tool rejection only through an explicitly approved opt-in contract.

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

Yes. A pinned real-Gateway baseline reproduced the MCP-authentication rejection, and current main retains the same throw; this reviewer did not run the current-main path.

Is this the best way to solve the issue?

Partly. The bounded-subset capture addresses the reported failure at the existing authority owner, but atomic rejection of mixed finite lists is an avoidable shipped-behavior break without owner acceptance.

Full review comments:

  • [P1] Preserve shipped finite-list scheduling compatibility — src/agents/tools/cron-tool-creator-cap.ts:327-332
    In v2026.9.6, a request such as toolsAllow: ["read", "temporarily_unavailable"] saves the available read cap. This new throw rejects the entire add or explicit tool edit, so an existing request can stop working after upgrade when one integration is unavailable. This finding remains from the prior review of the same head. Preserve the shipped default with a warning, or obtain explicit owner acceptance and fresh-create and upgrade-recovery proof for atomic rejection.
    Confidence: 0.95

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 6b3033b65ca9.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The repair addresses a real scheduling failure with a bounded affected workflow, while an upgrade-policy choice remains.
  • merge-risk: 🚨 compatibility: The PR changes shipped finite-list create and edit behavior from saving an available subset to rejecting the request.
  • merge-risk: 🚨 security-boundary: The PR changes how creator authority becomes a durable scheduled tool ceiling, requiring owner acceptance of partial capture.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The exact-head terminal trace exercises the production Gateway, managed Codex adapter, automation save, and scheduled shell/file effects with unrelated MCP OAuth unavailable; it records a saved bounded cap, warnings, denied unauthorized and revoked callers, and no old-job MCP call after login. Synthetic inference and MCP peers bound the scenario. Stored cap shape is unchanged, so data-model migration is not applicable.
  • proof: sufficient: Contributor real behavior proof is sufficient. The exact-head terminal trace exercises the production Gateway, managed Codex adapter, automation save, and scheduled shell/file effects with unrelated MCP OAuth unavailable; it records a saved bounded cap, warnings, denied unauthorized and revoked callers, and no old-job MCP call after login. Synthetic inference and MCP peers bound the scenario. Stored cap shape is unchanged, so data-model migration is not applicable.

Evidence

What I checked:

Likely related people:

  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • jalehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Resolve the finite-list compatibility choice with the scheduling owner.
  • If atomic rejection is approved, demonstrate fresh creation and upgrade recovery for an existing mixed finite request.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-28T23:40:16.581Z sha 51e6f31 :: needs real behavior proof before merge. :: [P1] Preserve the shipped finite-list scheduling contract
  • reviewed 2026-09-29T00:40:48.481Z sha 8f100e742aa191ea42b49d1dc48ea75fbcf49e01 :: needs real behavior proof before merge. :: [P1] Preserve the shipped finite-list scheduling contract
  • reviewed 2026-09-29T01:44:43.074Z sha 685ddfc :: blocked before merge. :: [P1] Preserve shipped finite-list scheduling compatibility

@roboclaw-bot

roboclaw-bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Real Gateway before/after proof

Verified candidate: 685ddfc5f86d242c115c96b988975421ad962d2c (tree 669c1027a4e95e6bc1daf18263c5eb9c999d2a39).
Baseline: fb503c9e1f25d8c3877881e55e83d4378eda3676.

Scenario Observed result
Baseline inherited/local continuation with unrelated MCP OAuth unavailable OAuth-specific rejection; requested job absent. Finite shell aliases were saved literally.
Candidate, same unavailable integration Saved a finite 43-tool authorized cap, returned exclusions in warnings, and executed real shell write + file read.
Required unavailable integration, unknown name, and wildcard plus required name Targeted refusal before saving. Trusted aliases persisted as exec/process/read.
Caller/current-authority controls Signed read-only operator denied with missing scope: operator.admin; creator aborted while actual discovery was held could not save a job.
Later OAuth and fresh discovery Real CLI OAuth/PKCE exchange; owned Gateway restarted to force fresh discovery. Stored cap stayed identical and local work still ran. New authorized job called the MCP peer once; old saved job returned unsupported call: unrelated_oauth__ping and made zero MCP tool calls.
Interactive tool becomes unavailable before scheduled capture Fresh required-tool capture rejected it; no job saved. Healthy MCP sibling remained usable.

All 16 candidate cases passed. The Gateway, managed Codex 0.158.0, signed-device authentication, SQLite jobs/history, tool dispatch, shell/file effects, and MCP HTTP/OAuth transport were real. Inference and the local MCP/OAuth peers were deterministic synthetic fixtures, not a mock Gateway or direct-helper substitute. No production MCP login/config or operator Gateway was changed.

  • Baseline Crabbox/Testbox run: baseline-v2-5, expected-failure assertions exit 0.
  • Candidate Crabbox/Testbox run: candidate-v2-final, exit 0; exact clean candidate built with pnpm install --frozen-lockfile && pnpm build (build stage 338s; real-Gateway matrix 31s).
  • Recorded commands: node .openclaw/tmp/mcp-proof/v2-launch.mjs baseline 5; node .openclaw/tmp/mcp-proof/v2-launch.mjs prepare (combined final-head build and matrix). Both owned leases are released. Lease-carrier Actions status can reflect cleanup; the wrapper’s settled exit and assertions are the proof receipt.
  • Candidate report SHA-256: cdb2d43d71b155cf9a0daa0ade50b1645c452140f0f8becb8e5c5dfef313af46.

Limits: this does not claim live-vendor inference or immediate warm MCP-cache invalidation after login. A prior observation retained the existing OAuth startup backoff; the final ceiling control deliberately uses a new Gateway process and fresh discovery. The native mirror labels the unsupported-call result isError:false; denial is established by the exact returned text plus zero external calls, against a successful authenticated positive control—not by that mirror flag. Earlier fixture namespace/history mistakes were corrected using the registered openclaw_direct.exec and cron.history contracts; file-effect assertions were never relaxed. The exact rebased head was freshly built and rerun after resolving upstream test conflicts; this is not reuse of a pre-rebase receipt.

Inspected result artifact
{
  "sourceSha": "685ddfc5f86d242c115c96b988975421ad962d2c",
  "sourceTree": "669c1027a4e95e6bc1daf18263c5eb9c999d2a39",
  "cases": 16,
  "result": "PASS",
  "capUnchanged": true,
  "savedCapSize": 43,
  "authenticatedNewJobCalls": 1,
  "excludedOldJobCalls": 0,
  "nativeDenial": "unsupported call: unrelated_oauth__ping",
  "nativeMirrorIsError": false,
  "gatewayRestartAfterLogin": true,
  "revocationDenied": true,
  "readOnlyDenied": true
}
Inline reproducibility artifact (sanitized; no bearer download URL)

Reproduction harness

Deterministic synthetic inference uses the repository’s Responses WebSocket adapter. Gateway, managed Codex, signed-device auth, tool dispatch, MCP HTTP/OAuth exchange, SQLite jobs/history and scheduled shell/file execution are real. All token values in this fixture are public synthetic values; no production configuration or credentials are used.

The tested model identifier is parameterized as PROOF_MODEL in this public copy. Choose a model whose actual Codex catalog enables the native tool surface needed by the shell-alias controls; this is not a claim that every model supports that surface. The scheduled date is in the future of the recorded September 29 run; choose a future date when reproducing later.

Pins: baseline fb503c9e1f25d8c3877881e55e83d4378eda3676; candidate 685ddfc5f86d242c115c96b988975421ad962d2c; candidate tree 669c1027a4e95e6bc1daf18263c5eb9c999d2a39. Candidate rebased onto d4be6500114cff6fcbf72f323fc520861a06c6c9 without changing the production feature patch.

Save the seven files under .openclaw/tmp/mcp-proof/. Write the candidate SHA/tree to candidate-head.txt/candidate-tree.txt, and create empty candidate.patch (unused legacy input) and lease-id.txt. Set PROOF_MODEL; the public launcher forwards it to the isolated process. Preserve the configured Crabbox provider.

node .openclaw/tmp/mcp-proof/v2-launch.mjs prepare allocates one retained lease, independently clones/builds the exact candidate, and automatically runs the candidate final matrix. Record the emitted lease ID in lease-id.txt. To reproduce baseline in that owned lease, independently clone/pin/build baseline at /tmp/openclaw-mcp-proof-d69308f5/baseline, then run node .openclaw/tmp/mcp-proof/v2-launch.mjs baseline baseline-proof. Keep one active command; never sync/reclaim during a run. Release the lease with node scripts/crabbox-wrapper.mjs stop <lease-id> after collecting evidence.

Scheduled shell calls use the registered openclaw_direct.exec namespace; retained run transcripts use cron.history. After real CLI OAuth login the harness restarts only its owned Gateway, reconnects the same signed operator identity and asserts that the process instance changed. This forces fresh authenticated discovery and exercises persistence of the saved ceiling. Immediate warm-cache invalidation is not claimed.

The runner asserts exact HEAD/tree and clean tracked bytes. Baseline PASS means the expected regression was reproduced, not that baseline behavior is correct. Candidate PASS requires every positive, forbidden, revocation, alias, fresh-capture and later-authentication assertion, including the exact native unsupported-call response and zero external MCP calls for the old saved job.

write-config.mjs

import fs from 'node:fs';
const out=process.env.PROOF_OUT;
const model=process.env.PROOF_MODEL;
if(!model?.startsWith('openai/'))throw Error('Set PROOF_MODEL to a native-tool-surface-capable model supported by the pinned runtime.');
const cfg={gateway:{mode:'local',port:19742,bind:'loopback',auth:{mode:'token',token:'mcp-proof-fixture-token'},controlUi:{enabled:false}},plugins:{enabled:true,allow:['codex'],entries:{codex:{enabled:true,config:{codexDynamicToolsLoading:'direct',appServer:{mode:'yolo',args:['app-server','--listen','stdio://','-c','openai_base_url="http://127.0.0.1:19741/v1"','-c','features.responses_websockets=false','-c','features.responses_websockets_v2=false'],requestTimeoutMs:60000}}}}},agents:{defaults:{model:{primary:model,fallbacks:[]},models:{[model]:{agentRuntime:{id:'codex'}}},workspace:out+'/workspace',skipBootstrap:true,timeoutSeconds:120,sandbox:{mode:'off'}},entries:{main:{default:true,workspace:out+'/workspace'}}},skills:{allowBundled:[]},tools:{codeMode:false,allow:['automations','read','create_goal','bundle-mcp']},mcp:{servers:{healthy:{url:'http://127.0.0.1:19741/mcp/healthy',transport:'streamable-http',enabled:true},unrelated_oauth:{url:'http://127.0.0.1:19741/mcp/blocked',transport:'streamable-http',enabled:true,auth:'oauth',connectionTimeoutMs:5000,requestTimeoutMs:5000}}}};
fs.mkdirSync(out+'/workspace',{recursive:true});fs.mkdirSync(out+'/home',{recursive:true});fs.mkdirSync(out+'/state',{recursive:true});fs.writeFileSync(out+'/config.json',JSON.stringify(cfg,null,2));

v2-config.mjs

import fs from 'node:fs';
await import('./write-config.mjs');
const out=process.env.PROOF_OUT;const cfg=JSON.parse(fs.readFileSync(out+'/config.json'));
// An explicit finite global policy intentionally disables native tools and their aliases.
// This owned operator fixture uses the full profile; each saved job still receives its finite captured ceiling.
cfg.tools={profile:'full',codeMode:false,exec:{host:'auto',mode:'full'}};
cfg.agents.defaults.heartbeat={every:'0m'};cfg.agents.defaults.timeoutSeconds=120;
cfg.mcp.servers.unrelated_oauth.oauth={redirectUrl:'http://127.0.0.1:19743/oauth/callback'};
fs.writeFileSync(out+'/config.json',JSON.stringify(cfg,null,2));

v2-peer.mjs

// Synthetic inference and MCP/OAuth peers; Gateway, Codex and all storage/dispatch are real.
import http from 'node:http';
import fs from 'node:fs';
import {randomUUID,createHash} from 'node:crypto';
import {zstdDecompressSync,gunzipSync} from 'node:zlib';
import {pathToFileURL} from 'node:url';
const out=process.env.PROOF_OUT, source=process.env.PROOF_SOURCE, origin='http://127.0.0.1:19741';
const log=(kind,data={})=>fs.appendFileSync(out+'/peer.jsonl',JSON.stringify({kind,at:new Date().toISOString(),...data})+'\n');
const json=(res,status,body,headers={})=>{res.writeHead(status,{'content-type':'application/json',...headers});res.end(JSON.stringify(body));};
const plans=new Map(), codes=new Map(); let activeTag;
function dispatch(body){
 const tag=activeTag, plan=plans.get(tag); if(!plan)throw new Error('No authorized proof scenario');
 const outputs=(body.input||[]).filter(x=>x.type==='function_call_output'||x.type==='custom_tool_call_output');
 for(const item of outputs)if(item.call_id?.startsWith('call_'+tag+'_'))plan.completed.add(item.call_id);
 const index=plan.completed.size, selected=plan.calls[index];
 if(selected?.name==='automations'&&(plan.holdCapture||plan.rejectCapture))plan.captureIssued=true;
 const specs=(body.tools||[]).flatMap(t=>t.type==='namespace'?(t.tools||[]).map(s=>({...s,namespace:t.name})):[t]);
 log('inference',{tag,index,transport:body.type==='response.create'?'websocket':'http',tools:specs.map(x=>x.name||x.function?.name),outputs:outputs.map(x=>({callId:x.call_id,output:x.output}))});
 const id='resp_'+randomUUID(), created_at=Math.floor(Date.now()/1000);
 const spec=specs.find(x=>(x.name||x.function?.name)===selected?.name);
 const item=selected?{type:'function_call',id:'fc_'+randomUUID(),call_id:'call_'+tag+'_'+index,name:selected.name,...((selected.namespace||spec?.namespace)?{namespace:selected.namespace||spec.namespace}:{}),arguments:JSON.stringify(selected.args)}:{type:'message',id:'msg_'+randomUUID(),role:'assistant',status:'completed',phase:'final_answer',content:[{type:'output_text',text:'PROOF_FINISHED_'+tag,annotations:[]}]};
 const events=[{type:'response.created',response:{id,object:'response',created_at,model:body.model,status:'in_progress',output:[]}},{type:'response.output_item.added',output_index:0,item:{...item,...(selected?{arguments:''}:{status:'in_progress',content:[]})}}];
 if(selected)events.push({type:'response.function_call_arguments.delta',item_id:item.id,output_index:0,delta:item.arguments});
 else events.push({type:'response.output_text.delta',item_id:item.id,output_index:0,content_index:0,delta:item.content[0].text},{type:'response.output_text.done',item_id:item.id,output_index:0,content_index:0,text:item.content[0].text});
 events.push({type:'response.output_item.done',output_index:0,item},{type:'response.completed',response:{id,object:'response',created_at,model:body.model,status:'completed',output:[item],usage:{input_tokens:100,output_tokens:30,total_tokens:130,input_tokens_details:{cached_tokens:0},output_tokens_details:{reasoning_tokens:0}}}});
 return {events,model:body.model};
}
const server=http.createServer(async(req,res)=>{
 try{
  const url=new URL(req.url,origin);const chunks=[];for await(const c of req)chunks.push(c);let bytes=Buffer.concat(chunks);
  if(req.headers['content-encoding']==='zstd')bytes=zstdDecompressSync(bytes);if(req.headers['content-encoding']==='gzip')bytes=gunzipSync(bytes);
  const raw=bytes.toString();let body;try{body=JSON.parse(raw)}catch{body={};}
  if(url.pathname==='/control'&&req.method==='POST'){activeTag=body.tag;plans.set(body.tag,{calls:body.calls,completed:new Set(),holdCapture:body.holdCapture===true,rejectCapture:body.rejectCapture===true,held:0,releases:[]});return json(res,200,{ok:true});}
  if(url.pathname==='/health')return json(res,200,{ok:true});
  if(url.pathname==='/probe')return json(res,200,{tag:activeTag,held:plans.get(activeTag)?.held||0});
  if(url.pathname==='/release'){const plan=plans.get(activeTag);if(plan){plan.released=true;for(const release of plan.releases)release();}return json(res,200,{ok:true});}
  if(url.pathname.startsWith('/mcp/')){
   const authorized=req.headers.authorization==='Bearer synthetic-mcp-proof-access';
   log('mcp',{path:url.pathname,rpc:body.method,tool:body.params?.name,clientInfo:body.params?.clientInfo,authorized,tag:activeTag});
   const plan=plans.get(activeTag);if(url.pathname==='/mcp/healthy'&&body.method==='tools/list'&&plan?.holdCapture&&plan.captureIssued&&!plan.released){plan.held++;log('capture_held',{tag:activeTag});await new Promise(resolve=>plan.releases.push(resolve));}
   if((url.pathname==='/mcp/blocked'&&!authorized)||(url.pathname==='/mcp/healthy'&&plan?.rejectCapture&&plan.captureIssued))return json(res,401,{error:'OAuth required'},{'WWW-Authenticate':'Bearer resource_metadata="'+origin+'/.well-known/oauth-protected-resource"'});
   if(req.method==='DELETE')return json(res,200,{});if(req.method==='GET'){res.writeHead(405);res.end();return;}if(body.id===undefined){res.writeHead(202);res.end();return;}
   let result={};if(body.method==='initialize')result={protocolVersion:'2025-03-26',capabilities:{tools:{}},serverInfo:{name:url.pathname.endsWith('healthy')?'healthy-proof':'oauth-proof',version:'1.0.0'}};
   if(body.method==='tools/list')result={tools:[{name:'ping',description:'Harmless protocol proof ping',inputSchema:{type:'object',properties:{}},annotations:{readOnlyHint:true}}]};
   if(body.method==='tools/call')result={content:[{type:'text',text:'MCP_PONG_'+(authorized?'AUTHORIZED':'HEALTHY')}]};
   return json(res,200,{jsonrpc:'2.0',id:body.id,result});
  }
  if(url.pathname.startsWith('/.well-known/oauth-protected-resource'))return json(res,200,{resource:origin+'/mcp/blocked',authorization_servers:[origin]});
  if(url.pathname.startsWith('/.well-known/'))return json(res,200,{issuer:origin,authorization_endpoint:origin+'/authorize',token_endpoint:origin+'/token',registration_endpoint:origin+'/register',response_types_supported:['code'],grant_types_supported:['authorization_code'],token_endpoint_auth_methods_supported:['none'],code_challenge_methods_supported:['S256']});
  if(url.pathname==='/register')return json(res,201,{...body,client_id:'synthetic-proof-client',token_endpoint_auth_method:'none'});
  if(url.pathname==='/authorize'){
   const code=randomUUID(), redirect=new URL(url.searchParams.get('redirect_uri'));
   if(redirect.hostname!=='127.0.0.1'||redirect.port!=='19743')return json(res,400,{error:'unexpected redirect'});
   codes.set(code,{challenge:url.searchParams.get('code_challenge'),redirect:redirect.href});redirect.searchParams.set('code',code);redirect.searchParams.set('state',url.searchParams.get('state'));
   log('oauth_authorized');res.writeHead(302,{location:redirect.href});res.end();return;
  }
  if(url.pathname==='/token'){
   const params=new URLSearchParams(raw), saved=codes.get(params.get('code'));const valid=saved&&saved.redirect===params.get('redirect_uri')&&saved.challenge===createHash('sha256').update(params.get('code_verifier')||'').digest('base64url');
   log('oauth_exchange',{valid:Boolean(valid)});if(!valid)return json(res,400,{error:'invalid_grant'});codes.delete(params.get('code'));
   return json(res,200,{access_token:'synthetic-mcp-proof-access',token_type:'Bearer',expires_in:3600});
  }
  if(url.pathname.endsWith('/models'))return json(res,200,{object:'list',data:[{id:process.env.PROOF_MODEL.split('/').slice(1).join('/'),object:'model'}]});
  if(url.pathname==='/v1/responses'&&req.method==='POST'){
   const {events}=dispatch(body);if(body.stream===false)return json(res,200,events.at(-1).response);
   res.writeHead(200,{'content-type':'text/event-stream'});for(const event of events)res.write('data: '+JSON.stringify(event)+'\n\n');res.end();return;
  }
  return json(res,404,{error:'unhandled synthetic route'});
 }catch(error){log('fixture_error',{message:String(error)});return json(res,500,{error:'fixture error'});}
});
const {attachQaMockResponsesWebSocketServer}=await import(pathToFileURL(source+'/extensions/qa-lab/src/providers/mock-openai/mock-openai-responses-websocket.ts'));
attachQaMockResponsesWebSocketServer({server,dispatch:async({body})=>dispatch(body)});
server.listen(19741,'127.0.0.1',()=>console.log('SYNTHETIC_PEER_READY'));

v2-client.mjs

import fs from 'node:fs';
import {randomUUID,generateKeyPairSync,createHash,sign} from 'node:crypto';
import {spawn} from 'node:child_process';
import {setTimeout as sleep} from 'node:timers/promises';
import {pathToFileURL} from 'node:url';
import assert from 'node:assert/strict';
const source=process.env.PROOF_SOURCE,out=process.env.PROOF_OUT,expected=process.env.PROOF_EXPECT;
const {createGatewayWsClient}=await import(pathToFileURL(source+'/scripts/lib/gateway-ws-client.ts'));
const {PROTOCOL_VERSION}=await import(pathToFileURL(source+'/packages/gateway-protocol/src/version.ts'));
const {buildDeviceAuthPayloadV3}=await import(pathToFileURL(source+'/packages/gateway-client/src/device-auth.ts'));
const pair=generateKeyPairSync('ed25519'),publicKey=pair.publicKey.export({format:'der',type:'spki'}).subarray(-32).toString('base64url'),deviceId=createHash('sha256').update(Buffer.from(publicKey,'base64url')).digest('hex');
let challengeResolve,challenge,c;
const events=[];
function createClient(){challenge=new Promise(r=>challengeResolve=r);c=createGatewayWsClient({url:'ws://127.0.0.1:19742',onEvent:e=>{if(e.event==='connect.challenge')challengeResolve(e.payload.nonce);events.push(e);fs.appendFileSync(out+'/gateway-events.jsonl',JSON.stringify(e)+'\n');}});}

const save=(name,value)=>fs.writeFileSync(out+'/'+name+'.json',JSON.stringify(value,null,2));
const report={expected,cases:[],sourceSha:process.env.PROOF_SHA,sourceTree:process.env.PROOF_TREE,baseline:'fb503c9e1f25d8c3877881e55e83d4378eda3676',syntheticPeers:true};
const request=async(method,params)=>{const r=await c.request(method,params,180000);fs.appendFileSync(out+'/rpc.jsonl',JSON.stringify({method,response:r})+'\n');if(!r.ok)throw new Error(method+': '+JSON.stringify(r));return Object.hasOwn(r,'payload')?r.payload:r.result;};
const control=async(tag,calls,extra={})=>{const r=await fetch('http://127.0.0.1:19741/control',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({tag,calls,...extra})});assert(r.ok);};
const toolResults=h=>(h.messages||[]).filter(m=>m.role==='toolResult');
const resultText=h=>toolResults(h).map(m=>JSON.stringify(m.content)).join('\n');
async function turn(tag,calls,extra={}){
 await control(tag,calls,extra);const sessionKey='agent:main:mcp-v2-'+tag+'-'+randomUUID();const runId=randomUUID();
 const sent=await request('chat.send',{sessionKey,idempotencyKey:runId,message:'Authorized isolated regression proof '+tag+': perform the exact harmless scheduling/tool operation requested by the operator; keep configured permission ceilings. No unrelated integration is required.'});
 const done=await request('agent.wait',{runId:sent.runId||runId,timeoutMs:160000});
 const history=await request('chat.history',{sessionKey,limit:80});save(tag+'-history',history);save(tag+'-wait',done);
 const text=JSON.stringify(history);assert(text.includes('PROOF_FINISHED_'+tag),'Native model final missing: '+tag);
 report.cases.push({tag,runId:sent.runId||runId,toolResults:toolResults(history).length});return history;
}
const job=(name,toolsAllow,message)=>({name,declarationKey:'proof-'+name,schedule:{kind:'at',at:'2026-10-28T12:00:00.000Z'},sessionTarget:'isolated',payload:{kind:'agentTurn',message:message||'Perform harmless local shell and file work.',...(toolsAllow?{toolsAllow}:{})},delivery:{mode:'none'},enabled:false,deleteAfterRun:false});
const addCall=j=>({name:'automations',args:{action:'add',job:j}});
async function jobs(){return (await request('cron.list',{includeDisabled:true,limit:100})).jobs;}
async function runJob(tag,savedJob,calls){
 await control(tag,calls);const queued=await request('cron.run',{id:savedJob.id,mode:'force'});save(tag+'-enqueue',queued);assert(queued.runId,'scheduled runId missing');
 const started=Date.now();let entry;
 while(Date.now()-started<160000){const page=await request('cron.runs',{id:savedJob.id,runId:queued.runId,limit:1});entry=page.entries?.[0];if(['ok','error','skipped'].includes(entry?.status))break;await sleep(500);}
 assert(entry&&['ok','error','skipped'].includes(entry.status),'No terminal run history: '+tag);save(tag+'-run',entry);
 const history=await request('cron.history',{id:savedJob.id,runId:queued.runId,limit:80});save(tag+'-history',history);
 report.cases.push({tag,runId:queued.runId,status:entry.status,toolResults:toolResults(history).length});return {entry,history,queued};
}
async function readOnlyCaller(){
 const keys=generateKeyPairSync('ed25519'),pub=keys.publicKey.export({format:'der',type:'spki'}).subarray(-32).toString('base64url'),id=createHash('sha256').update(Buffer.from(pub,'base64url')).digest('hex');
 let ready;const noncePromise=new Promise(r=>ready=r);
 const reader=createGatewayWsClient({url:'ws://127.0.0.1:19742',onEvent:e=>{if(e.event==='connect.challenge')ready(e.payload.nonce);}});
 try{
  await reader.waitOpen();const nonce=await noncePromise,signedAtMs=Date.now(),scopes=['operator.read'];
  const signed=buildDeviceAuthPayloadV3({deviceId:id,clientId:'openclaw-tui',clientMode:'ui',role:'operator',scopes,signedAtMs,token:'mcp-proof-fixture-token',nonce,platform:process.platform});
  const connected=await reader.request('connect',{minProtocol:PROTOCOL_VERSION,maxProtocol:PROTOCOL_VERSION,client:{id:'openclaw-tui',version:'1',platform:process.platform,mode:'ui'},role:'operator',scopes,device:{id,publicKey:pub,signature:sign(null,Buffer.from(signed),keys.privateKey).toString('base64url'),signedAt:signedAtMs,nonce},caps:[],auth:{token:'mcp-proof-fixture-token'}},30000);
  assert(connected.ok,'Read-only client was not admitted for the scope control');
  const denied=await reader.request('cron.add',job('read-only-forbidden'),30000);save('read-only-denial',denied);assert.equal(denied.ok,false,'Read-only caller unexpectedly created automation');assert.match(JSON.stringify(denied.error),/scope|unauthorized|permission|forbidden/i);
  assert(!(await jobs()).some(j=>j.name==='read-only-forbidden'));report.readOnlyCallerDenied=true;report.cases.push({tag:'read_only_caller',saved:false});
 }finally{reader.close();}
}
async function revokeCreator(){
 const tag='revoked_creator',sessionKey='agent:main:mcp-v2-revoke-'+randomUUID(),runId=randomUUID();
 await control(tag,[addCall(job('revoked-before-save'))],{holdCapture:true});
 const sent=await request('chat.send',{sessionKey,idempotencyKey:runId,message:'Create the authorized local-only continuation for the revocation boundary proof.'});
 const start=Date.now();let held;
 while(Date.now()-start<30000){held=await (await fetch('http://127.0.0.1:19741/probe')).json();if(held.tag===tag&&held.held>0)break;await sleep(100);}
 assert(held?.held>0,'Creator capture did not reach the held MCP discovery boundary');
 const before=await request('chat.history',{sessionKey,limit:40});save('revoked-before-abort',before);assert(JSON.stringify(before).includes('automations'),'No actual scheduling tool call before revocation');
 let aborted,abortError;const abortPromise=request('chat.abort',{sessionKey,runId:sent.runId||runId}).then(r=>{aborted=r;},e=>{abortError=e;});
 const abortStart=Date.now();const committed=()=>events.some(e=>e.event==='chat'&&e.payload?.runId===(sent.runId||runId)&&e.payload?.state==='aborted');
 while(!aborted&&!abortError&&!committed()&&Date.now()-abortStart<10000)await sleep(10);
 assert(committed()||aborted?.aborted===true||aborted?.runIds?.includes(sent.runId||runId),'No committed abort before release');
 await fetch('http://127.0.0.1:19741/release',{method:'POST'});
 await abortPromise;if(abortError)throw abortError;save('revoked-abort-result',aborted);
 const done=await request('agent.wait',{runId:sent.runId||runId,timeoutMs:160000});save('revoked-wait',done);assert.notEqual(done.status,'timeout','Revoked run did not settle');
 save('revoked-after-release',await request('chat.history',{sessionKey,limit:60}));
 assert(!(await jobs()).some(j=>j.name==='revoked-before-save'),'Revoked creator saved a job');
 report.creatorRevokedBeforeSave=true;report.cases.push({tag,runId:sent.runId||runId,heldDiscovery:true,saved:false});
}
async function login(){
 const child=spawn(process.execPath,['openclaw.mjs','mcp','login','unrelated_oauth'],{cwd:source,env:process.env,stdio:['ignore','pipe','pipe']});
 let output='',browsed=false,browser;const collect=b=>{output+=b.toString();const match=output.split(String.fromCharCode(27)).join(' ').match(/http:\/\/127\.0\.0\.1:19741\/authorize[^\s]+/);if(match&&!browsed){browsed=true;browser=fetch(match[0]).then(async r=>{assert.equal(r.status,200);assert((await r.text()).includes('Authorization received'));});}};
 child.stdout.on('data',collect);child.stderr.on('data',collect);
 const code=await new Promise((resolve,reject)=>{child.on('error',reject);child.on('exit',resolve);});if(browser)await browser;assert(browsed,'No operator authorization URL');assert.equal(code,0,output);assert(output.includes('credentials saved'),'OAuth exchange did not save credentials');save('login-result',{browsed,exitCode:code,credentialsSaved:true});
}
async function connectOperator(){createClient();
 await c.waitOpen();const nonce=await challenge,signedAtMs=Date.now(),scopes=['operator.read','operator.write','operator.admin'];
 const payload=buildDeviceAuthPayloadV3({deviceId,clientId:'openclaw-tui',clientMode:'ui',role:'operator',scopes,signedAtMs,token:'mcp-proof-fixture-token',nonce,platform:process.platform});
 await request('connect',{minProtocol:PROTOCOL_VERSION,maxProtocol:PROTOCOL_VERSION,client:{id:'openclaw-tui',displayName:'MCP boundary proof',version:'1',platform:process.platform,mode:'ui'},role:'operator',scopes,device:{id:deviceId,publicKey,signature:sign(null,Buffer.from(payload),pair.privateKey).toString('base64url'),signedAt:signedAtMs,nonce},caps:[],auth:{token:'mcp-proof-fixture-token'}});
}
async function restartOwnedGateway(){
 c.close();fs.writeFileSync(out+'/restart-requested','OAuth login committed; exercise fresh authenticated discovery with the same persisted jobs.');
 const started=Date.now();while(!fs.existsSync(out+'/restart-ready')&&Date.now()-started<60000)await sleep(100);
 assert(fs.existsSync(out+'/restart-ready'),'Owned Gateway restart did not reach readiness');
 await connectOperator();report.gatewayRestartAfterLogin=true;
}
try{
 await connectOperator();
 const localHistory=await turn('inherited_local',[addCall(job('inherited-local'))]);
 let inventory=await jobs();const local=inventory.find(j=>j.name==='inherited-local');
 if(expected==='baseline'){assert(!local,'Baseline unexpectedly saved default job');assert.match(resultText(localHistory),/Sign in to the affected MCP server/);report.defaultCapture='rejected-unrelated-oauth';}
 else {assert(local,'Candidate did not save default job');assert.match(resultText(localHistory),/warnings/);assert.match(resultText(localHistory),/unrelated_oauth/);assert(local.payload.toolsAllow.includes('exec'));assert(local.payload.toolsAllow.includes('read'));assert(!local.payload.toolsAllow.some(n=>n.startsWith('unrelated_oauth__')));report.defaultCapture='saved-bounded-subset';report.savedCap=local.payload.toolsAllow;save('saved-local-before-login',local);}
 const required=await turn('required_unavailable',[addCall(job('required-unavailable',['unrelated_oauth__ping']))]);
 assert(!(await jobs()).some(j=>j.name==='required-unavailable'));
 assert.match(resultText(required),expected==='candidate'?/not currently executable: unrelated_oauth__ping/:/Sign in to the affected MCP server/);
 if(expected==='candidate')assert.match(resultText(required),/openclaw mcp login unrelated_oauth/);
 const aliasHistory=await turn('finite_alias',[addCall(job('finite-alias',['gateway_exec','gateway_process','read']))]);
 const alias=(await jobs()).find(j=>j.name==='finite-alias');assert(alias,'Executable aliases did not save: '+resultText(aliasHistory));if(expected==='candidate'){assert(alias.payload.toolsAllow.includes('exec'));assert(alias.payload.toolsAllow.includes('process'));assert(!alias.payload.toolsAllow.includes('gateway_exec'));report.aliasCapture='canonical';}else{assert.deepEqual(alias.payload.toolsAllow,['gateway_exec','gateway_process','read']);report.aliasCapture='broken-literal-aliases';}
 const unknown=await turn('unknown_name',[addCall(job('unknown-name',['invented__not_executable']))]);
 const unknownSaved=(await jobs()).find(j=>j.name==='unknown-name');if(expected==='candidate'){assert(!unknownSaved);assert.match(resultText(unknown),/not currently executable: invented__not_executable/);report.unknownSelector='rejected';}else{assert(!unknownSaved);assert.match(resultText(unknown),/Sign in to the affected MCP server/);report.unknownSelector='unrelated-oauth-rejection';}
 if(expected==='candidate'){
  const mixed=await turn('wildcard_required',[addCall(job('wildcard-required',['*','unrelated_oauth__ping']))]);
  assert(!(await jobs()).some(j=>j.name==='wildcard-required'));assert.match(resultText(mixed),/not currently executable: unrelated_oauth__ping/);
  await readOnlyCaller();
  const ceilingHistory=await turn('capture_ceiling',[addCall(job('saved-ceiling',undefined,'Probe whether the unrelated_oauth__ping integration is available. Report failure accurately.'))]);assert.match(resultText(ceilingHistory),/warnings/);
  const ceiling=(await jobs()).find(j=>j.name==='saved-ceiling');assert(ceiling);
  const marker=out+'/workspace/local-proof.txt';
  const localRun=await runJob('local_before_login',local,[{name:'exec',namespace:'openclaw_direct',args:{command:'printf MCP_LOCAL_FILE_OK > '+marker}},{name:'read',args:{path:marker}}]);
  assert.equal(localRun.entry.status,'ok');assert.equal(fs.readFileSync(marker,'utf8'),'MCP_LOCAL_FILE_OK');assert.match(resultText(localRun.history),/MCP_LOCAL_FILE_OK/);
  const healthyHistory=await turn('healthy_requirement',[addCall(job('healthy-required',['healthy__ping'],'Call healthy__ping once.'))]);const healthy=(await jobs()).find(j=>j.name==='healthy-required');assert(healthy,'Healthy integration unavailable: '+resultText(healthyHistory));
  const healthyRun=await runJob('healthy_sibling',healthy,[{name:'healthy__ping',args:{}}]);assert.equal(healthyRun.entry.status,'ok');assert.match(resultText(healthyRun.history),/MCP_PONG_HEALTHY/);
  await revokeCreator();
  await login();
  await restartOwnedGateway();
  const current=await request('cron.get',{id:local.id});save('saved-local-after-login',current);assert.deepEqual(current.payload.toolsAllow,local.payload.toolsAllow);
  const after=await runJob('local_after_login',local,[{name:'exec',namespace:'openclaw_direct',args:{command:'printf MCP_AFTER_LOGIN_OK > '+marker}},{name:'read',args:{path:marker}}]);assert.equal(after.entry.status,'ok');assert.equal(fs.readFileSync(marker,'utf8'),'MCP_AFTER_LOGIN_OK');assert.notEqual(after.queued.processInstanceId,localRun.queued.processInstanceId,'Gateway process did not change');
  const authorizedHistory=await turn('new_authorized_requirement',[addCall(job('newly-authorized',['unrelated_oauth__ping'],'Call unrelated_oauth__ping once.'))]);const authorized=(await jobs()).find(j=>j.name==='newly-authorized');assert(authorized,'Post-login tool not available: '+resultText(authorizedHistory));
  const authorizedRun=await runJob('new_authorized_run',authorized,[{name:'unrelated_oauth__ping',args:{}}]);assert.equal(authorizedRun.entry.status,'ok');assert.match(resultText(authorizedRun.history),/MCP_PONG_AUTHORIZED/);
  const beforeLines=fs.readFileSync(out+'/peer.jsonl','utf8').trim().split('\n').length;
  const denied=await runJob('saved_ceiling_denial',ceiling,[{name:'unrelated_oauth__ping',args:{}}]);
  const attempts=fs.readFileSync(out+'/peer.jsonl','utf8').trim().split('\n').slice(beforeLines).map(JSON.parse);assert(!attempts.some(x=>x.kind==='mcp'&&x.path==='/mcp/blocked'&&x.rpc==='tools/call'),'Saved job reached excluded integration after login');
  const refusal=toolResults(denied.history).find(m=>m.toolCallId==='call_saved_ceiling_denial_0'&&m.toolName==='unrelated_oauth__ping');
  assert(refusal,'No retained response to the attempted excluded tool');assert.equal(refusal.content.filter(x=>x.type==='text').map(x=>x.text).join('\n'),'unsupported call: unrelated_oauth__ping');
  const vanished=await turn('interactive_then_unavailable',[addCall(job('vanished-required',['healthy__ping']))],{rejectCapture:true});
  assert(!(await jobs()).some(j=>j.name==='vanished-required'));assert.match(resultText(vanished),/not currently executable: healthy__ping/);
  report.interactiveVisibilityCannotPreauthorize=true;
  report.loginDoesNotWiden=true;report.localFileBeforeAndAfter=true;report.healthySibling=true;report.postLoginNewGrant=true;report.savedCeilingDenied=true;
 }
 save('jobs-final',{jobs:await jobs()});report.result='PASS';save('report',report);console.log(JSON.stringify(report,null,2));
}catch(error){report.result='FAIL';report.error=String(error);save('report',report);console.error(error);process.exitCode=1;}finally{c.close();}

v2-run.sh

#!/usr/bin/env bash
set -euo pipefail
synced="$(pwd -P)"
proof=/tmp/openclaw-mcp-proof-d69308f5
export PROOF_TREE="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-tree.txt")"
expected="$PROOF_EXPECT"
export PROOF_SOURCE="$proof/baseline"
if [ "$expected" = candidate ]; then export PROOF_SOURCE="$proof/candidate-complete-$PROOF_TREE"; fi
export PROOF_OUT="$proof/$expected-v2-$PROOF_ATTEMPT"
test ! -e "$PROOF_OUT"
mkdir -p "$PROOF_OUT" "$proof/fixtures-v2"
cp "$synced"/.openclaw/tmp/mcp-proof/{v2-peer.mjs,v2-config.mjs,v2-client.mjs,write-config.mjs} "$proof/fixtures-v2/"
if [ "$expected" = candidate ]; then test "$(git -C "$PROOF_SOURCE" write-tree)" = "$PROOF_TREE"; git -C "$PROOF_SOURCE" diff --exit-code; else test -z "$(git -C "$PROOF_SOURCE" status --porcelain --untracked-files=no)"; fi
export PROOF_SHA="$(git -C "$PROOF_SOURCE" rev-parse HEAD)"
if [ "$expected" = candidate ]; then test "$PROOF_SHA" = "$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-head.txt")"; else test "$PROOF_SHA" = fb503c9e1f25d8c3877881e55e83d4378eda3676; fi
export PROOF_TREE="$(git -C "$PROOF_SOURCE" rev-parse HEAD^{tree})"
node "$proof/fixtures-v2/v2-config.mjs"
export HOME="$PROOF_OUT/home" OPENCLAW_HOME="$PROOF_OUT/home" OPENCLAW_STATE_DIR="$PROOF_OUT/state" OPENCLAW_CONFIG_PATH="$PROOF_OUT/config.json" OPENCLAW_GATEWAY_TOKEN=mcp-proof-fixture-token OPENAI_API_KEY=synthetic-proof-key
unset CODEX_HOME CODEX_API_KEY OPENCLAW_GATEWAY_URL OPENCLAW_CODEX_APP_SERVER_COMMAND OPENCLAW_CODEX_APP_SERVER_BIN OPENCLAW_CODEX_APP_SERVER_ARGS OPENAI_BASE_URL OPENCLAW_AGENT_DIR OPENCLAW_WORKSPACE_DIR
export OPENCLAW_NO_RESPAWN=1
cd "$PROOF_SOURCE"
node --import ./scripts/tsx.mjs "$proof/fixtures-v2/v2-peer.mjs" > "$PROOF_OUT/peer.log" 2>&1 & peer_pid=$!
client_pid=""
cleanup() {
 if [ -n "$client_pid" ]; then kill "$client_pid" 2>/dev/null || true; fi
 kill "$gateway_pid" "$peer_pid" 2>/dev/null || true
 wait "$gateway_pid" "$peer_pid" 2>/dev/null || true
}
trap cleanup EXIT
start_gateway() {
 node openclaw.mjs gateway run --allow-unconfigured --port 19742 >> "$PROOF_OUT/gateway.log" 2>&1 & gateway_pid=$!
 for i in $(seq 1 120); do
  if curl -fsS http://127.0.0.1:19742/readyz >/dev/null 2>&1 && curl -fsS http://127.0.0.1:19741/health >/dev/null 2>&1; then break; fi
  kill -0 "$gateway_pid" "$peer_pid" || { tail -60 "$PROOF_OUT/gateway.log" "$PROOF_OUT/peer.log";exit 1; }
  sleep 1
 done
 curl -fsS http://127.0.0.1:19742/readyz >/dev/null
}
start_gateway
node --import ./scripts/tsx.mjs "$proof/fixtures-v2/v2-client.mjs" > "$PROOF_OUT/client.log" 2>&1 & client_pid=$!
restarted=false
while kill -0 "$client_pid" 2>/dev/null; do
 if [ "$restarted" = false ] && [ -f "$PROOF_OUT/restart-requested" ]; then
  kill "$gateway_pid"
  stopped=0; wait "$gateway_pid" || stopped=$?
  if [ "$stopped" != 0 ] && [ "$stopped" != 143 ]; then echo "Unexpected Gateway exit: $stopped";exit 1;fi
  start_gateway
  touch "$PROOF_OUT/restart-ready"
  restarted=true
 fi
 sleep 0.1
done
status=0;wait "$client_pid" || status=$?
client_pid=""
if [ "$status" != 0 ]; then tail -45 "$PROOF_OUT/client.log";tail -45 "$PROOF_OUT/gateway.log";tail -20 "$PROOF_OUT/peer.log";exit "$status";fi
cat "$PROOF_OUT/report.json"
printf 'PROOF_OUTPUT=%s\n' "$PROOF_OUT"

v2-prepare.sh

#!/usr/bin/env bash
set -euo pipefail
synced="$(pwd -P)"
proof=/tmp/openclaw-mcp-proof-d69308f5
head="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-head.txt")"
tree="$(cat "$synced/.openclaw/tmp/mcp-proof/candidate-tree.txt")"
mkdir -p "$proof"
candidate="$proof/candidate-complete-$tree"
test ! -e "$candidate"
echo CRABBOX_PHASE:prepare-complete-candidate
git clone --no-checkout https://github.com/openclaw/openclaw.git "$candidate"
git -C "$candidate" checkout --detach "$head"
test "$(git -C "$candidate" rev-parse HEAD)" = "$head"
test "$(git -C "$candidate" rev-parse HEAD^{tree})" = "$tree"
test -z "$(git -C "$candidate" status --porcelain --untracked-files=no)"
cd "$candidate"
pnpm install --frozen-lockfile > "$proof/candidate-install.log" 2>&1
echo CRABBOX_PHASE:build-candidate
pnpm build > "$proof/candidate-build.log" 2>&1
test -z "$(git status --porcelain --untracked-files=no)"
node extensions/codex/node_modules/@openai/codex/bin/codex.js --version
printf 'SOURCE_READY stage=candidate sha=%s tree=%s\n' "$(git rev-parse HEAD)" "$(git rev-parse HEAD^{tree})"

echo CRABBOX_PHASE:real-gateway-proof
(cd "$synced" && PROOF_EXPECT=candidate PROOF_ATTEMPT=final bash .openclaw/tmp/mcp-proof/v2-run.sh)

v2-launch.mjs

import fs from 'node:fs';
import {spawnSync} from 'node:child_process';
const stage=process.argv[2];if(!['prepare','baseline','candidate'].includes(stage))throw Error('stage required');
const attempt=process.argv[3]||'1';if(!/^[a-zA-Z0-9_-]+$/.test(attempt))throw Error('bad attempt');
const root=new URL('./',import.meta.url);
const names=['v2-peer.mjs','v2-config.mjs','v2-client.mjs','write-config.mjs','v2-prepare.sh','v2-run.sh','candidate-tree.txt','candidate-head.txt','candidate.patch'];
const files=Object.fromEntries(names.map(n=>[n,fs.readFileSync(new URL(n,root),'utf8')]));
const remote="const fs=require('node:fs');const dir=process.cwd()+'/.openclaw/tmp/mcp-proof';fs.mkdirSync(dir,{recursive:true});for(const [n,c] of Object.entries(JSON.parse(process.argv[1])))fs.writeFileSync(dir+'/'+n,c);";
const q=s=>"'"+s.replaceAll("'","'\\''")+"'";
if(!process.env.PROOF_MODEL?.startsWith('openai/'))throw Error('Set PROOF_MODEL');
const command='node -e '+q(remote)+' '+q(JSON.stringify(files))+' && PROOF_MODEL='+q(process.env.PROOF_MODEL)+' '+(stage==='prepare'?'bash .openclaw/tmp/mcp-proof/v2-prepare.sh':'PROOF_EXPECT='+stage+' PROOF_ATTEMPT='+attempt+' bash .openclaw/tmp/mcp-proof/v2-run.sh');
const lease=fs.readFileSync(new URL('lease-id.txt',root),'utf8').trim();
const result=spawnSync(process.execPath,['scripts/crabbox-wrapper.mjs','run',...(lease?['--id',lease]:[]),'--keep','--label','mcp-proof-d69308f5','--timing-json','--','bash','-c',command],{stdio:'inherit'});
process.exitCode=result.status??1;

roboclaw-bot and others added 2 commits September 29, 2026 01:20
Capture the currently executable authorized subset with visible exclusions, reject unresolved required selectors, and retain existing run-bound grants and saved tool ceilings.

Co-authored-by: jalehman <[email protected]>
Refresh finite integration caps before saving and reject unavailable explicit selectors even beside a wildcard. Preserve exact host alias provenance through admission-fenced normalization without replacing the executable or losing the current view guard.

Co-authored-by: jalehman <[email protected]>
@roboclaw-bot
roboclaw-bot force-pushed the openclaw/fix-156379-mcp-continuation-capture branch from 8f100e7 to 685ddfc Compare September 29, 2026 01:36
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 13, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant