Repository navigation
refactor(macos): move PortGuardian state to SQLite - #110527
Conversation
|
Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 12:47 PM ET / 16:47 UTC. Summary PR surface: Tests +54, Docs +10, Other +2109. Total +2173 across 24 files. Reproducibility: no. high-confidence live reproduction was independently established in this read-only review. The current JSON read/merge/write ownership path and the proposed crash/concurrency failure mode are clear from the supplied source context, but no current-main failure scenario was run. Review metrics: 1 noteworthy metric.
Stored data model Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Proof guidance:
Risk before merge
Maintainer options:
Next step before merge
Maintainer decision needed
Security Review detailsBest possible solution: Land one canonical SQLite-only PortGuardian owner only after a maintainer accepts the one-way downgrade/mixed-version contract and the PR contains redacted, inspectable final-head native evidence for migration and orphan recovery. Do we have a high-confidence way to reproduce the issue? No high-confidence live reproduction was independently established in this read-only review. The current JSON read/merge/write ownership path and the proposed crash/concurrency failure mode are clear from the supplied source context, but no current-main failure scenario was run. Is this the best way to solve the issue? Unclear until maintainers accept the upgrade contract: using the existing canonical SQLite table is the maintainable direction, but retiring a host-global JSON ledger requires final-head native proof and an explicit downgrade/mixed-version policy. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against c8fe8f102f97. Label changesLabel justifications:
Evidence reviewedPR surface: Tests +54, Docs +10, Other +2109. Total +2173 across 24 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
Review history (12 earlier review cycles; latest 8 shown)
|
c1f0e62 to
36219f8
Compare
a6b74d8 to
7fd9b3a
Compare
36219f8 to
4328e27
Compare
7fd9b3a to
0fa7512
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
4328e27 to
d7c329c
Compare
0fa7512 to
41e3e75
Compare
d4889f4 to
bd1fc1e
Compare
|
Merged via squash.
|
* refactor: compose native SQLite bootstrap tables * refactor: share native SQLite state bootstrap * refactor(macos): move PortGuardian state to SQLite * test: align PortGuardian future-schema fixture * fix(macos): reserve PortGuardian ledger across tunnel spawn * fix(ci): align PortGuardian migration gates * fix(macos): tolerate vanished SQLite sidecars * fix(macos): revalidate PortGuardian writes * test(macos): use sqlite identity bootstrap
* refactor: compose native SQLite bootstrap tables * refactor: share native SQLite state bootstrap * refactor(macos): move PortGuardian state to SQLite * test: align PortGuardian future-schema fixture * fix(macos): reserve PortGuardian ledger across tunnel spawn * fix(ci): align PortGuardian migration gates * fix(macos): tolerate vanished SQLite sidecars * fix(macos): revalidate PortGuardian writes * test(macos): use sqlite identity bootstrap
* refactor(apple): simplify old shared and macOS bookkeeping Replace redundant generations with existing cancellation or actual owner identity, consolidate parallel fallback/policy paths, and remove test-only forwarding layers. Preserve authority, FIFO, durable state, resource bounds, public protocol/config shapes, signing, permissions, and visible rendering. Reuse canonical session-key normalization for Voice Wake delivery selection: opaque Signal group IDs remain case-sensitive and main aliases are not added. Use canonical IP-literal policy for discovery labels and remote CLI validation. Best-effort tradeoffs accepted - Palette generation (#159350): synthetic direct completions bypassed the sole cancellation-owning caller; unsupported future callers can show stale results until the next search. Current cancellation/request/agent checks remain. - Link preview generation (#160710): synthetic URL replacement without caller cancellation is outside the SwiftUI task lifecycle; a late cosmetic result can remain until the next refresh. Network/SSRF checks and bounded caches remain. - Sidebar preview generation (#147197): same-request overlapping cache reads can finish out of order; no linked human failure report, and a later refresh replaces the cosmetic projection. Owner/request checks remain. - Source-preview producer revision (#148906): duplicate of exact task cancellation, with no human failure report. Consumer revision and authenticated resource authority remain. - Mermaid generations (#135470/#135746): feature stress fixtures, no linked human race report. Exact subscriber cancellation and job/WebView identity retain the same admission; no extra failure accepted. - Camera JPEG UUID (#107879): duplicates exact task cancellation; #107804 was a human feature request, not a generation-specific incident. Captured session/agent/route and attachment admission remain. - Discovery generation (#145435): speculative queued callbacks, no linked human incident. A stopped browser may publish one late discovery projection; next discovery/refresh repairs it. Connection authority remains separate. - FSEvents generation (#145453): synthetic stop/restart fixtures, no linked human incident. An old callback after restart may cause one extra refresh; serial lifecycle ownership and pending-work cancellation remain. - Menu generations (#139688): feature-local late-result fixtures, no linked human incident. Exact task cancellation replaces duplicate tokens; drain-before-disconnect and real consumer/window authority remain. - Cron generation (#131466/#137502): #138209 cut every load over to one cancel-and-drain chain. No direct concurrent load caller remains; cancellation and physical source leases stay checked after awaits. - WebChat visibility acknowledgement/retry (#113634/#137089): synthetic timeout/reconnect interleavings, no linked human incident. A timed-out visibility update is best effort until the next transition/reconnect; FIFO and live socket leases remain. - WebChat cleanup UUID (#113634/#137089): retain one bounded completed Task handle per live connection instead of matching cleanup tokens. Completion releases captures; replacement/retirement removes the handle. - Child-exit polling (#145437): synthetic missed-notification coverage, no linked human report. A lost OS exit notification may wait for the existing deadline; final non-reaping liveness/status checks and cleanup remain. - Realtime iterator borrowing trap (#156772): every real consumer awaits its own iterator sequentially. Unsupported concurrent next calls no longer get a custom custody protocol; bounded stream/cancellation/socket checks remain. - Receipt projection admission (#161745): both real callers already match receipt and row identity immediately before synchronous projection. Those effect checks remain; no unsupported internal caller is defended twice. - Recap attribution heuristics (#112188/#113084): synthetic guard matrix, no linked human race report. Missing initial rows or very late unrelated completion may supply a cosmetic footer; per-session freshness, failed-turn handling and settled results remain. - PortGuardian per-write schema scans (#110527): synthetic live-handle version advance, no linked human incident. Concurrent external schema upgrades are best effort until reopen; initial admission, migration locks, receipts, transactions and durability remain. - Unread queue counter (#110019): actual Task equality replaces the duplicate integer token. Exact-tail reclamation, bounded bookkeeping, FIFO and route authority remain unchanged. Review dispositions: the claimed Task compilation failure is disproved by the selected SDK's Equatable conformance and native builds. Repeated receipt identity admission is unnecessary at its internal projector because both real callers retain it immediately before projection. Per-write schema revalidation was declined under the explicit best-effort policy above. Proof and scope Net production reduction: 369 lines (148 added, 517 deleted), excluding tests. Fresh seven-day census permits all substantive production edits; the only recent caller change is the unavoidable one-line fallback-to-parse rename. Shared Swift build passed. Final focused shared tests passed 396 cases in six suites (6.683s execution), Watch decoder tests passed five cases (0.003s), and isolated whole-owner native tests passed 16 cases. macOS SwiftPM compiled all products and the test bundle. Final macOS and iOS/Watch xcodebuild builds passed (89.60s and 120.87s wall), without signing changes or app launches. Canonical Apple lint/format checks passed; the initial iOS format failure in WatchCommands was ours and corrected, with no gate weakened. Lint-suppression tests passed 3/3 (14.09s wall). Earlier runtime cycles and Madge each reported 0; the TypeScript graph is unchanged. Native localization stayed at 4476 entries. The 45 original packaging/elevation timeout cases passed one focused retry (94.79s wall), with no assertion/budget change and no claim of a diagnosed fix. Known gaps: seven issues remained in the earlier ChatStreamReplayTests narration=false package cases; causality/current-main attribution is unproven. App-hosted macOS tests were not executed on the operator desktop. No hosted CI or PR was started: the explicit BELOW-500 rule requires a branch-only handoff. * refactor(ui): consolidate old UI owners and validation Share route decoding, attachment retention, gallery preparation, transient identity encoding, override copying, and extension classification. Remove duplicate admission/schema mirrors and obsolete supported-browser fallbacks. Both Lit and Solid paths remain; no rendering change is intended. No config, protocol, persisted shape, dependency, or public SDK change. Best-effort tradeoffs accepted - Malformed internal native requests (#140988): all callers are typed and native hosts validate at the effect; their error replaces the renderer mirror. - Worker replacement during an identity query (#140484): added for synthetic autoreview interleavings, not a human incident. Return false; normal worker announcements and foreground recovery observe the next active worker. - Native readiness changing between synchronous checks (#140484/#109719): rely on queued events. A broken native event can require another worker event or reload; camera readiness retains its existing five-second error deadline. - Overlapping application-root health reporters (#152638): startup mounts one root. Unsupported overlapping roots are last-publication-wins; the actual reported health/status feature and native trusted-document checks remain. - Polling after stop (#139704): its sole owner retires eligibility first. Scheduling now uses that owner admission, not a separate read-only generation. - Resetting an observer without retiring its connection (#116887): no production caller does this. Canonical connection epochs remain the sole retirement owner; unsupported direct live-scope reset no longer fences an old response separately. - Upload policy changing during local reads (#158567): decoded/hash work can finish. Draft publication and every upload request retain live policy checks. - Missing supported browser primitives (#105240/#151388/#100024/#102745): unsupported runtimes error instead of code-point initials, skipped input yield, wall-clock timing, or approximate microtask paint. The human progress-card fix in #151386 keeps its browser yield and durable FIFO handoff unchanged. - URL APIs disappearing after URL creation (#100024/#149330): supported browsers keep paired APIs. An unsupported replaced global can throw during cleanup; undefined URLs, creation fallback, cancellation and release ordering remain. - Malformed internal MCP calls bypassing AppBridge (#161747): may throw. The SDK still rejects malformed wire blocks before dispatch, proved over real in-memory App/AppBridge transport. UI content, authority, confirmation and custody policy remain. The introducing PR cites no human incident for the second mirror. Production: +176/-394, net -218 lines across 21 eligible old files. Tests: +30. Focused owner/sibling tests, targeted types/lint/format, lint-suppression and independent P0-P2 review pass. Import edges are unchanged; runtime/Madge cycle proof remains zero. Whole-tree Knip timed out at existing limits; heavy gallery renderer runs did not reach assertions, while its owning controller suite passed. * refactor(ui): remove obsolete Fetch capability branch The supported Control UI browser floor includes Fetch. Start attachment metadata reads directly rather than leaving an unsupported runtime in a permanent checking state. Best-effort tradeoffs accepted - Missing global Fetch: the guard originated in #64104, whose feature report cites no human missing-Fetch incident. An unsupported runtime that replaces Fetch now reaches the existing rejected-request/unavailable path. Metadata validation, auth/tickets, allow POST, cancellation, resource admission, expiry and bounded retry remain unchanged. No intended rendering change. Unchanged lifecycle baseline: 21/21, 25.09 s. Final lifecycle and attachment siblings: 50/50, 14.77 s. UI types, typed lint, formatting and lint-suppression checks pass. This cut removes five production lines including formatter reflow, bringing the lane to 223 net production lines removed. Fresh independent P0-P2 review is scoped-clean with no actionable findings. * fix(ui): use global frame scheduling APIs Preserve double-frame paint timing and cancellation without requiring a Window object in renderer-free hosts that supply the standard global APIs. The existing access suite reproduces seven unhandled errors before this fix and passes on main; all 130 affected cases plus 262 timing/state/send sibling cases now pass without test changes.
…#170823) * refactor(apple): simplify old shared and macOS bookkeeping Replace redundant generations with existing cancellation or actual owner identity, consolidate parallel fallback/policy paths, and remove test-only forwarding layers. Preserve authority, FIFO, durable state, resource bounds, public protocol/config shapes, signing, permissions, and visible rendering. Reuse canonical session-key normalization for Voice Wake delivery selection: opaque Signal group IDs remain case-sensitive and main aliases are not added. Use canonical IP-literal policy for discovery labels and remote CLI validation. Best-effort tradeoffs accepted - Palette generation (openclaw#159350): synthetic direct completions bypassed the sole cancellation-owning caller; unsupported future callers can show stale results until the next search. Current cancellation/request/agent checks remain. - Link preview generation (openclaw#160710): synthetic URL replacement without caller cancellation is outside the SwiftUI task lifecycle; a late cosmetic result can remain until the next refresh. Network/SSRF checks and bounded caches remain. - Sidebar preview generation (openclaw#147197): same-request overlapping cache reads can finish out of order; no linked human failure report, and a later refresh replaces the cosmetic projection. Owner/request checks remain. - Source-preview producer revision (openclaw#148906): duplicate of exact task cancellation, with no human failure report. Consumer revision and authenticated resource authority remain. - Mermaid generations (openclaw#135470/openclaw#135746): feature stress fixtures, no linked human race report. Exact subscriber cancellation and job/WebView identity retain the same admission; no extra failure accepted. - Camera JPEG UUID (openclaw#107879): duplicates exact task cancellation; openclaw#107804 was a human feature request, not a generation-specific incident. Captured session/agent/route and attachment admission remain. - Discovery generation (openclaw#145435): speculative queued callbacks, no linked human incident. A stopped browser may publish one late discovery projection; next discovery/refresh repairs it. Connection authority remains separate. - FSEvents generation (openclaw#145453): synthetic stop/restart fixtures, no linked human incident. An old callback after restart may cause one extra refresh; serial lifecycle ownership and pending-work cancellation remain. - Menu generations (openclaw#139688): feature-local late-result fixtures, no linked human incident. Exact task cancellation replaces duplicate tokens; drain-before-disconnect and real consumer/window authority remain. - Cron generation (openclaw#131466/openclaw#137502): openclaw#138209 cut every load over to one cancel-and-drain chain. No direct concurrent load caller remains; cancellation and physical source leases stay checked after awaits. - WebChat visibility acknowledgement/retry (openclaw#113634/openclaw#137089): synthetic timeout/reconnect interleavings, no linked human incident. A timed-out visibility update is best effort until the next transition/reconnect; FIFO and live socket leases remain. - WebChat cleanup UUID (openclaw#113634/openclaw#137089): retain one bounded completed Task handle per live connection instead of matching cleanup tokens. Completion releases captures; replacement/retirement removes the handle. - Child-exit polling (openclaw#145437): synthetic missed-notification coverage, no linked human report. A lost OS exit notification may wait for the existing deadline; final non-reaping liveness/status checks and cleanup remain. - Realtime iterator borrowing trap (openclaw#156772): every real consumer awaits its own iterator sequentially. Unsupported concurrent next calls no longer get a custom custody protocol; bounded stream/cancellation/socket checks remain. - Receipt projection admission (openclaw#161745): both real callers already match receipt and row identity immediately before synchronous projection. Those effect checks remain; no unsupported internal caller is defended twice. - Recap attribution heuristics (openclaw#112188/openclaw#113084): synthetic guard matrix, no linked human race report. Missing initial rows or very late unrelated completion may supply a cosmetic footer; per-session freshness, failed-turn handling and settled results remain. - PortGuardian per-write schema scans (openclaw#110527): synthetic live-handle version advance, no linked human incident. Concurrent external schema upgrades are best effort until reopen; initial admission, migration locks, receipts, transactions and durability remain. - Unread queue counter (openclaw#110019): actual Task equality replaces the duplicate integer token. Exact-tail reclamation, bounded bookkeeping, FIFO and route authority remain unchanged. Review dispositions: the claimed Task compilation failure is disproved by the selected SDK's Equatable conformance and native builds. Repeated receipt identity admission is unnecessary at its internal projector because both real callers retain it immediately before projection. Per-write schema revalidation was declined under the explicit best-effort policy above. Proof and scope Net production reduction: 369 lines (148 added, 517 deleted), excluding tests. Fresh seven-day census permits all substantive production edits; the only recent caller change is the unavoidable one-line fallback-to-parse rename. Shared Swift build passed. Final focused shared tests passed 396 cases in six suites (6.683s execution), Watch decoder tests passed five cases (0.003s), and isolated whole-owner native tests passed 16 cases. macOS SwiftPM compiled all products and the test bundle. Final macOS and iOS/Watch xcodebuild builds passed (89.60s and 120.87s wall), without signing changes or app launches. Canonical Apple lint/format checks passed; the initial iOS format failure in WatchCommands was ours and corrected, with no gate weakened. Lint-suppression tests passed 3/3 (14.09s wall). Earlier runtime cycles and Madge each reported 0; the TypeScript graph is unchanged. Native localization stayed at 4476 entries. The 45 original packaging/elevation timeout cases passed one focused retry (94.79s wall), with no assertion/budget change and no claim of a diagnosed fix. Known gaps: seven issues remained in the earlier ChatStreamReplayTests narration=false package cases; causality/current-main attribution is unproven. App-hosted macOS tests were not executed on the operator desktop. No hosted CI or PR was started: the explicit BELOW-500 rule requires a branch-only handoff. * refactor(ui): consolidate old UI owners and validation Share route decoding, attachment retention, gallery preparation, transient identity encoding, override copying, and extension classification. Remove duplicate admission/schema mirrors and obsolete supported-browser fallbacks. Both Lit and Solid paths remain; no rendering change is intended. No config, protocol, persisted shape, dependency, or public SDK change. Best-effort tradeoffs accepted - Malformed internal native requests (openclaw#140988): all callers are typed and native hosts validate at the effect; their error replaces the renderer mirror. - Worker replacement during an identity query (openclaw#140484): added for synthetic autoreview interleavings, not a human incident. Return false; normal worker announcements and foreground recovery observe the next active worker. - Native readiness changing between synchronous checks (openclaw#140484/openclaw#109719): rely on queued events. A broken native event can require another worker event or reload; camera readiness retains its existing five-second error deadline. - Overlapping application-root health reporters (openclaw#152638): startup mounts one root. Unsupported overlapping roots are last-publication-wins; the actual reported health/status feature and native trusted-document checks remain. - Polling after stop (openclaw#139704): its sole owner retires eligibility first. Scheduling now uses that owner admission, not a separate read-only generation. - Resetting an observer without retiring its connection (openclaw#116887): no production caller does this. Canonical connection epochs remain the sole retirement owner; unsupported direct live-scope reset no longer fences an old response separately. - Upload policy changing during local reads (openclaw#158567): decoded/hash work can finish. Draft publication and every upload request retain live policy checks. - Missing supported browser primitives (openclaw#105240/openclaw#151388/openclaw#100024/openclaw#102745): unsupported runtimes error instead of code-point initials, skipped input yield, wall-clock timing, or approximate microtask paint. The human progress-card fix in openclaw#151386 keeps its browser yield and durable FIFO handoff unchanged. - URL APIs disappearing after URL creation (openclaw#100024/openclaw#149330): supported browsers keep paired APIs. An unsupported replaced global can throw during cleanup; undefined URLs, creation fallback, cancellation and release ordering remain. - Malformed internal MCP calls bypassing AppBridge (openclaw#161747): may throw. The SDK still rejects malformed wire blocks before dispatch, proved over real in-memory App/AppBridge transport. UI content, authority, confirmation and custody policy remain. The introducing PR cites no human incident for the second mirror. Production: +176/-394, net -218 lines across 21 eligible old files. Tests: +30. Focused owner/sibling tests, targeted types/lint/format, lint-suppression and independent P0-P2 review pass. Import edges are unchanged; runtime/Madge cycle proof remains zero. Whole-tree Knip timed out at existing limits; heavy gallery renderer runs did not reach assertions, while its owning controller suite passed. * refactor(ui): remove obsolete Fetch capability branch The supported Control UI browser floor includes Fetch. Start attachment metadata reads directly rather than leaving an unsupported runtime in a permanent checking state. Best-effort tradeoffs accepted - Missing global Fetch: the guard originated in openclaw#64104, whose feature report cites no human missing-Fetch incident. An unsupported runtime that replaces Fetch now reaches the existing rejected-request/unavailable path. Metadata validation, auth/tickets, allow POST, cancellation, resource admission, expiry and bounded retry remain unchanged. No intended rendering change. Unchanged lifecycle baseline: 21/21, 25.09 s. Final lifecycle and attachment siblings: 50/50, 14.77 s. UI types, typed lint, formatting and lint-suppression checks pass. This cut removes five production lines including formatter reflow, bringing the lane to 223 net production lines removed. Fresh independent P0-P2 review is scoped-clean with no actionable findings. * fix(ui): use global frame scheduling APIs Preserve double-frame paint timing and cancellation without requiring a Window object in renderer-free hosts that supply the standard global APIs. The existing access suite reproduces seven unhandled errors before this fix and passes on main; all 130 affected cases plus 262 timing/state/send sibling cases now pass without test changes.
#110392 landed as prerequisite commit
98410d986eee7ce7cff8e8466c6d5f9314ae784b; this PR now targetsmain.What Problem This Solves
The macOS PortGuardian orphan-tunnel ledger remains in a host-global JSON file even though OpenClaw already ships a canonical SQLite table for the same durable records. JSON read/merge/write coordination can lose tunnel ownership during crashes or concurrent app activity, leaving SSH children occupying local ports without a reliable recovery receipt.
Why This Change Was Made
PortGuardian now uses the existing
macos_port_guardian_recordstable in the host-global OpenClaw state database. The logical record shape remains unchanged:pid,port,command,mode, andtimestamp. This is additive at the schema and API boundaries: no table change, schema-version bump, wire-format change, or dual-write path.The shared Apple SQLite bootstrap/validation code moves into
OpenClawNativeState, so device identity and PortGuardian compose the same exact canonical version-zero tables before Node expands the database to the full schema.Legacy
port-guard.jsonis a one-time migration input only. Migration snapshots under the shipped Darwin lock, plans process reconciliation outside both the file lock and SQLite transaction, revalidates the exact source, applies a short synchronous transaction, verifies receipts, and retires the JSON file. Runtime then reads and writes SQLite only.Mixed-version app copies fail closed. A signed storage-capability marker is accepted only when Security.framework metadata matches the running process kernel CDHash. Tunnel launch holds a guardian reservation from completed legacy reconciliation through process spawn and durable receipt commit. Every mutation transaction revalidates the supported schema and canonical table, including retained connections after another process advances the database.
User Impact
macOS SSH tunnel ownership and orphan cleanup become transactionally durable across concurrent app instances, PID reuse, crashes, delayed teardown, and legacy migration. Fresh installs no longer create the JSON ledger or lock sidecar.
This is a one-way storage cutover. Downgrading afterward to an older JSON-only app does not expose receipts written only to SQLite; rollback requires restoring a compatible backup or upgrading again.
Maintainer Decision
Accepted by the maintainer's explicit
land allinstruction:Evidence
bd1fc1eb3b93c55cc5d8269ecb0438454cafb449, targetingmainafter refactor(state): move device identity into canonical SQLite state #110392 landed.git range-diffproves all 9 PortGuardian commits patch-identical to prior fully reviewed headd4889f49d1dbdb8e9a4f7bc440f81b7387696f7a.SIGNED_PORTGUARDIAN_PROOF=PASS, then snapshot restore stopped the VM.macos-swift,ios-build, andopenclaw/ci-gateall passed in run 29652606607.OpenClawKittarget build and exact SwiftFormat check.AI assistance was used for implementation and review. Maintainer-directed design, focused tests, signed native behavior proof, and patch-identity checks were performed before handoff.