Skip to content

refactor(agents): keep private execution phases with their owners - #180961

Merged
steipete merged 17 commits into
mainfrom
deslop/z25-104-agent-host-owners-20261015
Oct 22, 2026
Merged

steipete merged 17 commits into
mainfrom
deslop/z25-104-agent-host-owners-20261015

Conversation

@steipete

@steipete steipete commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agent execution and host utilities expose private helpers and modules that have only one production consumer.

User Impact

No user-visible behavior change. Auth and tool authority, public SDK/CLI/config/protocol contracts, lazy imports, and durable user state remain unchanged. The standalone session-memory backend and its machinery are untouched.

Why This Change Was Made

Fold private phases into their existing owners: attempt identity normalization, reply preflight and database admission, suspicious-text diagnostics, Gemini cache auth, TUI model catalogs, native resource binding, daemon environment/ownership inspection, system-agent post-write repair, Claw draft selections, usage/expiry labels, and small Markdown/MIME assembly frames.

This is the agent/host area slice of the z25 single-consumer family, split under campaign rule 11 because the combined family reaches 82 files. It removes 271 net production lines (+956/-1,227), excluding tests, fixtures, support, generated files, and declarations. Moved algorithm bodies receive no deletion credit. Existing owners and public entry points replace the old private seams; no new test-only production API is added.

Best-effort tradeoffs accepted

  • Suspicious-text diagnostics capture the optional session ID once at message-completion setup. Mutating or replacing that diagnostic ID during the same synchronous callback now logs the captured ID. Runtime session identity is stable; this does not change live authority or any external effect. The parsing and warning guards remain.
  • No guard is removed by the other cuts. All claim/actor handoff, restart cancellation, accepted-write settlement, model/header validation, input persistence, archive privacy, and public text behavior remain.

Evidence

Every cut received focused boundary tests, targeted native types/lint/format, a simplify pass, and fresh independent P0-P2 review. Private-entry test migrations were proven with production unchanged before the corresponding folds. Relevant proof includes normalization's 30 cases, reply preflight's 48 cases, TUI's 125 cases, Claw draft publication/privacy's 17 cases, native resource lifecycle/transport's 22 cases, Gemini cache/prefix stability's 58 cases, and public database-admission/fixture's same 178 cases across ten suites before and after the fold. Two launchd rows pinning a second query already removed by #168882 were retired; native parser/error and real duplicate-manager coverage remain.

The database fixture now completes its operation, joins the exact-target successor barrier, and verifies the original claim is retired; owner settlement alone is not treated as database-release proof. No local builds, broad suites, whole-graph types, or E2E were run; exact-head hosted CI supplies broad proof. No live service or operator state was touched. No retries, skips, timeout increases, new suppressions, or allowance growth.

The required local suppression-inventory test retains its unrelated fresh-main failure (13 pass, one failure; 104 observed rows versus 100 allowlisted). Extra rows are in unchanged scripts/perf/idle-gateway-measure-preload.mjs, src/cron/store/job-mutations.ts, src/transcripts/library.query-budget.test-support.ts, and ui/src/pages/sessions/view.tsx. The test and those inputs are byte-identical to main; no suppression or allowance is added here.

The production cutovers match the reviewed and tested source family after conflict-free composition on fresh main. Among selected paths, main drift touched only existing shrink-only ratchet inventories. Hosted CI verifies the full dependency composition.

The first exact-head CI exposed an incomplete test-fixture migration: fixture disposal ran inside withSessionTurn, before that outer owner released retained execution, so its database claim could not retire yet. The repair disposes after the outer turn and returns the existing bound admission fact needed by the durability consumer. Production code, test expectations, and claim-retirement checks are unchanged. The original auth-guidance case fails before this repair; afterward, all eleven CI-failed execution suites plus durable capacity admission pass unchanged: 118 cases across twelve files. Targeted native types, typed lint, format, line caps, and fresh independent P0-P2 review also pass.

Repaired-head CI 39853368463, attempt 1 at 1e3981240d785e756f4cb8610ee1fdd7d29a6127, completed. All execution/type jobs passed. Complete exact-head accounting: 183 terminal checks, 124 success, 54 skipped, one neutral, two failures, and two cancelled metadata executions with verified same-head/same-workflow successful replacements. No missing test suite is waived.

Failed job Attribution
120087543137: checks-node-compact-small-3 Inherited exact source-owner omission: expected nine rows, received eight, missing commands-plugin.scheduled-turns.test.ts. Same case/row/stack on scheduled main 39840622841, job120040645368. Determining planner/test/authority inputs are unchanged.
120097249178: openclaw/ci-gate Downstream aggregate for that leaf only; every other selected group passed.

The aggregate's informational new label compares a same-named newest-main shard without comparing selected scope. Actual matching-signature proof comes from the earlier scheduled run within the inspected latest six, not from job-name similarity. Main-flakes registry has no matching entry. The authorized native inherited-failure exception preserves this red CI and the separately investigated local inventory failure; neither is presented as green. No CI rerun or re-push for green.

Fresh-main structural proof passes: zero runtime cycles, zero static cycles, assertion-safety and mock-export ratchets, the selected wrapper/eager-import closure contracts, and the native line-cap ratchet (32 source files, no new violation or over-cap growth).

Native landing is currently refused before dispatch by an old retained tooling parser, not by missing security clearance. Security Review39856898261/job120097432174 passed its exact-head enforcement step. Its job name includes the selected CI run and attempt; the retained workflow recognizes only the older two-field name. #180929 corrects that parser on main. No merge intent was created, no binding or receipt was changed, and no security gate was bypassed. The existing documented current-workflow recovery requires a retained cancelled-auto or qualified REST405 outcome, neither of which exists here. Necessary review/preparation/evidence remains intact while other campaign work continues.

@clawsweeper

clawsweeper Bot commented Oct 22, 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 gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Oct 22, 2026
@steipete
steipete marked this pull request as ready for review October 22, 2026 20:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T21:01:05.754383Z 1e39812 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a592fb275b

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

},
);
}
// Parsed headers need a bracket or angle delimiter, written literally or as an entity.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the QA scenario to the relocated diagnostics

After moving the transcript-role detection here, qa/scenarios/ui/control-ui-assistant-transcript-role-boundary.yaml:25 still names the deleted src/agents/embedded-agent-subscribe.tool-text-diagnostics.ts. QA Lab publishes these codeRefs into both the agent workspace and evidence summaries, so this scenario now supplies a dead source reference instead of the implementation being exercised; point it at this lifecycle module as part of the cutover.

AGENTS.md reference: AGENTS.md:L51-L52

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 22, 2026
@clawsweeper

clawsweeper Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR folds private execution and host-utility helpers into their existing production owners.

Example: A reply requires preflight compaction.

  • Before: Turn preparation calls a separate private preflight module.
  • After: Turn preparation performs the same checks, memory flush, and compaction directly.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The owner-local refactor is justified, but exact-head CI confirms a cleanup regression in the migrated fixture.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored refactor is outside the ordinary contributor proof gate; supplied evidence consists of focused owner tests and CI, with no claimed shipped-entry-point run. Source comparison verifies no persisted format, schema, configuration shape, or migration change.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
Reason: The maintainer-authored direction removes private module seams and preserves existing public behavior, contracts, and decision owners.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open: the maintainer-directed refactor is useful, but migrated fixture cleanup introduces a confirmed CI failure and one QA source reference remains stale.

Priority: P3
Reviewed head: a592fb275b27651a3ce20823beeb4485ef418531

Before merge

  • Dispose the borrowed fixture after execution custody is released (P2) - getRawExecuteAgentTurnForTest disposes this fixture inside the callback passed to withSessionTurn. That owner retains execution until the callback returns, so complete() here only schedules completion; it cannot clear the operation or publish the deferred database-release barrier. The wait then sees no barrier and returns settled while databaseClaim.isCurrent() remains true, making successful agent-runner tests throw this new cleanup error and masking original errors. Exact-head CI reports this failure across multiple agent-runner lanes. Move disposal and the retirement assertion outside the retaining callback while keeping release through the production lifecycle owner.
  • Update the QA scenario to the relocated diagnostics owner (P3) - This codeRefs entry names the diagnostics module deleted by this PR. QA Lab includes these references in its generated agent workspace and evidence summaries, so the transcript-role boundary scenario now directs investigators to a nonexistent implementation. Replace it with src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts as part of the cutover.

Findings

  • [P2] Dispose the borrowed fixture after execution custody is released — src/auto-reply/reply/restart-recovery-claim.test-support.ts:54-57
  • [P3] Update the QA scenario to the relocated diagnostics owner — qa/scenarios/ui/control-ui-assistant-transcript-role-boundary.yaml:25
Agent review details

How this fits together

Agent turns, session claims, provider credentials, and host settings enter existing runtime owners, which prepare execution, preserve resource custody, and produce replies or host operations.

flowchart TD
  A[Incoming agent turn] --> B[Turn preparation]
  B --> C[Admission lifecycle]
  C --> D[Embedded execution]
  D --> E[Attempt normalization]
  D --> F[Message completion]
  G[Host utility callers] --> H[Private operations within owners]
Loading

Technical review

Best possible solution:

Keep the owner-local folds, move borrowed-fixture disposal outside the retaining turn callback, and update the QA scenario reference.

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

The fixture failure is supported by exact-head CI annotations and a source trace through withSessionTurn execution retention, deferred completion, and successor-barrier publication; no local run was performed.

Is this the best way to solve the issue?

Folding sole-consumer helpers into existing owners fits the repository contract, but fixture cleanup must respect the outer execution lifetime.

Full review comments:

  • [P2] Dispose the borrowed fixture after execution custody is released — src/auto-reply/reply/restart-recovery-claim.test-support.ts:54-57
    getRawExecuteAgentTurnForTest disposes this fixture inside the callback passed to withSessionTurn. That owner retains execution until the callback returns, so complete() here only schedules completion; it cannot clear the operation or publish the deferred database-release barrier. The wait then sees no barrier and returns settled while databaseClaim.isCurrent() remains true, making successful agent-runner tests throw this new cleanup error and masking original errors. Exact-head CI reports this failure across multiple agent-runner lanes. Move disposal and the retirement assertion outside the retaining callback while keeping release through the production lifecycle owner.
    Confidence: 0.99
  • [P3] Update the QA scenario to the relocated diagnostics owner — qa/scenarios/ui/control-ui-assistant-transcript-role-boundary.yaml:25
    This codeRefs entry names the diagnostics module deleted by this PR. QA Lab includes these references in its generated agent workspace and evidence summaries, so the transcript-role boundary scenario now directs investigators to a nonexistent implementation. Replace it with src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts as part of the cutover.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Attempt identity and reply database admission keeps the original intent (4590844: Retain selected physical database ownership across turn phases; later session-controller work unified lifecycle custody. The moved guards and settlement ordering remain.)
  • Reply preflight keeps the original intent (36e277d: Give each session one controller for turns, queues, and Stop, including required memory checkpoints and approved-input persistence.)
  • Suspicious assistant-text diagnostics changes intended behavior with a stated reason (e8ad046: Recognize transcript-role-looking text through the canonical Markdown parser; the PR retains inert-text handling and explicitly accepts capturing the diagnostic session ID earlier.)
  • Native resource binding keeps the original intent (9c93bc3: Retain snapshot and child-process cleanup custody through worker failures; the implementation moves into NativeWorker with the same broker and release ordering.)
  • TUI model catalogs keeps the original intent (d02f309: Open model pickers without waiting for Gateway responses; later worker-placement changes added session-scoped catalogs. Both behaviors remain in the client.)
  • Claw review selections keeps the original intent (94867f9: Build an exact selected portable archive for explicit human publication; the later readable-name behavior from improve: clarify the Create Claw review flow #179098 is preserved.)
  • Launchd inspection and service environment planning keeps the original intent (895b691: Prevent duplicate Gateway managers while preserving service environment provenance; refactor(cli): simplify update and service lifecycle bookkeeping #168882 already accepted best-effort concurrent scan observations.)
  • System-agent post-write verification keeps the original intent (b1f4aac: Keep persistent configuration writes behind operator approval and provide corrective guidance after failed validation; lazy config reads and repair behavior remain.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/auto-reply/reply/agent-runner-execution-mcp-context.test.ts
  • pnpm test src/auto-reply/reply/restart-recovery-claim.lifecycle.test.ts src/auto-reply/reply/restart-recovery-claim.successor.test.ts
  • pnpm tsgo:core:test
  • git grep -n 'embedded-agent-subscribe.tool-text-diagnostics'
  • git diff --check

What I checked:

PR surface

Source -271, Tests +75, Other -2. Total -198 across 46 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 28 956 1227 -271
Tests 16 320 245 +75
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 0 2 -2
Total 46 1276 1474 -198

Review metrics

Metric Value Why it matters
Production versus test changes Production +955/−1,226; tests and test support +320/−245 Excludes text inventories and lifecycle type declarations; production shrinks while tests move toward existing production boundaries.

Labels

Label changes:

  • add P3: This is an internal cleanup with no intended user-visible change; its confirmed blockers affect test-fixture correctness and QA navigation.
  • 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 an internal cleanup with no intended user-visible change; its confirmed blockers affect test-fixture correctness and QA navigation.
  • 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 22, 2026, 4:54 PM ET / 20:54 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

PR180961 exact-head final accounting

Head1e3981240d785e756f4cb8610ee1fdd7d29a6127; CI39853368463 attempt1 completed/failure. Paginated exact-head census z25-ci104-final-checks.json contains183 terminal checks:124success/54skipped/1neutral/2failure/2cancelled; zero pending. This supersedes the earlier180-check pending snapshot in z25-ci104-current-attribution.md.

Failed job Attribution
120087543137 checks-node-compact-small-3 Exact source-owner test expects9/receives8, omitting src/auto-reply/reply/commands-plugin.scheduled-turns.test.ts. Same case, omitted row and helper179/test231 stack on scheduled main39840622841@dfe0396d/job120040645368. Determining planner/test/authority inputs unchanged.
120097249178 openclaw/ci-gate Downstream aggregate: only selected checks-node-core-test-nondist-shard fails; no second defect. Its informational classifier calls this new based only on the same-named shard in newest main passing, explicitly without scope comparison. Actual exact-signature evidence is the older scheduled run within the latest six.

Cancelled metadata120085098521 and120085097550 have positively verified same-head/same-workflow successful replacements120085207402 and120085208056. Actual evidence/dispatch steps passed. No cancelled test suite or missing proof is excused. Security-fast120087540422 and all production/test typecheck jobs pass.

Checkout recorded in failed log is7dd8de291add81a6afa13a3d410bce1571a2b43a, ordered parents60c9291360c93c54a0d8be7cffd799a0ef6014c2 and1e3981240d785e756f4cb8610ee1fdd7d29a6127, tree83e2298790a671bbaf64d3969d882167b10b6f3b. Independently reconstructed merge tree matches. Baseline is ancestor of captured main. Selected failure/planner/test/authority sources are byte-identical baseline to tested merge. Whole trees are not claimed equal; PR changes are included.

Latest six completed scheduled runs inspected:39849675545,39840622841,39832966696,39823514819,39815322394,39805986795. Main-flakes registry has no matching entry; actual398406 signature and unchanged inputs establish inheritance. No rerun, dispatch, rebase or push for green. Local suppression inventory104vs100 remains investigated and honestly failed; no allowance changed. All other focused structural checks passed. Phase E untouched.

@steipete

Copy link
Copy Markdown
Contributor Author

Exact reviewed/prepared head: 1e3981240d785e756f4cb8610ee1fdd7d29a6127.

Using the campaign-authorized exact-head guarded squash fallback after two genuine native inherited-only submissions failed on the retained workflow's Security Review matcher: this PR and #181042. Independent prepared PRs, not blind retries; operator setup/path errors are excluded. Both native refusals occurred before intent/dispatch, with locks/children released. No workflow binding or receipt is edited and no security gate is waived.

Retained workflow9b49df67 accepts only review (pr, head). Official main74f3083/#180929 fixes selected-attempt job matching. Actual Security Review publisher 39856898261, job120097432174, is review (180961, 1e3981240d785e756f4cb8610ee1fdd7d29a6127, 39853368463, 1) and Enforce security review completed successfully. Current independent dependency/security-sensitive statuses succeed; combined status fails only for CI.

CI 39853368463, attempt1, completed failure. Fresh paginated exact-head census201 entries, all terminal; no additional failed leaf since the earlier183-entry receipt.

Failed job Evidence
120087543137 checks-node-compact-small-3 Source-owner inventory expects9/receives8, missing src/auto-reply/reply/commands-plugin.scheduled-turns.test.ts. Same case, omitted row, helper179/test231 signature on scheduled main39840622841@dfe0396d/job120040645368. Determining sources unchanged baseline→actual tested merge7dd8de29.
120097249178 openclaw/ci-gate Downstream only. Informational classifier compares same-named shards without scope; exact scheduled signature establishes inheritance.

Cancelled metadata120085098521 and120085097550 have successful same-head replacements120085207402 and120085208056; no cancelled test execution waived. Security-fast120087540422 and all production/test types pass. Repaired fixture's118 unchanged public cases and focused ownership proof pass; original investigated local suppression-inventory failure remains honestly recorded, without allowance growth.

Current-mainaf059b5 to exact head merges without conflicts. All47 PR paths' production/test inputs are unchanged since actual CI base60c92913 except wrapper-inventory metadata (two additions/one unrelated retirement), which merges cleanly. Main behavior is preserved, not overwritten. No drift-only rebase/push/rerun for green. Fresh independent P0–P2 review and scoped proof retained. Phase E remains untouched. Guarded fallback pins the exact head above; merge/ancestry will be verified separately.

@steipete
steipete merged commit 0843b94 into main Oct 22, 2026
199 of 204 checks passed
@steipete
steipete deleted the deslop/z25-104-agent-host-owners-20261015 branch October 22, 2026 22:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…enclaw#180961)

* refactor(agents): prepare Gemini cache auth at its sole caller

* refactor(media): initialize MIME reverse table at its owner

* refactor(markdown): render table fallbacks at their sole owner

* refactor(usage): label windows at their projection owner

* refactor(promos): label expiry at the rendering owner

* refactor(daemon): keep environment assembly in its consumer

* refactor(system-agent): own post-write repair in the chat engine

* refactor(infra): bind native resources in their worker owner

* refactor(daemon): keep installed ownership scanning in its inspector

* refactor(agents): retire the compaction predicate forwarding module

* refactor(agents): diagnose suspicious text at message completion

* refactor(agents): adopt attempt identity in normalization

* refactor(tui): keep model catalogs in their client owner

* refactor(reply): keep preflight in turn preparation

* refactor(claws): apply draft selections in archive preparation

* refactor(reply): bind database admission in its lifecycle owner

* test(reply): retire fixture admission after outer execution settles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations 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. scripts Repository scripts size: XL 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