Repository navigation
refactor(infra): prepare execution policy through workers - #169584
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: needs real behavior proof before merge. What this changesThis 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.
Review scores
ProductKind: Refactor · Worth it: Yes · Fix scope: Complete 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 Before merge
Findings
Tests
Agent review detailsHow this fits togetherAgent 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]
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 684874efa1c5. Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: The retained guard can permit execution after policy revocation when its database was created during preparation. EvidenceSecurity concerns:
What I checked:
PR surfaceSource +22, Tests -21, Docs +15, Other -11. Total +5 across 71 files. Added test files: 0. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed October 12, 2026, 4:59 AM ET / 08:59 UTC (Revision 8). |
…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
…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.
## 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]>
## 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]>
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-nativemintMcpToolGrantLockedcall fromoperator-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:
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 candidate25f563f06d6cfb9c753b318e8e741fcdbac6eb26against4de0aa6700755d4e7f3303633b7c757a9a2d9def. 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.git diff --check, and normal commit hooks pass. No local test suites, broad scans, or typecheck were run for the final cleanup.gateway-prewarm.mjsandrenderPublicSessionCardSvginsrc/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 inbash-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.b82b033920ee7a4df6323e3ee2b04ac8c6037fe0with the actual CI merge935c33628e5014d5e6dd64a62ff86f9fc41a43e1containing 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.b9727038c080cdfd97f7969bd65cdc7c9d546099c1580ca895adc408b6d164dc).timeoutSecondsargument and restarted a consistent pair; no product code or builds changed.SYNTHETIC_EXEC_OWNER_OKwith exit 0; a policy revocation committed before releasing the held provider response producedexec 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:284expects a new workspace manifest at reply completion;required-native-same-session.e2e.test.ts:626expects the reply to remain pending during workspace settlement. Main commit883d61f645a0a(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.b82b033920ee7a4df6323e3ee2b04ac8c6037fe0. Its core-4 type errors are in newly addedsession-entry-patch.authority.test.ts:41,56from main commit31a4b923387e5(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 inagent-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 candidate25f563f, final head83698faas qualified above.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-approvals.readexecApprovals.commitAuthorizationsexecApprovals.ensureSnapshotexecApprovals.updateThe removed class is ten synchronous
raw_jsonpolicy 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.