Skip to content

fix(codex): avoid repeated host compaction after manual compact - #158044

Closed
scotthuang wants to merge 15 commits into
openclaw:mainfrom
scotthuang:fix/manual-codex-byte-compaction
Closed

scotthuang wants to merge 15 commits into
openclaw:mainfrom
scotthuang:fix/manual-codex-byte-compaction

Conversation

@scotthuang

@scotthuang scotthuang commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #126171

What Problem This Solves

Fixes repeated host compaction on the next chat turn after successful manual Codex compaction when OpenClaw's transcript mirror remains above its byte budget.

User Impact

Explicit compaction applies the existing host byte guard before native Codex compaction. Below-budget sessions and sessions with valid byte-progress accounting remain native-only. A committed host summary stays committed if native compaction fails; the manual failure remains visible and clients receive the host update once.

Maintainer decision remains open: accept host-first manual compaction latency. Historical operator testing measured about 15m26s for the first host summary plus 30s native time; this PR does not claim to make that first summary faster. There are no configuration, schema, retention, or migration changes. The released synchronous SessionManager SDK and process-local incognito contracts remain supported.

Why This Change Was Made

Codex owns its native history; native compaction does not rewrite OpenClaw's SQLite transcript mirror. Manual and ordinary-turn paths share one host accounting owner, with atomic boundary/count/latch persistence and current writer authority. Native-only accounting retains the host byte latch; a host rewrite below budget explicitly clears it.

The October 13 refresh resolves 12 text conflicts by merging main f6c9a769e0f24780696a5aaf0e90dabf748adbcc into the existing PR history. It retains upstream #168051 latch semantics, #169622 worker-backed source/currentness checks, #170199 actor ownership, and committed compaction details. It removes the superseded PR-only write-view helper because main's native persistence owner now carries that rollback protection.

The latest review's P2 navigation finding is fixed: compaction captures the existing navigation assertion, checks it at worker admission and before receipt adoption, and preserves a genuinely newer published view. The dedicated accounting transaction retains the same exception while still checking binding, writer, ownership, lifecycle, and caller authority. No new state owner or public SDK export is introduced.

Evidence

Product head: a33bc638124dd72f88e6289e79dbff76417dc68c. Previous head 7eb59d0bf6f3c442c628a41cd68b44fbaa4f4efb remains first parent; history is not rewritten.

Code anchors for this revision: manual byte/accounting owner, navigation capture and receipt adoption, dedicated-owner newer-view exception, and real-worker navigation regression.

At publication GitHub reports MERGEABLE / BLOCKED, with 35 later main commits behind the branch but no merge conflict. New-head CI is still running; the block is not being treated as a code conflict or a passing review. Maintainers can edit the branch. The security-review publisher workflow completed successfully, but deliberately marks openclaw/security-sensitive-review and openclaw/ci-gate red: Security review is awaiting maintainer approval. This is an approval gate, not a failing product test.

All current runs used temporary synthetic state and private frozen dependencies, Node 24.18.0 / pnpm 12.9.0 on macOS. No running installation, Gateway, real database/configuration, or external channel was used.

Check Observed result
Scoped integration coverage 243 distinct passing cases / 15 files across the runs below; combined coverage, not one monolithic invocation
Final affected batch 128 passed / 7 files, process wall 148.07s
Navigation and newer-view owner suite 21 passed, process wall 36.35s; the five navigation/publication cases cost 40–54ms each in that run
Deliberate defect controls Five independent mutations all fail at the intended boundary; restored candidate passes all 8 selected cases, process wall 56.46s
Last test-only type correction Both newer-view cases pass again, process wall 14.22s; raw database rows are narrowed with the existing record guard, without casts
Production / test types Production core passed (51.90s); all five selected test graphs passed (sessions 8.6s, agents-other 47.4s, gateway-server 56.1s, messaging 47.7s, agents-root 45.1s compiler time)
Static checks Scoped Oxfmt/Oxlint, 3-file MDX compilation, whitespace/conflict checks, line-cap/max-lines/assertion/database-worker/database-dialect/timeout/mock-export ratchets pass
Independent review Codex P0–P2 autoreview: scoped-clean on the complete candidate delta plus unchanged owner context. The final record-type narrowing and unused test import removal also received independent scoped review. This is static review, not runtime proof

The current tests exercise the queued manual entry, real host compaction owner and SQLite workers, slash-command handling, Gateway RPC, admission/cancellation, canonical path aliases, incognito storage, committed-host/native-failure publication, and latch refresh/rearming. Model and native-harness outputs are synthetic; these are runtime/storage boundary tests, not a new live Codex or Weixin end-to-end run.

Initial failures were identified and corrected: old delegate/hydration fixtures lacked the newly required runtime-config snapshot (the delegate also resets its module graph, so preparation must use the post-reset instance); an actor callback signature and a raw-JSON test type needed adaptation. The line-cap check required moving existing entry/routing fixture factories into their existing test-support module, without deleting coverage. These integration/fixture failures are not claimed as upstream product regressions.

The 12 conflicted files and resolution
  • docs/reference/database-schemas/worker-access.md: retain the current worker/actor owner documentation and the manual boundary/accounting contract.
  • src/agents/sessions/agent-session-compaction.ts and .test.ts: publish committed details once, preserve provider/server-endpoint compaction and cancellation fencing.
  • src/agents/sessions/session-manager-entries.ts, session-manager-metadata.ts, and session-manager-persistence.ts: retain main's actor/worker split, currentness and navigation assertions, and acknowledged-commit handling.
  • src/auto-reply/reply/agent-runner-memory.ts: share accounting with manual compaction while preserving native-only latch retention.
  • src/auto-reply/reply/commands-compact.ts: use current prepared session reads and skip accounting already committed by the host owner.
  • src/config/sessions/session-entry-projection.ts: retain main unchanged (undefined retains, null clears the latch).
  • src/config/sessions/session-accessor.compaction-boundary.test.ts: preserve both upstream writer/transaction coverage and manual accounting regressions.
  • src/gateway/server-methods/sessions-compact.ts and src/gateway/server.sessions.compaction.test.ts: preserve native/server semantics, stale-owner checks, negative-estimate coverage, and one committed-host notification even after native failure.
Reproducible commands, negative controls, and observed failure signatures
node scripts/run-vitest.mjs src/agents/sessions/session-manager-async-message.test.ts --maxWorkers=1
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/compact.delegate.test.ts src/agents/sessions/agent-session-compaction.test.ts src/agents/sessions/agent-session-compaction.admission.test.ts src/agents/sessions/agent-session-compaction.degraded-reload.test.ts src/agents/sessions/session-manager.test.ts src/agents/sessions/session-manager-hydration.test.ts src/agents/session-tool-result-guard.transcript-events.test.ts src/config/sessions/session-accessor.compaction-boundary.test.ts src/auto-reply/reply/commands-compact.test.ts src/auto-reply/reply/commands-compact.lifecycle.test.ts src/auto-reply/reply/commands-compact.runtime.test.ts src/gateway/server.sessions.compaction.test.ts src/gateway/server.sessions.compaction-accounting.test.ts --maxWorkers=1
# After repairing the runtime-snapshot fixtures, rerun the affected files and
# the command/storage shards that had not run after the earlier shard failure:
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/compact.delegate.test.ts src/agents/sessions/session-manager-hydration.test.ts src/auto-reply/reply/agent-runner-memory.test.ts src/config/sessions/session-accessor.compaction-boundary.test.ts src/auto-reply/reply/commands-compact.test.ts src/auto-reply/reply/commands-compact.lifecycle.test.ts src/auto-reply/reply/commands-compact.runtime.test.ts --maxWorkers=1
pnpm tsgo:core
node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-sessions","core-test-agents-other","core-test-gateway-server","core-test-messaging"]'
node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-root"]'

The second command initially passed 27 Gateway cases and 103 infra cases but failed the ten unprepared-snapshot fixture cases; it is not claimed as an entirely passing invocation. The next command passed 128 cases after those fixtures were corrected. Unaffected passing results are retained rather than rerun for appearances.

Each control below changed only the named production condition in the isolated worktree, ran the specified existing test filter, then restored the exact source bytes. These are deliberate defect controls, not a claim that the whole historical head was rerun.

Removed/changed protection Test file / -t filter Actual result
Omit navigation assertion passed to persistWorkerRecord session-manager-async-message.test.ts / fences local navigation 2 fail, 1 pass; refusal happens only after commit instead of before commit; exit 1, 29.09s
Omit navigation check before receipt adoption Same file/filter 1 fail, 2 pass; expected committed-view failure is absent (Received: undefined); exit 1, 27.95s
Restore unconditional navigation check after dedicated compaction commit Same file / keeps a newer published view when an awaited compaction receipt Dedicated-owner case fails; generic worker control passes; exit 1, 27.98s
Restore undefined instead of explicit host latch clearing compact.delegate.test.ts / clears (the byte latch|stale byte suppression) Both cases fail: stale latch remains instead of undefined; exit 1, 36.92s
Always clear latch after accounting, including native-only token compaction agent-runner-memory.test.ts / preserves host byte suppression when native token-pressure compaction succeeds Durable latch-preservation assertion fails; exit 1, 32.10s

Final restored-source command (8 pass):

node scripts/run-vitest.mjs src/agents/sessions/session-manager-async-message.test.ts src/agents/embedded-agent-runner/compact.delegate.test.ts src/auto-reply/reply/agent-runner-memory.test.ts -t 'fences local navigation|keeps a newer published view when an awaited compaction|clears (the byte latch|stale byte)|preserves host byte suppression' --maxWorkers=1

The new host-summary-under-budget case cost 2.354s in the full delegate run; native latch preservation was under one second in the full owner run. No new sleeps, polling, longer timeouts, production test seams, or serial test configuration were added. Hosted CI timing for this revision is not yet available.

Preserved historical live/hosted evidence and limits

On macOS over official v2026.9.6, earlier operator testing reduced host bytes from 21,224,992 to 311,754, persisted the checkpoint, completed native compaction, kept a second manual request native-only, and allowed ordinary chat afterward. Initial host compaction took about 15m26s + 30s native. This is historical evidence, not a current-head provider run or a latency fix.

Historical product head 2bc49c17c57dd739f460fb7e7af702195f315bba passed secretless fork validation through evidence commit c202912da226699ab07c11fd3a38618b42d8739f: 77 tests, production/test types, scoped static checks, and runtime build. Earlier broader 226-test/build and four type-lane results remain pinned to their historical revisions. They do not certify this refresh.

The native contract was personally rechecked in sibling Codex source at be9060ff9620e170a05a6353ab293efb7c704248: ThreadCompactStartParams identifies a native thread; thread_processor.rs::thread_compact_start submits Op::Compact; core/compact.rs rewrites native history, not the OpenClaw transcript database.

Current-head CI/review and maintainer acceptance of host-first latency remain separate. No CI rerun/dispatch, production restart, real model/channel request, or PR merge was performed.

@clawsweeper

clawsweeper Bot commented Sep 25, 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.

@scotthuang
scotthuang marked this pull request as ready for review September 25, 2026 09:33
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: codex size: XL labels Sep 25, 2026
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: a33bc638124dd72f88e6289e79dbff76417dc68c

These sensitive security changes were made:

  • src/agents/embedded-agent-runner/transcript-byte-preflight-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR applies the host transcript byte guard before manual Codex compaction and preserves committed accounting when native compaction fails.

Example: Manually compact a Codex session whose host transcript occupies 21,224,992 bytes.

  • Before: Native compaction leaves the oversized host transcript eligible for another host summary on the next chat turn.
  • After: Historical operator testing reported 311,754 host bytes afterward, with the second manual request remaining native-only.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The navigation repair is verified and no discrete introduced bug was found; unresolved product and SDK decisions, partial linked-issue coverage, and unclassified CI limit readiness.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Historical macOS operator evidence exercises manual Codex compaction over v2026.9.6, durable host shrinkage, a native-only second request, and subsequent chat; current worker regressions and deliberate controls supplement that scenario without claiming a new live provider run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: After manual Codex compaction succeeds, the next message can wait through another expensive host summary.
Reason: The manual repair has clear value, but changes completion timing and addresses only part of the linked automatic memory-flush report.

Merge readiness

⛔ Blocked before merge - 3 items remain

This PR still addresses a distinct manual-compaction problem, and the previous navigation finding is resolved; product direction, SDK scope, and an unclassified CI failure remain unsettled.

Priority: P1
Reviewed head: a33bc638124dd72f88e6289e79dbff76417dc68c
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should oversized manual Codex compaction wait for host semantic compaction before native completion, given the reported roughly 15-minute initial host delay?
  • Recommendation: Accept host-first manual compaction: Accept the initial delay in exchange for settling the host transcript and accounting before completing the native request.
  • Why: The patch changes established manual completion timing, and no recorded maintainer approval settles that tradeoff.

Before merge

  • Resolve merge risk - Keep the receipt-publication callbacks internal, or obtain SDK-owner acceptance of the new public appendCompactionAsync parameter and its supported lifecycle contract.
  • Complete next step - Classify the exact-head same-device Stop failure in server.sessions.abort-authorization.test.ts against the base, fixing only a demonstrated patch-caused defect.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

The shared compaction owner receives manual or ordinary-turn requests, coordinates OpenClaw's SQLite transcript separately from Codex's native history, and publishes accounting and client notifications.

flowchart TD
 A[Manual compaction request] --> B[Check host byte budget and latch]
 B --> C[Host semantic compaction when needed]
 C --> D[Commit boundary count and latch]
 D --> E[Native Codex compaction]
 B --> E
 E --> F[Publish committed host change and native outcome]
Loading

Technical review

Best possible solution:

Retain shared host accounting, keep receipt callbacks internal, and explicitly settle the host-first manual timing contract.

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

Current main leaves native manual compaction separate from the host byte guard, so an oversized mirror without valid suppression can trigger host compaction on the next turn; historical operator evidence corroborates this path.

Is this the best way to solve the issue?

Sharing the existing byte guard and accounting owner is appropriate, and navigation protection is restored, but manual timing and exposure of internal receipt callbacks still need owner direction.

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Keep receipt publication internal (recommended)
    Carry AgentSession's authority and committed-receipt callbacks through an internal compaction owner while preserving the released public appendCompactionAsync signature.
  2. Approve the additive SDK contract
    Have the SDK owner explicitly accept and document the new optional publication parameter and its commit, failure, and cancellation semantics.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still lacks manual byte preparation: Fetched main proceeds from the prepared session entry to queued compaction without prepareManualTranscriptByteCompaction; the introduced patch adds that preparation before manual dispatch. (src/agents/embedded-agent-runner/compact.queued.ts:143, a33bc638124d)
  • Previous navigation finding resolved: The compaction append now captures navigation, passes its assertion into worker admission, and checks it before receipt adoption while preserving a newer published view; the regression exercises both ordinary and dedicated compaction persistence. (src/agents/sessions/session-manager-compaction.ts:96, a33bc638124d)
  • Related merged fix has different scope: fix(sessions): avoid repeated host compaction after native compaction #168051 preserves an existing byte latch after native-only compaction; it does not add host-first manual compaction for an oversized transcript without valid suppression. Its body credits ruel225's original fix and overlapping coverage from xydigitLybnnnn. (src/auto-reply/reply/agent-runner-memory.ts:269, 9cd23e6067c8)
  • Public SDK parameter addition: appendCompactionAsync gains an eighth optional publication parameter; SessionManager remains publicly exported through openclaw/plugin-sdk/agent-sessions, so the callbacks are exposed despite adding no export name. (src/agents/sessions/session-manager-compaction.ts:57, a33bc638124d)
  • Native compaction ownership verified directly: OpenClaw's thread/compact/start behavior requires the Codex protocol contract. The inspected checkout, verified through its cache's upstream remote, loads the specified native thread and submits Op::Compact; core compaction replaces Codex history rather than OpenClaw's SQLite transcript. (codex-rs/app-server/src/request_processors/thread_processor.rs:2368, a956835d0207)
  • Contributor evidence and open timing decision: The complete REST body preserves historical macOS operator evidence over v2026.9.6 and distinguishes it from current synthetic-provider worker regressions and deliberate defect controls; it explicitly leaves acceptance of host-first manual latency open. (a33bc638124d)

PR surface

Source +344, Tests +906, Docs +24, Other -1. Total +1273 across 35 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 18 626 282 +344
Tests 13 1099 193 +906
Docs 3 25 1 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 35 1750 477 +1273

Review metrics

Metric Value Why it matters
Production versus test growth production +622/-276; tests and support +1103/-199 Shared accounting and committed-receipt handling justify production growth; tests cover storage, navigation, native failure, latch clearing, and client publication.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: The exported SessionManager API gains an optional receipt-publication parameter without recorded SDK-owner acceptance.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit. Replaced prior rating: 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: Oversized existing Codex conversations can impose another expensive host compaction before an ordinary reply after manual compaction.
  • merge-risk: 🚨 availability: An oversized manual request without a valid latch now waits through host summarization before native completion.
  • merge-risk: 🚨 compatibility: The exported SessionManager API gains an optional receipt-publication parameter without recorded SDK-owner acceptance.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit. Replaced prior rating: 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-26T12:49:18.434Z sha 7578450 :: blocked before merge. :: none
  • reviewed 2026-09-28T16:55:49.449Z sha f9f2130 :: blocked before merge. :: none
  • reviewed 2026-09-29T09:45:16.037Z sha f891a4d :: blocked before merge. :: none
  • reviewed 2026-09-29T10:00:00.056Z sha 24eaf20 :: blocked before merge. :: none
  • reviewed 2026-09-29T10:09:41.689Z sha 2bc49c1 :: blocked before merge. :: none
  • reviewed 2026-09-29T10:27:45.550Z sha 2bc49c1 :: blocked before merge. :: none
  • reviewed 2026-10-06T05:39:23.806Z sha 4cdd2a9 :: blocked before merge. :: none
  • reviewed 2026-10-09T06:21:39.340Z sha 7eb59d0 :: blocked before merge. :: [P2] Preserve navigation fencing in async compaction appends

Reviewed October 12, 2026, 11:59 PM ET / October 13, 2026, 03:59 UTC (Revision 13).

@scotthuang
scotthuang force-pushed the fix/manual-codex-byte-compaction branch from 5482714 to ff85341 Compare September 26, 2026 02:58
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
@scotthuang
scotthuang force-pushed the fix/manual-codex-byte-compaction branch from ff85341 to 51b023f Compare September 26, 2026 09:08
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 26, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 29, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 29, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 6, 2026
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Maintainer decision (Ayaan): instead of host-first manual compaction, Codex sessions will stop running the host summarizer on transcript-byte growth; the transcript copy is bounded only when a fresh native thread is seeded, with at most one host summary at that moment. This PR will be superseded by that change (credit to @scotthuang for the diagnosis); I'll link it here.

obviyus added a commit that referenced this pull request Oct 17, 2026
Related: #158044, #126171, #115514, #167916

## What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit.

## User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (#126171).

## Why This Change Was Made

The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in #158044; this implements the maintainer's [lazy-seed direction](#158044 (comment)), not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged.

**Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

## Evidence

**Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here.

BEFORE executed `7bfde4923e84f67e2961ea24d6a6fb6108680a03`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c001 7083100 --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](7bfde49...0b64fd1) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

### Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

| Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result |
|---|---:|---:|---:|---|
| Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained |
| Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained |
| Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained |
| Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained |
| 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice |
| Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained |
| Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained |
| Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance |
| High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained |

Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

### Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

| Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms |
|---|---:|---:|
| Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] |
| Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] |

### Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests.

| Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes |
|---|---:|---:|---:|---:|
| A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 |
| B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 |
| C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 |

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed.

### Authority, compatibility, and limitations

- The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`.
- Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
- E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
- The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
- The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/0b64fd18fcdccfa5ef3a1837909e7321ebcbca50/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
- With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
- Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

[Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

`pr-simplify` against merge base `0b64fd18fcdccfa5ef3a1837909e7321ebcbca50`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut.

The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.


Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #175256 (landed in 6db8577), which removes the eager host byte compaction for Codex instead of reordering it. Thanks @scotthuang for the diagnosis.

@obviyus obviyus closed this Oct 17, 2026
github-actions Bot pushed a commit to KubaPrzekoraKubaPrzekora7172/openclaw that referenced this pull request Oct 17, 2026
Related: #158044, #126171, #115514, #167916

## What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit.

## User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (#126171).

## Why This Change Was Made

The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in #158044; this implements the maintainer's [lazy-seed direction](openclaw/openclaw#158044 (comment)), not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged.

**Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

## Evidence

**Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here.

BEFORE executed `7bfde4923e84f67e2961ea24d6a6fb6108680a03`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c0017 7083100a --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](openclaw/openclaw@7bfde49...0b64fd1) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

### Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

| Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result |
|---|---:|---:|---:|---|
| Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained |
| Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained |
| Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained |
| Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained |
| 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice |
| Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained |
| Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained |
| Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance |
| High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained |

Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

### Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

| Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms |
|---|---:|---:|
| Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] |
| Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] |

### Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests.

| Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes |
|---|---:|---:|---:|---:|
| A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 |
| B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 |
| C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 |

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed.

### Authority, compatibility, and limitations

- The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`.
- Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
- E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
- The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
- The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/0b64fd18fcdccfa5ef3a1837909e7321ebcbca50/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
- With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
- Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

[Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

`pr-simplify` against merge base `0b64fd18fcdccfa5ef3a1837909e7321ebcbca50`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut.

The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.

Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to caoyuanchenxicaoyuanchenxi3238/openclaw that referenced this pull request Oct 17, 2026
Related: #158044, #126171, #115514, #167916

## What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit.

## User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (#126171).

## Why This Change Was Made

The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in #158044; this implements the maintainer's [lazy-seed direction](openclaw/openclaw#158044 (comment)), not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged.

**Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

## Evidence

**Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here.

BEFORE executed `7bfde4923e84f67e2961ea24d6a6fb6108680a03`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c0017 7083100a --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](openclaw/openclaw@7bfde49...0b64fd1) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

### Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

| Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result |
|---|---:|---:|---:|---|
| Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained |
| Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained |
| Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained |
| Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained |
| 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice |
| Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained |
| Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained |
| Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance |
| High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained |

Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

### Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

| Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms |
|---|---:|---:|
| Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] |
| Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] |

### Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests.

| Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes |
|---|---:|---:|---:|---:|
| A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 |
| B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 |
| C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 |

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed.

### Authority, compatibility, and limitations

- The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`.
- Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
- E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
- The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
- The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/0b64fd18fcdccfa5ef3a1837909e7321ebcbca50/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
- With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
- Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

[Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

`pr-simplify` against merge base `0b64fd18fcdccfa5ef3a1837909e7321ebcbca50`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut.

The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.

Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to yun7764285/openclaw that referenced this pull request Oct 17, 2026
Related: #158044, #126171, #115514, #167916

## What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit.

## User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (#126171).

## Why This Change Was Made

The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in #158044; this implements the maintainer's [lazy-seed direction](openclaw/openclaw#158044 (comment)), not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged.

**Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

## Evidence

**Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here.

BEFORE executed `7bfde4923e84f67e2961ea24d6a6fb6108680a03`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c0017 7083100a --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](openclaw/openclaw@7bfde49...0b64fd1) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

### Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

| Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result |
|---|---:|---:|---:|---|
| Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained |
| Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained |
| Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained |
| Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained |
| 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice |
| Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained |
| Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained |
| Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance |
| High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained |

Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

### Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

| Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms |
|---|---:|---:|
| Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] |
| Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] |

### Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests.

| Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes |
|---|---:|---:|---:|---:|
| A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 |
| B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 |
| C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 |

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed.

### Authority, compatibility, and limitations

- The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`.
- Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
- E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
- The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
- The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/0b64fd18fcdccfa5ef3a1837909e7321ebcbca50/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
- With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
- Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

[Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

`pr-simplify` against merge base `0b64fd18fcdccfa5ef3a1837909e7321ebcbca50`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut.

The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.

Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
…175256)

Related: openclaw#158044, openclaw#126171, openclaw#115514, openclaw#167916

## What Problem This Solves

Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit.

## User Impact

Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing.

Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (openclaw#126171).

## Why This Change Was Made

The guard introduced in openclaw#115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in openclaw#158044; this implements the maintainer's [lazy-seed direction](openclaw#158044 (comment)), not host-first manual compaction.

Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; openclaw#167916's bounded summarization remains unchanged.

**Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained.

## Evidence

**Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here.

BEFORE executed `81dde48ac1141487da66e6b9106aa6f7412e6e3b`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c001 7083100 --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](openclaw/openclaw@81dde48...140f7d9) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically.

### Paired runtime results

“Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction.

| Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result |
|---|---:|---:|---:|---|
| Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained |
| Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained |
| Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained |
| Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained |
| 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice |
| Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained |
| Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained |
| Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance |
| High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained |

Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files.

### Five-repeat latency

Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup.

| Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms |
|---|---:|---:|
| Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] |
| Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] |

### Real-provider confirmation

Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests.

| Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes |
|---|---:|---:|---:|---:|
| A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 |
| B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 |
| C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 |

The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed.

### Authority, compatibility, and limitations

- The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`.
- Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression.
- E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs.
- The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked.
- The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/140f7d9e325f6f38f94bf8a9041050ecc3fd1e55/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation.
- With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim.
- Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched.

[Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness.

`pr-simplify` against merge base `140f7d9e325f6f38f94bf8a9041050ecc3fd1e55`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut.

The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact.


Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-review-required security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants