Skip to content

refactor(agents): delete the receipt boolean and the MCP grant and settle-batch receipts - #203892

Merged
obviyus merged 3 commits into
mainfrom
refactor/receipt-boolean-removal
Nov 23, 2026
Merged

obviyus merged 3 commits into
mainfrom
refactor/receipt-boolean-removal

Conversation

@obviyus

@obviyus obviyus commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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 refactor(gateway): check runtime and HTTP authority once at request start #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 refactor(agents): drop authority reads from the admitted-run receipt body #203664/refactor(gateway): check HTTP request authority once at admission #203590/refactor: drop tool-caller re-checks from session tools and subagent registry #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:
    [{"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}}]

obviyus and others added 3 commits November 23, 2026 08:29
…ttle-batch receipts

Receipt authority is now a plain session-source assertion: it throws or
returns. Delete captureGatewayToolReceiptAssertion, the boolean
composeReceiptAuthority loop, approvalAuthorityCheck, and the MCP grant and
settle-batch receipts that re-checked permission inside a started tool call.
Dispatch-time checks and Stop are unchanged.

Co-authored-by: obviyus <[email protected]>
…ean-removal

# Conflicts:
#	scripts/check-lifetime-check-ratchet.mts
@clawsweeper

clawsweeper Bot commented Nov 23, 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 scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 23, 2026
@github-actions

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: eb077c177329abbccb443f87eaf13a933c7aced2
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/cron-creator-authority-context.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/harness/host-source-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/harness/tool-authority.runtime.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/gateway/skill-library-authoring.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
@clawsweeper

clawsweeper Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes MCP grant and settle-batch receipt rechecks and converts remaining receipt consumers from boolean results to throwing assertions.

Example: An MCP tool call starts with a valid CLI grant, then that grant is replaced while the call awaits work.

  • Before: The receipt can refuse the already-started call at its effect boundary.
  • After: Grant replacement no longer refuses that call through its receipt; subsequent dispatch still checks the grant, and Stop retains its cancellation path.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The source change is focused and no introduced defect was found, but supplied runtime coverage does not establish the specific changed paths and current CI failures lack complete independent attribution.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: An accepted tool call can lose its work when a grant or settle batch changes while the call is running.
Reason: The maintainer-authored direction is also explicitly recorded in the merged predecessor and matches the repository's admission contract.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR completes an explicitly planned simplification of tool-call authority; source review found no actionable introduced defect.

Priority: P2
Reviewed head: eb077c177329abbccb443f87eaf13a933c7aced2

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted runtime output identifying MCP grant replacement and settle-batch replacement through their shipped paths, with admitted-call completion, subsequent-call admission behavior, and Stop cancellation.
Agent review details

How this fits together

Gateway and agent wrappers attach admitted caller identity to tool execution; dispatch checks permission, while source assertions carry lifecycle and storage fences to downstream effects.

flowchart TD
  A[CLI or settle continuation] --> B[Dispatch or handoff admission]
  B --> C[Admitted caller identity]
  C --> D[Tool execution]
  D --> E[Source and storage assertions]
  E --> F[Tool effect]
  G[Stop signal] --> D
Loading

Technical review

Best possible solution:

Keep admission with the existing dispatch owners and use the existing source-assertion composer for retained lifecycle and storage fences.

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

Current-main source shows both callbacks feeding the receipt composer, allowing grant or batch changes to refuse effects after admission; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch follows the recorded direction and is a focused deletion using existing owners; migrated consumers preserve throwing refusal, prepared source handling, and cancellation without adding parallel machinery.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Receipt composition and prepared-source adaptation changes intended behavior with a stated reason (a51a76b: Preserve prepared receipt metadata, false refusal, prototype-backed fields, method receivers, and cleanup through caller and harness wrappers.)
  • Settle-batch receipt changes intended behavior with a stated reason (27de2f8: Restore requester tools after children settle while binding continuation policy to the exact requester and batch, including a final-effect recheck.)
  • MCP grant receipt changes intended behavior with a stated reason (unknown: Base source requires grant and requester lineage currentness at dispatch and effects; the exact introducing commit remained unresolved in the partial history, while the merged predecessor explicitly authorizes deleting the effect receipt.)
  • Terminal input authority keeps the original intent (3626a8e: Bind PTY input to effective execution permission, exact run, Gateway, terminal ownership, and approval; this patch changes receipt refusal representation while retaining those checks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit adb2f7c adds src/agents/tools/gateway-caller-context.ts:449 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: adb2f7c4d4bc; files: src/agents/tools/gateway-caller-context.ts)
  • Peter Steinberger: Raw commit 7f232d4 adds src/agents/tools/gateway-caller-context.ts:376 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7f232d4e6421; files: src/agents/tools/gateway-caller-context.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

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: This addresses interrupted admitted tool calls on limited MCP and settle-continuation paths without evidence of an urgent outage.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This addresses interrupted admitted tool calls on limited MCP and settle-continuation paths without evidence of an urgent outage.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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:30 PM ET / November 23, 2026, 03:30 UTC.

@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: every red job on head eb077c177329 fails the same tests on the merge base 49795c31df01 (current main), run locally with ocx test on a clean base checkout. main CI is green only because its changed-lane jobs do not select these files.

ci-triage 203892 (tags OURS because the main run skipped these files):

checks-node-changed-compact-large-17	src/gateway/github-publication-imported-actions.test.ts	OURS
checks-node-changed-compact-large-19	src/gateway/mcp-http.personal-authority.test.ts	OURS
checks-node-changed-compact-large-31	src/gateway/server-cron-failure-repair.final-effect.test.ts	OURS
checks-node-changed-compact-large-33	src/gateway/mcp-http.async-scope.test.ts	OURS
checks-node-changed-compact-large-41-1	src/gateway/server-methods/question.recovery.test.ts	OURS
checks-node-changed-compact-large-41-2	src/gateway/server-methods/question.communication.test.ts	OURS
checks-node-changed-compact-large-45-1	src/gateway/server-methods/agent.test.ts	OURS

Base 49795c31df01 results (same tests, same failures):

  • github-publication-imported-actions.test.ts: 3 failed ("rechecks explicit edit/request_review target requester … before the write")
  • mcp-http.personal-authority.test.ts: 2 failed (expected 500 to be 401)
  • server-cron-failure-repair.final-effect.test.ts: 11 failed | 1 passed
  • mcp-http.async-scope.test.ts: 1 failed ("keeps each CLI grant's own ceiling and liveness …")
  • question.recovery.test.ts: 1 failed ("denies a stopped observer's local response …")
  • question.communication.test.ts: 1 failed ("retains creator/admin rights …")
  • agent.test.ts: 2 failed ("does not deliver prepared identity …", "honors owner cancellation …")

These were also listed as main reds in #203664, #203590, #203516 and #203551. Not caused by this PR; landing with the override.

@obviyus
obviyus merged commit 096214a into main Nov 23, 2026
171 of 180 checks passed
@obviyus
obviyus deleted the refactor/receipt-boolean-removal branch November 23, 2026 03:39
@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 096214a. The receipt boolean is gone: receiptAuthority is now a plain session-source assertion that throws or returns, and the MCP grant and settle-batch receipts no longer re-check permission inside a started tool call. Dispatch-time checks and Stop are unchanged. Proof: local review clean, one-admission E2E Q/R/S pass on the exact head, every CI red reproduced on base (override above).

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 added a commit that referenced this pull request Nov 23, 2026
…op-only tool-caller captures (#203920)

## Problem

R3+R4 of the one-admission receipt cluster: delete the last two names in `LIFETIME_CHECK_CALLS`, `captureAdmittedRunActiveAssertion` and `captureGatewayToolCallerAssertion`. After R1, R1b, R1c and R2 (#203664, #203788, #203760, #203892) neither body reads authority. What is left is Stop and session data fences.

## Change

**Cut less (Fable 5.2 consult, option C).** This PR deletes `captureAdmittedRunActiveAssertion` and the 2 Stop-only sites of `captureGatewayToolCallerAssertion`. The ratchet keeps one name.

- `captureAdmittedRunActiveAssertion` is deleted. Its body (Stop on the run signal, run occurrence, `foregroundClosed`, registry claim and the run's registry session source) moves into `resolveAdmittedRunActiveAssertion`, which already wrapped it and already has ~50 callers. The 4 other callers (`runWithPreparedRunSourceScope`, `prepareAgentRunAdmission`, `bindHarnessHostSourceAuthority`, `createAdmittedGatewayToolCallerIdentity`) call `resolveAdmittedRunActiveAssertion(context)`. Each passed the lease's own root authority, so the result is the same. `bindHarnessHostSourceAuthority` loses its now-unused `delegatedAuthority` parameter.
- `captureGatewayToolCallerAssertion`, the 2 Stop-only sites: the plugin tool `assertInvocationCurrent` (`openclaw-plugin-tools.ts`) and `prepareGatewayToolCallerAssertion` now call `throwIfAborted()` on the caller's own `approvalSignals`. Both used only the synchronous call, which was Stop-only. The plugin factory context wraps the check in a closure, so the receipt's prepared properties never reached a write.
- `LIFETIME_CHECK_CALLS` now holds only `captureGatewayToolCallerAssertion`.

Production: 6 files, +24/−44. No new export, `capture*` name, hook, flag, guard, timer or state. Behavior is unchanged.

## What is left, and why it was not cut here

I removed `captureAdmittedRunActiveAssertion` and 2 of the 9 tool-caller calls. The other 7 calls (6 files) still need the "prepared-only receipt" shape. I did not patch them.

These sites compose the capture as a session source: the in-process Gateway dispatch and commit guard (`in-process-gateway.ts` ×2), media launch admission (`media-generate-background-shared.ts`), `agent-step.ts`, `operator-invocation-authority.ts`, `server-plugin-in-process-authority.ts` and the message tool (`message-tool-execution.ts`). The capture's synchronous call is Stop-only, and its prepared session-source properties carry the receipt's data fences. Detached work calls the synchronous check after the run closed. For example, media background `run` calls `assertAdmissionCurrent()` before the provider call.

- Passing `caller.receiptAuthority` directly would also run the receipt's fences (including `foregroundClosed`) on those synchronous calls. Background media and other detached work would then be refused after the run closes, which is lost work. It would also reverse the edge case accepted in #203487.
- Copying the "sync no-op, prepared = receipt" idiom into 7 producers removes the name, not the concept.

**Proposed follow-up:** move "prepared-only source" into the `composeSessionSourceAssertion` owner as a relocation of the existing shape, then delete the last name and empty the list. If that needs a new flag or parameter on the composer, that cut is wrong too.

## What users see

Nothing changes. Stop still cancels, and stale-writer, generation and run-occurrence refusals are unchanged.

## Evidence

- **Stop proof on both changed tool-caller paths (new tests):** `openclaw-plugin-tools.stop.test.ts`: a plugin tool's `assertInvocationCurrent` passes, then throws the Stop reason after the run signal aborts. `gateway-caller-context.test.ts` "lets Stop on the caller refuse a prepared watch admission": same for `prepareGatewayToolCallerAssertion`. The admitted-run path keeps `signal?.aborted` → refuse unchanged.
- **Tests (pre-push):** the importer set is 554 files, over the 150 cap, so CI runs it. Locally, one `ocx test` call with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1` on 67 files: every test that names `resolveAdmittedRunActiveAssertion`, `runWithPreparedRunSourceScope`, `bindHarnessHostSourceAuthority` or the refusal string, plus the admitted-run, harness host, plugin-tools, gateway-caller-context, sessions-send-followup and ratchet tests. All green, including stale-writer, generation and occurrence tests (unedited).
- **Typecheck / lint / ratchet:** `pnpm tsgo:core`, `pnpm tsgo:test` clean; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK.
- **One-admission E2E** on exact head `1b9812f6114c`: `pass: true`, R/Q/S all pass (#203920 (comment)).
- **Local ClawSweeper review** on `1b9812f6114c`: complete, patch is correct, 0 findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…203176)

## Problem

A requester that calls `sessions_yield` after spawning several completion-mode subagents was woken only when every member of the frozen yield batch was ready. A sibling that keeps running, or that pauses on its own `sessions_yield` while a background command runs, held every finished result back.

Production incident (2026-11-21): a dashboard parent spawned 3 children and yielded at 16:20 IST. Two children finished at 16:26:58 and 16:29:41 with reports that needed a decision. The third kept cycling through exec-yield and resume. The Gateway log has no `announce:requester-settle:…` run for that parent. The parent ran again only at 18:32, when the user typed into the chat. A copy of the state database shows why: both finished rows were `terminal`/`ok` with `delivery.status: pending` and a pending `requesterSettleWake` (`batchRunIds` = all 3, `rearmGeneration: 1`). The third row was still `running`. The gate in `subagent-announce.requester-settle-wake.ts` returned `false` unless every frozen member passed `isRequesterSettleMemberReady`. #200967 had already made an exception for siblings that wait for a message. An exec-yielded or running sibling is the same bug class.

## Change

Rule: every ready result wakes the yielded parent. Siblings that are still working keep their wake, with the same `rearmGeneration`, and wake the parent again when they finish. Each result is delivered once.

- **Settle wake:** removed the all-or-nothing gate and the message-wait exception (`isEndedSubagentMessageWait` is deleted). The wake delivers the ready members of the frozen batch as one partition, and lists the members that are still working. A member whose partition has already started dispatch records its own batch, so a later partition never offers it again. When a partition holds only results that were already delivered and siblings are still pending, it settles without a redundant wake.
- **Wake message:** a partition that leaves members pending no longer says "every subagent has settled… do not call sessions_yield again". It names the siblings that are still working (label, task name or run ID, at most 5, each truncated) and tells the parent: if the request needs those results, call `sessions_yield` to wait; otherwise act on the ready results without reporting the batch as finished.
- **Lifecycle failure path:** `offeredBatch` now offers only ready members, so failure settlement can never consume the wake of a sibling that is still running or exec-yielded.
- **Yield transfer:** when a child ended before the yield and a sibling is still running, `afterRelease` now schedules the settle for the finished child. Before, nothing woke the parent until the sibling ended.
- **Followup owners** (`sessions_send` wait-for-reply, `agent-step`, nested `agent-run-subagent`): the caller is waiting for a single reply. Only the partition that leaves no member pending continues the followup. Earlier partitions wake the session as ordinary settle turns. `successor()` accepts that last partition as a subset of its cohort, so it no longer throws and records the result as a permanent failure.
- **Automation authority:** a yield that carried cron-management authority keeps it for the partition that leaves no member pending. Earlier partitions run without borrowing it, and settling them shrinks the retained cohort instead of discarding the authority.
- **Silent waits:** while siblings are still working, the parent may stay silent (`NO_REPLY`) and wait. Such a turn is not treated as a missing visible reply, so it is not retried.
- **Goal return:** an earlier partition leaves the Goal cohort when it settles. The partition that settles the cohort last resumes the Goal once.
- `isRequesterSettleMemberReady` moved to `subagent-run-liveness.ts`, its only owner, and replaces the deleted message-wait predicate.
- Docs: `tools/subagents/announce.md` and `concepts/subagent-yield-handoff.md`.

Product decisions, under the rules "no stranded user" and "no false done":
- A stopped child is a settled outcome, so its report now wakes the parent right away instead of waiting for its siblings.
- A followup caller gets one reply, after all results are in. The session itself is still woken for each result.

## Evidence

**Regression test** (`subagent-registry.requester-wake.e2e.test.ts`, real registry, lifecycle, yield tool and wake entry point): spawn 2 children, yield, finish one, keep the other exec-yielded. The parent is woken with the finished result, and the wake names the working sibling. The sibling's continuation then wakes the parent again with only its own result. A sweep adds no third wake. A second case covers a child that ended before the yield, while the requester's turn held it.
- Base `eb7ca3d33375`: both cases red (`expected [] to have a length of 1`: no wake).
- Head: both cases green.

**Owner tests:** cron authority (`requester-cron-authority.test.ts`: the early partition neither borrows nor consumes the authority, and the last partition is admitted with it), followup partition (`subagent-announce.requester-settle-followup.test.ts`: early partition runs with no followup successor, last partition carries it). Goal partition (`goal-continuation.test.ts`: early partition does not resume the Goal, last partition resumes it once).

**Updated tests that asserted the all-at-once rule:** `requester-settle-cross-turn` (paused member), `subagent-control.worker` progress card (one wake per result; the card retires once), `requester-wake-settlement` (stopped child).

**Real-Gateway E2E**, incident shape. Scratch `ocx src` Gateway under `env -i`, OpenAI `gpt-5.5` on the OpenClaw runtime. Parent spawns `alpha` (replies at once) and `beta` (`exec` with `background: true` running `sleep 90`, then `sessions_yield`), then yields.

| | alpha ended | first parent wake | beta yielded | beta ended | second parent wake |
|---|---|---|---|---|---|
| base | 19:47:10 | **19:48:53** (one combined run, after beta) | 19:47:13 | 19:48:50 | none |
| head | 19:40:08 | **19:40:11** (`announce:requester-settle:…:<alpha>:yield-1`) | 19:40:12 | 19:41:55 | 19:41:59 (`…:<beta>:yield-1`) |

The parent's replies on head were `alpha: ALPHA-RESULT-7`, then `alpha: ALPHA-RESULT-7 / beta: BETA-RESULT-9`. The live Peanutto launchd pid and `openclaw.json` hash did not change.

**Live sibling suites** (`subagent-yield-pause`, `subagent-followup-yield`, `subagent-yield-resume`, real OpenAI `gpt-5.5`): the same tests fail on base `eb7ca3d33375` and on this branch, with the same assertions (missing `completion.resultText` after a resumed or paused child completes, a Gateway shutdown timeout, an interim reply in the follow-up watch case; follow-up-yield failed 2 of 2 on base). One run of this branch showed a parent that wrote its final report as soon as the first result arrived; the wake message now says to keep waiting when the request needs the remaining results, and that failure no longer appears. The real-Gateway restart e2e files (`test/gateway-*-restart*.e2e.test.ts`) fail locally on base too (11 of 26 on base, 9 of 26 here, same assertions).

**Gates:** `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on the changed files. Every test file in `src/agents/subagents` and `goal-continuation.test.ts` was run across the unit-fast, infra, agents-support, spawn-boundary, core-isolated and e2e projects. Two infra tests failed once under host load and passed when run alone, on head and on base.

## Size

Production code is +96 / −56. The gate, the message-wait exception and its predicate are deleted. The added lines are the partition support the old gate did not need: pending members in the message, the followup last-partition rule, Goal cohort shrink, and pre-yield scheduling, and cron-authority cohort shrink. A census of `batchRunIds`, `requesterYieldBatch`, the frozen branch and `selectConnectedSettledSubagentWave` found every remaining reader still in use. v8 coverage could not attribute lines under the compiled-worker test runner (0 files collected in two attempts), so the census was done by reading the code.

## Accepted edge cases

- If a Goal cohort's last partition is rejected for an unrelated reason (for example, a rearm-generation mismatch), the Goal return stays retained until Stop or a lifecycle rotation. That is the same outcome as a failed final delivery today.
- A nested requester whose early partition answers without yielding reports that answer to its parent. The later result wakes it again as a separate completion.

## Merge danger

- **Two-way door.** No schema, stored-row or config change: the wake rows keep their existing fields and generation. A revert restores the all-at-once wake for every cohort, including rows written while this change ran.
- **Blast radius:** requesters that yield on two or more completion children (dashboard, chat and nested subagent requesters). A defect here would show as an extra or a missing wake for the parent, not as a lost child result: every result stays saved in its child session.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 09d956b)

Release adaptation: Kept stable QA Gateway fixture lifecycle; filtered intentionally silent partial-result wakes.

Companion audit: #203222 selected. #204249, #204069, #204048, #203892, #202513, #198960 not applicable (refactors/test cleanup); #204260, #204178, #204098, #204089, #203839, #203271 missing in lane and not prerequisites.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
(cherry picked from commit 9aae282)

Companions: #203551 propagates the owning turn's abort signal to in-flight approval work; it addresses a separate existing Stop behavior and is not needed for plugin generation readmission. #203892 changes receipt and authority ownership independently and is not applicable. Baseline has the same generation-only scope escape and lifecycle error classifiers.
Co-authored-by: VACInc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 24, 2026
…op-only tool-caller captures (openclaw#203920)

## Problem

R3+R4 of the one-admission receipt cluster: delete the last two names in `LIFETIME_CHECK_CALLS`, `captureAdmittedRunActiveAssertion` and `captureGatewayToolCallerAssertion`. After R1, R1b, R1c and R2 (openclaw#203664, openclaw#203788, openclaw#203760, openclaw#203892) neither body reads authority. What is left is Stop and session data fences.

## Change

**Cut less (Fable 5.2 consult, option C).** This PR deletes `captureAdmittedRunActiveAssertion` and the 2 Stop-only sites of `captureGatewayToolCallerAssertion`. The ratchet keeps one name.

- `captureAdmittedRunActiveAssertion` is deleted. Its body (Stop on the run signal, run occurrence, `foregroundClosed`, registry claim and the run's registry session source) moves into `resolveAdmittedRunActiveAssertion`, which already wrapped it and already has ~50 callers. The 4 other callers (`runWithPreparedRunSourceScope`, `prepareAgentRunAdmission`, `bindHarnessHostSourceAuthority`, `createAdmittedGatewayToolCallerIdentity`) call `resolveAdmittedRunActiveAssertion(context)`. Each passed the lease's own root authority, so the result is the same. `bindHarnessHostSourceAuthority` loses its now-unused `delegatedAuthority` parameter.
- `captureGatewayToolCallerAssertion`, the 2 Stop-only sites: the plugin tool `assertInvocationCurrent` (`openclaw-plugin-tools.ts`) and `prepareGatewayToolCallerAssertion` now call `throwIfAborted()` on the caller's own `approvalSignals`. Both used only the synchronous call, which was Stop-only. The plugin factory context wraps the check in a closure, so the receipt's prepared properties never reached a write.
- `LIFETIME_CHECK_CALLS` now holds only `captureGatewayToolCallerAssertion`.

Production: 6 files, +24/−44. No new export, `capture*` name, hook, flag, guard, timer or state. Behavior is unchanged.

## What is left, and why it was not cut here

I removed `captureAdmittedRunActiveAssertion` and 2 of the 9 tool-caller calls. The other 7 calls (6 files) still need the "prepared-only receipt" shape. I did not patch them.

These sites compose the capture as a session source: the in-process Gateway dispatch and commit guard (`in-process-gateway.ts` ×2), media launch admission (`media-generate-background-shared.ts`), `agent-step.ts`, `operator-invocation-authority.ts`, `server-plugin-in-process-authority.ts` and the message tool (`message-tool-execution.ts`). The capture's synchronous call is Stop-only, and its prepared session-source properties carry the receipt's data fences. Detached work calls the synchronous check after the run closed. For example, media background `run` calls `assertAdmissionCurrent()` before the provider call.

- Passing `caller.receiptAuthority` directly would also run the receipt's fences (including `foregroundClosed`) on those synchronous calls. Background media and other detached work would then be refused after the run closes, which is lost work. It would also reverse the edge case accepted in openclaw#203487.
- Copying the "sync no-op, prepared = receipt" idiom into 7 producers removes the name, not the concept.

**Proposed follow-up:** move "prepared-only source" into the `composeSessionSourceAssertion` owner as a relocation of the existing shape, then delete the last name and empty the list. If that needs a new flag or parameter on the composer, that cut is wrong too.

## What users see

Nothing changes. Stop still cancels, and stale-writer, generation and run-occurrence refusals are unchanged.

## Evidence

- **Stop proof on both changed tool-caller paths (new tests):** `openclaw-plugin-tools.stop.test.ts`: a plugin tool's `assertInvocationCurrent` passes, then throws the Stop reason after the run signal aborts. `gateway-caller-context.test.ts` "lets Stop on the caller refuse a prepared watch admission": same for `prepareGatewayToolCallerAssertion`. The admitted-run path keeps `signal?.aborted` → refuse unchanged.
- **Tests (pre-push):** the importer set is 554 files, over the 150 cap, so CI runs it. Locally, one `ocx test` call with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1` on 67 files: every test that names `resolveAdmittedRunActiveAssertion`, `runWithPreparedRunSourceScope`, `bindHarnessHostSourceAuthority` or the refusal string, plus the admitted-run, harness host, plugin-tools, gateway-caller-context, sessions-send-followup and ratchet tests. All green, including stale-writer, generation and occurrence tests (unedited).
- **Typecheck / lint / ratchet:** `pnpm tsgo:core`, `pnpm tsgo:test` clean; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK.
- **One-admission E2E** on exact head `1b9812f6114c`: `pass: true`, R/Q/S all pass (openclaw#203920 (comment)).
- **Local ClawSweeper review** on `1b9812f6114c`: complete, patch is correct, 0 findings.

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

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts security-sensitive-changed size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant