Skip to content

refactor: drop tool-caller re-checks from session tools and subagent registry - #203516

Merged
obviyus merged 2 commits into
mainfrom
refactor/tool-caller-sessions-callers
Nov 22, 2026
Merged

obviyus merged 2 commits into
mainfrom
refactor/tool-caller-sessions-callers

Conversation

@obviyus

@obviyus obviyus commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

#203487 made captureGatewayToolCallerAssertion stop re-checking permission in the middle of a started tool call; it now only checks Stop and carries the caller receipt's session fences. The sessions_* tools and the subagent registry still captured it and called it again at each step. Those calls are dead weight. Some of them also used "the capture returned a function" to mean "this is an admitted agent run".

Why This Change Was Made

Admission checks permission one time, when work starts. This PR removes the leftover capture from the session tools and the subagent registry:

  • sessions-list-tool.ts: the capture and its call in finalize; the tool signal check stays.
  • sessions-tool.ts (assign_owner), sessions-tool-control.ts (captureSessionStopCaller, stopSessionTool): the admitted-run gate reads caller.operationalRunInstance, which is the condition the capture tested. The tool signal check stays at each step.
  • sessions-operator-authority.ts: the sessions.patch capture is removed from the composed control source.
  • sessions-send-communication.ts: the capture is removed from assertSource, which already checks the tool call's signal and closes on abort. The approval gate reads caller.operationalRunInstance.
  • sessions-send-tool.delivery.ts, sessions-send-tool.steering.ts: the steering guard still uses the guarded (V2) injection for an admitted run. Stop reaches it through assertSendCurrent (the communication assertion, which is signal-bound).
  • sessions-send-followup.ts, sessions-send-followup-custody.ts: the follow-up checks are the prepared custody (request.custody.assertCurrent) only.
  • sessions-send-resume.ts, gateway/session-subagent-resume.ts: a live admitted caller has no assertCurrent. A host-retained replay keeps its retained source assertion. requirePausedChild runs caller.assertCurrent?.(); admission is decided once in captureSessionsSendResumeCaller (the only producer of this caller).
  • subagent-registry-public-api.ts, subagent-registry-requester-claim.ts: the registry writes keep the state-worker source check and the continuation custody.

Session write fences are not dropped. Every sessions tool write goes through the in-process Gateway caller (in-process-gateway.ts, PR 1d), which still composes the caller's receipt into sessionMutationCommitGuard. The removed captures were all sync closures (Stop only) or duplicated that composed fence.

No new export, name, hook, flag or guard. Production: 13 files, +43 / −108.

Accepted edge cases (no code for them):

  • acknowledgeSubagentResultForRequesterTurn and claimSubagentYield no longer check Stop before their registry write. These are internal bookkeeping writes for a result the run already has (mark delivered, record the yield), not user-visible effects.
  • prepareSessionsSendFollowup no longer checks the tool Stop during its preparation reads. The dispatch that follows stays signal-fenced through the communication assertion.

Changed tests

  • sessions-tool.self-archive.test.ts, agent-tools.session-owner.test.ts: sessions.assignOwner no longer carries assertDispatchCurrent.
  • sessions-send-communication.test.ts: the mocked caller now has an operationalRunInstance (that is what "admitted" means now); the removed capture mock is gone.

No test asserted a mid-run refusal through these callers, so no test was deleted.

User Impact

None visible. An admitted session tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict.

Evidence

  • Pre-push: one ocx test run with fail-fast off over 41 files (every direct importer of a changed source, plus importers of the test-support files that import them). After the test fixes, everything is green except:
    • agent.test.ts ("honors owner cancellation while explicit recipient session routing is pending", "does not deliver prepared identity after the client loses authority") and question.communication.test.ts ("retains creator/admin rights without treating assigned responsibility as authority"): also red on the merge base 6ff7a062e54e.
    • server.plugin-reload-send-revocation.product.test.ts: it expects "Operator access was revoked; start a new user turn.", which no production code emits since refactor(gateway): admit saved requesters once when work starts #202513. On head the revoked replay is still refused with 0 effects; the notice says "Restart recovery operator authority changed; start a new user turn.". On the base it timed out under host load.
  • pnpm tsgo:core, pnpm tsgo:test, oxfmt and oxlint on the changed files: clean.

…ubagent registry

Admission checks permission once; Stop stays on the tool signal and session fences stay on the in-process Gateway caller.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 22, 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 gateway Gateway runtime agents Agent runtime and tooling size: S labels Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 6d3de4f9d37e7e66ed5b36d07f82fa52f9e580bf
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/tools/sessions-operator-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 22, 2026
@clawsweeper

clawsweeper Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR removes redundant caller assertions from session tools and subagent bookkeeping while retaining existing cancellation, custody, and write-fence owners.

Example: An admitted parent sends "continue" to paused child agent:main:worker.

  • Before: The resume path repeatedly invokes the captured caller assertion alongside communication and Gateway guards.
  • After: The resume path uses the admitted caller identity while communication and Gateway owners retain cancellation and session-write checks.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, focused production simplification, but the edited mock creates a definite validation failure.
Proof confidence 🦐 gold shrimp (3/6) This behavior-preserving refactor requires no separate shipped-entry-point demonstration; supplied validation consists of test and static-check reports, and predecessor runtime evidence is not counted as proof of this head.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Session tools still carry redundant caller checks after admission moved to request start.
Reason: The maintainer-authored direction matches the repository contract and merged predecessor, removes duplicated machinery, and explicitly accepts the limited bookkeeping behavior after Stop.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the simplification follows the accepted admission contract, but an edited module mock introduces a concrete CI blocker.

Priority: P2
Reviewed head: 3b9f44001f5b3ac0f00dbf590a2f8ff111435f3c

Before merge

  • Preserve real exports in the edited caller-context mock (P2) - Removing captureGatewayToolCallerAssertion changes this closed vi.mock factory's token fingerprint. config/test-mock-exports-baseline.txt still grandfathers only the original fingerprint, so check:test-mock-exports rejects this revision; the hosted baseline-ratchets job also reports mock-exports failed. Convert this mock to importOriginal pass-through and prune the obsolete baseline entry, or document a concrete isolation requirement using the supported annotation. Do not add a replacement baseline allowance.

Findings

  • [P2] Preserve real exports in the edited caller-context mock — src/agents/tools/sessions-send-followup.test.ts:43-45
Agent review details

How this fits together

Session tools translate admitted agent requests into Gateway operations, session-controller steering, and subagent registry updates; existing owners enforce destination access, cancellation, and durable writes.

flowchart TD
  A[Admitted agent request] --> B[Session tools]
  B --> C[Communication admission]
  C --> D[In-process Gateway]
  C --> E[Session controller]
  D --> F[Session storage]
  B --> G[Subagent registry]
Loading

Technical review

Best possible solution:

Keep the focused assertion removal, preserve real exports in the edited test mock, and prune its obsolete baseline entry.

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

The mock-export failure is source-reproducible: removing a factory property changes its exact fingerprint, while the unchanged ledger permits only the old factory; hosted CI independently reports that check failing.

Is this the best way to solve the issue?

The production change is a small continuation of the accepted admission design, reusing existing Gateway and custody owners without adding machinery; the remaining repair belongs entirely in test setup and its generated baseline.

Full review comments:

  • [P2] Preserve real exports in the edited caller-context mock — src/agents/tools/sessions-send-followup.test.ts:43-45
    Removing captureGatewayToolCallerAssertion changes this closed vi.mock factory's token fingerprint. config/test-mock-exports-baseline.txt still grandfathers only the original fingerprint, so check:test-mock-exports rejects this revision; the hosted baseline-ratchets job also reports mock-exports failed. Convert this mock to importOriginal pass-through and prune the obsolete baseline entry, or document a concrete isolation requirement using the supported annotation. Do not add a replacement baseline allowance.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8d1e59c2fddc.

Provenance checked

  • Synchronous caller assertions and admission markers keeps the original intent (adb2f7c: Allow a started tool call to finish after permission changes while retaining Stop and prepared session-write fences.)
  • Paused-child resume and retained replay keeps the original intent (0f28bcd: Resume only parent-controlled paused tasks while preserving the original task identity and completion owner; later bca8823 added retained replay assertions.)
  • Requester yield and completion bookkeeping changes intended behavior with a stated reason (437572e: Await requester yield and cohort handoff under registry source checks; this PR explicitly allows already-owned bookkeeping to finish after Stop.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

Acceptance criteria:

  • pnpm check:test-mock-exports --base 6ff7a06
  • pnpm test src/agents/tools/sessions-send-followup.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 714129c adds src/agents/subagents/registry/subagent-registry-requester-claim.ts:126 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 714129c06ea1; files: src/agents/subagents/registry/subagent-registry-requester-claim.ts)
  • Peter Steinberger: Raw commit 437572e adds src/agents/subagents/registry/subagent-registry-public-api.ts:211 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 437572e2e90b; files: src/agents/subagents/registry/subagent-registry-public-api.ts)
  • Jason (Json): Raw commit bca8823 adds src/agents/tools/sessions-send-resume.ts:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: bca882333b9d; files: src/agents/tools/sessions-send-resume.ts)

PR surface

Source -65, Tests +1. Total -64 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 13 43 108 -65
Tests 3 5 4 +1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 48 112 -64

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Useful internal simplification with a narrow, diff-caused test-validation blocker and no demonstrated urgent user-facing regression.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Useful internal simplification with a narrow, diff-caused test-validation blocker and no demonstrated urgent user-facing regression.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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.

Reviewed November 22, 2026, 10:07 AM ET / 15:07 UTC.

Keep the follow-up test mock factory unchanged for the mock-exports ratchet.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Head E2E (one-admission journey) on 3b9f44001f5b. The production code is the same on the current head 6d3de4f9d37e; the second commit changes only tests.

  • Q. revoke while queued → refused visibly: PASS
  • R. revoke while running → finishes: PASS
  • S. Stop → cancels: PASS

verdict.json:

{
  "pass": true,
  "prefix": "HEAD",
  "sessionKey": "agent:main:one-admission-dd74f089",
  "models": [
    "gpt-5.5-2026-04-23",
    null
  ],
  "relayStatuses": [
    200,
    421
  ],
  "checks": [
    {
      "id": "R.running-turn-finishes",
      "pass": true,
      "detail": {
        "state": "final",
        "toolEnds": 3,
        "toolEndsAfterRevoke": 3
      }
    },
    {
      "id": "Q.queued-input-refused-visibly",
      "pass": true,
      "detail": {
        "accepted": true,
        "providerRequestsWithQueuedMarker": 0,
        "visibleRefusalInTranscript": true
      }
    },
    {
      "id": "S.stop-cancels",
      "pass": true,
      "detail": {
        "abort": {
          "ok": true,
          "aborted": true,
          "runIds": [
            "4b673922-b4a6-4d27-8c4d-0761c65896b2"
          ]
        },
        "state": "aborted",
        "requestsWithStopMarker": 1
      }
    }
  ],
  "elapsedMs": 57631
}

results.jsonl steps (28 lines; t, step, ok):

2026-11-22T14:55:07.856Z	admin#1.hello	
2026-11-22T14:55:07.912Z	worker#1.hello	
2026-11-22T14:55:07.934Z	worker.users.self	true
2026-11-22T14:55:07.943Z	worker#1.close	
2026-11-22T14:55:07.952Z	admin.setRole.worker	true
2026-11-22T14:55:08.821Z	worker#2.hello	
2026-11-22T14:55:10.788Z	admin.sessions.create	true
2026-11-22T14:55:10.872Z	admin.members.add	true
2026-11-22T14:55:11.120Z	R.worker.chat.send	true
2026-11-22T14:55:15.210Z	Q.worker.chat.send.queued	true
2026-11-22T14:55:16.838Z	Q.admin.history.beforeRevoke	true
2026-11-22T14:55:16.840Z	Q.pendingBeforeRevoke	
2026-11-22T14:55:16.862Z	worker#2.close	
2026-11-22T14:55:16.864Z	R.admin.setRole.readonly	true
2026-11-22T14:55:57.818Z	Q.admin.history.after	true
2026-11-22T14:55:57.819Z	QR.relay	
2026-11-22T14:55:57.819Z	CHECK R.running-turn-finishes	
2026-11-22T14:55:57.819Z	CHECK Q.queued-input-refused-visibly	
2026-11-22T14:55:57.841Z	worker#2.close	
2026-11-22T14:55:57.843Z	S.admin.setRole.worker	true
2026-11-22T14:55:58.355Z	worker#3.hello	
2026-11-22T14:55:58.418Z	S.worker.chat.send	true
2026-11-22T14:56:00.982Z	S.admin.chat.abort	true
2026-11-22T14:56:04.984Z	CHECK S.stop-cancels	
2026-11-22T14:56:04.996Z	final.history	true
2026-11-22T14:56:04.997Z	done	
2026-11-22T14:56:04.998Z	admin#1.close	
2026-11-22T14:56:04.999Z	worker#3.close	

@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the remaining reds on 6d3de4f9d37e (CI run 45036694905) do not come from this PR.

  • src/gateway/server-methods/agent.test.ts "does not deliver prepared identity after the client loses authority" and "honors owner cancellation while explicit recipient session routing is pending": red on merge base 6ff7a062e54e locally (ocx test on the base checkout, same assertions).
  • src/gateway/server-methods/question.communication.test.ts "retains creator/admin rights without treating assigned responsibility as authority": red on merge base 6ff7a062e54e locally.
  • src/gateway/server.plugin-reload-send-revocation.product.test.ts: it expects the notice "Operator access was revoked; start a new user turn.". No production code emits that string since refactor(gateway): admit saved requesters once when work starts #202513 (git log -S), so it cannot pass on main. On this head the revoked replay is still refused with 0 effects and 0 target messages; only the reason text differs ("Restart recovery operator authority changed; start a new user turn.").
  • checks-node-core-test-nondist-shard is the aggregate of the shards above.

ci-triage output:

# PR #203516 head 6d3de4f9d37e; main run 45032841873
checks-node-changed-compact-large-10-2	src/gateway/server-methods/agent.test.ts	OURS
checks-node-changed-compact-large-10-2	src/gateway/server.plugin-reload-send-revocation.product.test.ts	OURS
checks-node-changed-compact-large-39	src/gateway/server-methods/question.communication.test.ts	OURS

@obviyus
obviyus merged commit cc7b482 into main Nov 22, 2026
125 of 130 checks passed
@obviyus
obviyus deleted the refactor/tool-caller-sessions-callers branch November 22, 2026 15:26
@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as cc7b482. The session tools and the subagent registry no longer re-check the tool caller mid-call (production −65 lines). Stop still cancels through the tool signal, and session write fences stay on the in-process Gateway caller. Proof: head E2E Q/R/S pass, local review clean, remaining CI reds are main-side (override comment above).

github-actions Bot pushed a commit to Anti-RombikAnti-Rombik8790/openclaw that referenced this pull request Nov 22, 2026
…registry (#203516)

## What Problem This Solves

#203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call; it now only checks Stop and carries the caller receipt's session fences. The `sessions_*` tools and the subagent registry still captured it and called it again at each step. Those calls are dead weight. Some of them also used "the capture returned a function" to mean "this is an admitted agent run".

## Why This Change Was Made

Admission checks permission one time, when work starts. This PR removes the leftover capture from the session tools and the subagent registry:

- `sessions-list-tool.ts`: the capture and its call in `finalize`; the tool signal check stays.
- `sessions-tool.ts` (`assign_owner`), `sessions-tool-control.ts` (`captureSessionStopCaller`, `stopSessionTool`): the admitted-run gate reads `caller.operationalRunInstance`, which is the condition the capture tested. The tool signal check stays at each step.
- `sessions-operator-authority.ts`: the `sessions.patch` capture is removed from the composed control source.
- `sessions-send-communication.ts`: the capture is removed from `assertSource`, which already checks the tool call's `signal` and closes on abort. The approval gate reads `caller.operationalRunInstance`.
- `sessions-send-tool.delivery.ts`, `sessions-send-tool.steering.ts`: the steering guard still uses the guarded (V2) injection for an admitted run. Stop reaches it through `assertSendCurrent` (the communication assertion, which is signal-bound).
- `sessions-send-followup.ts`, `sessions-send-followup-custody.ts`: the follow-up checks are the prepared custody (`request.custody.assertCurrent`) only.
- `sessions-send-resume.ts`, `gateway/session-subagent-resume.ts`: a live admitted caller has no `assertCurrent`. A host-retained replay keeps its retained source assertion. `requirePausedChild` runs `caller.assertCurrent?.()`; admission is decided once in `captureSessionsSendResumeCaller` (the only producer of this caller).
- `subagent-registry-public-api.ts`, `subagent-registry-requester-claim.ts`: the registry writes keep the state-worker source check and the continuation custody.

Session write fences are not dropped. Every sessions tool write goes through the in-process Gateway caller (`in-process-gateway.ts`, PR 1d), which still composes the caller's receipt into `sessionMutationCommitGuard`. The removed captures were all sync closures (Stop only) or duplicated that composed fence.

No new export, name, hook, flag or guard. Production: 13 files, +43 / −108.

Accepted edge cases (no code for them):

- `acknowledgeSubagentResultForRequesterTurn` and `claimSubagentYield` no longer check Stop before their registry write. These are internal bookkeeping writes for a result the run already has (mark delivered, record the yield), not user-visible effects.
- `prepareSessionsSendFollowup` no longer checks the tool Stop during its preparation reads. The dispatch that follows stays signal-fenced through the communication assertion.

### Changed tests

- `sessions-tool.self-archive.test.ts`, `agent-tools.session-owner.test.ts`: `sessions.assignOwner` no longer carries `assertDispatchCurrent`.
- `sessions-send-communication.test.ts`: the mocked caller now has an `operationalRunInstance` (that is what "admitted" means now); the removed capture mock is gone.

No test asserted a mid-run refusal through these callers, so no test was deleted.

## User Impact

None visible. An admitted session tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict.

## Evidence

- Pre-push: one `ocx test` run with fail-fast off over 41 files (every direct importer of a changed source, plus importers of the test-support files that import them). After the test fixes, everything is green except:
  - `agent.test.ts` ("honors owner cancellation while explicit recipient session routing is pending", "does not deliver prepared identity after the client loses authority") and `question.communication.test.ts` ("retains creator/admin rights without treating assigned responsibility as authority"): also red on the merge base `6ff7a062e54e`.
  - `server.plugin-reload-send-revocation.product.test.ts`: it expects "Operator access was revoked; start a new user turn.", which no production code emits since #202513. On head the revoked replay is still refused with 0 effects; the notice says "Restart recovery operator authority changed; start a new user turn.". On the base it timed out under host load.
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean.
- Head E2E: Q, R and S pass (openclaw/openclaw#203516 (comment)). Local review on the final head: patch correct, zero findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 22, 2026
## What Problem This Solves

Fixes #203512. Since #203487, Stop does not cancel an MCP loopback tool call from a CLI-backed turn (Claude CLI and other CLI runtimes). If the user stops the turn while a message action waits on a channel lookup, the action still finishes: `test/cli-message-authority.integration.test.ts > stops the reaction lookup after abort retirement` gets `isError: false`.

## Why

The MCP loopback server rebuilds the tool caller from the CLI grant (`src/gateway/mcp-http.ts`). That caller had no `approvalSignals`. The turn's abort signal reached the tool only through the receipt boolean `isGrantAndLineageCurrent` → `isMcpLoopbackClientGrantCurrent`. That boolean also checks the grant row, the admitted run's delegated authority and the capture, so it mixes run lifecycle with permission. #203487 removed the synchronous receipt boolean from `captureGatewayToolCallerAssertion` as an authority re-check. Stop was lost with it.

## Fix

- `resolveMcpLoopbackClientGrant` now returns the grant's existing `abortSignal`, which is the CLI turn's abort signal. The MCP caller passes it as `approvalSignals`, the lifecycle channel that `captureGatewayToolCallerAssertion` already checks. The permission part of the receipt stays out of the synchronous check, as #203487 intended.
- Removed: the MCP `cronAuthorityCheck` pass-through (grant field, mint copy, resolved field, caller field) and `bindActiveCronAuthorityCurrentness`. #203487 removed the only reader of the identity `cronAuthorityCheck`, so this chain had no reader left.
- No new export, name, flag or guard. Production: +3 / −17.

## Sweep of #203487, #203503 and #203516

- I traced every production caller that sets `receiptAuthority` (`agent-tools.caller`, embedded `attempt-gateway-tools`, `settled-turn-finalization`, harness `tool-authority.runtime`, `plugin-native-subagent`, `scheduled-owner-tool-guard`, `cron-tool`, `node-claude-skill-runtime`, worker `placement-turn-claim-events` and `worker-turn-tool-surface`, plugin `hooks`). Each one still delivers Stop through `approvalSignals` or through the tool's own execute signal. The MCP loopback was the only caller where the receipt carried Stop alone.
- The 1b and 1c call sites run inside in-process Gateway dispatch. That dispatch still runs the caller assertion (`in-process-gateway.ts`, `server-plugin-in-process-authority.ts`), or the tool's own signal covers them. No other instance was found, so this PR has one fix and one test.

## User Impact

When you stop a CLI-backed turn, a running message action is cancelled before its write. The tool result reads "The message turn has ended. Start a new turn to retry." A permission change in the middle of a call still does not interrupt a started call (#203487).

## Tests

- `test/cli-message-authority.integration.test.ts` "stops the reaction lookup after abort retirement": red on main (`isError: false`). Green on head, with no PATCH or PUT after Stop. The expected text is now the message route's "message turn has ended". Before #203487 the text was the generic "authority is no longer active", which #203487 removed.
- `test/cron-message-read.integration.test.ts` (claude-cli, disabled before 429): Stop now reaches the tool, so the result text is the message route's "message turn has ended". The regex now accepts it. The single PATCH and the absent retry are unchanged.
- `cron-creator-authority-context.test.ts`: the two lines that read the deleted helper are removed. The revocation assertion on the creator stays.

## Evidence

- Pre-push: one `ocx test` run with fail-fast off over the touched tests and every test importing a changed file (60 files). Green except `mcp-http.async-scope` "keeps each CLI grant's own ceiling" and `cron.scheduled-policy-adoption.integration` ×3, both red on main before this PR (see #203503 override), plus `cron-message-read` (updated above, then green 9/9).
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean.
- Real Gateway E2E on the final head `7e1c3b07ffde`: R, Q and S (Stop → cancels) pass (#203551 (comment); first head: #issuecomment-7081968622).
- Local review on the final head `7e1c3b07ffde`: patch correct, zero findings.
- Session-identity allowlist: `cron-creator-authority-context.ts` shrinks from 41 to 39.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 22, 2026
…203561)

## What Problem This Solves

#203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call. Its synchronous call now only checks Stop (`approvalSignals`); its prepared form carries the caller receipt's session fences. Agent-side callers still captured it just to call it synchronously, and some used "the capture returned a function" to mean "this is an admitted agent run".

## Why This Change Was Made

Admission checks permission one time, when work starts. This PR removes the capture where it was only a synchronous Stop check:

- `agent-tools.before-tool-call.approval.ts`, `bash-tools.exec-approval-request.ts`, `harness/gateway-question.ts`, `tools/agents-wait-tool.ts`: the capture only fed watchdog `isCurrent` callbacks. They keep their tool/request signal check where they had one. Exec approval has no signal in scope; its watchdog wait ends with the run's attempt, and the approval wait ends with `run-aborted`.
- `openclaw-plugin-tools.ts` (node MCP elicitation): the gate is `caller.operationalRunInstance`; Stop is the same signal the elicitation registers with (tool signal + caller `approvalSignals`).
- `tools/computer-tool-bindings.ts`: the gate is the existing `operationalRunInstance` check; Stop is `params.signal` / `request.signal`.
- `tools/personal-instructions-tool.ts`, `tools/presence-tool-authority.ts`: the gate reads `caller.operationalRunInstance`; personal instructions checks the tool signal.

**Kept on purpose (cut less):** where the capture is composed into a session source assertion or passed whole as one, it still carries the receipt's prepared session fence to the write. The brief says that fence must not be dropped, so these stay unchanged:

- `tools/in-process-gateway.ts`: composes it into `sessionMutationCommitGuard` for every in-process Gateway write (#203516).
- `tools/message-tool-execution.ts` / `message-tool-turn-authority.ts`, `tools/media-generate-background-shared.ts`, `tools/agent-step.ts`, and plugin tool `assertInvocationCurrent` in `openclaw-plugin-tools.ts`.

Replacing the capture with `captureGatewayToolReceiptAssertion` would bring back the "agent tool caller authority is no longer active" refusal on the synchronous path, and copying the 1a body would make a second implementation (Fable 5.2 consult: keep the carrier). PR 1e, when it deletes the declaration, must move the body to the remaining fence carriers as one implementation.

No new export, name, hook, flag or guard. Production: 8 files, +30 / −69.

Accepted edge case (no code for it): exec approval's watchdog `isCurrent` no longer checks Stop itself (no signal in scope); Stop still ends the run's watchdog attempt and the approval wait.

### Changed tests

None. No test asserted a mid-run refusal through the removed calls.

## User Impact

None visible. A started agent tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict.

## Evidence

- Pre-push: one `ocx test` run, fail-fast off, over 146 files (direct importers of every changed source, importers of test-support files that import them, and every test that names `captureGatewayToolCallerAssertion`), then the repaired and re-touched set (37 files) again on the final tree. Green except:
  - `slack-download-read-authority.integration.test.ts` "rejects revoked output ... after result (revoke: claim)": also red on the merge base `cc7b482f887b` (run there with `ocx test`); not this PR.
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. `check:lifetime-check-ratchet`: OK, no growth. `check:changed` SQLite worker ratchet OOMs locally on its 4 GB heap (known, whole-repo scan); CI covers it.

Co-authored-by: Ayaan Zaidi <[email protected]>
steipete added a commit that referenced this pull request Nov 22, 2026
…anded policy

Three more test files fail on main but are not selected by main push CI:

- doctor-health.legacy-update: the notification heartbeat-owner variants
  expected the 10th failure to auto-disable the job and send a safety
  notice. #203106 (8bdaed5) removed run-failure auto-disable, so
  Doctor now settles the interrupted run and the job keeps its schedule.
- auth-api-key: asserted a mid-request requester-revocation refusal that
  one-time admission retired (#203516, cc7b482).
- server.sessions.create.projects: the repository-child revocation phases
  asserted the same retired refusal; keep the parent-reassigned data fence.
obviyus added a commit that referenced this pull request Nov 23, 2026
…ttle-batch receipts (#203892)

## Problem

R2 of the one-admission receipt cluster. After #203760 (R1c), two receipt producers still returned a boolean, and the receipt boolean itself (`ReceiptAuthority = () => boolean | void`, the `composeReceiptAuthority` check loop, `assertAllowed` in `captureGatewayToolReceiptAssertion`) still hid permission re-checks from the lifetime-check ratchet:

- **MCP loopback grant receipt** (`mcp-http.ts`, `isGrantAndLineageCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the CLI grant row and the requester lineage.
- **Settle-batch receipt** (`agent-tools.caller.ts`, `settleBatch.isCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the subagent settle batch.

Both answer "may this requester still act?" in the middle of a call. R1c showed that turning them into throws is a new mid-request re-check (both ratchets went red), so they are deleted.

## Change

- **Deleted** the MCP grant receipt and the settle-batch receipt. The grant row and lineage are still checked once at each tool-call dispatch (`authorizeToolCall`); the settle batch is still checked at handoff admission (`subagent-announce-handoff.ts`). Stop still reaches the call through the grant's `abortSignal` and the run signal.
- **Deleted the receipt boolean:** the `ReceiptAuthority` type, the boolean check loop in `composeReceiptAuthority`, `captureGatewayToolReceiptAssertion` (and its lifetime-ratchet entry), and the `approvalAuthorityCheck` field (a duplicate of the receipt). `receiptAuthority` is now a plain `SessionSourceAssertion`: it throws or returns. `composeReceiptAuthority` only de-duplicates sources into `composeSessionSourceAssertion` and keeps its existing `assertScopeCurrent` forwarding.
- Readers that compared `receiptAuthority() === false` now call it and let it throw (or catch where the reader already returns `false`): before-tool-call decision receipt, cron tool, sessions access, terminal tool, session event target, node skill runtime, delegated approval, skill authoring, question broker, plugin hooks, cron management/owner bindings, harness host source and embedded tool authority.
- The "no delegated run" receipt `() => false` becomes a throw with the same message the boolean path already produced ("agent tool caller authority is no longer active").

Production: 17 files, +55/−173 (plus one session-identity allowlist entry pruned: `cron-tool.ts` lost its "no longer active" refusal string). No new export, name, hook, flag, guard, timer or state.

## Tests

- **Deleted (obsolete):** `mcp-http.test.ts` "fences caller authority when the grant is replaced during tool execution". It asserts that a started MCP tool call is refused at its commit after the grant row is replaced mid-call, i.e. the mid-call permission re-check this PR removes. Replacement is still refused at the next dispatch.
- About 60 test fixtures returned `false` from `receiptAuthority` to mean "run closed / revoked" (`() => validateAgentRunDelegatedAuthority(a)`, `() => current`, `() => !signal.aborted`, `() => false`). TypeScript accepts `() => boolean` as `() => void`, so these would silently stop refusing. Each now throws on the same condition (or uses `signal.throwIfAborted()`), so every refusal test keeps its meaning. Assertions on the boolean (`receiptAuthority()).toBe(false)`) became `toThrow`. The `hooks.before-tool-call.test.ts` "authority reports stale" row is gone (no boolean to report); both settlements now run with a throwing authority.
- `server.visible-spawn-fallback.product-proof.test.ts` no longer passes `currentGrant.isCurrent` as a receipt, matching production `mcp-http.ts`.
- Run-instance, claim, disconnect and stale-writer refusal tests keep their assertions. Two only changed the expected wording, because the refusal now comes from the run's own assertion instead of the deleted receipt wrapper: `session-event-handoff.test.ts` "rejects invocation retirement" (`no longer owns its invocation` → `no longer active`) and the retained-receipt check in `tool-authority.runtime.retention.test-support.ts` (`=== false` → throws).

## What users see

A tool call already running through a CLI (MCP loopback) or a subagent settle turn finishes when the grant or batch is replaced mid-call. The next call is refused before it starts, as before. Stop still cancels a running call. Error text for a closed run inside some tools (terminal, skill authoring, session events) now comes from the run's own assertion instead of the caller-specific wording.

## Evidence

- **Typecheck / lint / ratchets:** `pnpm tsgo:core`, `pnpm tsgo:test` clean on the head; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK, session-identity ratchet OK (after prune).
- **Tests (pre-push):** importer set of every changed source and test-support file (816 files) with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`, run in lanes (the runner aborted once on a vitest resource-claim error after the gateway lanes, so the rest ran in a second call), then a focused rerun of every repaired file and a post-merge rerun after merging `main` for a ratchet-list conflict with #203847. Remaining reds, all not ours: red on the base locally (`dd56cf3d6457` / `49795c31df01`): `slack-download-read-authority` (claim at result), `github-pr-workspace-preparation`, `server.sessions.create.{durability,lifecycle,projects}`, `sessions-create-device-folder`, `provider-destroy-authority`, `service.pr-automation{,-feedback}`, `openclaw-tools.subagents.sessions-spawn.lifecycle`, `mcp-http.personal-authority`; known main reds from #203664/#203590/#203516: `server-cron-failure-repair.final-effect`, `cron.scheduled-policy-adoption`, `github-publication-imported-actions`, `question.communication`/`.recovery`, `mcp-http.async-scope`, `agent.test`, `plugin-reload-send-revocation.product`.
- **Local ClawSweeper review** on exact head `eb077c177329`: `review_status: complete`, "patch is correct", 0 findings.
- **One-admission E2E** (isolated Gateway, real model, exact head `eb077c177329`, `ocx build --dist`): `pass: true`. `results.jsonl` (28 rows) kept with the task proof. `verdict.json` checks:
  ```json
  [{"id":"R.running-turn-finishes","pass":true,"detail":{"state":"final","toolEnds":3,"toolEndsAfterRevoke":3}},{"id":"Q.queued-input-refused-visibly","pass":true,"detail":{"accepted":true,"providerRequestsWithQueuedMarker":0,"visibleRefusalInTranscript":true}},{"id":"S.stop-cancels","pass":true,"detail":{"abort":{"ok":true,"aborted":true},"state":"aborted","requestsWithStopMarker":1}}]
  ```

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…registry (openclaw#203516)

## What Problem This Solves

openclaw#203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call; it now only checks Stop and carries the caller receipt's session fences. The `sessions_*` tools and the subagent registry still captured it and called it again at each step. Those calls are dead weight. Some of them also used "the capture returned a function" to mean "this is an admitted agent run".

## Why This Change Was Made

Admission checks permission one time, when work starts. This PR removes the leftover capture from the session tools and the subagent registry:

- `sessions-list-tool.ts`: the capture and its call in `finalize`; the tool signal check stays.
- `sessions-tool.ts` (`assign_owner`), `sessions-tool-control.ts` (`captureSessionStopCaller`, `stopSessionTool`): the admitted-run gate reads `caller.operationalRunInstance`, which is the condition the capture tested. The tool signal check stays at each step.
- `sessions-operator-authority.ts`: the `sessions.patch` capture is removed from the composed control source.
- `sessions-send-communication.ts`: the capture is removed from `assertSource`, which already checks the tool call's `signal` and closes on abort. The approval gate reads `caller.operationalRunInstance`.
- `sessions-send-tool.delivery.ts`, `sessions-send-tool.steering.ts`: the steering guard still uses the guarded (V2) injection for an admitted run. Stop reaches it through `assertSendCurrent` (the communication assertion, which is signal-bound).
- `sessions-send-followup.ts`, `sessions-send-followup-custody.ts`: the follow-up checks are the prepared custody (`request.custody.assertCurrent`) only.
- `sessions-send-resume.ts`, `gateway/session-subagent-resume.ts`: a live admitted caller has no `assertCurrent`. A host-retained replay keeps its retained source assertion. `requirePausedChild` runs `caller.assertCurrent?.()`; admission is decided once in `captureSessionsSendResumeCaller` (the only producer of this caller).
- `subagent-registry-public-api.ts`, `subagent-registry-requester-claim.ts`: the registry writes keep the state-worker source check and the continuation custody.

Session write fences are not dropped. Every sessions tool write goes through the in-process Gateway caller (`in-process-gateway.ts`, PR 1d), which still composes the caller's receipt into `sessionMutationCommitGuard`. The removed captures were all sync closures (Stop only) or duplicated that composed fence.

No new export, name, hook, flag or guard. Production: 13 files, +43 / −108.

Accepted edge cases (no code for them):

- `acknowledgeSubagentResultForRequesterTurn` and `claimSubagentYield` no longer check Stop before their registry write. These are internal bookkeeping writes for a result the run already has (mark delivered, record the yield), not user-visible effects.
- `prepareSessionsSendFollowup` no longer checks the tool Stop during its preparation reads. The dispatch that follows stays signal-fenced through the communication assertion.

### Changed tests

- `sessions-tool.self-archive.test.ts`, `agent-tools.session-owner.test.ts`: `sessions.assignOwner` no longer carries `assertDispatchCurrent`.
- `sessions-send-communication.test.ts`: the mocked caller now has an `operationalRunInstance` (that is what "admitted" means now); the removed capture mock is gone.

No test asserted a mid-run refusal through these callers, so no test was deleted.

## User Impact

None visible. An admitted session tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict.

## Evidence

- Pre-push: one `ocx test` run with fail-fast off over 41 files (every direct importer of a changed source, plus importers of the test-support files that import them). After the test fixes, everything is green except:
  - `agent.test.ts` ("honors owner cancellation while explicit recipient session routing is pending", "does not deliver prepared identity after the client loses authority") and `question.communication.test.ts` ("retains creator/admin rights without treating assigned responsibility as authority"): also red on the merge base `e7aeeb39c145`.
  - `server.plugin-reload-send-revocation.product.test.ts`: it expects "Operator access was revoked; start a new user turn.", which no production code emits since openclaw#202513. On head the revoked replay is still refused with 0 effects; the notice says "Restart recovery operator authority changed; start a new user turn.". On the base it timed out under host load.
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean.
- Head E2E: Q, R and S pass (openclaw#203516 (comment)). Local review on the final head: patch correct, zero findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…law#203551)

## What Problem This Solves

Fixes openclaw#203512. Since openclaw#203487, Stop does not cancel an MCP loopback tool call from a CLI-backed turn (Claude CLI and other CLI runtimes). If the user stops the turn while a message action waits on a channel lookup, the action still finishes: `test/cli-message-authority.integration.test.ts > stops the reaction lookup after abort retirement` gets `isError: false`.

## Why

The MCP loopback server rebuilds the tool caller from the CLI grant (`src/gateway/mcp-http.ts`). That caller had no `approvalSignals`. The turn's abort signal reached the tool only through the receipt boolean `isGrantAndLineageCurrent` → `isMcpLoopbackClientGrantCurrent`. That boolean also checks the grant row, the admitted run's delegated authority and the capture, so it mixes run lifecycle with permission. openclaw#203487 removed the synchronous receipt boolean from `captureGatewayToolCallerAssertion` as an authority re-check. Stop was lost with it.

## Fix

- `resolveMcpLoopbackClientGrant` now returns the grant's existing `abortSignal`, which is the CLI turn's abort signal. The MCP caller passes it as `approvalSignals`, the lifecycle channel that `captureGatewayToolCallerAssertion` already checks. The permission part of the receipt stays out of the synchronous check, as openclaw#203487 intended.
- Removed: the MCP `cronAuthorityCheck` pass-through (grant field, mint copy, resolved field, caller field) and `bindActiveCronAuthorityCurrentness`. openclaw#203487 removed the only reader of the identity `cronAuthorityCheck`, so this chain had no reader left.
- No new export, name, flag or guard. Production: +3 / −17.

## Sweep of openclaw#203487, openclaw#203503 and openclaw#203516

- I traced every production caller that sets `receiptAuthority` (`agent-tools.caller`, embedded `attempt-gateway-tools`, `settled-turn-finalization`, harness `tool-authority.runtime`, `plugin-native-subagent`, `scheduled-owner-tool-guard`, `cron-tool`, `node-claude-skill-runtime`, worker `placement-turn-claim-events` and `worker-turn-tool-surface`, plugin `hooks`). Each one still delivers Stop through `approvalSignals` or through the tool's own execute signal. The MCP loopback was the only caller where the receipt carried Stop alone.
- The 1b and 1c call sites run inside in-process Gateway dispatch. That dispatch still runs the caller assertion (`in-process-gateway.ts`, `server-plugin-in-process-authority.ts`), or the tool's own signal covers them. No other instance was found, so this PR has one fix and one test.

## User Impact

When you stop a CLI-backed turn, a running message action is cancelled before its write. The tool result reads "The message turn has ended. Start a new turn to retry." A permission change in the middle of a call still does not interrupt a started call (openclaw#203487).

## Tests

- `test/cli-message-authority.integration.test.ts` "stops the reaction lookup after abort retirement": red on main (`isError: false`). Green on head, with no PATCH or PUT after Stop. The expected text is now the message route's "message turn has ended". Before openclaw#203487 the text was the generic "authority is no longer active", which openclaw#203487 removed.
- `test/cron-message-read.integration.test.ts` (claude-cli, disabled before 429): Stop now reaches the tool, so the result text is the message route's "message turn has ended". The regex now accepts it. The single PATCH and the absent retry are unchanged.
- `cron-creator-authority-context.test.ts`: the two lines that read the deleted helper are removed. The revocation assertion on the creator stays.

## Evidence

- Pre-push: one `ocx test` run with fail-fast off over the touched tests and every test importing a changed file (60 files). Green except `mcp-http.async-scope` "keeps each CLI grant's own ceiling" and `cron.scheduled-policy-adoption.integration` ×3, both red on main before this PR (see openclaw#203503 override), plus `cron-message-read` (updated above, then green 9/9).
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean.
- Real Gateway E2E on the final head `7e1c3b07ffde`: R, Q and S (Stop → cancels) pass (openclaw#203551 (comment); first head: #issuecomment-7081968622).
- Local review on the final head `7e1c3b07ffde`: patch correct, zero findings.
- Session-identity allowlist: `cron-creator-authority-context.ts` shrinks from 41 to 39.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…penclaw#203561)

## What Problem This Solves

openclaw#203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call. Its synchronous call now only checks Stop (`approvalSignals`); its prepared form carries the caller receipt's session fences. Agent-side callers still captured it just to call it synchronously, and some used "the capture returned a function" to mean "this is an admitted agent run".

## Why This Change Was Made

Admission checks permission one time, when work starts. This PR removes the capture where it was only a synchronous Stop check:

- `agent-tools.before-tool-call.approval.ts`, `bash-tools.exec-approval-request.ts`, `harness/gateway-question.ts`, `tools/agents-wait-tool.ts`: the capture only fed watchdog `isCurrent` callbacks. They keep their tool/request signal check where they had one. Exec approval has no signal in scope; its watchdog wait ends with the run's attempt, and the approval wait ends with `run-aborted`.
- `openclaw-plugin-tools.ts` (node MCP elicitation): the gate is `caller.operationalRunInstance`; Stop is the same signal the elicitation registers with (tool signal + caller `approvalSignals`).
- `tools/computer-tool-bindings.ts`: the gate is the existing `operationalRunInstance` check; Stop is `params.signal` / `request.signal`.
- `tools/personal-instructions-tool.ts`, `tools/presence-tool-authority.ts`: the gate reads `caller.operationalRunInstance`; personal instructions checks the tool signal.

**Kept on purpose (cut less):** where the capture is composed into a session source assertion or passed whole as one, it still carries the receipt's prepared session fence to the write. The brief says that fence must not be dropped, so these stay unchanged:

- `tools/in-process-gateway.ts`: composes it into `sessionMutationCommitGuard` for every in-process Gateway write (openclaw#203516).
- `tools/message-tool-execution.ts` / `message-tool-turn-authority.ts`, `tools/media-generate-background-shared.ts`, `tools/agent-step.ts`, and plugin tool `assertInvocationCurrent` in `openclaw-plugin-tools.ts`.

Replacing the capture with `captureGatewayToolReceiptAssertion` would bring back the "agent tool caller authority is no longer active" refusal on the synchronous path, and copying the 1a body would make a second implementation (Fable 5.2 consult: keep the carrier). PR 1e, when it deletes the declaration, must move the body to the remaining fence carriers as one implementation.

No new export, name, hook, flag or guard. Production: 8 files, +30 / −69.

Accepted edge case (no code for it): exec approval's watchdog `isCurrent` no longer checks Stop itself (no signal in scope); Stop still ends the run's watchdog attempt and the approval wait.

### Changed tests

None. No test asserted a mid-run refusal through the removed calls.

## User Impact

None visible. A started agent tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict.

## Evidence

- Pre-push: one `ocx test` run, fail-fast off, over 146 files (direct importers of every changed source, importers of test-support files that import them, and every test that names `captureGatewayToolCallerAssertion`), then the repaired and re-touched set (37 files) again on the final tree. Green except:
  - `slack-download-read-authority.integration.test.ts` "rejects revoked output ... after result (revoke: claim)": also red on the merge base `120fd2984e02` (run there with `ocx test`); not this PR.
- `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. `check:lifetime-check-ratchet`: OK, no growth. `check:changed` SQLite worker ratchet OOMs locally on its 4 GB heap (known, whole-repo scan); CI covers it.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…ttle-batch receipts (openclaw#203892)

## Problem

R2 of the one-admission receipt cluster. After openclaw#203760 (R1c), two receipt producers still returned a boolean, and the receipt boolean itself (`ReceiptAuthority = () => boolean | void`, the `composeReceiptAuthority` check loop, `assertAllowed` in `captureGatewayToolReceiptAssertion`) still hid permission re-checks from the lifetime-check ratchet:

- **MCP loopback grant receipt** (`mcp-http.ts`, `isGrantAndLineageCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the CLI grant row and the requester lineage.
- **Settle-batch receipt** (`agent-tools.caller.ts`, `settleBatch.isCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the subagent settle batch.

Both answer "may this requester still act?" in the middle of a call. R1c showed that turning them into throws is a new mid-request re-check (both ratchets went red), so they are deleted.

## Change

- **Deleted** the MCP grant receipt and the settle-batch receipt. The grant row and lineage are still checked once at each tool-call dispatch (`authorizeToolCall`); the settle batch is still checked at handoff admission (`subagent-announce-handoff.ts`). Stop still reaches the call through the grant's `abortSignal` and the run signal.
- **Deleted the receipt boolean:** the `ReceiptAuthority` type, the boolean check loop in `composeReceiptAuthority`, `captureGatewayToolReceiptAssertion` (and its lifetime-ratchet entry), and the `approvalAuthorityCheck` field (a duplicate of the receipt). `receiptAuthority` is now a plain `SessionSourceAssertion`: it throws or returns. `composeReceiptAuthority` only de-duplicates sources into `composeSessionSourceAssertion` and keeps its existing `assertScopeCurrent` forwarding.
- Readers that compared `receiptAuthority() === false` now call it and let it throw (or catch where the reader already returns `false`): before-tool-call decision receipt, cron tool, sessions access, terminal tool, session event target, node skill runtime, delegated approval, skill authoring, question broker, plugin hooks, cron management/owner bindings, harness host source and embedded tool authority.
- The "no delegated run" receipt `() => false` becomes a throw with the same message the boolean path already produced ("agent tool caller authority is no longer active").

Production: 17 files, +55/−173 (plus one session-identity allowlist entry pruned: `cron-tool.ts` lost its "no longer active" refusal string). No new export, name, hook, flag, guard, timer or state.

## Tests

- **Deleted (obsolete):** `mcp-http.test.ts` "fences caller authority when the grant is replaced during tool execution". It asserts that a started MCP tool call is refused at its commit after the grant row is replaced mid-call, i.e. the mid-call permission re-check this PR removes. Replacement is still refused at the next dispatch.
- About 60 test fixtures returned `false` from `receiptAuthority` to mean "run closed / revoked" (`() => validateAgentRunDelegatedAuthority(a)`, `() => current`, `() => !signal.aborted`, `() => false`). TypeScript accepts `() => boolean` as `() => void`, so these would silently stop refusing. Each now throws on the same condition (or uses `signal.throwIfAborted()`), so every refusal test keeps its meaning. Assertions on the boolean (`receiptAuthority()).toBe(false)`) became `toThrow`. The `hooks.before-tool-call.test.ts` "authority reports stale" row is gone (no boolean to report); both settlements now run with a throwing authority.
- `server.visible-spawn-fallback.product-proof.test.ts` no longer passes `currentGrant.isCurrent` as a receipt, matching production `mcp-http.ts`.
- Run-instance, claim, disconnect and stale-writer refusal tests keep their assertions. Two only changed the expected wording, because the refusal now comes from the run's own assertion instead of the deleted receipt wrapper: `session-event-handoff.test.ts` "rejects invocation retirement" (`no longer owns its invocation` → `no longer active`) and the retained-receipt check in `tool-authority.runtime.retention.test-support.ts` (`=== false` → throws).

## What users see

A tool call already running through a CLI (MCP loopback) or a subagent settle turn finishes when the grant or batch is replaced mid-call. The next call is refused before it starts, as before. Stop still cancels a running call. Error text for a closed run inside some tools (terminal, skill authoring, session events) now comes from the run's own assertion instead of the caller-specific wording.

## Evidence

- **Typecheck / lint / ratchets:** `pnpm tsgo:core`, `pnpm tsgo:test` clean on the head; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK, session-identity ratchet OK (after prune).
- **Tests (pre-push):** importer set of every changed source and test-support file (816 files) with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`, run in lanes (the runner aborted once on a vitest resource-claim error after the gateway lanes, so the rest ran in a second call), then a focused rerun of every repaired file and a post-merge rerun after merging `main` for a ratchet-list conflict with openclaw#203847. Remaining reds, all not ours: red on the base locally (`d6b84a4c90a1` / `2f6261e2a4ec`): `slack-download-read-authority` (claim at result), `github-pr-workspace-preparation`, `server.sessions.create.{durability,lifecycle,projects}`, `sessions-create-device-folder`, `provider-destroy-authority`, `service.pr-automation{,-feedback}`, `openclaw-tools.subagents.sessions-spawn.lifecycle`, `mcp-http.personal-authority`; known main reds from openclaw#203664/openclaw#203590/openclaw#203516: `server-cron-failure-repair.final-effect`, `cron.scheduled-policy-adoption`, `github-publication-imported-actions`, `question.communication`/`.recovery`, `mcp-http.async-scope`, `agent.test`, `plugin-reload-send-revocation.product`.
- **Local ClawSweeper review** on exact head `eb077c177329`: `review_status: complete`, "patch is correct", 0 findings.
- **One-admission E2E** (isolated Gateway, real model, exact head `eb077c177329`, `ocx build --dist`): `pass: true`. `results.jsonl` (28 rows) kept with the task proof. `verdict.json` checks:
  ```json
  [{"id":"R.running-turn-finishes","pass":true,"detail":{"state":"final","toolEnds":3,"toolEndsAfterRevoke":3}},{"id":"Q.queued-input-refused-visibly","pass":true,"detail":{"accepted":true,"providerRequestsWithQueuedMarker":0,"visibleRefusalInTranscript":true}},{"id":"S.stop-cancels","pass":true,"detail":{"abort":{"ok":true,"aborted":true},"state":"aborted","requestsWithStopMarker":1}}]
  ```

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus pushed a commit that referenced this pull request Nov 23, 2026
…anded policy

Three more test files fail on main but are not selected by main push CI:

- doctor-health.legacy-update: the notification heartbeat-owner variants
  expected the 10th failure to auto-disable the job and send a safety
  notice. #203106 (8bdaed5) removed run-failure auto-disable, so
  Doctor now settles the interrupted run and the job keeps its schedule.
- auth-api-key: asserted a mid-request requester-revocation refusal that
  one-time admission retired (#203516, cc7b482).
- server.sessions.create.projects: the repository-child revocation phases
  asserted the same retired refusal; keep the parent-reassigned data fence.
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Release adaptation: extract the independent mixed-requester repair and its queue regression. Stable already strips display/owner flags but copies requester origin and the private owner capability. The wider saved-requester cutover needs the newer fixed-request and Cron occurrence authorities and the durable queue owner; do not replace the stable custody or restart contract.

Companions: #203468 and #203521 are separate selected start-grant repairs. #201334, #201377, #200533 and #202318 are missing full-cutover prerequisites; #203516, #202522 and #202520 are later distinct lifetime refactors, not needed by the isolated mixed-requester repair.

(cherry picked from commit 3ad2cce)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a26e1e7b02425b94d31c3e6bc6add8d417dc3fda)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. security-sensitive-changed size: S 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