Skip to content

refactor(infra): prepare execution policy through workers - #169584

Merged
steipete merged 9 commits into
mainfrom
dbasync/t1cut-infra-exec
Oct 12, 2026
Merged

steipete merged 9 commits into
mainfrom
dbasync/t1cut-infra-exec

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Bundled exec-default, execution-guard, runtime-fact, node-host and operator-token paths still read SQLite synchronously on the Gateway thread. Repeated guard reads also reloaded policy already owned by this process.

User Impact

No intended user-visible behavior change. Execution policy and credential checks remain enforced before effects; bundled callers await preparation rather than blocking the Gateway thread. External synchronous SDK callers receive deprecation warnings and have documented async replacements.

Why This Change Was Made

Use the existing shared-state reader for preparation. The execution owner retains policy postimages from its existing write receipts and checks that policy synchronously at the actual command effect. Pending or uncertain writes fail closed; committed writes update the guard before the next execution. Migrate bundled consumers, including attached environment execution and worker tool preparation. The operator-token handshake awaits its existing credential owner before connection admission.

The public synchronous approval SDK readers remain deprecated for the current SDK major, with bounded warnings and documented asynchronous replacements. The deprecated external harness factory remains compatible. CLI audit, Doctor, and the native opaque approval compatibility transaction retain their existing owners. There is no schema, retention, durability, migration, or service-lifecycle change.

T1 inventory for exec-approvals-sqlite.ts: 3 → 3. The mixed kernels retain deprecated external SDK readers, CLI/Doctor one-shots, and the Gateway-native mintMcpToolGrantLocked call from operator-approval-store.transitions.ts. That call mints the durable MCP allow-always grant inside the winning approval-resolution transaction, preserving atomic approval/grant publication and the existing live security checks. Moving only its SQLite calls would split that security transaction. Its retirement requires moving the owning approval-resolution transaction into one worker operation; it is explicitly retained under the security/owner-redesign escape hatch. The deprecated SDK readers retire at the next SDK major. This PR moves the listed bundled preparation reads off MAIN, not every approval SQLite call, and does not misclassify these mixed kernels as worker-only. The staging-token call is reclassified as the existing snapshot admission/retirement lock primitive; no lock code changed.

Removed checks and accepted edges:

  • Repeated native approval reads at command checks: current in-process write receipts own policy freshness; external SQL writers must hold exclusive offline ownership.
  • Foreign direct-writer regression: unsupported concurrent external writers are outside the Gateway single-owner contract.
  • Unrelated lazy schema installation no longer revokes prepared execution authority through a repeated schema probe. Accepted edge: the schema owner publishes schema facts; execution authority changes only through policy receipts and live run authority.
  • Duplicate environment policy resolutions in one synchronous frame: use the policy already resolved for that check; changes after an await are checked again at dispatch.

Against the integrated base: production, docs and tooling +541 / −484 lines across 44 files; tests and test support +282 / −334 across 27 files. Total +823 / −818 across 71 files. Caller and fixture migration account for most additions; the superseded private direct-reader owner and its dedicated tests are deleted.

Evidence

Final candidate: 83698faee94a2ff1c478b6e2b243d21a4722beae. Integrated main: 230ea6864eb1407bbc79c78d906a28eb0acb8403. Live measurement remains pinned to the preceding candidate 25f563f06d6cfb9c753b318e8e741fcdbac6eb26 against 4de0aa6700755d4e7f3303633b7c757a9a2d9def. The final integration resolved only overlapping additions in SDK migration documentation, preserving both; the exec preparation and approval-owner implementations are unchanged from the measured candidate. The private synchronous direct-reader implementation is deleted after its last production caller moved to the worker-backed owner; pooled-reader regression coverage remains.

  • Codex autoreview: two implementation rounds completed. The authorized two-round cap is reached; no additional review is claimed for mechanical dead-code removal or conflict-only integration.
  • Basic local validation: changed-file oxfmt and oxlint, git diff --check, and normal commit hooks pass. No local test suites, broad scans, or typecheck were run for the final cleanup.
  • Final-head normal CI 38225104559 completed. Build, production types, all but the inherited core-4 test-type shard, changed-file lint, source contracts/export-collision guards, Madge (zero cycles), and baseline/T1/dialect ratchets passed. All selected test shards passed except the two inherited workspace-settlement fixtures below. Supplemental static CI 38225183665, pinned directly to the final head, passed every production/test-type shard including core-4, plus its lint/source/ratchet gates. Its fresh SDK report also passed, as detailed below.
  • Previous-head normal CI run 38212841432 passed builds, production/test types, changed-file lint, source contracts, Madge and baseline/T1/dialect ratchets. All selected tests passed except the two inherited fixtures documented below. The preceding run 38209894345 passed fully before the cleanup and main integration.
  • Final-head production Knip in the supplemental run reports only main-owned gateway-prewarm.mjs and renderPublicSessionCardSvg in src/gateway/control-ui-public-session-card-render.ts. The producer files, entry configuration, and scanner inputs are identical between integrated main and this head; this PR removed no references to either. The main issue is source-qualified inherited. That production failure short-circuits the final whole-tree all-export scan, which is therefore unrun, not green. Previous-head run 38213022936 passed production and all-export Knip; its all-export result is reused only for this PR’s unchanged exec API exports/callers. Between that candidate and final integration, the only overlapping source change moves background-completion wording after run creation in bash-tools.exec-run.ts; it removes no imports, exports, or callers. Incoming unrelated main exports are outside that reused proof. The previous full-tree unused-file scan also reported two unchanged boundary scripts; no fresh full-tree unused-file pass is claimed.
  • Fresh SDK API report passed in supplemental run 38225183665, comparing main b82b033920ee7a4df6323e3ee2b04ac8c6037fe0 with the actual CI merge 935c33628e5014d5e6dd64a62ff86f9fc41a43e1 containing this final head. It reports zero added/removed entrypoints and zero direct public export signature changes; 157 existing exports have reachable-declaration changes from the documented async additions. Report digest: e77d9a315c621d685d2b7fa1f66ff8a7601454542098b7f34854a0f2ee922059. The full report artifact is available in CI.
  • Runtime API guardrails and changed/mock-consuming suites passed in the previous-head normal PR CI. Earlier failed runs caught a missing awaited worker preparation, scope-abort authority, stale synchronous mocks and unregistered plugin owners; those were fixed before the successful prior run without weakening effect authority.
  • Live-harness preparation: the original shared harness is unchanged. The copied fixture adds a real exec allow/deny flow. An attempted baseline boot timed out during its 15-second WebSocket handshake under heavy host load, before any turn or measured RPC; that attempt is excluded. The valid pair uses the supported 60-second handshake override symmetrically on baseline and candidate, with no product timeout change (fixture SHA-256 b9727038c080cdfd97f7969bd65cdc7c9d546099c1580ca895adc408b6d164dc).
  • A later baseline completed the 13 shared turns and child flow, but the added exec fixture used the wrong timeout argument and failed tool validation before command execution. Those turns remain supplementary only. The runner corrected the copied fixture to the documented timeoutSeconds argument and restarted a consistent pair; no product code or builds changed.
  • One valid baseline/candidate live pair completed with both sides exit 0, all shared turns, child flow, real exec allow/revocation, cron, compaction and shutdown passed, no optional failures or remaining child processes. The allowed command returned SYNTHETIC_EXEC_OWNER_OK with exit 0; a policy revocation committed before releasing the held provider response produced exec denied: host=gateway security=deny, and no command marker was created. This proves that preparation can move to workers while committed in-process policy still governs the effect. Published-driver × candidate update cell is not applicable: no update, Doctor, schema/migration, plugin-loading, or service-lifecycle behavior changed.

Inherited failures observed in final-head normal CI:

  • node-worker-launch-wire.e2e.test.ts:284 expects a new workspace manifest at reply completion; required-native-same-session.e2e.test.ts:626 expects the reply to remain pending during workspace settlement. Main commit 883d61f645a0a (perf(worker): deliver replies before workspace reconciliation #169484) deliberately delivers the reply before settlement. Both tests and the relevant settlement owners were unchanged between that run's main parent and its tested merge. The first test drains only node invokes, not Gateway settlement; the second explicitly holds settlement. The existing early-final regression proves the new ordering. These failures are unresolved fixture contract mismatches, not green results.
  • Normal CI tests a GitHub merge of this head into main b82b033920ee7a4df6323e3ee2b04ac8c6037fe0. Its core-4 type errors are in newly added session-entry-patch.authority.test.ts:41,56 from main commit 31a4b923387e5 (perf(sessions): combine candidate transfer with commit admission #169744), where the fixture returns an optional entry and the new test dereferences it. This PR changes neither fixture nor test. The directly pinned final-head supplemental core-4 shard passes. The earlier optional supplemental run timed out in agent-session-dedup-reconnect.e2e.test.ts; its normal PR shard passed. No fix or successful replay is claimed for that timeout.

One baseline/candidate pair under the campaign’s current relaxed-testing rule; all ten warmed turns are included. Baseline 4de0aa67, measured candidate 25f563f, final head 83698fa as qualified above.

Warmed turn Baseline median [min–max] Candidate median [min–max]
All-thread SQL statements 354 [298–481] 307 [266–426]
Worker requests 110.5 [94–130] 96 [85–118]
MAIN SQL statements 0 [0–2] 0 [0–2]

Means: statements 355.5 → 308.7, requests 109.3 → 95.7, MAIN 0.2 → 0.2. Whole workload: statements 10,949 → 10,453, requests 2,366 → 2,240, MAIN 2,000 → 1,988. First turn: statements 808 → 777, requests 197 → 185, MAIN 38 → 38. These are raw workload results; no exec-owner operations occur in the warmed window, so its reduction is not claimed as an exec saving. This PR’s directly attributed saving is the exec-owner table below.

Exec-owner work Baseline Candidate Delta
All-thread statements 36 26 −10
Worker requests 13 13 0
MAIN statements 10 0 −10
Whole-workload exec operation Statements M → C Requests M → C MAIN M → C
exec-approvals.read 5 → 5 5 → 5 0 → 0
execApprovals.commitAuthorizations 1 → 1 1 → 1 0 → 0
execApprovals.ensureSnapshot 8 → 8 4 → 4 0 → 0
execApprovals.update 12 → 12 3 → 3 0 → 0
Native policy SELECT 10 → 0 0 → 0 10 → 0

The removed class is ten synchronous raw_json policy SELECTs. Existing worker operations emit the same requests/statements; no touched owner operation increases. Static mixed-kernel T1 sites remain 3 → 3 for the named compatibility/security exceptions; the measured bundled exec flow’s MAIN statements fall 10 → 0. Broader warmed reductions are reported without attributing them all to this owner.

Release-note context: internal database scheduling improvement; command approval and credential authority remain enforced immediately before effects.

Use committed owner publications for SQL-free execution guards and migrate bundled default-policy and operator-token readers. Deprecate synchronous SDK readers without changing released signatures.
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@github-actions

github-actions Bot commented Oct 12, 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: 83698faee94a2ff1c478b6e2b243d21a4722beae
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/context.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/gateway/server/ws-connection/connect-session.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/worker-tool-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/exec-approvals-store.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/node-host/plugin-exec-policy.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts commands Command implementations docker Docker and sandbox tooling agents Agent runtime and tooling extensions: codex size: XL labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR prepares execution policy through workers and replaces final SQLite reads with committed in-process policy facts.

Example: An allowed command such as echo synthetic executes against an existing policy database.

  • Before: The final authorization guard queries SQLite on the calling thread.
  • After: The guard checks retained policy facts without querying SQLite.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction is worthwhile, but the unresolved authorization defect blocks merge and final-effect authority proof is absent; the diff introduces no persisted-format or schema migration.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Synchronous policy preparation can occupy the Gateway thread during agent and approval handling.
Reason: The maintainer-authored direction follows the existing worker and publication owners, with explicit compatibility and single-owner tradeoffs.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this maintainer-authored PR open: the worker cutover is useful, but the retained policy guard still misses revocation after first database creation.

Priority: P2
Reviewed head: 83698faee94a2ff1c478b6e2b243d21a4722beae

Before merge

  • Add real behavior proof - Authority-chain proof required: the complete body supplies CI and pending runtime measurements, but no final-effect observations through execution and approval entry points. Provide redacted terminal output or logs showing allowed execution and rejection before launch or retry after policy revocation and originating-scope cancellation, including first database creation and attached-environment dispatch, plus local approval success and remote or rotated-token refusal; redact IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Rebind retained policy guards after first database creation (P1) - This prior finding remains unresolved. retainExecApprovalsCurrentRead captures the map key before the authorization worker opens the database. For an absent database that key is path:…, but first creation changes the same live admission to file:… without invalidating it. Pending writes and committed revocations then publish under the file key, while seed() and read() continue using the path entry. A command authorized during first creation can therefore pass its retained launch or retry guard after a later owner-written deny policy. Resolve the policy entry through the admitted physical identity and preserve pending/unknown fencing across that binding; add a first-creation-then-revocation regression.
  • Resolve security concern: First-creation guards miss authority publications - The same identity mismatch also bypasses pending and unknown publication fencing for the retained guard, weakening denial before command launch or retry.

Findings

  • [P1] Rebind retained policy guards after first database creation — src/infra/exec-approvals-store.ts:260-265
  • [high] First-creation guards miss authority publications — src/infra/exec-approvals-store.ts:261

Tests

  • Missing end-to-end proof: Supply final-effect traces for first creation followed by revocation, caller-scope cancellation, attached-environment dispatch, and local versus remote or rotated approval tokens; no failing-base/passing-head regression for first creation is supplied.
Agent review details

How this fits together

Agent tools, node plugins, and attached-environment RPCs consume execution policy from the shared-state owner; final guards authorize command launch or dispatch.

flowchart TD
  A[Agent or environment request] --> B[Worker preparation]
  B --> C[Shared policy database]
  C --> D[Committed policy publications]
  D --> E[Retained execution guard]
  E --> F[Command launch or dispatch]
Loading

Technical review

Best possible solution:

Bind retained policy facts to the live physical database identity while preserving synchronous final-effect checks and the documented SDK deprecation window.

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

The patch source establishes the first-creation failure: capture a path identity, let the authorization worker create the database, then revoke policy through its owner; the retained guard still reads the old map entry.

Is this the best way to solve the issue?

Worker-backed preparation and owner-published policy facts fit the repository contract, provided first creation preserves one policy identity and subsequent revocation reaches every retained guard.

Full review comments:

  • [P1] Rebind retained policy guards after first database creation — src/infra/exec-approvals-store.ts:260-265
    This prior finding remains unresolved. retainExecApprovalsCurrentRead captures the map key before the authorization worker opens the database. For an absent database that key is path:…, but first creation changes the same live admission to file:… without invalidating it. Pending writes and committed revocations then publish under the file key, while seed() and read() continue using the path entry. A command authorized during first creation can therefore pass its retained launch or retry guard after a later owner-written deny policy. Resolve the policy entry through the admitted physical identity and preserve pending/unknown fencing across that binding; add a first-creation-then-revocation regression.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Final execution-policy reads and direct-reader removal changes intended behavior with a stated reason (9324ed6: The earlier implementation retained a current-row SELECT to enforce revocation, including foreign commits; this PR explains its replacement through committed publications under exclusive Gateway ownership.)
  • Approval-runtime token keeps the original intent (2affecc: Share a derived socket token while retaining a process-local fallback; the async conversion retains that credential derivation and fallback.)
  • Prepared execution defaults keeps the original intent (bb9f63c: Prepare execution defaults and approvals through async readers; the new callers reuse that preparation contract.)
  • Worker tool authority keeps the original intent (fix(worker): restore tool parity and compact presentation on nodes #164296: Preserve node tool parity and presentation; the diff retains those policy decisions while awaiting sandbox and approval preparation.)

Testing

Proof path: in-process harness.

Security

Needs attention: The retained guard can permit execution after policy revocation when its database was created during preparation.

Evidence

Security concerns:

  • [high] First-creation guards miss authority publications — src/infra/exec-approvals-store.ts:261
    The same identity mismatch also bypasses pending and unknown publication fencing for the retained guard, weakening denial before command launch or retry.
    Confidence: 0.99

What I checked:

PR surface

Source +22, Tests -21, Docs +15, Other -11. Total +5 across 71 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 37 483 461 +22
Tests 30 320 341 -21
Docs 2 18 3 +15
Config 0 0 0 0
Generated 0 0 0 0
Other 2 2 13 -11
Total 71 823 818 +5

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a useful internal scheduling improvement without an established urgent current-main regression.
  • merge-risk: 🚨 compatibility: The public approval SDK gains async replacements and deprecates synchronous readers; the maintainer-approved compatibility window preserves existing signatures.
  • merge-risk: 🚨 security-boundary: The changed final authorization guard can retain policy that no longer authorizes execution after first database creation.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

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

Workflow

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

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-12T03:57:18.917Z sha 9712267 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-12T04:22:07.085Z sha e15f5c5 :: needs real behavior proof before merge. :: [P2] Retain originating cancellation in execution guards | [P2] Honor integrity invalidation before returning cached policy | [P2] Migrate node-command fixtures to loaded plugin records
  • reviewed 2026-10-12T05:37:50.769Z sha 9065e5b :: needs real behavior proof before merge. :: [P2] Complete the loaded-plugin migration in node-command fixtures
  • reviewed 2026-10-12T06:04:09.163Z sha 9283934 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-12T06:48:45.820Z sha 25f563f :: needs real behavior proof before merge. :: [P1] [P1] Rebind retained policy guards after first database creation
  • reviewed 2026-10-12T07:15:13.246Z sha 25f563f :: needs real behavior proof before merge. :: [P1] Rebind retained policy guards after first database creation
  • reviewed 2026-10-12T08:38:21.036Z sha 25f563f :: needs real behavior proof before merge. :: [P1] Rebind retained policy guards after first database creation

Reviewed October 12, 2026, 4:59 AM ET / 08:59 UTC (Revision 8).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 12, 2026
@steipete
steipete merged commit d502f1a into main Oct 12, 2026
270 of 284 checks passed
@steipete
steipete deleted the dbasync/t1cut-infra-exec branch October 12, 2026 09:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…69584)

* refactor(infra): prepare execution policy through workers

Use committed owner publications for SQL-free execution guards and migrate bundled default-policy and operator-token readers. Deprecate synchronous SDK readers without changing released signatures.

* fix(infra): preserve typed execution preparation contracts

* fix(infra): retain execution authority through async preparation

* test(infra): register plugin owners in invocation fixtures

* refactor(state): remove obsolete direct approval reader
amittell added a commit to amittell/openclaw that referenced this pull request Oct 28, 2026
…the fork's #1 diagnostic

beta.4 carries openclaw#169584, which deletes prepareOpenClawStateDirectReader and its
'Direct shared-state reader requires current integrity admission' throw (0 hits
in beta.4 src). The fork's only change to openclaw-state-db-read-connection.ts
was the alexm/openclaw#1 diagnostic hooked into that function, so this takes
beta.4's file unchanged and removes the diagnostic module, its test and its
scripts/pr-lib/wrapper-components.txt line.
obviyus added a commit that referenced this pull request Nov 22, 2026
## What Problem This Solves

Exec approvals were checked twice for one command. The worker commit (`execApprovals.commitAuthorizations`) checks the command against the current policy row. After that, `retainExecApprovalsCurrentRead` kept a per-database policy view that the launch guard read again right before spawn. A policy write that landed between the commit and the spawn refused a command that was already admitted ("Exec approval changed before execution", "Exec approval policy is unavailable or changing before execution"). Under the one-admission rule, a policy change applies to the next command; a command that has started finishes.

## Fix

- `src/infra/exec-approvals-store.ts`: delete `retainExecApprovalsCurrentRead`, the `currentPolicies` map and its publication/lifecycle bookkeeping.
  - `prepareExecApprovalsCurrentRead` returns the policy it read at preparation, through the existing prepared-snapshot cache, which a publication still clears for the next reader.
  - The launch guard from `commitExecAuthorizations` keeps Stop (`signal.throwIfAborted()`) and the caller's own `assertCurrent`, and returns the committed file.
- `src/infra/exec-approvals-authorization.ts`: `commitExecAuthorizationLocked` no longer runs `assertCurrentUsageAuthorization` again on the file it just committed. The worker already ran that check inside the commit transaction.
- `scripts/check-lifetime-check-ratchet.mts`: remove `retainExecApprovalsCurrentRead` (it is gone) and `createPluginRuntimeCapabilityLease` from `LIFETIME_CHECK_CALLS`.

### Classification

| Name | Class | Action |
|---|---|---|
| `retainExecApprovalsCurrentRead` (#169584) | authority. It re-read the exec policy, which is the permission for the command, after the worker commit had admitted it. It refused while a policy write was pending or after one committed. | deleted |
| `createPluginRuntimeCapabilityLease` (#133297, "scope HTTP routes to account lifetimes") | resource lifetime fence. Its only `revoke()` callers are channel account stop (`server-channels.ts`), plugin service stop (`services.ts`), plugin CLI scheduler close (`cli-service-scheduler.ts`) and shutdown drain. It never reads role, scopes, profile or grants. It retires HTTP routes, listeners and schedulers that a stopped account or service still holds. | code kept; name removed from the ratchet list |

Kept: Stop on the launch guard, the worker commit check against the current row (it protects the usage/grant write), and the DB-lifecycle fences inside the shared-state reads.

Not in scope (accepted for now): `plugin-node-host.ts` still compares the node exec **config** (`resolveNodeExecConfigPolicy`) at launch. The ratchet does not list it; it can go in a later PR.

## User Impact

- If you tighten exec approvals while a command is between approval and spawn, that command now runs. The next command uses the new policy. Before this change, the command failed with "Exec approval changed before execution".
- Stop still cancels the launch.
- A policy change made before the worker commit still refuses the command.

## Tests

Deleted or flipped. Each one asserted a refusal after the commit had admitted the command, which this change removes:
- `bash-tools.exec-authorization.integration.test.ts`: "revalidates … after asynchronous shell preparation" ×3, "rechecks policy after deferred supervisor admission", the PTY fallback `revoked=true` case. Added "finishes an admitted launch when policy is revoked during supervisor admission" (real exec tool → supervisor).
- `invoke-system-run.test.ts`, `invoke-agent-cli-claude.test.ts`: the revoke cases now expect the admitted launch to finish (real node `system.run` / Claude CLI entry points).
- `plugin-exec-policy.test.ts`: approvals tightened after the invocation started → the launch is allowed. A config change is still refused.
- `agent-tools.browser-loopback-current.e2e.test.ts`: deleted the approvals-revocation case. The abort (Stop) and config cases stay.
- `exec-approvals-store*.test.ts`, `operator-approval-store.worker.test.ts`: the pending-write / committed-change refusals are replaced by "the prepared read keeps its admitted policy; a fresh preparation sees the write".

## Evidence

Pre-push: one `ocx test` run of the 78 importer/touched files (continue-on-failure); the remaining reds there (`server-methods/exec-approvals.test.ts` ×4, `agents-mutate.test.ts`, `bash-tools.exec-gateway-approval.e2e.test.ts` hook-token reload) fail the same way on the merge base `1a0a24dcd2cf`. Touched tests rerun green (202 cases). `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt, oxlint, lifetime ratchet pass. Head E2E and CI follow in comments.

- Head E2E (Q/R/S pass): #203572 (comment)
- Local review rejected finding: #203572 (comment)

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

Exec approvals were checked twice for one command. The worker commit (`execApprovals.commitAuthorizations`) checks the command against the current policy row. After that, `retainExecApprovalsCurrentRead` kept a per-database policy view that the launch guard read again right before spawn. A policy write that landed between the commit and the spawn refused a command that was already admitted ("Exec approval changed before execution", "Exec approval policy is unavailable or changing before execution"). Under the one-admission rule, a policy change applies to the next command; a command that has started finishes.

## Fix

- `src/infra/exec-approvals-store.ts`: delete `retainExecApprovalsCurrentRead`, the `currentPolicies` map and its publication/lifecycle bookkeeping.
  - `prepareExecApprovalsCurrentRead` returns the policy it read at preparation, through the existing prepared-snapshot cache, which a publication still clears for the next reader.
  - The launch guard from `commitExecAuthorizations` keeps Stop (`signal.throwIfAborted()`) and the caller's own `assertCurrent`, and returns the committed file.
- `src/infra/exec-approvals-authorization.ts`: `commitExecAuthorizationLocked` no longer runs `assertCurrentUsageAuthorization` again on the file it just committed. The worker already ran that check inside the commit transaction.
- `scripts/check-lifetime-check-ratchet.mts`: remove `retainExecApprovalsCurrentRead` (it is gone) and `createPluginRuntimeCapabilityLease` from `LIFETIME_CHECK_CALLS`.

### Classification

| Name | Class | Action |
|---|---|---|
| `retainExecApprovalsCurrentRead` (openclaw#169584) | authority. It re-read the exec policy, which is the permission for the command, after the worker commit had admitted it. It refused while a policy write was pending or after one committed. | deleted |
| `createPluginRuntimeCapabilityLease` (openclaw#133297, "scope HTTP routes to account lifetimes") | resource lifetime fence. Its only `revoke()` callers are channel account stop (`server-channels.ts`), plugin service stop (`services.ts`), plugin CLI scheduler close (`cli-service-scheduler.ts`) and shutdown drain. It never reads role, scopes, profile or grants. It retires HTTP routes, listeners and schedulers that a stopped account or service still holds. | code kept; name removed from the ratchet list |

Kept: Stop on the launch guard, the worker commit check against the current row (it protects the usage/grant write), and the DB-lifecycle fences inside the shared-state reads.

Not in scope (accepted for now): `plugin-node-host.ts` still compares the node exec **config** (`resolveNodeExecConfigPolicy`) at launch. The ratchet does not list it; it can go in a later PR.

## User Impact

- If you tighten exec approvals while a command is between approval and spawn, that command now runs. The next command uses the new policy. Before this change, the command failed with "Exec approval changed before execution".
- Stop still cancels the launch.
- A policy change made before the worker commit still refuses the command.

## Tests

Deleted or flipped. Each one asserted a refusal after the commit had admitted the command, which this change removes:
- `bash-tools.exec-authorization.integration.test.ts`: "revalidates … after asynchronous shell preparation" ×3, "rechecks policy after deferred supervisor admission", the PTY fallback `revoked=true` case. Added "finishes an admitted launch when policy is revoked during supervisor admission" (real exec tool → supervisor).
- `invoke-system-run.test.ts`, `invoke-agent-cli-claude.test.ts`: the revoke cases now expect the admitted launch to finish (real node `system.run` / Claude CLI entry points).
- `plugin-exec-policy.test.ts`: approvals tightened after the invocation started → the launch is allowed. A config change is still refused.
- `agent-tools.browser-loopback-current.e2e.test.ts`: deleted the approvals-revocation case. The abort (Stop) and config cases stay.
- `exec-approvals-store*.test.ts`, `operator-approval-store.worker.test.ts`: the pending-write / committed-change refusals are replaced by "the prepared read keeps its admitted policy; a fresh preparation sees the write".

## Evidence

Pre-push: one `ocx test` run of the 78 importer/touched files (continue-on-failure); the remaining reds there (`server-methods/exec-approvals.test.ts` ×4, `agents-mutate.test.ts`, `bash-tools.exec-gateway-approval.e2e.test.ts` hook-token reload) fail the same way on the merge base `75564d96e6eb`. Touched tests rerun green (202 cases). `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt, oxlint, lifetime ratchet pass. Head E2E and CI follow in comments.

- Head E2E (Q/R/S pass): openclaw#203572 (comment)
- Local review rejected finding: openclaw#203572 (comment)

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 commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant