Skip to content

refactor(infra): trust prepared internal owner facts - #178563

Merged
steipete merged 5 commits into
mainfrom
deslop/z40-21-owner-residue-20261015
Oct 20, 2026
Merged

steipete merged 5 commits into
mainfrom
deslop/z40-21-owner-residue-20261015

Conversation

@steipete

@steipete steipete commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Internal read owners still reconstruct or revalidate facts they already own, forward through single-use wrappers, and repeat Windows process inspection for each socket row. This residue removes 105 net production lines across 21 production files, plus focused existing-owner test updates and one generated inventory line-number correction. It uses the campaign's 100-line residue waiver; it is not a LARGE PR.

What changed

Use normalized voice-wake targets and prepared pairing/requester payloads directly. Flatten single-use Goal/message-cut/conversation-selection wrappers and unused delivery callback plumbing. Return display preference snapshots without an inner replay loop, retaining the real HTTP/Web Push authority predicates and all writes/CAS/settlement. Remove redundant background owner fields, empty transaction callbacks, Doctor pre-delete checks and parser forwarding.

Validate queue replacement IDs once in the existing kernel rather than twice; make its assertion private after the adapter no longer needs it. Remove ignored cron helper input members left behind by #168996, without changing public CronJob types or any runtime routing branch.

Windows inspection now uses one request-local netstat snapshot and the existing bounded per-PID enrichment owner. Single-port and connection APIs use the same owner. Keep native collectors, tasklist/CIM/WMIC fallback, environment isolation, abort/deadline handling, bind probes and effect-time process identity checks. Presence retains its private non-evictable self row directly; malformed external text and numeric bounds still meet the existing boundary.

Best-effort tradeoffs accepted

  • A display settings read overlapping an edit can return its captured older value once; subsequent reads/events update it. perf(gateway): avoid redundant tail RPC reads #172433 introduced a synthetic delayed-RPC ordering regression, not an identified human incident. Write/CAS policy and external-effect authority remain.
  • Background settings likewise use their captured snapshot; private image HTTP retains its outer freshness/auth retry and live authority. feat: personalize session backgrounds #168301 supplies the original nested mechanism, with no inspected human report requiring both replay layers.
  • A buggy future internal producer of normalized voice-wake targets, pairing payloads, requester snapshots or delivery summaries fails visibly instead of receiving another normalization/fallback pass. The actual unknown/persisted-input boundaries stay. Provenance: refactor(infra): consolidate variant handling and lifecycle projections #167012, refactor(gateway): register and redeem device join codes in workers #164759 and refactor(sessions): move gateway discovery reads into workers #169311; inspected evidence did not identify an actual-use human incident requiring those repeated internal passes. Returned voice-wake targets can alias their normalized/default owner object; the real caller only reads them.
  • Placement probes are used by reference rather than defensively copied; the actual caller constructs the private records and does not mutate them during the read. Cancellation, discovery precedence and destructive-effect admission stay.
  • Windows ports in one batch share a diagnostic instant and one metadata outcome per PID, including a transient missing result. Previously each port/socket row retried the same facts. No cross-request reuse or process-termination authority is introduced; refactor(infra): add p-map concurrency limit to ports-inspect enrichment #107121's bounded enrichment remains.
  • Presence's matched regex cannot omit its mandatory captures; fix(core): make indexed access explicit across remaining src (NUIA phase 3b) #104773 added the redundant branch during indexed-access cleanup. External mismatch/finite-number handling remains. The self-row fallback predates the private symbol invariant introduced by fix(infra): keep presence bounded under entry pressure #134740; that row is initialized once and excluded from deletion. A future invariant violation now fails visibly rather than reconstructing self. TTL/cap/spoof/pending/privacy protections stay.
  • Deleting an absent optional Doctor data property is a no-op; the redundant prechecks do not protect a migration boundary. The parser entry point keeps its implementation and unknown-input checks. Literal empty stage/rollback callbacks disappear; the existing optional-call owner preserves commit/invalidation and all transaction behavior. No schema, durability, protocol or config shape changes.
  • A future invalid internal queue replacement ID pair reaches shared-state admission before its unchanged kernel error, but cannot replace any row. refactor: consolidate outbound delivery and auth profile internals #167002 consolidated the same precheck into a shared function while retaining its duplicate invocation. Keep ID validation, exact source comparison, namespace/staging checks, transactions and settlement. Cron's unused type-member removal has no runtime tradeoff.

All Phase E standalone memory backend/factory/registry/expiry/federation code and tests are unchanged. Security, FIFO, accepted native work settlement and public contracts stay.

Evidence

Focused proof: 132 passing cases across eight port/presence suites, plus 14 passing suppression cases (two shards, 227.81s wrapper; infra 173.11s including bounded native-worker compilation). Five existing platform/environment skips: native Windows tasklist, native Linux ss and three unavailable loopback-bind cases on this Mac. No skips, retries, timeouts or assertions were changed. The new ports fixture file is covered by that full-file run; hosted CI owns its CI-seconds/native-platform result.

Three-root targeted types, three-file typed lint/format and diff check passed. Earlier unchanged-input proof has 292 distinct passing cases across 25 files, including the same 14 suppression cases; canonical database-worker inventory passed. Runtime/Madge cycles were zero; the later cuts add no import edges, so they cannot introduce a new cycle component. Independent review of the 100-line base is scoped-clean P0–P2 with no actionable findings. Requester suites requiring broad runtime preparation remain hosted-CI gaps, not disabled tests.

The namespace append passed targeted types/typed lint/format, independent scoped-clean P0–P2 review, all 12 real migration cases and 14 suppression cases (124.23s wrapper; migration 98.58s including native worker preparation). The canonical inventory was regenerated; its only delta is the adapter's first-call position 26→24, without weakening counts or evidence. The cron append passed seven-root caller types, lint/format, independent scoped-clean P0–P2 review and all seven unchanged owner cases (2.36s Vitest, 12.38s wrapper). Final canonical inventory verification passed. The 100-line base and both later source increments each received independent review; all unchanged-input proof is retained rather than counted twice.

CI follow-up: PostgreSQL conformance (3/3), run 39460557343/job 118759613460, exposed one stale test expectation for the removed private snapshot profileId field. That failure is ours, not inherited. The existing case now asserts real background data through the same lock and transaction boundaries: empty first profile, a distinct retained target image visible after an uncommitted canonical merge, and the empty result again after rollback. Advisory lock, 100ms lock timeout, read-only snapshot, enclosing transaction checks and cleanup remain. No production change, timeout increase, retry, skip or suppression was needed.

That exact case passed with no skips against a task-owned PostgreSQL 18.6 Unix-socket database with TCP disabled: 1.835s test body, 84.86s Vitest including 76.619s canonical worker preparation, 103.63s wrapper. All 14 suppression cases passed separately in 27.08s wrapper. The single-test-root typecheck, typed lint and formatting passed; independent P0–P2 review is scoped-clean. This adds one distinct passing case/file to the retained proof, for 444 cases across 36 files. Hosted CI on the repaired exact head remains the broad proof; this is not a Linux or whole-suite local claim.

Deterministic Windows fixture: two ports, IPv4+IPv6 rows, one PID, duplicate requested port. Before: 10 native requests, or 14 with WMIC fallback. After: 3 / 4 with identical listener projections. Red control failed only those counts; final full-file run passed both fixtures. No latency, CPU or native-Windows claim.

@clawsweeper

clawsweeper Bot commented Oct 20, 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.

@steipete
steipete marked this pull request as ready for review October 20, 2026 16:47
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations labels Oct 20, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T17:23:56.143508Z 10f62ba 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 Oct 20, 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: 10f62ba7778b468a5965f089eed29542cbeaf1dd
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/infra/device-pairing-join-code.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR removes redundant internal validation and forwarding, simplifies snapshot reads, and shares Windows socket and process inspection within each request.

Example: Windows ports 18789 and 19001 each have IPv4 and IPv6 listeners owned by PID 4242.

  • Before: Inspection repeats native requests for each port and socket row: 10 requests, or 14 with WMIC fallback.
  • After: Inspection shares one netstat snapshot and one metadata lookup per PID: 3 requests, or 4 with fallback.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner consolidation with supporting integration evidence, but the reply-contract cutover leaves a confirmed failing test consumer.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal refactor is outside the ordinary contributor proof gate; supplied tests support the changed owners, and source tracing found no material change to authorized principals or final-effect checks.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Repeated Windows diagnostic subprocesses add unnecessary work, while redundant internal layers increase maintenance cost.
Reason: The maintainer-authored direction explicitly accepts bounded snapshot staleness and consolidates work within existing owners without adding configuration or public APIs.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the maintainer-directed simplification is useful, but removing the background reply’s profileId leaves a PostgreSQL test consumer broken.

Priority: P3
Reviewed head: 2399057ab150c30edf2aabb46bce5fed2bbfa68a

Before merge

  • Migrate the PostgreSQL snapshot test before removing profileId (P2) - Removing this reply field leaves src/infra/database-engine/state-read-lock.postgres.test.ts expecting it in the full snapshot at line 63 and reading it at lines 72, 85, and 92. Exact-head PostgreSQL conformance already fails with the missing-field diff, and the property accesses no longer match UserBackgroundReadReply. Update that consumer in this PR, using distinguishable profile-specific snapshot results to retain its enclosing-read, profile-merge, and rollback assertions without restoring redundant production metadata.

Findings

  • [P2] Migrate the PostgreSQL snapshot test before removing profileId — src/state/user-background.kernel.ts:65-67

Tests

  • Missing end-to-end proof: The supplied current-change evidence exercises tests and fixtures; the inspected screenshots show historical presence behavior rather than this head’s shipped entry points.
Agent review details

How this fits together

Gateway and worker callers supply prepared routing, identity, and storage facts to infrastructure owners, which return diagnostic snapshots or perform admitted database operations.

flowchart TD
A[Gateway and CLI callers] --> B[Prepared internal facts]
B --> C[Existing infrastructure owners]
C --> D[Database workers]
C --> E[Native socket collectors]
D --> F[Snapshots and admitted writes]
E --> F
Loading

Technical review

Best possible solution:

Keep the simplifications and migrate the PostgreSQL test to profile-specific snapshot results while preserving lock, merge, and rollback coverage.

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

Exact-head CI reproduces the PostgreSQL assertion mismatch, and source confirms three additional accesses to the removed property; no current-main product bug is claimed.

Is this the best way to solve the issue?

The existing owners support the simplification, but the reply-contract cutover must include its PostgreSQL test consumer.

Full review comments:

  • [P2] Migrate the PostgreSQL snapshot test before removing profileId — src/state/user-background.kernel.ts:65-67
    Removing this reply field leaves src/infra/database-engine/state-read-lock.postgres.test.ts expecting it in the full snapshot at line 63 and reading it at lines 72, 85, and 92. Exact-head PostgreSQL conformance already fails with the missing-field diff, and the property accesses no longer match UserBackgroundReadReply. Update that consumer in this PR, using distinguishable profile-specific snapshot results to retain its enclosing-read, profile-merge, and rollback assertions without restoring redundant production metadata.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Port snapshots and process enrichment keeps the original intent (cc13ef8: Deduplicate Unix process metadata per request while retaining bounded subprocess concurrency and fresh diagnostic facts.)
  • Presence self-row fallback keeps the original intent (4bbdedb: Preserve a private Gateway row under expiry, peer pressure, and caller-supplied identity collisions.)
  • Preference publication replay changes intended behavior with a stated reason (2c0d5bb: Prevent delayed preference reads from publishing older values after a write or profile merge.)
  • Background read replay and reply metadata changes intended behavior with a stated reason (afafe74: Keep private background ownership, atomic replacement, compare-and-set writes, and freshness across asynchronous reads.)
  • Pairing payload preparation keeps the original intent (f288016: Move join-code registration and atomic redemption into the existing pairing worker while preserving expiry and current authority.)
  • Requester serialization changes intended behavior with a stated reason (65e49fa: Retain original requester and grant facts across queued publication and restart, with current authorization required before new effects.)
  • Conversation-selection forwarding keeps the original intent (286ff4f: Select higher-priority absences and fallback bindings from the same database snapshot.)
  • Queue replacement validation keeps the original intent (d3309e5: Consolidate replacement-ID validation while preserving exact source comparison and transactional mutation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • node scripts/test-database-conformance.mjs --engine postgres --connection postgresql://[email protected]:5432/postgres -- src/infra/database-engine/state-read-lock.postgres.test.ts --maxWorkers=1
  • node scripts/run-tsgo-core-test-shards.mjs src
  • git diff --check

What I checked:

  • Pinned introduced changes: Reviewed the merge-base-to-head diff; current main retains the original implementations, so this work is not already implemented. (2399057ab150)
  • Confirmed PostgreSQL consumer failure: Exact-head PostgreSQL conformance reports an unexpected missing profileId at line 63. The same test also accesses the removed property at lines 72, 85, and 92. (src/infra/database-engine/state-read-lock.postgres.test.ts:63, 2399057ab150)
  • Accepted snapshot tradeoff: The maintainer-authored body explicitly accepts returning an older display snapshot during an overlapping edit and explains the departure from perf(gateway): avoid redundant tail RPC reads #172433; write policy and external-effect authority remain separate. (src/state/user-preferences.ts:45, 2399057ab150)
  • Authority checks retained: Pairing registration still checks current caller authority at worker admission; redemption burns and decodes stored payloads. Publication restoration retains schema validation and live requester checks. Private image HTTP retains freshness retry and authorization before response I/O. (src/gateway/user-background-http.ts:63, 2399057ab150)
  • Historical media inspected: Both prepared Devices screenshots belong to the presence-pressure proof in fix(infra): keep presence bounded under entry pressure #134740; they demonstrate that earlier change and do not establish execution of this PR’s changed paths. (src/infra/system-presence.ts:28, 4bbdedbb9b94)
  • CI attribution limits: The exact-head test-types check and PR-context check also failed. Their annotations do not establish complete causes; job-log retrieval was blocked at productionresultssa11.blob.core.windows.net. Only the independently confirmed PostgreSQL mismatch is assigned as a finding. (2399057ab150)

Likely related people:

  • Peter Steinberger: Raw commit cc13ef8 adds src/infra/ports-inspect.ts:220 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cc13ef846d51; files: src/infra/ports-inspect.ts)
  • Shakker: Raw commit 65e49fa adds src/state/github-publication-requester.ts:90 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 65e49fa2008c; files: src/state/github-publication-requester.ts)
  • lzhan011: Raw commit 4bbdedb adds src/infra/system-presence.ts:50 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4bbdedbb9b94; files: src/infra/system-presence.ts)

PR surface

Source -105, Tests +33, Docs 0. Total -72 across 25 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 21 105 210 -105
Tests 3 36 3 +33
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 25 142 214 -72

Review metrics

Metric Value Why it matters
Production versus tests Production +105/-210; tests +36/-3 The reduction reuses existing owners; added Windows fixtures check preserved listener results and reduced native work.

Labels

Label changes:

  • add P3: This is internal cleanup with a focused test-consumer omission and no demonstrated user-facing production failure.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P3: This is internal cleanup with a focused test-consumer omission and no demonstrated user-facing production failure.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 October 20, 2026, 1:09 PM ET / 17:09 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Exact-head CI attribution for 10f62ba7778b468a5965f089eed29542cbeaf1dd, completed run 39465210998, attempt 1. CI remains failed; this is the campaign-authorized inherited-failure exception, not a green claim.

Failed job Observed failure Attribution
Node compact 23-2 Canonical cron/retired-sidecar Doctor-readiness case exceeds its 45s whole-test cap after Doctor repair and readiness. Same exact case/cap fails on unrelated PR #177933, run 39447933203/job 118715559025. Its merged commit 27aa0742fc28 repairs that owner’s sequential child-budget mismatch. This PR changes neither the case nor its budget; status success is not claimed.
UI E2E 6/8 First ordinary-text touch gesture records zero movement (279→279), before streaming starts. Unchanged browser gesture and synthetic MockGateway flow; no changed backend request handler executes. The Canvas fixture is unchanged.
UI E2E 7/8 Synthetic 180s duration label disappears in a post-hello reconciliation frame; initial cached frames passed. Duration/history are browser MockGateway inputs. No changed backend session/storage work executes. Whole UI and compared build/fixture inputs are unchanged.
CI gate Selected Node/UI aggregates failed. Downstream of exactly those three leaves.

Attribution is bound to the actual tested merge bd66f29c166825a2985c3ec39a6fe74abafb0455, with ordered parents main 16ab1602cb4868a9ef5f1c638fd96ac3b58df13f and this exact PR head. Its complete main-parent delta is the intended 26-path PR. Entire ui/, packages/, test helpers/Vitest fixtures, scripts, and inspected Canvas/host-contract/shared/logging inputs match that main parent. The browser fixtures have no Node request handlers or backend passthrough. An audio helper’s dynamic import is uncalled in both failing cases; it is not an executed backend path. This is concrete source/flow attribution, not an exhaustive transitive-import claim or an exact-main UI-flake reproduction.

The coordinator flake ledger and last six completed scheduled-main runs were checked. Their related cold-load title:false failures are not the observed duration:false signature and are not used as matching evidence. The automatic classifier correctly says unknown/no matching job; the additional causal evidence above supplies the scoped attribution.

Every other selected job passed, including repaired PostgreSQL conformance and security-fast. The cancelled older PR-body job has a successful replacement on this same head. Local proof retains 444 distinct focused passing cases/36 files, targeted types/lint/format, suppression checks, inventory and zero cycles; existing platform skips remain disclosed in the body. No CI rerun, timeout increase, retry, skip, assertion weakening or green-chasing push was made. Security, required reviews and exact-head protection remain required.

@steipete
steipete merged commit d5bca3c into main Oct 20, 2026
138 of 144 checks passed
@steipete
steipete deleted the deslop/z40-21-owner-residue-20261015 branch October 20, 2026 18:11
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
* refactor: trust prepared internal owner facts

* refactor(infra): share inspection facts and trust presence invariants

* refactor(infra): validate queue replacement at its kernel owner

* refactor(cron): drop unused delivery target input members

* test(postgres): assert background data across snapshots
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 P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. security-sensitive-changed size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant