Skip to content

fix: start Gateway with conflicting legacy exec approvals - #196401

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-exec-approvals-startup-20260919
Nov 10, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-exec-approvals-startup-20260919

Conversation

@steipete

@steipete steipete commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Gateway restart loops when an older node host or another writer leaves conflicting or invalid exec-approvals.json beside canonical SQLite approvals.

User Impact

Gateway and node startup retain the legacy file and report degraded state through the existing status/Doctor warning report. Canonical approvals remain authoritative; no conflicting policy or socket credential is imported. Runtime reads and authorized edits use canonical policy. Legacy-only execution remains unavailable until migration succeeds. Valid legacy-only imports and byte-identical source retirement keep their existing migration owner.

Why This Change Was Made

The SQLite cutover (#114063) refused legacy presence to prevent silently serving empty/default policy, and automatic credential preparation (#178998) promoted that refusal into a startup failure. The protection now belongs at the canonical snapshot boundary: only absent canonical policy requires the legacy gate. Preparation returns a typed, redacted retained-input diagnostic instead of treating a conflict as a service-wide failure. Doctor retains reconciliation ownership and the existing stop/reconcile instructions; the warning explicitly identifies a possible older node host or external writer.

No configuration, schema, cache, or policy default changes. Related open #153405 adds an explicit reconciliation surface to the same migration owner; this fix does not add that surface or archive conflicting files.

Follow-up outside this repository: investigate openclaw-windows-node tray tests writing the real ~/.openclaw/exec-approvals.json without HOME/state isolation.

Evidence

Acceptance for the owner measurement: real prepareLegacyExecApprovals, 316-byte synthetic conflicting legacy file and canonical deny policy in the existing synthetic team-scale fixture; five alternating fresh-process baseline/candidate pairs and baseline A/A controls. Separate first-call and 100-call warm wall time, process/thread CPU, and V8 allocation. Success means baseline refusal becomes a diagnostic, with exact canonical/source preservation. Timing compares owner work, not a speedup against a failed Gateway startup. macOS/APFS proof does not establish Linux/btrfs timings.

211 distinct focused cases pass across Gateway startup, state migration/canonical repair, credential startup, Doctor policy/security/settlement, and runtime/cron authorization. The new real Gateway preflight regression fails on the original owner and passes with HTTP readiness, canonical deny policy, unchanged source bytes, and redacted diagnostics. Final Gateway test: 23.426s (71.52s wrapper with cold compilation); runtime conflict case: 1.189s. No inference/channel or packaged-upgrade claim is made. Three existing final-effect node tests also pass on head 58311e6: an allowed /bin/ls launches and produces output, while revocation after authorization commit or in the pre-spawn callback yields SYSTEM_RUN_DENIED, no output, and no completion event. These use canonical policy without retained legacy input; retained-input authority/preservation is covered separately by the Gateway and worker regressions. This is complementary boundary evidence, not a combined retained-input host-launch claim.

pnpm check:changed completed. Core/scripts/test typechecks and other guards passed. Its own lint findings were fixed and both affected files passed focused lint afterward. Its remaining dead-export findings reproduce exactly on parent 2609b4f93bf851274e94635bc19ebe10cb624236; attribution is below. Production/full-tree unused-file scans pass. Test-line ratchet and diff checks pass. No changed module is imported by ui/src.

Independent Codex autoreview of the complete implementation against that parent is scoped-clean through P2. A subsequent Codex review of the CI test repair is also scoped-clean through P2. No unresolved actionable review finding.

Initial exact-head CI run 42744343690 exposed three stale assertions in two sibling files: managed Doctor expected retained malformed/conflicting input to throw, and node startup expected a malformed approvals claim to veto admission. Those three failures reproduced locally. The test-only repair retains source bytes, canonical deny, missing-canonical execution refusal, and warning assertions; all 15 tests in those two files pass (197.34s Vitest, 241.81s wrapper). Production code is unchanged by this repair. The changed-file pass also caught an extra argument in the new test assertion; it was removed to match the existing zero-argument reader, then the node test and affected typecheck graphs were rerun.

The inherited macOS Doctor fixture failure also reproduces on the exact parent. #189246 (0a02f57ab706) added restoration reservation → process namespace → native boot observation. A seven-line test-only fix supplies a synthetic boot identity while retaining the strict no-native-process assertion; all 5 readiness and 49 settlement/refusal cases pass.

Production source is net +13 LOC: runtime consolidation removes 22 lines, while typed reporting and startup scheduling require the remaining growth. Tests/support add 133 lines with the focused allocation and existing ratchet headroom; the reproducible benchmark adds 217 tooling lines. No production compatibility path was added.

Synthetic fixture: 8 agents, 10,000 sessions, 35.09 GiB largest agent DB, 12.03 GiB shared DB, 62,000 workspace files/1.181 GB, 46 synthetic plugins. Five interleaved A/B pairs and five A/A pairs. All 505 baseline calls refused; all 505 candidate calls returned a diagnostic, preserving source/canonical state. The owner receives admitted canonical facts; unchanged DB snapshot preparation and unrelated agent/workspace reads are excluded.

Owner metric (median; p95) Before After
First call wall ms 10.248; 10.932 29.022; 33.609
First call process CPU ms 15.533; 16.579 37.377; 40.614
First call allocated bytes 3,693,752; 4,696,984 7,114,808; 10,000,448
Warm call wall ms 0.530; 0.616 0.616; 0.822
Warm call process CPU ms 0.723; 0.806 0.834; 1.057
Warm call allocated bytes 375,697; 407,176 350,031; 399,052

The required cold diagnostic adds ~18.77ms wall, ~21.84ms CPU, and ~3.42MB allocation. Separate profiles attribute the extra work to warning recording/redaction. This is the cost of observable degraded startup instead of termination, not a speedup. Warm A/A medians: wall 0.481→0.448ms, CPU 0.660→0.618ms, allocation 309,182→405,308 bytes; no allocation improvement is claimed. Five samples make p95 the observed maximum, not a robust tail estimate. Host load 12.66–16.94, macOS/APFS/Node26.12.1; no btrfs qualification or Team data/access. Final lint-only explicit empty returns affect no measured conflict branch.

Reproduction: scripts/perf/exec-approvals-startup-measure.ts header commands, using the existing bench-gateway-startup.ts --case teamBoot --team-scale --seed-only fixture. The large task fixture has been removed.

Inherited main dead-export failures (exact-parent reproduction)

Only the failed scripts/check-deadcode-exports.mts command was replayed on the exact parent. All 28 ordered finding lines match byte-for-byte (21 production, 7 full-tree); no dependency-resolution errors. These are main regressions for follow-up, not ignored noise. No unrelated export cleanup is included.

File / exported names Unused-state introducing commit / PR Source evidence
src/daemon/launchd.ts: isLaunchctlNotLoaded b4262689db5dbb4b88660119f67ae6fc4372cd97 / #130634 Doctor's final production import switches from launchd.js to launchd-exec.js; exact-ref grep finds only the unused facade export and direct leaf consumers. Production + full-tree.
src/daemon/launchd.ts: parseLaunchAgentEnabled 7713e8fb749e0dec479c088b672d99e26df59b55 / #103537 Introduces exported function with only same-module production use; external references are tests. Later #121929 retains the facade export. Production-only.
src/daemon/launchd.ts: resolveLaunchAgentPlistPath 5e591205828657a5a20f5aa81f75f35b6a414f91 / #151777 Final service-audit consumer moves to service-audit-launchd.ts and imports launchd-service-files.js directly. Production-only.
src/gateway/server-methods/config-write-flow.ts: replyWithBillingRouteWarnings 56617cd00086481212d29745ed71f5feb8a40b9e / #191326 Introduced exported with only same-module production consumer; all external consumers are test fixtures. Production-only.
src/plugins/types.ts: ProviderAuthOptionBag, ProviderNonInteractiveApiKeyCredentialParams, ProviderNonInteractiveApiKeyResult, ProviderResolveNonInteractiveApiKeyParams cf1ae7bb6a729a7f13a28ca2ef9d6f108c00566f / #190544 Definitions and consumers move to provider-auth-types.ts; unused explicit facade reexports remain in types.ts. Production + full-tree.
src/plugins/provider-runtime.ts: augmentModelCatalogWithProviderPlugins, formatProviderAuthProfileApiKeyWithPlugin, loginProviderOAuthWithPlugin, refreshProviderOAuthCredentialWithPlugin, resolveProviderOAuthCredentialWithPlugin, resolveProviderOAuthRefreshCapabilityWithPlugin f63e5cd0f6d38f1d0438978255d9e244183864c3 / #190205 Lazy runtime forwarding and SDK catalog facade switch from broad barrel directly to auth/catalog owners; old barrel exports remain. Production-only.
src/plugins/provider-runtime.ts: classifyProviderFailoverSignalWithPlugin, resolveExternalAuthProfilesWithPlugins 964fa991c0aff81e2ae46a0c9f99ebc0ab349d1a / #132716 agents/failover/provider-patterns.ts switches from runtime barrel to provider-failover.ts; agents/auth-profiles/external-auth.ts switches from runtime barrel to provider-external-auth.ts. Both barrel reexports remain. Exact-ref grep confirms only direct leaf production consumers. Production-only.
src/plugins/provider-runtime.ts: resolveProviderModernModelRef 33d8f24c9926f8b291b71785c5b4dea4181a8128 / #129184 Consumer moves from agents/live-model-filter.ts into agents/test-helpers/live-model-dynamic-candidates.ts; export becomes test-only. Production-only.
src/plugins/provider-external-auth.ts: resolveExternalAuthProfilesWithPlugins 071f606eae77a13f6c4c161da009dd2ba31a1c10 / #139911 Production caller in agents/auth-profiles/external-auth.ts switches from facade import to injected native-loader binding; thin facade remains. Production-only.
src/plugins/provider-runtime.ts: resolveProviderRuntimePlugin a7436c8b4a93bff59d099661d2b206bb0627ac2b (no associated PR returned by GitHub commit-pulls API) Sole non-test external consumer agents/transcript-policy.ts moves directly to provider-hook-runtime.ts; barrel reexport remains. Production-only.
src/shared/browser-pair.ts: BROWSER_PAIR_CODE_LENGTH d85ebfe8daad438c8141b9efada73d5c05e174a3 / #191513 Introduced exported with only same-module loop use; exact-introduction grep confirms no external reference. Production + full-tree.
ui/src/pages/dashboards/dashboard-tools.tsx: authorDisplayName cde34f111b4d893d0ce03d6c80094203690d5d22 / #194455 Removes final external import and card consumer from view.tsx; exact-ref grep thereafter finds declaration and two same-module uses only. Its introduction in #194450 was valid and is not the regression. Production + full-tree.

Review disposition: the two concrete old-head ClawSweeper findings are fixed in 58311e6. The review found no concrete execution bypass or data-model incompatibility. Final-effect authority checks are unchanged and their real-process regression passes; canonical conflict reads/writes are separately proven. No schema, policy format, credential format, or import algorithm changes, so a packaged latest-stable upgrade campaign is outside this startup-availability fix. Its absence remains explicit rather than being presented as completed proof.

Final validation: CI run 42747571732 completed successfully on 58311e643816648999c66fc0a8140cbc04a9e1ae: 51 successful jobs, zero failed or running. Merged through ordinary gated auto-merge as a0ec2b5b4ba6532237705777a470a1d154cd1ccc; no admin exception or CI rerun.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts commands Command implementations size: L labels Nov 10, 2026
@steipete
steipete marked this pull request as ready for review November 10, 2026 02:40
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T03:12:26.569068Z 58311e6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Nov 10, 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: 58311e643816648999c66fc0a8140cbc04a9e1ae
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/infra/exec-approvals-authorization.worker.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals-cron-policy.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals-mutation.worker.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals-retirement.worker.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals-sqlite.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/infra/exec-approvals-store.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Allows Gateway and node startup to retain conflicting legacy approvals while using canonical SQLite policy and reporting degraded state.

Example: SQLite specifies security="deny", while exec-approvals.json specifies security="full".

  • Before: Credential preparation rejects the conflict and prevents Gateway startup.
  • After: The Gateway starts with a retained-input warning, preserves the legacy file, and uses SQLite's deny policy.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused implementation has clear value, but affected consumer tests fail and required execution-authority and upgrade evidence is incomplete.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A retained legacy approval file can prevent an otherwise usable Gateway or node host from starting.
Reason: The maintainer-approved direction restores service availability while retaining canonical policy and conflicting input for recovery.

Merge readiness

⛔ Blocked before merge - 6 items remain

Keep open: this maintainer-authored PR addresses a current startup failure, but its changed behavior leaves three existing CI assertions failing.

Priority: P1
Reviewed head: a14ea6158a06f0cace683d7723191604501fb658

Before merge

  • Add real behavior proof - Authority-chain proof required: the supplied Gateway test demonstrates readiness and canonical deny-policy reads, and store tests exercise authorization commits, but neither records a real host launch or rejection at the final effect. Show a canonically allowed command launching, a canonically denied command remaining unlaunched despite permissive legacy input, and revocation preventing a prepared command from launching. The body expressly makes no packaged-upgrade claim; latest-stable upgrade preservation is also unproven. Redact credentials, IPs, and non-public endpoints from evidence. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Update node-host readiness coverage for retained approval input (P2) - Returning successfully for retained invalid approvals changes the node-host startup contract, but src/node-host/startup-state-readiness.test.ts:145 still expects ExecApprovalsMigrationRequiredError for exec-approvals.json.doctor-importing. Exact-head CI receives the runtime-preparation sentinel instead and fails. Update this consumer test to verify degraded admission, retained bytes and diagnostics, while retaining the missing-canonical execution refusal.
  • Update Doctor restoration coverage for the narrowed legacy gate (P2) - Removing the readiness refusal makes the malformed and conflicting approval cases complete instead of rejecting, but src/flows/doctor-health.managed.test-support.ts:450 still requires ExecApprovalsMigrationRequiredError. Exact-head CI fails both cases. Update the affected assertions to verify the intended restoration outcome, retained legacy bytes, and unchanged canonical policy rather than the removed service-wide refusal.
  • Resolve security review attention item - No concrete bypass was found, but the changed execution gate needs final-effect authority evidence.
  • Resolve merge risk - Before merge, the author must establish that removing the blanket legacy veto cannot let a canonically denied or revoked command reach host execution.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Update node-host readiness coverage for retained approval input — src/commands/startup-client-credentials.ts:184-185
  • [P2] Update Doctor restoration coverage for the narrowed legacy gate — src/commands/doctor-maintenance-inspection.ts:215-217

Tests

  • Missing end-to-end proof: Supply production-boundary execution evidence for allowed, denied, and revoked commands with retained legacy input, plus a latest-stable upgrade preserving policy and credentials.
Agent review details

How this fits together

Startup credential preparation inspects legacy approval files; the shared approval store supplies canonical policy to runtime authorization, mutations, and cron execution.

flowchart LR
A[Gateway or node startup] --> B[Credential preparation]
C[Legacy approvals file] --> B
B --> D[Retained input warning]
B --> E[Canonical SQLite policy]
E --> F[Runtime authorization]
F --> G[Host execution guard]
Loading

Technical review

Best possible solution:

Keep the centralized canonical-policy boundary and existing migration owner, complete the affected consumer tests, and establish execution and upgrade safety.

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

Current-main source deterministically rejects conflicting legacy approvals during startup preparation; the PR reports a red-on-parent Gateway regression, but no target code was executed in this read-only review.

Is this the best way to solve the issue?

Moving the gate to the existing canonical snapshot owner is a focused solution that preserves migration ownership and avoids competing policy sources.

Full review comments:

  • [P2] Update node-host readiness coverage for retained approval input — src/commands/startup-client-credentials.ts:184-185
    Returning successfully for retained invalid approvals changes the node-host startup contract, but src/node-host/startup-state-readiness.test.ts:145 still expects ExecApprovalsMigrationRequiredError for exec-approvals.json.doctor-importing. Exact-head CI receives the runtime-preparation sentinel instead and fails. Update this consumer test to verify degraded admission, retained bytes and diagnostics, while retaining the missing-canonical execution refusal.
    Confidence: 1
  • [P2] Update Doctor restoration coverage for the narrowed legacy gate — src/commands/doctor-maintenance-inspection.ts:215-217
    Removing the readiness refusal makes the malformed and conflicting approval cases complete instead of rejecting, but src/flows/doctor-health.managed.test-support.ts:450 still requires ExecApprovalsMigrationRequiredError. Exact-head CI fails both cases. Update the affected assertions to verify the intended restoration outcome, retained legacy bytes, and unchanged canonical policy rather than the removed service-wide refusal.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Verify the final execution boundary (recommended)
    The author should exercise allowed execution, canonical denial despite permissive legacy input, and revocation before a queued command launches through the production execution owner.

Provenance checked

  • Legacy refusal and canonical approval reads changes intended behavior with a stated reason (9eae43b: The SQLite cutover refused unmigrated legacy state to avoid silently serving empty or default policy.)
  • Automatic startup credential preparation changes intended behavior with a stated reason (5f40d22: Supported upgrades prepare credentials and approvals before startup without requiring manual repair.)
  • Worker authorization and mutation paths keeps the original intent (9324ed6: Move policy writes off the Gateway thread while preserving current-policy checks and committed publication.)
  • Doctor restoration readiness changes intended behavior with a stated reason (51fcb7f: Restore stopped services only after checking persisted-state readiness; this PR intentionally permits retained legacy input because runtime policy access remains gated.)

Testing

Proof path: in-process harness.

Security

Needs attention: No concrete bypass was found, but the changed execution gate needs final-effect authority evidence.

Evidence

What I checked:

PR surface

Source +13, Tests +127, Docs +8, Other +219. Total +367 across 18 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 92 79 +13
Tests 5 137 10 +127
Docs 1 10 2 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 2 219 0 +219
Total 18 458 91 +367

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.

Review metrics

Metric Value Why it matters
Production and regression-test delta Production +92/-79; tests/support +137/-10 Net production growth of 13 lines supplies typed diagnostics and startup scheduling while consolidating duplicated gates; the test growth covers distinct startup, policy, and selected-root boundaries.

Labels

Label changes:

  • add P1: The central defect prevents Gateway startup when retained legacy approvals conflict with canonical policy.
  • add merge-risk: 🚨 security-boundary: The patch removes blanket execution refusals across runtime and cron paths, requiring final-effect evidence that canonical denial and revocation still prevent host execution.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P1: The central defect prevents Gateway startup when retained legacy approvals conflict with canonical policy.
  • merge-risk: 🚨 security-boundary: The patch removes blanket execution refusals across runtime and cron paths, requiring final-effect evidence that canonical denial and revocation still prevent host execution.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Add final-effect proof that canonical denial and revocation block host execution despite permissive retained legacy input.

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 9, 2026, 9:57 PM ET / November 10, 2026, 02:57 UTC.

@steipete
steipete enabled auto-merge (squash) November 10, 2026 03:32
@steipete
steipete merged commit a0ec2b5 into main Nov 10, 2026
144 of 146 checks passed
@steipete
steipete deleted the steipete/perf-micro-exec-approvals-startup-20260919 branch November 10, 2026 03:39
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

@steipete

Copy link
Copy Markdown
Contributor Author

Post-merge closeout of all six items in the review of a14ea6158a06f0cace683d7723191604501fb658. The two P2 assertion repairs were included in merge a0ec2b5b4ba6532237705777a470a1d154cd1ccc; the additional execution and compatibility proof below ran on fetched main c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2 with Node 24.22.1. An older reviewed head does not waive an open item. The earlier merge happened before these proof items were closed; this comment supplies the missing evidence rather than treating them as optional.

  1. Real behavior proof. A real source Gateway ran with its normal startup preflight and sidecars, an isolated HOME/state/config/workspace, and conflicting legacy security=full, ask=off present before startup. /readyz returned 200 and the retained-conflict diagnostic was recorded. The production createExecTool().execute() ran in that process with host=gateway, security=full, ask=off; policy edits went through the running Gateway's authenticated exec.approvals.get/set WebSocket RPC. No model/provider, policy reader, authorization function, process adapter, or native spawn implementation was mocked. The command was a harmless executable writing a synthetic marker. Results are below. The test driver calls the actual tool directly, as an agent tool invocation does; it does not claim /tools/invoke exposes Gateway-local exec.

  2. P2 node-host readiness — resolved. Lines 147–150 now expect degraded admission, assert the typed invalid-legacy diagnostic, and retain ExecApprovalsMigrationRequiredError for execution when canonical policy is absent. Lines 155–157 verify exact source retention and no fabricated policy/credential databases. This file is byte-identical at the merge and the main used for proof.

  3. P2 Doctor restoration — resolved. Lines 451–452 await successful completion; 473–480 verify stop/repair/restart and health checking; 491–511 verify custody release, retained malformed/conflicting bytes, missing-canonical execution refusal, canonical deny, unchanged canonical raw JSON, and Doctor completion. Both affected cases are registered in managed-approvals.test.ts. The support file is byte-identical at merge and proof main. Fresh focused run: 2 files, 15 tests passed (command below). These service mocks/sentinels establish restoration behavior; they are not substituted for the real execution proof.

  4. Security attention — execution evidence supplied. The canonical snapshot owner only checks pending legacy state when the canonical row is absent. Existing canonical policy still tightens requested execution at the host approval boundary. No full-permission-session bypass was enabled in the proof. Canonical denial and removal of the canonical allowlist grant both rejected the real exec call despite the retained permissive legacy file.

  5. Merge risk — final-effect and prepared-command evidence supplied. The additional race case first admits/prepares the allowed command, pauses only scheduling at the production supervisor entry, revokes its canonical grant through exec.approvals.set, and resumes the original supervisor with its original arguments and guards. The retained authorization rereads current policy; the exec runtime passes that guard to the supervisor, which checks it before native launch. The barrier asserts it was reached. The observer wraps ChildProcess.prototype.spawn, records only this synthetic command, and calls the original unchanged; the allowed control proves it sees a real launch. Rejected cases have zero target launch attempts and no marker. No bypass or new product defect was observed, so no production follow-up patch is proposed.

  6. Data-model compatibility — passed. The pre-fix production owner at 2609b4f93bf851274e94635bc19ebe10cb624236 wrote actual SQLite deny, durable exact-command allow, and revoked-grant stores, plus nonempty synthetic canonical socket credentials. Current main read those same stores without converting or reconstructing them. All four production readers (snapshot, synchronous, synchronous read-only, asynchronous read-only) matched the complete old snapshot. Real worker-backed commitExecAuthorizationLocked plus its returned current guard produced the matrix below; requireExactCommandApproval verifies the persisted durable grant. Exact policy/raw bytes/hash and socket record hash remained unchanged in all nine fresh-process probes; foreign bytes stayed untouched. This establishes pre-change SQLite owner compatibility, not a packaged/latest-stable installer upgrade claim.

Old canonical policy Pre-fix owner, no legacy Main, no legacy Main, conflicting full/off legacy
deny denied denied denied
durable exact-command grant allowed allowed allowed
revoked grant denied denied denied

The compatibility writer is the old maintenance transaction owner; the current authorization kernel requires the durable exact-command grant. Fixture stores and commands are entirely synthetic; no production data or service was accessed.

Fresh focused test command, at the main SHA above:

pnpm test src/node-host/startup-state-readiness.test.ts src/flows/doctor-health.managed-approvals.test.ts --maxWorkers=1
# Test Files 2 passed (2); Tests 15 passed (15)

Actual host-execution results (all with the same retained permissive legacy file):

Canonical state / timing Real tool outcome Native target launch attempts Marker
canonical-deny Error: exec denied: host=gateway security=deny 0 absent
canonical-allow-control completed, exit 0; LANE2353_EXECUTED 1 present
canonical-revoked Error: exec denied: allowlist miss 0 absent
prepared-then-revoked Error: Exec approval changed before execution 0 absent

preparedRevocationBarrierReached=true, legacyUnchanged=true, pass=true; Gateway shutdown completed cleanly. The allowed command completed in 111 ms. No performance claim is inferred from this correctness run.

Complete live Gateway proof driver and command

Save the two files below in a fresh scratch directory outside the checkout. Run from the pinned main checkout with its existing dependencies and supported Node 24. The driver asserts the Git SHA, seeds canonical state in a separate process (so startup sees the foreign file on its first inspection), starts the real Gateway, waits for readiness, performs the four real exec calls, asserts the outcomes, writes results.json, and closes the Gateway. There are no Vitest/minimal-Gateway flags. Synthetic authentication is generated locally and never printed.

node --import ./scripts/tsx.mjs "$PROOF_DIR/proof.mts"
# PROOF_PASS

seed.mts:

const {updateExecApprovalsForMaintenance}=await import(process.cwd()+'/src/infra/exec-approvals-store.ts');
const {closeOpenClawStateDatabaseAsync}=await import(process.cwd()+'/src/state/openclaw-state-db.ts');
updateExecApprovalsForMaintenance(()=>({version:1,defaults:{security:'deny',ask:'off'},agents:{}}));
await closeOpenClawStateDatabaseAsync();

proof.mts:

import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { ChildProcess, execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import net from 'node:net';
import os from 'node:os';
const repo = process.cwd();
assert.equal(execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim(),'c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2');
const root = path.dirname(new URL(import.meta.url).pathname);
const cache = fs.mkdtempSync(path.join(os.tmpdir(),'lane2353-private-cache-'));
const state = path.join(root, 'state-' + Date.now());
fs.mkdirSync(state, {recursive:true});
process.env={PATH:process.env.PATH};
Object.assign(process.env, {HOME:state, OPENCLAW_STATE_DIR:state, OPENCLAW_CONFIG_PATH:path.join(state,'openclaw.json'), XDG_CONFIG_HOME:path.join(state,'config'), XDG_CACHE_HOME:cache});
const workspace=path.join(state,'workspace'); fs.mkdirSync(workspace);
const probe=path.join(workspace,'lane2353-probe');
fs.writeFileSync(probe, '#!/bin/sh\nprintf "executed:%s\\n" "$$" > "$1"\nprintf "LANE2353_EXECUTED\\n"\n', {mode:0o755});
const launches:any[]=[];
let phase='startup';
const nativeSpawn=ChildProcess.prototype.spawn;
ChildProcess.prototype.spawn=function(options:any) {
  if (JSON.stringify(options.args).includes(probe)) launches.push({phase,file:options.file,args:options.args});
  return nativeSpawn.call(this,options);
};
const listener=net.createServer(); await new Promise<void>(r=>listener.listen(0,'127.0.0.1',r));
const port=(listener.address() as net.AddressInfo).port; await new Promise<void>(r=>listener.close(()=>r()));
const token=randomUUID();
const config={agents:{defaults:{workspace,model:{primary:'openai/gpt-5.6-sol'}}}, tools:{exec:{host:'gateway',mode:'full'}},gateway:{mode:'local',port,bind:'loopback',auth:{mode:'token',token},controlUi:{enabled:false},tools:{allow:['exec']}},plugins:{enabled:false},cron:{enabled:false},discovery:{mdns:{mode:'off'}}};
fs.writeFileSync(process.env.OPENCLAW_CONFIG_PATH!,JSON.stringify(config));
const source=(name:string)=>import(path.join(repo,'src',name));
execFileSync(process.execPath,['--import',path.join(repo,'scripts/tsx.mjs'),path.join(root,'seed.mts')],{env:process.env,stdio:'inherit'});
const legacy=JSON.stringify({version:1,defaults:{security:'full',ask:'off'},agents:{}});
const legacyPath=path.join(state,'exec-approvals.json'); fs.writeFileSync(legacyPath,legacy);
const {runStartupConfigPreflight}=await source('commands/startup-config-preflight.ts');
const preflight=await runStartupConfigPreflight({gateway:true,observe:false});
const {startGatewayServer}=await source('gateway/server.ts');
const server=await startGatewayServer(port,{bind:'loopback',controlUiEnabled:false,startupConfigSnapshotRead:preflight});
const results:any={head:'c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2',state,route:'production createExecTool.execute(host=gateway), live Gateway approvals RPC',cases:[]};
try {
 await server.startupSettled;
 let ready; for(let i=0;i<120;i++){ready=await fetch(`http://127.0.0.1:${port}/readyz`);if(ready.status===200)break;await new Promise(r=>setTimeout(r,500));} assert.equal(ready!.status,200,await ready!.text());
 const {readStartupMigrationWarning}=await source('infra/state-migrations.messages.ts');
 assert.match(readStartupMigrationWarning(),/legacy-exec-approvals-conflict/);
 const {callGateway}=await source('gateway/call.ts');
 const rpc=(method:string,params?:unknown)=>callGateway({url:`ws://127.0.0.1:${port}`,token,config,method,params,skipImplicitAuth:true,timeoutMs:30000});
 const setPolicy=async(file:any)=>{const snapshot=await rpc('exec.approvals.get'); await rpc('exec.approvals.set',{baseHash:snapshot.hash,file});};
 const {createExecTool}=await source('agents/bash-tools.ts');
 const execTool=createExecTool({host:'gateway',security:'full',ask:'off',safeBins:[],cwd:workspace,agentId:'main'});
 async function invoke(label:string,allowed:boolean){
  phase=label; const marker=path.join(workspace,label+'.marker'); const before=launches.length;
  let body:any; try {body={ok:true,result:await execTool.execute(label,{command:`${probe} ${marker}`,workdir:workspace,yieldMs:10000})};} catch(error){body={ok:false,error:String(error)};}
  const result={label,body,observedNativeLaunches:launches.length-before,markerExists:fs.existsSync(marker)}; results.cases.push(result); console.log('CASE',JSON.stringify(result));
  if(allowed){assert.equal(result.markerExists,true);assert.ok(result.observedNativeLaunches>0);}
  else {assert.equal(result.markerExists,false);assert.equal(result.observedNativeLaunches,0);assert.match(JSON.stringify(body),/denied|deny|allowlist|approval changed/i);}
  assert.equal(fs.readFileSync(legacyPath,'utf8'),legacy);
 }
 await invoke('canonical-deny',false);
 const grant={version:1,defaults:{security:'allowlist',ask:'off'},agents:{main:{allowlist:[{id:'synthetic-path-grant',pattern:probe}]}}};
 await setPolicy(grant);
 await invoke('canonical-allow-control',true);
 await setPolicy({...grant,agents:{main:{allowlist:[]}}});
 await invoke('canonical-revoked',false);
 await setPolicy(grant);
 const {getProcessSupervisor}=await source('process/supervisor/index.ts');
 const supervisor=getProcessSupervisor(); const realSupervisorSpawn=supervisor.spawn.bind(supervisor);
 let barrierReached=false;
 supervisor.spawn=async(input:any)=>{
   if(phase==='prepared-then-revoked' && JSON.stringify(input.argv).includes(probe)){
     barrierReached=true;
     await setPolicy({...grant,agents:{main:{allowlist:[]}}});
   }
   return realSupervisorSpawn(input);
 };
 try {await invoke('prepared-then-revoked',false);assert.equal(barrierReached,true);}
 finally {supervisor.spawn=realSupervisorSpawn;}
 results.preparedRevocationBarrierReached=barrierReached;
 results.legacyUnchanged=true;results.pass=true;
} finally {
 fs.writeFileSync(path.join(root,'results.json'),JSON.stringify({...results,launches},null,2));
 await server.close({reason:'Synthetic proof complete'});
 await preflight.pluginCache?.[Symbol.asyncDispose]();
}
fs.rmSync(cache,{recursive:true,force:true});
console.log('PROOF_PASS');
process.exit(0);
Complete pre-change SQLite compatibility driver and commands

Use existing dependency-ready checkouts at the exact BASE and MAIN SHAs above. Save compat.mjs below outside either checkout. Each probe is a fresh process; the first two reads have no legacy file, and the last writes conflicting permissive JSON without clobbering existing files.

# BASE = checkout at 2609b4f93bf851274e94635bc19ebe10cb624236
# MAIN = checkout at c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2
mkdir "$PROOF_DIR/compat-replay"
for scenario in deny allowed revoked; do
  node --import "$BASE/scripts/tsx.mjs" "$PROOF_DIR/compat.mjs" --repo "$BASE" --root "$PROOF_DIR/compat-replay/$scenario" --mode seed --scenario "$scenario"
  node --import "$BASE/scripts/tsx.mjs" "$PROOF_DIR/compat.mjs" --repo "$BASE" --root "$PROOF_DIR/compat-replay/$scenario" --mode probe --scenario "$scenario" --output "$PROOF_DIR/compat-replay/$scenario-before.json"
  node --import "$MAIN/scripts/tsx.mjs" "$PROOF_DIR/compat.mjs" --repo "$MAIN" --root "$PROOF_DIR/compat-replay/$scenario" --mode probe --scenario "$scenario" --output "$PROOF_DIR/compat-replay/$scenario-main.json"
  node --import "$MAIN/scripts/tsx.mjs" "$PROOF_DIR/compat.mjs" --repo "$MAIN" --root "$PROOF_DIR/compat-replay/$scenario" --mode probe --scenario "$scenario" --conflict --output "$PROOF_DIR/compat-replay/$scenario-main-conflict.json"
done
# All 9 probes pass: canonicalUnchanged=true, socketUnchanged=true;
# conflicting-file probes also legacyUnchanged=true.

compat.mjs:

import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
const {values}=parseArgs({options:{repo:{type:'string'},root:{type:'string'},mode:{type:'string'},scenario:{type:'string'},conflict:{type:'boolean'},output:{type:'string'}}});
assert(values.repo && values.root && values.mode && values.scenario);
const repo=path.resolve(values.repo),root=path.resolve(values.root);
const scenario=values.scenario;
assert(['deny','allowed','revoked'].includes(scenario));
const sha=execFileSync('git',['-C',repo,'rev-parse','HEAD'],{encoding:'utf8'}).trim();
assert(['2609b4f93bf851274e94635bc19ebe10cb624236','c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2'].includes(sha));
if(values.mode==='seed') {assert(sha==='2609b4f93bf851274e94635bc19ebe10cb624236');fs.mkdirSync(root);}
process.env={PATH:process.env.PATH,HOME:root,USERPROFILE:root,OPENCLAW_HOME:root,OPENCLAW_STATE_DIR:root,OPENCLAW_CONFIG_PATH:path.join(root,'openclaw.json'),NO_COLOR:'1',OPENCLAW_DISABLE_BUNDLED_PLUGINS:'1'};
const load=(file)=>import(pathToFileURL(path.join(repo,file)).href);
const [store,authorization,credentials,state,snapshots,lifecycle]=await Promise.all([
 load('src/infra/exec-approvals-store.ts'),load('src/infra/exec-approvals-authorization.ts'),load('src/infra/client-credential-store.ts'),load('src/state/openclaw-state-db.ts'),load('src/infra/sqlite-readonly-location-cleanup.ts'),load('src/infra/worker-native-lifecycle.ts')]);
const hash=(value)=>createHash('sha256').update(typeof value==='string'?value:JSON.stringify(value)).digest('hex');
const command='/usr/bin/printf compatibility';
const grant={id:'compatibility-grant',pattern:'=command:'+hash(command).slice(0,16),source:'allow-always'};
const policy={version:1,defaults:{security:scenario==='deny'?'deny':'allowlist',ask:'on-miss',askFallback:'deny',autoAllowSkills:false},agents:{main:{allowlist:[grant]}}};
const legacyPath=path.join(root,'exec-approvals.json');
try {
 if(values.mode==='seed') {
  store.updateExecApprovalsForMaintenance(()=>policy);
  if(scenario==='revoked') store.updateExecApprovalsForMaintenance((file)=>({...file,agents:{...file.agents,main:{allowlist:[]}}}));
  credentials.runClientCredentialOperation(process.env,{kind:'socket.ensure',fallback:{socket_key:'current',socket_path:path.join(root,'canonical.sock'),socket_token:'synthetic-canonical-compatibility-socket',updated_at_ms:123},requested:{path:path.join(root,'canonical.sock'),token:'synthetic-canonical-compatibility-socket'}});
  const canonical=store.readExecApprovalsSnapshot();
  const socket=credentials.runClientCredentialOperation(process.env,{kind:'socket.read'});
  assert(socket.kind==='socket' && socket.socket?.socket_path===path.join(root,'canonical.sock') && socket.socket?.socket_token==='synthetic-canonical-compatibility-socket','Canonical synthetic socket must exist');
  fs.writeFileSync(path.join(root,'expected.json'),JSON.stringify({writer:sha,canonical,socketHash:hash(socket),expected:scenario==='allowed'?'allowed':'denied'}),{flag:'wx',mode:0o600});
  console.log(JSON.stringify({scenario,writer:sha,canonicalHash:hash(canonical.raw),socketHash:hash(socket)}));
 } else {
  const expected=JSON.parse(fs.readFileSync(path.join(root,'expected.json'),'utf8'));
  assert.equal(expected.writer,'2609b4f93bf851274e94635bc19ebe10cb624236');
  if(values.conflict)fs.writeFileSync(legacyPath,JSON.stringify({version:1,defaults:{security:'full',ask:'off'},agents:{},socket:{path:path.join(root,'foreign.sock'),token:'synthetic-foreign-compatibility-socket'}})+'\n',{flag:'wx',mode:0o600});
  const legacyBefore=values.conflict?fs.readFileSync(legacyPath):undefined;
  const canonical=store.readExecApprovalsSnapshot();
  assert.deepEqual(canonical,expected.canonical);
  assert.deepEqual(store.loadExecApprovals(),expected.canonical.file);
  assert.deepEqual(store.loadExecApprovalsReadOnly(),expected.canonical.file);
  assert.deepEqual(await store.loadExecApprovalsReadOnlyAsync(),expected.canonical.file);
  let outcome='allowed';
  try {
   const assertCurrent=await authorization.commitExecAuthorizationLocked({agentId:'main',matches:[],command,authorization:{source:'current-policy',security:'allowlist',ask:'on-miss',allowlistSatisfied:true,requireExactCommandApproval:true}});
   assertCurrent();
  } catch(error) {
   assert(error instanceof Error && error.message==='Exec approval changed before execution',String(error));
   outcome='denied';
  }
  assert.equal(outcome,expected.expected);
  assert.deepEqual(store.readExecApprovalsSnapshot(),expected.canonical);
  const socket=credentials.runClientCredentialOperation(process.env,{kind:'socket.read'});
  assert(socket.kind==='socket' && socket.socket?.socket_path===path.join(root,'canonical.sock') && socket.socket?.socket_token==='synthetic-canonical-compatibility-socket','Canonical synthetic socket must exist');
  assert.equal(hash(socket),expected.socketHash);
  if(legacyBefore)assert.deepEqual(fs.readFileSync(legacyPath),legacyBefore);
  const result={scenario,node:process.version,writer:expected.writer,reader:sha,conflictingLegacy:!!values.conflict,outcome,canonicalUnchanged:true,canonicalHash:hash(canonical.raw),socketUnchanged:true,socketHash:hash(socket),legacyUnchanged:values.conflict?true:null,readers:['snapshot','sync','sync-readonly','async-readonly'],authorization:'commitExecAuthorizationLocked + retained final guard; requireExactCommandApproval; no usage mutation'};
  assert(values.output);fs.writeFileSync(values.output,JSON.stringify(result,null,2));console.log(JSON.stringify(result));
 }
} finally {
 await state.closeOpenClawStateDatabaseAsync();
 await snapshots.cleanupSnapshotOperations();
 await lifecycle.closeDefaultRetainedNativeWorkerSource();
}

No source/schema/config-contract change was needed for this closeout (additional production LOC: 0). The separate Windows-node test HOME/state-isolation follow-up remains outside this PR. Please evaluate all six items against this evidence, including the previously reviewed older head; none should be waived based on head age.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper could not start a re-review for this item.
Reason: re-review requires an open issue or PR.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
…96401)

* fix: preserve Gateway startup with retained legacy exec approvals

* test: cover degraded legacy approvals in startup siblings
RomneyDa added a commit that referenced this pull request Nov 12, 2026
Retain conflicting, invalid, or unreadable legacy input with an actionable
warning while canonical SQLite approvals remain authoritative. When no
canonical policy exists, keep execution unavailable rather than importing
legacy authority or blocking unrelated Gateway startup.

Adapt credential preparation to the release branch and retain its database
admission and runtime intent ownership. Cover native Gateway startup,
canonical policy reads/writes, node readiness, and Doctor consumers.

Independent local review omitted by explicit release-owner instruction.
Full release qualification remains separate from this bounded backport.

(cherry picked from commit a0ec2b5)

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit 74e2e4117388338a1f362c2b276b2d3b02cbbde7)
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 16, 2026
Release-specific port of openclaw#196401. Preserve missing-canonical refusal and malformed-policy fail-closed behavior across workers, Node readiness and Doctor. Independent local review waived by Dallin; full CI qualification pending.

(cherry picked from commit a0ec2b5)

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

Labels

commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: L 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